Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs

Back to Questions

129. Padding and stride effects

easy
GeneralGeneral
senior

Padding and stride are two simple knobs in convolutional layers that control output size and how much neighboring pixels influence each other. In this task, you’ll compute the output height/width of a 2D convolution given an input image size and conv settings.

Requirements

Implement the function

python

Rules:

  • Use out=⌊in+2p−ks⌋+1\text{out} = \left\lfloor \frac{\text{in} + 2p - k}{s} \right\rfloor + 1 for both height and width.
  • Return the output shape as a NumPy array: np.array([out_h, out_w]).
  • Do not simulate convolution over pixels; just compute the shape.
  • Use only NumPy and Python built-in libraries.
  • Keep it in a single Python function.

Example

python

Output:

python
Input Signature
ArgumentType
hint
wint
k_hint
k_wint
strideint
paddingint
Output Signature
Return NameType
valuenp.ndarray

Constraints

  • Return NumPy array [out_h, out_w].

  • Use integer floor division (//), no convolution simulation.

  • Only NumPy and Python built-ins allowed.

Hint 1

Use the standard output-size formula separately for height and width: \n(\text{out} = \left\lfloor\frac{\text{in} + 2p - k}{s}\right\rfloor + 1).

Hint 2

In Python, floor division for non-negative integers is //, so compute:
out_h = (h + 2*padding - k_h) // stride + 1 and similarly for width.

Hint 3

Return as a NumPy array np.array([out_h, out_w]).

Roles
ML Engineer
AI Engineer
Companies
GeneralGeneral
Levels
senior
entry
Tags
convolution
output-shape
stride-padding
floor-division
35 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit