Given two same sized arrays A and B (both arrays contain distinct elements individually but may have some common elements), task is to form a third (or result) array of same size. The result array should have maximum n elements from both array. It should have chosen elements of A first, then chosen elements of B in same order as they appear in original arrays. If there are common elements, then only one element should be present in res and priority should be given to A.
Input : A = [ 9 7 2 3 6 ] B = [ 7 4 8 0 1 ] Output : res = [9 7 6 4 8] res has maximum n elements of both A and B such that elements of A appear first (in same order), then elements of B. Also 7 is common and priority is given to A's 7. Input : A = [ 6 7 5 3 ] B = [ 5 6 2 9 ] Output : res = [ 6 7 5 9 ]
1) Create copies of both arrays and sort the copies in decreasing order.
2) Use a hash to pick unique n maximum elements of both arrays, giving priority to A.
3) Initialize result array as empty.
4) Traverse through A, copy those elements of A that are present in the hash. This is done to keep order of elements same.
5) Repeat step 4 for B. This time we only consider those elements that are not present in A (Do not appear twice in hash).
Below c++ implementation of above idea.
9 7 6 4 8
Time complexity: O(n Log n)
- Maximum sum by picking elements from two arrays in order
- Maximum sum of increasing order elements from n arrays
- Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum
- Find k maximum elements of array in original order
- Break an array into maximum number of sub-arrays such that their averages are same
- Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
- Merging two unsorted arrays in sorted order
- Number of ways to merge two arrays such retaining order
- Sort an array where a subarray of a sorted array is in reverse order
- Print elements of an array according to the order defined by another array | set 2
- Find maximum topics to prepare in order to pass the exam
- Sort an array according to the order defined by another array
- Maximum OR sum of sub-arrays of two different arrays
- Performance analysis of Row major and Column major order of storing arrays in C
- Maximum Sum Path in Two Arrays
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.