Equal Row and Column Pairs - Problem
Matrix Row-Column Matching Challenge

Given an n Ɨ n integer matrix grid, your task is to find how many row-column pairs are identical. A row and column pair (ri, cj) is considered equal if they contain the exact same elements in the same order.

Think of it like finding matching patterns - you're comparing each horizontal line (row) with each vertical line (column) to see if they're mirror images of each other in terms of their values.

Example: If row 0 is [3,2,1] and column 1 is also [3,2,1] (reading top to bottom), that's one matching pair!

Goal: Return the total count of such matching pairs.

Input & Output

example_1.py — Basic Matrix
$ Input: grid = [[3,2,1],[1,7,6],[2,7,7]]
› Output: 1
šŸ’” Note: Row 2 [2,7,7] matches Column 1 [2,7,7]. This is the only matching pair, so we return 1.
example_2.py — Multiple Matches
$ Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
› Output: 3
šŸ’” Note: Row 2 [2,4,2,2] and Row 3 [2,4,2,2] both match Column 2 [2,4,2,2]. So we have pairs (2,2), (3,2), plus one more match making 3 total.
example_3.py — No Matches
$ Input: grid = [[1,2],[3,4]]
› Output: 0
šŸ’” Note: Row 0 [1,2] ≠ Column 0 [1,3], Row 0 [1,2] ≠ Column 1 [2,4], Row 1 [3,4] ≠ Column 0 [1,3], Row 1 [3,4] ≠ Column 1 [2,4]. No pairs match.

Constraints

  • n == grid.length == grid[i].length
  • 1 ≤ n ≤ 200
  • 1 ≤ grid[i][j] ≤ 105
  • The matrix is always square (n Ɨ n)

Visualization

Tap to expand
šŸ“š Library Pattern Matching VisualizationHorizontal Shelves (Rows)321517642779Vertical Towers (Columns)277Col 1Pattern MatchingRow 2: [2,7,7] ≔ Column 1: [2,7,7]āœ“ MATCH FOUND!Hash table enables O(1) pattern lookup instead of O(n) comparisonFinal Result: 1 matching row-column pair
Understanding the Visualization
1
Catalog Shelves
Record every horizontal shelf pattern in a catalog with frequencies
2
Check Towers
For each vertical tower, look it up in your shelf catalog
3
Count Matches
Add the frequency of matching shelf patterns to your total
4
Final Count
Sum all matches found across all tower patterns
Key Takeaway
šŸŽÆ Key Insight: Convert row and column sequences into hashable patterns (tuples/strings) to enable instant O(1) lookups instead of expensive O(n) element-by-element comparisons.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 10
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
šŸ’” Explanation
AI Ready
šŸ’” Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen