Rasta and Kheshtak

Pattern: Binary search on the answer

medium

The largest square that appears in both matrices. If a k × k square is shared, so is every smaller square inside it, so binary search k. To check one k, hash every k × k square of the first matrix and look for a match in the second.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given two matrices of whole numbers, a and b, of any sizes. Find the largest k such that some k × k block of neighbouring cells in a is exactly equal to some k × k block in b. Return k, or 0 if no single value is shared. For example, with a = [[1, 2, 0], [1, 2, 1], [1, 2, 3]] and b = [[0, 1, 2], [1, 1, 2], [3, 1, 2]] the answer is 2.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name largestCommonSquare and this exact statement are this guide's own, so check the original wording before comparing.

Think first

  • If two matrices share a 3 × 3 block, do they share a 2 × 2 block?
  • For one fixed k, how can you compare all k × k blocks of a with all of b without checking each pair cell by cell?
  • Hashes of different blocks can clash. How do you stay exactly correct?

Hints

    Brute force, and why it fails

    Try every side k, every block of a and every block of b, comparing cell by cell: about O(n⁶) for n × n matrices. This guide uses that on small tests. Hashing makes each check about O(n²), and binary search needs O(log n) checks.

    The key insight

    Two ideas combine. The answer is monotonic, so binary search it. And a rolling hash turns "compare two blocks" into "compare two numbers", so all blocks of one side can be checked at once with a hash map.

    Dry run

    a = 1 2 0 / 1 2 1 / 1 2 30lo
    b = 0 1 2 / 1 1 2 / 3 1 21 

    a has rows 1 2 0, 1 2 1, 1 2 3, and b has rows 0 1 2, 1 1 2, 3 1 2. Squares of side 0 to 3 are possible.

    Step 1 of 3

    The plan

    lo = 0, hi = smallest side of a and b
    while lo < hi:
        mid = lo + (hi - lo + 1) / 2
        if shared(mid): lo = mid
        else: hi = mid - 1
    return lo
    
    shared(k):
        map = hash of every k x k block of a -> its corners
        for each k x k block of b:
            for each corner in map[hash of block]:
                if the two blocks are equal cell by cell: return true
        return false
    

    Complexity

    Time
    O(n² log n) expected
    Space
    O(n²)

    For n × n matrices, each check builds O(n²) hashes in O(n²) time, and there are O(log n) checks. Direct comparisons after a hash match cost O(k²), and clashes are rare. The hash tables take O(n²).

    Edge cases

    • No value in common: 0.
    • Identical matrices: the smaller side length.
    • Negative values: reduce them into the hash's range before mixing them in.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        private static final long MOD = 1_000_000_007L, B1 = 131, B2 = 137;
    
        public int largestCommonSquare(int[][] a, int[][] b) {
            int lo = 0, hi = Math.min(Math.min(a.length, a[0].length), Math.min(b.length, b[0].length));
            while (lo < hi) {                       // if a k x k square is shared, so is a smaller one inside it
                int mid = lo + (hi - lo + 1) / 2;
                if (shared(a, b, mid)) lo = mid;
                else hi = mid - 1;
            }
            return lo;
        }
    
        private boolean shared(int[][] a, int[][] b, int k) {
            long[][] ha = hashes(a, k), hb = hashes(b, k);
            Map<Long, List<int[]>> seen = new HashMap<>();   // hash -> top-left corners in a
            for (int i = 0; i < ha.length; i++)
                for (int j = 0; j < ha[0].length; j++)
                    seen.computeIfAbsent(ha[i][j], z -> new ArrayList<>()).add(new int[]{i, j});
            for (int i = 0; i < hb.length; i++)
                for (int j = 0; j < hb[0].length; j++)
                    for (int[] p : seen.getOrDefault(hb[i][j], Collections.emptyList()))
                        if (same(a, p[0], p[1], b, i, j, k)) return true;   // check cell by cell: hashes can clash
            return false;
        }
    
        private long[][] hashes(int[][] m, int k) {        // hash of every k x k square, by its top-left corner
            int rows = m.length, cols = m[0].length;
            long p1 = 1, p2 = 1;
            for (int i = 0; i < k; i++) { p1 = p1 * B1 % MOD; p2 = p2 * B2 % MOD; }
            long[][] row = new long[rows][cols - k + 1];    // step 1: each row, k cells wide
            for (int r = 0; r < rows; r++) {
                long h = 0;
                for (int c = 0; c < cols; c++) {
                    h = (h * B1 + Math.floorMod(m[r][c], MOD)) % MOD;
                    if (c >= k) h = Math.floorMod(h - Math.floorMod(m[r][c - k], MOD) * p1 % MOD, MOD);
                    if (c >= k - 1) row[r][c - k + 1] = h;
                }
            }
            long[][] sq = new long[rows - k + 1][cols - k + 1];   // step 2: k of those row hashes stacked
            for (int c = 0; c < cols - k + 1; c++) {
                long h = 0;
                for (int r = 0; r < rows; r++) {
                    h = (h * B2 + row[r][c]) % MOD;
                    if (r >= k) h = Math.floorMod(h - row[r - k][c] * p2 % MOD, MOD);
                    if (r >= k - 1) sq[r - k + 1][c] = h;
                }
            }
            return sq;
        }
    
        private boolean same(int[][] a, int ai, int aj, int[][] b, int bi, int bj, int k) {
            for (int x = 0; x < k; x++)
                for (int y = 0; y < k; y++)
                    if (a[ai + x][aj + y] != b[bi + x][bj + y]) return false;
            return true;
        }
    }

    C++

    class Solution {
    public:
        static const long long MOD = 1000000007LL, B1 = 131, B2 = 137;
    
        int largestCommonSquare(vector<vector<int>>& a, vector<vector<int>>& b) {
            int lo = 0, hi = static_cast<int>(min(min(a.size(), a[0].size()), min(b.size(), b[0].size())));
            while (lo < hi) {                       // if a k x k square is shared, so is a smaller one inside it
                int mid = lo + (hi - lo + 1) / 2;
                if (shared(a, b, mid)) lo = mid;
                else hi = mid - 1;
            }
            return lo;
        }
    
        bool shared(vector<vector<int>>& a, vector<vector<int>>& b, int k) {
            vector<vector<long long>> ha = hashes(a, k), hb = hashes(b, k);
            unordered_map<long long, vector<pair<int, int>>> seen;   // hash -> top-left corners in a
            for (size_t i = 0; i < ha.size(); i++)
                for (size_t j = 0; j < ha[0].size(); j++) seen[ha[i][j]].push_back(make_pair(static_cast<int>(i), static_cast<int>(j)));
            for (size_t i = 0; i < hb.size(); i++)
                for (size_t j = 0; j < hb[0].size(); j++) {
                    auto it = seen.find(hb[i][j]);
                    if (it == seen.end()) continue;
                    for (const pair<int, int>& p : it->second)
                        if (same(a, p.first, p.second, b, static_cast<int>(i), static_cast<int>(j), k)) return true;   // hashes can clash
                }
            return false;
        }
    
        long long md(long long v) { v %= MOD; return v < 0 ? v + MOD : v; }
    
        vector<vector<long long>> hashes(vector<vector<int>>& m, int k) {   // hash of every k x k square
            int rows = static_cast<int>(m.size()), cols = static_cast<int>(m[0].size());
            long long p1 = 1, p2 = 1;
            for (int i = 0; i < k; i++) { p1 = p1 * B1 % MOD; p2 = p2 * B2 % MOD; }
            vector<vector<long long>> row(rows, vector<long long>(cols - k + 1));   // step 1: each row, k cells wide
            for (int r = 0; r < rows; r++) {
                long long h = 0;
                for (int c = 0; c < cols; c++) {
                    h = (h * B1 + md(m[r][c])) % MOD;
                    if (c >= k) h = md(h - md(m[r][c - k]) * p1 % MOD);
                    if (c >= k - 1) row[r][c - k + 1] = h;
                }
            }
            vector<vector<long long>> sq(rows - k + 1, vector<long long>(cols - k + 1));   // step 2: stack k rows
            for (int c = 0; c < cols - k + 1; c++) {
                long long h = 0;
                for (int r = 0; r < rows; r++) {
                    h = (h * B2 + row[r][c]) % MOD;
                    if (r >= k) h = md(h - row[r - k][c] * p2 % MOD);
                    if (r >= k - 1) sq[r - k + 1][c] = h;
                }
            }
            return sq;
        }
    
        bool same(vector<vector<int>>& a, int ai, int aj, vector<vector<int>>& b, int bi, int bj, int k) {
            for (int x = 0; x < k; x++)
                for (int y = 0; y < k; y++)
                    if (a[ai + x][aj + y] != b[bi + x][bj + y]) return false;
            return true;
        }
    };

    Python

    class Solution:
        MOD, B1, B2 = 1_000_000_007, 131, 137
    
        def largestCommonSquare(self, a: list[list[int]], b: list[list[int]]) -> int:
            lo, hi = 0, min(len(a), len(a[0]), len(b), len(b[0]))
            while lo < hi:                          # if a k x k square is shared, so is a smaller one inside it
                mid = (lo + hi + 1) // 2
                if self.shared(a, b, mid):
                    lo = mid
                else:
                    hi = mid - 1
            return lo
    
        def shared(self, a, b, k) -> bool:
            seen = {}                               # hash -> top-left corners in a
            for (i, j), h in self.hashes(a, k).items():
                seen.setdefault(h, []).append((i, j))
            for (i, j), h in self.hashes(b, k).items():
                for ai, aj in seen.get(h, []):
                    if all(a[ai + x][aj:aj + k] == b[i + x][j:j + k] for x in range(k)):   # hashes can clash
                        return True
            return False
    
        def hashes(self, m, k) -> dict:            # hash of every k x k square, by its top-left corner
            rows, cols = len(m), len(m[0])
            p1, p2 = pow(self.B1, k, self.MOD), pow(self.B2, k, self.MOD)
            row = [[0] * (cols - k + 1) for _ in range(rows)]   # step 1: each row, k cells wide
            for r in range(rows):
                h = 0
                for c in range(cols):
                    h = (h * self.B1 + m[r][c]) % self.MOD
                    if c >= k:
                        h = (h - m[r][c - k] * p1) % self.MOD
                    if c >= k - 1:
                        row[r][c - k + 1] = h
            out = {}                                # step 2: k of those row hashes stacked
            for c in range(cols - k + 1):
                h = 0
                for r in range(rows):
                    h = (h * self.B2 + row[r][c]) % self.MOD
                    if r >= k:
                        h = (h - row[r - k][c] * p2) % self.MOD
                    if r >= k - 1:
                        out[(r - k + 1, c)] = h
            return out

    Common mistakes

    • Trusting a hash match without checking the cells, which can give a wrong answer.
    • Rolling the hash without removing the value that leaves the window.
    • Forgetting that the matrices can be different sizes and not square.

    Similar problems