VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-of-possible-squares/

⇱ Number of possible squares - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of possible squares

Last Updated : 11 Dec, 2025

Given an N × N chessboard. Find the total number of distinct squares that can be formed on this board.

Note: A square can be of any size: 1×1, 2×2, 3×3, …, up to N×N.

Examples:

Input: N = 3
Output: 14
Explanation: A 3×3 chessboard contains:
9 squares of size 1×1
4 squares of size 2×2
1 square of size 3×3
Total = 9 + 4 + 1 = 14

Input: N = 5
Output: 55
Explanation: A 5×5 chessboard contains:
25 squares of size 1×1
16 squares of size 2×2
9 squares of size 3×3
4 squares of size 4×4
1 square of size 5×5
Total = 25 + 16 + 9 + 4 + 1 = 55

[Naive Approach] Brute Force - O(N^3) Time and O(1) Space

The naive idea is to count all possible squares by checking every size from 1×1 up to N×N. For each square size k, we slide a k×k window across the board and count how many such squares fit, which is (N − k + 1)². We repeat this for all k and add them up to get the total number of squares. This method is simple and intuitive but runs slower for large N because it explicitly checks all square sizes.


Output
14

[Better Approach] Linear Solution - O(N) Time and O(1) Space

The idea is to count squares by size, not by position. A chessboard has 1×1 squares, 2×2 squares, …, N×N squares. A k×k square can fit only in (N − k + 1) rows and columns, so there are (N − k + 1)² such squares. Adding this for all k gives the total number of squares.


Output
14

[Expected Approach] Optimal solution - O(1) Time and O(1) Space

A chessboard contains squares of many sizes. A 1×1 square can appear everywhere, a 2×2 square has fewer possible positions, a 3×3 square even fewer, and so on. For a k×k square, we can slide it horizontally and vertically, and it fits in exactly (N−k+1)×(N−k+1) places.

So the total number of squares is the sum of all these counts: 1² + 2² + 3² + … + N².

This sum has a known closed-form formula: (N * (N+1) * (2N+1)) / 6.


Output
14


Comment
Article Tags:
Article Tags: