Kth element of 2 sorted arrays

Pattern: Median of two sorted arrays

hard

The k smallest values take i from one array and k - i from the other. Binary search i in the shorter array until the two cuts are consistent; the answer is the larger of the two last values taken.

The problem

Given two sorted arrays and k (counting from 1), return the k-th smallest value of the two together. For example, [2, 3, 6, 7, 9] and [1, 4, 8, 10] with k = 5 give 6, since the merged order is 1 2 3 4 6 7 8 9 10.

The function name kthElement matches the takeUforward practice page. Use the link above for the exact statement and limits. k is always between 1 and the total length.

Think first

  • If i of the k smallest come from a, how many come from b?
  • Which values of i are even possible, given the lengths?
  • How do you check a choice of i in O(1)?

Hints

    Brute force, and why it fails

    Merge until the k-th value: O(k). Binary search the split in the shorter array: O(log(min(m, n))).

    The key insight

    This is the general form of the median problem. Every "k-th of two sorted arrays" question is a search for one consistent pair of cuts.

    Dry run

    a = 1 4 8 100 
    b = 2 3 6 7 91 
    lo0
    hi4

    a = [2, 3, 6, 7, 9], b = [1, 4, 8, 10] and k = 5. Search the shorter array, so swap them. Now a = [1, 4, 8, 10] and b = [2, 3, 6, 7, 9].

    Step 1 of 4

    The plan

    make a the shorter array
    lo = max(0, k - n), hi = min(k, m)
    while lo <= hi:
        i = (lo + hi) / 2, j = k - i
        aL = a[i - 1] or -inf, aR = a[i] or +inf
        bL = b[j - 1] or -inf, bR = b[j] or +inf
        if aL <= bR and bL <= aR: return max(aL, bL)
        if aL > bR: hi = i - 1
        else: lo = i + 1
    

    Complexity

    Time
    O(log(min(m, n)))
    Space
    O(1)

    The search runs over the shorter array.

    Edge cases

    • k = 1: the smaller of the two first values.
    • k = m + n: the larger of the two last values.
    • All of the k smallest in one array, as in [1, 2, 3] and [10, 20, 30] with k = 3.
    I've built my logic, show the code

    Java

    class Solution {
        public int kthElement(int[] a, int[] b, int k) {
            if (a.length > b.length) return kthElement(b, a, k);   // search the shorter one
            int m = a.length, n = b.length;
            int lo = Math.max(0, k - n), hi = Math.min(k, m);       // i = how many of the k smallest come from a
            while (lo <= hi) {
                int i = (lo + hi) / 2, j = k - i;
                int aLeft = i > 0 ? a[i - 1] : Integer.MIN_VALUE, aRight = i < m ? a[i] : Integer.MAX_VALUE;
                int bLeft = j > 0 ? b[j - 1] : Integer.MIN_VALUE, bRight = j < n ? b[j] : Integer.MAX_VALUE;
                if (aLeft <= bRight && bLeft <= aRight) return Math.max(aLeft, bLeft);   // a valid split
                if (aLeft > bRight) hi = i - 1;     // took too many from a
                else lo = i + 1;
            }
            return -1;                              // not reached when 1 <= k <= m + n
        }
    }

    C++

    class Solution {
    public:
        int kthElement(vector<int>& a, vector<int>& b, int k) {
            if (a.size() > b.size()) return kthElement(b, a, k);   // search the shorter one
            int m = static_cast<int>(a.size()), n = static_cast<int>(b.size());
            int lo = max(0, k - n), hi = min(k, m);                 // i = how many of the k smallest come from a
            while (lo <= hi) {
                int i = (lo + hi) / 2, j = k - i;
                int aLeft = i > 0 ? a[i - 1] : INT_MIN, aRight = i < m ? a[i] : INT_MAX;
                int bLeft = j > 0 ? b[j - 1] : INT_MIN, bRight = j < n ? b[j] : INT_MAX;
                if (aLeft <= bRight && bLeft <= aRight) return max(aLeft, bLeft);   // a valid split
                if (aLeft > bRight) hi = i - 1;     // took too many from a
                else lo = i + 1;
            }
            return -1;                              // not reached when 1 <= k <= m + n
        }
    };

    Python

    class Solution:
        def kthElement(self, a: list[int], b: list[int], k: int) -> int:
            if len(a) > len(b):
                a, b = b, a                         # search the shorter one
            m, n = len(a), len(b)
            lo, hi = max(0, k - n), min(k, m)       # i = how many of the k smallest come from a
            while lo <= hi:
                i = (lo + hi) // 2
                j = k - i
                a_left = a[i - 1] if i > 0 else float("-inf")
                a_right = a[i] if i < m else float("inf")
                b_left = b[j - 1] if j > 0 else float("-inf")
                b_right = b[j] if j < n else float("inf")
                if a_left <= b_right and b_left <= a_right:
                    return max(a_left, b_left)      # a valid split
                if a_left > b_right:
                    hi = i - 1                      # took too many from a
                else:
                    lo = i + 1
            return -1                               # not reached when 1 <= k <= m + n

    Common mistakes

    • Letting i start at 0 when k > n, which makes j larger than b's length.
    • Returning min of the right values instead of max of the left ones.
    • Treating k as 0-based.

    Similar problems