You are given two binary matrices img1 and img2 each of size n x n. An image overlap is the number of positions that have a 1 in both matrices. We need to translate one of the images in each of the eight possible directions (left, right, up, down) and count the maximum number of overlapping 1s for any such translation of one image over the other.
Implement a function int largestOverlap(int[][] img1, int[][] img2) that returns the maximum number of overlapping 1’s.
n x n.n could range from 1 to 30 given typical constraints for interview scenarios.We will use a combination of brute-force and clever shifting to solve the problem effectively:
1s.maxCount to keep track of the maximum overlap.dy and dx are integer values ranging from -(n-1) to n-1.img1 and the shifted img2.maxCount whenever a higher overlap count is found.maxCount.public class ImageOverlap {
public int largestOverlap(int[][] img1, int[][] img2) {
int n = img1.length;
int maxCount = 0;
for (int dy = -n + 1; dy < n; dy++) {
for (int dx = -n + 1; dx < n; dx++) {
maxCount = Math.max(maxCount, countOverlap(img1, img2, dy, dx));
}
}
return maxCount;
}
private int countOverlap(int[][] img1, int[][] img2, int dy, int dx) {
int n = img1.length;
int overlap = 0;
for (int y = 0; y < n; y++) {
for (int x = 0; x < n; x++) {
if (y + dy < 0 || y + dy >= n || x + dx < 0 || x + dx >= n) {
continue;
}
if (img1[y][x] == 1 && img2[y + dy][x + dx] == 1) {
overlap++;
}
}
}
return overlap;
}
public static void main(String[] args) {
ImageOverlap io = new ImageOverlap();
int[][] img1 = {
{1, 1, 0},
{0, 1, 0},
{0, 1, 0}
};
int[][] img2 = {
{0, 0, 0},
{0, 1, 1},
{0, 0, 1}
};
System.out.println(io.largestOverlap(img1, img2)); // Output should be 3
}
}
The time complexity of this algorithm is O(n^4) where n is the size of the matrix:
(n-1) to (n-1) results in O(n^2) combinations.Thus, the total complexity is O(n^4). While this may seem high, it is typically manageable for n up to around 30, given typical interview constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?