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):
    left = 0
    right = len(arr) - k
   
    # Binary search against the criteria described
    while left < right:
        mid = (left + right) // 2
        if x - arr[mid] > arr[mid + k] - x: Very Tricky
            left = mid + 1
        else:
            right = mid

    return arr[left:left + k]
   

def findClosestElements_MyAlgo(arr: List[int], k: int, x: int):
   
    p = bisect.bisect_left(arr, x)
   
    left = p-1
    right = p
   
    count = 0
    left_list, right_list = [], []
   
    while count < k and (left >= 0 or right < len(arr)):
       
        left_dist  = abs(x-arr[left]) if left >= 0 else math.inf
        right_dist = abs(x-arr[right]) if right < len(arr) else math.inf
       
        if left_dist <= right_dist:
            left_list.append(arr[left])
            left -= 1
            count += 1
        else:
            right_list.append(arr[right])
            right += 1
            count += 1
           

    return list(reversed(left_list)) + right_list 

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break