Leetcode 1929. Concatenation of Array
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, you need to return the array ans
.
Example:
nums = [1, 2, 1]
[1, 2, 1, 1, 2, 1]
nums
have negative integers?
nums
?
1 <= nums.length <= 1000
.ans
array?
ans
should mirror the order in nums
.Let’s proceed with the solution.
The problem is quite straightforward. We need to concatenate the array nums
with itself to create the ans
array.
Steps:
nums
.ans
with a length of 2n
.n
elements of ans
with elements from nums
.n
elements of ans
with elements from nums
again.ans
array.Here’s the Java implementation of the described strategy:
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;
}
}
The time complexity for this solution is (O(n)), where (n) is the length of the input array nums
. This is because we are iterating through the array once to populate the ans
array.
The space complexity is also (O(n)) for the new array ans
because we are creating a new array that is double the size of the input array nums
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?