Concatenation of Array - Problem
Array Concatenation Challenge

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
Array Concatenation VisualizationOriginal Array1234Process: Copy Each Element Twice12341234First CopySecond CopyFinal Result: [1, 2, 3, 4, 1, 2, 3, 4]Length doubled from n=4 to 2n=8Each element appears exactly twice in the same order
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

n
2n
โœ“ 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

n
2n
โšก Linearithmic Space

Constraints

  • n == nums.length
  • 1 โ‰ค n โ‰ค 1000
  • 1 โ‰ค nums[i] โ‰ค 1000
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 5
89.3K Views
Medium Frequency
~5 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen