Skip to content

Practice Find K Closest Elements

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#658
LeetCode Problem

Find K Closest Elements

Problem Statement

From the sorted array arr, return the k values closest to x, ordered ascending. Compare absolute distance first. If two values have equal distance, prefer the smaller value. Preserve repeated occurrences when selecting k array elements.

Source: Find K Closest Elements on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

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

# Example 2

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

Constraints

1 <= k <= arr.length
1 <= arr.length <= 10^4
arr is sorted in ascending order.
-10^4 <= arr[i], x <= 10^4

Related LeetCode Problems

Practice more problems similar to Find K Closest Elements.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.