Leetcode 365: Water and Jug Problem

dume0011
2 min readApr 11, 2021

--

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.

Example 1:

Input: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4
Output: true
Explanation: The famous Die Hard example

Example 2:

Input: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5
Output: false

Example 3:

Input: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3
Output: true

Constraints:

  • 1 <= jug1Capacity, jug2Capacity, targetCapacity <= 10^6

Problem Analysis:

We need some math knowledge to solve it. First, we should know the concept of greatest common divisor, denoted gcd(a, b), is the greatest integer that can divided two integer a and b without remainder.

If we let c = gcd(a, b), then exist integers x and y such that ax + by = c. So we can find all number that is multiplied by c, i.e., to get 3c, we can use equation 3ax + 3by = 3c, the two integer is 3x and 3y.

Solution

int gcd(int x, int y) {
int c = x % y;
if (c == 0) return y;
return gcd(y, c);
}
class Solution {
public:
bool canMeasureWater(int x, int y, int z) {
if (x < y) swap(x, y);
return (z == 0) || ((z <= (long long)x + y) && ((y == 0 && z == y) || (z % gcd(x, y) == 0)));
}
};

Space complexity is O(1)

--

--