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 <= 105
This problem asks for the probability that the nth passenger gets their own seat, given that the first passenger picks a seat randomly, and subsequent passengers take their own seat if available, otherwise picking a random available seat.
Instead of simulating the process, a mathematical approach is significantly more efficient. Let's analyze the probabilities:
Base Cases:
n = 1
, the probability is 1.0 (only one seat, one passenger).n = 2
, the probability is 0.5. If passenger 1 takes seat 1, passenger 2 gets seat 2. If passenger 1 takes seat 2, passenger 2 gets seat 1.Recursive Reasoning (Incorrect but Illustrative): A naive attempt might involve recursion. Consider the seat the first passenger chooses:
The Key Insight: The key is recognizing a pattern. For n≥2, the probability the nth passenger gets their seat is always 0.5. This isn't immediately obvious, but it holds true.
The algorithm is extremely simple based on the insight above:
n
is 1, return 1.0.The code implementations across various languages are nearly identical, reflecting the simplicity of the algorithm:
Python:
class Solution:
def nthPersonGetsNthSeat(self, n: int) -> float:
return 1 if n == 1 else 0.5
Java:
class Solution {
public double nthPersonGetsNthSeat(int n) {
return n == 1 ? 1 : 0.5;
}
}
C++:
class Solution {
public:
double nthPersonGetsNthSeat(int n) {
return n == 1 ? 1.0 : 0.5;
}
};
Go:
func nthPersonGetsNthSeat(n int) float64 {
if n == 1 {
return 1
}
return 0.5
}
TypeScript:
function nthPersonGetsNthSeat(n: number): number {
return n === 1 ? 1 : 0.5;
}
Rust:
impl Solution {
pub fn nth_person_gets_nth_seat(n: i32) -> f64 {
match n {
1 => 1.0,
_ => 0.5,
}
}
}
All these implementations achieve the same O(1) time and space complexity. The elegance of this solution lies in its mathematical insight, making it far superior to any simulation-based approach in terms of efficiency.