Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Prefix Sums and Binary Search (Summary)

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 a Map of 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 with Math.floor(), and round whole-unit costs up with Math.ceil().
  • Built-in helpers like indexOf(), includes(), and filter() scan the whole array. Name their cost when you use them.

Keep Practicing

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.