Image Overlap - 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.

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 of the matrix borders are erased.

Return the largest possible overlap.

Input & Output

Example 1 — Basic Translation
$ Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
Output: 3
💡 Note: We translate img1 to the right by 1 unit. After translation: img1[0][1] aligns with img2[0][1], img1[1][1] aligns with img2[1][1], and img1[2][1] aligns with img2[2][1]. Total overlap is 3.
Example 2 — No Translation Needed
$ Input: img1 = [[1]], img2 = [[1]]
Output: 1
💡 Note: Both images have a single 1 at position (0,0). No translation needed, overlap is 1.
Example 3 — No Overlap Possible
$ Input: img1 = [[0,0],[0,0]], img2 = [[1,1],[1,1]]
Output: 0
💡 Note: img1 has no 1s, so regardless of translation, there can be no overlap with img2's 1s.

Constraints

  • n == img1.length == img1[i].length
  • n == img2.length == img2[i].length
  • 1 ≤ n ≤ 30
  • img1[i][j] is either 0 or 1
  • img2[i][j] is either 0 or 1

Visualization

Tap to expand
Image Overlap Problem110010010img1000011001img2011010011Translated img1Slide img1 right by 1 unitMaximum Overlap: 3 positions★ Orange borders show overlapping 1s ★
Understanding the Visualization
1
Input Images
Two binary matrices with 1s at different positions
2
Slide & Count
Try different translations and count overlapping 1s
3
Maximum Overlap
Return the highest overlap count found
Key Takeaway
🎯 Key Insight: Only positions with 1s matter for overlap calculation
Asked in
Google 25 Facebook 20 Amazon 15
58.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen