Concatenation of Array
Given an integer array nums of length n, return an array ans of length 2n where ansi == numsi and ans[i + n] == numsi for every valid index i. In other words, ans is the concatenation of two nums arrays.
Constraints
- n == nums.length
- 1 ≤ n ≤ 1000
- 1 ≤ numsi ≤ 1000
Example
nums = [1, 2, 1][1, 2, 1, 1, 2, 1]Explanation The array [1, 2, 1] is concatenated with itself to form [1, 2, 1, 1, 2, 1].
In plain terms
- Concatenation
- Joining two sequences end to end to form one longer sequence — here, nums followed immediately by another copy of nums.
Copy nums, then copy it again right after
First pass: copy nums[0]=1 into ans[0].
What happens in this step
ans[0] = nums[0] = 1 ans = [1]
Steps to visualize
- Create an empty result array.
- Copy every value of nums into the result, in order.
- Copy every value of nums into the result again, right after the first copy.
- The result now has length 2n, with nums repeated twice.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
First pass: copy nums[0]=1 into ans[0].
What happens in this step
ans[0] = nums[0] = 1 ans = [1]
Solution
function getConcatenation(nums) {
const n = nums.length;
const ans = new Array(2 * n);
for (let i = 0; i < n; i++) {
ans[i] = nums[i];
ans[i + n] = nums[i];
}
return ans;
}- Time
- O(n)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [1, 2, 1] | [1, 2, 1, 1, 2, 1] | example from the docstring |
nums = [7] | [7, 7] | smallest valid input, a single element |
nums = [1, 3, 2, 1] | [1, 3, 2, 1, 1, 3, 2, 1] | a slightly longer array with a duplicate value |
nums = [4, 4] | [4, 4, 4, 4] | every value identical |
nums = [1, 2, 3] | [1, 2, 3, 1, 2, 3] | strictly increasing values |
nums = [5, 3, 1] | [5, 3, 1, 5, 3, 1] | strictly decreasing values |