Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Find K Closest Elements

Medium Acceptance 76.00% Points 30.00

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].

Hints
Hint 1
N/A
Constraints
  • 1 = arr.length = 105
  • 1 = k = arr.length
  • -104 = arr[i], x = 104
  • arr is sorted in ascending order
Companies
Microsoft
Topics
Binary Search
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions