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

class Solution {
public:
    int count(unordered_map<int, int>& freq, int* freq_presum, int dist,
              int max_num) {
        int cnt = 0;

        for (auto it = freq.begin(); it != freq.end(); ++it) {
            int key = it->first;
            int value = it->second;

            // add (i, i+dist]
            int range = 0;

            if (key + dist > max_num) {
                range += freq_presum[max_num];
            } else {
                range += freq_presum[key + dist];
            }

            range -= freq_presum[key];

            cnt += range * value + value * (value - 1) / 2;
        }

        return cnt;
    }

    int smallestDistancePair(vector<int>& nums, int k) {
        unordered_map<int, int> freq;

        int max_num = 0;
        for (int i = 0; i < nums.size(); i++) {
            max_num = max(max_num, nums[i]);

            freq[nums[i]]++;
        }

        int* freq_presum = new int[max_num + 1];

        freq_presum[0] = freq[0];
        for (int i = 1; i <= max_num; i++) {
            freq_presum[i] = freq_presum[i - 1] + freq[i];
        }

        // binary search
        int left = 0, right = max_num;
        while (left < right) {
            int mid = left + (right - left) / 2;

            int cnt = count(freq, freq_presum, mid, max_num);

            if (cnt < k) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }

        // left == right == lower_bound, 1 element

        return left;
    }
};
196691