Problem 1227

Abstract / Summary

A passenger randomly takes a seat on a plane and the last passenger gets their seat half the time.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1227.py

class Solution:
    def nthPersonGetsNthSeat(self, n: int) -> float:
        # this is a weird problem:
        # writing a simulation was fun but figuring out
        # that the math behind it leads to a one-liner makes me feel bad

        if n < 10:
            # simulation
            last = n - 1 # zero-based
            correct = 0
            for first in range(n):
                occupied = [ False ] * n
                occupied[first] = True
                for i in range(1, last): # all except the first and last
                    if occupied[i]:
                        # pick randomly an available seat
                        available = n - i
                        pick = randint(1, available)
                        for j in range(n):
                            if not occupied[j]:
                                pick -= 1
                                if pick == 0:
                                    occupied[j] = True
                                    break

                        # last passenger's seat taken
                        if occupied[last]:
                            break
                    else:
                        # pre-assigned seat
                        occupied[i] = True

                if not occupied[last]:
                    correct += 1

            #print(correct / n)

        # yes, that's all there is ...
        return 1 if n == 1 else 0.5
39 lines | 1459 bytes | submitted October 29, 2023 | GitHub   44% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 68% (90k+ submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
  • Math
  • Probability And Statistics
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method that computes the probability that the n-th passenger sits in his own seat on a plane where the first passenger chooses a seat at random and each subsequent passenger either sits in his assigned seat if it is free or picks a random free seat otherwise. The implementation contains two distinct execution paths: a short simulation used for very small values of n and a direct mathematical result for all other inputs.

Core Logic

Method Signature

def nthPersonGetsNthSeat(self, n: int) -> float:

The method receives a single integer n and returns a floating-point probability.

Immediate Return for Trivial Case

return 1 if n == 1 else 0.5

When there is only one passenger, the probability is trivially 1. For any larger number of passengers the method returns the constant value 0.5, reflecting the known analytical solution of the problem.

Simulation Path for Small n

if n < 10:
    # simulation
    last = n - 1  # zero-based index of the last passenger
    correct = 0
    for first in range(n):
        occupied = [False] * n
        occupied[first] = True
        for i in range(1, last):
            if occupied[i]:
                # pick randomly an available seat
                available = n - i
                pick = randint(1, available)
                for j in range(n):
                    if not occupied[j]:
                        pick -= 1
                        if pick == 0:
                            occupied[j] = True
                            break
                # last passenger's seat taken
                if occupied[last]:
                    break
            else:
                # pre-assigned seat
                occupied[i] = True
        if not occupied[last]:
            correct += 1

The simulation iterates over every possible initial seat choice for the first passenger (first ranging from 0 to n-1). An occupied list tracks which seats have been taken. For each subsequent passenger i (excluding the first and the last), the code checks whether his assigned seat is already occupied. If it is, a random free seat is selected by counting down from a random integer pick. The inner loop walks through the seat array to locate the pick-th free seat and marks it as occupied. If at any point the last seat becomes occupied, the inner loop aborts early. After processing all intermediate passengers, the simulation increments correct when the last passenger’s seat remains free.

Final Result

The simulation result is not used in the returned value; the method always returns the constant expression shown earlier. The simulation block therefore serves only as a demonstration or verification tool for very small inputs.

Edge Cases Handled

When n equals 1, the early return yields a probability of 1, correctly handling the degenerate scenario where the sole passenger must sit in his own seat. For any n less than 10, the simulation runs, ensuring that the algorithm can produce empirical results for tiny problem sizes without relying on the analytical shortcut. For n greater than or equal to 10, the method bypasses the simulation entirely, directly applying the known probability.

The inner loop that selects a random free seat includes a break condition once the target seat is found, guaranteeing termination even when the number of free seats is minimal. Additionally, the check if occupied[last]: break prevents unnecessary iterations once the last passenger’s seat is already taken, avoiding wasted work.

Performance Optimizations

The most significant optimization is the early exit for n >= 10. By returning the constant value 0.5 without performing any simulation, the method avoids the combinatorial explosion that would occur if the random process were executed for larger inputs. This constant-time path ensures that the function scales instantly regardless of the magnitude of n.

Within the simulation, the use of a pre-allocated list occupied = [False] * n avoids repeated list construction inside inner loops. The break statements after locating the randomly chosen seat and after detecting that the last seat is occupied both truncate loops as soon as their purpose is fulfilled, reducing the number of iterations in typical runs. The calculation of available = n - i provides the exact count of remaining free seats without scanning the list, allowing the random selection to be bounded correctly.

Overall, the code balances a straightforward brute-force verification for tiny inputs with a mathematically derived shortcut for all practical sizes, delivering immediate results while still offering a concrete simulation for educational or testing purposes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big room full of chairs that have numbers on them. Each person has a special ticket with a number, and they really want to sit in their own seat. If there is only one person and one chair, they will definitely find their seat. But if there is more than one person, things get a little bit silly. The first person loses their ticket and picks a chair just by guessing. Everyone else tries to sit in their own seat, but if someone is already sitting there, they have to pick a random open spot too. This code checks what happens when the very last person walks into the room. If there is only one person, they always get the right seat. If there are two or more people, it is just like flipping a coin to see if the last person gets their seat or not. That is why the answer is either one or half.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 5 | μ = 4.93 | σ = 1.68

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
fsq C++
JoshCrozier JS
Krazune C++
lkwq007 Python
suxrobGM C#
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
fsq C++
JoshCrozier JavaScript
Krazune C++
lkwq007 Python
suxrobGM C#
wisdompeak C++
YuriSpiridonov Python
26 links | 14 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

6 solutions   October 29, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality