652/670

652. Concatenation of Array

Easy

You receive an integer array nums of length n.

Build and return the array ans of length 2n made by writing nums twice, back to back. Formally, for every 0 <= i < n:

  • ans[i] = nums[i]
  • ans[i + n] = nums[i]

Print the 2n values of ans separated by single spaces.

Example 1:

Input: nums = [3, 1, 4]

Output: [3, 1, 4, 3, 1, 4]

Explanation: n = 3, so ans has length 6: the first three slots copy nums, and slots 3..5 copy it again.

Example 2:

Input: nums = [7, 7]

Output: [7, 7, 7, 7]

Explanation: Duplicating [7, 7] gives four sevens: ans[0] = ans[2] = nums[0] and ans[1] = ans[3] = nums[1].

Constraints:

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 1000

Hints:

The output has exactly 2n slots. What index of nums does slot i of the answer read from when i >= n?

Either append the elements of nums twice in two passes, or fill one array of size 2n using ans[i] = nums[i % n].

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: nums = [3, 1, 4]

Expected output: [3, 1, 4, 3, 1, 4]