Airplane Seat Assignment Probability Problem
Description
LeetCode Problem 1227.
n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
- Take their own seat if it is still available, and
- Pick other seats randomly when they find their seat occupied
Return the probability that the n^th person gets his own seat.
Example 1:
Input: n = 1
Output: 1.00000
Explanation: The first person can only get the first seat.
Example 2:
Input: n = 2
Output: 0.50000
Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
Constraints:
1 <= n <= 10^5
Solution
Approach: Math
With one passenger the answer is clearly 1. For n >= 2 it is always 0.5, and here is why.
Follow the "displaced" passenger: first passenger 1 picks a seat at random, and whenever someone finds their seat taken, they pick a random free seat. The process is decided the moment someone picks seat 1 or seat n:
- If seat 1 is picked, everyone after that finds their own seat free, including passenger
n. - If seat
nis picked, passengernwill not get it.
Any other pick only moves the problem to another passenger (the owner of the seat just taken). And at every random pick, seat 1 and seat n are both still free and equally likely to be chosen. So the two endings are equally likely, and the probability is 1/2.
The same result comes out of the recurrence for f(n): passenger 1 picks seat 1 (probability 1/n, success), seat n (probability 1/n, failure), or seat i in between, which leaves a smaller copy of the same problem. Subtracting the equations for n and n - 1 gives f(n) = f(n - 1) for n >= 3, and f(2) = 0.5.
Complexity: O(1) time and space.
class Solution:
def nthPersonGetsNthSeat(self, n: int) -> float:
# With one seat the only passenger gets it; otherwise the answer is always one half.
return 1.0 if n == 1 else 0.5