FastPrepClipped Box Average

Clipped Box Average

NVIDIA logoNVIDIA● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

Given a rectangular integer-valued image image and positive odd dimensions kernelHeight and kernelWidth, compute its local mean with an all-one rectangular kernel.

Place the kernel center at every image position [r][c], with stride 1. Its footprint includes rows from r - kernelHeight / 2 through r + kernelHeight / 2 and columns from c - kernelWidth / 2 through c + kernelWidth / 2, inclusive. The divisions in these index formulas are integer divisions.

  • Ignore footprint positions outside the image. Do not add padding values.
  • At each position, divide the sum of the included image values by the number of included pixels.
  • Return the unrounded arithmetic means in a floating-point matrix with the same shape as image.

Every footprint contains its center pixel, so its pixel count is positive. Kernel dimensions may exceed the image dimensions.

Each returned value is accepted when its error is at most 10^-6 * max(1, abs(expected)).

Optimization follow-up

After a direct implementation, explain how precomputed rectangle sums reduce the total running time to O(rows * cols), and how the border pixel counts are computed.

What the interview report shared

The report asks for a basic two-dimensional all-one convolution average, explicitly excludes out-of-image pixels, and follows up with an oral region-sum optimization and a discussion of potential issues. It does not name the particular issues or give the kernel placement and numeric conventions.

Function

clippedBoxAverage(image: int[][], kernelHeight: int, kernelWidth: int) → double[][]

Examples

Example 1

image = [[1,2,3],[4,5,6],[7,8,9]]kernelHeight = 3kernelWidth = 3return = [[3.0,3.5,4.0],[4.5,5.0,5.5],[6.0,6.5,7.0]]

The top-left footprint contains 1, 2, 4, 5, giving 12 / 4 = 3. The top-middle footprint contains six pixels, giving 21 / 6 = 3.5. The center uses all nine pixels, giving 45 / 9 = 5.

Example 2

image = [[2,8,0,6]]kernelHeight = 1kernelWidth = 3return = [[5.0,3.3333333333333335,4.666666666666667,3.0]]

The four clipped sums are 10, 10, 14, 6, and their pixel counts are 2, 3, 3, 2. Divide each sum by its own count.

Example 3

image = [[1,-2],[7,10]]kernelHeight = 5kernelWidth = 7return = [[4.0,4.0],[4.0,4.0]]

Every centered footprint covers the whole image. Its four pixels sum to 16, so every mean is 4.

Constraints

  • 1 <= image.length <= 32.
  • Every image row has the same length, with 1 <= image[0].length <= 32.
  • -10^9 <= image[r][c] <= 10^9.
  • 1 <= kernelHeight, kernelWidth <= 63; both dimensions are odd.

More NVIDIA problems

See NVIDIA hiring insights
public double[][] clippedBoxAverage(int[][] image, int kernelHeight, int kernelWidth) {
    // Return the mean at each image position.
}
image[[1,2,3],[4,5,6],[7,8,9]]
kernelHeight3
kernelWidth3
expected[[3.0,3.5,4.0],[4.5,5.0,5.5],[6.0,6.5,7.0]]
Checking account…