Skip to the code
cf.
+25 XP

#159 Closest Font Size

medium

A design system offers a fixed type scale: the font sizes in sizes, sorted ascending with no repeats. When a designer pastes text with an arbitrary size, the editor snaps it to the closest size on the scale.

Write closestSize(sizes, target) that returns the size in sizes closest to target. If two sizes are equally close, return the smaller one.

The scale can be long (think every half pixel), so use O(log n) time.

Example 1

Input: sizes = [12,14,16,20,24,32], target = 19
Output: 20

20 is 1 away, closer than 16, which is 3 away.

Example 2

Input: sizes = [12,14,16,20,24,32], target = 18
Output: 16

16 and 20 are both 2 away, so pick the smaller one.

Constraints

  • 1 <= sizes.length <= 100000
  • sizes is sorted ascending with no repeats.
  • 1 <= sizes[i], target <= 10^6
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).