Problem 372974 · medium · Level 03 Linear Management & Searching

Tuning Forks Nearest the Note

binary search · sliding window

A music shop lists the pitches of its tuning forks in sorted order as nums. A customer wants the k forks nearest to the pitch x. Return their pitches in ascending order; when two forks are equally far from x, the lower one is chosen first.

Examples

Input:  nums = [2, 4, 5, 8, 11], k = 2, x = 6
Output: [4, 5]
Explanation: 5 is at distance 1; 4 and 8 are both at distance 2, so the smaller one, 4, is taken.

Input:  nums = [2, 4, 5, 8, 11], k = 2, x = 20
Output: [8, 11]

Input:  nums = [1, 1, 2, 4, 7], k = 2, x = 3
Output: [2, 4]

Constraints

  • 1 <= k <= len(nums) <= 10**6
  • -10**9 <= nums[i], x <= 10**9
  • O(log n + k) time is required.

Goals

  • Binary search over the start of a window rather than over a single element
  • Return a contiguous slice in sorted order
Starting Python…