Open In App

Pair of arrays with equal sum after removing exactly one element from each

Last Updated : 23 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 \mathcal{O}(k*k*maxl*maxl)       Space Complexity\mathcal{O}(k*maxl)       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: 

CPP

// C++program to print the pair of arrays
// whose sum are equal after removing
// exactly one element from each
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the pair of array and index
// of element to be removed to make sum equal
void printPair(vector<int> a[], int k)
{
 
    // stores the sum removing one element,
    // array number and index of removed element
    vector<pair<int, pair<int, int> > > ans;
 
    // traverse in every array
    for (int i = 0; i < k; i++) {
 
        // length of array
        int l = a[i].size();
 
        int sum = 0;
 
        // compute total sum of array
        for (int j = 0; j < l; j++) {
            sum = sum + a[i][j];
        }
 
        // remove each element once and insert sum in
        // ans vector along with index
        for (int j = 0; j < l; j++) {
            ans.push_back({ sum - a[i][j], { i + 1, j } });
        }
    }
 
    // sort the ans vector so that
    // same sum values after removing
    // a single element comes together
    sort(ans.begin(), ans.end());
 
    bool flag = false;
 
    // iterate and check if any adjacent sum are equal
    for (int p = 1; p < ans.size(); p++) {
 
        // check if the adjacent sum belong to different array
        // if the adjacent sum is equal
        if (ans[p - 1].first == ans[p].first
            && ans[p - 1].second.first != ans[p].second.first) {
 
            // first array number
            int ax = ans[p - 1].second.first;
 
            // element's index removed from first array
            int aidx = ans[p - 1].second.second;
 
            // second  array number
            int bx = ans[p].second.first;
 
            // element's index removed from second array
            int bidx = ans[p].second.second;
 
            cout << "Array " << ax << ", index " << aidx << "\n";
            cout << "Array " << bx << ", index " << bidx << "\n";
 
            flag = true;
            break;
        }
    }
 
    // If no pairs are found
    if (!flag)
        cout << "No special pair exists\n";
}
 
// Driver Code
int main()
{
    // k sets of array
    vector<int> a[] = {
        { 8, 1, 4, 7, 1 },
        { 10, 10 },
        { 1, 3, 4, 7, 3, 2, 2 }
    };
    int k = sizeof(a) / sizeof(a[0]);
 
    // Calling Function to print the pairs if any
    printPair(a, k);
 
    return 0;
}

                    

Java

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
 
class Pair<F, S> {
    private F first;
    private S second;
 
    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }
 
    public F getFirst() {
        return first;
    }
 
    public S getSecond() {
        return second;
    }
}
 
public class Main {
    // Function to print the pair of array and index
    // of element to be removed to make the sum equal
    static void printPair(List<Integer>[] a, int k) {
        // Stores the sum removing one element,
        // array number, and index of the removed element
        List<Pair<Integer, Pair<Integer, Integer>>> ans = new ArrayList<>();
 
        // Traverse in every array
        for (int i = 0; i < k; i++) {
            // Length of array
            int l = a[i].size();
            int sum = 0;
 
            // Compute the total sum of the array
            for (int j = 0; j < l; j++) {
                sum += a[i].get(j);
            }
 
            // Remove each element once and insert the sum in
            // ans list along with index
            for (int j = 0; j < l; j++) {
                ans.add(new Pair<>(sum - a[i].get(j), new Pair<>(i + 1, j)));
            }
        }
 
        // Sort the ans list so that
        // the same sum values after removing
        // a single element come together
        Collections.sort(ans, (p1, p2) -> p1.getFirst().compareTo(p2.getFirst()));
 
        boolean flag = false;
 
        // Iterate and check if any adjacent sums are equal
        for (int p = 1; p < ans.size(); p++) {
            // Check if the adjacent sum belongs to different arrays
            // If the adjacent sums are equal
            if (ans.get(p - 1).getFirst().equals(ans.get(p).getFirst()) &&
                    !ans.get(p - 1).getSecond().getFirst().equals(ans.get(p).getSecond().getFirst())) {
 
                // First array number
                int ax = ans.get(p - 1).getSecond().getFirst();
 
                // Element's index removed from the first array
                int aidx = ans.get(p - 1).getSecond().getSecond();
 
                // Second array number
                int bx = ans.get(p).getSecond().getFirst();
 
                // Element's index removed from the second array
                int bidx = ans.get(p).getSecond().getSecond();
 
                System.out.println("Array " + ax + ", index " + aidx);
                System.out.println("Array " + bx + ", index " + bidx);
 
                flag = true;
                break;
            }
        }
 
        // If no pairs are found
        if (!flag)
            System.out.println("No special pair exists");
    }
 
    public static void main(String[] args) {
        // k sets of arrays
        List<Integer>[] a = new List[]{
            List.of(8, 1, 4, 7, 1),
            List.of(10, 10),
            List.of(1, 3, 4, 7, 3, 2, 2)
        };
        int k = a.length;
 
        // Calling the function to print the pairs if any
        printPair(a, k);
    }
}

                    

Python3

def print_pair(a):
    k = len(a)
 
    # stores the sum removing one element,
    # array number and index of removed element
    ans = []
 
    # traverse in every array
    for i in range(k):
 
        # length of array
        l = len(a[i])
 
        sum = 0
 
        # compute total sum of array
        for j in range(l):
            sum = sum + a[i][j]
 
        # remove each element once and insert sum in
        # ans list along with index
        for j in range(l):
            ans.append((sum - a[i][j], (i + 1, j)))
 
    # sort the ans list so that
    # same sum values after removing
    # a single element comes together
    ans.sort()
 
    flag = False
 
    # iterate and check if any adjacent sum are equal
    for p in range(1, len(ans)):
 
        # check if the adjacent sum belong to different array
        # if the adjacent sum is equal
        if ans[p - 1][0] == ans[p][0] and ans[p - 1][1][0] != ans[p][1][0]:
 
            # first array number
            ax = ans[p - 1][1][0]
 
            # element's index removed from first array
            aidx = ans[p - 1][1][1]
 
            # second array number
            bx = ans[p][1][0]
 
            # element's index removed from second array
            bidx = ans[p][1][1]
 
            print(f"Array {ax}, index {aidx}")
            print(f"Array {bx}, index {bidx}")
 
            flag = True
            break
 
    # If no pairs are found
    if not flag:
        print("No special pair exists")
 
# k sets of array
a = [
    [8, 1, 4, 7, 1],
    [10, 10],
    [1, 3, 4, 7, 3, 2, 2]
]
 
# Calling Function to print the pairs if any
print_pair(a)

                    

C#

using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    // Function to print the pair of array and index
    // of element to be removed to make sum equal
    static void PrintPair(List<int>[] a, int k)
    {
        // stores the sum removing one element,
        // array number, and index of removed element
        List<Tuple<int, Tuple<int, int>>> ans = new List<Tuple<int, Tuple<int, int>>>();
 
        // traverse in every array
        for (int i = 0; i < k; i++)
        {
            // length of array
            int l = a[i].Count;
 
            int sum = 0;
 
            // compute the total sum of array
            for (int j = 0; j < l; j++)
            {
                sum = sum + a[i][j];
            }
 
            // remove each element once and insert sum in
            // ans list along with index
            for (int j = 0; j < l; j++)
            {
                ans.Add(new Tuple<int, Tuple<int, int>>(sum - a[i][j],
                                                        new Tuple<int, int>(i + 1, j)));
            }
        }
 
        // sort the ans list so that
        // same sum values after removing
        // a single element come together
        ans = ans.OrderBy(t => t.Item1).ToList();
 
        bool flag = false;
 
        // iterate and check if any adjacent sums are equal
        for (int p = 1; p < ans.Count; p++)
        {
            // check if the adjacent sum belongs to a different array
            // if the adjacent sum is equal
            if (ans[p - 1].Item1 == ans[p].Item1 &&
                ans[p - 1].Item2.Item1 != ans[p].Item2.Item1)
            {
                // first array number
                int ax = ans[p - 1].Item2.Item1;
 
                // element's index removed from the first array
                int aidx = ans[p - 1].Item2.Item2;
 
                // second array number
                int bx = ans[p].Item2.Item1;
 
                // element's index removed from the second array
                int bidx = ans[p].Item2.Item2;
 
                Console.WriteLine($"Array {ax}, index {aidx}");
                Console.WriteLine($"Array {bx}, index {bidx}");
 
                flag = true;
                break;
            }
        }
 
        // If no pairs are found
        if (!flag)
            Console.WriteLine("No special pair exists");
    }
 
    // Driver Code
    static void Main()
    {
        // k sets of array
        List<int>[] a = {
            new List<int> { 8, 1, 4, 7, 1 },
            new List<int> { 10, 10 },
            new List<int> { 1, 3, 4, 7, 3, 2, 2 }
        };
        int k = a.Length;
 
        // Calling Function to print the pairs if any
        PrintPair(a, k);
    }
}

                    

Javascript

function printPair(arrays) {
    const ans = [];
     
    // Traverse through each array
    for (let i = 0; i < arrays.length; i++) {
        const array = arrays[i];
        const sum = array.reduce((acc, val) => acc + val, 0);
         
        // Remove each element once and insert sum in ans array along with index
        for (let j = 0; j < array.length; j++) {
            ans.push([sum - array[j], [i + 1, j]]);
        }
    }
     
    // Sort the ans array so that same sum values after removing a single element come together
    ans.sort((a, b) => a[0] - b[0]);
     
    let flag = false;
     
    // Iterate and check if any adjacent sums are equal
    for (let p = 1; p < ans.length; p++) {
        // Check if the adjacent sums belong to different arrays and if the sums are equal
        if (ans[p - 1][0] === ans[p][0] && ans[p - 1][1][0] !== ans[p][1][0]) {
            const ax = ans[p - 1][1][0];
            const aidx = ans[p - 1][1][1];
            const bx = ans[p][1][0];
            const bidx = ans[p][1][1];
             
            console.log(`Array ${ax}, index ${aidx}`);
            console.log(`Array ${bx}, index ${bidx}`);
             
            flag = true;
            break;
        }
    }
     
    // If no pairs are found
    if (!flag) {
        console.log("No special pair exists");
    }
}
 
// Driver Code
const arrays = [
    [8, 1, 4, 7, 1],
    [10, 10],
    [1, 3, 4, 7, 3, 2, 2]
];
 
// Calling the function to print the pairs if any
printPair(arrays);
 
 
// code is contributed by shinjanpatra

                    

Output
Array 1, index 4
Array 3, index 5




Time Complexity\mathcal{O}(\sum_{i=1}^{i=k}l_{i})       , or simply, \mathcal{O}(k*maxl)       Space Complexity\mathcal{O}(\sum_{i=1}^{i=k}l_{i})       , or simply, \mathcal{O}(k*maxl)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads