Loading

LeetCode problem#1929

Concatenation of Array

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

12 lines
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 ans that has twice the length of nums. This is necessary because we need to hold the elements of nums twice (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 for loop to iterate through each index i of the nums array.
  • Inside the loop:
    • ans[i] = nums[i]; copies the current element from nums to the corresponding index in ans.
    • ans[i + nums.length] = nums[i]; copies the same current element from nums to the index in ans that is nums.length positions ahead of i. This effectively places the first half (the original nums) and the second half (the copy of nums) into ans.

Step 4: Return the Result

return ans;
  • After the loop completes, we have filled the ans array with the concatenated values, and the method returns this array.

Example of Execution

For an input of nums = [1, 2, 3]:

  • nums.length is 3.
  • The ans array is initialized to have length 6 (since 3 * 2 = 6).
  • Iteration through the loop proceeds as follows:
    • When i = 0: ans[0] = 1 and ans[3] = 1 → ans = [1, 0, 0, 1, 0, 0]
    • When i = 1: ans[1] = 2 and ans[4] = 2 → ans = [1, 2, 0, 1, 2, 0]
    • When i = 2: ans[2] = 3 and ans[5] = 3 → ans = [1, 2, 3, 1, 2, 3]

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.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.