Sort Colors — LeetCode 75 Python Solution

MediumArrayTwo PointersSorting
Problem
#75
Reading time
2 min

The problem

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

Example

Input
nums = [2,0,2,1,1,0]
Output
[0,0,1,1,2,2]

Python solution

Python
class Solution:
    def sortColors(self, nums: List[int]) -> None:
        i, j, k = -1, len(nums), 0
        while k < j:
            if nums[k] == 0:
                i += 1
                nums[i], nums[k] = nums[k], nums[i]
                k += 1
            elif nums[k] == 2:
                j -= 1
                nums[j], nums[k] = nums[k], nums[j]
            else:
                k += 1

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 75. Sort Colors 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 Grind 75.

Frequently asked questions

How hard is LeetCode 75. Sort Colors?
LeetCode 75. Sort Colors is rated Medium on LeetCode.
What is the time complexity of LeetCode 75. Sort Colors?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 75. Sort Colors?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 75. Sort Colors cover?
LeetCode 75. Sort Colors 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