Algorithms from zero
Thinking & complexity: multiple-choice review
Six questions that cut across the whole unit. None of them is a definition to recite — each one is a decision you make when you size up an algorithm before you ever run it.
Confirm you can connect step-counting, Big-O, complexity classes, the time-space tradeoff, and input constraints into one judgement: given some code and some limits, what does this cost and is it fast enough?
An algorithm performs exactly 5n + n²/2 + 1000 basic operations on input of size n. What is its Big-O, and why?
A problem states n ≤ 1,000,000 with a 1-second limit. Your first idea is a nested-loop O(n²) scan. Read the constraint — what does it tell you before you write any code?
To detect a duplicate you can use a nested loop (O(n²) time, O(1) space) or a hash set (O(n) time, O(n) space). On a server with memory to spare and users waiting on the response, which do you pick and why?
A function has a single loop that runs n times, and inside it calls binary search (O(log n)) on a sorted array. What is its time complexity?
A junior writes largestOf with `let largest = 0` instead of `let largest = numbers[0]`, tests it on several positive-number lists, and ships it. What is the deeper lesson when it returns 0 for [-5, -3, -1]?
Two sort routines are both 'correct'. Merge sort is O(n log n) time / O(n) space; bubble sort is O(n²) time / O(1) space. For sorting 1,000,000 records on a normal machine, what is the right read?
The through-line of the unit is one habit: before you run anything, estimate the cost. Count steps, keep only the dominant term, name the Big-O class, weigh time against space for your real constraint, and let the input bound tell you which class is even allowed. And never confuse cost with correctness — Big-O measures how fast, a loop invariant proves whether it is right at all.