LeetCode 75

Equal Row and Column Pairs

Problem
LC 2352
Topic
Hash Map / Set
File
official75_LC2352EqualRowAndColumnPairs.java
Path
pkg5leetcode/official75/official75_LC2352EqualRowAndColumnPairs.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC2352EqualRowAndColumnPairs.java
Approach
Hash row signatures; count matching columns.
Complexity
Time O(n^2), Space O(n^2)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC2352EqualRowAndColumnPairs.java
1package pkg5leetcode.official75;2 3/*4 * Equal Row and Column Pairs | LC 23525 * APPROACH: Hash row signatures; count matching columns.6 * COMPLEXITY: Time O(n^2), Space O(n^2)7 */8import java.util.*;9 10public class official75_LC2352EqualRowAndColumnPairs {11    static int equalPairs(int[][] grid) {12        int n = grid.length, count = 0;13        Map<String, Integer> rows = new HashMap<>();14        for (int[] r : grid) {15            String key = Arrays.toString(r);16            rows.put(key, rows.getOrDefault(key, 0) + 1);17        }18        for (int c = 0; c < n; c++) {19            int[] col = new int[n];20            for (int r = 0; r < n; r++) col[r] = grid[r][c];21            count += rows.getOrDefault(Arrays.toString(col), 0);22        }23        return count;24    }25 26    public static void main(String[] args) {27        check(equalPairs(new int[][]{{3,2,1},{1,7,6},{2,7,7}}) == 1, "case1");28        check(equalPairs(new int[][]{{3,1,2,2},{1,4,4,5},{2,4,2,2},{2,4,2,2}}) == 3, "case2");29        System.out.println("all tests passed");30    }31 32    static void check(boolean cond, String name) {33        if (!cond) throw new AssertionError("FAILED: " + name);34        System.out.println("  PASS " + name);35    }36}