Number of Laser Beams in a Bank — LeetCode 2125 Python Solution

MediumArrayMathStringMatrix
Problem
#2125
Reading time
2 min

The problem

Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix.

Example

Input
bank = ["011001","000000","010100","001000"]
Output
8
Explanation
Between each of the following device pairs, there is one beam. In total, there are 8 beams:

Python solution

Python
class Solution:
    def numberOfBeams(self, bank: List[str]) -> int:
        ans = pre = 0
        for row in bank:
            if (cur := row.count("1")) > 0:
                ans += pre * cur
                pre = cur
        return ans

Complexity

MeasureComplexity
TimeO(m \times n), where m and n are the number of rows and columns, respectively
SpaceO(1) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2125. Number of Laser Beams in a Bank is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2125. Number of Laser Beams in a Bank?
LeetCode 2125. Number of Laser Beams in a Bank is rated Medium on LeetCode.
What is the time complexity of LeetCode 2125. Number of Laser Beams in a Bank?
The Python solution on this page runs in O(m \times n), where m and n are the number of rows and columns, respectively.
What is the space complexity of LeetCode 2125. Number of Laser Beams in a Bank?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2125. Number of Laser Beams in a Bank cover?
LeetCode 2125. Number of Laser Beams in a Bank is tagged Array, Math, String and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview