KatInterview

Rank Among Values Occurring Once Across Two Lists

Arrays & HashingAuto-graded · 20 test cases
MediumAuto-gradedArrays & Hashinghash-mapcountingsorting

Last updated

Count occurrences across two combined lists, keep values seen exactly once, and return the k-th largest of them or -1 if there are fewer than k.

You are given two integer lists, first and second, and a positive integer k.

Treat the two lists as one pool of numbers. Call a value a singleton if it occurs exactly one time in the whole pool, counting occurrences in both lists together. A value that appears twice in one list, or once in each list, is not a singleton.

Order the singleton values from largest to smallest. Return the one in position k (counting from 1). If the pool has fewer than k singleton values, return -1.

Details

  • Occurrences are counted over both lists combined, not per list.
  • Each singleton value is considered once in the ranking.
  • One or both lists may be empty.
  • Values may be negative. The return value -1 is the required result when there are fewer than k singletons, even though -1 can also be a genuine singleton value. Follow the rule exactly as stated.

Constraints

  • 0 <= len(first), len(second) <= 10^5
  • Every value is in the range [-10^6, 10^6]
  • 1 <= k <= 10^5

Examples

Example 1

Input: kth_largest_singleton([3, 2, 1, 3], [4, 1, 5], 2)

Output: 4

Example 2

Input: kth_largest_singleton([1, 1], [2, 2], 1)

Output: -1

Hints

Hint 1

Whether a value qualifies depends on its total count across both lists, so checking each list separately is not enough.

Hint 2

Build a frequency map over the combined data, then keep only the values whose frequency is exactly 1.

Hint 3

Sort the surviving values in descending order and read index k - 1, after checking that k does not exceed their number. A size-k min-heap also works.