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:
Return the probability that the nth 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
Let's explore this probability problem. First, we'll consider a naive approach, then proceed to a more optimal solution.
The most straightforward way to think about this might be to simulate the process for each value of n
. However, this is not an efficient approach for larger values of n
because it involves simulating random seat selections multiple times and calculating probabilities.
Upon closer inspection, a pattern emerges that simplifies the problem dramatically.
Consider these cases:
n = 1
, the first person always gets their own seat, so the probability is 1.0
.n = 2
, the first person either picks their own seat (seat 1) with probability 1/2, or the second person's seat (seat 2) with probability 1/2. If the first person picks their own seat, the second person gets their own seat. If the first person picks the second person's seat, the second person does not get their own seat. So the probability is 1/2 or 0.5.n = 3
, the first person can pick seat 1, 2, or 3. If seat 1 is picked, everyone gets their assigned seat. If seat 2 is picked, then person 2 is without a seat and they will pick a seat at random (either seat 1 or 3), therefore there's a 50% chance person 3 will get their seat. If seat 3 is picked, then person 3 will not get their seat. So the probability is 0.5.Generalizing, the critical decision point is the first passenger's choice. They either pick their own seat (1st seat), the last passenger's seat (nth seat), or some other seat in between. If they pick the 1st seat, the nth passenger gets their seat. If they pick the nth seat, the nth passenger does not get their seat. If they pick a seat k
(where 1 < k < n
), then passengers 2
through k-1
will sit in their assigned seat. Then passenger k
is in the same position as passenger 1, but with a smaller set of seats (1
, k+1
, ... , n
).
Surprisingly, for n > 1
, the probability is always 0.5.
def nth_person_gets_nth_seat(n: int) -> float:
if n == 1:
return 1.0
else:
return 0.5
n = 1
: The first person will always get their own seat, so the probability is 1.0.n = 2
: The first person has a 50% chance of picking the second person's seat, so the probability is 0.5.