Problem
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 arrayans
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
n == nums.length
1 <= n <= 1000
1 <= nums[i] <= 1000
Solution
Method 1 – Simple Array Concatenation
Intuition
The task is to create a new array by repeating the input array twice in order. This is a direct simulation problem with no tricky edge cases.
Approach
- Let n be the length of nums.
- Create a new array ans of length 2n.
- For each i from 0 to n-1:
- Set ans[i] = nums[i]
- Set ans[i + n] = nums[i]
- Return ans.
Code
C++
|
|
Go
|
|
Java
|
|
Kotlin
|
|
Python
|
|
Rust
|
|
TypeScript
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is the length of nums. We copy each element twice. - 🧺 Space complexity:
O(n)
, for the output array of size 2n.