Open In App

Number of squares in a rectangle

Last Updated : 20 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a m x n matrix, count the number of squares in the matrix.

Examples : 

Input: m = 2, n = 2
Output: 5
Explanation: There are 4 squares of size 1x1 + 1 square of size 2x2.

Input: m = 4, n = 3
Output: 20
Explanation: There are 12 squares of size 1x1 + 6 squares of size 2x2 + 2 squares of size 3x3.


[Naive Approach] Using Loop - O(min(n,m)) time and O(1) space

This approach counts the number of squares in a given rectangle of size m x n by iterating over all possible square sizes from 1 to the minimum of m and n, and adding up the number of squares of each size that can fit in the rectangle. 

C++
#include <iostream>
using namespace std;

// Function to count the number of squares 
// in an m x n grid
int count_squares(int m, int n) {
    int count = 0;
    for (int i = 1; i <= min(m, n); i++) {
        
        // Calculate the number of squares 
        //with side length 'i' that fit in the grid
        count += (m - i + 1) * (n - i + 1);
    }
    return count;
}

int main() {
    int m = 4;
    int n = 3;
    cout << count_squares(m, n) << endl;
    return 0;
}
Java
public class Main {
    public static void main(String[] args) {
        int m = 4;
        int n = 3;
        System.out.println(countSquares(m, n));
    }

    // Function to count the number of squares in an m x n grid
    public static int countSquares(int m, int n) {
        int count = 0;
        for (int i = 1; i <= Math.min(m, n); i++) { 
            
            // Calculate the number of squares with
            // side length 'i' that fit in the grid
            count += (m - i + 1) * (n - i + 1);
        }
        return count;
    }
}
Python
# Function to count the number of squares in an m x n grid
def count_squares(m, n):
    count = 0
    for i in range(1, min(m, n) + 1):
        
        # Calculate the number of squares 
        # with side length 'i' that fit in the grid
        count += (m - i + 1) * (n - i + 1)
    return count

m = 4
n = 3
print(count_squares(m, n))
C#
using System;

public class CountSquaresInGrid
{
    public static int CountSquares(int m, int n)
    {
        int count = 0;
        
        // Iterate through the side lengths of squares
        // from 1 to the minimum of m and n.
        for (int i = 1; i <= Math.Min(m, n); i++)
        {
            // For each side length 'i', calculate
            // the number of squares that can fit in the grid.
            count += (m - i + 1) * (n - i + 1);
        }
        
        return count;
    }

    public static void Main(string[] args)
    {
        int m = 4;
        int n = 3;
        
        // Call the function to count squares in the grid and print the result.
        int result = CountSquares(m, n);
        Console.WriteLine(result);
    }
}
JavaScript
// Function to count the number of squares in an m x n grid
function count_squares(m, n) {
    let count = 0;
    // Iterate over all possible square sizes
    for (let i = 1; i <= Math.min(m, n); i++) {
        
        // Count the number of squares of size 
        // 'i' that can fit in the grid
        count += (m - i + 1) * (n - i + 1);
    }
    return count;
}

let m = 4;
let n = 3;
console.log(count_squares(m, n)); // Output: 20

Output
20

[Expected Approach] Formula Based Approach - O(1) time and O(1) space

For a Square Grid (m=n)

  • For a grid where m=n, the total number of squares is the sum of all possible square sizes from 1×1 up to n×n. The formula for the total number of squares in a square grid is:

Total Squares=(n(n+1)(2n+1))/6

  • This is derived from the sum of the squares of all integers from 1 to n (i.e., n2+(n−1)2+⋯+12).

For a Rectangular Grid (m≠n)

Now, when the grid is rectangular, and m≤n, we calculate the number of squares of each size separately:

  • Number of squares in an m×m grid:
    The total number of squares in a m×m grid is:
    (m*(m+1)*(2m+1))/6
  • Adding (n−m) columns:
    When (n−m) columns are added to the grid, the total number of squares increases. The additional number of squares is calculated by:
    (n−m)×(m*(m+1))/2​
  • Total Number of Squares:
    The total number of squares in an m×n grid (with m≤n) is:
    (m*(m+1)*(2m+1))/6+ ((n-m)*(m*(m+1)))/2

The formula for the total number of squares will be (m * (m + 1) * (2 * m + 1)) /6 + ((n - m) * m *(m + 1)) / 2

C++
#include <iostream>
using namespace std;

// Returns count of all squares
// in a rectangle of size m x n
int countSquares(int m, int n)
{

    // If n is smaller, swap m and n
    if (n < m) {
        swap(m, n);
    }

    // Now n is greater dimension,
    // apply formula
    return (m * (m + 1) * (2 * m + 1)) /
6 + ((n - m) * m *(m + 1)) / 2;;
}

int main()
{
    int m = 4, n = 3;
    cout << countSquares(m, n);
}
C
#include <stdio.h>

// Returns count of all squares
// in a rectangle of size m x n
int countSquares(int m, int n) {
    // If n is smaller, swap m and n
    if (n < m) {
        int temp = m;
        m = n;
        n = temp;
    }

    // Now n is greater dimension,
    // apply formula
    return (m * (m + 1) * (2 * m + 1)) / 6 + ((n - m) * m * (m + 1)) / 2;
}

int main() {
    int m = 4, n = 3;
    printf("%d", countSquares(m, n));
    return 0;
}
Java
public class Main {
    // Returns count of all squares
    // in a rectangle of size m x n
    public static int countSquares(int m, int n) {
        // If n is smaller, swap m and n
        if (n < m) {
            int temp = m;
            m = n;
            n = temp;
        }

        // Now n is greater dimension,
        // apply formula
        return (m * (m + 1) * (2 * m + 1)) / 6 + ((n - m) * m * (m + 1)) / 2;
    }

    public static void main(String[] args) {
        int m = 4, n = 3;
        System.out.println(countSquares(m, n));
    }
}
Python
def countSquares(m, n):
    # If n is smaller, swap m and n
    if n < m:
        m, n = n, m

    # Now n is greater dimension,
    # apply formula
    return (m * (m + 1) * (2 * m + 1)) // 6 + ((n - m) * m * (m + 1)) // 2

m = 4
n = 3
print(countSquares(m, n))
C#
using System;

class Program {
    // Returns count of all squares
    // in a rectangle of size m x n
    static int countSquares(int m, int n) {
        // If n is smaller, swap m and n
        if (n < m) {
            int temp = m;
            m = n;
            n = temp;
        }

        // Now n is greater dimension,
        // apply formula
        return (m * (m + 1) * (2 * m + 1)) / 6 + ((n - m) * m * (m + 1)) / 2;
    }

    static void Main() {
        int m = 4, n = 3;
        Console.WriteLine(countSquares(m, n));
    }
}
JavaScript
// Returns count of all squares
// in a rectangle of size m x n
function countSquares(m, n) {
    
    // If n is smaller, swap m and n
    if (n < m) {
        [m, n] = [n, m];
    }

    // Now n is greater dimension,
    // apply formula
    return (m * (m + 1) * (2 * m + 1)) / 6 + ((n - m) * m * (m + 1)) / 2;
}

let m = 4, n = 3;
console.log(countSquares(m, n));

Output
20

Similar Reads