LeetCode 88: Merge Sorted Array — Python Solution

Solve LeetCode 88: Merge Sorted Array in Python with a reverse two pointers approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyEasy
TopicArray / String
Reusable patternreverse two pointers
ComplexityO(m+n) time and O(1) extra space

What the problem is testing

Compare the largest unused values and write into the final open slot of nums1. Working backward avoids overwriting values that have not been compared.

Algorithm

  1. Compare the largest unused values and write into the final open slot of nums1. Working backward avoids overwriting values that have not been compared.
  2. Maintain this invariant: Every position after the write pointer already contains the correct largest remaining value.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def merge(self, nums1, m, nums2, n):
        i, j, write = m - 1, n - 1, m + n - 1
        while j >= 0:
            if i >= 0 and nums1[i] > nums2[j]:
                nums1[write] = nums1[i]
                i -= 1
            else:
                nums1[write] = nums2[j]
                j -= 1
            write -= 1

Why this is correct

The proof follows the maintained state: Every position after the write pointer already contains the correct largest remaining value. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(m+n) time and O(1) extra space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

Either input can be empty; equal values and duplicate runs are valid.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Next: 27. Remove Element