Isaac Emmanuel
15 Jun 2024•EasyC++ / Python / TypeScript

Arranging Coins

C++, Python and TypeScript solutions for Arranging Coins.

The Arranging Coins solutions are below.

Solution files

Python•arranging-coins/synced-solution.py
def arrangeCoins(n):
    left, right = 0, n

    while left <= right:
        mid = (left + right) // 2
        cost = mid * (mid + 1) // 2

        if cost == n:
            return mid
        elif cost < n:
            left = mid + 1
        else:
            right = mid - 1

    return right
C++•arranging-coins/synced-solution.cpp
class Solution {
public:
    int arrangeCoins(int n) {
        long left = 0, right = n;

        while (left <= right) {
            long mid = (left + right) / 2;
            long cost = mid * (mid + 1) / 2;

            if (cost == n) {
                return mid;
            } else if (cost < n) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return right;
    }
};
TypeScript•arranging-coins/synced-solution.ts
function arrangeCoins(n: number): number {
    let left = 0, right = n;

    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        const cost = (mid * (mid + 1)) / 2;

        if (cost === n) {
            return mid;
        } else if (cost < n) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return right;
}