Sorting

O(n log n)

Use sorting as a preprocessing step to simplify problems, or apply partition logic for in-place rearrangement. Many interview problems become trivial once the array is sorted.

Time: O(n log n)Space: O(1) to O(n)

When to Use

  • Interval problems (merge, insert, non-overlapping)
  • Finding closest pairs or grouping adjacent elements
  • Problems requiring custom ordering (largest number, frequency sort)
  • In-place partitioning (sort colors, sort by parity)

Pattern Variants

Sort + Linear Scan

Sort the array first, then scan linearly to find the answer. Sorting makes adjacent elements comparable.

Use for: Merge intervals, meeting rooms, 3Sum, closest pairs

Custom Comparator

Define a custom sort order using a comparator function. The key insight is choosing what to compare.

Use for: Largest number, sort by frequency, relative sort, custom ordering

Partition / Dutch Flag

Rearrange elements in-place by partitioning around a condition without fully sorting.

Use for: Sort colors (0s, 1s, 2s), sort by parity, QuickSelect for Kth element

Bucket / Counting Sort

When values are bounded, use counting or bucket sort for O(n) time instead of O(n log n).

Use for: Top K frequent, sort characters by frequency, bounded integer sorting

Interactive Visualization

Step-through visualization coming soon...

This will include beginner, intermediate, and advanced examples with code highlighting.

Practice this Pattern

Go to Network Delay Time

Network Delay Time

Find time for all nodes to receive signal from source

Go to Meeting Rooms II

Meeting Rooms II

Find minimum number of conference rooms needed

Go to Merge Sort

Merge Sort

Implement merge sort using divide-and-conquer

Go to Quick Sort

Quick Sort

Implement quicksort with partition — the most important sort for interviews

Go to Merge Intervals

Merge Intervals

Merge all overlapping intervals — classic FAANG sorting problem

Go to Kth Largest Element

Kth Largest Element

Find the kth largest element using QuickSelect (partition)

Go to Largest Number

Largest Number

Arrange numbers to form the largest possible number

Go to Meeting Rooms

Meeting Rooms

Can a person attend all meetings? Check for overlapping intervals

Go to Sort Colors (Dutch Flag)

Sort Colors (Dutch Flag)

Sort array of 0s, 1s, 2s in-place using three pointers

Go to Sort Characters by Frequency

Sort Characters by Frequency

Sort characters by how often they appear, most frequent first