Water Jug Problem — AI Technical Interview Questions & Answers
Water Jug Problem
Water Jug Problem
- Water jug: jugs of size A and B, get exactly D litres. States are (x, y) litres. Actions: fill, empty, pour. Search (BFS) finds a shortest sequence. Classic AI planning toy — not a plumbing exam.
- 3 and 5 litre jugs, goal 4. Trace a few states on paper before code. That trace is the viva.
- Water Jug Problem — output: a list of (x,y) states ending with 4 litres in one jug. BFS on states.
Technical Interview Tip: State representation + one action trace.
Code Examples for Water Jug Problem
Example
# 3 and 5 litre jugs → 4
from collections import deque
def jugs(a=3, b=5, goal=4):
q = deque([(0, 0, [])])
seen = {(0, 0)}
while q:
x, y, path = q.popleft()
if x == goal or y == goal or x + y == goal:
return path + [(x, y)]
nxt = [
(a, y), (x, b), (0, y), (x, 0),
(x - min(x, b - y), y + min(x, b - y)),
(x + min(y, a - x), y - min(y, a - x)),
]
for s in nxt:
if s not in seen:
seen.add(s)
q.append((s[0], s[1], path + [(x, y)]))
return None
print(jugs())
Water Jug Problem — output: a list of (x,y) states ending with 4 litres in one jug. BFS on states.
How to Explain Water Jug Problem to an Interviewer
Explain Water Jug Problem as if you are teaching a junior — definition, then one example.
States (x,y). Fill / empty / pour. Search for goal D.
What does the example print, and what does that prove?
Water Jug Problem — output: a list of (x,y) states ending with 4 litres in one jug
What mistake do freshers make with Water Jug Problem?
Only the buzzword, no example