pythonarraysarray-merge

Merging sorted arrays with defined length in Python (good practices)


I have encountered interesting case during practicing writing Python algorithms on Leetcode.

The task: "You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively." The result should be stored inside the nums1 (which has length m+n, where n represents those elements that should be ignored from nums1 and added from nums2).

I have came with the simples solution, It is giving the expected results in VSCode but it is not passing test cases designed in LeetCode.

I am wondering why... What I am missing?

`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.
        """

        nums1 = sorted(nums1[0:m] + nums2[0:n])



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

solution = Solution()
result = solution.merge(nums1, m, nums2, n)
print(result)`

Please note I am a beginner. I am probably not taking something important into consideration. I guess it might me unwisely updating nums1 because I am loosing information about array, but is there anything else?

I couldn't find code for test cases in LeetCode to understand why problem occurred. Maybe anyone could help and guide me where to look for it?


Solution

  • The sorted function generates a new list object, but the solution requires modifying the existing nums1 variable.

    > origin_list = [3,2,1]
    > origin_list
    [3, 2, 1]
    > answer = sorted(origin_list)
    > answer
    [1, 2, 3]
    > answer is origin_list
    False
    

    Try to use methods of the list in your solution like: pop(), append(...)

    Pay attention to the comment: None Do not return anything, modify nums1 in-place instead.