You’ve practiced two patterns that replace repeated work with a smarter question:
- Prefix sums store running totals once, so any range total is
prefix[to + 1] - prefix[from]in O(1) time. Paired with aMapof earlier totals, they find stretches with an exact sum in one pass, even when values can be negative. - Binary search keeps only the half of a sorted range that can still hold the answer, for O(log n) time. The same loop finds an exact match, the first position that’s at least some value, or the smallest answer that passes a check.
Things to Remember in an Interview
- Say which ends of a range are inclusive before you write the formula. Most bugs in both patterns are off by one.
- Keep money and other totals in whole units such as cents, and remember that numbers are exact only up to
Number.MAX_SAFE_INTEGER. - Pass a starting value to
reduce(), round the midpoint withMath.floor(), and round whole-unit costs up withMath.ceil(). - Built-in helpers like
indexOf(),includes(), andfilter()scan the whole array. Name their cost when you use them.