DSA Tracker

Easy

Sort an Array of 0s 1s and 2s

An easy Arrays problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Arrays
Sheets
3
Core for
25 roles
Platform
LeetCode

The problem

Sort an array containing only 0s, 1s, and 2s in ascending order in a single pass.

Example 1

Input
[2,0,2,1,1,0]
Output
[0,0,1,1,2,2]

Example 2

Input
[1,2,0,1,2,0]
Output
[0,0,1,1,2,2]

Example 3

Input
[0]
Output
[0]

Constraints

  • 1 <= n <= 3*10^4
  • arr[i] is 0, 1, or 2

How to think about it

Updated 2026-09-09

Because there are only three distinct values, maintaining three pointers partitions the array into four zones: known 0s, known 1s, an unexamined middle, and known 2s. Inspecting the current element lets you swap it immediately into its proper boundary zone, shrinking the unexamined window to zero in a single pass.

Approaches, worst first

  1. Counting and overwriting

    time O(n) · space O(1)

    Iterate once to count the occurrences of 0s, 1s, and 2s. Run a second pass to overwrite the original array cells in order based on those counts. Correct and straightforward, but requires two full sequential sweeps over the array.

  2. Dutch national flag partitionWrite this one

    time O(n) · space O(1)

    Maintain pointers low, mid, and high. If arr[mid] is 0, swap with arr[low] and advance both low and mid. If arr[mid] is 1, advance mid. If arr[mid] is 2, swap with arr[high] and decrement high without advancing mid, processing every element in a single pass.

Where people lose marks · 3
  • Advancing `mid` after swapping with `high`: the element brought in from `high` has not been examined yet and could be a 0 or 2 that requires further swapping.
  • Terminating the loop at `mid < high` instead of `mid <= high`, which misses processing the element at index `high`.
  • Arrays containing only a single distinct repeated number (e.g. all 2s) where low and high cross must terminate without pointer index out-of-bounds.

The theory behind it

Arrays — the ground this problem stands on. All Arrays problems

What Arrays is

An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.

When to reach for it

Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.

How the pattern works

Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.

What each operation costs

OperationTime
look up element by indexO(1)
insert or delete at the startO(n)
search an unsorted collection for a valueO(n)
What usually goes wrong with Arrays
  • Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
  • Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
  • Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.

Which roles need this problem

Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Arrays problems

Problem set and role mapping as of .