[Naive Approach] Generate all possible sub-square matrices
Generate all possible sub-squares and check sum of all the elements of the sub-square equals to x. For each square size, it slides a window over all possible top-left positions in the matrix where a square of that size can fit. At each position, it computes the sum of all elements inside the current square using nested loops. If the computed sum is equal to the target value x, it increments the count.
C++
#include<iostream>#include<vector>usingnamespacestd;intcountSquare(vector<vector<int>>&mat,intx){intcount=0;intn=mat.size();intm=mat[0].size();// Maximum possible size of a squareintmaxSize=min(n,m);// Try all possible square sizesfor(intsize=1;size<=maxSize;size++){// Loop through all top-left corners of // squares of this sizefor(inti=0;i<=n-size;i++){for(intj=0;j<=m-size;j++){intsum=0;// Compute the sum of the current squarefor(intp=i;p<i+size;p++){for(intq=j;q<j+size;q++){sum+=mat[p][q];}}// Check if the sum matches the target value xif(sum==x){count++;}}}}returncount;}intmain(){vector<vector<int>>mat={{2,4,7,8,10},{3,1,1,1,1},{9,11,1,2,1},{12,-17,1,1,1}};intx=10;intres=countSquare(mat,x);cout<<res<<endl;return0;}
Java
publicclassGfG{publicstaticintcountSquare(int[][]mat,intx){intcount=0;intn=mat.length;intm=mat[0].length;// Largest possible square sizeintmaxSize=Math.min(n,m);// Try all square sizes from 1x1 to maxSize x maxSizefor(intsize=1;size<=maxSize;size++){// Slide square of current size across all // valid top-left positionsfor(inti=0;i<=n-size;i++){for(intj=0;j<=m-size;j++){intsum=0;// Compute sum of the current square submatrixfor(intp=i;p<i+size;p++){for(intq=j;q<j+size;q++){sum+=mat[p][q];}}// If sum matches the target, increment the countif(sum==x){count++;}}}}returncount;}publicstaticvoidmain(String[]args){int[][]mat={{2,4,7,8,10},{3,1,1,1,1},{9,11,1,2,1},{12,-17,1,1,1}};intx=10;intres=countSquare(mat,x);System.out.println(res);}}
Python
defcountSquare(mat,x):count=0n=len(mat)m=len(mat[0])# Largest square size allowedmaxSize=min(n,m)# Try each square size from 1x1 to max_size x max_sizeforsizeinrange(1,maxSize+1):# Slide the square over all valid top-left positionsforiinrange(n-size+1):forjinrange(m-size+1):total=0# Calculate sum of the current square submatrixforpinrange(i,i+size):forqinrange(j,j+size):total+=mat[p][q]# If the sum equals the target x, count itiftotal==x:count+=1returncountif__name__=="__main__":mat=[[2,4,7,8,10],[3,1,1,1,1],[9,11,1,2,1],[12,-17,1,1,1]]x=10res=countSquare(mat,x)print(res)
C#
usingSystem;classGfG{staticintcountSquare(int[,]mat,intx){intcount=0;intn=mat.GetLength(0);intm=mat.GetLength(1);// Largest square possibleintmaxSize=Math.Min(n,m);// Try all square sizes from 1x1 to maxSize x maxSizefor(intsize=1;size<=maxSize;size++){// Loop over all valid top-left cornersfor(inti=0;i<=n-size;i++){for(intj=0;j<=m-size;j++){intsum=0;// Calculate sum of current square submatrixfor(intp=i;p<i+size;p++){for(intq=j;q<j+size;q++){sum+=mat[p,q];}}// Check if the submatrix sum matches targetif(sum==x){count++;}}}}returncount;}staticvoidMain(){int[,]mat={{2,4,7,8,10},{3,1,1,1,1},{9,11,1,2,1},{12,-17,1,1,1}};intx=10;intres=countSquare(mat,x);Console.WriteLine(res);}}
JavaScript
functioncountSquare(mat,x){letcount=0;constn=mat.length;constm=mat[0].length;// Largest square size allowedconstmaxSize=Math.min(n,m);// Try all square sizes from 1 to maxSizefor(letsize=1;size<=maxSize;size++){// Loop over all valid top-left corners // for the current square sizefor(leti=0;i<=n-size;i++){for(letj=0;j<=m-size;j++){letsum=0;// Compute the sum of the current squarefor(letp=i;p<i+size;p++){for(letq=j;q<j+size;q++){sum+=mat[p][q];}}// If sum matches the target, increment countif(sum===x){count++;}}}}returncount;}// Driver Codeconstmat=[[2,4,7,8,10],[3,1,1,1,1],[9,11,1,2,1],[12,-17,1,1,1]];constx=10;constres=countSquare(mat,x);console.log(res);
Output
3
Time Complexity:O(n2 * m2 * min(n,m)), because for each square size, the code checks all possible positions and sums all elements within each square. Auxiliary Space:O(1), since no extra space has been taken.
[Expected Approach]Prefix sum with hashing
Compute prefix sums row-wise to allow quick calculation of horizontal subarray sums. Then, for every pair of columns i and j, reduce the matrix to a 1D array by summing values in each row between columns i and j. For each such 1D array, maintain a running sum and use a hash map to count how many times a particular prefix sum has occurred. Whenever the difference between the current sum and the target is found in the map, increment the result by that frequency.
C++
#include<iostream>#include<vector>#include<unordered_map>usingnamespacestd;intcountSquare(vector<vector<int>>&mat,intx){intres=0;intn=mat.size();intm=mat[0].size();// Compute row-wise prefix sumvector<vector<int>>rowPrefix=mat;for(inti=0;i<n;i++)for(intj=1;j<m;j++)rowPrefix[i][j]+=rowPrefix[i][j-1];// Maximum square size possibleintmaxSize=min(n,m);// Try each possible square sizefor(intsize=1;size<=maxSize;size++){// Slide over all column ranges of width = sizefor(inti=0;i<=m-size;i++){// Right column indexintj=i+size-1;// Compute column sum for `size` consecutive rowsintsum=0;for(introw=0;row<size-1;row++){sum+=rowPrefix[row][j]-(i>0?rowPrefix[row][i-1]:0);}// Now apply sliding window over rowsfor(introw=size-1;row<n;row++){// Add the new rowsum+=rowPrefix[row][j]-(i>0?rowPrefix[row][i-1]:0);// Check if the current square has the required sumif(sum==x)res++;// Remove the top row of the previous windowsum-=rowPrefix[row-size+1][j]-(i>0?rowPrefix[row-size+1][i-1]:0);}}}returnres;}intmain(){intx=10;vector<vector<int>>mat={{2,4,7,8,10},{3,1,1,1,1},{9,11,1,2,1},{12,-17,1,1,1}};cout<<countSquare(mat,x)<<endl;return0;}
Java
publicclassGfG{publicstaticintcountSquare(int[][]mat,intx){intres=0;intn=mat.length;intm=mat[0].length;// Compute row-wise prefix sumint[][]rowPrefix=newint[n][m];for(inti=0;i<n;i++){rowPrefix[i][0]=mat[i][0];for(intj=1;j<m;j++){rowPrefix[i][j]=rowPrefix[i][j-1]+mat[i][j];}}intmaxSize=Math.min(n,m);// Try each possible square sizefor(intsize=1;size<=maxSize;size++){for(inti=0;i<=m-size;i++){intj=i+size-1;intsum=0;for(introw=0;row<size-1;row++){sum+=rowPrefix[row][j]-(i>0?rowPrefix[row][i-1]:0);}for(introw=size-1;row<n;row++){sum+=rowPrefix[row][j]-(i>0?rowPrefix[row][i-1]:0);if(sum==x)res++;sum-=rowPrefix[row-size+1][j]-(i>0?rowPrefix[row-size+1][i-1]:0);}}}returnres;}publicstaticvoidmain(String[]args){intx=10;int[][]mat={{2,4,7,8,10},{3,1,1,1,1},{9,11,1,2,1},{12,-17,1,1,1}};System.out.println(countSquare(mat,x));}}
Python
defcountSquare(mat,x):res=0n=len(mat)m=len(mat[0])# Compute row-wise prefix sumrowPrefix=[row[:]forrowinmat]foriinrange(n):forjinrange(1,m):rowPrefix[i][j]+=rowPrefix[i][j-1]maxSize=min(n,m)# Try all possible square sizesforsizeinrange(1,maxSize+1):# Try all possible column ranges [i, j] of width 'size'foriinrange(m-size+1):j=i+size-1total=0# Compute sum for top (size - 1) rows of the square windowforrowinrange(size-1):total+=rowPrefix[row][j]- \
(rowPrefix[row][i-1]ifi>0else0)# Slide the square window down row by rowforrowinrange(size-1,n):total+=rowPrefix[row][j]- \
(rowPrefix[row][i-1]ifi>0else0)# Check if the current square has sum xiftotal==x:res+=1# Remove the top row of the previous windowtotal-=rowPrefix[row-size+1][j]- \
(rowPrefix[row-size+1][i-1]ifi>0else0)returnresif__name__=="__main__":mat=[[2,4,7,8,10],[3,1,1,1,1],[9,11,1,2,1],[12,-17,1,1,1]]x=10print(countSquare(mat,x))
C#
usingSystem;usingSystem.Collections.Generic;classGfG{staticintcountSquare(int[,]mat,intx){intres=0;intn=mat.GetLength(0);intm=mat.GetLength(1);// Compute row-wise prefix sumint[,]rowPrefix=newint[n,m];for(inti=0;i<n;i++){rowPrefix[i,0]=mat[i,0];for(intj=1;j<m;j++){rowPrefix[i,j]=rowPrefix[i,j-1]+mat[i,j];}}intmaxSize=Math.Min(n,m);// Try all square sizesfor(intsize=1;size<=maxSize;size++){// Slide square window horizontallyfor(inti=0;i<=m-size;i++){intj=i+size-1;intsum=0;// Add top (size - 1) rows initiallyfor(introw=0;row<size-1;row++){sum+=rowPrefix[row,j]-(i>0?rowPrefix[row,i-1]:0);}// Slide window down verticallyfor(introw=size-1;row<n;row++){sum+=rowPrefix[row,j]-(i>0?rowPrefix[row,i-1]:0);if(sum==x)res++;// Remove top row of current square windowsum-=rowPrefix[row-size+1,j]-(i>0?rowPrefix[row-size+1,i-1]:0);}}}returnres;}staticvoidMain(){intx=10;int[,]mat={{2,4,7,8,10},{3,1,1,1,1},{9,11,1,2,1},{12,-17,1,1,1}};Console.WriteLine(countSquare(mat,x));}}
JavaScript
functioncountSquare(mat,x){letres=0;constn=mat.length;constm=mat[0].length;// Compute row-wise prefix sumconstrowPrefix=mat.map(row=>row.slice());for(leti=0;i<n;i++){for(letj=1;j<m;j++){rowPrefix[i][j]+=rowPrefix[i][j-1];}}constmaxSize=Math.min(n,m);// Try all square sizesfor(letsize=1;size<=maxSize;size++){// Slide square window horizontallyfor(leti=0;i<=m-size;i++){letj=i+size-1;letsum=0;// Add top (size - 1) rows initiallyfor(letrow=0;row<size-1;row++){sum+=rowPrefix[row][j]-(i>0?rowPrefix[row][i-1]:0);}// Slide the window down verticallyfor(letrow=size-1;row<n;row++){sum+=rowPrefix[row][j]-(i>0?rowPrefix[row][i-1]:0);// Check if current square sum equals targetif(sum===x)res++;// Subtract top row as window slides downsum-=rowPrefix[row-size+1][j]-(i>0?rowPrefix[row-size+1][i-1]:0);}}}returnres;}// Driver Codeconstmat=[[2,4,7,8,10],[3,1,1,1,1],[9,11,1,2,1],[12,-17,1,1,1]];constx=10;console.log(countSquare(mat,x));
Output
3
Time Complexity: O(n * m * min(n,m)), because for each possible square size (up to min(n, m)), the code slides a square window of that size across all valid positions in the matrix, doing constant-time work per position. Auxiliary Space: O(n*m)