Microsoft Code Signal Question
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2023-09-08Added By Anonymous
Source: Link
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
1class Solution {
2 public int solution(String[] board) {
3 int n = board.length;
4 int m = board[0].length();
5
6 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.
7
8 int totalRectangles = 0;
9
10 // Loop through each row and column
11 for (int i = 1; i <= n; i++) {
12 for (int j = 1; j <= m; j++) {
13 char currentCell = board[i - 1].charAt(j - 1);
14
15 // Update the count of rectangles ending at (i-1, j-1)
16 if (currentCell == 'A') {
17 dp[i][j][0] = dp[i - 1][j][0] + 1;
18 dp[i][j][1] = dp[i - 1][j][1];
19 } else if (currentCell == 'B') {
20 dp[i][j][1] = dp[i - 1][j][1] + 1;
21 dp[i][j][0] = dp[i - 1][j][0];
22 }
23
24 // Check if the rectangle formed by (0,0) and (i-1, j-1) has equal A's and B's
25 for (int x = 1; x <= i; x++) {
26 for (int y = 1; y <= j; y++) {
27 int aCount = dp[i][j][0] - dp[x - 1][j][0] - dp[i][y - 1][0] + dp[x - 1][y - 1][0];
28 int bCount = dp[i][j][1] - dp[x - 1][j][1] - dp[i][y - 1][1] + dp[x - 1][y - 1][1];
29
30 if (aCount == bCount) {
31 totalRectangles++;
32 }
33 }
34 }
35 }
36 }
37
38 return totalRectangles;
39 }
40}it didn't work , can someone provide me one .