Algorithms from zero
Arrays and strings: multiple-choice review
Six questions that cut across the whole unit. Each one is a choice you make at a whiteboard or in a code review — not a definition to recite, but the right pattern to reach for and the precondition it quietly depends on.
Confirm you can connect the array’s contiguity cost model to the patterns built on it — two pointers, sliding window, prefix sums, in-place writes, and strings-as-arrays — and recognise the precondition each one silently assumes.
A profiler shows a hot loop that inserts at index 0 of a 1M-element array on every request. Why is this the bottleneck, and what is the right fix?
You apply the opposite-ends two pointers two-sum to find a pair summing to a target, but it misses pairs you can spot by hand. What is the most likely cause?
For 'smallest subarray with sum ≥ target' on positive integers, the variable-size sliding window runs in O(n) even though it has a nested while loop. Why is it not O(n²)?
A service answers thousands of range-sum queries over a fixed-length log. Each query currently traverses the range. When is precomputing a prefix sum the right call, and what does it cost?
A reviewer flags that your in-place 'remove all zeros' using a write pointer mutates the caller's array, breaking a later read of the original. What is the correct framing of the tradeoff?
A function builds a large CSV by doing result += line inside a loop over n rows and is unexpectedly slow at scale. What is happening and what is the fix?
The through-line of the unit is one cost model and the patterns that exploit it. Contiguity gives O(1) indexing but O(n) shifts, so front/middle insertion is the trap and append is cheap. Two pointers turn nested pair-scans into one pass — but opposite-ends two-sum needs sorted input. Sliding window is O(n) because the pointers only move forward. Prefix sums trade O(n) space for O(1) static range queries. In-place writes buy O(1) space at the cost of the original. And strings are arrays with one sting: immutability makes loop concatenation O(n²) — collect and join instead.