Find K Closest Elements
LeetCode 658 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
bisect to x, then expand the closer side.
ನಾನು Find K Closest Elements (LeetCode 658) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Top K ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Binary search puts you right next to x. Then grow a window outward one element at a time, always taking the closer of the two neighbours (the left one on ties), until it holds k elements.
Approach
- 1
low = bisect_left(arr, x) − 1, high = low + 1 (exclusive window).
- 2
While the window has fewer than k: if low is exhausted or arr[low] is at least as close, take low; else take high.
- 3
Return arr[low+1 : high].
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Binary search + two pointersPythonO(log n + k) time
from bisect import bisect_left
from typing import List
#TC- O(logn+k)
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
if len(arr)==k:
return arr
low=bisect_left(arr,x)-1 #logn
high=low+1
while high-low-1<k: #O(k)
if low==-1:
high+=1
continue
if high==len(arr) or abs(arr[low]-x)<=abs(arr[high]-x):
#low is closer to x
low-=1 #expand to left
else:
high+=1
return arr[low+1:high]
Find K Closest Elements — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Find K Closest Elements ಹಿಂದಿನ intuition ಏನು?
Binary search puts you right next to x. Then grow a window outward one element at a time, always taking the closer of the two neighbours (the left one on ties), until it holds k elements.
Find K Closest Elements (LeetCode 658) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. low = bisect_left(arr, x) − 1, high = low + 1 (exclusive window). 2. While the window has fewer than k: if low is exhausted or arr[low] is at least as close, take low; else take high. 3. Return arr[low+1 : high].
Find K Closest Elements ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(log n + k). Space: O(1) extra. (Accepted approach: Binary search + two pointers.)
Find K Closest Elements ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Ties go to the smaller element (the left side).