Count Total Number of Colored Cells

medium math pattern

Problem

An infinitely large grid starts completely uncolored. At minute 1 you color one cell blue. During every following minute, every uncolored cell that shares an edge with a blue cell becomes blue as well. Given an integer n (1 ≤ n ≤ 10⁵), return how many cells are colored after n minutes.

Inputn = 4
Output25
Minute 1 colors the center cell; minutes 2, 3 and 4 add diamond rings of 4, 8 and 12 cells: 1 + 4 + 8 + 12 = 25.

def colored_cells(n):
    total = 1                    # minute 1: the single center cell
    for m in range(2, n + 1):
        total += 4 * (m - 1)     # minute m adds a ring of 4(m-1) cells
    return total                 # closed form: 2*n*n - 2*n + 1
function coloredCells(n) {
  let total = 1;                 // minute 1: the single center cell
  for (let m = 2; m <= n; m++) {
    total += 4 * (m - 1);        // minute m adds a ring of 4(m-1) cells
  }
  return total;                  // closed form: 2*n*n - 2*n + 1
}
long coloredCells(int n) {
    long total = 1;              // minute 1: the single center cell
    for (int m = 2; m <= n; m++) {
        total += 4L * (m - 1);   // minute m adds a ring of 4(m-1) cells
    }
    return total;                // closed form: 2L*n*n - 2L*n + 1
}
long long coloredCells(int n) {
    long long total = 1;         // minute 1: the single center cell
    for (int m = 2; m <= n; m++) {
        total += 4LL * (m - 1);  // minute m adds a ring of 4(m-1) cells
    }
    return total;                // closed form: 2LL*n*n - 2LL*n + 1
}
Time: O(n) Space: O(1)