#441

Arranging Coins

Easy
MathBinary SearchMathematical FormulasQuadratic Equations
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

Instead of building the staircase row by row, we can use a mathematical approach to find the maximum number of complete rows that can be formed with 'n' coins using the formula for the sum of the first k natural numbers.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use the formula k(k + 1) / 2 <= n to find the maximum k.
  2. 2Step 2: Rearrange it to k² + k - 2n <= 0 and apply the quadratic formula.
  3. 3Step 3: Calculate k = (-1 + sqrt(1 + 8n)) / 2 and return the integer part of k.
solution.py5 lines
1# Full working Python code
2import math
3n = 5
4k = int((-1 + math.sqrt(1 + 8 * n)) // 2)
5print(k)

Complexity note: The time complexity is O(1) because we are performing a constant number of arithmetic operations and a square root calculation, regardless of the size of 'n'.

  • 1Understanding the relationship between the number of coins and the rows formed is crucial.
  • 2Using mathematical formulas can significantly reduce the complexity of the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.