Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

835. Image Overlap

ArrayMatrix

Explanation:

To solve this problem, we can iterate over all possible translations of one image over the other and count the number of overlapping 1s. We can achieve this by trying all possible translations (left, right, up, down) and counting the overlapping 1s. The maximum count of overlapping 1s will give us the largest possible overlap.

Here is the step-by-step approach:

  1. Iterate through all possible translations of img1 over img2.
  2. For each translation, count the number of overlapping 1s by comparing the corresponding positions in both images.
  3. Keep track of the maximum count of overlapping 1s.
  4. Return the maximum count as the largest possible overlap.

Time Complexity: O(n^4) where n is the size of the input matrix Space Complexity: O(1)

class Solution {
    public int largestOverlap(int[][] img1, int[][] img2) {
        int n = img1.length;
        int maxOverlaps = 0;
        
        for (int rowOffset = -n + 1; rowOffset < n; rowOffset++) {
            for (int colOffset = -n + 1; colOffset < n; colOffset++) {
                int overlaps = 0;
                
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        if ((i + rowOffset >= 0 && i + rowOffset < n) && (j + colOffset >= 0 && j + colOffset < n)) {
                            overlaps += img1[i][j] & img2[i + rowOffset][j + colOffset];
                        }
                    }
                }
                
                maxOverlaps = Math.max(maxOverlaps, overlaps);
            }
        }
        
        return maxOverlaps;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.