Water and Jug Problem

Solvable iff target ≤ x + y and target is a multiple of gcd(x, y) — Bezout's identity.

Medium
Time O(log min(x, y)) Space O(1)
LeetCode
3 min read
math gcd number-theory

Problem#

Given two jugs of capacities x and y, can you measure exactly target liters using only fill, empty, and pour operations?

Examples#

  • x=3, y=5, target=4true.
  • x=2, y=6, target=5false.

Constraints#

  • 1 <= x, y, target <= 10^6.

Approach#

By Bezout’s identity, integer combinations a*x + b*y produce exactly the multiples of gcd(x, y). We can measure target iff target <= x + y and target % gcd(x, y) == 0.

Solution#

Water and Jug Problem
class Solution {
public:
bool canMeasureWater(int x, int y, int target) {
if (target > x + y) return false;
if (target == 0) return true;
return target % __gcd(x, y) == 0;
}
};

Editorial#

gcd(x, y) is the finest granularity any combination of fills and pours can reach. As long as target fits in the total capacity and is a multiple of that granularity, a constructive sequence exists. The target == 0 corner case is trivially achievable.

Complexity#

  • Time: O(log min(x, y)) for gcd.
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.