May LeetCode Challenge Day 21: Count Square Submatrices with All Ones- (in-place solution)

iAwale
2 min readMay 22, 2020

A trick to solving this problem efficiently is that, we keep track of and update something I would call a square completer. A square completer is the bottom right element of a square that completes the square. For example the dark shaded area below is the square completer of the light shaded areas.

Now the first row and the first columns are excluded from the calculation because they never complete any squares.

So starting from the second row of second column we check if each completes a square. The size of square it completes is the minimum( among its top, top-left and top-left-diagonal elements) + 1. As we move through the array we keep a count of each Square completer’s value and update them as we traverse through the array.

Then, we count the 1 sized squares in the first row and column we excluded earlier. The total count gives the required solution.

Full solution:

class Solution {
public int countSquares(int[][] matrix) {
int count = 0;

// Traversing through the array determining square completer values

for(int i = 1; i < matrix.length; i ++){
for(int j = 1; j < matrix[i].length; j ++){
int val = checkSquare(matrix,i,j);
if(val != 0){
matrix[i][j] = val+1;
}
count += matrix[i][j];
}
}
// Counting the excluded areas for(int i = 0; i < matrix.length; i ++){
count+=matrix[i][0];
}

for(int j = 1; j < matrix[0].length; j ++){
count+=matrix[0][j];
}


return count;
}

// Check if square
public int checkSquare(int [][] matrix, int x, int y){
if (matrix [x][y] == 0
|| matrix [x][y-1] == 0
|| matrix [x-1][y] == 0
|| matrix [x-1][y-1] == 0 ){
return 0;
}

int min = Math.min(matrix [x][y-1],matrix [x-1][y]);
return Math.min(matrix [x-1][y-1],min);

}
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

iAwale
iAwale

Written by iAwale

Learn Productivity. Learn Growth. Learn Coding. Learn to Build Applications. If you like the content please follow Twitter Youtube

No responses yet

Write a response