Daily iOS
CS fundamentals and algorithms

Anchored two-way lookup

Chat messages sit in an array sorted by id ascending. When the user taps a push notification to jump to a specific message, how would you write a function that returns that id plus up to 5 messages on each side, at most 11 in total, in ascending order?

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

Binary search finds the id's position (or its insertion point) in O(log n), then slice 5 on each side. The result is a subrange of the original array, so it's already ascending.

Share a question