0
0
DSA Pythonprogramming~3 mins

Why Sort Colors Two Pointer Dutch Flag in DSA Python?

Choose your learning style9 modes available
The Big Idea

What if you could sort three colors perfectly in just one quick sweep?

The Scenario

Imagine you have a box of mixed colored balls: red, white, and blue. You want to arrange them so all reds come first, then whites, then blues. Doing this by picking each ball and placing it in the right spot one by one is tiring and slow.

The Problem

Manually sorting each ball means checking every ball multiple times and moving them around again and again. This wastes time and can cause mistakes, like mixing colors or missing some balls.

The Solution

The two-pointer Dutch Flag method sorts the balls in just one pass. It uses two pointers to keep track of where reds and blues should go, swapping balls as needed. This way, you sort all colors quickly and without confusion.

Before vs After
Before
colors = [2,0,2,1,1,0]
for i in range(len(colors)):
    for j in range(i+1, len(colors)):
        if colors[i] > colors[j]:
            colors[i], colors[j] = colors[j], colors[i]
After
colors = [2,0,2,1,1,0]
red, white, blue = 0, 0, len(colors) - 1
while white <= blue:
    if colors[white] == 0:
        colors[red], colors[white] = colors[white], colors[red]
        red += 1
        white += 1
    elif colors[white] == 2:
        colors[white], colors[blue] = colors[blue], colors[white]
        blue -= 1
    else:
        white += 1
What It Enables

This method lets you sort three groups in one quick pass, saving time and effort.

Real Life Example

Sorting laundry by color: whites, darks, and colors. Instead of sorting each piece multiple times, you quickly separate them in one go.

Key Takeaways

Manual sorting is slow and error-prone.

Two-pointer Dutch Flag sorts in one pass efficiently.

It uses swapping and pointers to organize colors quickly.