Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Beams connect devices only between consecutive nonempty rows; empty rows do not block them. If those rows contain a and b devices, every cross-row pair forms a beam, contributing a*b.
Approach
Scan rows and count their ones. For a nonempty row, add its device count multiplied by the previous nonempty row's count, then remember the current count. For an empty row, leave the remembered count unchanged. Initialize it to zero so the first nonempty row contributes no beams. Return the accumulated products without examining individual device pairs or column positions.
class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
prev = 0
res = 0
for row in bank:
curr = sum(1 if x == '1' else 0 for x in row)
if curr > 0:
res += curr * prev
prev = curr
return resComplexity analysis
Let C be the total number of characters in the bank. Both displayed implementations scan every character once, taking O(C) time and O(1) auxiliary space.
