Maximize Binary Image Overlap by Translation

Quick Overview

Maximize Binary Image Overlap by Translation. Translate one n-by-n binary image horizontally and vertically by integer offsets, without rotating it.

Maximize Binary Image Overlap by Translation

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Translate one n-by-n binary image horizontally and vertically by integer offsets, without rotating it. Bits moved outside the image boundary are discarded. Return the largest number of positions containing 1 in both translated img 1 and img 2. ```cpp class Solution { public: int largestOverlap(vector<vector<int>>& img1, vector<vector<int>>& img2); }; ``` ### Examples **Example 1:** ```text img1 = [[1,0],[1,0]], img2 = [[0,1],[0,1]] Output: 2 Explanation: Shift img1 one column right, aligning both ones. ``` **Example 2:** ```text img1 = [[1,0],[0,1]], img2 = [[0,1],[1,0]] Output: 1 Explanation: A translation can align one pair, but matching both would require different offsets. ``` ### Constraints - Both images are n-by-n with 1 <= n <=30. - All cells are binary. ### Contract considerations Count overlap only, allowing arbitrary integer translation but no rotation. ```hint Read the boundary condition What displacement aligns one chosen pair of1 cells? ``` ### Boundary reminders Count overlap only, allowing arbitrary integer translation but no rotation.

Overview: Maximize Binary Image Overlap by Translation. Translate one n-by-n binary image horizontally and vertically by integer offsets, without rotating it.

Google logo
Google
Source window: 0–3 months · as of Oct 21, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Translate one n-by-n binary image horizontally and vertically by integer offsets, without rotating it. Bits moved outside the image boundary are discarded. Return the largest number of positions containing 1 in both translated img 1 and img 2.

class Solution {
public:
    int largestOverlap(vector<vector<int>>& img1, vector<vector<int>>& img2);
};

Examples

Example 1:

img1 = [[1,0],[1,0]], img2 = [[0,1],[0,1]]
Output: 2
Explanation: Shift img1 one column right, aligning both ones.

Example 2:

img1 = [[1,0],[0,1]], img2 = [[0,1],[1,0]]
Output: 1
Explanation: A translation can align one pair, but matching both would require different offsets.

Constraints

  • Both images are n-by-n with 1 <= n <=30.
  • All cells are binary.

Contract considerations

Count overlap only, allowing arbitrary integer translation but no rotation.

Boundary reminders

Count overlap only, allowing arbitrary integer translation but no rotation.