Skip to content

← leetcode

Count Total Number of Colored Cells

· Medium

LeetCode problem 2579

You can calculate the number of coloured cells in n cells instantly by realising that:

  • ignoring the center row, both halves always has (n-1)^2 coloured cells
  • the center row always has 2n-1 coloured cells

Therefore, you can simply just return 2 * (n-1)^2 + (2n - 1).

code

class Solution {
public:
    long long coloredCells(int n) {
        return 2 * ((long long) (n-1) * (n-1)) + (n * 2 - 1);
    }
};

complexity

  • Time: O(1)
  • Space: O(1)

time taken

  • erm, I forgot to stop the timer, but it was like 3 minutes or something...