Skip to content

Comments

Working Solution#1773

Open
avcode3 wants to merge 1 commit intosuper30admin:masterfrom
avcode3:master
Open

Working Solution#1773
avcode3 wants to merge 1 commit intosuper30admin:masterfrom
avcode3:master

Conversation

@avcode3
Copy link

@avcode3 avcode3 commented Feb 22, 2026

No description provided.

@super30admin
Copy link
Owner

Your solution for the "Merging of 2 arrays" problem is correct and efficient. Well done! Here are a few suggestions to improve code clarity and adhere to the problem requirements:

  • Instead of modifying the parameters m and n (which are originally the counts of elements), it is better to create new variables for the pointers. For example, you can use p1 = m - 1 and p2 = n - 1 to point to the last valid elements in nums1 and nums2, respectively. This makes the code more readable and avoids changing the meaning of the parameters.

  • The problem states that the function should not return anything. Your solution returns nums1, which is not necessary since the array is modified in-place. You should remove the return statement to match the problem's requirement.

  • Consider adding a comment to explain the algorithm briefly, which can help others understand your approach.

Here is a slightly revised version of your code with these changes:

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        p1 = m - 1  # pointer for the last element in the initial part of nums1
        p2 = n - 1  # pointer for the last element in nums2
        idx = m + n - 1  # pointer for the last position in nums1

        while p1 >= 0 and p2 >= 0:
            if nums1[p1] >= nums2[p2]:
                nums1[idx] = nums1[p1]
                p1 -= 1
            else:
                nums1[idx] = nums2[p2]
                p2 -= 1
            idx -= 1

        # If there are remaining elements in nums2, copy them
        while p2 >= 0:
            nums1[idx] = nums2[p2]
            p2 -= 1
            idx -= 1

Overall, your solution is excellent. Keep up the good work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants