Image Overlap — LeetCode 835 Python Solution

MediumArrayMatrix
Problem
#835
Reading time
2 min

The problem

You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values.

Example

Input
img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
Output
3
Explanation
We translate img1 to right by 1 unit and down by 1 unit.

Python solution

Python
class Solution:
    def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
        n = len(img1)
        cnt = Counter()
        for i in range(n):
            for j in range(n):
                if img1[i][j]:
                    for h in range(n):
                        for k in range(n):
                            if img2[h][k]:
                                cnt[(i - h, j - k)] += 1
        return max(cnt.values()) if cnt else 0

Complexity

MeasureComplexity
TimeO(n^4)
SpaceO(n^2), where n is the side length of \textit{img1} auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 835. Image Overlap is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 835. Image Overlap?
LeetCode 835. Image Overlap is rated Medium on LeetCode.
What is the time complexity of LeetCode 835. Image Overlap?
The Python solution on this page runs in O(n^4).
What is the space complexity of LeetCode 835. Image Overlap?
The Python solution on this page uses O(n^2), where n is the side length of \textit{img1} auxiliary space.
What topics does LeetCode 835. Image Overlap cover?
LeetCode 835. Image Overlap is tagged Array and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview