864. Image Overlap
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the maximum overlap between two n x n binary images, img1 and img2, after translating one image relative to the other. A translation involves sliding one image horizontally and vertically. The overlap is the count of positions where both images have a 1.
Solution
Image Overlap in Python
class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
n = len(img1)
ones1 = []
ones2 = []
# Step 1: Extract coordinates of 1s from both images.
for r in range(n):
for c in range(n):
if img1[r][c] == 1:
ones1.append((r, c))
if img2[r][c] == 1:
ones2.append((r, c))
# Dictionary to store frequency of each translation vector.
# The key is a tuple (dy, dx) representing the vector.
counts = {}
# Step 2: Calculate and count translation vectors.
for r1, c1 in ones1:
for r2, c2 in ones2:
dy = r2 - r1
dx = c2 - c1
vec = (dy, dx)
counts[vec] = counts.get(vec, 0) + 1
# Step 3: Find the maximum count.
# If counts is empty (e.g., no 1s in one image), max of an empty sequence would error.
# So we add 0 to handle this case, returning 0 if counts is empty.
return max(counts.values()) if counts else 0
Image Overlap in Java
class Solution {
public int largestOverlap(int[][] img1, int[][] img2) {
int n = img1.length;
List<int[]> ones1 = new ArrayList<>();
List<int[]> ones2 = new ArrayList<>();
// Step 1: Extract coordinates of 1s from both images.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (img1[i][j] == 1) {
ones1.add(new int[]{i, j});
}
if (img2[i][j] == 1) {
ones2.add(new int[]{i, j});
}
}
}
// Map to store frequency of each translation vector.
// Key is an encoded integer representing the vector (dy, dx).
// Value is the count.
Map<Integer, Integer> counts = new HashMap<>();
// Step 2: Calculate and count translation vectors.
for (int[] p1 : ones1) {
for (int[] p2 : ones2) {
int dy = p2[0] - p1[0];
int dx = p2[1] - p1[1];
// Encode the vector (dy, dx) into a single integer.
// dy and dx are in [-n+1, n-1]. A simple encoding is dy * C + dx.
// Since n <= 30, |dy|, |dx| < 30. Using 100 as multiplier is safe.
int key = dy * 100 + dx;
counts.put(key, counts.getOrDefault(key, 0) + 1);
}
}
int maxOverlap = 0;
// Step 3: Find the maximum count.
for (int count : counts.values()) {
maxOverlap = Math.max(maxOverlap, count);
}
return maxOverlap;
}
}
Image Overlap in C++
class Solution {
public:
int largestOverlap(vector<vector<int>>& img1, vector<vector<int>>& img2) {
int n = img1.size();
vector<pair<int, int>> ones1, ones2;
// Step 1: Extract coordinates of 1s from both images.
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (img1[i][j] == 1) {
ones1.push_back({i, j});
}
if (img2[i][j] == 1) {
ones2.push_back({i, j});
}
}
}
// Map to store frequency of each translation vector.
// The key is the translation vector (dy, dx), value is the count.
map<pair<int, int>, int> counts;
// Step 2: For each pair of '1's from img1 and img2, calculate the translation vector.
for (const auto& p1 : ones1) {
for (const auto& p2 : ones2) {
int dy = p2.first - p1.first;
int dx = p2.second - p1.second;
// Increment the count for this vector.
counts[{dy, dx}]++;
}
}
int maxOverlap = 0;
// Step 3: Find the maximum count, which represents the largest overlap.
for (const auto& entry : counts) {
maxOverlap = max(maxOverlap, entry.second);
}
// If there are no 1s in one of the images, counts will be empty, and maxOverlap remains 0.
return maxOverlap;
}
};
Image Overlap in TypeScript
function largestOverlap(img1: number[][], img2: number[][]): number {
const n = img1.length;
const ones1: number[][] = [];
const ones2: number[][] = [];
// Step 1: Extract coordinates of 1s from both images.
for (let r = 0; r < n; r++) {
for (let c = 0; c < n; c++) {
if (img1[r][c] === 1) {
ones1.push([r, c]);
}
if (img2[r][c] === 1) {
ones2.push([r, c]);
}
}
}
// Map to store frequency of each translation vector.
// Key is a string "dy,dx", value is the count.
const counts = new Map<string, number>();
// Step 2: Calculate and count translation vectors.
for (const p1 of ones1) {
for (const p2 of ones2) {
const dy = p2[0] - p1[0];
const dx = p2[1] - p1[1];
const key = `${dy},${dx}`;
counts.set(key, (counts.get(key) || 0) + 1);
}
}
let maxOverlap = 0;
// Step 3: Find the maximum count.
for (const count of counts.values()) {
maxOverlap = Math.max(maxOverlap, count);
}
return maxOverlap;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.