#365

Water and Jug Problem

Medium
MathDepth-First SearchBreadth-First SearchGraph Traversal (BFS/DFS)Mathematical Properties (GCD)
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log(min(x, y)))
Space
O(1)
O(1)
💡

Intuition

Time O(log(min(x, y)))Space O(1)

The optimal solution leverages the mathematical properties of the problem, specifically the greatest common divisor (GCD). If the target can be expressed as a combination of the two jug capacities, we can reach the target without simulating every possible state.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if the target is greater than the sum of the jug capacities; if so, return false.
  2. 2Step 2: Calculate the GCD of the two jug capacities.
  3. 3Step 3: Check if the target is a multiple of the GCD and less than or equal to the sum of the capacities.
solution.py6 lines
1import math
2
3def canMeasureWater(x, y, target):
4    if target > x + y:
5        return False
6    return target % math.gcd(x, y) == 0

Complexity note: The time complexity is O(log(min(x, y))) due to the GCD calculation, which is efficient and does not require exploring all states.

  • 1The target must be less than or equal to the sum of the jug capacities.
  • 2The target must be a multiple of the GCD of the two jug capacities.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.