VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-nth-item-set-formed-sum-two-arrays/

⇱ K'th item in a set formed by sum of two arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

K'th item in a set formed by sum of two arrays

Last Updated : 31 May, 2026

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.

[Expected Approach 1] Sort all Possible Sums - O(n^2 Log n) Time and O(n^2) Space

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.

  • Generate all possible pair sums a[i] + b[j]
  • Store them in an array and sort the array of sums
  • Remove duplicate sums using unique()
  • If k exceeds the number of distinct sums, return -1
  • Otherwise, return the (k-1)-th index element

Output
7

[Expected Approach 2] Using Ordered Set - O(n^2 Log n) Time and O(n^2) Space

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.

  • Create an ordered set
  • Generate all possible sums a[i] + b[j]
  • Insert each sum into the set: Duplicates are automatically ignored and elements remain sorted
  • If the set contains fewer than n elements, return -1
  • Return the value at that position

Note : Python does not support sorted set, so we create a hash set and then sort the elements.


Output
7
Comment
Article Tags: