EasyNo. 2582

Pass the Pillow — LeetCode 2582 Python Solution

Topics
Math, Simulation
Reading time
2 min

The problem

There are n people standing in a line labeled from 1 to n. The first person in the line is holding a pillow initially.

Example

Input
n = 4, time = 5
Output
2
Explanation
People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2.

Python solution

PythonSolution
class Solution:
    def passThePillow(self, n: int, time: int) -> int:
        ans = k = 1
        for _ in range(time):
            ans += k
            if ans == 1 or ans == n:
                k *= -1
        return ans

Complexity

Time
O(time)
Space · auxiliary
O(1)where time is the given time

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2582. Pass the Pillow is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0043Multiply StringsMedium
0258Add DigitsEasy
0412Fizz BuzzEasy
0415Add StringsEasy
0537Complex Number MultiplicationMedium
0592Fraction Addition and SubtractionMedium

Frequently asked questions

How hard is LeetCode 2582. Pass the Pillow?

LeetCode 2582. Pass the Pillow is rated Easy on LeetCode.

What is the time complexity of LeetCode 2582. Pass the Pillow?

The Python solution on this page runs in O(time).

What is the space complexity of LeetCode 2582. Pass the Pillow?

The Python solution on this page uses O(1), where time is the given time auxiliary space.

What topics does LeetCode 2582. Pass the Pillow cover?

LeetCode 2582. Pass the Pillow is tagged Math and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.