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.
The operations you can perform are:
Input: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4
Output: true
Input: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5
Output: false
Input: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3
Output: true
This problem is equivalent to the classic water jug problem, which can be solved using the properties of greatest common divisors (GCD). According to Bézout’s identity, for any integers a
and b
, if d
is the GCD of a
and b
, there exist integers x
and y
such that ax + by = d
. For this problem, the target capacity (targetCapacity
) must be a multiple of the GCD of the two jug capacities (jug1Capacity
and jug2Capacity
), and must not exceed the sum of both jugs’ capacities.
The conditions to return True
are:
targetCapacity
is less than or equal to the sum of both jugs’ capacities.targetCapacity
is a multiple of the GCD of jug1Capacity
and jug2Capacity
.Let’s write the code to implement this solution.
import math
def canMeasureWater(jug1Capacity, jug2Capacity, targetCapacity):
if targetCapacity > jug1Capacity + jug2Capacity:
return False
if targetCapacity % math.gcd(jug1Capacity, jug2Capacity) == 0:
return True
return False
# Test cases
print(canMeasureWater(3, 5, 4)) # Expected output: True
print(canMeasureWater(2, 6, 5)) # Expected output: False
print(canMeasureWater(1, 2, 3)) # Expected output: True
The time complexity of this solution is constant, O(1)
, because:
Thus, the overall complexity is O(1)
, making this approach highly efficient.
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?