#1929
Concatenation of Array
Easy Array basics
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Return an array of length 2n that is the input array followed by itself.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: make an array twice as long that holds the input two times in a row.
Why this works: Java arrays have a fixed size, so you create the full 2n array first and fill both halves with simple index maths.
Example: nums = [1, 2, 1]
ans has length 6i=0: ans[0]=1, ans[3]=1i=1: ans[1]=2, ans[4]=2i=2: ans[2]=1, ans[5]=1ans = [1, 2, 1, 1, 2, 1]
✦Hints open one at a time
Create a new int array of size 2 * n.
Position i and position i + n hold the same value.
↗Approach
Allocate the result once and fill both halves in a single loop. Java arrays have a fixed size, so you must know the length when you create it.
</>Solution (Java)
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] = nums[i]; // first copy
ans[i + n] = nums[i]; // second copy
}
return ans;
}
}
!Common mistake
Trying to "append" to a Java int[] — arrays can't grow. Allocate the full size first.
Complexity
- Time: O(n).
- Space: O(n) for the output.
