Given 2 integer arrays A and B(with no repeated elements in each) of size N and M respectively, form N + M – 1 pairs, each pair having one element from both the arrays, such that the sum of all the pairs is unique. For each pair, print the index of the elements in their respective array.
Input: N = 5, M = 3 A = [6, 5, 7, 1, 3] B = [2, 4, 8] Output: 2 0 2 1 2 2 3 0 4 0 1 0 0 0 We have to form 5 + 3 - 1 = 7 pairs. These pairs are: (7, 2), (7, 4), (7, 8), (1, 2), (3, 2), (5, 2), (6, 2) All have unique sum
Brute Force Approach: We can run a loop on both arrays A and B to find the first N+M-1 unique sum pairs, and print their indexes along the way.
To check if a particular sum has already been used, we make a python bool dictionary. If the dictionary value for that sum is False, that means it is a new sum value. If it is True, the sum has already been used.
0 0 0 1 0 2 0 3 1 0 1 3 2 3 4 1 4 2
Time Complexity: Since we traverse the array with nested loops, the time complexity comes out to be O().
Efficient Approach: Once we sort both the arrays, first we can make N unique sum pairs by pairing all elements of array A with the first element of array B, and then pairing the other M – 1 elements of array B with the last element of array A.
5 3 2 3 1 3 3 3 0 3 4 3 4 0 4 2 4 1
Time Complexity: The complexity for this is equal to the time required for sorting: O(n Log n).
Space Complexity: Since we are using two different maps/dictionaries to store the indexes of the array. The time complexity will be O(n + m) , where n is the size of first array and m is the size of second array.
- Find the first non-repeating character from a stream of characters
- Regular Expressions in Python | Set 2 (Search, Match and Find All)
- Python String Methods | Set 1 (find, rfind, startwith, endwith, islower, isupper, lower, upper, swapcase & title)
- Analysis of Different Methods to find Prime Number in Python
- Merge two sorted arrays in Python using heapq
- intersection_update() in Python to find common elements in n arrays
- Python program to find IP Address
- Set update() in Python to do union of n arrays
- Using Counter() in Python to find minimum character removal to make two strings anagram
- Find average of a list in python
- Find all the patterns of “1(0+)1” in a given string using Python Regex
- Find the first repeated word in a string in Python using Dictionary
- Dictionary and counter in Python to find winner of election
- Find the k most frequent words from data set in Python
- Python program to find N largest elements from a list
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.