Concatenation of Array - Problem
Array Concatenation Challenge
You're given an integer array
More specifically, you need to create an array
โข The first n elements are identical to the original array:
โข The next n elements are a copy of the original array:
For example, if
Goal: Return the concatenated array
You're given an integer array
nums of length n, and your task is to create a new array that contains the original array twice - essentially concatenating the array with itself.More specifically, you need to create an array
ans of length 2n where:โข The first n elements are identical to the original array:
ans[i] == nums[i]โข The next n elements are a copy of the original array:
ans[i + n] == nums[i]For example, if
nums = [1,2,1], then ans = [1,2,1,1,2,1]Goal: Return the concatenated array
ans. Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1,2,1]
โบ
Output:
[1,2,1,1,2,1]
๐ก Note:
The array is concatenated with itself. First copy: [1,2,1], second copy: [1,2,1], result: [1,2,1,1,2,1]
example_2.py โ Single Element
$
Input:
nums = [1,3,2,1]
โบ
Output:
[1,3,2,1,1,3,2,1]
๐ก Note:
Four elements are duplicated to create an 8-element array where the second half mirrors the first half exactly
example_3.py โ Minimum Case
$
Input:
nums = [5]
โบ
Output:
[5,5]
๐ก Note:
Single element array becomes a two-element array with the same value repeated twice
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Create a new array twice the size of the original
2
Single Pass
For each element at position i, place it at both position i and position i+n
3
Complete
Result contains the original array followed by its exact duplicate
Key Takeaway
๐ฏ Key Insight: Since we know the exact target positions (i and i+n), we can efficiently fill both positions in a single pass, making this an optimal O(n) solution.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the input array of length n, performing constant time operations for each element
โ Linear Growth
Space Complexity
O(n)
We create a new array of size 2n to store the result, so space complexity is O(n) additional space
โก Linearithmic Space
Constraints
- n == nums.length
- 1 โค n โค 1000
- 1 โค nums[i] โค 1000
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code