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.Pattern: Sorting by Multiple Criteria
Problem: Sort students by grade (descending), then by name (ascending).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.| Problem | Rating | Link |
|---|---|---|
| Cloud of Hashtags | 1300 | CF 777C |
| Div2A - Many sorting problems | 800-1000 | Problemset |
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
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.