Skip to the page

Foundations · core

Big-O in plain words

Big-O says how time or memory grows when the input size n grows, keeping only the biggest term: one loop is O(n), a loop inside a loop is O(n²), and halving the work each step is O(log n).

The notes

What you must know

  • Drop constants and small terms: O(3n + 20) is O(n); O(n² + n) is O(n²). Two different inputs stay separate: O(n + m) or O(n·m).
  • Costs to remember in every language: append to a dynamic array is O(1) amortised; insert or remove at the front or middle is O(n); search in an unsorted array is O(n); a hash map or hash set lookup is O(1) on average; sorting is O(n log n); a balanced tree or a heap push and pop is O(log n).
  • A hidden loop counts: checking 'is x in this array' inside a loop is O(n·m), not O(n). Replacing the array with a hash set makes it O(n + m). Copying a substring or a slice of length k also costs O(k).
  • Space counts too: a new array or hash map of size n is O(n) extra space; recursion uses O(depth) memory for the call stack.
  • Amortised O(1) means one append may cost O(n) when the array grows, but n appends cost O(n) in total, so the average per append is O(1).
  • Rough limits for a one-second answer: n up to about 10^3 allows O(n²); n up to 10^5 or 10^6 needs O(n log n) or O(n). A simple loop runs about 10^8 steps per second in Java and C++ and about 10^7 in Python (rough numbers).
  • Say the complexity before coding ('brute force is O(n²); with a hash map it becomes O(n)') and again after, including space. Interviewers expect both.

The red pen

Common traps: mistake → fix

  • Mistake: Removing from the front of an array is O(1)

    Fix: every element moves, so it is O(n) (Python list.pop(0), Java ArrayList.remove(0), C++ vector erase at begin). A BFS built on it becomes O(n²); use a deque or a head index.

  • Mistake: My loop is O(n) because there is one loop

    Fix: check the body: a contains, a substring, a copy or a sort inside the loop is another loop.

  • Mistake: Recursion is free in memory

    Fix: each call is a stack frame, so depth n means O(n) space and a possible stack overflow.

  • Mistake: O(log n) means 'a bit faster'

    Fix: it means the problem size is divided (usually halved) each step: 1,000,000 items need only about 20 steps.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the time and space complexity of your solution?
  2. Why is checking 'is x in this array' inside a loop slow? How do you fix it?
  3. What does amortised O(1) mean for adding to a dynamic array?
  4. Your input grows from 1,000 to 1,000,000 items. Which of your two solutions still works and why?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview