LeetCode 719: Kth Smallest Pair Distance Solution

🚀 Day 46 of #100DaysOfCode Solved 719. Find K-th Smallest Pair Distance on LeetCode 📏 🧠 Key Insight: We need to find the k-th smallest absolute difference among all possible pairs in the array. Brute force (generating all pairs) would be O(n²) → not efficient. Instead, we use Binary Search on Answer + Two Pointers. ⚙️ Approach: 1️⃣ Sort the array 2️⃣ Define search space: 🔹left = 0 (minimum distance) 🔹right = max(nums) - min(nums) 3️⃣ Apply Binary Search: 🔹For a given mid, count how many pairs have distance ≤ mid 4️⃣ Counting pairs efficiently: 🔹Use two pointers 🔹For each i, move j while nums[j] - nums[i] ≤ mid 🔹Add (j - i - 1) to count 5️⃣ If count ≥ k → try smaller distance 6️⃣ Else → increase distance 🎯 Final answer = smallest distance satisfying the condition ⏱️ Time Complexity: O(n log n + n log D) 🔹Sorting + Binary Search with linear check 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #BinarySearch #TwoPointers #Algorithms #Java #InterviewPrep #CodingJourney

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories