Problem 237298 · medium · Phase 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 = [[3, 2, 1],
                [1, 7, 6],
                [2, 7, 7]]
Output: 1
Explanation: row 2 = [2, 7, 7] equals column 1 = [2, 7, 7].

Input:  grid = [[3, 1, 2, 2],
                [1, 4, 4, 5],
                [2, 4, 2, 2],
                [2, 4, 2, 2]]
Output: 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…