DDSA Solutions

2125. Number of Laser Beams in a Bank

Time: O(mn)
Space: O(1)
Advertisement

Approach

For each row count devices; multiply consecutive non-zero row counts.

Key Techniques

Array

Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.

Math

Math problems test number theory, combinatorics, and modular arithmetic. Common tools: GCD/LCM (Euclidean algorithm), prime sieve, modular inverse (Fermat's little theorem), digit manipulation, and bit tricks. Overflow is a key concern in C# — use long when products may exceed 2³¹.

Matrix

Matrix problems often involve BFS/DFS flood fill, dynamic programming on 2D grids, or spiral/diagonal traversal. For row × column DP, break it into 1D sub-problems column by column. Common pitfalls: boundary checks and modifying the input matrix in-place.

2125.cs
C#
// Approach: For each row count devices; multiply consecutive non-zero row counts.
// Time: O(mn) Space: O(1)

public class Solution
{
    public int NumberOfBeams(string[] bank)
    {
        int laserBeam = 0;
        int n = bank.Length;

        int prevBankDeviceCnt = 0;
        for (int i = 0; i < bank.Length; i++)
        {
            string b = bank[i];
            int deviceCnt = 0;
            int j = 0;
            while (j < b.Length)
            {
                if (b[j] == '1')
                    deviceCnt++;
                j++;
            }

            if (deviceCnt > 0)
            {
                laserBeam += prevBankDeviceCnt * deviceCnt;
                prevBankDeviceCnt = deviceCnt;
            }
        }

        return laserBeam;
    }
}
Advertisement
Was this solution helpful?