658. Find K Closest Elements

Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.

An integer a is closer to x than an integer b if:

  • |a - x| < |b - x|, or
  • |a - x| == |b - x| and a < b
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: 
    left = 0 
    right = len(arr) - k 
     
    while left < right: 
        mid = left + (right - left) // 2 
        if x - arr[mid] > arr[mid + k] - x: # Think about middle point. I am comparing mid and mid + k because both cannot be in the result
            left = mid + 1 
        else: 
            right = mid 
    return arr[left : left + k]