Image Overlap LeetCode

In the world of computer vision and image processing, the challenge of image overlap is intriguing. It identifies common regions between two distinct images. The LeetCode image overlap problem mirrors real-world scenarios where precise alignment is vital, such as in medical imaging and satellite analysis. Now, let's consider a scenario to understand image overlap:

Example of image overlap
Example of image overlap

This visual example lays the foundation for the concepts we'll explore further in the problem statement.

Problem statement

We are given two square binary matrices, Image A and Image B, of size (n×n)(n \times n) . Our task is to find the maximum overlap between them by shifting either Image A or Image B up, down, left, or right. The overlap is the count of positions where both matrices have a 1.

Some important points that need to be remembered while solving this problem:

  1. We can slide either Image A or B, but not both, to find the maximum overlap.

  2. The sliding operation doesn't involve rotating the images, only shifting them horizontally or vertically.

  3. If a 1 in one of the images is shifted outside the matrix boundary during the sliding operation, it is considered erased and does not contribute to the overlap.

  4. Image A and Image B have the same size, (n×nn \times n).

Our task is to determine the largest possible overlap that can be achieved between Image A and Image B under these constraints. The result should be an integer representing the maximum overlap. Now, let's map our previous example to the problem for better understanding.


Consider the same example and convert these blue and white boxes into their binary representations where blue boxes will be considered as 1’s and white boxes are considered as 0’s.
Consider the same example and convert these blue and white boxes into their binary representations where blue boxes will be considered as 1’s and white boxes are considered as 0’s.
1 of 11

Note: In our current case, we found the best overlap in a single image translation. However, in different scenarios, we might need different translation (up, down, left, right) to achieve the maximum overlap in an image.

Knowledge test

Now that we have understood the problem, let’s check our knowledge by finding the maximum overlap of the example below:

Knowledge test
Knowledge test

Algorithm

Now that we’ve understood the problem, let’s understand it programmatically. The idea is to slide one matrix over the other and look for all possible overlaps in the up, down, left, and right directions. Educative 99 helps you solve complex coding problems like image overlap by teaching you to recognize patterns and apply the right algorithms.

Here’s how the algorithm works:

  1. We start sliding Image A on the Image B in a loop.

    1. We start with the index [0][0][0][0] of the matrix.

    2. Within this loop, we run a nested loop to check for the overlap in each iteration.

      1. In this nested loop, we count the ones in the current overlapped area.

      2. If the count of overlapping ones is greater than the previous counts, we update the maximum overlaps.

Image overlap algorithmic approach
Image overlap algorithmic approach
1 of 24

Note: In the context of this algorithm, we don't introduce any extra 0's when determining the overlap between two images. Instead, we slide one image over the other to identify the maximum overlap between images A and B.

Coding example

Let’s have a look at the code for the algorithm we just discussed:

# count overlaps in arrays:
def find_max_overlap(row, col, A, B):
# Initialize variables to store an overlap in different directions
overlap_right_down = 0
overlap_right_up = 0
overlap_left_down = 0
overlap_left_up = 0
n = len(A) # Assuming A and B are square matrices of size n x n
for i in range(n):
for j in range(n):
# Calculate overlap in the right-down direction
if i + row < n and j + col < n:
overlap_right_down += A[i + row][j + col] & B[i][j]
# Calculate overlap in the left-down direction
if i - row >= 0 and j + col < n:
overlap_left_down += A[i - row][j + col] & B[i][j]
# Calculate overlap in the left-up direction
if i - row >= 0 and j - col >= 0:
overlap_left_up += A[i - row][j - col] & B[i][j]
# Calculate overlap in the right-up direction
if j - col >= 0 and i + row < n:
overlap_right_up += A[i + row][j - col] & B[i][j]
# Return the maximum overlap among the four directions
return max(overlap_right_down, overlap_left_down, overlap_right_up, overlap_left_up)
def largestOverlap(A,B):
max_overlap = 0
# slides over the whole matrix in loops
for i in range(len(A)):
for j in range(len(A)):
# calculate and update the maximum overlap in current iteration
max_overlap = max(max_overlap, find_max_overlap(i, j, A, B))
return max_overlap
# ---------------------------------------------------------------
A = [[0,0,0],
[0,1,1],
[0,0,0]]
B = [[0,0,0],
[1,1,0],
[0,1,0]]
print("The largest overlap is :",largestOverlap(A,B))

Code explanation

  • Line 2: The find_max_overlap function slides one position up, down, left, and right and finds the maximum number of 1’s overlapping in the given arrangement.

  • Lines 11–27: In the nested for loops, we iterate through the elements of matrices A and B to check for overlapping 1’s. We use four variables—overlap_right_down, overlap_right_up, overlap_left_down, and overlap_left_up—to keep track of the count of overlapping 1’s in different directions: right-down, right-up, left-down, and left-up.

  • Line 14: We calculate the overlap in the right-down direction by checking if we can move one matrix A down and to the right without going out of bounds. If so, we increment the count based on the overlapping values of A and B. (The same translations are performed for other directions in lines 18–27)

  • Line 30: The find_max_overlap function returns the maximum overlap among the four directions by finding the maximum value among overlap_right_down, overlap_left_down, overlap_right_up, and overlap_left_up.

  • Line 33: The largestOverlap function iterates over the entire matrix, considering different starting positions for A and B to calculate the maximum overlap in all possible arrangements. The maximum overlap is stored in the max_overlap variable and returned at the end.

Time complexity

The time complexity of the solution is O(n4)O(n^4). where n×nn \times n represents the size of square matrices A and B. This is due to the presence of four nested loops, with two in the find_max_overlap function and two in the largestOverlap function. In each iteration of these loops, calculations depend on the size of the matrices, leading to a quartic time complexity concerning n.

Space complexity

The space complexity of the provided solution is constant, denoted as O(1)O(1). The algorithm uses a fixed amount of additional space for variables and loop counters, regardless of the size of the input matrices. It does not create any data structures proportional to the input size, resulting in a constant space complexity.

Copyright ©2024 Educative, Inc. All rights reserved