Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #835: Image Overlap

In this guide, we solve Leetcode #835 Image Overlap in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Array, Matrix

Intuition

Grid problems are easiest when you define clear row/column boundaries.

A consistent traversal order prevents off-by-one errors.

Approach

Iterate by rows, columns, or layers depending on the requirement.

Keep bounds updated as the traversal progresses.

Steps:

  • Define bounds or directions.
  • Visit cells in order.
  • Update result and move bounds.

Example

Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]] Output: 3 Explanation: We translate img1 to right by 1 unit and down by 1 unit. The number of positions that have a 1 in both images is 3 (shown in red).

Python Solution

class Solution: def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int: n = len(img1) cnt = Counter() for i in range(n): for j in range(n): if img1[i][j]: for h in range(n): for k in range(n): if img2[h][k]: cnt[(i - h, j - k)] += 1 return max(cnt.values()) if cnt else 0

Complexity

The time complexity is O(n4)O(n^4)O(n4), and the space complexity is O(n2)O(n^2)O(n2), where nnn is the side length of img1\textit{img1}img1. The space complexity is O(n2)O(n^2)O(n2), where nnn is the side length of img1\textit{img1}img1.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy