Airplane Seat Assignment Probability in C++

Suppose n passengers board an airplane with exactly n seats. If the first passenger has lost the ticket and picks a seat randomly. But after that, the rest of passengers will follow these operations −

  • Take their own seat written in the ticket if it is still available,

  • Pick other seats randomly when they find their seat occupied

So we have to find what is the probability that the n-th person can get his own seat? So if the input is 2, then the output will be 0.5. So the second person has a probability of 0.5 to get the second seat (when first person gets the first seat).

To solve this, we will follow these steps −

  • If n is 1, then return 1, otherwise 0.5

Example (C++)

Let us see the following implementation to get a better understanding −

class Solution {
   double nthPersonGetsNthSeat(int n) {
      if (n == 1) return 1;
      return 0.5;