Problem 372974 · medium · Phase 03 Linear Management & Searching

K Nearest Values

binary search · sliding window

Given a sorted list nums, an integer k and an integer x, return the k values of nums closest to x, in ascending order. When two values are equally close, prefer the smaller one.

Examples

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

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

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…