Problem · Array

Find K Closest Elements in a Sorted Array

Learn this problem
MediumLinkedIn logoLinkedInFULLTIMEONSITE INTERVIEW

Problem statement

Given a sorted integer array arr, an integer k, and a target x, return the k closest values to x in ascending order.

A value a is closer than b when |a - x| < |b - x|. For equal distances, the smaller value is closer.

Function

findClosestElements(arr: int[], k: int, x: int) → int[]

Examples

Example 1

arr = [1,2,3,4,5]k = 4x = 3return = [1,2,3,4]

The four smallest distances belong to 1, 2, 3, and 4.

Example 2

arr = [1,2,3,4,5]k = 4x = -1return = [1,2,3,4]

The target lies left of the array, so the first four values are closest.

Constraints

  • arr is non-empty and sorted in nondecreasing order.
  • 1 <= k <= arr.length.
  • All values and x are signed integers.

More LinkedIn problems

drafts saved locally
public int[] findClosestElements(int[] arr, int k, int x) {
    // TODO: return the sorted window of k closest values.
}
arr[1,2,3,4,5]
k4
x3
expected[1,2,3,4]
checking account