Back to Practice
#0022

Resize Image With Nearest Neighbor

MediumML22 min15 XP

Problem

Given a 2D NumPy array image and new height/width, return a resized image using nearest-neighbor sampling.

Why This Matters

Image resizing looks magical in libraries until you implement the coordinate mapping yourself.

Function Signature

def resize_nearest(image, new_h, new_w):

Examples

Example 1
Input[[1, 2], [3, 4]] resized to 4x4
Outputeach original pixel becomes a 2x2 block

Nearest neighbor copies the closest source pixel without interpolation.

Constraints

  • Input is a 2D grayscale image.
  • Use nearest-neighbor sampling, not averaging.
  • Return shape must be (new_h, new_w).
CodePython
Visible browser tests run here when available.
Testcases1 visible / 4 hidden categories
Upscale 2x2 to 4x4
Input[[1,2],[3,4]] -> 4x4
Expected2x2 blocks of each value

Each source pixel covers a larger region in the output.

Hidden Test Categories
Downscale imageResize to same shapeNon-square target shapeSingle-row image