You are given an integer array nums of length n. Create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).
Specifically, ans is the concatenation of two nums arrays.
Return the array ans.
Example 1:
Input: nums = [1,4,1,2]
Output: [1,4,1,2,1,4,1,2]Example 2:
Input: nums = [22,21,20,1]
Output: [22,21,20,1,22,21,20,1]Constraints:
1 <= nums.length <= 1000.1 <= nums[i] <= 1000Before attempting this problem, you should be comfortable with:
To concatenate an array with itself, we need to create a new array that contains all elements of the original array twice, maintaining the same order. The elements at indices to are followed by the same elements at indices to .
For example, if nums = [1, 2, 3]:
ans will be nums[0], nums[1], nums[2] -> [1, 2, 3]ans will also be nums[0], nums[1], nums[2] -> [1, 2, 3][1, 2, 3, 1, 2, 3]ans of size 2n, where n is the length of the input array.num in the input array nums.num to the result list or assign it to the next available index in the result array.The problem defines the result array ans such that ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n. Instead of looping through the input twice, we can fill both required positions in the result array simultaneously while iterating through the input array just once. This utilizes the index mapping i and i + n directly.
n of the input array.ans of size 2n.nums using an index i from 0 to n - 1.i:ans[i] = nums[i].ans[i + n] = nums[i].Allocating an array of size n instead of 2n causes an index out of bounds error when writing to the second half.
# Wrong
ans = [0] * n
# Correct
ans = [0] * (2 * n)When using the one-pass approach with ans[i + n] = nums[i], forgetting that indices are zero-based or miscalculating the offset leads to incorrect placement of elements in the second half.