You are given an array of whole numbers, nums, with n elements. Build a new array ans of length 2n that holds nums twice in a row: first every element of nums in order, then every element again in the same order.
Put another way, for each index i from 0 to n − 1, both ans[i] and ans[i + n] equal nums[i]. Return ans.
Example 1
Input: nums = [5, 8, 3] Output: [5, 8, 3, 5, 8, 3] Why: the list, then the list again
2 more examples and the constraints
Example 2
Input: nums = [9] Output: [9, 9] Why: one element, written twice
Example 3
Input: nums = [2, 2, 7, 4] Output: [2, 2, 7, 4, 2, 2, 7, 4] Why: repeats inside nums are copied as they are
Constraints
- 1 ≤ n ≤ 1,000
- 1 ≤ each nums[i] ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Append two roundsO(n)
- Fill both halves at onceO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Work for 1,000 numbers | Verdict |
|---|---|---|---|
| Append two rounds | O(n) | Passes; list may resize | |
| Fill both halves at once | O(n) | Best; one allocation |
n = length of nums. Both write each of the 2n values once.
Edge cases to test
- One element. [9] becomes [9, 9].
- Repeated values. [2, 2, 7, 4] keeps its repeats: the copy is exact, nothing is removed.
- Largest input. 1,000 values give 2,000; no sums are taken, so overflow is not a concern.
Common mistakes
- Making ans only n long, then writing past its end at index i + n.
- Writing the second copy at i + n − 1 or i + n + 1, which shifts it by one slot.
- Interleaving the copies, as in [5, 5, 8, 8, 3, 3], instead of placing the whole list twice.
How to talk through it
- 1Clarify. Is the answer the whole list twice in order, not each value doubled in place? Can nums be empty?
- 2Name the size. The output is exactly 2n long, so it can be allocated once.
- 3Give the mapping. nums[i] goes to ans[i] and to ans[i + n].
- 4Code the loop. One loop over i with two writes. Mention the one-line built-in as an alternative.
- 5Test out loud. Run [9] and [2, 2, 7, 4] and check the second half starts at index n.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?