Community Problem

Arranging Coins

Difficulty: Easy

Find the largest k such that 1+2+...+k <= n, framed as a binary-search-on-answer warmup with a closed-form sanity check.

Arranging Coins

Find the largest k such that 1+2+...+k <= n, framed as a binary-search-on-answer warmup with a closed-form sanity check.

EASY
Free
binary-search
math
elenamuller

By @elenamuller

March 12, 2026

·

Updated May 18, 2026

484 views

15

4.4 (9)

I use this as the cleanest warmup for the binary-search-on-answer pattern. The closed-form k = floor((-1 + sqrt(1 + 8n)) / 2) exists, but the interview signal is the search version: define a monotone predicate, pin a closed interval that contains the answer, and walk through the off-by-one with the lo / hi update rules.

Arranging Coins

You have n coins and want to arrange them in a staircase shape where the i-th row contains exactly i coins. The last row may be incomplete (i.e. fewer than its full count). Return the largest number of complete rows you can build.

Formally, return the largest integer k such that 1 + 2 + 3 + ... + k <= n.

Examples

Example 1:

  • Input: n = 5
  • Output: 2
  • Explanation: Row 1 has 1 coin, row 2 has 2 coins (3 used). The third row would need 3 more coins, but only 2 are left, so it is incomplete.

Example 2:

  • Input: n = 8
  • Output: 3
  • Explanation: Rows of size 1, 2, 3 use exactly 6 coins. Row 4 would need 4 more, but only 2 are left.

Example 3:

  • Input: n = 1
  • Output: 1
  • Explanation: Exactly one full row.

Example 4:

  • Input: n = 0
  • Output: 0
  • Explanation: No coins, no rows.

Constraints

  • 0 <= n <= 2^31 - 1

Follow-up

The closed-form answer is k = floor((-1 + sqrt(1 + 8n)) / 2). Why does the binary-search version still get asked? Because for very large n, sqrt on doubles can be off by 1 due to floating-point rounding, and binary search on integers is exact. Solve both ways and use one to validate the other.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems