Number of Laser Beams in a Bank

medium array math string matrix

Problem

You are given an m × n binary grid where each row is a floor of a bank and '1' marks a security device. Two devices form a laser beam if they lie on adjacent non-empty rows (any rows in between must be empty). Return the total number of beams.

Inputbank = ["011001", "000000", "010100", "001000"]
Output8
Counts of non-empty rows: 3, 2, 1 → 3*2 + 2*1 = 8.

def number_of_beams(bank):
    prev = 0
    total = 0
    for row in bank:
        c = row.count('1')
        if c > 0:
            total += prev * c
            prev = c
    return total
function numberOfBeams(bank) {
  let prev = 0, total = 0;
  for (const row of bank) {
    let c = 0;
    for (const ch of row) if (ch === '1') c++;
    if (c > 0) {
      total += prev * c;
      prev = c;
    }
  }
  return total;
}
class Solution {
    public int numberOfBeams(String[] bank) {
        int prev = 0, total = 0;
        for (String row : bank) {
            int c = 0;
            for (int i = 0; i < row.length(); i++) if (row.charAt(i) == '1') c++;
            if (c > 0) {
                total += prev * c;
                prev = c;
            }
        }
        return total;
    }
}
int numberOfBeams(vector<string>& bank) {
    int prev = 0, total = 0;
    for (auto& row : bank) {
        int c = 0;
        for (char ch : row) if (ch == '1') c++;
        if (c > 0) {
            total += prev * c;
            prev = c;
        }
    }
    return total;
}
Time: O(m · n) Space: O(1)