← Questions
Count single-colour squares in a character grid
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's first round (coding), last asked Nov 2025. It tests dynamic programming and grids.
Each cell of a grid holds a letter that stands for a colour. Count every square sub-grid, of every size and position, whose cells all hold the same letter. Every single cell counts as a 1 x 1 square.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
count_uniform_squares(grid: list[str]) -> int— each string is one row;0for an empty grid.
Example
count_uniform_squares(["aab",
"aab",
"bbb"]) -> 10 # 9 single cells + the 2x2 of a's
count_uniform_squares(["aaa",
"aaa",
"aaa"]) -> 14 # 9 + 4 + 1
count_uniform_squares(["ab",
"ba"]) -> 4
count_uniform_squares([]) -> 0
Constraints
- Up to 1000 x 1000 cells (10^6 in total); all rows have the same length.
- Letters are case-sensitive:
aandAare different colours.
Clarifying questions
- Do all sizes count, including 1 x 1?
- Is a square counted by position, so overlapping squares count separately?
- Are upper and lower case different colours?
- Can the grid be empty or have empty rows?
What a strong answer covers
- The DP:
dp[i][j]is the side of the largest single-colour square whose bottom-right corner is(i, j). It is 1, or1 + min(top, left, top-left)when the cell matches all three neighbours. - The answer is the sum of
dp, because a cell with valuekis the corner of exactlykuniform squares (sides 1 tok). - O(m·n) time; O(n) space by keeping one previous row.
- Why the brute force (check every square) is O(m·n·min(m,n)^2) or worse.
- Tests: empty grid, one row, all one colour, a checkerboard.
Follow-ups
- Count single-colour rectangles instead of squares.
- Return the largest uniform square and its colour.
- Cells change colour one at a time; keep the count current.
Where it's asked
- Google · First round: coding · Last asked Nov 202545 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
