What is Big-O notation and why is it needed?
The gist
Big-O describes how an algorithm's running time (or memory) grows with the input size n. Constants and lower-order terms are dropped: O(2n + 10) is O(n). By default it refers to the worst case; for Array.append and hash tables you should say "amortized" and "on average".
Classes in ascending order:
- O(1) — index access,
Dictionarylookup on average. - O(log n) — binary search, a balanced tree.
- O(n) — a linear pass,
containson an array. - O(n log n) — good sorts, Swift's
sort(). - O(n²) — nested loops over one collection.
- O(2ⁿ) — naive recursion (Fibonacci), brute force over subsets.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep