progress

~/problems / Binary search / Binary search

Log entries in a time range

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A server's request times (in seconds) are stored sorted in times; several can share a second. A dashboard keeps asking how many requests arrived between seconds a and b, inclusive.

Write count_in_range(times: list[int], queries: list[list[int]]) -> list[int] answering each [a, b].

times = [3, 5, 5, 5, 8, 12, 12, 20]
count_in_range(times, [[5, 5], [4, 12], [0, 2], [13, 19], [0, 100], [12, 20]])
# [3, 6, 0, 0, 8, 3]
  • Up to 2 * 10^5 times and queries, values in [0, 10^9]. Don't use bisect: write the search loop.
  • ⭐ Bonus: a speed test at full size earns a star in O((n + q) log n).
Show hint

the matches form one contiguous stretch. Find its start and its end, each with its own search.

Topic: Binary search. lo/hi invariants, lower vs upper bound, rotated arrays, bisect.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc