Number of Laser Beams in a Bank - 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.

bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while '1' means the cell has a security device.

There is one laser beam between any two security devices if both conditions are met:

  • The two devices are located on two different rows: r1 and r2, where r1 < r2.
  • For each row i where r1 < i < r2, there are no security devices in the ith row.

Laser beams are independent, i.e., one beam does not interfere nor join with another.

Return the total number of laser beams in the bank.

Input & Output

Example 1 — Basic Bank Layout
$ Input: bank = ["011001","000000","010100","001000"]
Output: 8
💡 Note: Row 0 has 3 devices, Row 2 has 2 devices, Row 3 has 1 device. Beams: 3×2=6 (Row 0 to Row 2), 2×1=2 (Row 2 to Row 3). Total: 6+2=8
Example 2 — Single Row
$ Input: bank = ["000","111","000"]
Output: 0
💡 Note: Only one row has devices. No laser beams possible since beams require two different rows with devices.
Example 3 — Adjacent Active Rows
$ Input: bank = ["11","11"]
Output: 4
💡 Note: Row 0 has 2 devices, Row 1 has 2 devices. Total beams: 2×2=4 between the adjacent rows.

Constraints

  • m == bank.length
  • n == bank[i].length
  • 1 ≤ m, n ≤ 500
  • bank[i][j] is either '0' or '1'.

Visualization

Tap to expand
Number of Laser Beams in a Bank INPUT Bank Floor Plan (4x6 grid) r0 0 0 0 3 devices r1 0 devices r2 0 0 0 0 2 devices r3 0 0 0 0 0 1 device bank = ["011001", "000000", "010100", "001000"] ALGORITHM STEPS 1 Count devices per row Count '1's in each row string counts = [3, 0, 2, 1] Row 0:3, Row 1:0, Row 2:2, Row 3:1 2 Skip empty rows Rows with 0 devices are skipped non_empty = [3, 2, 1] 3 Multiply adjacent counts prev_count * curr_count 3 * 2 = 6 beams (r0 to r2) 2 * 1 = 2 beams (r2 to r3) 4 Sum all beams total = 6 + 2 = 8 FINAL RESULT Laser Beam Calculation From Row 0 (3 devices) to Row 2 (2 devices): 3 x 2 = 6 beams (Row 1 is empty, so skipped) From Row 2 (2 devices) to Row 3 (1 device): 2 x 1 = 2 beams Total Laser Beams: 8 Output: 8 OK - Verified 6 + 2 = 8 total beams Key Insight: Empty rows (0 devices) act as "transparent" layers - beams pass through them to connect consecutive rows with devices. Total beams = sum of (prev_row_count * curr_row_count) for all adjacent non-empty rows. Time: O(m*n), Space: O(1) TutorialsPoint - Number of Laser Beams in a Bank | Count Devices Per Row Approach
Asked in
Amazon 15 Microsoft 8
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen