Similar Problems

Similar Problems not available

Concatenation Of Array - Leetcode Solution

Companies:

  • amazon

LeetCode:  Concatenation Of Array Leetcode Solution

Difficulty: Easy

Topics: array simulation  

Problem Statement:

Given two arrays of integers nums1 and nums2, concatenate them into a single array.

Example 1: Input: nums1 = [1,2,3], nums2 = [4,5,6,7] Output: [1,2,3,4,5,6,7] Explanation: Concatenate nums1 and nums2 into [1,2,3,4,5,6,7].

Example 2: Input: nums1 = [1], nums2 = [] Output: [1] Explanation: Concatenate nums1 and nums2 into [1].

Solution:

To solve this problem, we can simply create a new array and copy all elements of the given arrays into the new array in sequence. The time complexity of this approach is O(n), where n is the total number of elements in both the arrays.

Algorithm:

  1. Create an empty array arr3 to store the concatenation of the two arrays.

  2. Traverse through the first array nums1 and add each element to the arr3 using the push() method.

  3. Traverse through the second array nums2 and add each element to the arr3 using the push() method.

  4. Return the final array arr3 as the output.

Javascript Implementation:

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var getConcatenation = function(nums1, nums2) {
    let arr3 = []; // Creating an empty array to store the concatenation of nums1 and nums2
    
    // Adding all the elements of nums1 to arr3
    for(let i=0; i<nums1.length; i++){
        arr3.push(nums1[i]);
    }
    
    // Adding all the elements of nums2 to arr3
    for(let i=0; i<nums2.length; i++){
        arr3.push(nums2[i]);
    }
    
    return arr3; // Returning the concatenated array
};

Time Complexity: O(n), where n is the total number of elements in both the arrays.

Space Complexity: O(n), as we are creating a new array to store the concatenated elements of the given arrays.

Concatenation Of Array Solution Code

1