Difficulty: 🟢 Easy
Given an integer array nums
of length n
, you want to 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,2,1]
Output: [1,2,1,1,2,1]
Explanation: The array ans is formed as follows:
- 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 array ans is formed as follows:
- 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]
n == nums.length
1 <= n <= 1000
1 <= nums[i] <= 1000
class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
for i in range(len(nums)):
nums.append(nums[i])
return nums
The given solution creates the array ans
by iterating through each element of the nums
array and appending it to the end of the same nums
array. It then returns the resulting array ans
.
The algorithm works as follows:
- Iterate through each element
num
in thenums
array.- Append
num
to the end of thenums
array.
- Append
- Return the modified
nums
array, which contains the concatenation ofnums
with itself.
The algorithm appends each element of the nums
array to the end of the same array, effectively concatenating it with itself.
The time complexity of this algorithm is O(n), where n is the length of the nums
array. The algorithm iterates through each element of the nums
array once and performs constant-time operations.
The space complexity of the algorithm is O(1) as it modifies the nums
array in-place without using any additional space.
The given solution creates the array ans
by concatenating the input array nums
with itself. It has a time complexity of O(n) and a space complexity of O(1), making it an efficient solution for the problem at hand.
NB: If you want to get community points please suggest solutions in other languages as merge requests.