Concatenation of Array (LeetCode 1929): Solution and Explanation

Easy
Array
Simulation

Given an integer array nums of length n, return an array ans of length 2n where ans[i] = nums[i] and ans[i + n] = nums[i], which is nums followed by itself.

Intuition

The answer is two copies of nums side by side. The first copy occupies indices 0..n-1 and the second occupies n..2n-1.

Any element nums[i] therefore appears at exactly two places: index i in the first half and index i + n in the second half. The offset n is the length of one half.

One pass over nums can fill both halves at the same time, since each value knows both of its destinations.

Approach: Write each value twice

  1. Let n be the length of nums and create ans with 2n slots.
  2. For each index i, set ans[i] = nums[i].
  3. In the same iteration, set ans[i + n] = nums[i].
  4. Return ans.

Step-by-step example

nums = [1,2,1]
  1. n = 3, so ans has 6 slots: the first half is 0..2 and the second half is 3..5.
  2. i = 0: nums[0] = 1 goes to ans[0] and ans[3].
  3. i = 1: nums[1] = 2 goes to ans[1] and ans[4].
  4. i = 2: nums[2] = 1 goes to ans[2] and ans[5].
  5. All six slots are filled, so ans = [1,2,1,1,2,1].

Code: Python, Java, C++

1class Solution:
2    def getConcatenation(self, nums: List[int]) -> List[int]:
3        n = len(nums)
4        ans = [0] * (2 * n)
5        for i in range(n):
6            ans[i] = nums[i]
7            ans[i + n] = nums[i]
8        return ans
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each of the n elements is read once and written twice.

Space

O(n)

The output has 2n slots. Nothing else is allocated.

Other approaches

Built-in concatenation (time O(n), space O(n))

Use the language's own tools: nums + nums in Python, [...nums, ...nums] in JavaScript, or two calls to System.arraycopy in Java. Same complexity with less code.

One loop over 2n with modulo (time O(n), space O(n))

Loop k from 0 to 2n - 1 and set ans[k] = nums[k % n]. This is the same idea seen from the output side, and it generalizes to repeating the array any number of times.

Common mistakes

  • Allocating ans with n slots instead of 2n, which overflows on the write to ans[i + n].
  • Appending to nums while iterating over it in languages where the loop bound is re-read, which can loop forever.
  • Using i + n - 1 or i + n + 1 for the second-half index. The second copy starts exactly at index n.

Frequently asked questions

Why is the second index i + n?

The first half takes indices 0..n-1, so the second half starts at index n. The element at offset i inside the second half is therefore at n + i.

Where does this pattern show up in harder problems?

Doubling an array is a standard way to handle circular arrays, for example in Next Greater Element II or Maximum Sum Circular Subarray, where scanning nums + nums lets a linear algorithm see every wrap-around window.