oneby7

Heaps Top K

410. Find K Closest Elements

Medium

You are given an array of integers arr, sorted in non-decreasing order, and two integers k and x. Return the k elements of arr that are closest to x, sorted in increasing order.

An element a is closer to x than an element b when |a - x| < |b - x|. When the two are equally far from x, the smaller one counts as closer.

A value can appear in arr more than once. Each copy is a separate element, so the answer can hold the same value more than once.

Example 1

Input: arr = [-6, -2, 1, 3, 3, 8, 12], k = 5, x = 5

Output: [-2,1,3,3,8]

Explanation: The distances to 5 are 11, 7, 4, 2, 2, 3 and 7. The four closest elements are 3, 3, 8 and 1. For the fifth place, −2 and 12 are both 7 away, and the smaller one wins.

Example 2

Input: arr = [-10, -7, -3, 0, 2], k = 3, x = 9

Output: [-3,0,2]

Explanation: Every element is below 9, so the closest three are the three largest.

Example 3

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

Output: [4,4]

Explanation: Every element is 1 away from 5. The smaller value wins each tie, so the answer is two of the 4s.

Check your understanding

Work out the answer for this input before you write any code.

arr = [1, 2, 6, 7, 9], k = 3, x = 4

Constraints

  • 1 ≤ k ≤ arr.length ≤ 105
  • -109 ≤ arr[i] ≤ 109
  • arr[i] ≤ arr[i + 1] (non-decreasing)
  • -109 ≤ x ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.