Skip to main content
๐Ÿ“œ WAYPOINT LESSON

Choosing an algorithm

โญ beginnerโณ 10 min read๐Ÿ“ Lesson 67 of 256

Match the tool to the guarantee: sorted vs unsorted, one value vs all pairs.

Choosing an algorithm โ€” matching the tool to the constraint:

  • Need the max/min/sum of an array? One pass โ€” O(n). Nothing better exists (you must look at every element at least once).
  • Need to know whether a value is present in an unsorted array? Linear scan, O(n).
  • Same question, sorted array? Binary search, O(log n) โ€” but only because sortedness lets you discard half each step.
  • Need all pairs? That's nยฒ by nature; the trick is usually to avoid needing all pairs.
// sorted: discards half each step โ€” unsorted: cannot
while (lo <= hi) {
    int mid = (lo + hi) / 2;
    if (a[mid] == target) return mid;
    if (a[mid] < target) lo = mid + 1;
    else hi = mid - 1;
}
return -1;

The exam phrases this as "which algorithm is most appropriate" โ€” answer by naming what the data guarantees (sorted or not) and what the question needs (one value? all pairs? a position?). Guarantees are what you buy complexity savings with.

โšก Now practice

Ready to Code
Algorithmic reasoning repsFormula vs loop, equal pairs, binary search, max repair, sum trick.
4 challenges ยท ยท ~55 min