Leetcode 365. Water and Jug Problem
You are given two jugs with capacities jug1Capacity
and jug2Capacity
liters. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly targetCapacity
liters using these two jugs.
If targetCapacity
liters of water is measurable, you must do it by using these operations:
Return true
if targetCapacity
liters can be measured using the two jugs, otherwise return false
.
jug1Capacity
, jug2Capacity
, and targetCapacity
? Are they all non-negative integers?targetCapacity
be greater than the sum of jug1Capacity
and jug2Capacity
?jug1Capacity
, jug2Capacity
, targetCapacity
) to be zero?With these clarifications in mind, let’s move on to defining the solution strategy.
The problem boils down to a classic mathematical problem that can be solved using Bézout’s identity and the properties of the greatest common divisor (GCD).
Key Insight:
A solution exists if and only if the targetCapacity
is a multiple of the GCD of jug1Capacity
and jug2Capacity
, and targetCapacity
does not exceed the sum of the two jug capacities.
jug1Capacity
and jug2Capacity
.targetCapacity
is less than or equal to the sum of the two jug capacities.targetCapacity
is a multiple of the GCD obtained.O(log(min(jug1Capacity, jug2Capacity)))
using the Euclidean algorithm.#include <algorithm> // for __gcd function
class Solution {
public:
bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
// If the target capacity is greater than the sum of both jugs, it's impossible
if(targetCapacity > jug1Capacity + jug2Capacity) {
return false;
}
// Calculate the GCD of both jug capacities
int gcd = std::__gcd(jug1Capacity, jug2Capacity);
// Check if targetCapacity is a multiple of GCD
return targetCapacity % gcd == 0;
}
};
std::__gcd
function to compute the GCD of jug1Capacity
and jug2Capacity
.targetCapacity
is greater than the total capacity of both jugs combined. If it is, then it’s impossible to measure that amount of water.targetCapacity
is a multiple of the GCD, which ensures it’s measurable by using the two jugs.This completes our solution. The strategy leverages basic number theory to determine the feasibility of measuring the desired water capacity with two jugs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?