Image Overlap (LeetCode 835): Solution and Explanation

Medium
Array
Matrix
Hash Table

Slide one binary n x n image over another (no rotation, cells past the edge are lost) and return the largest number of positions where both images hold a 1.

Intuition

The direct idea is to try every shift (dr, dc) from -(n-1) to n-1 in both directions and count matching 1s for each. That is (2n-1)^2 shifts times n^2 cells, which works for small n but wastes time on zeros.

Flip the question around. Take one 1 at a in img1 and one 1 at b in img2. There is exactly one shift that drops a onto b: the vector b - a. So each pair of 1s is a vote for one specific shift.

The overlap produced by a shift is just the number of pairs that voted for it, because every overlapping position under that shift is one such pair. Count the votes in a (2n-1) x (2n-1) tally and the biggest tally is the answer.

Zeros never vote, so sparse images finish much faster than the shift-by-shift scan.

Approach: Count shift vectors

  1. Let size = 2n - 1 and make a tally of size * size zeros.
  2. Collect the coordinates of every 1 in img1 into a and every 1 in img2 into b.
  3. For each (ar, ac) in a and each (br, bc) in b, compute the shift (br - ar, bc - ac) and add one to its tally slot (br - ar + n - 1) * size + (bc - ac + n - 1).
  4. Keep best as the largest tally seen and return it (0 when either image has no 1s).

Step-by-step example

img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
  1. Ones of img1: a = (0,0), (0,1), (1,1), (2,1). Ones of img2: b = (1,1), (1,2), (2,2).
  2. (0,0) votes for shifts (1,1), (1,2) and (2,2). best = 1.
  3. (0,1) votes for (1,0), (1,1) and (2,1). Shift (1,1) now has 2 votes, so best = 2.
  4. (1,1) votes for (0,0), (0,1) and (1,1). Shift (1,1) reaches 3 votes, best = 3.
  5. (2,1) votes for (-1,0), (-1,1) and (0,1). No tally passes 3, so the answer is 3: move img1 down one and right one.

Code: Python, Java, C++

1class Solution:
2    def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
3        n = len(img1)
4        size = 2 * n - 1
5        a = [(r, c) for r in range(n) for c in range(n) if img1[r][c]]
6        b = [(r, c) for r in range(n) for c in range(n) if img2[r][c]]
7        count = [0] * (size * size)
8        best = 0
9        for ar, ac in a:
10            for br, bc in b:
11                key = (br - ar + n - 1) * size + (bc - ac + n - 1)
12                count[key] += 1
13                best = max(best, count[key])
14        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^4)

With A ones in img1 and B ones in img2 the double loop runs A * B times. Both are at most n^2, so the worst case is n^4, but sparse images are much cheaper.

Space

O(n^2)

The tally has (2n - 1)^2 slots and the two coordinate lists hold at most n^2 entries each.

Other approaches

Try every shift (time O(n^4), space O(1))

Loop over all (2n - 1)^2 shifts and, for each, count cells where the shifted img1 and img2 both hold 1. Simple and always n^4, regardless of how many 1s there are.

Bitmask rows (time O(n^3), space O(n))

Store each row as an integer bitmask. A horizontal shift becomes a bit shift and the overlap of a row pair is popcount(x & y), which cuts the inner loop to O(1) word operations for n up to 64.

Common mistakes

  • Forgetting negative shifts. img1 may move up or left, so dr and dc range from -(n - 1) to n - 1, and the tally index must add n - 1 before use.
  • Using a hash key such as dr * n + dc. Different shifts collide (for example (0, n) and (1, 0)); use a stride of 2n - 1 or a tuple key.
  • Returning the number of distinct shifts or the shift itself instead of the largest vote count.
  • Treating it as a cyclic shift. Cells pushed off the edge disappear; they never wrap around.

Frequently asked questions

Why does the vote count equal the overlap?

Under a fixed shift, each overlapping position pairs one 1 of img1 with one 1 of img2, and that pair voted for exactly this shift. Different positions give different pairs, so the counts match.

Do I need to check that the shifted cell stays inside the grid?

No. Both cells of a voting pair are inside their grids by construction, so every vote describes an overlap that really exists after the shift.

Is translating img2 instead of img1 different?

No. Moving img2 by (dr, dc) gives the same overlap as moving img1 by (-dr, -dc), so the maximum is the same.

What is the time complexity of Image Overlap?

O(A * B) for A and B ones, which is O(n^4) in the worst case when both images are full of 1s. Space is O(n^2) for the tally.