0% completed
Clearer problem description (No solution/spoiler)
Rudy Peralta
Jun 9, 2025
So for this problem the wording is a bit weird and doesn't convey the spirit of the problem.
Here's a clearer description for what we want to achieve and why using arr.sort() is both not allowed and wouldn't fully solve the problem:
You are given an array that contains only three types of elements: 0, 1, and 2.
Your task is to sort the array in-place (i.e., without using extra space for another array), such that:
- All
0s come first, - Followed by all
1s, - Followed by all
2s.
You cannot just count the number of 0s, 1s, and 2s and then overwrite the array — you must sort the array in one pass (the two pointers technique lends itself quite well to this type of in place sort.
Example:
Input:
[2, 0, 2, 1, 1, 0]
Output:
[0, 0, 1, 1, 2, 2]
Why it's called the Dutch National Flag Problem:
The Dutch flag has three horizontal bands of different colors. Similarly, you're organizing the array into three sections (0s, 1s, 2s). So the sorting simulates the structure of the Dutch flag.
Goal:
Sort the array with O(n) time and O(1) space using a single pass.
2
0
Comments
On this page
Problem Statement
Examples
Example 2
Try it yourself