<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>

import heapq
import collections

class Solution:
    def smallestDistancePair(self, nums: List[int], k: int) -> int:
        cnt = collections.Counter(nums)
        del nums
        #print(sorted(cnt.keys()))
        sc = [(k, cnt[k]) for k in sorted(cnt.keys())]
        #print(sc)
        pairc = sum(v*(v-1)/2 for v in cnt.values())
        minsq = []
        maxsq = []
        dpair = {}
        k -= pairc
        if k <= 0:
            return 0
        d = 1
        last_it_v = 0  # debug
        while True:
            rmin = 10e6
            rmax = 0
            for i in range(0, len(sc)-d):
                lk, lc = sc[i]
                rk, rc = sc[i+d]
                dd = rk-lk
                if dd not in dpair:
                    dpair[dd] = lc*rc
                else:
                    dpair[dd] += lc*rc
                if dd < rmin:
                    rmin = dd
                if dd > rmax:
                    rmax = dd
            if maxsq and rmin >= maxsq[0]:
                todel = []
                for pk in sorted(dpair.keys()):
                    if pk > maxsq[0]:
                        break
                    pc = dpair[pk]
                    assert pk > last_it_v, (pk, pc, last_it_v)
                    last_it_v = pk
                    todel.append(pk)
                    k -= pc
                    if k <= 0:
                        return pk
                maxsq.pop(0)
                for pk in todel:
                    del dpair[pk]
            maxsq.append(rmax)
            d += 1
20164