Find K Closest Elements in Sorted Array

Most people overcomplicate this problem. I almost did too. 🚀 Day 78/365 — DSA Challenge Find K Closest Elements You're given a sorted array. Pick k elements closest to x. Sounds simple... but there's a catch: You must return them sorted And follow distance rules carefully. 💡 My Approach: Instead of checking every combination... I used a two-pointer shrinking window Start with the full array Then shrink it until only k elements remain At each step: Compare: • distance from start → |arr[start] - x| • distance from end → |arr[end] - x| Remove the one farther from x Repeat until window size = k ⚡ Why this works: We always remove the worst candidate So the remaining window is optimal ⏱ Time: O(n) 📦 Space: O(1) What I learned: Sometimes the solution is not about building... It's about removing smartly Code 👇 https://lnkd.in/dad5sZfu #DSA #Java #LeetCode #LearningInPublic #ProblemSolving #Consistency

  • text

To view or add a comment, sign in

Explore content categories