↓Skip to main content
  1. LeetCode/

LeetCode 441: Arranging Coins

·1 min· ·
LeetCode Easy Math Binary-Search
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-24

  • Submissions: Accepted → Time Limit Exceeded → Accepted

Approach
#

Filling k rows takes k(k + 1) / 2 coins, increasing in k; find the largest k that fits within n (Binary Search Template 2). With a closed interval, r ends on the last valid value.

My Attempts
#

The first submission passed; when practicing binary search afterward I wrote while l < r with l = mid, so with r = l + 1 the mid kept equaling l and it looped forever (TLE), e.g. n = 8.

Solution
#

class Solution:
    def arrangeCoins(self, n: int) -> int:
        l, r = 0, n
        while l <= r:
            mid = (l + r) // 2
            if mid * (mid + 1) // 2 <= n:
                l = mid + 1
            else:
                r = mid - 1
        return r

Complexity
#

Time O(log n), space O(1). A formula with isqrt(8n + 1) also works.

Mistakes to Avoid
#

  • With while l < r and l = mid, mid rounds down and l may never move, looping forever.

Interview Explanation
#

k full rows need k(k+1)/2 coins, so I binary search the largest k that fits. Time O(log n).

Related

LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 367: Valid Perfect Square
·1 min
LeetCode Easy Math Binary-Search
LeetCode 367 note: binary search [1, num] for mid² == num without using sqrt
LeetCode 69: Sqrt(x)
·1 min
LeetCode Easy Math Binary-Search Newtons-Method
LeetCode 69 note: find the largest mid with mid² <= x; when a closed-interval search ends, r is the answer
LeetCode 415: Add Strings
·2 mins
LeetCode Easy Math String Simulation
LeetCode 415 note: add digit by digit from the ends with two pointers, tracking the carry, and append any leftover carry after the loop
LeetCode 492: Construct the Rectangle
·2 mins
LeetCode Easy Math
LeetCode 492 note: search the width downward from √area; the first divisor of area gives the most square-like rectangle
LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1