Unpacking "Concatenation of Array": My First Dive into LeetCode (Java)
Complexity - Easy
Today, I’ll kick things off with a fundamental array problem: "Concatenation of Array" (LeetCode #1929). This problem is a great starting point for understanding array manipulation and basic indexing.
Understanding the Problem:
The problem asks us to take an integer array nums of length n, and create a new array, ans, that is twice the length (2n). The ans array should be formed by concatenating nums with itself.
Basically, if nums = [a, b, c], then ans should be [a, b, c, a, b, c].
Let's look at an example:
Input:
nums = [1, 2, 1]Length (n): 3
Expected Output (ans):
[1, 2, 1, 1, 2, 1]
The problem specifies ans[i] == nums[i] for the first half, and ans[i + n] == nums[i] for the second half. This means the element at index i in the original array nums should appear at both i and i + n in the new ans array.
My Thought Process & Approach:
When I first read this, the core idea was pretty straightforward: I need a new array that's double the size of the original. Then, I need to fill this new array.
Determine
n: The first step is to get the length of the input arraynums. Thisnwill be crucial for defining the size of our new array and for managing indices.Initialize
resultarray: Create a new array, let's call itresult(oransas per the problem), with a size of2 * n.Handle Edge Case (Empty Array): What if
numsis empty? The problem statement impliesncan be 0. Ifnis 0,2*nis 0, and returning an empty array is correct. My code includes a check forn==0which handles this explicitly.Populate the
resultarray: This is the core logic. I need a loop that iterates2 * ntimes (covering every index in theresultarray).First Half: For indices
ifrom0up ton-1, the valueresult[i]should benums[i].Second Half: For indices
ifromnup to2n-1, the valueresult[i]should benums[i-n]. Thisi-nis key because it brings the index back to the0ton-1range of the originalnumsarray. For example, ifn=3, wheni=3,result[3]needs to benums[0].3-3 = 0. Wheni=4,result[4]needs to benums[1].4-3 = 1. This logic works perfectly.
Java Code Implementation:
class Solution {
public int[] getConcatenation(int[] nums) {
int n = nums.length;
int[] result = new int[2*n];
if(n==0){
return result;
}
for(int i = 0;i<2*n;i++){
if(i<n){
result[i] = nums[i];
}
else{
result[i] = nums[i-n];
}
}
return result;
}
}
Time and Space Complexity Analysis:
Time Complexity: O(n)
- We iterate through the input array
numseffectively once (or rather, we iterate2ntimes, but it's directly proportional ton). Each operation inside the loop (assignment) takes constant time. Therefore, the time complexity grows linearly with the size of the input arrayn.
- We iterate through the input array
Space Complexity: O(n)
- We create a new array
resultwhose size is2 * n. The space required grows linearly with the size of the input arrayn.
- We create a new array