75. Sort Colors πŸ”₯

Medium

Problem:

Considering the color red as 0, white as 1, and blue as 2, perform an in-place sorting in the order.

Example 1:

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

Example 2:

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

https://leetcode.com/problems/sort-colors/arrow-up-right

What to learn:

This problem is identical to the Dutch National Flag Problem proposed by Dijkstra in 1976 and is closely related to the idea of improving quicksort.

The idea was to use a pivot to divide into three parts: the smaller part, the equal part, and the larger part (Three-way partitioning), aiming to enhance the conventional two-part division of quicksort.

three-way-partition(AΒ : array of values, midΒ : value):
    i ← 0
    j ← 0
    k ← size of A - 1

    while j <= k:
        if A[j] < mid:
            swap A[i] and A[j]
            i ← i + 1
            j ← j + 1
        else if A[j] > mid:
            swap A[j] and A[k]
            k ← k - 1
        else:
            j ← j + 1

This pseudocode uses i and k as pointers on both sides, with j moving and swapping based on the mid value.

Pseudocode: https://en.wikipedia.org/wiki/Dutch_national_flag_problemarrow-up-right

Solution:

When the comparison is finally complete, red points to one position beyond the index smaller than 1, blue points to the initial spot of the index larger than 1, and the comparison concludes as white and blue overlap.

chevron-rightExample run with nums = [2,0,2,1,1,0]hashtag

Last updated