Skip to content

365. Water and Jug Problem

  • Time: $O(1)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
class Solution {
 public:
  bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
    return targetCapacity == 0 ||
           jug1Capacity + jug2Capacity >= targetCapacity &&
               targetCapacity % __gcd(jug1Capacity, jug2Capacity) == 0;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
    return targetCapacity == 0 || jug1Capacity + jug2Capacity >= targetCapacity &&
                                      targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0;
  }

  private int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def canMeasureWater(
      self,
      jug1Capacity: int,
      jug2Capacity: int,
      targetCapacity: int,
  ) -> bool:
    return (targetCapacity == 0 or
            jug1Capacity + jug2Capacity >= targetCapacity and
            targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0)