Problem Description
Given an integer array nums of length n, form an array ans of length 2n by concatenating nums with itself, such that ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n.
Key Insights
- The problem is essentially about duplicating the array by concatenating it with itself.
- A new array of size 2n needs to be created.
- The solution involves a simple copy of elements, first copying the original array, then copying it again.
- The use of simple array operations ensures clarity and efficiency.
Space and Time Complexity
Time Complexity: O(n) where n is the number of elements in nums. Space Complexity: O(n) for the additional array of size 2n (ignoring output space, the extra space is linear with respect to n).
Solution
The approach is straightforward:
- Create a new array, ans, of length 2n (or, in high-level languages, you can simply append/catenate the array with itself).
- Iterate over the original array and copy each element to the corresponding position in ans.
- During the same or a separate iteration, copy the original array again so that the first copy is placed at the beginning and the second copy starts at index n.
- Return the final array ans.
This method leverages simple array traversal and copying, ensuring clarity and optimal performance.