Glass Pyramid Water Flow - Problem

Water is poured into the top glass of a pyramid structure. When a glass becomes full, it overflows equally into the two glasses directly below it. Given the amount of water poured and the position of a specific glass, find how much water is in that glass.

The pyramid is structured such that:

  • Row 0 has 1 glass
  • Row 1 has 2 glasses
  • Row r has (r+1) glasses

Each glass has a capacity of 1.0 liter. When a glass overflows, the excess water is split equally between the two glasses below it.

Input:

  • poured: Amount of water poured (double)
  • query_row: Row of the target glass (integer)
  • query_glass: Column position in that row (integer)

Output:

Return the amount of water in the glass at position (query_row, query_glass).

Input & Output

Example 1 — Basic Water Flow
$ Input: poured = 1.0, query_row = 1, query_glass = 1
Output: 0.0
💡 Note: Pour 1.0 liter into top glass. Top glass holds exactly 1.0, no overflow. Glasses in row 1 remain empty.
Example 2 — Overflow Distribution
$ Input: poured = 2.0, query_row = 1, query_glass = 1
Output: 0.5
💡 Note: Pour 2.0 liters. Top glass holds 1.0, overflow 1.0 splits equally: 0.5 to each glass in row 1.
Example 3 — Deep Pyramid
$ Input: poured = 100000009.0, query_row = 33, query_glass = 17
Output: 1.0
💡 Note: Massive amount of water ensures all glasses in upper rows are full. Glass at (33,17) will be completely full.

Constraints

  • 0 ≤ poured ≤ 109
  • 0 ≤ query_row ≤ 99
  • 0 ≤ query_glass ≤ query_row

Visualization

Tap to expand
INPUT DATAALGORITHM STEPSFINAL RESULT2.0Poured Water?Query: Row 2, Glass 11Initialize DP table2Pour water into top glass3Process overflow row by row4Return query resultDP TableRow 0: [1.0]Row 1: [0.5, 0.5]Row 2: [0.25, 0.5, 0.25]Water Amount0.5Glass at (2,1) contains0.5 liters of waterKey Insight:Water cascades predictably through the pyramid structure. Each glass can holdexactly 1.0 liter, with overflow splitting equally to the two glasses below it.TutorialsPoint - Glass Pyramid Water Flow | Bottom-Up DP
Asked in
Google 35 Microsoft 28 Amazon 22 Facebook 18
34.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen