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
Concatenation of Array INPUT Original Array: nums 1 i=0 2 i=1 1 i=2 Input Values: nums = [1, 2, 1] length n = 3 Goal: Create array of length 2n = 6 ALGORITHM STEPS 1 Create Result Array ans = new int[2n] 2 Loop i from 0 to n-1 for i in range(n) 3 Copy to First Half ans[i] = nums[i] 4 Copy to Second Half ans[i+n] = nums[i] Mapping Example: i=0: ans[0]=1, ans[3]=1 i=1: ans[1]=2, ans[4]=2 i=2: ans[2]=1, ans[5]=1 FINAL RESULT Concatenated Array: ans 1 0 2 1 1 2 1 3 2 4 1 5 First copy Second copy Output: [1, 2, 1, 1, 2, 1] OK - Length = 6 Key Insight: Single pass concatenation is O(n) time and O(n) space. Each element nums[i] is placed at two positions: index i (first half) and index i+n (second half). This creates the doubled array in one iteration without needing to append or copy arrays separately. TutorialsPoint - Concatenation of Array | Single Pass Concatenation
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