LeetCode Entry

1518. Water Bottles

01.10.2025 easy 2025 kotlin rust

Total drinks with exchange empty for full

1518. Water Bottles easy blog post substack youtube

1.jpg

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1129

Problem TLDR

Total drinks with exchange empty for full #easy #simulation

Intuition

Simulate the process. Don’t forget to keep lefover empty bottles.

Approach

  • the single math formula can be derived from: s = b + b/x + (b/x+b%x)/x + ((b/x+b%x)/x+(b/x+b%x)%x)/x...
  • or s = b*(1 + 1/x + 1/x^2 + 1/x^3 + ...), geometric series converges to 1/(1-r) where r=1/x
  • so s = b*(1/(1-1/x)) = b/(1-1/x) = b*x/(x-1) (ask chatgpt why it is (b*x-1) instead)

Complexity

  • Time complexity: \(O(1)\)

  • Space complexity: \(O(1)\)

Code


// 0ms
    fun numWaterBottles(b: Int, x: Int, e: Int = 0): Int =
    b + if (b < 1) 0 else numWaterBottles((b+e)/x, x, (b+e)%x)


// 0ms
    pub fn num_water_bottles(b: i32, x: i32) -> i32 {
        (b*x-1)/(x-1)
    }