Concatenation of Array easy
Problem Statement
Given an integer array nums
of length n
, return an array of length 2n
where the array is [nums, nums]
. In other words, it should be the concatenation of the array nums
with itself.
Example 1:
Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Explanation: The array nums
is concatenated with itself to produce the output [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 array nums
is concatenated with itself to produce the output [1,3,2,1,1,3,2,1]
.
Steps:
-
Create a new array: Initialize an empty array of length
2n
, wheren
is the length of the input arraynums
. This will store the concatenated result. -
Copy the original array: Copy the elements of
nums
into the first half of the new array. -
Copy again: Copy the elements of
nums
again into the second half of the new array. -
Return the new array: Return the new array containing the concatenated elements.
Explanation:
The problem directly asks for the concatenation of an array with itself. We can achieve this efficiently by creating a new array twice the size of the original and then populating it with the original array's contents twice. There's no need for complex algorithms; a simple copy operation suffices.
Code:
def getConcatenation(nums):
"""
Concatenates an array with itself.
Args:
nums: The input integer array.
Returns:
A new array containing the concatenation of nums with itself.
"""
n = len(nums)
ans = [0] * (2 * n) # Initialize an array of size 2n with zeros
for i in range(n):
ans[i] = nums[i]
ans[i + n] = nums[i]
return ans
# Example usage
nums1 = [1, 2, 1]
print(getConcatenation(nums1)) # Output: [1, 2, 1, 1, 2, 1]
nums2 = [1, 3, 2, 1]
print(getConcatenation(nums2)) # Output: [1, 3, 2, 1, 1, 3, 2, 1]
Complexity:
- Time Complexity: O(n), where n is the length of the input array. We iterate through the array twice (once to copy to the first half and once to copy to the second half).
- Space Complexity: O(n). We create a new array of size 2n to store the result.