Microsoft Code Signal Question

Anonymous User
264
Sep 08, 2023
Sep 08, 2023

there is a board of size N x M, rowsare numbered 0 to N-1 and columns are numbered 0 to M-1 , Each cell is either empty (denoted by '.') or contains letters A or B , the cell in the rth row and cth column is represented by board[r][c]

calculate the number of rectangles inside the board with the corner at position (0,0) (board[0][0]) which covers an equal number of letters A and B

for Example for board = ["AB.", "B..", "..A"] there are 5 such rectangles

  1. the first row without the last element
  2. the whole first row
  3. symmetrically the whole first column and the first column without the last element
  4. the whole board

please write the solution in java 8

class Solution {
public int solution(String[] board) {
// Implement your solution here
}
}

my SOlution

class Solution {
    public int solution(String[] board) {
        int n = board.length;
        int m = board[0].length();

        int[][][] dp = new int[n + 1][m + 1][2]; // dp[i][j][k] represents the count of rectangles ending at (i-1, j-1) with k A's and k B's.

        int totalRectangles = 0;

        // Loop through each row and column
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                char currentCell = board[i - 1].charAt(j - 1);

                // Update the count of rectangles ending at (i-1, j-1)
                if (currentCell == 'A') {
                    dp[i][j][0] = dp[i - 1][j][0] + 1;
                    dp[i][j][1] = dp[i - 1][j][1];
                } else if (currentCell == 'B') {
                    dp[i][j][1] = dp[i - 1][j][1] + 1;
                    dp[i][j][0] = dp[i - 1][j][0];
                }

                // Check if the rectangle formed by (0,0) and (i-1, j-1) has equal A's and B's
                for (int x = 1; x <= i; x++) {
                    for (int y = 1; y <= j; y++) {
                        int aCount = dp[i][j][0] - dp[x - 1][j][0] - dp[i][y - 1][0] + dp[x - 1][y - 1][0];
                        int bCount = dp[i][j][1] - dp[x - 1][j][1] - dp[i][y - 1][1] + dp[x - 1][y - 1][1];

                        if (aCount == bCount) {
                            totalRectangles++;
                        }
                    }
                }
            }
        }

        return totalRectangles;
    }
}

it didn't work , can someone provide me one .

Comments (3)