Start With the Problem#
StudyBuddy wants to check: "has any student ID been entered twice in this upload?" Here are three correct solutions, timed on the same Mac with lists of distinct IDs (so every solution must look at everything):
n slow (check every pair) sort, then check neighbours remember what you've seen (HashSet)
10000 8.9 ms 0.75 ms 0.67 ms
20000 34.8 ms 1.50 ms 1.47 ms
40000 136.7 ms 2.06 ms 2.32 ms
80000 540.9 ms 3.94 ms 3.25 msAt 80,000 IDs they're all "fast enough". But look at the pattern: every time n doubles, the first solution takes about 4× longer, and
the others about 2×. Keep going:
at 1 million IDs, the first solution takes roughly 540 ms × (1,000,000 ÷ 80,000)² ≈ 85 seconds; the HashSet one about 40 ms;
at 100 million IDs, the first would take about 10 days.
The time on your laptop today is not what matters. How the time grows as the input grows is what matters — and you can work it out from the code, before running anything. That's what Big-O is. In an interview you have no time to run benchmarks; you must predict.
The Plain Picture#
Two people are asked, "How long does it take to read a book?" One says "3 hours". But that depends on who's reading, their glasses, the light. A better answer: "It takes about one minute per page." Now the answer works for any book and scales: a 600-page book takes twice as long as a 300-page one — for any reader.
The Real Names#
The input size, usually called n, is how big the input is: the number of items in an array, characters in a string, nodes in a graph.
The running time is counted as the number of basic steps as a function of n — not in seconds. A basic step is anything that takes a fixed amount of time regardless of n: an arithmetic operation, a comparison, reading
arr[i](Java Basics Ch 8), a variable assignment.Seconds depend on the machine, the JIT (How Computers Work Ch 8), and what else is running. Step counts don't.
Under the Hood#
int sum = 0; // 1 step
for (int i = 0; i < n; i++) {
// the loop body runs n times
sum += arr[i]; // ~2 steps each time (read, add)
}Total ≈ 1 + 2n steps. The exact numbers (1, 2) depend on how you count — which is why the next chapter throws them away.
Check yourself
2 questionsWhy count steps rather than measure seconds?
Show answerHide answer
Seconds depend on the machine and conditions; step counts depend only on the algorithm and input size.
What is n?
Show answerHide answer
The size of the input (items, characters, nodes…).