Water and Jug Problem

MediumMathmath

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You have two jugs with capacities x and y litres and an unlimited water supply. Both start empty. In one operation you may fill either jug completely, empty either jug completely, or pour water from one jug into the other until the source is empty or the destination is full. Return true if it is possible to end up with exactly target litres of water in total across the two jugs (in one jug or split between both), otherwise false.

Examples

Input: x = 3, y = 5, target = 4
Output: true
Fill the 5, pour into the 3 (leaves 2), empty the 3, pour the 2 into it, fill the 5, top up the 3: 4 litres remain in the 5-litre jug.
Input: x = 2, y = 6, target = 5
Output: false
Every reachable amount is even, so 5 is impossible.
Input: x = 1, y = 2, target = 3
Output: true
Fill both jugs.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More math problems