1 · MindsetBig-O Without the Panic
All courses

Interviewers do not care how fast your laptop is — they care how the work grows.

Take an array of size n. One loop that touches each element once does about n units of work. Double n, roughly double the time → that is O(n). Nest another loop over the same length and you are looking at O(n²): 10 items feel fine, 10,000 feel painful.

scan → 4 0 1 1 3 2 9 3 2 4

Picture [4, 1, 3, 9, 2] on paper. A single scan visits 5 boxes. A nested “compare every pair” visits about 5×5 checks. Same input, wildly different growth. Big-O is just naming that trend — not counting exact milliseconds.

Hash maps flip the story: average lookup is O(1), so many “brute force nested loops” problems collapse to one pass plus a map. Patterns (two pointers, sliding window, hashing) beat memorizing 500 problems.

Dry run

n = 5
i: 0 → count=1
i: 1 → count=2
i: 2 → count=3
i: 3 → count=4
i: 4 → count=5
loop done → print 5

Complexity

This loop is O(n) time and O(1) extra space — one counter, no growing data structure. Nested loops over n are usually O(n²). Sorting first is typically O(n log n).

Common mistakes

  • Confusing “number of lines of code” with runtime growth.
  • Saying O(1) just because the loop body looks short — body cost × iterations still matters.
  • Ignoring hidden costs (sorting inside the function, copying the whole array each step).
Rule of thumb: one loop over n → usually O(n). Nested loops over n → often O(n²). Hash map lookup → average O(1).

Your turn: keep the loop as-is. Output should be 5.

Watch it run

One pass = O(n)

1 / 6

Start at index 0. We look at one cell at a time.

40
11
32
93
24
Output
Press Run to execute your code.