Skip to the code
cf.
+10 XP

#154 Nearest Supported Viewport

easy

A screenshot service can only render at the viewport widths in widths, which are listed in no particular order. A user asks for a screenshot at width target.

Write nearestWidth(widths, target) that returns the supported width closest to target. If two widths are equally close, return the smaller one.

Example 1

Input: widths = [1280,375,768,1024], target = 800
Output: 768

768 is 32 away from 800. 1024 is 224 away.

Example 2

Input: widths = [480,320], target = 400
Output: 320

Both are 80 away, so pick the smaller width, 320.

Constraints

  • 1 <= widths.length <= 1000
  • 1 <= widths[i], target <= 10000
  • Widths may repeat.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).