Problem Description
Given a integer array nums of length n, create a new array ans of length 2 * n that satisfies the following conditions for all indices 0 ≤ i < n:
ans[i]equalsnums[i]ans[i + n]equalsnums[i]
In other words, the resulting array ans is formed by concatenating two copies of the original nums array.
Constraints
n = nums.length1 ≤ n ≤ 10001 ≤ nums[i] ≤ 1000
Examples
Example 1:
Input: nums = [1, 2, 1]
Output: [1, 2, 1, 1, 2, 1]
Explanation: The answer array is formed as:
ans = [nums[0], nums[1], nums[2], nums[0], nums[1], nums[2]]
ans = [1, 2, 1, 1, 2, 1]
Example 2:
Input: nums = [1, 3, 2, 1]
Output: [1, 3, 2, 1, 1, 3, 2, 1]
Explanation: The answer array is formed as:
ans = [nums[0], nums[1], nums[2], nums[3], nums[0], nums[1], nums[2], nums[3]]
ans = [1, 3, 2, 1, 1, 3, 2, 1]
Solution Approach
This problem has a straightforward solution. Since we need to create an array that conssits of two copies of the input array placed end-to-end, we can simply use array concatenation. The operation nums + nums in Python creates a new list by appenidng a copy of nums to itself.
The time complexity is O(n) since we need to copy all n elements twice, and the space complexity is O(n) for storing the resulting array.
Reference Implementation
def concatenate_arrays(source: list) -> list:
"""Return a new array containing two concatenated copies of the input."""
return source + source
def main():
"""Read input and display the concatenated array."""
raw_input = input("Enter integers separated by spaces: ")
numbers = list(map(int, raw_input.split()))
result = concatenate_arrays(numbers)
print("Concatenated array:", result)
if __name__ == "__main__":
main()