You are given a square grid grid of size n by n. Row r is read left to right, and column c is read top to bottom.
Count the pairs (r, c) where row r and column c hold exactly the same numbers in the same order. Every matching row and column pair counts, so a row pattern that appears twice can match the same column twice.
Example 1
Input: grid = [[5, 8, 5], [8, 2, 8], [9, 8, 6]] Output: 1 Why: row 1 and column 1 both read 8, 2, 8
2 more examples and the constraints
Example 2
Input: grid = [[2, 2], [2, 2]] Output: 4 Why: each of the 2 rows matches each of the 2 columns
Example 3
Input: grid = [[1, 2], [3, 4]] Output: 0 Why: the rows are 1, 2 and 3, 4; the columns 1, 3 and 2, 4
Constraints
- 1 ≤ n ≤ 200
- grid has n rows and n columns
- 1 ≤ grid[i][j] ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Compare every row with every columnO(n³)
- Hash the rows, look up the columnsO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 200 by 200 grid | Verdict |
|---|---|---|---|
| Compare every row with every column | O(n³) | Works at n = 200; repeats work | |
| Hash the rows, look up the columns | O(n²) | Best; each cell read twice |
n = the side length of the grid.
Edge cases to test
- A 1 by 1 grid. [[7]] gives 1: the only row equals the only column.
- Repeated rows. Two identical rows that match a column count as two pairs, which is why the map stores counts, not a set.
- Same numbers, different order. [[1, 2, 3], [3, 1, 2], [2, 3, 1]] gives 0: order matters.
- Symmetric grid. When
grid[i][j] == grid[j][i], row i always equals column i, so the answer is at least n.
Common mistakes
- Storing row patterns in a set, which loses repeated rows and undercounts.
- Joining numbers into a string with no separator, so different rows collide.
- Reading a column left to right by accident (
grid[col][r]), which just reads a row again.
How to talk through it
- 1Clarify. Does order inside a row matter? Do repeated rows count once per matching column?
- 2Give the brute force. Compare all n² row and column pairs, n cells each: O(n³).
- 3Remove the repeat. Hash each row once and count it, so a column needs a single lookup.
- 4Mind the key. Use a tuple, a vector, or a string with separators as the map key.
- 5Test out loud. Run a 1 by 1 grid, a grid of equal values and a grid with no match.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?