Glasses are stacked in a pyramid: row 0 has one glass, row 1 has two, and so on, down to row 99. Each glass holds exactly one cup.
You pour poured cups into the top glass. Once a glass is full, whatever more reaches it spills out, half onto each of the two glasses just below it. Champagne spilling from the bottom row is lost.
Return how full glass query_glass of row query_row is, as a number from 0 to 1. Rows and glasses are numbered from 0.
Example 1
Input: poured = 5, query_row = 2, query_glass = 0 Output: 0.5 Why: row 1 spills 1 cup per glass; the edge glass gets half of one
2 more examples and the constraints
Example 2
Input: poured = 3, query_row = 2, query_glass = 1 Output: 0.0 Why: 3 cups fill rows 0 and 1 exactly, with nothing left over
Example 3
Input: poured = 5, query_row = 2, query_glass = 1 Output: 1.0 Why: the middle glass gets 0.5 from each side
Constraints
- 0 ≤ poured ≤ 1,000,000,000
- 0 ≤ query_glass ≤ query_row < 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Full flow tableO(R²)
- One row at a timeO(R²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Memory for 100 rows | Verdict |
|---|---|---|---|
| Full flow table | O(R²) | Simple; stores every row | |
| One row at a time | O(R²) | Best; same time, two rows |
R = query_row + 1. The bars compare memory; both take the same time.
Edge cases to test
- Nothing poured. poured = 0 leaves every glass empty: 0.
- The top glass. query_row = 0 returns
min(1, poured), so 1 when poured ≥ 1. - Exactly full rows. 3 cups fill rows 0 and 1 and leave row 2 empty.
- Huge pour. A billion cups fill even deep glasses; cap the total at 1.
- Edge glasses. Glass 0 and the last glass of a row get only one parent, so they fill more slowly than the middle.
Common mistakes
- Returning the total that reached the glass without capping it at 1.
- Spilling the whole amount instead of the amount minus the cup the glass keeps.
- Using integer division for the half, which drops the 0.5 values.
How to talk through it
- 1Clarify. Does a glass keep exactly 1 cup? Are rows and glasses 0-indexed? What precision is needed?
- 2Drop the per-cup idea. A billion single pours is too slow; only the total reaching each glass matters.
- 3Set up the flow. Each glass keeps 1 and passes half the excess to each glass below; rows depend only on the row above.
- 4Code two rows. row and nxt, swap after each row, cap the answer at 1.
- 5Test out loud. Run 0 cups, 3 cups to row 2, and a huge pour deep down before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?