Pattern #9

Sorting

Important interview questions, thinking patterns, sorting algorithms, and rules for solving sorting problems in Go.

Must Solve

18 core questions — solve these first.

  1. 1.Sort Colors
    medium
  2. 2.Merge Intervals
    medium
  3. 3.Insert Interval
    medium
  4. 4.Meeting Rooms
    easy
  5. 5.Meeting Rooms II
    medium
  6. 6.3Sum
    medium
  7. 7.4Sum
    medium
  8. 8.Largest Number
    medium
  9. 9.Top K Frequent Elements
    medium
  10. 10.Kth Largest Element in an Array
    medium
  11. 11.Merge Sorted Array
    easy
  12. 12.Squares of a Sorted Array
    easy
  13. 13.Non-overlapping Intervals
    medium
  14. 14.Minimum Number of Arrows to Burst Balloons
    medium
  15. 15.Relative Sort Array
    easy
  16. 16.Sort Characters By Frequency
    medium
  17. 17.H-Index
    medium
  18. 18.Maximum Gap
    hard

Also Important

10 more questions worth practicing.

  1. 19.Sort an Array
    medium
  2. 20.Custom Sort String
    medium
  3. 21.Reorder Data in Log Files
    medium
  4. 22.Queue Reconstruction by Height
    medium
  5. 23.Minimum Difference Between Highest and Lowest of K Scores
    easy
  6. 24.Find K Closest Elements
    medium
  7. 25.Rank Transform of an Array
    easy
  8. 26.Boats to Save People
    medium
  9. 27.Maximum Units on a Truck
    easy
  10. 28.Minimum Moves to Equal Array Elements II
    medium

How to Think

  1. Need order first?Sort
  2. Need pair/triplet?Sort + Two Pointers
  3. Intervals?Sort by start time
  4. Need smallest / largest K?Sort or Heap
  5. Need greedy choice?Sort → Pick best next item
  6. Need duplicate values together?Sort them

Go Thinking & Reference

Basic Built-in Sorting

sort.Ints(nums)     // Sort slice of ints ascending
sort.Strings(words) // Sort slice of strings lexicographically

Custom Comparator (sort.Slice)

sort.Slice(intervals, func(i, j int) bool {
    return intervals[i].Start < intervals[j].Start // return true means i comes before j
})

👉 Built-in sort uses Pattern-defeating Quicksort (pdqsort): O(n log n)

Main Sorting Algorithms

Bubble Sort

O(n²)

Compare neighbors → Swap if wrong order. Repeat passes until sorted.

👉 Simple, but usually too slow.

Selection Sort

O(n²)

Find min → Place at start. Find next min → Place next.

👉 Select the next correct value.

Insertion Sort

O(n²)

Build sorted part one item at a time by shifting elements.

👉 Good when data is small or almost sorted.

Merge Sort

O(n log n)

Divide into halves recursively → Sort halves → Merge in order. (Space: O(n))

👉 Divide → Sort → Merge.

Quick Sort

O(n log n) avg | O(n²) worst

Choose pivot → Partition elements (smaller < pivot < bigger) → Recurse.

👉 Pivot and partition.

Stable vs Unstable Sorting

Stable sorting means equal values keep their original relative order.

Alice  score 90
Bob    score 90

After stable sort by score:
Alice
Bob  (original relative order stays)

💡 Stable matters when sorting by multiple fields (e.g. sort by name first, then by score).

Interview Rules

  1. 1. Pair/triplet problem? → Consider Sort + Two Pointers
  2. 2. Intervals? → Usually sort by start time first
  3. 3. Need ordering? → Sort
  4. 4. Need K largest/smallest? → Sort or Heap
  5. 5. Need duplicates together? → Sort
  6. 6. Need binary search? → Data must be sorted
  7. 7. Need greedy choice? → Sorting often comes first
  8. 8. Need to preserve original index? → Store index before sorting
  9. 9. General good sortingO(n log n)
  10. 10. Avoid O(n²) sorting for large inputs

Small Rules

  1. Rule 1: Sorting costs O(n log n). If it makes the rest easy, it is worth it.
  2. Rule 2: Sorted data unlocks Two Pointers, Binary Search, Greedy, and Interval Merging.
  3. Rule 3:Don't use Bubble Sort in production for large data (100k items = 10 billion comparisons).
  4. Rule 4: If order must stay unchanged, attach original index before sorting.
  5. Rule 5: Interviewers care more about WHAT you sort by (custom comparators) than writing sort from scratch.

Production Thinking

Database ResultsORDER BY created_at DESC (Prefer DB index over app memory sort)

Logs MergingSort by timestamp to merge multi-server logs

Job SchedulingSort by priority / deadline / start time

E-commerceCustom comparator for price, rating, popularity

Interval SystemsSort meetings by start time to detect overlaps

What Should You Actually Remember?

Bubble / Insertion  → understand only
Merge Sort          → know properly (Split + Merge)
Quick Sort          → know properly (Pivot + Partition)
Built-in sorting    → use confidently (sort.Slice)

Remember This

Need order          → Sort
Pair / Triplet      → Sort + Two Pointers
Intervals           → Sort by start time
K largest/smallest  → Sort / Heap
Merge sorted data   → Two Pointers
General efficient   → O(n log n)
Merge Sort          → Split + Merge
Quick Sort          → Pivot + Partition

💡 Golden Rule: "Sorting may cost O(n log n), but the order it creates can make the whole problem much easier."