Similar Problems

Similar Problems not available

Image Overlap - Leetcode Solution

Companies:

LeetCode:  Image Overlap Leetcode Solution

Difficulty: Medium

Topics: matrix array  

Problem Statement:

Given two binary matrices A and B, you need to find the maximum number of positions at which the two matrices have the same value.

Solution:

Approach: The idea for solving this problem is pretty simple. First, we need to find all possible shifts of matrix B with respect to matrix A. We can do this by iterating over all the rows and columns of matrix A and then calculating the overlap of elements in matrix A and B. For each shift, we can count the number of overlapping elements and store the maximum count. This will give us the maximum number of positions at which the two matrices have the same value.

Algorithm:

  1. Initialize a variable max_overlap to 0.
  2. Iterate over all rows and columns of matrix A. a. For each row and column pair (i,j), define a shift (di, dj) = (i, j) - (0, 0). b. For each shift (di, dj), iterate over all rows and columns of matrix B. i. If the shifted position (i+di, j+dj) is within the range of both matrix A and B, and the values of elements in matrix A and B at these positions are both 1, increment a variable overlap by 1. c. After iterating over all possible shifts for matrix B, update the max_overlap by comparing it with the current overlap count.
  3. Return the max_overlap.

Time Complexity: The time complexity of this algorithm is O(n^4), where n is the size of the matrices A and B.

Code:

class Solution: def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int: max_overlap = 0

    n = len(A)
    for i in range(n):
        for j in range(n):
            overlap = 0
            for di in range(-n+1, n):
                for dj in range(-n+1, n):
                    if i+di>=0 and i+di<n and j+dj>=0 and j+dj<n and i+di<n and j+dj<n:
                        if A[i+di][j+dj] == 1 and B[i+di][j+dj] == 1:
                            overlap += 1
            max_overlap = max(max_overlap, overlap)
    return max_overlap

Explanation: The solution starts by initializing a variable max_overlap to 0. Then it iterates over all rows and columns of matrix A using nested for loops. For each row and column pair (i,j), it defines a shift (di, dj) with respect to (0, 0). Then for each shift, it iterates over all rows and columns of matrix B using nested for loops. If the shifted position (i+di, j+dj) is within the range of both matrix A and B, and the values of elements in matrix A and B at these positions are both 1, it increments a variable overlap by 1. After iterating over all possible shifts for matrix B, it updates the max_overlap by comparing it with the current overlap count. Finally, it returns the max_overlap.

Image Overlap Solution Code

1