Problem 237298 · medium · Level 02 Linear Data Structures

Matching Rows and Columns

hash maps · tuples as keys · matrices

Given a square grid grid (a list of n rows, each a list of n integers), count the pairs (r, c) such that row r read left to right is exactly the same sequence as column c read top to bottom. Every matching (r, c) pair counts separately.

Examples

Input:  grid = [[7, 3, 7],
                [2, 9, 3],
                [5, 4, 7]]
Output: 1
Explanation: row 0 = [7, 3, 7] equals column 2 = [7, 3, 7].

Input:  grid = [[7, 3, 7, 3],
                [3, 7, 3, 7],
                [7, 3, 7, 3],
                [1, 4, 3, 7]]
Output: 3
Explanation: rows 0 and 2 both equal column 2; row 1 equals column 3.

Constraints

  • 0 <= n <= 300
  • Target complexity: O(n2) time. Comparing every row against every column is O(n3) and too slow.

Goals

  • Use tuples as dictionary keys
  • Count matches between two collections with one lookup table
Starting Python…