DDSA Solutions

1518. Water Bottles

Time: O(log n)
Space: O(1)

Problem Overview

Water Bottles (Unknown) asks you to solve a structured algorithmic task. This is a common Math / Simulation pattern in coding interviews. Simulate; repeatedly exchange full bottles for new ones, tracking the total drunk.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Simulate; repeatedly exchange full bottles for new ones, tracking the total drunk.

Related patterns: Math, Simulation

1518.cs
C#
// Approach: Simulate; repeatedly exchange full bottles for new ones, tracking the total drunk.
// Time: O(log n) Space: O(1)

public class Solution
{
    public int NumWaterBottles(int numBottles, int numExchange)
    {
        int ans = numBottles;

        while (numBottles >= numExchange)
        {
            numBottles -= numExchange;
            ans++;
            numBottles += 1;
        }

        return ans;
    }
}
Was this solution helpful?

Related Problems