Skip to content

Concatenation of Array

LeetCode

01 · Question

Given nums of length n, return an array of length 2n containing nums twice: [nums, nums].

02 · Analysis

Allocate the result once, then fill both halves in the same loop:

  • Write nums[i] to ans[i].
  • Write the same value to ans[i + n].

The point: use an index offset to map one input position to both output positions.

Complexity: O(n)O(n) time and O(n)O(n) output space, with O(1)O(1) auxiliary space.

03 · Solution

Fill both halves in one pass

1def getConcatenation(nums: List[int]) -> List[int]:
2 n = len(nums)
3 ans = [0] * (2 * n)
4 for i in range(n):
5 ans[i] = nums[i]
6 ans[i + n] = nums[i]
7 return ans