EasyNo. 0441

Arranging Coins — LeetCode 441 Python Solution

Topics
Math, Binary Search
Reading time
2 min

The problem

You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins.

Example

Input
n = 5
Output
2
Explanation
Because the 3rd row is incomplete, we return 2.

Python solution

PythonSolution
class Solution:
    def arrangeCoins(self, n: int) -> int:
        return int(math.sqrt(2) * math.sqrt(n + 0.125) - 0.5)

Complexity

Time
O(log n) or O(n log n)
Space · auxiliary
O(1)

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 441. Arranging Coins is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0069Sqrt(x)Easy
0367Valid Perfect SquareEasy
0400Nth DigitMedium
0483Smallest Good BaseHard
0497Random Point in Non-overlapping RectanglesMedium
0528Random Pick with WeightMedium

Frequently asked questions

How hard is LeetCode 441. Arranging Coins?

LeetCode 441. Arranging Coins is rated Easy on LeetCode.

What topics does LeetCode 441. Arranging Coins cover?

LeetCode 441. Arranging Coins is tagged Math and Binary Search 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.