Python 2125.py
class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
result = 0
prev = 0
for b in bank:
devices = b.count("1")
if devices > 0:
result += devices * prev
prev = devices
return result
Difficulty
and has an acceptance rate of about 87% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
- Matrix
- String
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 defines a Solution class with a single method numberOfBeams. The method receives a list of strings, each string representing a row of a security device layout where '1' indicates the presence of a device and '0' indicates empty space. The goal is to compute the total number of laser beams that can be formed between devices in consecutive rows that contain at least one device. A beam is counted for every pair formed by a device in the current row and a device in the previous non-empty row.
Key Steps
The algorithm proceeds with a single pass over the input list.
result = 0
prev = 0
for b in bank:
devices = b.count("1")
if devices > 0:
result += devices * prev
prev = devices
return result
The first step initializes two accumulators: result to store the running total of beams and prev to remember the number of devices in the most recent row that contained at least one device.
During each iteration the code counts the '1' characters in the current row using the built-in count method. This count, stored in devices, represents the number of devices in the current row.
If the current row is empty (devices equals zero) the loop simply moves to the next row, leaving both result and prev unchanged.
When the row is non-empty, the algorithm adds the product of devices and prev to result. This product corresponds to all possible beams between every device in the current row and every device in the previous non-empty row. After updating result, prev is set to devices so that the next non-empty row will use the current row as its predecessor.
Finally, after processing all rows, the method returns the accumulated result.
Edge Cases Handled
The code gracefully handles rows that contain no devices. By checking if devices > 0 before performing any arithmetic, it ensures that empty rows do not contribute to the beam count and do not disturb the prev value. This means that sequences of empty rows are effectively ignored, and the beam calculation only involves pairs of consecutive rows that both contain devices.
If the input list is empty, the loop body never executes, leaving result at its initial value of zero, which correctly reflects that no beams can be formed.
When the first row in the list contains devices, prev is initially zero, so the first addition to result yields zero, correctly representing that there is no preceding row to form beams with.
Rows that consist entirely of '0' characters are treated identically to empty rows, as the count method returns zero, triggering the same bypass logic.
Performance Optimizations
The implementation leverages Python’s native string method count, which is implemented in C and runs in linear time relative to the length of the string. This avoids the overhead of manual character iteration in Python code.
By maintaining only two integer variables (result and prev) and updating them in place, the algorithm uses constant additional memory regardless of the size of the input.
The single-pass design eliminates the need for auxiliary data structures such as lists of device counts or nested loops, thereby reducing the overall amount of work performed.
The multiplication devices * prev is performed only when both operands are non-zero, which avoids unnecessary arithmetic for rows that do not contribute to the final count.
Overall, the code achieves an efficient solution by combining built-in string processing with a minimal stateful loop.
ELI5 - Simplified Explanation
Imagine a long hallway filled with rows of glowing light bulbs. Each row is a string of characters where a one represents a working bulb and a zero represents something else. The goal is to connect these bulbs with laser beams.
The code starts by looking at each row one by one. It counts how many ones are in the current row. If it finds even one light, that row is ready to shine. It takes the number of bulbs in the current row and multiplies that by the number of bulbs from the last row that were already glowing. This creates a set of laser beams between those rows. After connecting the beams, the current row becomes the new reference point, or the previous row, for the next group of bulbs. This process repeats until every row has been checked, adding up all the connections made along the way.
Code Quality
Complexity Analysis
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++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | C | Rust | TS | ||||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| pruthvikp | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| withaarzoo | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| pruthvikp | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 73: Set Matrix Zeroes
Solved On The Same Day
- problem 1313: Decompress Run-Length Encoded List
- problem 1678: Goal Parser Interpretation
- problem 2652: Sum Multiples
- problem 2859: Sum of Values at Indices With K Set Bits
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