![]() |
VOOZH | about |
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 = 14Input: 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
Table of Content
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.
14
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.
14
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.
14