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
Understanding the Visualization
1
Input
Two jug capacities (x, y) and target amount
2
Process
Check mathematical feasibility using GCD
3
Output
Boolean indicating if target is achievable
Key Takeaway
🎯 Key Insight: The problem reduces to checking if target is divisible by GCD(x,y) - a pure mathematical solution
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code