Concatenation of Array LeetCode Solution

Difficulty Level Easy
Frequently asked in Adobe Bloomberg GE Healthcare GoogleViews 42

Problem Statement :

Concatenation of Array LeetCode Solution – 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.

Example :

Example 1

Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
- ans = [1,2,1,1,2,1]

Example 2 

Input: nums = [1,3,2,1]
Output: [1,3,2,1,1,3,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
- ans = [1,3,2,1,1,3,2,1]

Constraints :

n == nums.length
1 <= n <= 1000
1 <= nums[i] <= 1000

Algorithm :

Let’s save the length at the beginning of our function so that we have a snapshot of the length before we begin mutating our array. If we were to only use nums.length inside of our loop, we’d be inside of an infinite loop since we continually increase the length as we push items.

Instead, use the saved length and push numbers as you iterate through the input array.

The time complexity for this problem is O(n) as we have to linearly walk through our input array. You can argue that the space complexity is either constant O(1) or linear O(n) depending on whether or not you consider the mutation of our input array.

  • Create an answer array of twice the length.
  • Iterate in the nums array.
  • We will put nums[i] at the (i)th index and (i+n)th index into the ans array.

Concatenation of Array LeetCode Solution

  • At last, return the ans array.

Code For Concatenation of Array :

Java Code

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

C++ Code

class Solution {
public:
    vector<int> getConcatenation(vector<int>& nums) {
          int n=nums.size();
        vector<int>ans(2*n);
        for(int i=0;i<n;i++){
            ans[i]=nums[i];
            ans[i+n]=nums[i];
        }
        return ans;
    }
};

Complexity Analysis For Concatenation of Array LeetCode Solution:

Time Complexity

O(N), N is the length of the array and we are iterating only Once in the nums array.

Space Complexity 

O(1), If  we are not considering the ans array space.

Translate »