![]() |
VOOZH | about |
Given two arrays a[] and b[] of size n. The task is to create an array the same size using the elements from both the arrays such that the new array formed contains n greatest but unique elements of both the arrays. The order of elements should follow the below rules.
Examples:
Input: a[] = [2, 4, 3] , b[] = [5, 6, 1]
Output: 5 6 4
Explanation: As 5, 6 and 4 are maximum elements from two arrays giving second array higher priority. Order of elements is same in output as in input.Input: a[] = [7, 4, 8, 0, 1] , b[] = [9, 10, 2, 3, 6]
Output: 9 10 6 7 8
Explanation: As 10, 9, 8, 7 and 6 are maximum elements from two arrays giving second array higher priority. Order of elements is same in output as in input.
Table of Content
The idea is to merge both arrays and sort the merged array in decreasing order. Then store the
nlargest unique elements using a hash set. Finally, traversebfirst andanext, and add elements toansonly if they are among the selected elements and are not already added. This maintains the required order and gives the maximum unique elements.
9 10 6 7 8
Time Complexity: O(n log n)
Auxiliary Space: O(n)
The idea is to use a max heap to store all elements of both arrays so that the largest elements can be accessed efficiently. Then store the
nlargest unique elements in a hash set. Finally, traversebfirst andanext, and add elements toansonly if they belong to the selected elements and are not already added. This maintains the required order and gives the maximum unique elements.
9 10 6 7 8
Time Complexity: O(n log n)
Auxiliary Space: O(n)