Skip to the code
cf.
+25 XP

#161 Nearest Zoom Levels

medium

A map widget supports the zoom levels in levels, sorted ascending with no repeats. To offer quick choices, it shows the k levels closest to the current zoom x.

Write nearestLevels(levels, x, k) that returns those k levels, sorted ascending. A level is closer if Math.abs(level - x) is smaller; if two levels are equally close, the smaller level is preferred.

Example 1

Input: levels = [1,2,3,4,5], x = 3, k = 2
Output: [2,3]

3 is 0 away. 2 and 4 are both 1 away, and 2 is smaller.

Example 2

Input: levels = [1,5,10,20], x = 12, k = 3
Output: [5,10,20]

10 is 2 away, 5 is 7 away, and 20 is 8 away. 1 is 11 away, so it is left out.

Constraints

  • 1 <= k <= levels.length <= 10000
  • levels is sorted ascending with no repeats.
  • -10^4 <= levels[i], x <= 10^4
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).