Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Find K Closest Elements

Medium Acceptance 76% Points 30

You are given a sorted integer array arr[], an integer k, and an integer x. Your task is to find the k closest elements to x in the array. An element a is closer to x than element b if the absolute difference |a - x| is smaller than |b - x|. If there is a tie, choose the smaller element. Return the k closest elements in ascending order.

Examples
Example 1

Example 1

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

Output: [1,2,3,4]

Explanation: The elements closest to 3 are 3, 2, 4, and 1. After sorting them in ascending order, the result is [1,2,3,4].

Example 2

Example 2

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

Output: [1,2,3,4]

Explanation: Since x = -1 is smaller than all elements, the first 4 elements are the closest.

Example 3

Example 3

Input: arr = [2,4,5,6,9], k = 3, x = 7

Output: [5,6,9]

Explanation: The elements closest to 7 are 6, 5, and 9. After sorting them in ascending order, the result is [5,6,9].

Constraints
  • 1 = arr.length = 105
  • 1 = k = arr.length
  • -104 = arr[i], x = 104
  • arr is sorted in ascending order
Topics
Binary Search
Companies
Microsoft
Added 25 Jul 2026 76% acceptance
Ln 1, Col 1Sign in to save your code
1 2 3 4 5
4
3
1 2 3 4