Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created October 1, 2025 22:33
Show Gist options
  • Select an option

  • Save Ifihan/b2061ff0663873db5ff312e7d677252c to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/b2061ff0663873db5ff312e7d677252c to your computer and use it in GitHub Desktop.
Water Bottles

Question

Approach

I start by drinking all the initial bottles, keeping track of empties. While I have enough empties to exchange for a full one, I perform the exchange, drink those, and update my empty count. I continue until I can no longer exchange.

Implementation

class Solution:
    def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
        total = numBottles
        empty = numBottles
        
        while empty >= numExchange:
            new_full = empty // numExchange  
            total += new_full
            empty = empty % numExchange + new_full 
        
        return total

Complexities

  • Time: O(log(numBottles)) (since bottles shrink with each exchange)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment