Back to posts

LeetCode Challenge Day 42 β€” 2125. Number of Laser Beams in a Bank

Nitin Ahirwal / October 27, 2025

LeetCode ChallengeDay 42SimulationStringJavaScriptMediumPortfolio

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:

  1. Count the number of devices in each row.
  2. For every non-empty row, multiply its count with the previous non-empty row’s count.
  3. Accumulate the result.

πŸ”‘ Approach

  1. Initialize prev = 0 (count of devices in last non-empty row) and beams = 0.
  2. Traverse each row:
    • Count devices (curr).
    • If curr > 0:
      • Add prev * curr to beams.
      • Update prev = curr.
    • Otherwise skip (empty row).
  3. Return beams.

⏱️ Complexity Analysis

  • Time complexity:
    We scan each row of length n for m rows β†’ 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 πŸ‘¨β€πŸ’»