Kth smallest number again

Pattern: Binary search on the answer

medium

Merge the ranges so no number is counted twice, keep a running count of how many numbers each range adds, and for every query binary search the range that holds the k-th number.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given several ranges [a, b] of whole numbers, which may overlap. Put every number from every range into one set, so each number appears once. Then answer queries: for each k, return the k-th smallest number in the set, or -1 if the set has fewer than k numbers. For example, ranges [1, 3] and [5, 7] with queries [1, 4, 6, 7] give [1, 5, 7, -1].

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name kthSmallest and the input as two arrays are this guide's own.

Think first

  • Ranges can hold billions of numbers. Why can you not list them?
  • Overlapping ranges count some numbers twice. How do you fix that first?
  • With the ranges separate and sorted, how do you find which one holds the k-th number?

Hints

    Brute force, and why it fails

    List every number in a sorted set and index into it: fine for tiny ranges, impossible for huge ones. This guide does that on small tests. Merging plus binary search costs O(n log n + q log n).

    The key insight

    You never need the numbers themselves, only how many lie before each range. A running count that only grows is exactly what binary search needs.

    Dry run

    [1, 3]0 
    [5, 7]1 
    counts0, 3, 6

    ranges [1, 3] and [5, 7], queries 1, 4, 6, 7. The numbers are 1 2 3 5 6 7.

    Step 1 of 4

    The plan

    merged = merge the ranges after sorting by start
    before[0] = 0; before[i + 1] = before[i] + (end - start + 1) of range i
    for each query k:
        if k < 1 or k > before[m]: answer -1
        else:
            i = first index with before[i + 1] >= k
            answer merged[i].start + (k - before[i] - 1)
    

    Complexity

    Time
    O(n log n + q log n)
    Space
    O(n)

    Sorting and merging the n ranges, then one binary search for each of the q queries.

    Edge cases

    • Overlapping or nested ranges: merging removes the repeats.
    • A range of one number, as in [0, 0].
    • Negative numbers: the formula works the same.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int[] kthSmallest(int[][] ranges, int[] queries) {
            int[][] r = ranges.clone();
            Arrays.sort(r, (x, y) -> Integer.compare(x[0], y[0]));
            List<int[]> merged = new ArrayList<>();          // join overlapping ranges so no number is counted twice
            for (int[] cur : r) {
                if (!merged.isEmpty() && cur[0] <= merged.get(merged.size() - 1)[1]) {
                    int[] last = merged.get(merged.size() - 1);
                    last[1] = Math.max(last[1], cur[1]);
                } else {
                    merged.add(new int[]{cur[0], cur[1]});
                }
            }
            int m = merged.size();
            long[] before = new long[m + 1];                 // before[i] = how many numbers lie in the first i ranges
            for (int i = 0; i < m; i++) before[i + 1] = before[i] + (merged.get(i)[1] - (long) merged.get(i)[0] + 1);
            int[] out = new int[queries.length];
            for (int q = 0; q < queries.length; q++) {
                long k = queries[q];
                if (k < 1 || k > before[m]) { out[q] = -1; continue; }
                int lo = 0, hi = m - 1;                      // the first range whose running count reaches k
                while (lo < hi) {
                    int mid = lo + (hi - lo) / 2;
                    if (before[mid + 1] >= k) hi = mid;
                    else lo = mid + 1;
                }
                out[q] = (int) (merged.get(lo)[0] + (k - before[lo] - 1));
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> kthSmallest(vector<vector<int>>& ranges, vector<int>& queries) {
            vector<vector<int>> r = ranges;
            sort(r.begin(), r.end());
            vector<vector<int>> merged;                      // join overlapping ranges so no number is counted twice
            for (const vector<int>& cur : r) {
                if (!merged.empty() && cur[0] <= merged.back()[1]) merged.back()[1] = max(merged.back()[1], cur[1]);
                else merged.push_back(cur);
            }
            int m = static_cast<int>(merged.size());
            vector<long long> before(m + 1, 0);              // before[i] = how many numbers lie in the first i ranges
            for (int i = 0; i < m; i++) before[i + 1] = before[i] + (merged[i][1] - static_cast<long long>(merged[i][0]) + 1);
            vector<int> out;
            for (int kq : queries) {
                long long k = kq;
                if (k < 1 || k > before[m]) { out.push_back(-1); continue; }
                int lo = 0, hi = m - 1;                      // the first range whose running count reaches k
                while (lo < hi) {
                    int mid = lo + (hi - lo) / 2;
                    if (before[mid + 1] >= k) hi = mid;
                    else lo = mid + 1;
                }
                out.push_back(static_cast<int>(merged[lo][0] + (k - before[lo] - 1)));
            }
            return out;
        }
    };

    Python

    class Solution:
        def kthSmallest(self, ranges: list[list[int]], queries: list[int]) -> list[int]:
            merged = []                             # join overlapping ranges so no number is counted twice
            for a, b in sorted(ranges):
                if merged and a <= merged[-1][1]:
                    merged[-1][1] = max(merged[-1][1], b)
                else:
                    merged.append([a, b])
            before = [0]                            # before[i] = how many numbers lie in the first i ranges
            for a, b in merged:
                before.append(before[-1] + (b - a + 1))
            out = []
            for k in queries:
                if k < 1 or k > before[-1]:
                    out.append(-1)
                    continue
                lo, hi = 0, len(merged) - 1         # the first range whose running count reaches k
                while lo < hi:
                    mid = (lo + hi) // 2
                    if before[mid + 1] >= k:
                        hi = mid
                    else:
                        lo = mid + 1
                out.append(merged[lo][0] + (k - before[lo] - 1))
            return out

    Common mistakes

    • Skipping the merge, so overlapping numbers are counted twice.
    • Forgetting the + 1 in the size of a range.
    • Using 32-bit counts when ranges are huge.

    Similar problems