Magicsheet logo

Arranging Coins

Easy
25%
Updated 8/1/2025

Arranging Coins

What is this problem about?

In the Arranging Coins interview question, you are given n coins and you want to build a staircase where the i-th row has exactly i coins. The goal is to find the total number of full rows you can complete. This Arranging Coins coding problem is essentially about finding the largest integer k such that the sum of the first k integers is less than or equal to n.

Why is this asked in interviews?

Google, Meta, and Microsoft ask this to see if a candidate can optimize a mathematical search. While a linear loop works, a binary search or a direct mathematical formula (O(1)) demonstrates a higher level of technical maturity and mathematical reasoning.

Algorithmic pattern used

This utilizes the Math, Binary Search interview pattern. You can treat this as a search for k in the range [0, n] where the sum formula k(k+1)/2 <= n holds true. Binary search allows you to find this k in O(log N) time. Alternatively, you can solve the quadratic equation k^2 + k - 2n = 0 using the quadratic formula.

Example explanation

Suppose n = 8 coins.

  1. Row 1: 1 coin (7 left)
  2. Row 2: 2 coins (5 left)
  3. Row 3: 3 coins (2 left)
  4. Row 4: Needs 4 coins, but only 2 are left. Result: 3 full rows were completed.

Common mistakes candidates make

  • Integer Overflow: When calculating k(k+1), the result can easily exceed the range of a 32-bit integer if n is large.
  • Off-by-one errors: Returning k+1 instead of k or vice versa in the binary search boundary conditions.
  • Floating Point Issues: Relying on sqrt() without considering precision issues for very large values of n.

Interview preparation tip

When a problem involves finding a maximum value k that satisfies a monotonic condition (like a sum), always consider Binary Search on the answer. It is often faster than simulation and highly favored by interviewers.

Similar Questions