LeetCode Challenge Day 42 β 2125. Number of Laser Beams in a Bank
Nitin Ahirwal / October 27, 2025
Hey folks
This is Day 42 of my LeetCode streak π.
Todayβs problem is 2125. Number of Laser Beams in a Bank β a matrix simulation problem where we count beams formed by security devices placed in rows.
π Problem Statement
You are given a binary string array bank representing rows of a bank security floor.
'1'represents a security device.'0'means no device.
A laser beam is formed between two devices in different rows if and only if all rows between them are empty (contain no devices).
Return the total number of beams.
π‘ Intuition
Beams only occur between consecutive non-empty rows.
So we can:
- Count the number of devices in each row.
- For every non-empty row, multiply its count with the previous non-empty rowβs count.
- Accumulate the result.
π Approach
- Initialize
prev = 0(count of devices in last non-empty row) andbeams = 0. - Traverse each row:
- Count devices (
curr). - If
curr > 0:- Add
prev * currtobeams. - Update
prev = curr.
- Add
- Otherwise skip (empty row).
- Count devices (
- Return
beams.
β±οΈ Complexity Analysis
-
Time complexity:
We scan each row of lengthnformrows β O(m Β· n). -
Space complexity:
Only a few variables (prev,curr,beams) β O(1).
π§βπ» Code (JavaScript)
/**
* @param {string[]} bank
* @return {number}
*/
var numberOfBeams = function (bank) {
let prev = 0; // number of devices in the previous non-empty row
let beams = 0;
for (const row of bank) {
// count '1's in this row
let curr = 0;
for (let i = 0; i < row.length; i++) {
if (row[i] === '1') curr++;
}
// if this row has devices, it forms beams with the previous non-empty row
if (curr > 0) {
beams += prev * curr;
prev = curr; // update previous non-empty row count
}
}
return beams;
};
π§ͺ Example Walkthrough
Input: bank = ["011001","000000","010100","001000"]
- Row 1 β 3 devices.
- Row 2 β empty (skip).
- Row 3 β 2 devices β beams += 3 * 2 = 6.
- Row 4 β 1 device β beams += 2 * 1 = 2.
Total = 8 β
π₯ Reflections
This problem highlights the importance of simplifying conditions. Instead of checking all row pairs, tracking only consecutive non-empty rows gives a clean and efficient solution.
Thatβs it for Day 42 of my LeetCode journey! Onwards to the next challenge π₯
Happy Coding π¨βπ»