835. Image Overlap
Difficulty: Medium
Topics: Senior Staff, Array, Matrix, Weekly Contest 84
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.
We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images.
Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside the matrix borders are erased.
Return the largest possible overlap.
Example 1:
- 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.
- The number of positions that have a 1 in both images is 3 (shown in red).
- We translate img1 to right by 1 unit and down by 1 unit.
Example 2:
- Input: img1 = [[1]], img2 = [[1]]
- Output: 1
Example 3:
- Input: img1 = [[0]], img2 = [[0]]
- Output: 0
Example 4:
- Input: img1 = [[1,0],[0,0]], img2 = [[0,0],[0,1]]
- Output: 1
Example 5:
- Input: img1 = [[1,1],[1,1]], img2 = [[1,1],[1,1]]
- Output: 4
Example 6:
- Input: img1 = [[1,0],[0,0]], img2 = [[0,0],[0,1]]
- Output: 1
Example 7:
- Input: img1 = [[0,0],[0,0]], img2 = [[1,1],[1,1]]
- Output: 0
Example 8:
- Input: img1 = [[0]], img2 = [[1]]
- Output: 0
Example 9:
- Input: img1 = [[1,1,1],[1,1,1],[1,1,1]], img2 = [[0,0,0],[0,1,1],[0,1,1]]
- Output: 4
Constraints:
n == img1.length == img1[i].lengthn == img2.length == img2[i].length1 <= n <= 30-
img1[i][j]is either0or1. -
img2[i][j]is either0or1.
Solution:
We solve the image overlap problem by identifying all positions of 1s in both images, then computing the translation vectors that align each 1 in img1 with each 1 in img2. By counting how many pairs share the same translation vector, we determine the maximum possible overlap without explicitly simulating every possible shift.
Approach
-
Extract
1positions: Traverse both matrices and store the coordinates of every cell containing1into separate lists (ones1andones2). -
Compute translation vectors: For every pair
(pos1, pos2)wherepos1is fromimg1andpos2is fromimg2, calculate the shift(dx, dy) = (pos2[0] - pos1[0], pos2[1] - pos1[1]). -
Count frequency of each vector: Use a hash map keyed by
"dx,dy"to count how many pairs share the same translation. The value for a key represents how many1s fromimg1would overlap with1s fromimg2under that translation. - Track maximum: Continuously update the maximum overlap seen so far.
- Return result: The highest count is the largest possible overlap.
Let's implement this solution in PHP: 835. Image Overlap
<?php
/**
* @param Integer[][] $img1
* @param Integer[][] $img2
* @return Integer
*/
function largestOverlap(array $img1, array $img2): int
{
...
...
...
/**
* go to ./solution.php
*/
}
// Test cases
echo largestOverlap([[1, 1, 0], [0, 1, 0], [0, 1, 0]], [[0, 0, 0], [0, 1, 1], [0, 1, 1]]) . "\n"; // Output: 3
echo largestOverlap([[1]], [[1]]) . "\n"; // Output: 1
echo largestOverlap([[0]], [[0]]) . "\n"; // Output: 0
echo largestOverlap([[1,0],[0,0]], [[0,0],[0,1]]) . "\n"; // Output: 1
echo largestOverlap([[1,1],[1,1]], [[1,1],[1,1]]) . "\n"; // Output: 4
echo largestOverlap([[1,0],[0,0]], [[0,0],[0,1]]) . "\n"; // Output: 1
echo largestOverlap([[0,0],[0,0]], [[1,1],[1,1]]) . "\n"; // Output: 0
echo largestOverlap([[0]], [[1]]) . "\n"; // Output: 0
echo largestOverlap([[1,1,1],[1,1,1],[1,1,1]], [[0,0,0],[0,1,1],[0,1,1]]) . "\n"; // Output: 4
?>
Explanation:
-
Why translation vectors work: Shifting
img1by(dx, dy)moves each1at(i, j)to(i+dx, j+dy). If this new position coincides with a1inimg2at(i', j'), thendx = i' - ianddy = j' - j. Thus, each aligned pair defines a unique translation. -
Grouping by vector: Multiple pairs can share the same
(dx, dy). The number of pairs with the same vector equals the number of overlapping1s for that shift. -
Ignoring invalid shifts: Translations that push
1s outside the matrix borders automatically produce no overlap because those positions cannot match any1in the other image. Our counting method only considers pairs that can actually align, so invalid shifts naturally yield lower counts. -
Efficiency: Instead of checking all
(2n-1)²possible shifts (up to ~3481 for n=30), we only consider pairs of1s. In the worst case (all ones), there aren²ones per image, givingn⁴pairs — for n=30, that's 810,000 pairs, which is manageable.
Complexity Analysis
-
Time Complexity:
O(n⁴)in the worst case, wherenis the matrix dimension.- Extracting ones:
O(n²). - Pairwise translation computation:
O(k1 * k2)wherek1andk2are the number of ones inimg1andimg2. In the worst case (all ones),k1 = k2 = n², soO(n⁴). - Hash map operations:
O(1)average per pair.
- Extracting ones:
-
Space Complexity:
O(n⁴)in the worst case for the hash map storing up tok1 * k2distinct translation vectors. In practice, distinct vectors are bounded by(2n-1)², so space isO(n²)for the map plusO(n²)for the position lists.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

Top comments (0)