Airplane Seat Assignment Probability Solution in Java

Problem Description

So, you think you can just waltz into an airplane, plop down in your assigned seat, and enjoy a peaceful flight? Think again! Welcome to the Airplane Seat Assignment Probability problem, where chaos reigns supreme! Imagine a scenario where the first passenger, who clearly skipped their morning coffee, decides to sit anywhere they please. This sets off a chain reaction of seat swapping that would make even the most seasoned game of musical chairs look like a walk in the park.

In this delightful mess, we need to figure out the probability that the nth passenger ends up in their assigned seat. Spoiler alert: if you’re the first passenger, you might just ruin it for everyone else!

Code Solution


class Solution {
  public double nthPersonGetsNthSeat(int n) {
    return n == 1 ? 1 : 0.5;
  }
}

Approach

The code provided is a simple yet elegant solution to this problem. It checks if there is only one passenger (n == 1). If so, the probability of them sitting in their assigned seat is 100% (or 1). However, if there are more passengers, the probability drops to 50% (or 0.5). This is because the first passenger’s random choice creates a 50/50 chance of the last passenger sitting in their assigned seat.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(1)
Space Complexity O(1)

Real-World Example

Picture this: you’re on a flight to a tropical paradise, and the first passenger decides to sit in your window seat. Now, everyone else is forced to play a game of “who’s sitting where?” By the time the last passenger boards, they might find themselves in a seat that was never theirs to begin with. The probability of them sitting in their assigned seat? Well, it’s a coin toss!

Similar Problems

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

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