Skip to the code
+25 XP

#180 Search an Endless Feed

medium

An infinite-scroll feed loads posts sorted by ID, ascending, with no repeats. The client can read feed[i] for any i, but it does not know how many posts exist: reading past the end gives undefined. Pretend you can't use feed.length.

Write searchFeed(feed, target) that returns the index of the post with ID target, or -1 if there is none. Find a range by doubling an index, then binary search inside it.

Example 1

Input: feed = [2,4,7,9,13,18,21,30,35,41,50], target = 30
Output: 7

Probe 1, 2, 4, 8: feed[8] is 35, past 30. Binary search 4 to 8 finds 30 at index 7.

Example 2

Input: feed = [2,4,7,9,13], target = 8
Output: -1

8 is not in the feed.

Constraints

  • 0 <= number of posts <= 100000
  • IDs are sorted ascending with no repeats.
  • 1 <= feed[i], target <= 10^9
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).