Pattern — Sort Then Search

Khi nào dùng

Bài hỏi cặp / cluster / interval / “k phần tử thoả mãn quan hệ” — nhưng input KHÔNG sorted. Sort trước cho phép two pointers / binary search.

Heuristic

Khi bạn nghĩ tới HashMap/Brute force và thấy O(N²), thử SORT trước. Sort mất nhưng mở ra:

  • Two pointers
  • Binary search per query
  • Sweep line

Top problems

BàiLCVì sao sort?
3SumLC #15Sort → 3 pointers + skip dup
Meeting Rooms IILC #253Sort theo start, sweep theo end
Merge IntervalsLC #56Sort theo start → merge tuần tự
Non-overlapping IntervalsLC #435Sort theo end → greedy
Largest NumberLC #179Sort với custom compare b+a vs a+b
Top K Closest PointsLC #973Quickselect / sort by distance
Reduce Array Size to HalfLC #1338Sort freq desc → greedy lấy lớn nhất
Boats to Save PeopleLC #881Sort + two pointers
Custom Sort StringLC #791Sort by custom order
H-IndexLC #274Sort desc → tìm h

Pitfalls

  1. Sort mất O(N log N) — nếu bài cần O(N), sort không phải đáp án.
  2. Lost original order: nếu cần index gốc, lưu [value, originalIndex] rồi sort.
  3. Stable sort matter: JS Array.sort từ ES2019 stable; cẩn thận với engine cũ.
  4. Custom compare overflow: (a, b) => a - b có thể overflow với int64 — JS dùng float64 OK.

→ Nguồn: 06-Sorting-Merge-Quick, 15-Intervals