Counting Squares in an N x N Grid
You have an $n \times n$ grid made up of $n^2$ unit squares (
Give a closed-form formula in terms of $n$, and compute the answer for $n = 10$.
Hints
- Count squares by size: how many $k \times k$ squares fit in the $n \times n$ grid?
- A $k \times k$ square has $(n - k + 1)^2$ possible positions. Sum this over $k = 1$ to $n$.
- Use the sum of squares formula: $\sum_{m=1}^n m^2 = n(n+1)(2n+1)/6$.
Worked Solution
How to Think About It: Break the count by square size. A $k \times k$ square needs to fit inside the $n \times n$ grid, so its top-left corner can be placed at any position $(i, j)$ where
Quick Estimate: The total is $\sum_{k=1}^n (n-k+1)^2 = \sum_{m=1}^n m^2$. For $n = 10$:
Approach: Count by square size and apply the sum of squares formula.
Formal Solution:
For each $k = 1, 2, \ldots, n$, a $k \times k$ square can be placed with its top-left corner at any of $(n - k + 1)$ rows and $(n - k + 1)$ columns. So there are $(n - k + 1)^2$ squares of size $k \times k$.
The total count is:
$\sum_{k=1}^{n} (n - k + 1)^2 = \sum_{m=1}^{n} m^2 = \frac{n(n+1)(2n+1)}{6}$
where we substituted $m = n - k + 1$.
For $n = 10$:
$\frac{10 \cdot 11 \cdot 21}{6} = \frac{2310}{6} = 385$
Verification by direct count: -
Answer: The total number of squares is $\dfrac{n(n+1)(2n+1)}{6}$. For $n = 10$, the answer is $385$.
Intuition
This is a counting exercise that teaches a universally useful technique: when objects come in different sizes, count each size separately and sum. The key observation is that a $k \times k$ square in an $n \times n$ grid has $(n-k+1)^2$ valid placements, because the top-left corner is constrained to a smaller grid. The re-indexing $m = n - k + 1$ turns the sum into the familiar $\sum m^2$, which has the clean closed form $n(n+1)(2n+1)/6$.
This problem appears in interviews because it tests whether you can systematically decompose a combinatorial question. The same "count by size and sum" strategy applies to counting rectangles in a grid (which gives $\binom{n+1}{2}^2$ for an $n \times n$ grid), counting substrings of a string, or counting subarrays -- all common algorithmic building blocks.