Merge Sorted Array — LeetCode 88 Python Solution

EasyArrayTwo PointersSorting
Problem
#88
Reading time
2 min

The problem

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. Merge nums1 and nums2 into a single array sorted in non-decreasing order.

Example

Input
nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output
[1,2,2,3,5,6]
Explanation
The arrays we are merging are [1,2,3] and [2,5,6].

Python solution

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

Complexity

MeasureComplexity
TimeO(m + n), where m and n are the lengths of two arrays
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 88. Merge Sorted Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 88. Merge Sorted Array?
LeetCode 88. Merge Sorted Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 88. Merge Sorted Array?
The Python solution on this page runs in O(m + n), where m and n are the lengths of two arrays.
What is the space complexity of LeetCode 88. Merge Sorted Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 88. Merge Sorted Array cover?
LeetCode 88. Merge Sorted Array is tagged Array, Two Pointers and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview