DEV Community

codingpineapple
codingpineapple

Posted on

88. Merge Sorted Array (javascript solution)

Description:

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2.

Solution:

Time Complexity : O(n)
Space Complexity: O(1)

// Two pointer solution
// Start by comparing the largest numbers between the two arrays and add to the end of nums1
var merge = function(nums1, m, nums2, n) {
 while (n) {
    if (nums1[m - 1] > nums2[n - 1]) {
      nums1[m + n - 1] = nums1[--m];  
    } else {
      nums1[m + n - 1] = nums2[--n];   
    }
  }
  return nums1;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)