1227. Airplane Seat Assignment Probability

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 passengers will:

  • Take their own seat if it is still available, 
  • Pick other seats randomly when they find their seat occupied 

What is the probability that the n-th person can get 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

Rust Solution

struct Solution;

impl Solution {
    fn nth_person_gets_nth_seat(n: i32) -> f64 {
        if n > 1 {
            0.5
        } else {
            1.0
        }
    }
}

#[test]
fn test() {
    use assert_approx_eq::assert_approx_eq;
    let n = 1;
    let res = 1.0;
    assert_approx_eq!(Solution::nth_person_gets_nth_seat(n), res);
    let n = 2;
    let res = 0.5;
    assert_approx_eq!(Solution::nth_person_gets_nth_seat(n), res);
}

Having problems with this solution? Click here to submit an issue on github.