Skip to main content

Sorting & Custom Comparators

The Mental Model

Sorting is often the first step in solving a problem, not the solution itself. A sorted array enables binary search, two pointers, and greedy approaches. The key skill is knowing when to sort and how to define the sort order.
Pattern Recognition Signals:
  • Problem mentions “minimum” or “maximum”
  • Need to pair elements optimally
  • Need to process elements in a specific order
  • Two pointers would work “if only the array were sorted”

When Sorting Helps

Enables Binary Search

Find elements, count less/greater, find bounds.

Enables Two Pointers

Pair elements from ends, merge operations.

Greedy Processing

Process smallest/largest first, interval scheduling.

Reduces Complexity

Many O(n²) become O(n log n) with sorting.

Sorting Fundamentals

Basic Sorting

Sorting Pairs and Tuples


Custom Comparators: The Power Tool

Lambda Comparators

Struct with Custom Comparator


Pattern: Coordinate Compression

Problem: Values are large (up to 10⁹) but count is small (up to 10⁵). Solution: Map values to smaller range while preserving order.
Use Cases: Segment trees, BIT when values are too large.

Pattern: Sorting by Multiple Criteria

Problem: Sort students by grade (descending), then by name (ascending).
Alternative using tuples (for complex sorting):

Pattern: Interval Scheduling

Problem: Select maximum number of non-overlapping intervals. Key Insight: Sort by end time. Greedy works because finishing early leaves room for more.
Codeforces Problems:

Pattern: Custom Order for Greedy

Problem: Arrange elements to maximize/minimize some combined result. Example: Concatenate numbers to form largest number.

Stable Sort

When: You need to preserve relative order of equal elements.

Common Mistakes

Mistake 1: Inconsistent Comparator Comparator must define a strict weak ordering:
  • a < a must be false (irreflexivity)
  • If a < b then b < a must be false (antisymmetry)
  • If a < b and b < c then a < c (transitivity)
Mistake 2: Sorting Changes Index Mapping If you need original indices, create pairs:
Mistake 3: Forgetting That Sort Modifies Array If you need the original, copy first:

Practice Problems

Beginner (800-1100)

Intermediate (1100-1400)

Advanced (1400-1600)


Key Takeaways

Sort First

Many problems become trivial after sorting. Always consider it.

Custom Comparators

Use lambdas for flexible, readable sorting logic.

Strict Weak Ordering

Comparator must use <, not <=. Violating this causes undefined behavior.

Preserve Indices

If you need original positions, pair elements with indices before sorting.

Next Up

Chapter 8: Recursion & Backtracking

Master the art of breaking problems into subproblems and exploring all possibilities systematically.