• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
May 22, 2024 |600 Views

PROBLEM OF THE DAY : 21/05/2024 | K closest elements

Description
Discussion

Welcome to the daily solving of our PROBLEM OF THE DAY with Nitin Kaplas. We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Array but also build up problem-solving skills.

In this problem, we are given an array, arr[] of n integers, and a value x. Find the K closest elements to x in arr[].
Keep the following points in mind:

If x is present in the array, then it need not be considered.
If two elements have the same difference as x, the greater element is prioritized.
If sufficient elements are not present on the right side, take elements from the left and vice versa.

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: 
First closest element to 35 is 39. Second closest element to 35 is 30. Third closest element to 35 is 42. And fourth closest element to 35 is 45.

Give the problem a try before going through the video. All the best!!!
Problem Link: https://www.geeksforgeeks.org/problems/k-closest-elements3619/1