The Wayback Machine - https://web.archive.org/web/20240819104121/https://www.geeksforgeeks.org/find-sub-arrays-from-given-two-arrays-such-that-they-have-equal-sum/
Open In App

Find sub-arrays from given two arrays such that they have equal sum

Last Updated : 16 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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


Output

Indices 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>


Output

Indices in array 1 : 0, 1, 2
Indices in array 2 : 0







Time Complexity: O(N* Log N)
Space Complexity: O(N)



Similar Reads

Count the number of sub-arrays such that the average of elements present in the sub-array is greater than that not present in the sub-array
Given an array of integers arr[], the task is to count the number of sub-arrays such that the average of elements present in the sub-array is greater than the average of elements that are not present in the sub-array.Examples: Input: arr[] = {6, 3, 5} Output: 3 The sub-arrays are {6}, {5} and {6, 3, 5} because their averages are greater than {3, 5}
8 min read
Distinct strings such that they contains given strings as sub-sequences
Given two strings str1 and str2 of lengths M and N respectively. The task is to find all the distinct strings of length M + N such that the frequency of any character in the resultant string is equal to the sum of frequencies of the same character in the given strings and both the given strings are present as a sub-sequence in all the generated str
6 min read
Count sub-arrays which have elements less than or equal to X
Given an array of n elements and an integer X. Count the number of sub-arrays of this array which have all elements less than or equal to X. Examples: Input : arr[] = {1, 5, 7, 8, 2, 3, 9} X = 6 Output : 6 Explanation : Sub-arrays are {1}, {5}, {2}, {3}, {1, 5}, {2, 3} Input : arr[] = {1, 10, 12, 4, 5, 3, 2, 7} X = 9 Output : 16 Naive Approach : A
15 min read
Maximum sub-array sum after dividing array into sub-arrays based on the given queries
Given an array arr[] and an integer k, we can cut this array at k different positions where k[] stores the positions of all the cuts required. The task is to print maximum sum among all the cuts after every cut made. Every cut is of the form of an integer x where x denotes a cut between arr[x] and arr[x + 1]. Examples: Input: arr[] = {4, 5, 6, 7, 8
9 min read
Ways to divide a binary array into sub-arrays such that each sub-array contains exactly one 1
Give an integer array arr[] consisting of elements from the set {0, 1}. The task is to print the number of ways the array can be divided into sub-arrays such that each sub-array contains exactly one 1. Examples: Input: arr[] = {1, 0, 1, 0, 1} Output: 4 Below are the possible ways: {1, 0}, {1, 0}, {1}{1}, {0, 1, 0}, {1}{1, 0}, {1}, {0, 1}{1}, {0, 1}
6 min read
Divide array into two sub-arrays such that their averages are equal
Given an integer array, the task is to divide an integer array into two sub-arrays to make their averages equal if possible. Examples : Input : arr[] = {1, 5, 7, 2, 0}; Output : (0 1) and (2 4) Subarrays arr[0..1] and arr[2..4] have same average. Input : arr[] = {4, 3, 5, 9, 11}; Output : Not possible Asked in Microsoft A Naive Approach is to run t
11 min read
Count of elements such that difference between sum of left and right sub arrays is equal to a multiple of k
Given an array arr[] of length n and an integer k, the task is to find the number of indices from 2 to n-1 in an array having a difference of the sum of the left and right sub arrays equal to the multiple of the given number k. Examples: Input: arr[] = {1, 2, 3, 3, 1, 1}, k = 4 Output: 2 Explanation: The only possible indices are 4 and 5 Input: arr
7 min read
Find an integer such that if it is multiplied by any of the given integers they form G.P.
Given three integers A, B, and C, the task is to find out a positive integer K (if exists) such that if k is multiplied by any of the given integers A, B, or C they form G.P.(Geometric Progression) in the given order. If there exists no K print -1. Examples: Input: A = 1, B = 9, C = 27Output: 3Explanation: If A is multiplied by 3 then the integers
6 min read
Given a string and an integer k, find the kth sub-string when all the sub-strings are sorted according to the given condition
Given a string str, its sub-strings are formed in such a way that all the sub-strings starting with the first character of the string will occur first in the sorted order of their lengths followed by all the sub-strings starting with the second character of the string in the sorted order of their lengths and so on. For example for the string abc, i
9 min read
Maximum OR sum of sub-arrays of two different arrays
Given two arrays of positive integers. Select two sub-arrays of equal size from each array and calculate maximum possible OR sum of the two sub-arrays. Note: Let f(x, l, r) is the OR sum of all the elements in the range [l, r] in array x. Examples : Input : A[] = {1, 2, 4, 3, 2} B[] = {2, 3, 3, 12, 1} Output : 22 Explanation: Here, one way to get m
5 min read
Find the sums for which an array can be divided into sub-arrays of equal sum
Given an array of integers arr[], the task is to find all the values for sum such that for a value sum[i] the array can be divided into sub-arrays of sum equal to sum[i]. If array cannot be divided into sub-arrays of equal sum then print -1. Examples: Input: arr[] = {2, 2, 2, 1, 1, 2, 2} Output: 2 4 6 The array can be divided into sub-arrays of sum
10 min read
Find Four points such that they form a square whose sides are parallel to x and y axes
Given 'n' pair of points, the task is to find four points such that they form a square whose sides are parallel to x and y axes or print "No such square" otherwise. If more than one square is possible then choose the one with the maximum area. Examples: Input : n = 6, points = (1, 1), (4, 4), (3, 4), (4, 3), (1, 4), (4, 1)Output : side of the squar
12 min read
Count of integers of length N and value less than K such that they contain digits only from the given set
Given a set of digits A[] in sorted order and two integers N and K, the task is to find how many numbers of length N are possible whose value is less than K and the digits are from the given set only. Note that you can use the same digit multiple times. Examples: Input: A[] = {0, 1, 5}, N = 1, K = 2 Output: 2 Only valid numbers are 0 and 1. Input:
14 min read
Largest number by which given 3 numbers should be divided such that they leaves same remainder
Given three numbers, our task is to find the largest number by which when given 3 numbers are divided leads to same remainder. It may be assumed that all given numbers are given in increasing order. Examples: Input : a = 62, b = 132, c = 237 Output : 35 35 leads to same remainder 27 when divides 62, 132 and 237. Input : a = 74, b = 272, c = 584 Out
9 min read
Number of sub-arrays that have at least one duplicate
Given an array arr of n elements, the task is to find the number of the sub-arrays of the given array that contain at least one duplicate element. Examples: Input: arr[] = {1, 2, 3} Output: 0 There is no sub-array with duplicate elements. Input: arr[] = {4, 3, 4, 3} Output: 3 Possible sub-arrays are {4, 3, 4}, {4, 3, 4, 3} and {3, 4, 3} Approach: F
5 min read
Find minimum length sub-array which has given sub-sequence in it
Given an array arr[] of N elements, the task is to find the length of the smallest sub-array which has the sequence {0, 1, 2, 3, 4} as a sub-sequence in it. Examples: Input: arr[] = {0, 1, 2, 3, 4, 2, 0, 3, 4} Output: 5 The required Subarray is {0, 1, 2, 3, 4} with minimum length. The entire array also includes the sequence but it is not minimum in
10 min read
Check if array can be divided into two sub-arrays such that their absolute difference is K
Given an array arr[] and an integer K, the task is to find whether the array can be divided into two sub-arrays such that the absolute difference of the sum of the elements of both the sub-arrays is K. Examples: Input: arr[] = {2, 4, 5, 1}, K = 0 Output: Yes {2, 4} and {5, 1} are the two possible sub-arrays. |(2 + 4) - (5 + 1)| = |6 - 6| = 0 Input:
6 min read
Number of ways to divide an array into K equal sum sub-arrays
Given an integer K and an array arr[] of N integers, the task is to find the number of ways to split the array into K equal sum sub-arrays of non-zero lengths. Examples: Input: arr[] = {0, 0, 0, 0}, K = 3 Output: 3 All possible ways are: {{0}, {0}, {0, 0}} {{0}, {0, 0}, {0}} {{0, 0}, {0}, {0}}Input: arr[] = {1, -1, 1, -1}, K = 2 Output: 1 Approach:
9 min read
Permute two arrays such that sum of every pair is greater or equal to K
Given two arrays of equal size n and an integer k. The task is to permute both arrays such that sum of their corresponding element is greater than or equal to k i.e a[i] + b[i] &gt;= k. The task is to print "Yes" if any such permutation exists, otherwise print "No". Examples : Input : a[] = {2, 1, 3}, b[] = { 7, 8, 9 }, k = 10. Output : YesPermutat
7 min read
Maximum subset sum such that no two elements in set have same digit in them
Given an array of N elements. Find the subset of elements which has maximum sum such that no two elements in the subset has common digit present in them.Examples: Input : array[] = {22, 132, 4, 45, 12, 223} Output : 268 Maximum Sum Subset will be = {45, 223} . All possible digits are present except 1. But to include 1 either 2 or both 2 and 3 have
12 min read
Place K-knights such that they do not attack each other
Given integers M, N and K, the task is to place K knights on an M*N chessboard such that they don't attack each other. The knights are expected to be placed on different squares on the board. A knight can move two squares vertically and one square horizontally or two squares horizontally and one square vertically. The knights attack each other if o
15+ min read
Find the number of sub arrays in the permutation of first N natural numbers such that their median is M
Given an array arr[] containing the permutation of first N natural numbers and an integer M ? N. The task is to find the number of sub-arrays such that the median of the sequence is M. The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence i
7 min read
Count of equal value pairs from given two Arrays such that a[i] equals b[j]
Given two arrays a[] and b[] of length N and M respectively, sorted in non-decreasing order. The task is to find the number of pairs (i, j) such that, a[i] equals b[j]. Examples: Input: a[] = {1, 1, 3, 3, 3, 5, 8, 8}, b[] = {1, 3, 3, 4, 5, 5, 5}Output: 11Explanation: Following are the 11 pairs with given condition The 11 pairs are {{1, 1}, {1, 1},
14 min read
Maximum sum possible for a sub-sequence such that no two elements appear at a distance &lt; K in the array
Given an array arr[] of n integers and an integer k, the task is to find the maximum sum possible for a sub-sequence such that no two elements of the sub-sequence appear at a distance ? k in the original array.Examples: Input: arr[] = {5, 3, 4, 11, 2}, k=1 Output: 16 All possible sub-sequences are {5, 4, 2}, {5, 11}, {5, 2}, {3, 11}, {3, 2}, {4, 2}
7 min read
Maximum sub-sequence sum such that indices of any two adjacent elements differs at least by 3
Given an array arr[] of integers, the task is to find the maximum sum of any sub-sequence in the array such that any two adjacent elements in the selected sequence have at least a difference of 3 in their indices in the given array. In other words, if you select arr[i] then the next element you can select is arr[i + 3], arr[i + 4], and so on... but
12 min read
Rearrange two given arrays such that sum of same indexed elements lies within given range
Given two arrays arr1[] and arr2[] consisting of N positive integers and an even integer K, the task is to check if the sum of the same indexed elements in the two arrays lie in the range [K/2, K] after rearranging the given arrays or not. If it is possible to obtain such an arrangement, then print "Yes". Otherwise, print "No". Examples: Input: arr
6 min read
Find the final X and Y when they are Altering under given condition
Given initial values of two positive integers X and Y, Find the final value of X and Y according to the below alterations: 1. If X=0 or Y=0, terminate the process. Else, go to step 2; 2. If X &gt;= 2*Y, then change the value of X to X - 2*Y, and repeat step 1. Else, go to step 3; 3. If Y &gt;= 2*X, then assign the value of Y to Y - 2*X, and repeat
15+ min read
Find the maximum element in the array other than A<sub>i</sub>
Given an array arr[] of size N. The task is to find maximum element among N - 1 elements other than arr[i] for each i from 1 to N.Examples: Input: arr[] = {2, 5, 6, 1, 3} Output: 6 6 5 6 6 Input: arr[] = {1, 2, 3} Output: 3 3 2 Approach: An efficient approach is to make prefix and suffix array of maximum elements and find maximum element among N -
6 min read
Count ways to partition a string such that both parts have equal distinct characters
Content has been removed on Author's request.
1 min read
Maximum absolute difference between sum of two contiguous sub-arrays
Given an array of integers, find two non-overlapping contiguous sub-arrays such that the absolute difference between the sum of two sub-arrays is maximum. Example: Input: [-2, -3, 4, -1, -2, 1, 5, -3] Output: 12 Two subarrays are [-2, -3] and [4, -1, -2, 1, 5] Input: [2, -1, -2, 1, -4, 2, 8] Output: 16 Two subarrays are [-1, -2, 1, -4] and [2, 8] E
15+ min read
Practice Tags :
three90RightbarBannerImg