75. Sort Colors

🟧 Medium

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.

You must solve this problem without using the library's sort function.

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]

Constraints

  • n == nums.length

  • 1 <= n <= 300

  • nums[i] is either 0, 1, or 2.

Solution

My Solution (Counting Sort)

Optimal Solution (Dutch National Flag Algorithm)

Approach

This solution uses the Dutch National Flag algorithm (by Edsger Dijkstra):

  1. Key Insight:

    • Array can be divided into four sections:

      • [0, left): All 0s (red)

      • [left, curr): All 1s (white)

      • [curr, right]: Unknown elements

      • (right, n-1]: All 2s (blue)

  2. Implementation Strategy:

    • Use three pointers: left, curr, and right

    • Process elements at curr pointer

    • Maintain invariant sections through swaps

  3. Processing Rules:

    • 0: Swap with left section

    • 1: Keep in place

    • 2: Swap with right section

Complexity Analysis

Time Complexity: O(n)

  • Single pass through the array

  • Each element processed at most twice

  • All operations are O(1)

  • No extra passes needed

Space Complexity: O(1)

  • Only constant extra space used:

    • Three pointers (left, curr, right)

    • One temporary variable for swaps

    • No additional data structures

Why it works

  • Partition Properties:

    • Elements < curr are properly sorted

    • Elements > right are properly sorted

    • Unknown elements between curr and right

    • Invariants maintained by pointer movements

  • Optimization Details:

    • In-place sorting

    • Single pass through array

    • Minimal swaps needed

    • Stable within color groups

  • Key Improvements over Original:

    • No counting needed

    • No second pass required

    • True in-place algorithm

    • Better cache performance

  • Edge Cases Handled:

    • All same colors

    • Already sorted array

    • Reverse sorted array

    • Small arrays (n < 3)

result

Leetcode: link

Last updated

Was this helpful?