1154. Four-Corner Frames

Medium3.5 points estimatedEnumerationCountingMatrixHash Table

A tile wall is an m x n grid, and grid[i][j] is the digit painted on the tile in row i and column j. A frame is an axis-aligned rectangle of tiles that spans at least 2 rows and at least 2 columns, and it is identified by its four corner tiles. Tiles on the edges or inside the frame do not matter.

Return the number of frames whose four corner tiles all show the same digit, as a 64-bit integer. Two frames are different when their row pair or column pair differs. Constraints: 1 <= m, n <= 100 and 0 <= grid[i][j] <= 9. Aim for O(m^2 * n) time and O(1) extra space, by looking at every pair of rows and counting, per digit, the columns where both rows agree.

Example 1

Input:
grid = [[1,2,1],[3,4,3],[1,5,1]]
Output:
1
Explanation:

Only the frame with rows 0 and 2 and columns 0 and 2 has four equal corners (all 1).

Example 2

Input:
grid = [[0,0],[0,0]]
Output:
1
Explanation:

The whole 2 x 2 grid is the single frame, and its four corners are all 0.

Example 3

Input:
grid = [[7,7,7],[7,7,7],[7,7,7]]
Output:
9
Explanation:

Each of the 3 row pairs can choose 2 of the 3 columns, so there are 3 * 3 = 9 frames.

Constraints

1 ≤ m, n ≤ 100
0 ≤ grid[i][j] ≤ 9

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(m^2 * n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…