Concatenation of Array — Solution in Python, Java & C++
Concatenation of Array solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Concatenation of Array is an easy coding problem on arrays and simulation, asked in Amazon and TCS interviews.
- Difficulty: Easy
- Topics: Arrays, Simulation
- Asked at: Amazon, TCS
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given an integer array nums of length n, return an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for every 0 <= i < n.
In other words, ans is nums concatenated with itself.
Example 1
Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Example 2
Input: nums = [1,3,2,1]
Output: [1,3,2,1,1,3,2,1]
Example 3
Input: nums = [7]
Output: [7,7]
Constraints
1 <= nums.length <= 401 <= nums[i] <= 1000
Hints for Concatenation of Array
Hint 1
Append the array to itself — either with a library concatenation or by looping over it twice.
How to solve Concatenation of Array
The answer is the array followed by itself.
Approach
- Return
nums + nums(or loop over the input twice, appending).
Why it works
ans[i] = nums[i] and ans[i + n] = nums[i] is the definition of concatenation with itself.
Complexity
- Time —
O(n) - Space —
O(n)
Pitfalls
- Iterating with index
i % nup to2nis the same thing without a library call.
Reference solution
Python
def getConcatenation(nums):
return list(nums) + list(nums)Java
public static int[] getConcatenation(int[] nums) {
int n = nums.length;
int[] out = new int[2 * n];
for (int i = 0; i < n; i++) {
out[i] = nums[i];
out[i + n] = nums[i];
}
return out;
}C++
vector<int> getConcatenation(vector<int>& nums) {
vector<int> out(nums);
for (int x : nums) out.push_back(x);
return out;
}JavaScript
var getConcatenation = function(nums) {
return nums.concat(nums);
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays