Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Program to find amount of water in a given glass
Next article icon

Program to find amount of water in a given glass

Last Updated : 12 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

There is a stack of water glasses in the form of a Pascal triangle and a person wants to pour the water at the topmost glass, but the capacity of each glass is 1 unit. Overflow occurs in such a way that after 1 unit, 1/2 of the remaining unit gets into the bottom left glass and the other half in the bottom right glass. We pour k units of water into the topmost glass. The task is to find how much water is there in the c'th glass of the r'th row.

Note: Assume that there are enough glasses in the triangle till no glass overflows.

Example:

Input: k = 3, r = 2, c = 1
Output: 1.000000
Explanation: After the first glass, 2 units of water will remain and they will spread equally on the two glasses on the second row. Therefore, the glass on the 2nd row and 1st column will have 1 unit of water.

water-overflow-1


Input: k = 2, r = 2, c = 2
Output: 0.5
Explanation: After the first glass, 1 units of water will remain and they will spread equally on the two glasses on the second row. Therefore, the glass on the 2nd row and 2nd column will have half unit of water.

water-overflow-2

Table of Content

  • Using Dynamic Programming - O(r^2) time and O(r^2) Space
  • Using Queue - O(r^2) Time and O(r) Space

Using Dynamic Programming - O(r^2) time and O(r^2) Space

The approach to solving the water overflow problem involves simulating water distribution through a grid-based representation of a Pascal triangle of glasses. The process starts by pouring a given amount of water into the top glass. Then, for each glass, the algorithm checks if the water exceeds the glass's capacity of 1 unit. If overflow occurs, the excess water is evenly distributed to the two glasses directly below. Each glass is capped at a maximum of 1 unit. This process is repeated iteratively until the target row is reached. The final result is the amount of water in the specified glass, ensuring no glass exceeds its maximum capacity.

C++
// C++ program to find amount // of water in a given glass Using Dynamic Programming #include <bits/stdc++.h> using namespace std;  double waterOverflow(int k, int r, int c) {          // DP matrix to simulate water flow in glasses     vector<vector<double>> memo(r, vector<double>(r, 0.0));          // Initial water in top glass     memo[0][0] = k;          // Simulate water flow through triangle     for (int row = 0; row < r - 1; row++) {         for (int col = 0; col <= row; col++) {                          // Calculate water overflow             double excess = max(0.0, memo[row][col] - 1.0);                          // Distribute excess water             if (excess > 0) {                                  // Cap current glass                 memo[row][col] = 1.0;                                  // Flow to bottom glasses                 memo[row + 1][col] += excess / 2.0;                 memo[row + 1][col + 1] += excess / 2.0;             }         }     }          // Return water in target glass     return min(1.0, memo[r - 1][c - 1]); }  int main() {     int k = 3;     int r = 2;     int c = 1;          double waterAmount = waterOverflow(k, r, c);     cout << waterAmount << endl;          return 0; } 
Java
// Java program to find amount // of water in a given glass Using Dynamic Programming import java.util.*;  class GfG {  	static double waterOverflow(int k, int r, int c) {  		// DP matrix to simulate water flow in glasses 		double[][] memo = new double[r][r];  		// Initial water in top glass 		memo[0][0] = k;  		// Simulate water flow through triangle 		for (int row = 0; row < r - 1; row++) { 			for (int col = 0; col <= row; col++) {  				// Calculate water overflow 				double excess = Math.max(0.0, memo[row][col] - 1.0);  				// Distribute excess water 				if (excess > 0) {  					// Cap current glass 					memo[row][col] = 1.0;  					// Flow to bottom glasses 					memo[row + 1][col] += excess / 2.0; 					memo[row + 1][col + 1] += excess / 2.0; 				} 			} 		}  		// Return water in target glass 		return Math.min(1.0, memo[r - 1][c - 1]); 	}  	public static void main(String[] args) { 		int k = 3; 		int r = 2; 		int c = 1;  		double waterAmount = waterOverflow(k, r, c); 		System.out.println(waterAmount); 	} } 
Python
# Python program to find amount   # of water in a given glass Using Dynamic Programming  def waterOverflow(k, r, c):          # DP matrix to simulate water flow in glasses     memo = [[0.0 for _ in range(r)] for _ in range(r)]          # Initial water in top glass     memo[0][0] = k          # Simulate water flow through triangle     for row in range(r - 1):         for col in range(row + 1):                          # Calculate water overflow             excess = max(0.0, memo[row][col] - 1.0)                          # Distribute excess water             if excess > 0:                                  # Cap current glass                 memo[row][col] = 1.0                                  # Flow to bottom glasses                 memo[row + 1][col] += excess / 2.0                 memo[row + 1][col + 1] += excess / 2.0          # Return water in target glass     return min(1.0, memo[r - 1][c - 1])   if __name__ == "__main__":     k = 3     r = 2     c = 1          waterAmount = waterOverflow(k, r, c)     print(waterAmount) 
C#
// C# program to find amount // of water in a given glass Using Dynamic Programming using System;  class GfG {  	static double waterOverflow(int k, int r, int c) {  		// DP matrix to simulate water flow in glasses 		double[,] memo = new double[r, r];  		// Initial water in top glass 		memo[0, 0] = k;  		// Simulate water flow through triangle 		for (int row = 0; row < r - 1; row++) { 			for (int col = 0; col <= row; col++) {  				// Calculate water overflow 				double excess = Math.Max(0.0, memo[row, col] - 1.0);  				// Distribute excess water 				if (excess > 0) {  					// Cap current glass 					memo[row, col] = 1.0;  					// Flow to bottom glasses 					memo[row + 1, col] += excess / 2.0; 					memo[row + 1, col + 1] += excess / 2.0; 				} 			} 		}  		// Return water in target glass 		return Math.Min(1.0, memo[r - 1, c - 1]); 	}  	static void Main(string[] args) { 		int k = 3; 		int r = 2; 		int c = 1;  		double waterAmount = waterOverflow(k, r, c); 		Console.WriteLine(waterAmount); 	} } 
JavaScript
// JavaScript program to find amount // of water in a given glass Using Dynamic Programming  function waterOverflow(k, r, c) {      // DP matrix to simulate water flow in glasses 	let memo = Array.from({ length: r }, () => Array(r).fill(0.0));      // Initial water in top glass 	memo[0][0] = k;      // Simulate water flow through triangle 	for (let row = 0; row < r - 1; row++) { 		for (let col = 0; col <= row; col++) {  			// Calculate water overflow 			let excess = Math.max(0.0, memo[row][col] - 1.0);  			// Distribute excess water 			if (excess > 0) {  				// Cap current glass 				memo[row][col] = 1.0;  				// Flow to bottom glasses 				memo[row + 1][col] += excess / 2.0; 				memo[row + 1][col + 1] += excess / 2.0; 			} 		} 	}      // Return water in target glass 	return Math.min(1.0, memo[r - 1][c - 1]); }  let k = 3; let r = 2; let c = 1; console.log(waterOverflow(k, r, c)); 

Output
1 

Using Queue - O(r^2) Time and O(r) Space

The approach simulates the water overflow process using a queue to track water distribution through a Pascal triangle of glasses. The algorithm processes glasses row by row, managing overflow by distributing excess water equally to the glasses below. It ensures that no glass exceeds its 1-unit capacity, using the queue to efficiently handle water amounts and overflow at each step. The water in each glass is updated progressively, and the target glass’s water amount is returned once the process reaches the specified row and column.

C++
// C++ program to find amount  // of water in a given glass using queue #include <bits/stdc++.h> using namespace std;  double waterOverflow(int k, int r, int c) {          r--;     c--;      // Initialize queue with total water units     queue<double> q;     q.push(1.0*k);      // Variable to track overflow from previous glasses     double prev = 0;      // Simulate water flow row by row     for (int i = 0; i <= r; i++) {                  // Process current row's glasses         int size = q.size();         for (int j = 0; j < size; j++) {                          // Get current glass water amount             double curr = q.front();              // Check if target glass is reached             if (i == r && j == c) return min(curr, 1.0);              // Reduce water in current glass             curr--;             q.pop();              // Calculate and distribute overflow             double val = max(curr/2.0, 0.0) + prev;             q.push(val);              // Track overflow for next iteration             prev = max(0.0, curr/2.0);         }          // Add previous row's overflow to next row         q.push(prev);         prev = 0;     }      return 0; }  int main() {      	int k = 3;     int r = 2;     int c = 1;      cout << waterOverflow(k, r, c);     return 0; } 
Java
// Java program to find amount  // of water in a given glass using queue import java.util.*;  class GfG {      static double waterOverflow(int k, int r, int c) {                  // Adjust row and column to 0-based indexing         r--;         c--;          // Initialize queue with total water units         Queue<Double> q = new LinkedList<>();         q.add(1.0 * k);          // Variable to track overflow from        	// previous glasses         double prev = 0;          // Simulate water flow row by row         for (int i = 0; i <= r; i++) {                          // Process current row's glasses             int size = q.size();             for (int j = 0; j < size; j++) {                                  // Get current glass water amount                 double curr = q.poll();                  // Check if target glass is reached                 if (i == r && j == c) return Math.min(curr, 1.0);                  // Reduce water in current glass                 curr--;                  // Calculate and distribute overflow                 double val = Math.max(curr / 2.0, 0.0) + prev;                 q.add(val);                  // Track overflow for next iteration                 prev = Math.max(0.0, curr / 2.0);             }              // Add previous row's overflow to next row             q.add(prev);             prev = 0;         }          return 0;     }      public static void main(String[] args) {              	int k = 3; 		int r = 2; 		int c = 1;         System.out.println(waterOverflow(k, r, c));     } } 
Python
# Python program to find amount  # of water in a given glass using queue from collections import deque  def waterOverflow(k, r, c):          # Adjust row and column to 0-based indexing     r -= 1     c -= 1      # Initialize queue with total water units     q = deque([1.0 * k])      # Variable to track overflow from previous glasses     prev = 0      # Simulate water flow row by row     for i in range(r + 1):                  # Process current row's glasses         size = len(q)         for j in range(size):                          # Get current glass water amount             curr = q.popleft()              # Check if target glass is reached             if i == r and j == c:                 return min(curr, 1.0)              # Reduce water in current glass             curr -= 1              # Calculate and distribute overflow             val = max(curr / 2.0, 0.0) + prev             q.append(val)              # Track overflow for next iteration             prev = max(0.0, curr / 2.0)          # Add previous row's overflow to next row         q.append(prev)         prev = 0      return 0  if __name__ == "__main__":     k = 3     r = 2     c = 1     print(waterOverflow(k, r, c)) 
C#
// C# program to find amount  // of water in a given glass using queue using System; using System.Collections.Generic;  class GfG {      static double waterOverflow(int k, int r, int c) {                  // Adjust row and column to 0-based indexing         r--;         c--;          // Initialize queue with total water units         Queue<double> q = new Queue<double>();         q.Enqueue(1.0 * k);          // Variable to track overflow from previous glasses         double prev = 0;          // Simulate water flow row by row         for (int i = 0; i <= r; i++) {                          // Process current row's glasses             int size = q.Count;             for (int j = 0; j < size; j++) {                                  // Get current glass water amount                 double curr = q.Dequeue();                  // Check if target glass is reached                 if (i == r && j == c) return Math.Min(curr, 1.0);                  // Reduce water in current glass                 curr--;                  // Calculate and distribute overflow                 double val = Math.Max(curr / 2.0, 0.0) + prev;                 q.Enqueue(val);                  // Track overflow for next iteration                 prev = Math.Max(0.0, curr / 2.0);             }              // Add previous row's overflow to next row             q.Enqueue(prev);             prev = 0;         }          return 0;     }      static void Main(string[] args) {              	int k = 3; 		int r = 2; 		int c = 1;         Console.WriteLine(waterOverflow(k, r, c));     } } 
JavaScript
// JavaScript program to find amount  // of water in a given glass using queue  function waterOverflow(k, r, c) {          // Adjust row and column to 0-based indexing     r--;     c--;      // Initialize queue with total water units     let q = [];     q.push(1.0 * k);      // Variable to track overflow from previous glasses     let prev = 0;      // Simulate water flow row by row     for (let i = 0; i <= r; i++) {                  // Process current row's glasses         let size = q.length;         for (let j = 0; j < size; j++) {                          // Get current glass water amount             let curr = q.shift();              // Check if target glass is reached             if (i === r && j === c) return Math.min(curr, 1.0);              // Reduce water in current glass             curr--;              // Calculate and distribute overflow             let val = Math.max(curr / 2.0, 0.0) + prev;             q.push(val);              // Track overflow for next iteration             prev = Math.max(0.0, curr / 2.0);         }          // Add previous row's overflow to next row         q.push(prev);         prev = 0;     }      return 0; }  let k = 3; let r = 2; let c = 1; console.log(waterOverflow(k, r, c)); 

Output
1

Next Article
Program to find amount of water in a given glass

K

kartik
Improve
Article Tags :
  • Dynamic Programming
  • Mathematical
  • Recursion
  • DSA
  • Amazon
  • D-E-Shaw
Practice Tags :
  • Amazon
  • D-E-Shaw
  • Dynamic Programming
  • Mathematical
  • Recursion

Similar Reads

    Find amount of water wasted after filling the tank
    Given the volume V of a tank in liter. There is a pump which is filling the tank at speed of M liter per minute. There is a leakage at the bottom of the tank which wasting water at speed N liter per minute. Given N is less than M. The task is to calculate how much amount of water will be wasted if l
    5 min read
    Program to find the Area and Volume of Icosahedron
    Given the side of an Icosahedron. The task is to find the area and volume of the given Icosahedron.Examples : Input : a = 5 Output : Area: 216.506 Volume: 272.712 Input : a = 10 Output : Area: 866.0254 Volume: 2181.695 In geometry, an Icosahedron is a regular polyhedron which contains 20 identical e
    5 min read
    Find amount to be added to achieve target ratio in a given mixture
    You are given a container of X liters containing a mixture of wine and water. The mixture contains W% of water in it. How many liters of water must be added to increase the ratio of water to Y%? The input includes 3 integers: X, W, and Y respectively. The output should be in float format up to 2 dec
    4 min read
    Count of operation required to water all the plants
    Given an array arr[] of N integers where ith element represents the amount of water required by the plant at ith index and an integer K, the task is to calculate the count of operations required to water all the plants using a container that can hold at most K liters of water wherein each operation,
    6 min read
    Program for focal length of a lens
    Write a program to determine the focal length of a lens.Focal length is the distance between the center of the lens to the principal foci. In order to determine the focal length of a lens we should know the distance between the lens and the image ( I ) and the distance between the lens and the objec
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences