Search⌘ K
AI Features

Find K Closest Elements

Explore how to apply modified binary search to find the k closest elements to a target value in a sorted array. Understand the comparison criteria and implement an efficient solution that returns elements in sorted order based on distance and value.

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 KClosest.java 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.

Java
usercode > KClosest.java
import java.util.*;
public class KClosest{
public static List<Integer> findClosestElements(int[] nums, int k, int target) {
// Replace this placeholder return statement with your code
return new ArrayList<>();
}
}
Find K Closest Elements