Concatenation of Array
Problem
Given nums of length n, return ans of length 2n where ans[i] == ans[i+n] == nums[i] for 0 ≤ i < n.
nums = [1,2,1][1,2,1,1,2,1]def get_concatenation(nums):
n = len(nums)
ans = [0] * (2 * n)
for i in range(n):
ans[i] = ans[i + n] = nums[i]
return ans
function getConcatenation(nums) {
const n = nums.length, ans = new Array(2 * n);
for (let i = 0; i < n; i++) ans[i] = ans[i + n] = nums[i];
return ans;
}
class Solution {
public int[] getConcatenation(int[] nums) {
int n = nums.length;
int[] ans = new int[2 * n];
for (int i = 0; i < n; i++) ans[i] = ans[i + n] = nums[i];
return ans;
}
}
vector<int> getConcatenation(vector<int>& nums) {
int n = nums.size();
vector<int> ans(2 * n);
for (int i = 0; i < n; i++) ans[i] = ans[i + n] = nums[i];
return ans;
}
Explanation
The goal is simple: take the list nums and glue a copy of it onto the end of itself. The neat part of this solution is that it does the whole thing in one pass without ever building a second list and stitching them together.
First we make an answer array ans that is exactly twice the length of nums (2 * n). Every slot starts empty, ready to be filled.
Then for each index i we write nums[i] into two places at once: position i (the first half) and position i + n (the second half). The line ans[i] = ans[i + n] = nums[i] does both copies in a single step.
Example: nums = [1, 2, 1] so n = 3. At i = 0 we put 1 at index 0 and index 3. At i = 1 we put 2 at index 1 and index 4. At i = 2 we put 1 at index 2 and index 5. The result is [1, 2, 1, 1, 2, 1].
Because we touch each original value just once, the work grows in step with the array size, which is why it is fast and clean.