1. Problem Summary
You are given an integer array nums of length n.
Your task is to build a new array ans of length 2n such that:
ans[i] = nums[i] ans[i + n] = nums[i]
for every index i from 0 to n−1.
In other words, you must concatenate the array with itself:
ans = nums + nums
Example:
Input: nums = [1,2,1] Output: [1,2,1,1,2,1]
2. Key Insights
Insight 1: Output size always exactly double
If nums has n elements, ans always has 2n elements.
Insight 2: Direct index mapping
For each i:
ans[i] = nums[i] ans[i+n] = nums[i]
Insight 3: No mutation or transformation needed
Values are copied exactly, no computation.
Insight 4: Can be done in one or two loops
Both correct:
- Fill ans while iterating once
- Or copy nums twice
Insight 5: No edge cases beyond length handling
Because nums is guaranteed valid.
3. Approach
Build a new array and fill positions
Steps:
- Let
n = nums.length - Create
answith size2n - Loop through indexes
ifrom 0 to n−1:ans[i] = nums[i] ans[i + n] = nums[i] - Return ans
4. Time and Space Complexity
Time Complexity:
O(N)
We copy each element twice.
Space Complexity:
O(N)
Extra array of size 2n allocated.
5. Java Solution
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];
ans[i + n] = nums[i];
}
return ans;
}
}
6. Alternative Java Solution (System.arraycopy)
class Solution {
public int[] getConcatenation(int[] nums) {
int n = nums.length;
int[] ans = new int[2 * n];
System.arraycopy(nums, 0, ans, 0, n);
System.arraycopy(nums, 0, ans, n, n);
return ans;
}
}
7. Dry Run Examples
Example 1
Input:
[1,2,1]
n = 3
ans initially size 6
Filling:
ans[0] = 1 ans[1] = 2 ans[2] = 1 ans[3] = 1 ans[4] = 2 ans[5] = 1
Output:
[1,2,1,1,2,1]
Example 2
Input:
[1,3,2,1]
Output:
[1,3,2,1,1,3,2,1]
Example 3
Input:
[0]
Output:
[0,0]
Example 4
Input:
[5,4,8]
Output:
[5,4,8,5,4,8]
Example 5
Input:
[7,7,7,7]
Output:
[7,7,7,7,7,7,7,7]
8. Why This Solution Works
- Mapping from nums to ans is direct
- No conditional logic required
- Always produces correct length output
- Works for:
- single element
- repeated values
- large arrays
9. Common Mistakes
- Incorrect array length (should be
2 * n) - Using concatenation methods intended for strings
- Forgetting second assignment at index
i + n - Modifying original nums instead of creating ans
- Off-by-one loop boundaries
