'Array merge anomaly

I don't understand why the below solution doesn't return the anticipated result.

Use case: nums1: [1,2,3,0,0,0], nums2: [2,5,6], m:3, n:3

Expected result: [1,2,2,3,5,6], reality [1,2,2,3,0,0]

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

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """
        i = 0
        j = 0
        while i+j <= m+n:
            if nums1[i] < nums2[j]:
                i+=1
            else:
                temp = nums2[j]
                nums1[i+j+1 : i+j+m+1] = nums1[i+j : i+j+m]
                nums1[i+j] = temp
                j +=1 
        return nums1

Algorithm:

  1. Initialize i and j to 0
  2. Check if nums1[i] < nums2[j]
    1. If 2: keep nums1[i] as is and increment i.
    2. If not 2: shift non zero nums1 values by an index of 1 and increment j.
  3. return nums1

Yet, perplexingly, this works as intended until the last two remaining elements of nums2 need to be visited. Why is this?



Solution 1:[1]

A viable option is to go backwards from the right to the left in this case, i = m - 1 and j = n - 1, because the first array nums1 is half filled from the left, and after merging, it will be completely filled with the sorted output. The function will not return a new array.

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """
        i = m - 1
        j = n - 1
        while j >= 0:
            if i < 0:
                nums1[:j+1] = nums2[:j+1]
                break
            if nums1[i] > nums2[j]:
                nums1[i+j+1] = nums1[i]
                i -= 1
            else:
                nums1[i+j+1] = nums2[j]
                j -= 1

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3

Output: [1,2,2,3,5,6]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1