Count Total Number of Colored Cells Problem
#2579
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2579.
There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer n, indicating that you must do the following routine for n minutes:
- At the first minute, color any arbitrary unit cell blue.
- Every minute thereafter, color blue every uncolored cell that touches a blue cell.
Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.

Return the number of colored cells at the end of n minutes.
Example 1:
Input: n = 1
Output: 1
Explanation: After 1 minute, there is only 1 blue cell, so we return 1.
Example 2:
Input: n = 2
Output: 5
Explanation: After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5.
Constraints:
1 <= n <= 10^5
Solution
Approach: Mathematics
After n minutes the colored cells form a diamond. Its columns hold 1, 3, 5, ..., 2n - 1, ..., 5, 3, 1 cells, two arithmetic progressions around the middle column, which sum to 2n(n - 1) + 1.
Complexity: time O(1), space O(1), where n is the number of minutes.
class Solution:
def coloredCells(self, n: int) -> int:
return 2 * n * (n - 1) + 1