Probability the Final Passenger Gets Their Seat
Medium · Coding & Algorithms · Data Scientist · Online Assessment
Problem Statement
An aircraft cabin has n seats labeled 1 through n, and n travelers line up to board in numerical order 1, 2, ..., n. Traveler i holds an assigned boarding pass for seat i.
Boarding follows two rules:
- Traveler
1misplaces their boarding pass and sits in one of thenseats chosen uniformly at random (each seat has probability1 / n). - Each remaining traveler
kfrom2throughnchecks seatkupon entering:- If seat
kis unoccupied, travelerksits in seatk. - If seat
khas already been taken by someone earlier, travelerkpicks uniformly at random among all currently unoccupied seats and sits there.
- If seat
Implement probability_last_passenger_own_seat(n) to return, as a floating-point number, the exact probability that the final traveler (traveler n) sits in their own assigned seat (seat n).
Examples
Example 1
Input:
n = 1
Output:
1.0
Explanation: With only a single seat in the cabin, traveler 1 is also the final traveler and takes seat 1 with certainty.
Example 2
Input:
n = 4
Output:
0.5
Explanation: Traveler 1 selects seat 1, 2, 3, or 4 with probability 1/4 each:
- Choosing seat 1 (1/4) leaves seats 2, 3, 4 undisturbed, so traveler 4 sits in seat 4.
- Choosing seat 4 (1/4) immediately takes traveler 4's seat, so traveler 4 cannot sit there.
- Choosing seat 2 (1/4) or seat 3 (1/4) displaces that middle traveler, whose subsequent random choice (and any chain of middle choices) treats empty seat 1 and empty seat 4 symmetrically, succeeding half the time ((1/4) * (1/2) + (1/4) * (1/2) = 1/4).
Summing all winning branches gives 1/4 + 1/4 = 0.5.
Example 3
Input:
n = 6
Output:
0.5
Explanation: Before traveler 6 boards, seats 2 through 5 are guaranteed to be filled, leaving either seat 1 or seat 6 open. Every random choice made while both seats remain open has an equal chance of landing on seat 1 (locking in seat 6 for traveler 6) or seat 6 (taking traveler 6's seat), yielding 0.5.
Example 4
Input:
n = 50
Output:
0.5
Explanation: Regardless of how many middle seats lie between seat 1 and seat 50, the exact symmetry between seat 1 being claimed first versus seat 50 being claimed first gives probability 0.5.
Constraints
1 <= n <= 10^9- Return the exact probability as a
float(answers within10^-6relative/absolute tolerance are accepted).
Step-by-step walkthrough
Restate the problem and spot the base case
An aircraft cabin has
nseats labeled1throughn, and traveleriholds an assignment for seati.- Traveler
1disregards their boarding pass and picks one of thenseats uniformly at random (meaning every seat has the exact same1 / nchance of being selected). - Travelers
2throughnboard in numerical order: if seatkis open, travelerksits in seatk; if seatkwas already taken, travelerkchooses uniformly at random from whichever seats remain open.
We want
probability_last_passenger_own_seat(n)to return the exact probability that the final traveler (travelern) sits in seatn.Check the smallest cabin first (Example 1) so we do not miss an edge case later: - When
n = 1, traveler1is the final traveler, and seat1is the only seat in the cabin. They sit in seat1with probability1.0.- Traveler
Trace small cabins by hand to see the pattern
Before jumping to
n = 50or larger, work outn = 2andn = 4(Example 2) by following every possible branch:n = 2: Traveler1picks seat1(1/2chance -> traveler2gets seat2) or seat2(1/2chance -> traveler2must sit in seat1). Win probability:1/2.n = 4(Example 2): Traveler1picks seat1,2,3, or4, each with probability1/4:
Traveler 1's random pick (each 1/4): +-- Seat 1 (1/4) --> T2->2, T3->3, T4->4 [WIN: 1/4] +-- Seat 2 (1/4) --> T2 displaced! Open seats: {1, 3, 4} (each 1/3) | +-- T2 picks Seat 1 (1/12) --> T3->3, T4->4 [WIN: 1/12] | +-- T2 picks Seat 3 (1/12) --> T3 displaced! Open: {1, 4} | | +-- T3 picks Seat 1 (1/24) --> T4->4 [WIN: 1/24] | | +-- T3 picks Seat 4 (1/24) --> T4 forced into Seat 1 [LOSE: 1/24] | +-- T2 picks Seat 4 (1/12) --> T3->3, T4 forced into Seat 1 [LOSE: 1/12] +-- Seat 3 (1/4) --> T2->2; T3 displaced! Open seats: {1, 4} | +-- T3 picks Seat 1 (1/8) --> T4->4 [WIN: 1/8] | +-- T3 picks Seat 4 (1/8) --> T4 forced into Seat 1 [LOSE: 1/8] +-- Seat 4 (1/4) --> T2->2, T3->3, T4 forced into Seat 1 [LOSE: 1/4] Total win probability = 1/4 + 1/12 + 1/24 + 1/8 = (6 + 2 + 1 + 3) / 24 = 12 / 24 = 1/2Notice that both
n = 2andn = 4simplify to1/2. Could we write a recursive brute-force search to sum all branches forn = 50? No: each extra traveler doubles the number of possible boarding histories (2^(n - 1)total histories, or2^49for50seats). We need to see why the answer keeps coming out to1/2.Key insight 1: only one displaced seat is loose at a time
Watch what happens to the occupied seats as travelers board a
6-seat cabin (Example 3):Suppose Traveler 1 picks seat 4: After T1: occupied = {4}, open = {1, 2, 3, 5, 6} T2 arrives: seat 2 is open! T3 arrives: seat 3 is open! After T3: occupied = {2, 3, 4}, open = {1, 5, 6} T4 arrives: seat 4 is taken! T4 now chooses randomly from {1, 5, 6}.Two crucial invariants hold for every cabin of size
n >= 2:- At most one future seat is ever occupied at once. Before traveler
kboards,k - 1people have sat down, and seats2, 3, ..., k - 1(k - 2seats) are all guaranteed to be occupied because each of those travelers either sat in their own seat or found it already occupied. That leaves only one extra occupied seat!- If that one extra occupied seat is seat
1, then every seat fromkthroughnis open, so travelersk, k + 1, ..., nall sit calmly in their own seats. - If seat
1is still open, that single extra occupied seat is either seatk(so travelerkis displaced right now, whilek + 1 .. nare completely open) or some seatj > k(so travelerksits in seatkand passes the displacement forward to travelerj).
- If that one extra occupied seat is seat
- When traveler
nfinally boards, the single remaining open seat MUST be seat1or seatn. Every middle seatk(2 <= k <= n - 1) was either already taken before travelerkarrived, or taken by travelerkthemselves.
- At most one future seat is ever occupied at once. Before traveler
Key insight 2: symmetry between seat 1 and seat n
Because only seat
1and seatncan decide travelern's outcome:- The first random pick that lands on seat
1ends all displacement immediately — every remaining traveler (including travelern) gets their own seat. - The first random pick that lands on seat
nimmediately claims travelern's seat. - Any random pick that lands on a middle seat
ksettles nothing; it simply hands the next random pick to travelerk.
Now look at any traveler making a random pick while the outcome is still undecided (meaning both seat
1and seatnare still open). That traveler chooses uniformly at random among all open seats. Because seat1and seatnare both in that open pool, the pick is equally likely to hit seat1as it is to hit seatn!Open pool at any undecided random pick: [ Seat 1 , ... middle seats ... , Seat n ] ^ ^ equal chance equal chance (locks in a WIN) (locks in a LOSS)By exact symmetry, seat
1is claimed before seatnwith probability1/2 = 0.5for everyn >= 2.- The first random pick that lands on seat
Confirm with a recurrence relation
In an interview, backing up a symmetry argument with an algebraic recurrence makes your answer airtight. Let
P(m)be the probability that the final traveler gets their own seat in a cabin withmseats (m >= 2). Conditioning on Traveler1'smequally likely choices:- Seat
1(1choice): nobody is displaced, so travelermwins with probability1. - Seat
m(1choice): travelerm's seat is gone, so travelermwins with probability0. - Seat
kfor2 <= k <= m - 1(m - 2choices): travelers2 .. k - 1sit in their own seats. Then travelerkfaces the remainingm - k + 1open seats{1, k + 1, ..., m}and chooses uniformly at random — where picking seat1acts just like picking their own seat because it stops all future displacement. That subproblem has the exact same structure as a cabin of sizes = m - k + 1(ranging from2tom - 1), so travelermwins with probabilityP(s).
Averaging over all
mequally likely initial choices gives:P(1) = 1 P(m) = (1 + P(2) + P(3) + ... + P(m - 1)) / m for m >= 2We can check this with mathematical induction (proving a base case first, then showing that if the rule holds up to
m - 1, it must also hold form): - Base casem = 2:P(2) = 1 / 2. - Inductive step: ifP(2) = P(3) = ... = P(m - 1) = 1/2, there arem - 2terms equal to1/2, so:P(m) = (1 + (m - 2) * (1/2)) / m = (m / 2) / m = 1/2.We can also code this recurrence using Python's exact
Fractiontype as a sanity-check helper:from fractions import Fraction def probability_by_recurrence(n: int) -> Fraction: # Helper that verifies the closed form using exact rational arithmetic # via P(m) = (1 + P(2) + P(3) + ... + P(m - 1)) / m for m >= 2. if n < 1: raise ValueError("there must be at least one passenger") if n == 1: return Fraction(1) # running_win_sum: exact Fraction storing P(2) + P(3) + ... + P(m - 1) running_win_sum = Fraction(0) current_prob = Fraction(0) # Build P(2), P(3), ..., P(n) bottom-up in O(n) steps: # - Passenger 1 picks seat 1 (1 case): win probability is 1. # - Passenger 1 picks seat m (1 case): win probability is 0. # - Passenger 1 picks seat k in 2..m-1: reduces to a plane of size m - k + 1. for m in range(2, n + 1): current_prob = (1 + running_win_sum) / m running_win_sum += current_prob return current_prob- Seat
Write the O(1) closed-form function
For the judged function
probability_last_passenger_own_seat(n), we only need theO(1)closed form: validaten >= 1, return1.0whenn == 1, and return0.5for alln >= 2.def probability_last_passenger_own_seat(n: int) -> float: # Reject invalid plane sizes with zero or negative seats. if n < 1: raise ValueError("there must be at least one passenger") # Base case: with 1 seat, passenger 1 is also the last passenger, # and seat 1 is the only seat available on the plane. if n == 1: return 1.0 # For n >= 2, seats 2..n-1 are always filled before passenger n boards, # leaving only seat 1 or seat n. Every random choice before either is # taken is equally likely to hit seat 1 (passenger n wins) or seat n # (passenger n loses), so the exact probability is always 1/2. return 0.5Complete solution
Putting the
O(1)closed-form solution and theO(n)exact recurrence verifier together:from typing import Any, Dict, List, Optional, Set, Tuple from fractions import Fraction def probability_last_passenger_own_seat(n: int) -> float: # Reject invalid plane sizes with zero or negative seats. if n < 1: raise ValueError("there must be at least one passenger") # Base case: with 1 seat, passenger 1 is also the last passenger, # and seat 1 is the only seat available on the plane. if n == 1: return 1.0 # For n >= 2, seats 2..n-1 are always filled before passenger n boards, # leaving only seat 1 or seat n. Every random choice before either is # taken is equally likely to hit seat 1 (passenger n wins) or seat n # (passenger n loses), so the exact probability is always 1/2. return 0.5 def probability_by_recurrence(n: int) -> Fraction: # Helper that verifies the closed form using exact rational arithmetic # via P(m) = (1 + P(2) + P(3) + ... + P(m - 1)) / m for m >= 2. if n < 1: raise ValueError("there must be at least one passenger") if n == 1: return Fraction(1) # running_win_sum: exact Fraction storing P(2) + P(3) + ... + P(m - 1) running_win_sum = Fraction(0) current_prob = Fraction(0) # Build P(2), P(3), ..., P(n) bottom-up in O(n) steps: # - Passenger 1 picks seat 1 (1 case): win probability is 1. # - Passenger 1 picks seat m (1 case): win probability is 0. # - Passenger 1 picks seat k in 2..m-1: reduces to a plane of size m - k + 1. for m in range(2, n + 1): current_prob = (1 + running_win_sum) / m running_win_sum += current_prob return current_probFor
n = 1the answer is1.0, and for every cabin withn >= 2seats (such as4,6, or50), the probability that travelerngets seatnis1/2 = 0.5.✅ Submit now — all tests should pass.
Intuition & how it works
Think of the boarding sequence as passing around a single "hot potato" — at any point in time, at most one displaced seat assignment is loose in the cabin. Traveler 1 starts with the hot potato by picking a seat uniformly at random (meaning every available seat has the exact same probability of being chosen): if they pick seat 1, nobody is ever displaced; if they pick seat n, the final traveler's seat is immediately gone; and if they pick some middle seat k, travelers 2 through k - 1 sit normally in their own seats until traveler k arrives, sees seat k taken, and picks up the hot potato to make the next uniform random choice. Notice that every middle seat k (2 <= k <= n - 1) is guaranteed to be occupied by the time traveler k finishes boarding, so only seat 1 and seat n can decide the outcome — and whichever of those two seats gets picked first settles everything!
A naive brute-force approach tries to trace every possible chain of displaced travelers and sum the branch probabilities. Because each extra seat doubles the number of possible boarding histories (2^(n - 1) total paths, which is 2^49 even for n = 50), exhaustive enumeration blows up exponentially and cannot finish. Running a Monte Carlo simulation (estimating a probability by repeating random trials in code and counting wins) is fast for moderate n, yet it only returns a noisy approximation like 0.497 rather than proving the exact answer or handling n = 10^9 in constant time.
Walk through Example 2 (n = 4 seats) to see the symmetry in action:
1. Traveler 1 picks seat 1 (1/4 chance): travelers 2, 3, 4 take seats 2, 3, 4 -> traveler 4 wins (1/4).
2. Traveler 1 picks seat 4 (1/4 chance): travelers 2 and 3 take seats 2 and 3, forcing traveler 4 into seat 1 -> traveler 4 loses (1/4).
3. Traveler 1 picks seat 3 (1/4 chance): traveler 2 takes seat 2, and displaced traveler 3 chooses uniformly from {1, 4} -> picking seat 1 (1/8) wins, picking seat 4 (1/8) loses.
4. Traveler 1 picks seat 2 (1/4 chance): displaced traveler 2 chooses from {1, 3, 4}, winning directly on seat 1 (1/12), losing on seat 4 (1/12), or passing to traveler 3 on seat 3 (1/24 win, 1/24 loss).
Adding all winning paths gives 1/4 + 1/8 + 1/12 + 1/24 = 12/24 = 0.5. Every undecided random pick sees seat 1 and seat n in the same open pool with identical odds, so for any n >= 2, the answer is 0.5 (and 1.0 when n = 1).
Complexity
- Time:
O(1)forprobability_last_passenger_own_seat, because we only checkn < 1andn == 1and return a constant float without iterating overn. (The optionalprobability_by_recurrenceverification helper runs inO(n)time because it loops once from2ton, updating a running sum in constant time per step since every exact fraction simplifies to1/2.) - Space:
O(1)auxiliary memory, because no lists or recursion frames are allocated — even the recurrence helper keeps only two scalarFractionvariables (running_win_sumandcurrent_prob).
Edge cases
n = 1(single-seat cabin, Example 1): Traveler1is the final traveler, and seat1is the only seat available, so the probability is1.0, not0.5.n = 2: Traveler1takes seat1or seat2with probability1/2each, matching0.5directly without any middle seats.- Very large
n(such asn = 50orn = 10^9): Because the symmetry between seat1and seatnholds regardless of how many middle seats sit between them, the answer stays0.5inO(1)time with zero floating-point drift. n < 1: A cabin with zero or negative travelers has no valid final traveler, so raisingValueErrorsurfaces invalid input immediately.
Common mistakes
- Guessing
(n - 1) / n(e.g.,49/50forn = 50): This only checks whether Traveler1directly claims seatn(1 / n) and overlooks that any displaced middle travelerkcan also randomly pick seatnlater. In fact,(n - 1) / nis Traveler2's probability of sitting in seat2, not Travelern's. - Assuming the final open seat could be a middle seat
k: When travelerk(2 <= k <= n - 1) boards, either seatkwas already occupied earlier or travelerksits in it right then — so seatkcan never remain empty when travelernboards. - Forgetting the
n = 1base case: Blindly returning0.5for every input fails Example 1 (n = 1), where seat1and seatnare the exact same seat. - Returning a noisy random simulation estimate: A simulation hovers near
0.5(say0.503), which fails strict10^-6float checks and misses the exact closed-form insight.
Alternative approaches
- Dynamic programming / recurrence with induction: Compute
P(m) = (1 + P(2) + ... + P(m - 1)) / mbottom-up using a running prefix sum inO(n)time, as shown inprobability_by_recurrence. This is great for verifying small and mediumnin code and provingP(m) = 1/2algebraically. - Seat-eviction bijection: Imagine an equivalent rule where each arriving traveler takes their own seat by politely asking any wrong occupant to stand up and pick a new random empty seat; tracking who holds the displaced ticket at the end pairs winning histories 1-to-1 with losing histories, yielding
1/2immediately.
Follow-up questions
- What is the probability that an arbitrary intermediate traveler k (where 2 <= k <= n) sits in their own assigned seat? It is
(n - k + 1) / (n - k + 2). Focus on then - k + 2critical seatsS = {1, k, k + 1, ..., n}: any random pick landing in{2, ..., k - 1}merely passes the random choice to another traveler boarding beforek, whereas the first random pick landing insideSdecides travelerk's fate — hitting seatkclaims their seat, while hitting seat1or any seat> kguarantees nobody else picks randomly before travelerksits down. Because alln - k + 2seats inSare unoccupied and equally likely at that moment, travelerkloses with probability1 / (n - k + 2)and wins with probability(n - k + 1) / (n - k + 2)(giving(n - 1) / nfork = 2and1/2fork = n). - How does the final traveler's probability change if traveler 1 is forbidden from choosing seat 1 and picks uniformly from seats 2 through n? For
n >= 2, traveler1now chooses uniformly amongn - 1seats: picking seatn(1 / (n - 1)chance) causes travelernto lose immediately, while picking any middle seatk(n - 2choices) hands a standard subproblem of sizen - k + 1 >= 2(including empty seat1and empty seatn) to travelerk, where travelernstill wins with probability1/2. Multiplying gives((n - 2) / (n - 1)) * (1/2) = (n - 2) / (2 * (n - 1)), which equals0forn = 2and24/49(about0.4898) forn = 50. - How would you validate your theoretical result empirically via Monte Carlo simulation, and how many trials are needed for tight confidence? Simulate the
n-traveler boarding processTindependent times and compute the sample win fraction for travelern. Each trial is a Bernoulli coin flip with true meanp = 0.5, so its standard error (the typical random fluctuation of a sample proportion acrossTtrials) issqrt(p * (1 - p) / T) = 0.5 / sqrt(T). RunningT = 10,000trials shrinks the standard error to0.005, giving a 99.7% (3-sigma) interval of0.5 +/- 0.015— easily distinguishing0.5from wrong guesses like(n - 1) / n, while the symmetry proof establishes exact equality.
Follow-up questions
- What is the probability that an arbitrary intermediate traveler k (where 2 <= k <= n) sits in their own assigned seat?
- How does the final traveler's probability change if traveler 1 is forbidden from choosing seat 1 and picks uniformly from seats 2 through n?
- How would you validate your theoretical result empirically via Monte Carlo simulation, and how many trials are needed for tight confidence?
Similar questions
- Minimum Threshold for 5-and-21 Integer Combinations
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One