<p>The <strong>distance of a pair</strong> of integers <code>a</code> and <code>b</code> is defined as the absolute difference between <code>a</code> and <code>b</code>.</p>

<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest <strong>distance among all the pairs</strong></em> <code>nums[i]</code> <em>and</em> <code>nums[j]</code> <em>where</em> <code>0 &lt;= i &lt; j &lt; nums.length</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,3,1], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> Here are all the pairs:
(1,3) -&gt; 2
(1,1) -&gt; 0
(3,1) -&gt; 2
Then the 1<sup>st</sup> smallest distance pair is (1,1), and its distance is 0.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,1,1], k = 2
<strong>Output:</strong> 0
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,6,1], k = 3
<strong>Output:</strong> 5
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == nums.length</code></li>
	<li><code>2 &lt;= n &lt;= 10<sup>4</sup></code></li>
	<li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>
	<li><code>1 &lt;= k &lt;= n * (n - 1) / 2</code></li>
</ul>

"""
3种方法从快到慢
1. Binary Search + Sliding Window - O(nlogM+nlogn), M=max(nums)
2. Binary Search + DP - O(nlogn+nlogM)
3. Bucket Sort - O(n^2+M)
"""
class Solution:
    def smallestDistancePair(self, nums: List[int], k: int) -> int:
        # def count_pairs(max_distance):
        #     count = 0
        #     left = 0
        #     for right in range(n):
        #         while nums[right] - nums[left] > max_distance:
        #             left += 1
        #         count += right - left # Add the number of valid pairs ending at right
        #     return count

        # n = len(nums)
        # nums.sort()

        # low, high = 0, nums[-1]-nums[0]
        # while low < high:
        #     mid = (low + high) // 2

        #     count = count_pairs(mid)

        #     if count < k:
        #         low = mid + 1
        #     else:
        #         high = mid
        
        # return low


        def count_pairs(max_distance):
            n = len(nums)
            count = 0
            i = 0
            while i < n:
                current = nums[i]
                count_current = value_count[current]

                # Calculate pairs Starting from current value with distance <= max_distance
                pairs_with_larger_values = (
                    prefix_count[min(current + max_distance, len(prefix_count)-1)] - prefix_count[current]
                )
                pairs_with_same_values = (count_current * (count_current - 1) // 2) # 握手n(n-1)/2
                
                count += (pairs_with_larger_values * count_current + pairs_with_same_values)

                # Skip duplicate values
                while i + 1 < n and nums[i] == nums[i + 1]:
                    i += 1
                i += 1

            return count
            
        n = len(nums)
        nums.sort()

        prefix_count = [0] * (nums[-1]+1)
        value_count = Counter(nums)

        i = 0
        for value in range(len(prefix_count)):
            while i < n and nums[i] <= value:
                i += 1
            prefix_count[value] = i

        left, right = 0, nums[-1]-nums[0]
        while left < right:
            mid = (left + right) // 2
            count = count_pairs(mid)
            if count < k:
                left = mid + 1
            else:
                right = mid
        return left

        
        
        # n = len(nums)
        # nums.sort()

        # min_interval = min([nums[i+1]-nums[i] for i in range(n-1)])

        # bucket = [0] * (nums[-1]-nums[0] + 1)

        # # Populate the bucket list with counts of each distance
        # for i in range(n):
        #     for j in range(i + 1, n):
        #         bucket[nums[j]-nums[i]] += 1

        # for dist in range(min_interval, len(bucket)):
        #     k -= bucket[dist]
        #     if k <= 0:
        #         return dist
25586