Water Jug Problem -Complete Tutorial
Last Updated :
09 Sep, 2024
You are given a m liter jug and a n liter jug where 0 < m < n. Both the jugs are initially empty. The jugs donât have markings to allow measuring smaller quantities. You have to use the jugs to measure d liters of water where d < n. Determine the minimum no of operations to be performed to obtain d liters of water.
The operations you can perform are:
- Empty a Jug
- Fill a Jug (You may assume that you have unlimited supply of water)
- Pour water from one jug to the other until one of the jugs is either empty or full.
Get d litre in One Jug Only
Our target amount d should be present in one jug only. Let us see below examples to understand this.
Input: m = 2, n = 3, d = 1
Output: Yes
Explanation:
1. Fill up the 3 litre jug
2. Pour 2 litre of water from the 3 litre Jug to 2 litre Jug, Now the 3 litre jug has 1 litre water.
Input: m = 3, n = 5, d = 4
Output: Yes
Explanation:
1. Fill up the 5 litre jug.
2. Then fill up the 3 litre jug using 5 litre jug. Now 5 litre jug contains 2 litre water.
3. Empty the 3 litre jug.
4. Now pour the 2 litre of water from 5 litre jug to 3 litre jug.
5. Now 3 litre jug contains 2 litre of water and 5 litre jug is empty. Now fill up the 5 litre jug.
6. Now fill one litre of water from 5 litre jug to 3 litre jug. Now we have 4 litre water in 5 litre jug
Input: m = 2, n = 3, d = 5
Output: No
Explanation: We need to fill in one jug only
Input: m = 2, n = 4, d = 3
Output: No
Explanation: Not possible
The problem can be modeled by means of the Diophantine equation of the form mx + ny = d which is solvable if and only if gcd(m, n) divides d. Also, the solution x,y for which equation is satisfied can be given using the Extended Euclid algorithm for GCD.
For example, if we have a jug J1 of 5 liters (n = 5) and another jug J2 of 3 liters (m = 3) and we have to measure 1 liter of water using them. The associated equation will be 5x + 3y = 1. First of all this problem can be solved since gcd(3,5) = 1 which divides 1 (See this for detailed explanation). Using the Extended Euclid algorithm, we get values of x and y for which the equation is satisfied which are x = 2 and y = -3. These values of x, y also have some meaning like here x = 2 and y = -3 means that we have to fill J1 twice and empty J2 thrice.
The main idea used here is that the Diophantine equation of the form mx + ny = d is solvable if and only if d divides gcd of m and n
How does this work?
Let g be the gcd of m and n
Part 1: We prove that if there is a solution, then g must divide both m and n
mx + ny = d
Let us divide both sides by g, we get
(mx)/g + (ny)/g = d/g
If mx + ny = d has a solution, then the above equation would also have a solution because gcd divides all three terms.
Part 2: If g does not divide d, then there is no solution.
mx + ny = d
Let us say we get a remainder r when we divide d with g, we can write the above as
(mx)/g + (ny)/g = floor(d/g) + r
If we multiply, both sides with g, we get
mx + ny = floor(d/g)*g + rg
Which becomes
mx + ny = d + r + rg
Which contradicts the fact the equation mx + ny = d for r > 0
Below is a solution based on the above idea.
C++
// C++ program to check if we can get
// d litre water in one of the two jugs
#include <bits/stdc++.h>
using namespace std;
// Utility function to return GCD of 'a'
// and 'b'.
int gcd(int m, int n)
{
if (n == 0)
return m;
return gcd(m, m % n);
}
// Returns treu if we can get d litre water
// in one of the two jugs
bool isFeasible(int m, int n, int d)
{
// If d is more than capacity of
// jugs than not possible
if (d > n && d > m)
return false;
// If gcd of n and m does not divide d
// then solution is not possible
return ((d % gcd(m, n)) == 0);
}
int main()
{
int n = 3, m = 5, d = 4;
cout << isFeasible(m, n, d);
return 0;
}
Java
class GfG {
// Utility function to return GCD of 'a' and 'b'.
public static int gcd(int m, int n) {
if (n == 0)
return m;
return gcd(n, m % n);
}
// Returns true if we can get d litre water in
// one of the two jugs
public static boolean isFeasible(int m, int n, int d) {
// If d is more than capacity of jugs,
// then not possible
if (d > n && d > m)
return false;
// If gcd of n and m does not divide d,
// then solution is not possible
return (d % gcd(m, n) == 0);
}
public static void main(String[] args) {
int n = 3, m = 5, d = 4;
System.out.println(isFeasible(m, n, d));
}
}
Python
import math
# Utility function to return GCD of 'a' and 'b'
def gcd(m, n):
return math.gcd(m, n)
# Returns true if we can get d litre water
# in one of the two jugs
def is_feasible(m, n, d):
# If d is more than capacity of jugs,
# then not possible
if d > n and d > m:
return False
# If gcd of n and m does not divide d,
# then solution is not possible
return d % gcd(m, n) == 0
if __name__ == "__main__":
n = 3
m = 5
d = 4
print(is_feasible(m, n, d))
Get d litre in Both Jugs
Our target amount d should be present in both jugs combined. Let us understand this problem with the below examples.
Input: m = 2, n = 3, d = 5
Output: Yes
Explanation:
1. Fill up the 3 litre jug.
2.Fill up the 2 litre jug
Input: m = 3, n = 5, d = 4
Output: Yes
Explanation:
1. Fill up the 5 litre jug.
2. Then fill up the 3 litre jug using 5 litre jug. Now 5 litre jug contains 2 litre water.
3. Empty the 3 litre jug.
4. Now pour the 2 litre of water from 5 litre jug to 3 litre jug.
5. Now 3 litre jug contains 2 litre of water and 5 litre jug is empty. Now fill up the 5 litre jug.
6. Now fill one litre of water from 5 litre jug to 3 litre jug. Now we have 4 litre water in 5 litre jug
7. Empty the 3 litre jug
Input: m = 2, n = 4, d = 3
Output: No
Explanation: Not possible
This problem is mainly a simple variation of the above problem. The solution is again to check if GCD of m an n divides d or not. Also our base condition changes now. We need to check if d > (m+n), then we return false.
C++
// C++ program to check if we can get d
// litre water in tow jjugs combined.
#include <bits/stdc++.h>
using namespace std;
// Utility function to return GCD of 'm'
// and 'n'.
int gcd(int m, int n)
{
if (n == 0)
return m;
return gcd(n, m % n);
}
// Returns count of minimum steps needed to
// measure d liter
bool isFeasible(int m, int n, int d)
{
// If d is more than total capacity
// of jugs then not possible
if (d > (n + m))
return false;
// If gcd of n and m does not divide d
// then solution is not possible
return ((d % gcd(m, n)) == 0);
}
// Driver code to test above
int main()
{
int n = 3, m = 2, d = 5;
cout << isFeasible(m, n, d);
return 0;
}
Java
class GfG {
// Utility function to return GCD of 'm' and 'n'.
public static int gcd(int m, int n) {
if (n == 0)
return m;
return gcd(n, m % n);
}
// Returns true if it is feasible to get 'd' liters by
// combining the jugs
public static boolean isFeasible(int m, int n, int d) {
// If d is more than total capacity of jugs,
// then not possible
if (d > (n + m))
return false;
// If gcd of n and m does not divide d,
// then solution is not possible
return (d % gcd(m, n) == 0);
}
public static void main(String[] args) {
int n = 3, m = 2, d = 5;
System.out.println(isFeasible(m, n, d));
}
}
Python
import math
# Returns true if it is feasible to get 'd'
# liters by combining the jugs
def is_feasible(m, n, d):
# If d is more than total capacity of jugs,
# then not possible
if d > (n + m):
return False
# If gcd of n and m does not divide d,
# then solution is not possible
return d % math.gcd(m, n) == 0
if __name__ == "__main__":
n = 3
m = 2
d = 5
print(is_feasible(m, n, d))
Count Minimum Steps
Here we need to find minimum steps to fill d litre in one of the two jugs.
Input: m = 2, n = 3, d = 1
Output: 2
Explanation:
1. Fill up the 3 litre jug
2. Pour 2 litre of water from the 3 litre Jug to 2 litre Jug, Now the 3 litre jug has 1 litre water.
Input: m = 3, n = 5, d = 4
Output: 6
Explanation:
1. Fill up the 5 litre jug.
2. Then fill up the 3 litre jug using 5 litre jug. Now 5 litre jug contains 2 litre water.
3. Empty the 3 litre jug.
4. Now pour the 2 litre of water from 5 litre jug to 3 litre jug.
5. Now 3 litre jug contains 2 litre of water and 5 litre jug is empty. Now fill up the 5 litre jug.
6. Now fill one litre of water from 5 litre jug to 3 litre jug. Now we have 4 litre water in 5 litre jug
Input: m = 2, n = 3, d = 5
Output: -1
Explanation: We need to fill in one jug only
Input: m = 2, n = 4, d = 3
Output: -1
Explanation: Not possible
Please refer The Water Jug Problem â Count Min Steps for solution of this.
We can also solve count minimum steps using BFS.
Similar Reads
Water Jug Problem -Complete Tutorial
You are given a m liter jug and a n liter jug where 0 < m < n. Both the jugs are initially empty. The jugs donât have markings to allow measuring smaller quantities. You have to use the jugs to measure d liters of water where d < n. Determine the minimum no of operations to be performed to
10 min read
Water Jug problem using BFS
Given two empty jugs of m and n litres respectively. The jugs don't have markings to allow measuring smaller quantities. You have to use the jugs to measure d litres of water. The task is to find the minimum number of operations to be performed to obtain d litres of water in one of the jugs. In case
12 min read
Puzzle | Water Jug Problem
We have two water jugs, one measures 4 Gallons (4G) while the other measure 9 Gallons (9G). But there is no measuring label mentioned on either of these two jugs i.e. we cannot know the exact amount filled in the jug. Now, assuming there is an infinite amount of water supply, can we measure all 1G,
2 min read
The Water Jug Problem - Count Min Steps
You are given a m liter jug and a n liter jug where 0 < m < n. Both the jugs are initially empty. The jugs donât have markings to allow measuring smaller quantities. You have to use the jugs to measure d liters of water where d < n. Determine the minimum no of operations to be performed to
14 min read
Water Connection Problem
Every house in the colony has at most one pipe going into it and at most one pipe going out of it. Tanks and taps are to be installed in a manner such that every house with one outgoing pipe but no incoming pipe gets a tank installed on its roof and every house with only an incoming pipe and no outg
11 min read
Water drop problem
Consider a pipe of length L. The pipe has N water droplets at N different positions within it. Each water droplet is moving towards the end of the pipe(x=L) at different rates. When a water droplet mixes with another water droplet, it assumes the speed of the water droplet it is mixing with. Determi
10 min read
Minimum cost to provide water
Given an integer N, where N denotes the number of villages numbered 1 to N, an array wells[] where wells[i] denotes the cost to build a water well in the i'th city, a 2D array pipes in form of [X Y C] which denotes that the cost to connect village X and Y with water pipes is C. Your task is to provi
11 min read
Water Jug Problem using Memoization
Given two jugs with the maximum capacity of m and n liters respectively. The jugs don't have markings on them which can help us to measure smaller quantities. The task is to measure d liters of water using these two jugs. Hence our goal is to reach from initial state (m, n) to final state (0, d) or
9 min read
Trapping Rain Water Problem - Tutorial with Illustrations
Trapping Rainwater Problem states that given an array of n non-negative integers arr[] representing an elevation map where the width of each bar is 1, compute how much water it can trap after rain. Examples: Input: arr[] = [3, 0, 1, 0, 4, 0, 2]Output: 10Explanation: The expected rainwater to be trap
15+ min read
Number of refills to complete the journey of N km
Given a number N which represents the total distance in km to be covered by a car on a single road. There are N petrol pumps at a distance of 1 km each(1, 2, 3, ..N). The capacity of the fuel tank of the car is such that at full tank it goes till a distance of K km. The car has to compulsorily stop
8 min read