Concatenation of Array - Problem

Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).

Specifically, ans is the concatenation of two nums arrays.

Return the array ans.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
💡 Note: The array ans is [1,2,1,1,2,1]. ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]] = [1,2,1,1,2,1]
Example 2 — Single Element
$ Input: nums = [1]
Output: [1,1]
💡 Note: The array ans is [1,1]. ans = [nums[0],nums[0]] = [1,1]
Example 3 — Multiple Elements
$ Input: nums = [1,3,2,1]
Output: [1,3,2,1,1,3,2,1]
💡 Note: The array ans is [1,3,2,1,1,3,2,1]. The original array is concatenated with itself

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 1000
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Array Concatenation: nums + numsInput Array121nums = [1,2,1], n = 3⬇ Concatenation Process ⬇Output Array (length 2n = 6)121121First CopySecond CopyResult: [1,2,1,1,2,1]
Understanding the Visualization
1
Input
Original array nums = [1,2,1] with length n=3
2
Process
Create result array of length 2n=6 and copy elements twice
3
Output
Concatenated array [1,2,1,1,2,1]
Key Takeaway
🎯 Key Insight: Simply copy the original array twice - first at positions 0 to n-1, then at positions n to 2n-1
Asked in
Amazon 12 Apple 8
108.2K Views
High Frequency
~10 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