Find K Closest Elements

Problem Id: 658 Difficulty: Medium


Intuition

Solution


class Solution:
    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
        m = min(arr, key=lambda i: abs(x - i))
        lo = arr.index(m)
        hi = lo + 1
        while hi - lo < k:
            if lo == 0:
                hi += 1
            elif hi == len(arr):
                lo -= 1
            elif abs(arr[lo - 1] - x) <= abs(arr[hi] - x):
                lo -= 1
            else:
                hi += 1
        return arr[lo:hi]