Find sub-arrays from given two arrays such that they have equal sum
Last Updated :
16 Nov, 2023
Given two arrays A[] and B[] of equal sizes i.e. N containing integers from 1 to N. The task is to find sub-arrays from the given arrays such that they have equal sum. Print the indices of such sub-arrays. If no such sub-arrays are possible then print -1.
Examples:
Input: A[] = {1, 2, 3, 4, 5}, B[] = {6, 2, 1, 5, 4}
Output:
Indices in array 1 : 0, 1, 2
Indices in array 2 : 0
A[0..2] = 1 + 2 + 3 = 6
B[0] = 6
Input: A[] = {10, 1}, B[] = {5, 3}
Output: -1
No such sub-arrays.
Naive Approach:
The idea is to find the sum of every subarray of 1st array and the sum of every subarray of 2nd array. Now compare the sum of each subarray of the 1st array with every subarray of the 2nd array. If anytime during comparison, the sum becomes equal, then print indices of the element that are chosen to make both subarrays. In last if the sum never becomes equal then print -1.
Steps for Implementation will be-
- Run two nested for loops to find all subarrays of 1st Array
- Now to compare each subarray of 1st array with every subarray of the 2nd array we will have two more nested for loops in that loop
- Anytime during this comparison, if the sum of the subarray from the 1st array becomes equal to the sum of the subarray of the 2nd Array then print indices of the subarrays using a for loop and stop comparing.
- Till last if nothing got printed then print "-1".
Code-
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find sub-arrays from two
// different arrays with equal sum
void findSubarray(int N, int A[], int B[])
{
int sum1;
int sum2;
for (int i = 0; i < N; i++) {
sum1 = 0;
for (int j = i; j < N; j++) {
sum1 += A[j];
for (int a = 0; a < N; a++) {
sum2 = 0;
for (int b = a; b < N; b++) {
sum2 += B[b];
if (sum1 == sum2) {
cout << "Indices in array 1 : ";
for (int m = i; m <= j; m++) {
cout << m << " ";
}
cout << endl;
cout << "Indices in array 2 : ";
for (int m = a; m <= b; m++) {
cout << m << " ";
}
cout << endl;
return;
}
}
}
}
}
// When no such answer exists then print -1
cout << "-1" << endl;
}
// Driver code
int main()
{
int A[] = { 1, 2, 3, 4, 5 };
int B[] = { 6, 2, 1, 5, 4 };
int N = sizeof(A) / sizeof(A[0]);
findSubarray(N, A, B);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
public class GFG {
// Function to find sub-arrays from two different arrays
// with equal sum
static void findSubarray(int N, int[] A, int[] B)
{
int sum1, sum2;
for (int i = 0; i < N; i++) {
sum1 = 0;
for (int j = i; j < N; j++) {
sum1 += A[j];
for (int a = 0; a < N; a++) {
sum2 = 0;
for (int b = a; b < N; b++) {
sum2 += B[b];
if (sum1 == sum2) {
System.out.print(
"Indices in array 1: ");
for (int m = i; m <= j; m++) {
System.out.print(m + " ");
}
System.out.println();
System.out.print(
"Indices in array 2: ");
for (int m = a; m <= b; m++) {
System.out.print(m + " ");
}
System.out.println();
return;
}
}
}
}
}
// When no such answer exists, then print -1
System.out.println("-1");
}
// Driver code
public static void main(String[] args)
{
int[] A = { 1, 2, 3, 4, 5 };
int[] B = { 6, 2, 1, 5, 4 };
int N = A.length;
findSubarray(N, A, B);
}
}
// This code is contributed by Susobhan Akhuli
Python3
# Python implementation of the approach
# Function to find sub-arrays from two different arrays with equal sum
def findSubarray(N, A, B):
for i in range(N):
sum1 = 0
for j in range(i, N):
sum1 += A[j]
for a in range(N):
sum2 = 0
for b in range(a, N):
sum2 += B[b]
if sum1 == sum2:
print("Indices in array 1 : ", end="")
for m in range(i, j + 1):
print(m, end=" ")
print()
print("Indices in array 2 : ", end="")
for m in range(a, b + 1):
print(m, end=" ")
print()
return
# When no such answer exists then print -1
print("-1")
# Driver code
if __name__ == "__main__":
A = [1, 2, 3, 4, 5]
B = [6, 2, 1, 5, 4]
N = len(A)
findSubarray(N, A, B)
# This code is contributed by Susobhan Akhuli
C#
using System;
class Program
{
// Function to find sub-arrays from two
// different arrays with equal sum
static void FindSubarray(int[] A, int[] B)
{
int sum1;
int sum2;
for (int i = 0; i < A.Length; i++)
{
sum1 = 0;
for (int j = i; j < A.Length; j++)
{
sum1 += A[j];
for (int a = 0; a < B.Length; a++)
{
sum2 = 0;
for (int b = a; b < B.Length; b++)
{
sum2 += B[b];
if (sum1 == sum2)
{
Console.Write("Indices in array 1: ");
for (int m = i; m <= j; m++)
{
Console.Write(m + " ");
}
Console.WriteLine();
Console.Write("Indices in array 2: ");
for (int m = a; m <= b; m++)
{
Console.Write(m + " ");
}
Console.WriteLine();
return;
}
}
}
}
}
// When no such answer exists then print -1
Console.WriteLine("-1");
}
static void Main()
{
int[] A = { 1, 2, 3, 4, 5 };
int[] B = { 6, 2, 1, 5, 4 };
FindSubarray(A, B);
}
}
JavaScript
// JavaScript implementation of the approach
// Function to find sub-arrays from two
// different arrays with equal sum
function findSubarray(N, A, B) {
let sum1;
let sum2;
for (let i = 0; i < N; i++) {
sum1 = 0;
for (let j = i; j < N; j++) {
sum1 += A[j];
for (let a = 0; a < N; a++) {
sum2 = 0;
for (let b = a; b < N; b++) {
sum2 += B[b];
if (sum1 === sum2) {
document.write("Indices in array 1 : " +
Array.from({ length: j - i + 1 }, (_, idx) => idx + i).join(" "));
document.write("<br>");
document.write("Indices in array 2 : " +
Array.from({ length: b - a + 1 }, (_, idx) => idx + a).join(" "));
return;
}
}
}
}
}
// When no such answer exists then print -1
document.write("-1");
}
// Driver code
let A = [1, 2, 3, 4, 5];
let B = [6, 2, 1, 5, 4];
let N = A.length;
findSubarray(N, A, B);
// This code is contributed by Susobhan Akhuli
OutputIndices in array 1 : 0
Indices in array 2 : 2
Time Complexity: O(N2 * N2 *N)=O(N5), O(N2) for finding subarray from the first array and O(N2) for finding subarray from 2nd array, and O(N) for printing indices.
Space Complexity: O(1), because no extra space has been used
Approach: Let Ai denote the sum of first i elements in A and Bj denote the sum of first j elements in B. Without loss of generality we assume that An <= Bn.
Now Bn >= An >= Ai. So for each Ai we can find the smallest j such that Ai <= Bj. For each i we find the difference
Bj - Ai .
If difference is 0 then we are done as the elements from 1 to i in A and 1 to j in B have the same sum. Suppose difference is not 0.Then the difference must lie in the range [1, n-1].
Proof:
Let Bj - Ai >= n
Bj >= Ai + n
Bj-1 >= Ai (As the jth element in B can be at most n so Bj <= Bj-1 + n)
Now this is a contradiction as we had assumed that j is the smallest index
such that Bj >= Ai is j. So our assumption is wrong.
So Bj - Ai < n
Now there are n such differences(corresponding to each index) but only (n-1) possible values, so at least two indices will produce the same difference(By Pigeonhole principle). Let Aj - By = Ai - Bx. On rearranging we get Aj - Ai = By - Bx. So the required subarrays are [ i+1, j ] in A and [ x+1, y ] in B.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to print the valid indices in the array
void printAns(int x, int y, int num)
{
cout << "Indices in array " << num << " : ";
for (int i = x; i < y; ++i) {
cout << i << ", ";
}
cout << y << "\n";
}
// Function to find sub-arrays from two
// different arrays with equal sum
void findSubarray(int N, int a[], int b[], bool swap)
{
// Map to store the indices in A and B
// which produce the given difference
std::map<int, pair<int, int> > index;
int difference;
index[0] = make_pair(-1, -1);
int j = 0;
for (int i = 0; i < N; ++i) {
// Find the smallest j such that b[j] >= a[i]
while (b[j] < a[i]) {
j++;
}
difference = b[j] - a[i];
// Difference encountered for the second time
if (index.find(difference) != index.end()) {
// b[j] - a[i] = b[idx.second] - a[idx.first]
// b[j] - b[idx.second] = a[i] = a[idx.first]
// So sub-arrays are a[idx.first+1...i] and b[idx.second+1...j]
if (swap) {
pair<int, int> idx = index[b[j] - a[i]];
printAns(idx.second + 1, j, 1);
printAns(idx.first + 1, i, 2);
}
else {
pair<int, int> idx = index[b[j] - a[i]];
printAns(idx.first + 1, i, 1);
printAns(idx.second + 1, j, 2);
}
return;
}
// Store the indices for difference in the map
index[difference] = make_pair(i, j);
}
cout << "-1";
}
// Utility function to calculate the
// cumulative sum of the array
void cumulativeSum(int arr[], int n)
{
for (int i = 1; i < n; ++i)
arr[i] += arr[i - 1];
}
// Driver code
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
int b[] = { 6, 2, 1, 5, 4 };
int N = sizeof(a) / sizeof(a[0]);
// Function to update the arrays
// with their cumulative sum
cumulativeSum(a, N);
cumulativeSum(b, N);
if (b[N - 1] > a[N - 1]) {
findSubarray(N, a, b, false);
}
else {
// Swap is true as a and b are swapped during
// function call
findSubarray(N, b, a, true);
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG {
// Function to print the valid indices in the array
static void printAns(int x, int y, int num)
{
System.out.print("Indices in array " + num + " : ");
for (int i = x; i < y; ++i) {
System.out.print(i + ", ");
}
System.out.println(y);
}
// Function to find sub-arrays from two
// different arrays with equal sum
static void findSubarray(int N, int a[], int b[], Boolean swap)
{
// Map to store the indices in A and B
// which produce the given difference
HashMap<Integer,ArrayList<Integer>> index = new HashMap<>();
int difference;
index.put(0 , new ArrayList<Integer>(Arrays.asList(-1, -1)));
int j = 0;
for (int i = 0; i < N; ++i) {
// Find the smallest j such that b[j] >= a[i]
while (b[j] < a[i]) {
j++;
}
difference = b[j] - a[i];
// Difference encountered for the second time
if (index.containsKey(difference)) {
// b[j] - a[i] = b[idx.second] - a[idx.first]
// b[j] - b[idx.second] = a[i] = a[idx.first]
// So sub-arrays are a[idx.first+1...i] and b[idx.second+1...j]
if (swap) {
ArrayList<Integer> idx = index.get(b[j] - a[i]);
printAns(idx.get(1) + 1, j, 1);
printAns(idx.get(0) + 1, i, 2);
}
else {
ArrayList<Integer> idx = index.get(b[j] - a[i]);
printAns(idx.get(0) + 1, i, 1);
printAns(idx.get(1) + 1, j, 2);
}
return;
}
// Store the indices for difference in the map
ArrayList<Integer>arr = new ArrayList<>(Arrays.asList(i,j));
}
System.out.print("-1");
}
// Utility function to calculate the
// cumulative sum of the array
static void cumulativeSum(int arr[], int n)
{
for (int i = 1; i < n; ++i)
arr[i] += arr[i - 1];
}
// Driver code
public static void main(String args[])
{
int a[] = { 1, 2, 3, 4, 5 };
int b[] = { 6, 2, 1, 5, 4 };
int N = a.length;
// Function to update the arrays
// with their cumulative sum
cumulativeSum(a, N);
cumulativeSum(b, N);
if (b[N - 1] > a[N - 1]) {
findSubarray(N, a, b, false);
}
else {
// Swap is true as a and b are swapped during
// function call
findSubarray(N, b, a, true);
}
}
}
// This code is contributed by shinjanpatra
Python3
# Python3 implementation of the approach
# Function to print the valid indices in the array
def printAns(x, y, num):
print("Indices in array", num, ":", end = " ")
for i in range(x, y):
print(i, end = ", ")
print(y)
# Function to find sub-arrays from two
# different arrays with equal sum
def findSubarray(N, a, b, swap):
# Map to store the indices in A and B
# which produce the given difference
index = {}
difference, j = 0, 0
index[0] = (-1, -1)
for i in range(0, N):
# Find the smallest j such that b[j] >= a[i]
while b[j] < a[i]:
j += 1
difference = b[j] - a[i]
# Difference encountered for the second time
if difference in index:
# b[j] - a[i] = b[idx.second] - a[idx.first]
# b[j] - b[idx.second] = a[i] = a[idx.first]
# So sub-arrays are a[idx.first+1...i] and b[idx.second+1...j]
if swap:
idx = index[b[j] - a[i]]
printAns(idx[1] + 1, j, 1)
printAns(idx[0] + 1, i, 2)
else:
idx = index[b[j] - a[i]]
printAns(idx[0] + 1, i, 1)
printAns(idx[1] + 1, j, 2)
return
# Store the indices for difference in the map
index[difference] = (i, j)
print("-1")
# Utility function to calculate the
# cumulative sum of the array
def cumulativeSum(arr, n):
for i in range(1, n):
arr[i] += arr[i - 1]
# Driver code
if __name__ == "__main__":
a = [1, 2, 3, 4, 5]
b = [6, 2, 1, 5, 4]
N = len(a)
# Function to update the arrays
# with their cumulative sum
cumulativeSum(a, N)
cumulativeSum(b, N)
if b[N - 1] > a[N - 1]:
findSubarray(N, a, b, False)
else:
# Swap is true as a and b are
# swapped during function call
findSubarray(N, b, a, True)
# This code is contributed by Rituraj Jain
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to print the valid indices in the array
static void printAns(int x, int y, int num)
{
Console.Write("Indices in array " + num + " : ");
for (int i = x; i < y; ++i) {
Console.Write(i + ", ");
}
Console.WriteLine(y);
}
// Function to find sub-arrays from two
// different arrays with equal sum
static void findSubarray(int N, int[] a, int[] b, bool swap)
{
// Map to store the indices in A and B
// which produce the given difference
Dictionary<int, List<int>> index = new Dictionary<int, List<int>>();
int difference;
index[0] = new List<int>(new[] {-1, -1});
int j = 0;
for (int i = 0; i < N; ++i) {
// Find the smallest j such that b[j] >= a[i]
while (b[j] < a[i]) {
j++;
}
difference = b[j] - a[i];
// Difference encountered for the second time
if (index.ContainsKey(difference)) {
// b[j] - a[i] = b[idx.second] - a[idx.first]
// b[j] - b[idx.second] = a[i] = a[idx.first]
// So sub-arrays are a[idx.first+1...i] and b[idx.second+1...j]
if (swap) {
List<int> idx = index[b[j] - a[i]];
printAns(idx[1] + 1, j, 1);
printAns(idx[0] + 1, i, 2);
}
else {
List<int> idx = index[b[j] - a[i]];
printAns(idx[0] + 1, i, 1);
printAns(idx[1] + 1, j, 2);
}
return;
}
}
Console.Write("-1");
}
// Utility function to calculate the
// cumulative sum of the array
static void cumulativeSum(int[] arr, int n)
{
for (int i = 1; i < n; ++i)
arr[i] += arr[i - 1];
}
// Driver code
public static void Main(string[] args)
{
int[] a = { 1, 2, 3, 4, 5 };
int[] b = { 6, 2, 1, 5, 4 };
int N = a.Length;
// Function to update the arrays
// with their cumulative sum
cumulativeSum(a, N);
cumulativeSum(b, N);
if (b[N - 1] > a[N - 1]) {
findSubarray(N, a, b, false);
}
else {
// Swap is true as a and b are swapped during
// function call
findSubarray(N, b, a, true);
}
}
}
// This code is contributed by phasing17
JavaScript
<script>
// JavaScript implementation of the approach
// Function to print the valid indices in the array
function printAns(x, y, num)
{
document.write("Indices in array", num, ":"," ")
for(let i = x; i < y; i++)
document.write(i,", ")
document.write(y,"</br>")
}
// Function to find sub-arrays from two
// different arrays with equal sum
function findSubarray(N, a, b, swap){
// Map to store the indices in A and B
// which produce the given difference
let index = new Map();
let difference = 0, j = 0
index.set(0, [-1, -1])
for(let i = 0; i < N; i++)
{
// Find the smallest j such that b[j] >= a[i]
while(b[j] < a[i])
j += 1
let difference = b[j] - a[i]
// Difference encountered for the second time
if(index.has(difference)){
// b[j] - a[i] = b[idx.second] - a[idx.first]
// b[j] - b[idx.second] = a[i] = a[idx.first]
// So sub-arrays are a[idx.first+1...i] and b[idx.second+1...j]
if(swap){
let idx = index.get(b[j] - a[i])
printAns(idx[1] + 1, j, 1)
printAns(idx[0] + 1, i, 2)
}
else{
let idx = index.get(b[j] - a[i])
printAns(idx[0] + 1, i, 1)
printAns(idx[1] + 1, j, 2)
}
return
// Store the indices for difference in the map
}
index.set(difference,[i, j])
}
document.write("-1")
}
// Utility function to calculate the
// cumulative sum of the array
function cumulativeSum(arr, n){
for(let i = 1; i < n; i++)
arr[i] += arr[i - 1]
}
// Driver code
let a = [1, 2, 3, 4, 5]
let b = [6, 2, 1, 5, 4]
let N = a.length
// Function to update the arrays
// with their cumulative sum
cumulativeSum(a, N)
cumulativeSum(b, N)
if(b[N - 1] > a[N - 1])
findSubarray(N, a, b, false)
else
// Swap is true as a and b are
// swapped during function call
findSubarray(N, b, a, true)
// This code is contributed by shinjanpatra
</script>
OutputIndices in array 1 : 0, 1, 2
Indices in array 2 : 0
Time Complexity: O(N* Log N)
Space Complexity: O(N)
Similar Reads
Find three element from given three arrays such that their sum is X | Set 2 Given three sorted integer arrays A[], B[] and C[], the task is to find three integers, one from each array such that they sum up to a given target value X. Print Yes or No depending on whether such triplet exists or not.Examples: Input: A[] = {2}, B[] = {1, 6, 7}, C[] = {4, 5}, X = 12 Output: Yes A
9 min read
Minimum sum of two elements from two arrays such that indexes are not same Given two arrays a[] and b[] of same size. Task is to find minimum sum of two elements such that they belong to different arrays and are not at same index in their arrays. Examples: Input : a[] = {5, 4, 13, 2, 1} b[] = {2, 3, 4, 6, 5}Output : 3We take 1 from a[] and 2 from b[]Sum is 1 + 2 = 3.Input
15+ min read
Choose two elements from the given array such that their sum is not present in any of the arrays Given two arrays A[] and B[], the task is to choose two elements X and Y such that X belongs to A[] and Y belongs to B[] and (X + Y) must not be present in any of the array.Examples: Input: A[] = {3, 2, 2}, B[] = {1, 5, 7, 7, 9} Output: 3 9 3 + 9 = 12 and 12 is not present in any of the given arrays
5 min read
Count of pairs between two arrays such that the sums are distinct Given two arrays a[] and b[], the task is to find the count of all pairs (a[i], b[j]) such that a[i] + b[j] is unique among all the pairs i.e. if two pairs have equal sum then only one will be counted in the result.Examples: Input: a[] = {3, 3}, b[] = {3} Output: 1 The two possible pairs are (a[0],
5 min read
Find N'th item in a set formed by sum of two arrays Given two sorted arrays, we can get a set of sums(add one element from the first and one from second). Find the N'th element in the elements of the formed set considered in sorted order. Note: Set of sums should have unique elements. Examples: Input: arr1[] = {1, 2} arr2[] = {3, 4} N = 3 Output: 6 W
6 min read