Concatenation of Array
The key idea
The answer is simply
nums written down twice in a row. Position i of the answer mirrors nums[i], and position i + n mirrors the SAME nums[i], so a single left-to-right pass that copies each value into two slots — index i and index i + n — builds the whole length-2n array.Problem
Given an integer array nums of length n, build and return a new array ans of length 2n where, for every index i from 0 to n - 1, ans[i] equals nums[i] and ans[i + n] also equals nums[i].
In other words, ans is the array nums concatenated with itself: the first n values repeat as the last n values, in the same order.
Constraints
n == nums.length1 <= n <= 10001 <= nums[i] <= 1000
Examples
Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Input: nums = [1,3,2,1]
Output: [1,3,2,1,1,3,2,1]
Complexity
Time: O(n) Space: O(n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Two Pointers problems
- 3SumMEDIUM
- 4SumMEDIUM
- Container With Most WaterMEDIUM
- Is SubsequenceEASY
- Merge Sorted ArrayEASY
- Merge Strings AlternatelyEASY
- Move ZeroesEASY
- Next PermutationMEDIUM
- Remove Duplicates from Sorted ArrayEASY
- Remove Duplicates from Sorted Array IIMEDIUM
- Remove ElementEASY
- Reverse StringEASY