Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional

Problem: A water-jug problem: a 3-litre jug and a 5-litre jug, both empty, and unlimited water. Allowed actions: fill a jug fully, empty a jug, or pour from one into the other until the source is empty or the target is full. What is the minimum number of actions to get exactly 4 litres in the 5-litre jug?

  1. A. 8
  2. B. 6
  3. C. 5
  4. D. 3

Correct answer: B. 6

BFS over (a, b) states finds fill 5, pour 5→3 (5L has 2), empty 3, pour 5→3, fill 5, pour 5→3, leaving 4 litres in the 5-litre jug: 6 actions. Starting by filling the 3-litre jug needs 8, not counting the 'empty' action gives 5, and counting only the pours gives 3.

More Coding Interview Problems questions

Exams that ask this topic