Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Eric Imho Jang
python solution without binary search.

Eric Imho Jang

Jul 27, 2024

follows the same previous pattern. except that this covers an edge case as described below.

from heapq import * class Solution: def findClosestElements(self, arr, K, X): maxHeap = [] for i in range(len(arr)): difference = -abs(arr[i] - X) tuple = (difference, arr[i]) # for edge cases where maxHeap is full already has K elements and there # already exists an element with same difference and is smaller number prevMaxDiff = maxHeap[0][0] if len(maxHeap) > 0 else None if len(maxHeap) == K and difference == prevMaxDiff: continue heappush(maxHeap, tuple) if i >= K: heappop(maxHeap) result = [] for i in range(len(maxHeap)): result.append(maxHeap[i][1]) result.sort() return result

0

0

Comments
Comments

On this page