KatInterview

2D Matrix Cross-Correlation Filter

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingarraysmatrix

Last 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.