Magicsheet logo

Image Overlap

Medium
25%
Updated 8/1/2025

Asked by 1 Company

Image Overlap

What is this problem about?

The Image Overlap coding problem provides two nimesnn imes n binary matrices, AA and BB. You can slide matrix AA in any direction (up, down, left, right) over matrix BB. After any shift, you count the number of positions where both matrices have a 1. Your goal is to find the maximum possible overlap count.

Why is this asked in interviews?

Google asks this to evaluate a candidate's ability to optimize geometric simulations. A naive approach of trying every possible shift (2nimes2n2n imes 2n) and then comparing matrices (n2n^2) results in O(n4)O(n^4) complexity. For n=30n=30, this is fine, but interviewers want to see if you can use Coordinate Mapping to focus only on the relevant points (the 1s), which is a common strategy in image processing and computer vision.

Algorithmic pattern used

The problem uses Coordinate Differencing and a Frequency Map.

  1. List the coordinates (r,c)(r, c) of all 1s in matrix AA and all 1s in matrix BB.
  2. Iterate through every pair of 1s: (ra,ca)(r_a, c_a) from AA and (rb,cb)(r_b, c_b) from BB.
  3. Calculate the "shift vector" required to align these two 1s: V=(rbra,cbca)V = (r_b - r_a, c_b - c_a).
  4. Use a Hash Map to count the frequency of each unique shift vector.
  5. The shift vector that appears most frequently represents the translation that maximizes the overlap.

Example explanation

Matrix A has 1s at: (0,0) and (1,1). Matrix B has 1s at: (1,1) and (2,2).

  1. Pair (0,0) and (1,1): Shift = (1, 1).
  2. Pair (0,0) and (2,2): Shift = (2, 2).
  3. Pair (1,1) and (1,1): Shift = (0, 0).
  4. Pair (1,1) and (2,2): Shift = (1, 1). Shift (1, 1) appears twice. Max overlap = 2.

Common mistakes candidates make

  • Brute Force Simulation: Implementing the O(n4)O(n^4) nested loop which is much harder to get right due to boundary checks for each shift.
  • Coordinate Encoding: Not using a proper key for the Hash Map (e.g., using a string "dr,dc" instead of a unique integer like dr * 100 + dc).
  • Ignoring Sparse Data: Failing to realize that if the number of 1s is small, the coordinate approach is vastly superior.

Interview preparation tip

When dealing with translations or "alignments" of points, think about the difference between coordinates. If multiple pairs share the same difference vector, they will all overlap under that specific translation. This is a foundational trick in geometry and pattern matching.

Similar Questions