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 Problem INPUT img1 (3x3) 1 1 0 0 1 0 0 1 0 img2 (3x3) 0 0 0 0 1 1 0 0 1 ALGORITHM STEPS 1 Extract 1s positions img1: (0,0)(0,1)(1,1)(2,1) img2: (1,1)(1,2)(2,2) 2 Calculate translation For each pair of 1s, compute delta (dx, dy) 3 Count translations Use hashmap to count frequency of each delta Best Translation: (1, 0) (0,0)-->(1,0): delta(1,0) (0,1)-->(1,1): delta(1,0) (1,1)-->(2,1): delta(1,0) Count: 3 overlaps! 4 Find maximum Return highest count from all translations FINAL RESULT After shifting img1 right by 1 1 1 1+1 1 1+1 1+1 = Overlap (both 1s) 3 positions overlap! OUTPUT 3 Key Insight: Focus on 1s Only Instead of trying all possible translations (O(n^4)), we focus only on positions containing 1s. For each pair of 1s from both images, calculate the translation vector (delta). The translation with the highest frequency gives the maximum overlap. Time: O(n^4), Space: O(n^2). TutorialsPoint - Image Overlap | Focus on 1s Only Approach
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