VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-water-in-a-glass/

⇱ Program to find amount of water in a given glass - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to find amount of water in a given glass

Last Updated : 23 Jul, 2025

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

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.


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.


Output
1
Comment