You have two empty jugs that hold x and y litres, and as much water as you want. In one move you may fill a jug to the top, pour a jug out completely, or pour from one jug into the other, stopping as soon as the giver runs dry or the other jug is full. The jugs have no other markings.
Return true if you can get exactly target litres in the two jugs combined, and false if no sequence of moves can.
Example 1
Input: x = 4, y = 9, target = 5 Output: true Why: fill the 9, pour 4 into the small jug, empty it: 5 remain
2 more examples and the constraints
Example 2
Input: x = 6, y = 9, target = 4 Output: false Why: every reachable total is a multiple of 3
Example 3
Input: x = 2, y = 5, target = 7 Output: true Why: fill both jugs
Constraints
- 1 ≤ x, y ≤ 1,000
- 1 ≤ target ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- BFS over jug statesO(x · y)
- Greatest common divisorO(log min(x, y))
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for x = y = 1,000 | Verdict |
|---|---|---|---|
| BFS over jug states | O(x · y) | Passes; easy to trust | |
| Greatest common divisor | O(log min(x, y)) | Best; a few remainders |
x and y = the jug sizes in litres.
Edge cases to test
- Target bigger than both jugs. x = 1, y = 1, target = 3: the gcd divides 3, but only 2 litres fit, so false.
- Target equals x + y. Fill both jugs: always true.
- Equal jugs. x = y = 7: only 7 and 14 can be held.
- A jug of 1 litre. The gcd is 1, so every total up to x + y works.
Common mistakes
- Checking only the gcd and forgetting that the target must fit in x + y.
- Pouring a full jug's worth instead of min(what is in the giver, room in the receiver).
- Looking for the target in one jug only; the question is about the total of both.
How to talk through it
- 1Clarify. Does the target count both jugs together? Can the target be larger than either jug?
- 2Model the states. A state is (a, b); six moves; BFS from (0, 0) answers the question.
- 3Find the invariant. Each move changes the total by x, y or 0, so totals are combinations a·x + b·y.
- 4Use Bézout. Those combinations are the multiples of gcd(x, y); add the check target ≤ x + y.
- 5Test out loud. Run a target above x + y, a multiple of the gcd and a non-multiple.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?