Skip to main content

πŸ“ˆ Sorting

Sort first, ask questions later. Many "hard" array problems become trivial once sorted. Know the sorts well enough to choose, and know when to use a custom comparator.

This category contains 21 problems. Use the patterns below to recognize what's being asked, then jump to the problem list at the bottom.


🧠 Key Patterns​

  • Sort + Two Pointers β€” Pair/triplet sum, closest target.
  • Counting / Bucket Sort β€” Integer values in known range β†’ O(n)O(n).
  • Custom Comparator β€” Sort by frequency, by digit, "largest number" trick.
  • Merge Sort β€” Count inversions, external sorting, stable sort.
  • Quickselect β€” O(n)O(n) average for k-th smallest.
  • Heap Sort / Top-K β€” Partial sort when full sort is overkill.

⚠️ Common Pitfalls​

  • Default sort in C# (Array.Sort) is not stable; List<T>.Sort is also not stable. Use OrderBy (LINQ) for stable.
  • Comparator returning subtraction can overflow with int.MinValue.

πŸ“š Study Resources​

πŸ“Ί Videos​

πŸ“– Books​

  • Introduction to Algorithms (CLRS) β€” Ch. 2, 6–8
  • Algorithms β€” Sedgewick β€” Ch. 2

🌐 Articles & References​


πŸ’» All Sorting Problems​