skip to Main Content

I’m working on this challenge:

https://leetcode.com/problems/merge-sorted-array/

This is my code:


/**
 Do not return anything, modify nums1 in-place instead.
 */
function merge(nums1, m, nums2, n) {
    nums2.forEach(i => {
        if (i > 0) {
            nums1.push(i)
        }

    })

    nums1.sort()


    for (let i = 0; i < nums1.length; i++) {
        if (nums1[i] == 0) {
            nums1.splice(i, 1)
        }
    }
};

This is the input ([1,2,3,0,0,0], 3, [2,5,6], 3)

My output is: [0,1,2,2,3,5,6]

Instead of: [1,2,2,3,5,6]

Can you tell me why?

Thanks!

2

Answers


  1. you’re looping over an array and using the index of the original array, but the array itself is being changed.

    So, if you start with [0,0,0,1,2,2,3,5,6], and you remove at index 0, [0,0,1,2,2,3,5,6].
    Then i=1, you check and remove at index 1 [0,(here=>)0,1,2,2,3,5,6] and end up with [0,1,2,2,3,5,6]. Further indexing reveals no zeroes.

    I would suggest you use a reduce or map instead and create a new array while maintaining the original for indexing.

    Login or Signup to reply.
  2. In your code you are altering the nums1 array length (by using the splice method) while looping over it using its initial length. This causes some indexes to be skipped. Adding i-- after you splice the array should solve your issue.

    function merge(nums1, m, nums2, n) {
        nums2.forEach((i) => {
            if (i > 0) {
                nums1.push(i);
            }
        });
    
        nums1.sort();
    
        for (let i = 0; i < nums1.length; i++) {
            if (nums1[i] == 0) {
                nums1.splice(i, 1);
                i--;
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search