Arrays · Core Array Techniques

Sorting-Based Techniques

Problems where sorting first (or a single-pass partitioning scheme like Dutch National Flag) turns a hard problem into a simple one.

  • 5 min read
  • 8 practice questions
  • 2 graded problems
On this page
  1. Description
  2. The approach: two ideas under one skill
  3. Where you'll see it
  4. Which tool for which job?
  5. Common mistakes
  6. Check yourself
  7. Key takeaways
  8. Quick revise
  9. Practice

Description

Sorting is often the step that turns a hard-looking problem into an easy one. Once the data is in order, overlapping intervals sit next to each other, duplicates are neighbors, and two pointers work. This skill covers that move: sort first, then scan. It also covers a faster cousin for data with only a few distinct values, the one-pass Dutch National Flag partition.

We'll go from simple to more technical:

  1. "Just sort it first" - and what it costs.
  2. Dutch National Flag: three pointers for three values.
  3. Where both show up in production (scheduling, priority buckets).
  4. Choosing between a general sort and a one-pass partition.

The approach: two ideas under one skill

1. "Just sort it first." Without sorting, "do any of these meetings overlap?" means comparing every pair, O(n^2). Sorted by start time, each meeting only needs comparing with the one before it. Take meetings from 13 to 14, 9 to 11, 10 to 12 and 15 to 16:

Meeting (sorted by start)Previous meeting ends atOverlap?
9 to 11
10 to 1211yes: it starts at 10, before 11
13 to 1412no
15 to 1614no

Merging intervals, finding the closest pair and checking whether two arrays hold the same values all get easier the same way. The cost is O(n log n), and the original order is lost. If a later step needs the original positions, sort (value, originalIndex) pairs instead of bare values.

2. Dutch National Flag (three-pointer partitioning). When there are only a few known values, classically 0, 1 and 2, you don't need a general sort at all. Three pointers split the array as you go: everything before low is 0, everything between low and mid is 1, and everything after high is 2. mid looks at the next unknown element.

Sorting [2, 0, 1, 2, 0]:

mid seesActionArray afterlow, mid, high
2swap with high, high down0 0 1 2 20, 0, 3
0swap with low, both up0 0 1 2 21, 1, 3
0swap with low, both up0 0 1 2 22, 2, 3
1mid up0 0 1 2 22, 3, 3
2swap with high, high down0 0 1 2 22, 3, 2

mid has passed high, so the array is sorted in one pass.

Java

int low = 0, mid = 0, high = nums.length - 1;
while (mid <= high) {
    if (nums[mid] == 0) { swap(nums, low++, mid++); }
    else if (nums[mid] == 1) { mid++; }
    else { swap(nums, mid, high--); }   // note: mid does NOT advance here
}

Python

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:
        nums[mid], nums[high] = nums[high], nums[mid]
        high -= 1                  # note: mid does NOT advance here

After a swap with high, mid stays put. The value that just came in from the end hasn't been looked at yet.

Where you'll see it

Splitting a queue of work into three severity levels in one pass is the same three-pointer shape. "Sort first" is the standard first move for scheduling and conflict checks, such as overlapping room bookings or clashing deployment windows.

Which tool for which job?

You needUse
Overlaps, merges, closest pairssort, then scan neighbors
Two or three known values (0/1/2)a one-pass partition (Dutch National Flag)
Small integer range (0..k)counting sort, O(n + k)
Sort, but keep the original positionssort (value, index) pairs
Several sort keysone sort with a tuple / thenComparing key
Only the k smallesta heap or quickselect, not a full sort

Common mistakes

MistakeWhat happensDo this instead
Dutch National Flag with many distinct valuesit doesn't sorta real sort, or counting sort
Advancing mid after the high swapan unexamined value is skippedleave mid where it is
Sorting when the answer needs original indicesindices point into the sorted copysort (value, index) pairs
(a, b) -> a - b as a Java comparatoroverflow puts negatives lastInteger.compare(a, b)
Sorting numbers stored as strings"10" comes before "9"sort by the numeric value

Check yourself

Try to answer before opening each one - recalling beats re-reading.

1. Dutch National Flag moves mid after a swap with low but not after a swap with high. Why?

Show answer

The value that comes in from low has already been looked at, since everything before mid has been. It's a 0 or a 1, so mid can move past it. The value that comes in from high hasn't been looked at at all. It could be anything, so mid stays to check it.

2. You need the closest pair of values and their original indexes. Why is sorting the bare values a problem?

Show answer

Sorting moves the values and forgets where each one came from. Once sorted, you can't recover the original indexes unless you kept them on purpose, for example by sorting (value, originalIndex) pairs.

3. An array holds only three known values, but a solution uses a general O(n log n) sort. Is the output wrong?

Show answer

No, it's correctly sorted. The miss is speed: an O(n) one-pass partition was available. That still counts in an interview, just differently from using Dutch National Flag where it doesn't apply, which gives wrong output.

Key takeaways

  • "Just sort it" costs O(n log n) and works for any values. Dutch National Flag is O(n) and works for a few known values.
  • After a swap with high, mid stays put. After a swap with low, it moves on.
  • Sorting loses the original order. Sort (value, originalIndex) pairs if you'll need it back.
  • Using Dutch National Flag on too many values is a correctness bug. Missing it where it fits is a speed miss.

Quick revise

The whole skill on one page, for the night before an interview.

Everything from the lesson and the deep dive on one page. Skim it before practice or an interview, and open the full lesson for anything that doesn't ring a bell.

Pick the tool

You needUse
Overlaps, merges, neighborssort, then scan
Three known valuesDutch National Flag
Small integer rangecounting sort
Original positionssort (value, index) pairs
Several keysa compound key
Only the k smallesta heap or quickselect

Snippets worth knowing by heart

Java

intervals.sort(Comparator.comparingInt((int[] a) -> a[0]));   // never (a, b) -> a[0] - b[0]
List<int[]> merged = new ArrayList<>();
for (int[] cur : intervals) {
    if (!merged.isEmpty() && cur[0] <= merged.get(merged.size() - 1)[1]) {
        int[] last = merged.get(merged.size() - 1);
        last[1] = Math.max(last[1], cur[1]);
    } else merged.add(cur);
}

Python

intervals.sort(key=lambda iv: iv[0])
merged = []
for start, end in intervals:
    if merged and start <= merged[-1][1]:
        merged[-1][1] = max(merged[-1][1], end)
    else:
        merged.append([start, end])

The traps

  • Dutch National Flag with many values: three-way partitioning sorts only three distinct values. Use a real sort, or counting sort.
  • Advancing mid after the high swap: the value swapped in is never examined. Leave mid where it is.
  • Lost indices after sorting: indices point into the sorted copy. Sort (value, index) pairs.
  • a - b comparators: overflow puts negatives last. Use Integer.compare(a, b).
  • Numbers as strings: "10" sorts before "9". Sort by the numeric value.

Staff-level points, one line each

  • Java: dual-pivot quicksort for primitives (unstable), TimSort for objects (stable); Python: Timsort, stable.
  • Stable sorts compose: name then department gave department, then name.
  • a - b sorted [1, MIN_VALUE, 0] as [0, 1, -2147483648].
  • ["9", "10", "2"] sorts to ['10', '2', '9'] - use key=int.
  • Comparisons for 10,000 items: 9,999 sorted, 10,906 nearly sorted, 120,188 shuffled.

Say it in an interview

  • "Sorting first costs O(n log n) and puts overlapping intervals next to each other."
  • "With only three values I can partition in one pass instead."
  • "I'll sort (value, index) pairs because I need the original positions."
  • "I use Integer.compare, not subtraction, in comparators."

Practice

This skill comes with 8 multiple-choice questions that tell you which misconception a wrong answer reveals and 2 graded problems. Your answers are graded and your mastery is tracked, so you'll know when the skill holds up. Running code and saving progress need a free account.

Practice Sorting-Based Techniques free

Sort Colors

MediumProCoding problemJava · Python

nums holds only the values 0, 1 and 2, standing for three colors (think red, white and blue). Rearrange it in place so all the 0s come first, then the 1s, then the 2s.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Merge Intervals

MediumProCoding problemJava · Python

You get a list of intervals [start, end], in no particular order. Wherever two intervals overlap (sharing just an endpoint counts), combine them into one. Return the merged intervals, sorted by their start.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Practice Sorting-Based Techniques free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime