progress

~/problems / Binary search / Sorted containers (bisect)

Nearest free parking spot

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 street has spots 0 to n - 1. Each driver asks for a spot near a number and gets the closest free spot.

Implement class Street:

  • Street(n): all spots free (n <= 200,000).
  • park(want) -> int: take and return the free spot closest to want, the lower one on a tie, or -1 if full.
  • leave(spot): free an occupied spot.
st = Street(5)
st.park(2)    # 2
st.park(2)    # 1   (1 and 3 are both one away: lower wins)
st.park(2)    # 3
st.park(0)    # 0
st.park(1)    # 4   (the only spot left)
st.park(3)    # -1  (full)
st.leave(1)
st.park(4)    # 1

⭐ Bonus: a speed test (100,000 cars at one end) earns a star at O(log n) comparisons per call.

Show hint

keep the free spots in a sorted list. With i = bisect_left(free, want), the only candidates are free[i] and free[i - 1].

Topic: Sorted containers (bisect). Ordered-set operations in Python: bisect.insort, floor/ceiling lookups.

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