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:

  1. Traveler 1 misplaces their boarding pass and sits in one of the n seats chosen uniformly at random (each seat has probability 1 / n).
  2. Each remaining traveler k from 2 through n checks seat k upon entering:
    • If seat k is unoccupied, traveler k sits in seat k.
    • If seat k has already been taken by someone earlier, traveler k picks uniformly at random among all currently unoccupied seats and sits there.

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 within 10^-6 relative/absolute tolerance are accepted).

Step-by-step walkthrough

  1. Restate the problem and spot the base case

    An aircraft cabin has n seats labeled 1 through n, and traveler i holds an assignment for seat i.

    • Traveler 1 disregards their boarding pass and picks one of the n seats uniformly at random (meaning every seat has the exact same 1 / n chance of being selected).
    • Travelers 2 through n board in numerical order: if seat k is open, traveler k sits in seat k; if seat k was already taken, traveler k chooses 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 (traveler n) sits in seat n.

    Check the smallest cabin first (Example 1) so we do not miss an edge case later: - When n = 1, traveler 1 is the final traveler, and seat 1 is the only seat in the cabin. They sit in seat 1 with probability 1.0.

  2. Trace small cabins by hand to see the pattern

    Before jumping to n = 50 or larger, work out n = 2 and n = 4 (Example 2) by following every possible branch:

    • n = 2: Traveler 1 picks seat 1 (1/2 chance -> traveler 2 gets seat 2) or seat 2 (1/2 chance -> traveler 2 must sit in seat 1). Win probability: 1/2.
    • n = 4 (Example 2): Traveler 1 picks seat 1, 2, 3, or 4, each with probability 1/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/2
    

    Notice that both n = 2 and n = 4 simplify to 1/2. Could we write a recursive brute-force search to sum all branches for n = 50? No: each extra traveler doubles the number of possible boarding histories (2^(n - 1) total histories, or 2^49 for 50 seats). We need to see why the answer keeps coming out to 1/2.

  3. 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:

    1. At most one future seat is ever occupied at once. Before traveler k boards, k - 1 people have sat down, and seats 2, 3, ..., k - 1 (k - 2 seats) 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 from k through n is open, so travelers k, k + 1, ..., n all sit calmly in their own seats.
      • If seat 1 is still open, that single extra occupied seat is either seat k (so traveler k is displaced right now, while k + 1 .. n are completely open) or some seat j > k (so traveler k sits in seat k and passes the displacement forward to traveler j).
    2. When traveler n finally boards, the single remaining open seat MUST be seat 1 or seat n. Every middle seat k (2 <= k <= n - 1) was either already taken before traveler k arrived, or taken by traveler k themselves.
  4. Key insight 2: symmetry between seat 1 and seat n

    Because only seat 1 and seat n can decide traveler n's outcome:

    • The first random pick that lands on seat 1 ends all displacement immediately — every remaining traveler (including traveler n) gets their own seat.
    • The first random pick that lands on seat n immediately claims traveler n's seat.
    • Any random pick that lands on a middle seat k settles nothing; it simply hands the next random pick to traveler k.

    Now look at any traveler making a random pick while the outcome is still undecided (meaning both seat 1 and seat n are still open). That traveler chooses uniformly at random among all open seats. Because seat 1 and seat n are both in that open pool, the pick is equally likely to hit seat 1 as it is to hit seat n!

    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 1 is claimed before seat n with probability 1/2 = 0.5 for every n >= 2.

  5. 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 with m seats (m >= 2). Conditioning on Traveler 1's m equally likely choices:

    • Seat 1 (1 choice): nobody is displaced, so traveler m wins with probability 1.
    • Seat m (1 choice): traveler m's seat is gone, so traveler m wins with probability 0.
    • Seat k for 2 <= k <= m - 1 (m - 2 choices): travelers 2 .. k - 1 sit in their own seats. Then traveler k faces the remaining m - k + 1 open seats {1, k + 1, ..., m} and chooses uniformly at random — where picking seat 1 acts just like picking their own seat because it stops all future displacement. That subproblem has the exact same structure as a cabin of size s = m - k + 1 (ranging from 2 to m - 1), so traveler m wins with probability P(s).

    Averaging over all m equally likely initial choices gives:

    P(1) = 1
    P(m) = (1 + P(2) + P(3) + ... + P(m - 1)) / m    for m >= 2
    

    We 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 for m): - Base case m = 2: P(2) = 1 / 2. - Inductive step: if P(2) = P(3) = ... = P(m - 1) = 1/2, there are m - 2 terms equal to 1/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 Fraction type 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
    
  6. Write the O(1) closed-form function

    For the judged function probability_last_passenger_own_seat(n), we only need the O(1) closed form: validate n >= 1, return 1.0 when n == 1, and return 0.5 for all n >= 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.5
    
  7. Complete solution

    Putting the O(1) closed-form solution and the O(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_prob
    

    For n = 1 the answer is 1.0, and for every cabin with n >= 2 seats (such as 4, 6, or 50), the probability that traveler n gets seat n is 1/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) for probability_last_passenger_own_seat, because we only check n < 1 and n == 1 and return a constant float without iterating over n. (The optional probability_by_recurrence verification helper runs in O(n) time because it loops once from 2 to n, updating a running sum in constant time per step since every exact fraction simplifies to 1/2.)
  • Space: O(1) auxiliary memory, because no lists or recursion frames are allocated — even the recurrence helper keeps only two scalar Fraction variables (running_win_sum and current_prob).

Edge cases

  • n = 1 (single-seat cabin, Example 1): Traveler 1 is the final traveler, and seat 1 is the only seat available, so the probability is 1.0, not 0.5.
  • n = 2: Traveler 1 takes seat 1 or seat 2 with probability 1/2 each, matching 0.5 directly without any middle seats.
  • Very large n (such as n = 50 or n = 10^9): Because the symmetry between seat 1 and seat n holds regardless of how many middle seats sit between them, the answer stays 0.5 in O(1) time with zero floating-point drift.
  • n < 1: A cabin with zero or negative travelers has no valid final traveler, so raising ValueError surfaces invalid input immediately.

Common mistakes

  • Guessing (n - 1) / n (e.g., 49/50 for n = 50): This only checks whether Traveler 1 directly claims seat n (1 / n) and overlooks that any displaced middle traveler k can also randomly pick seat n later. In fact, (n - 1) / n is Traveler 2's probability of sitting in seat 2, not Traveler n's.
  • Assuming the final open seat could be a middle seat k: When traveler k (2 <= k <= n - 1) boards, either seat k was already occupied earlier or traveler k sits in it right then — so seat k can never remain empty when traveler n boards.
  • Forgetting the n = 1 base case: Blindly returning 0.5 for every input fails Example 1 (n = 1), where seat 1 and seat n are the exact same seat.
  • Returning a noisy random simulation estimate: A simulation hovers near 0.5 (say 0.503), which fails strict 10^-6 float checks and misses the exact closed-form insight.

Alternative approaches

  • Dynamic programming / recurrence with induction: Compute P(m) = (1 + P(2) + ... + P(m - 1)) / m bottom-up using a running prefix sum in O(n) time, as shown in probability_by_recurrence. This is great for verifying small and medium n in code and proving P(m) = 1/2 algebraically.
  • 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/2 immediately.

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 the n - k + 2 critical seats S = {1, k, k + 1, ..., n}: any random pick landing in {2, ..., k - 1} merely passes the random choice to another traveler boarding before k, whereas the first random pick landing inside S decides traveler k's fate — hitting seat k claims their seat, while hitting seat 1 or any seat > k guarantees nobody else picks randomly before traveler k sits down. Because all n - k + 2 seats in S are unoccupied and equally likely at that moment, traveler k loses with probability 1 / (n - k + 2) and wins with probability (n - k + 1) / (n - k + 2) (giving (n - 1) / n for k = 2 and 1/2 for k = 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, traveler 1 now chooses uniformly among n - 1 seats: picking seat n (1 / (n - 1) chance) causes traveler n to lose immediately, while picking any middle seat k (n - 2 choices) hands a standard subproblem of size n - k + 1 >= 2 (including empty seat 1 and empty seat n) to traveler k, where traveler n still wins with probability 1/2. Multiplying gives ((n - 2) / (n - 1)) * (1/2) = (n - 2) / (2 * (n - 1)), which equals 0 for n = 2 and 24/49 (about 0.4898) for n = 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 process T independent times and compute the sample win fraction for traveler n. Each trial is a Bernoulli coin flip with true mean p = 0.5, so its standard error (the typical random fluctuation of a sample proportion across T trials) is sqrt(p * (1 - p) / T) = 0.5 / sqrt(T). Running T = 10,000 trials shrinks the standard error to 0.005, giving a 99.7% (3-sigma) interval of 0.5 +/- 0.015 — easily distinguishing 0.5 from wrong guesses like (n - 1) / n, while the symmetry proof establishes exact equality.

Follow-up questions

Similar questions

More Schonfeld interview questions

All 2 Schonfeld questions →