← Home

835. Image Overlap

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
835

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 835. Image Overlap, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • Brute force
  • time: O(N^4), space: O(1)

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are largestOverlap, non_zero_cells, convolute.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N^4), space: O(N^2)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Brute force
02//Runtime: 116 ms, faster than 53.82% of C++ online submissions for Image Overlap.
03//Memory Usage: 9.3 MB, less than 57.43% of C++ online submissions for Image Overlap.
04//time: O(N^4), space: O(1)
05class Solution {
06public:
07    int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) {
08        int n = A.size();
09        int max_overlap = 0;
10        
11        for(int rshift = -(n-1); rshift <= n-1; ++rshift){
12            for(int cshift = -(n-1); cshift <= n-1; ++cshift){
13                //only shift A
14                int overlap = 0;
15                for(int r = max(0, -rshift); r < min(n, n-rshift); ++r){
16                    for(int c = max(0, -cshift); c < min(n, n-cshift); ++c){
17                        overlap += A[r+rshift][c+cshift] * B[r][c];
18                    }
19                }
20                max_overlap = max(max_overlap, overlap);
21            }
22        }
23        
24        return max_overlap;
25    }
26};
27
28//Approach 2: Linear Transformation
29//Runtime: 212 ms, faster than 26.11% of C++ online submissions for Image Overlap.
30//Memory Usage: 12.8 MB, less than 13.66% of C++ online submissions for Image Overlap.
31//time: O(N^4), space: O(N^2)
32class Solution {
33public:
34    struct pair_hash_int {
35        inline std::size_t operator()(const std::pair<int,int> & v) const {
36            return v.first*31+v.second;
37        }
38    };
39    
40    void non_zero_cells(vector<vector<int>>& mat,
41                       vector<pair<int, int>>& ones){
42        int n = mat.size();
43        
44        for(int i = 0; i < n; ++i){
45            for(int j = 0; j < n; ++j){
46                if(mat[i][j]){
47                    ones.push_back({i, j});
48                }
49            }
50        }
51    };
52    
53    int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) {
54        vector<pair<int, int>> A_ones;
55        vector<pair<int, int>> B_ones;
56        
57        non_zero_cells(A, A_ones);
58        non_zero_cells(B, B_ones);
59        
60        int maxOverlaps = 0;
61        unordered_map<pair<int, int>, int, pair_hash_int> groupCount;
62        
63        for(pair<int, int>& a : A_ones){
64            for(pair<int, int>& b : B_ones){
65                pair<int, int> v = {b.first-a.first, b.second-a.second};
66                ++groupCount[v];
67                maxOverlaps = max(maxOverlaps, groupCount[v]);
68            }
69        }
70        
71        return maxOverlaps;
72    }
73};
74
75//Approach 3: Imagine Convolution
76//Runtime: 228 ms, faster than 25.30% of C++ online submissions for Image Overlap.
77//Memory Usage: 9.8 MB, less than 41.77% of C++ online submissions for Image Overlap.
78//time: O(N^4), space: O(N^2)
79class Solution {
80public:
81    int n;
82    
83    int convolute(vector<vector<int>>& A, vector<vector<int>>& kernel, 
84        int rshift, int cshift){
85        int res = 0;
86        
87        for(int r = 0; r < n; ++r){
88            for(int c = 0; c < n; ++c){
89                res += A[r][c] * kernel[r+rshift][c+cshift];
90            }
91        }
92        
93        return res;
94    };
95    
96    int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) {
97        n = A.size();
98        
99        //padding every side for n-1
100        //the original B is now at the center of B_padded
101        vector<vector<int>> B_padded(3*n-2, vector<int>(3*n-2, 0));
102        
103        for(int r = 0; r < n; ++r){
104            for(int c = 0; c < n; ++c){
105                B_padded[r+n-1][c+n-1] = B[r][c];
106            }
107        }
108        
109        int maxOverlaps = 0;
110        
111        for(int rshift = 0; rshift+n-1 < 3*n-2; ++rshift){
112            for(int cshift = 0; cshift+n-1 < 3*n-2; ++cshift){
113                maxOverlaps = max(maxOverlaps,
114                    convolute(A, B_padded, rshift, cshift));
115            }
116        }
117        
118        return maxOverlaps;
119    }
120};

Cost

Complexity

Time
O(N^4), space: O(N^2)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.