![]() |
VOOZH | about |
Given K arrays of different size. The task is to check if there exist any two arrays which have the same sum of elements after removing exactly one element from each of them. (Any element can be removed, but exactly one has to be removed). Print the indices of the array and the index of the removed elements if such pairs exist. If there are multiple pairs, print any one of them. If no such pairs exist, print -1. Examples:
Input: k = 3 a1 = {8, 1, 4, 7, 1} a2 = {10, 10} a3 = {1, 3, 4, 7, 3, 2, 2} Output: Array 1, index 4 Array 3, index 5 sum of Array 1{8, 1, 4, 7, 1} without index 4 is 20. sum of Array 3{1, 3, 4, 7, 3, 2, 2} without index 5 is 20. Input: k = 4 a1 = {2, 4, 6, 6} a2 = {1, 2, 4, 8, 16} a3 = {1, 3, 8} a4 = {1, 4, 16, 64} Output: -1
Brute Force: For every pair of arrays, for each element, find the sum excluding that element and compare it with the sum excluding each element one by one in the second array of the chosen pair. (Here maxl denotes the maximum length of an array in the set). Time Complexity : Space Complexity : Efficient Approach: Precompute all possible values of the sum obtained by removing one element from each of the arrays. Store the array index and element index which is removed with the computed sum. When these values are arranged in increasing order, it can easily be seen that if a solution exists, then both the sum values must be adjacent to the new arrangement. When two adjacent sum values are same, check if they belong to different arrays. If they do, print the array number and index of the element removed. If no such sum value is found, then no such pairs exist. Below is the implementation of the above approach:
Array 1, index 4 Array 3, index 5
Time Complexity : , or simply, Space Complexity : , or simply,