Skip to the code
+25 XP

#385 Closest Font Sizes

medium

A design tool suggests font sizes near the one the designer typed. The design system's sizes are in sizes, sorted ascending (repeats are possible).

Write closestSizes(sizes, target, k) that returns the k sizes closest to target, sorted ascending. A size a is closer than b if Math.abs(a - target) < Math.abs(b - target); when both are equally close, the smaller size wins. k is between 1 and sizes.length.

Example 1

Input: sizes = [10,12,14,16,20,24], target = 15, k = 3
Output: [12,14,16]

14 and 16 are 1 away. Next comes 12, which is 3 away; 20 is 5 away.

Example 2

Input: sizes = [10,12,14,16], target = 13, k = 1
Output: [12]

12 and 14 are both 1 away; the smaller one wins.

Constraints

  • 1 <= k <= sizes.length <= 10^5
  • -10^4 <= sizes[i], target <= 10^4
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

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