21(May) K closest elements

21. K Closest Elements

The problem can be found at the following link: Question Link

Problem Description

Given an array arr[] of size n integers and a value x, find the k closest elements to x in arr[].

Example:

Input:

n = 13
arr[] = {12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56}
k = 4, x = 35

Output:

39 30 42 45

Explanation: The first closest element to 35 is 39, the second is 30, the third is 42, and the fourth is 45.

My Approach

  1. Finding the Cross-Over Point:

  • Implement a binary search to find the index l such that arr[l] is the largest element smaller than or equal to x.

  • This step helps in determining the elements closest to x.

  1. Finding K Closest Elements:

  • Initialize two pointers l and r to the indices found in the previous step.

  • Compare the absolute differences of x with elements at l and r.

  • Move the pointers accordingly to find the k closest elements.

  1. Return:

  • Return an array containing the k closest elements found.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(log n + k), where log n is for binary search and k is for finding the closest elements.

  • Expected Auxiliary Space Complexity: O(k), as we use an array to store the k closest elements.

Code

Java

Python

CPP

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated