KatInterview

Ranked Element Selection and Common Entry Count in Sorted Arrays

Heaps, Sorting & SearchAuto-graded · 18 test cases
HardAuto-gradedHeaps, Sorting & Searchheaps-sortingarraysbinary-search

Last updated

Find the k-th smallest element across two sorted arrays and count their unique shared elements efficiently.

You are given two non-decreasingly sorted integer arrays, arr1 and arr2, with lengths $n$ and $m$ respectively.

Write a function that computes two metrics based on these arrays:

  1. $k$-th Smallest Value: Determine the value of the $k$-th smallest element (1-indexed) in the combined sorted sequence of both arrays. Your partition approach should execute in $O(\log(\min(n, m)))$ time.
  2. Distinct Intersection Count: Calculate the total count of distinct values that appear in both arr1 and arr2.

Return a tuple containing these two results: (k_th_smallest, distinct_intersection_count).

Constraints

  • $0 \le n, m \le 10^5$
  • $1 \le n + m$
  • $1 \le k \le n + m$
  • arr1 and arr2 are sorted in non-decreasing order.
  • Arrays may contain duplicate values.

Examples

Example 1

Input: solve_sorted_tasks([1, 3, 5], [2, 3, 6], 3)

Output: [3, 1]

Example 2

Input: solve_sorted_tasks([1, 4, 8], [2, 5, 9], 1)

Output: [1, 0]

Hints

Hint 1

To find the k-th smallest element in sub-linear time, binary search over the number of elements taken from the shorter array.

Hint 2

Ensure the partition indices i and j (where j = k - i) satisfy arr1[i-1] <= arr2[j] and arr2[j-1] <= arr1[i], handling boundary conditions safely.

Hint 3

For the intersection count, iterate over distinct values in the smaller array and binary-search for their presence in the larger array.