# Concatenation of Array LeetCode Solution

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

Table of Contents

## 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]

## 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 INDEX ORIGINAL ARRAY INDEX 0 0 % 4 = 0 1 1 % 4 = 1 2 2 % 4 = 2 3 3 % 4 = 3 4 4 % 4 = 0 5 5 % 4 = 1 6 6 % 4 = 2 7 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 »