AAlgoLoopSpaced repetition for LeetCode
EASYTwo PointersLeetCode ↗

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

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

410310
Step-by-step visualization
Start free →

More Two Pointers problems