Concatenation of Array
EasyUpdated: Jul 7, 2025
Practice on:
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
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]
Constraints
n == nums.length1 <= n <= 10001 <= 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++
class Solution {
public:
vector<int> getConcatenation(vector<int>& nums) {
int n = nums.size();
vector<int> ans(2 * n);
for (int i = 0; i < n; ++i) {
ans[i] = nums[i];
ans[i + n] = nums[i];
}
return ans;
}
};
Go
func GetConcatenation(nums []int) []int {
n := len(nums)
ans := make([]int, 2*n)
for i := 0; i < n; i++ {
ans[i] = nums[i]
ans[i+n] = nums[i]
}
return ans
}
Java
class Solution {
public int[] getConcatenation(int[] nums) {
int n = nums.length;
int[] ans = new int[2 * n];
for (int i = 0; i < n; i++) {
ans[i] = nums[i];
ans[i + n] = nums[i];
}
return ans;
}
}
Kotlin
class Solution {
fun getConcatenation(nums: IntArray): IntArray {
val n = nums.size
val ans = IntArray(2 * n)
for (i in 0 until n) {
ans[i] = nums[i]
ans[i + n] = nums[i]
}
return ans
}
}
Python
class Solution:
def getConcatenation(self, nums: list[int]) -> list[int]:
n = len(nums)
ans = [0] * (2 * n)
for i in range(n):
ans[i] = nums[i]
ans[i + n] = nums[i]
return ans
Rust
impl Solution {
pub fn get_concatenation(nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut ans = vec![0; 2 * n];
for i in 0..n {
ans[i] = nums[i];
ans[i + n] = nums[i];
}
ans
}
}
TypeScript
class Solution {
getConcatenation(nums: number[]): number[] {
const n = nums.length;
const ans = new Array(2 * n);
for (let i = 0; i < n; i++) {
ans[i] = nums[i];
ans[i + n] = nums[i];
}
return ans;
}
}
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.