Concatenation of Array easy
Problem Statement
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 all 0 <= i < n
.
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]
Steps:
- Create a new array: Initialize an empty array
ans
with a length of2 * nums.length
. - Populate the array: Iterate through the input array
nums
. For each elementnums[i]
, assign it to bothans[i]
andans[i + nums.length]
.
Explanation:
The problem requires us to concatenate the input array with itself. We achieve this by creating a new array twice the size of the input array and then copying the elements of the input array into the first and second halves of the new array. This ensures that each element of the original array appears twice in the resulting array.
Code:
function getConcatenation(nums: number[]): number[] {
const n = nums.length;
const ans: number[] = new Array(2 * n); // Initialize an array of size 2n
for (let i = 0; i < n; i++) {
ans[i] = nums[i]; // First half is a copy of nums
ans[i + n] = nums[i]; // Second half is also a copy of nums
}
return ans;
};
Complexity:
- Time Complexity: O(n), where n is the length of the input array. We iterate through the array once to copy its elements.
- Space Complexity: O(n), as we create a new array of size 2n to store the result.