AlgoMaster Logo

Sort Colors

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Counting Sort

Intuition:

The problem can be solved by first counting the number of occurrences of each color (0s, 1s, and 2s). This information can be used to overwrite the original array by placing the colors consecutively as per the number of occurrences. Although this is not done in one-pass, it is straightforward and efficient.

Steps:

  1. Count the number of 0s1s, and 2s in the array.
  2. Overwrite the array with the correct number of 0s, followed by 1s, and then 2s.

Code:

2. One-pass Dutch National Flag Problem (Three Pointers)

Intuition:

This approach utilizes the famous Dutch National Flag algorithm which sorts the array using one pass and constant space by maintaining three pointers: lowmid, and high.

  • low maintains the boundary of zeros.
  • mid iterates over the array.
  • high maintains the boundary of twos.

Steps:

  1. Initialize three pointers: low at the start, mid at the start, and high at the end of the array.
  2. While mid is less than or equal to high:
    • If the element at mid is 0, swap it with the element at low. Increment both low and mid.
    • If the element at mid is 1, just increment mid.
    • If the element at mid is 2, swap it with the element at high. Decrement high (do not increment mid because the swapped element from high may need further processing).

Code: