Water and Jug Problem - Medium - L

1 minute read

Published:

Question

  • https://leetcode.com/problems/water-and-jug-problem/

You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs.

If targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end.

Operations allowed:

Fill any of the jugs with water.
Empty any of the jugs.
Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty.

Approach

  • To solve this, we will follow these steps −

    if x + y < z, then return false
      
    if x = z or y = z, or x + y = z, then return true
      
    return true z is divisible by gcd of x and y, otherwise false
    

Solution

class Solution {
public:
    bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
        int x = jug1Capacity;
        int y = jug2Capacity;
        int z = targetCapacity;
        if(x + y < z) return false;
        if(x == z || y == z || x + y == z) return true;
        return z % __gcd(x, y) == 0;
    }
};