Search⌘ K
AI Features

Find K Closest Elements

Understand how to find k elements closest to a target value in a sorted array by applying modified binary search techniques. Learn to handle tie cases by selecting the smaller value and return results sorted. This lesson helps you develop problem-solving skills for coding interviews by focusing on pattern recognition and efficient search strategies.

Statement

You are given a sorted array of integers, nums, and two integers, target and k. Your task is to return k number of integers that are close to the target value, target. The integers in the output array should be in a sorted order.

An integer, nums[i], is considered to be closer to target, as compared to nums[j] when |nums[i] - target| << |nums[j] - target|. However, when |nums[i] - target| == |nums[j] - target|, the smaller of the two values is selected.

Constraints:

  • 11 \leq k \leq nums.length
  • 11 \leq nums.length 103\leq 10^3
  • nums is sorted in ascending order.
  • 104-10^4 \leq nums[i], target 104\leq 10^4

Examples

Understand the problem

Let’s take a moment to make sure you've correctly understood the problem. The quiz below helps you check if you're solving the correct problem:

Find K Closest Elements

1.

What are the k closest integers to target if the following data is given as input?

nums = [1, 3, 5, 7, 9, 11]

k = 4

target = -7

A.

[1, 3, 5]

B.

[1, 3, 5, 7]

C.

[1, 3, 5, 9]

D.

[0, 1, 3, 5, 7, 9, 11]


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in main.py in the following coding playground. We've provided a useful code template in the other file that you may build on to solve this problem.

Python
usercode > main.py
def find_closest_elements(nums, k, target):
# Replace this placeholder return statement with your code
return []
Find K Closest Elements