Dinesh Kolhe’s Post

🔥 Day 84 of #100DaysOfCode Today’s problem: LeetCode: Find K Closest Elements 🎯 📌 Problem Summary Given: A sorted array arr An integer k A target value x Return the k closest integers to x in the array. The result must be sorted in ascending order. Example: arr = [1,2,3,4,5], k = 4, x = 3 Output → [1,2,3,4] 🧠 Approach: Two Pointers Shrinking Window Since the array is already sorted, we can: Start with: l = 0 r = arr.length - 1 While the window size is bigger than k: Compare distances: |x - arr[l]| |x - arr[r]| Remove the element that is farther from x ⚙️ Core Idea: while (r - l >= k): if left is closer: r-- else: l++ Finally, return elements from l to r. ⏱ Time Complexity: O(n - k) 💾 Space Complexity: O(1) (excluding result list) 🚀 Performance ⚡ Runtime: 4ms (98% faster) Solid optimization using the sorted property of the array. 💡 What I Learned When array is sorted → always think Two Pointers. Instead of building result, shrink unnecessary elements. Cleaner logic often gives better performance. Consistency > Motivation. On to Day 85 🔥 #100DaysOfCode #LeetCode #TwoPointers #Java #DSA #CodingJourney #InterviewPrep

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories