Daily iOS
CS fundamentals and algorithms

Prefix sum binary search

You're writing a custom vertical layout (a UICollectionViewLayout subclass) where every cell has a different height. layoutAttributesForElements(in rect:) gets called on every scroll, and iterating 20,000 cells each time stutters. Which data structure and algorithm find the visible cell range in O(log n)?

How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

Build a prefix sum array of heights (cumulative y offsets) in prepare(), then binary search (lower bound) for rect.minY and rect.maxY to find the first and last index.

Share a question