All problems
0970MediumMathDepth-First SearchBreadth-First SearchBézout's LemmaEuclidean AlgorithmGreatest Common DivisorExtended Euclidean Algorithm

Measuring Out an Exact Amount With Two Cans

Tracked in this browser only
Write code

Trains the technique from

LeetCode 365Water and Jug Problem

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

Two cans hold x and y litres when full. There is an unlimited supply of water and a drain.

At any moment you may fill a can to the brim, empty a can out, or pour one can into the other until either the pouring can runs dry or the receiving can is full.

Return true when the two cans can be made to hold target litres between them.

Examples

Example 1

Input
x = 14, y = 21, target = 7
Output
true

The two sizes share the divisor 7, and 7 divides evenly by it and fits inside 35, so it can be measured out.

Example 2

Input
x = 2, y = 6, target = 5
Output
false

Both cans hold an even number of litres, so the total is always even and an odd target is out of reach.

Example 3

Input
x = 4, y = 6, target = 10
Output
true

The target is exactly both cans full, which is allowed, and it divides evenly by their shared divisor of 2.

Constraints

  • 1 <= x <= 1000
  • 1 <= y <= 1000
  • 1 <= target <= 1000

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def can_measure_water(x: int, y: int, target: int) -> bool:
Java
public boolean canMeasureWater(int x, int y, int target)
September 7
Apply