LeetCode 1227: Airplane Seat Assignment Probability Solution

Master LeetCode problem 1227 (Airplane Seat Assignment Probability), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1227. Airplane Seat Assignment Probability

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. Let dp[i] represent the probability that the i-th person gets their own seat. We can calculate the probability for each person by considering the scenarios where the first person takes either their own seat or someone else's seat.

  • If the first person takes their own seat (with probability 1/n), then the n-th person will definitely get their own seat.
  • If the first person takes another seat (with probability 1/n), then the n-th person has a probability of dp[n-1] of getting their own seat.

Therefore, the general formula for calculating dp[i] is: dp[i] = 1/i + (i-1)/i * dp[i-1].

Solution Code

class Solution {
    public double nthPersonGetsNthSeat(int n) {
        if (n == 1) {
            return 1.0;
        }
        
        double[] dp = new double[n+1];
        dp[1] = 1.0;
        
        for (int i = 2; i <= n; i++) {
            dp[i] = 1.0 / i + (i - 1.0) / i * dp[i - 1];
        }
        
        return dp[n];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1227 (Airplane Seat Assignment Probability)?

This page provides optimized solutions for LeetCode problem 1227 (Airplane Seat Assignment Probability) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1227 (Airplane Seat Assignment Probability)?

The time complexity for LeetCode 1227 (Airplane Seat Assignment Probability) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1227 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1227 in Java, C++, or Python.

Back to LeetCode Solutions