#835

Image Overlap

Medium
ArrayMatrixHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n²)
💡

Intuition

Time O(n²)Space O(n²)

The optimal solution leverages a hashmap to count the translations that yield overlaps. By using the positions of 1s in both matrices, we can efficiently calculate the maximum overlap without redundant checks.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a hashmap to count overlaps for each translation vector derived from 1s in both images.
  2. 2Step 2: For each 1 in img1, calculate its translation vector to each 1 in img2.
  3. 3Step 3: Increment the count in the hashmap for each translation vector.
  4. 4Step 4: The maximum value in the hashmap is the largest overlap.
solution.py14 lines
1from collections import defaultdict
2
3def largestOverlap(img1, img2):
4    n = len(img1)
5    count = defaultdict(int)
6    for i in range(n):
7        for j in range(n):
8            if img1[i][j] == 1:
9                for x in range(n):
10                    for y in range(n):
11                        if img2[x][y] == 1:
12                            dx, dy = i - x, j - y
13                            count[(dx, dy)] += 1
14    return max(count.values(), default=0)

Complexity note: The time complexity remains O(n²) as we still check all pairs of 1s, but we use a hashmap to store translation counts, which requires O(n²) space in the worst case.

  • 1Understanding translations is crucial for overlap calculation.
  • 2Using a hashmap can significantly reduce redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.