A2Z Lesson

Log in
← Back to the A2Z sheet

Step 01 Beginner Problems — Time Complexity

Theory with examples

Medium

Time complexity is the skill that separates 'my code works' from 'my code passes'. Instead of timing programs in seconds — which changes with every machine — we count how the number of operations grows with the input size n, and describe that growth with Big-O notation. Master the counting rules here and you will be able to look at any loop or recursion in this sheet and predict, before running it, whether it survives the constraints.

Why we count operations, not seconds

A stopwatch lies: the same program runs ten times faster on a new laptop, and a 'fast' algorithm in Python can lose to a 'slow' one in C++ on small inputs. What is stable across machines is the growth pattern — if input doubles, does the work double, quadruple, or explode? Big-O keeps only the dominant term of that growth and drops constants: 3n + 5 is O(n); n^2 + 100n is O(n^2), because for large n the n^2 term swamps everything else.

The growth ladder, slowest-growing first: O(1) constant — array access, one arithmetic op O(log n) logarithmic — binary search: n can be astronomically large O(n) linear — one pass over the data O(n log n) — good sorting: the practical speed limit for big inputs O(n^2) quadratic — nested loops over the data: fine to ~10^4, dead by 10^5 O(2^n) exponential — naive recursive Fibonacci: dead by n ≈ 45 O(n!) factorial — all permutations: dead by n ≈ 12

The three loop rules

Rule 1 — sequential work adds: a loop of n followed by another loop of n is O(n) + O(n) = O(n), not O(n^2). Rule 2 — nested work multiplies: a loop of n containing a loop of n is O(n^2); if the inner loop runs only to i (a triangle), the total is n(n+1)/2, still O(n^2). Rule 3 — halving is logarithmic: any loop that divides the problem size by 2 each step (i //= 2, binary search, Euclid's GCD) runs O(log n) times.

Apply them mechanically: read the code inside-out, multiplying as you exit each nesting level, adding as you pass sequential blocks. Watch inner bounds: a loop 'for j in range(i, n)' depends on i, so estimate its total across all i rather than assuming n every time.

n = 100 # input size total = 0 for i in range(n): # n times for j in range(n): # n times each total += 1 # -> O(n^2) x = n while x > 1: # halves each step x //= 2 # -> O(log n)

Recursion: count the calls, then the work per call

For recursion, total time = (number of calls) × (work per call). A function that calls itself once on n-1 (sum of first N, factorial) makes n calls — write the recurrence T(n) = T(n-1) + O(1) — and costs O(n). Binary search gives T(n) = T(n/2) + O(1) = O(log n).

The trap is branching recursion: naive Fibonacci calls itself twice, T(n) = T(n-1) + T(n-2) + O(1), and the call tree has roughly 2^n nodes — exponential, even though each call is trivial. Drawing the first three levels of the call tree is the fastest way to smell exponential blow-up. Dynamic programming, later in this sheet, exists precisely to collapse such trees.

Space complexity and auxiliary space

Space complexity counts memory growth with n. A few scalar variables are O(1) extra space; building a new array of size n is O(n). Recursion charges rent too: each live call holds a stack frame, so a recursion of depth n costs O(n) stack space even if it 'uses no arrays' — the hidden cost beginners forget when converting loops to recursion.

Say 'auxiliary space' when you mean extra space beyond the input itself; interviewers use the distinction to test whether your O(1)-space claim is honest. In-place algorithms (reversing an array by swapping) are the gold standard where achievable.

Worst, average, best — and the constraint reflex

Big-O usually quotes the worst case, because guarantees matter. But some structures shine on average: hash lookups are average O(1), worst-case O(n). Mention both when they differ.

Finally, build the reflex that maps constraints to budgets. Roughly 10^8 simple operations run in about a second in C++ (fewer in Python). So: n ≤ 10^5 demands O(n log n) or better; n ≤ 10^3 tolerates O(n^2); n ≤ 20 hints the intended solution is exponential or bitmask-based. Read the constraint before choosing the approach — it is the problem quietly telling you its intended complexity.

Common mistakes

Believing O(2n) and O(n) differ — constants are dropped, they are the same class. Forgetting that input reading and output printing themselves cost O(n). Analysing only the happy path of a recursive function and missing the branching factor. And the subtlest: summing loop bounds wrongly — an inner loop that runs to i inside an outer loop to n is still quadratic overall, while two separate sequential loops are merely linear. Draw the loops; count honestly.

Key points

  • Big-O describes growth: drop constants and lower terms; the dominant term is the whole story.
  • Loop rules: sequential adds, nested multiplies, halving is O(log n).
  • Recursion cost = number of calls × work per call; two-branch recursion is usually exponential.
  • Recursion depth is space too — depth n costs O(n) stack, even with no arrays.
  • Quote worst case by default; state average separately when it differs (hashing).
  • Read constraints first: n ≤ 10^5 → O(n log n); n ≤ 10^3 → O(n^2) OK; n ≤ 20 → exponential intended.

Suggested questions

Count of Prime Numbers till N ↗ Feel the difference an O(n√n) loop vs a sieve makes as N grows — complexity you can measure.
GCD of Two Numbers ↗ Euclid's algorithm is the halving rule in disguise: O(log) steps, not O(n).
Factorial of a given number ↗ One loop, one recurrence: verify it is exactly O(n) time and O(1) extra space.
Fibonacci Number ↗ Meet the exponential call tree from this lesson — then appreciate why memoisation exists.

Source note: this lesson follows the structure of Striver's public A2Z DSA course (takeUforward). Each problem links to its original platform, and all problems and content belong to their respective owners — STUDY-BUDDY does not claim ownership of the sheet or its problems, and no permission beyond public linking is claimed.