PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

AI · Theory

Water Jug Problem

← All stacks

Theory

205/215

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.

Exam tip

State representation + one action trace.

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.

Short notes

  • DefStates (x,y). Fill / empty / pour.
  • RuleSearch for goal D.

Questions

1

Explain Water Jug Problem as if you are teaching a junior — definition, then one example.

2

What does the example print, and what does that prove?

3

What mistake do freshers make with Water Jug Problem?

Previous← The Impact of Artificial Intelligence on EmploymentNextThe Role of Artificial Intelligence in Literature →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.