mediumDSA

How do you sort an array of 0s, 1s, and 2s?

825 views
01

Understand the problem

Explain the Dutch National Flag algorithm.

arrayssortingdutch-flag
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Dutch National Flag
Run Playground
def sort_colors(nums):
    low, mid, high = 0, 0, len(nums) - 1
    while mid <= high:
        if nums[mid] == 0:
            nums[low], nums[mid] = nums[mid], nums[low]
            low += 1; mid += 1
        elif nums[mid] == 1:
            mid += 1
        else:                               # == 2
            nums[mid], nums[high] = nums[high], nums[mid]
            high -= 1                        # do NOT advance mid
    return nums


# --- demo ---
print(sort_colors([2, 0, 2, 1, 1, 0]))   # [0, 0, 1, 1, 2, 2]
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.