2D Matrix Cross-Correlation Filter
Arrays & HashingAuto-graded · 23 test casesLast updated
Compute the 2D cross-correlation between a grid matrix and a filter kernel using valid padding and stride 1.
Given a 2D grid matrix input_matrix of dimensions $H \times W$ and a 2D filter matrix kernel of dimensions $K_H \times K_W$, compute the 2D discrete cross-correlation (also known as standard deep-learning convolution without kernel flipping). Use standard valid padding (no zero-padding) and a stride of 1.
The output value at coordinate $(r, c)$ is defined as:
$$\text{output}[r][c] = \sum_{i=0}^{K_H-1} \sum_{j=0}^{K_W-1} \text{input_matrix}[r+i][c+j] \times \text{kernel}[i][j]$$
The output grid shape is $(H - K_H + 1) \times (W - K_W + 1)$.
Return the computed 2D matrix as a list of lists. If $H < K_H$, return an empty list []. If $H \ge K_H$ but $W < K_W$, return a list of $H - K_H + 1$ empty lists.
Constraints
- $1 \le H, W \le 100$
- $1 \le K_H, K_W \le 100$
- Inputs contain numbers (integers or floats).
Examples
Example 1
Input: convolve_2d([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], [[1, 0, -1], [1, 0, -1], [1, 0, -1]])
Output: [[-6, -6], [-6, -6]]
Example 2
Input: convolve_2d([[1, 2, 0, -1], [3, 4, 5, 2], [-2, 1, 3, 0], [4, -1, 2, 6]], [[0, 1, 0], [-1, 2, -1], [0, 1, 0]])
Output: [[3, 7], [4, 12]]
Example 3
Input: convolve_2d([[2, 0, -1, 3], [-4, 5, 2, 1], [6, -2, 0, 4], [1, 3, -5, 2]], [[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
Output: [[-1, -1], [6, 15]]
Hints
Hint 1
Calculate the output grid dimensions as out_h = H - K_H + 1 and out_w = W - K_W + 1.
Hint 2
Cross-correlation applies the kernel elements directly as given, without flipping the kernel axes.
Hint 3
Ensure edge cases where the kernel is larger than the input matrix return empty outer or inner lists appropriately.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks for valid 2D discrete cross-correlation between a 2D input matrix and a kernel matrix with stride 1 and no padding.
-
Grid Dimensions: For an input grid of size $H \times W$ and a filter kernel of size $K_H \times K_W$, the resulting grid has height $out_h = H - K_H + 1$ and width $out_w = W - K_W + 1$.
-
Boundary and Empty Outputs:
- If $out_h \le 0$, the kernel height exceeds the input height, so return an empty list
[]. - If $out_h > 0$ but $out_w \le 0$, return $out_h$ empty lists (
[[] for _ in range(out_h)]).
- If $out_h \le 0$, the kernel height exceeds the input height, so return an empty list
-
Window Extraction and Calculation: Iterate over each starting position $(r, c)$ in the input grid where $0 \le r < out_h$ and $0 \le c < out_w$. For each position, compute the elementwise product sum between the input patch of size $K_H \times K_W$ starting at $(r, c)$ and the kernel matrix. Append each computed row to the output grid.
Complexity
- Time Complexity: $\mathcal{O}((H - K_H + 1) \cdot (W - K_W + 1) \cdot K_H \cdot K_W)$. Given dimensions up to $100 \times 100$, this performs at most $\approx 10^8$ operations, which executes quickly in standard Python.
- Space Complexity: $\mathcal{O}((H - K_H + 1) \cdot (W - K_W + 1))$ to allocate the output structure.
Python Reference Solution
from typing import List
def convolve_2d(input_matrix: List[List[float]], kernel: List[List[float]]) -> List[List[float]]:
rows = len(input_matrix)
cols = len(input_matrix[0])
k_rows = len(kernel)
k_cols = len(kernel[0])
out_h = rows - k_rows + 1
out_w = cols - k_cols + 1
if out_h <= 0:
return []
if out_w <= 0:
return [[] for _ in range(out_h)]
output = []
for r in range(out_h):
row = []
for c in range(out_w):
val = 0
for kr in range(k_rows):
for kc in range(k_cols):
val += input_matrix[r + kr][c + kc] * kernel[kr][kc]
row.append(val)
output.append(row)
return output