Skip to content

2125. Number of Laser Beams in a Bank 👍

  • Time: $O(mn)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int numberOfBeams(vector<string>& bank) {
    int ans = 0;
    int prevOnes = 0;

    for (const string& row : bank) {
      const int ones = count(begin(row), end(row), '1');
      if (ones) {
        ans += prevOnes * ones;
        prevOnes = ones;
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int numberOfBeams(String[] bank) {
    int ans = 0;
    int prevOnes = 0;

    for (final String row : bank) {
      final int ones = (int) row.chars().filter(c -> c == '1').count();
      if (ones > 0) {
        ans += prevOnes * ones;
        prevOnes = ones;
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def numberOfBeams(self, bank: List[str]) -> int:
    ans = 0
    prevOnes = 0

    for row in bank:
      ones = row.count('1')
      if ones:
        ans += prevOnes * ones
        prevOnes = ones

    return ans