Water and Jug Problem - Problem

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

Determine if you can measure exactly target liters using these operations.

Input & Output

Example 1 — Achievable Target
$ Input: x = 3, y = 5, target = 4
Output: true
💡 Note: Fill 5-liter jug, pour into 3-liter jug (2 liters remain in 5-liter jug). Empty 3-liter jug, pour the 2 liters from 5-liter jug into 3-liter jug. Fill 5-liter jug again, pour 1 liter into 3-liter jug (which had 2 liters). Now 5-liter jug has 4 liters.
Example 2 — Impossible Target
$ Input: x = 2, y = 6, target = 5
Output: false
💡 Note: GCD(2,6) = 2. Since 5 is not divisible by 2, it's impossible to measure exactly 5 liters using 2L and 6L jugs.
Example 3 — Edge Case Zero
$ Input: x = 1, y = 2, target = 0
Output: true
💡 Note: We can always achieve 0 liters by keeping both jugs empty.

Constraints

  • 1 ≤ x, y ≤ 106
  • 0 ≤ target ≤ x + y

Visualization

Tap to expand
Water and Jug Problem INPUT x = 3L Jug X y = 5L Jug Y 4L Target x = 3 y = 5 target = 4 Operations allowed: - Fill jug completely - Empty jug completely - Pour between jugs - Infinite water supply ALGORITHM STEPS 1 Use GCD Theorem Bezout's Identity applies 2 Calculate GCD(3,5) GCD(3,5) = 1 3 Check Divisibility target % GCD == 0? 4 Verify Bounds target <= x + y GCD Calculation: GCD(5, 3) = GCD(3, 5%3) GCD(3, 2) = GCD(2, 3%2) GCD(2, 1) = GCD(1, 2%1) GCD(1, 0) = 1 4 % 1 == 0 and 4 <= 8 OK - Condition Met! FINAL RESULT OK TRUE Output: true 4L is measurable One Solution Path: 1. Fill 5L jug: (0,5) 2. Pour to 3L: (3,2) 3. Empty 3L: (0,2) 4. Pour to 3L: (2,0) 5. Fill 5L: (2,5) 6. Pour to 3L: (3,4) Total: 4L in Jug Y! Key Insight: By Bezout's Identity, we can measure exactly target liters if and only if target is divisible by GCD(x, y) and target <= x + y. This transforms the problem from BFS/simulation to simple math: O(log(min(x,y))) time. Formula: target % GCD(x, y) == 0 AND target <= x + y ---> Return true TutorialsPoint - Water and Jug Problem | Optimal Solution (GCD/Bezout's Identity)
Asked in
Microsoft 15 Google 12 Amazon 8
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen