Concatenation of Array
Easy · Arrays & Hashing · Explanation and code example
Iteration (One Pass)
How it works
The problem defines the result array ans such that ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n. Instead of looping through the input twice, we can fill both required positions in the result array simultaneously while iterating through the input array just once. This utilizes the index mapping i and i + n directly.
Steps
- Determine the length
nof the input array. - Initialize a result array
ansof size2n. - Iterate through the input array
numsusing an indexifrom0ton - 1. - For each element at index
i:- Set
ans[i] = nums[i]. - Set
ans[i + n] = nums[i].
- Set
- Return the resulting array.
Complexity
- Time complexity:
O(n)wherenis the length of the input array. Although we iterate through the input once, we still perform2ntotal writes to the output array. - Space complexity:
O(n)as we must allocate an array of size2nfor the output.
Things to watch for
Incorrect Result Array Size
Allocating an array of size n instead of 2n causes an index out of bounds error when writing to the second half.
Off-by-One When Using Index Offset
When using the one-pass approach with ans[i + n] = nums[i], forgetting that indices are zero-based or miscalculating the offset leads to incorrect placement of elements in the second half.
Python code example
from typing import List
class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [0] * (2 * n)
for i, num in enumerate(nums):
ans[i] = ans[i + n] = num
return ans
C++ code example
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] = ans[i + n] = nums[i];
}
return ans;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.