Water and Jug Problem

You are given two jugs with capacities x liters and y liters. You have an infinite water supply. Return whether the total amount of water in both jugs may reach target using the following operations:

  • Fill either jug completely with water.
  • Completely empty either jug.
  • Pour water from one jug into another until the receiving jug is full, or the transferring jug is empty.
Example 1
Inputx = 3, y = 5, target = 4
Outputtrue
Following the allowed fill, empty, and pour operations, it is possible to leave exactly 4 liters total in the jugs.
Example 2
Inputx = 2, y = 6, target = 5
Outputfalse
There is no sequence of allowed operations that can make the total amount of water in the two jugs equal to 5 liters.

Constraints

  • 1 <= x, y, target <= 10^3

Asked at 8 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate