Concatenation of Array(#1929)
Category: Array, Foundation
๐งฉ Problem Statement
You're given an integer array nums of length n. Your task is to create a new array ans of length 2n, such that: ans[i] = nums[i] ans[i + n] = nums[i] for all 0 <= i < n. In simpler terms, return the concatenation of the array with itself.
๐ Examples
Input: nums = [1, 2, 1]
Output: [1, 2, 1, 1, 2, 1]
Explanation: Concatenate the input array with itself: [1, 2, 1] + [1, 2, 1] = [1, 2, 1, 1, 2, 1].
๐ง Approach
Approach 1: Using a For Loop
โข Initialize an empty array `ans`.
โข Loop through `nums`, and for each element, add it at index `i` and `i + n`.
โข Return `ans`.
Approach 2: Using Spread Operator
โข Return `[...nums, ...nums]` which duplicates and concatenates the array.
Both solutions run in O(n) time and are very beginner-friendly.
๐ป Code
var getConcatenation = function(nums) {
let ans = [];
let n = nums.length;
for (let i = 0; i < n; i++) {
ans[i] = nums[i];
ans[i + n] = nums[i];
}
return ans;
};
// One-liner approach:
var getConcatenation = function(nums) {
return [...nums, ...nums];
};
๐ Complexity
Time: O(n)
Space: O(n)