![]() |
VOOZH | about |
Given two arrays a and b, we can get a set of sums(add one element from the first and one from second). Find the nth element in the set considered in sorted order.
Note: Set of sums should have unique elements.
Examples:
Input: a = [1, 2], b = [3, 4], k = 3
Output: 6
Explanation: The set of sums are in the order 4, 5, 6.Input: a = [1, 3, 4, 8, 10], b = [20, 22, 30, 40], k = 4
Output: 25
Explanation: The numbers before it are 21, 23 and 24.
Table of Content
The idea is to generate every possible sum by taking one element from the first array and one element from the second array. All generated sums are stored in an array, then sorted in increasing order. Duplicate sums are removed so that only distinct sums remain. Finally, the
k-th smallest distinct sum is returned. If fewer than k distinct sums exist, the return-1.
a[i] + b[j]unique()k exceeds the number of distinct sums, return -1(k-1)-th index element7
The idea is to generate all possible sums formed by taking one element from each array and insert them directly into an ordered set. Since a set automatically maintains elements in sorted order and removes duplicates, there is no need for a separate sorting or duplicate-removal step. After all sums are inserted, the iterator is advanced to the
k-th smallest distinct sum and that value is returned.
a[i] + b[j]n elements, return -1Note : Python does not support sorted set, so we create a hash set and then sort the elements.
7