Concatenation of Array LeetCode Solution

Difficulty Level Easy
Frequently asked in Adobe Bloomberg GE Healthcare Google
ArrayViews 2028

Problem Description:

The Concatenation of Array Leetcode Solution: states that

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, ans is the concatenation of two nums arrays.

Return the array ans.

Let’s first try to understand the problem and what it states.

The problem states that we need to concatenate the array with itself or duplicate the array elements in the same order.

Let’s say we have an array = [1, 2, 3, 4] then the output will be [1, 2, 3, 4, 1, 2, 3, 4]

1929. Concatenation of Array LeetCode Solution

Concatenation of Array Leetcode Solution Approach:

Now let’s understand how these elements can be copied to the output/final array or in other words how the elements of an original array can be mapped to the output array.

Below is the table to understand the mapping of elements.

OUTPUT ARRAY INDEX column contains the indices corresponding to the indices of the ORIGINAL ARRAY INDEX column

OUTPUT ARRAY INDEXORIGINAL ARRAY INDEX
00 % 4 = 0
11 % 4 = 1
22 % 4 = 2
33 % 4 = 3
44 % 4 = 0
55 % 4 = 1
66 % 4 = 2
7 % 4 = 3

In the above table we can observe that the index of the original array can be easily mapped to the index of the output array by this simple mathematical formula :

outputArrayIndex = (outputArrayIndex % length of original array)

If we understand the above mapping then the solution is quite simple.

Below is the code for the solution discussed above

Concatenation of Array Leetcode Java Solution:

class Solution {
    public int[] getConcatenation(int[] nums) {
       
       int len = nums.length;
       int[] ans = new int[2 * len];
       
       for(int i = 0;i < 2*len;i++){
           ans[i] = nums[i%len];
       }
       
       return ans;
   }
}

Concatenation of Array Leetcode C++ Solution:

class Solution {
public:
    vector<int> getConcatenation(vector<int>& nums) {
        
        int len = nums.size();
        vector<int> vect;
        for(int i = 0;i < 2*len;i++){
            vect.push_back(nums.at(i%len));
        }
        return vect;
    }
};

Time Complexity:

The Time Complexity of the above solution is O(N).

Space Complexity:

The Space Complexity of the above solution is O(N), storing the concatenated result.

Hope this article helps in the understanding of the problem.

Happy learning !!!

Translate »