Python 0799.py
class Solution:
def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
# store how much champagne was poured into each glass,
# including everything that spilled over
row = [ poured ]
for i in range(query_row):
next = [ 0.5 * max(0, row[0] - 1) ] # all but 1 unit overflows, 50% to each side
for j in range(i):
next.append(0.5 * max(0, row[j] - 1) + 0.5 * max(0, row[j + 1] - 1))
next.append(next[0]) # right-most glass is identical to left-most
# actually all glasses on the right half are
# identical to the left half
# so we could save roughly 50% of computations
row = next
result = row[query_glass]
return min(result, 1) # return at most 1, the rest spilled over
Difficulty
and has an acceptance rate of about 64% (300k+ submissions).
Typical patterns to solve this problem:
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the amount of champagne in a specific glass of a pyramid after a given volume has been poured. It simulates the flow row by row, keeping only the current row’s values in memory. The algorithm stops once it reaches the target row, then extracts the content of the requested glass and caps the result at the glass capacity of one unit.
Core Logic
Initialization
The algorithm starts by representing the top glass as a single-element list containing the total poured volume.
row = [poured]
This list holds the cumulative amount that has entered each glass of the current row, including any overflow that will be distributed to the next row.
Row-by-Row Propagation
A loop iterates from the first row up to the row preceding the query row. For each iteration a new list next is built that represents the overflow contributions to the glasses of the next row.
for i in range(query_row):
next = [0.5 * max(0, row[0] - 1)]
for j in range(i):
next.append(0.5 * max(0, row[j] - 1) + 0.5 * max(0, row[j + 1] - 1))
next.append(next[0])
row = next
- The first element of
nextreceives half of the overflow from the leftmost glass of the current row. The overflow is calculated as the amount exceeding the glass capacity (row[0] - 1), clamped to a non-negative value withmax(0, …), and then split equally between the two glasses below. - The inner loop processes the interior glasses. Each interior glass receives half of the overflow from the glass directly above-left and half from the glass directly above-right. The same overflow calculation and halving are applied.
- The rightmost glass of the new row is set equal to the leftmost entry (
next.append(next[0])). This exploits the symmetry of the pyramid: the leftmost and rightmost glasses receive identical overflow because the pyramid is mirrored around its center.
After constructing next, the reference row is updated to point to this newly computed row, discarding the previous row’s data.
Extracting the Result
When the loop finishes, row corresponds to the query row. The amount in the requested glass is read directly from the list.
result = row[query_glass]
return min(result, 1)
The final min call ensures that the returned value never exceeds the glass capacity of one unit, effectively discarding any remaining overflow that would spill out of the pyramid.
Edge Cases Handled
- Zero or Negative Overflow - The expression
max(0, row[k] - 1)guarantees that a glass that is not full contributes no overflow to the row below. This prevents negative values from propagating. - Query at the Top Glass - When
query_rowis zero, the outer loop does not execute, leavingrowas the initial list[poured]. The subsequent extraction correctly returns the poured amount capped at one. - Large Poured Volumes - The algorithm does not assume any upper bound on
poured. By repeatedly applying the overflow formula, it correctly distributes arbitrarily large quantities across many rows, with each intermediate overflow being halved at each step. - Out-of-Range Glass Index - The code assumes that
query_glassis a valid index within the target row (i.e.,0 ≤ query_glass ≤ query_row). Under this precondition, the direct list access is safe. - Symmetric Row Completion - By mirroring the leftmost overflow to the rightmost position, the implementation correctly handles rows where the number of glasses is odd or even, preserving the pyramid’s symmetry without explicit handling of each side.
Performance Optimizations Observed
- Single-Row Memory Footprint - Only the current row is stored at any time. The previous row is discarded after its overflow contributions have been transferred, keeping memory usage proportional to the width of the current row rather than the entire pyramid.
- Symmetry Exploitation - The rightmost glass is derived from the leftmost value (
next.append(next[0])). This eliminates the need to compute the overflow for the rightmost glass separately, reducing the number of arithmetic operations roughly by half for each row. - Early Termination - The loop stops as soon as the target row is reached. No further rows are generated, which prevents unnecessary computation when the query lies high in the pyramid.
- Avoidance of Conditional Branches - The overflow calculation uses
max(0, …)instead of an explicitifstatement, allowing the interpreter to evaluate the expression in a straightforward arithmetic manner. This can lead to marginally faster execution in tight loops.
ELI5 - Simplified Explanation
Imagine a tall tower made of glass cups stacked in a triangle shape. When somebody pours champagne into the cup at the very top, it fills up. If there is more champagne than the glass can hold, the extra liquid spills out equally into the two cups sitting right below it. This continues all the way down the tower as more champagne spills from one level to the next.
The code acts like a helper who keeps track of how much liquid is in each cup. It starts with the top glass holding all the poured liquid. Then, it looks at the current row and calculates how much extra liquid spills over from each cup. It moves down the tower row by row, doing the math to figure out how much liquid reaches the specific cup you are pointing at. By the time it finishes, it knows exactly how much champagne is sitting in that one glass. If a cup tries to hold more than it can fit, the code remembers that the cup is just full and the rest moved on.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | ||||||||
| leetcode.ca | C++ | Java | Python | Rust | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| withaarzoo | C++ | |||||||||
| yuanliu666 | Kotlin | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| withaarzoo | C++ | |||||||||
| yuanliu666 | Kotlin |
Videos
Similar Problems
- problem 2189: Number of Ways to Build House of Cards
Solved On The Same Day
- problem 888: Fair Candy Swap
- problem 917: Reverse Only Letters
- problem 846: Hand of Straights
- problem 853: Car Fleet
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality