We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Water and Jug Problem

Difficulty: Medium


Problem Description

You are given two jugs with capacities x liters and y liters. You have an infinite water supply. Return whether the total amount of water in both jugs may reach target using the following operations:

  • Fill either jug completely with water.
  • Completely empty either jug.
  • Pour water from one jug into another until the receiving jug is full, or the transferring jug is empty.

Key Insights

  • The problem can be reduced to checking if the target amount of water can be expressed as a linear combination of the capacities of the two jugs.
  • The target amount must not exceed the total capacity of both jugs combined.
  • The greatest common divisor (GCD) of the two jug capacities plays a crucial role: the target must be a multiple of the GCD of the two capacities.

Space and Time Complexity

Time Complexity: O(log(min(x, y))) - for calculating the GCD Space Complexity: O(1) - no additional space is used other than variables


Solution

To solve this problem, we can use the mathematical properties of the GCD. Specifically, we check the following:

  1. If the target is greater than the sum of the two jug capacities, return false.
  2. If the target is a multiple of the GCD of the two jug capacities, return true; otherwise, return false.

This approach leverages the mathematical properties of integers and their combinations, ensuring an efficient solution.


Code Solutions

def canMeasureWater(x: int, y: int, target: int) -> bool:
    def gcd(a, b):
        while b:
            a, b = b, a % b
        return a
    
    if target > x + y:
        return False
    return target % gcd(x, y) == 0
← Back to All Questions