LeetCode 658: Find K Closest Elements

link

Since arr is sorted, the closest element to x would be near x‘s insert index.

With left and right pointers we keep collecting the closest elements from the two possible candidates.

Time: \mathcal{O}(\lg{n} + k), space: \mathcal{O}(k).

class Solution:
    def find_insert_index(self, x, nums):
        lo, hi = 0, len(nums)-1
        while lo <= hi:
            mid = (lo+hi) // 2
            if nums[mid] < x:
                lo = mid+1
            else:
                hi = mid-1

        return lo

    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
        n = len(arr)
        right = self.find_insert_index(x, arr)
        left = right-1
        elements = deque()
        while len(elements) < k:
            if left < 0:
                elements.append(arr[right])
                right += 1
                continue
            
            if right >= n:
                elements.appendleft(arr[left])
                left -= 1
                continue
            
            left_dist = abs( arr[left] - x )
            right_dist = abs( arr[right] - x )
            if left_dist <= right_dist:
                elements.appendleft(arr[left])
                left -= 1
            else:
                elements.append(arr[right])
                right += 1

        return list(elements)

Leave a comment