Airplane Seat Assignment Probability Solution in Python

Links to Other Languages
C++ Solution
Java Solution

Problem Description

Welcome to the world of airplane seat assignments, where the only thing more chaotic than boarding a flight is figuring out who gets to sit where! Imagine this: you’re on a flight with n seats, and the first person to board the plane decides to sit wherever they please. Spoiler alert: they don’t choose their assigned seat. Now, the rest of the passengers follow suit, either sitting in their assigned seat if it’s available or randomly choosing another seat.

So, what’s the probability that the n-th person ends up in their assigned seat? Well, if you thought this was a straightforward question, think again! It turns out that the answer is as simple as 1 for one passenger and 0.5 for more than one. Yes, you read that right!

Code Solution

class Solution:
    def nthPersonGetsNthSeat(self, n: int) -> float:
        return 1 if n == 1 else 0.5

Approach

The approach here is as straightforward as it gets. If there’s only one passenger, they obviously sit in their assigned seat, giving a probability of 1. However, if there are more passengers, the first passenger’s random choice leads to a 50% chance that the last passenger will find their seat available. It’s a classic case of “you snooze, you lose”!

Time and Space Complexity

  • Time Complexity: O(1) – The solution runs in constant time since it only checks the value of n.
  • Space Complexity: O(1) – No additional space is used, making it very efficient.

Real-World Example

Picture this: you’re at a concert, and the first person in line decides to sit in the VIP section instead of their assigned seat. As more people enter, they either take their assigned seats or scramble for the remaining spots. By the time you get in, there’s a 50% chance you’ll end up in the VIP section or stuck in the back. This chaotic scenario mirrors the airplane seat assignment problem perfectly!

Similar Problems

If you enjoyed this problem, you might also like these:

  • 2-Sum Solution in Python
  • 3-Sum Solution in Python
  • 4-Sum Solution in Python