Count Total Number of Colored Cells - Problem

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.

Return the number of colored cells at the end of n minutes.

Input & Output

Example 1 — Basic Case
$ Input: n = 1
Output: 1
💡 Note: At minute 1, we color the initial cell. Total colored cells = 1.
Example 2 — Small Diamond
$ Input: n = 2
Output: 5
💡 Note: Minute 1: 1 cell. Minute 2: original cell + 4 adjacent cells = 5 total.
Example 3 — Growing Pattern
$ Input: n = 3
Output: 13
💡 Note: Forms diamond shape: 1 + 4 + 8 = 13 cells after 3 minutes.

Constraints

  • 1 ≤ n ≤ 105

Visualization

Tap to expand
Count Total Number of Colored Cells INPUT Infinite 2D Grid (n=1) Minute 1: Color 1 cell blue Input: n = 1 Number of minutes n=1: 1 cell n=2: 5 cells n=3: 13 cells ALGORITHM STEPS 1 Observe Pattern Diamond shape grows each min 2 Find Formula Cells = 2n^2 - 2n + 1 3 Apply for n=1 2(1)^2 - 2(1) + 1 = 1 4 Return Result Output the count Formula Derivation: n=1: 1 = 1 n=2: 1 + 4 = 5 n=3: 5 + 8 = 13 n=4: 13 + 12 = 25 Diff: +4, +8, +12... (+4 each) FINAL RESULT After 1 minute: 1 Output: 1 colored cell OK - Verified Key Insight: The colored cells form a diamond (rhombus) pattern. Each minute adds a new layer around the existing shape. The closed-form formula is: cells = 2n^2 - 2n + 1, which equals n^2 + (n-1)^2 (sum of two squares). This gives O(1) time complexity instead of simulating each minute. For n=1: 2(1) - 2(1) + 1 = 1 cell. TutorialsPoint - Count Total Number of Colored Cells | Optimal O(1) Solution
Asked in
Google 25 Microsoft 18 Amazon 15
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen