← Questions
Highest safe floor with a monotonic check
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A building has floors 1 to n, and a call can_operate(floor) tells you whether an elevator can safely serve that floor. Some floor T splits them: every floor up to T is safe and every floor above it is not. Find T with O(log n) calls.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
highest_safe_floor(n: int, can_operate: Callable[[int], bool]) -> int—0when no floor is safe (includingn = 0).
Example
n = 10, safe floors 1..6 -> 6 # 4 calls: 5 yes, 8 no, 6 yes, 7 no
n = 10, no floor safe -> 0
n = 10, every floor safe -> 10
n = 1, floor 1 safe -> 1
Constraints
-
0 <= n <= 2 * 10^5(or far larger: the cost is the number of calls). - The answer is monotonic: safe floors never sit above unsafe ones.
Clarifying questions
- Can every floor be safe, or none?
- Is
can_operateexpensive, so the number of calls is what matters? - Is
nknown up front, or could the building be unbounded?
What a strong answer covers
- Binary search for the last
True: keeploas a floor known safe (starting at 0) andhias the highest floor not yet ruled out; testmid = (lo + hi + 1) // 2so the loop always shrinks. - The loop invariant stated out loud, and why the upward rounding prevents an infinite loop.
- About
ceil(log2(n + 1))calls,O(1)space. - Tests:
n = 0,n = 1, all safe, none safe,Tat either end.
Follow-ups
-
nis unknown: grow the range by doubling, then binary search. - Each unsafe test breaks a probe and you have only two (the egg-drop problem): what is the fewest tests in the worst case?
- Return the first unsafe floor instead.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
