LeetCode problem#1929
Concatenation of Array
Solved in 1 languageJava
Solution
1class Solution {
2 public int[] getConcatenation(int[] nums) {
3 int[] ans = new int[nums.length * 2];
4
5 for (int i = 0; i < nums.length; i++) {
6 ans[i] = nums[i];
7 ans[i + nums.length] = nums[i];
8 }
9
10 return ans;
11 }
12}How it works
This Solution class contains a method called getConcatenation, which takes an integer array nums as its input and returns a new array that is a concatenation of nums with itself.
Here's a step-by-step explanation of how the solution works:
Step 1: Understanding Concatenation
The problem requires that for an input array nums, we output a new array that contains all the elements of nums followed by all the elements of nums again. For example, if nums = [1, 2, 3], the result should be [1, 2, 3, 1, 2, 3].
Step 2: Initialize the Result Array
int[] ans = new int[nums.length * 2];- We create a new integer array
ansthat has twice the length ofnums. This is necessary because we need to hold the elements ofnumstwice (once for each concatenation).
Step 3: Fill the Result Array
1for (int i = 0; i < nums.length; i++) {
2 ans[i] = nums[i];
3 ans[i + nums.length] = nums[i];
4}- We use a
forloop to iterate through each indexiof thenumsarray. - Inside the loop:
ans[i] = nums[i];copies the current element fromnumsto the corresponding index inans.ans[i + nums.length] = nums[i];copies the same current element fromnumsto the index inansthat isnums.lengthpositions ahead ofi. This effectively places the first half (the originalnums) and the second half (the copy ofnums) intoans.
Step 4: Return the Result
return ans;- After the loop completes, we have filled the
ansarray with the concatenated values, and the method returns this array.
Example of Execution
For an input of nums = [1, 2, 3]:
nums.lengthis3.- The
ansarray is initialized to have length6(since3 * 2 = 6). - Iteration through the loop proceeds as follows:
- When
i = 0:ans[0] = 1andans[3] = 1→ans = [1, 0, 0, 1, 0, 0] - When
i = 1:ans[1] = 2andans[4] = 2→ans = [1, 2, 0, 1, 2, 0] - When
i = 2:ans[2] = 3andans[5] = 3→ans = [1, 2, 3, 1, 2, 3]
- When
Thus, the final result returned is [1, 2, 3, 1, 2, 3].
This algorithm has a time complexity of O(n), where n is the length of nums, because it iterates through nums once, and it has a space complexity of O(n) due to the creation of the ans array.
Written by AI from the code above, so double-check anything important.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.