Skip to content
Related Articles

Related Articles

Count of subarrays whose product is equal to difference of two different numbers
  • Last Updated : 03 Dec, 2020
GeeksforGeeks - Summer Carnival Banner

Given a non-negative array a, the task is to find the count of subarrays whose product of elements can be represented as the difference of two different numbers. 
Examples:

Input: arr = {2, 5, 6} 
Output:
Explanation: 
Product of elements of subarray {5} can be represented as 32 – 22 is equal to 5 
Product of elements of subarray {2, 5, 6} can be represented as 82 – 22 is equal to 60 
Hence, there are two subarrays which can be represented.
Input: arr = {1, 2, 3} 
Output:
 

Naive Approach: 
The naive solution to the above-mentioned question is to compute all the possible subarray from the given array. Then we have to compute the product of each subarray. But this method is not so efficient and is time-consuming.
Efficient approach: 
A common observation of the efficient approach to the above problem is that a number which is divisible by 2 and not by 4 gives remainder 2 when divided by 4. Hence, all the numbers can be represented as a product of two different numbers except the numbers which give the remainder 2 when done modulo with 4. Now to solve the problem we take a pair of vector and store elements along with the position of the next element which is divisible by 2. After that traverse the array and look for the necessary conditions given below:

  • If an odd number is encountered then this number forms all subarrays unless a number occurs which is divisible by 2. Now, this number also can form subarrays when another number occurs which is divisible by 2. Both of these are stored in pair type vector.
  • If a number is encountered which is divisible by 4 then this number can form all subarrays.
  • If a number occurs which is only divisible by 2 then this number cannot form subarray unless another number occurs which is a multiple of 2.

Below is the implementation of the above approach:
 

C++




// C++ program to Find count of
// Subarrays whose product can be
// represented as the difference between
// two different numbers
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print number of subarrays
void numberOfSubarrays(int arr[], int n)
{
 
    vector<pair<int, int> > next(n);
    vector<pair<int, int> > next_to_next(n);
 
    int f = -1;
    int s = -1;
 
    for (int i = n - 1; i >= 0; i--) {
        next[i].first = arr[i];
 
        next_to_next[i].first = arr[i];
 
        // check if number is divisible by 2
        if (arr[i] % 2 == 0) {
            s = f;
            f = i;
        }
 
        // Store the position
        // of the next element
        next[i].second = f;
 
        // Store the position of
        // next to next element
        // which is multiple of 2
        next_to_next[i].second = s;
    }
 
    int total = 0;
 
    for (int i = 0; i < n; i++) {
        int calculate;
 
        // Check if the element is divisible
        // is divisible by 4
        if (next[i].first % 4 == 0) {
            calculate = n - i;
 
            total += calculate;
        }
 
        // Check if current element
        // is an odd number
        else if (next[i].first & 1 == 1) {
 
            if (next[i].second == -1) {
                calculate = n - i;
 
                total += calculate;
            }
 
            else {
 
                // check if after the current element
                // only 1 element exist which is a
                // multiple of only 2 but not 4
                if (next_to_next[i].second == -1
                 && next[next[i].second].first % 4 != 0)
 
                {
                    calculate = next[i].second - i;
                    total += calculate;
                }
 
                // Check if after the current element an element exist
                // which is multiple of only 2 and not 4 and after that
                // an element also exist which is multiple of 2
                else if (next_to_next[i].second != -1
                         && next[next[i].second].first % 4 != 0) {
                    calculate = n - i;
                    total += calculate;
                    total -= next_to_next[i].second - next[i].second;
                }
 
                // All subarrays can be formed by current element
                else {
                    calculate = n - i;
                    total = total + calculate;
                }
            }
        }
 
        // Condition for an even number
        else {
 
            // Check if next element does not
            // exist which is multiple of 2
            if (next_to_next[i].second == -1)
                total = total;
 
            // Check if next element exist
            // which is multiple of 2
            else {
                calculate = n - i;
                total += calculate;
                total = total - next_to_next[i].second + i;
            }
        }
    }
 
    // Print the output
    cout << total << "\n";
}
 
// Driver Code
int main()
{
    // array initialisation
    int arr[] = { 2, 5, 6 };
 
    int size = sizeof(arr) / sizeof(arr[0]);
 
    numberOfSubarrays(arr, size);
 
    return 0;
}

Java




// Java program to find count of
// subarrays whose product can be
// represented as the difference
// between two different numbers
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to print number of subarrays
static void numberOfSubarrays(int arr[], int n)
{
    int[][] next = new int[n][2];
    int[][] next_to_next = new int[n][2];
 
    int f = -1;
    int s = -1;
 
    for(int i = n - 1; i >= 0; i--)
    {
        next[i][0] = arr[i];
 
        next_to_next[i][0] = arr[i];
 
        // Check if number is divisible by 2
        if (arr[i] % 2 == 0)
        {
            s = f;
            f = i;
        }
 
        // Store the position
        // of the next element
        next[i][1] = f;
 
        // Store the position of
        // next to next element
        // which is multiple of 2
        next_to_next[i][1] = s;
    }
 
    int total = 0;
 
    for(int i = 0; i < n; i++)
    {
        int calculate;
 
        // Check if the element is divisible
        // is divisible by 4
        if (next[i][0] % 4 == 0)
        {
            calculate = n - i;
            total += calculate;
        }
 
        // Check if current element
        // is an odd number
        else if ((next[i][0] & 1) == 1)
        {
            if (next[i][1] == -1)
            {
                calculate = n - i;
                total += calculate;
            }
 
            else
            {
 
                // Check if after the current element
                // only 1 element exist which is a
                // multiple of only 2 but not 4
                if (next_to_next[i][1] == -1 &&
                    next[next[i][1]][0] % 4 != 0)
                {
                    calculate = next[i][1] - i;
                    total += calculate;
                }
 
                // Check if after the current element
                // an element exist which is multiple
                // of only 2 and not 4 and after that
                // an element also exist which is
                // multiple of 2
                else if (next_to_next[i][1] != -1 &&
                         next[next[i][1]][0] % 4 != 0)
                {
                    calculate = n - i;
                    total += calculate;
                    total -= next_to_next[i][1] -
                                     next[i][1];
                }
 
                // All subarrays can be formed
                // by current element
                else
                {
                    calculate = n - i;
                    total = total + calculate;
                }
            }
        }
 
        // Condition for an even number
        else
        {
             
            // Check if next element does not
            // exist which is multiple of 2
            if (next_to_next[i][1] == -1)
                total = total;
 
            // Check if next element exist
            // which is multiple of 2
            else
            {
                calculate = n - i;
                total += calculate;
                total = total - next_to_next[i][1] + i;
            }
        }
    }
 
    // Print the output
    System.out.println(total);
}
 
// Driver Code
public static void main(String args[])
{
     
    // Array initialisation
    int arr[] = { 2, 5, 6 };
 
    int size = arr.length;
 
    numberOfSubarrays(arr, size);
}
}
 
// This code is contributed by offbeat

Python3




# Python program to find count of
# subarrays whose product can be
# represented as the difference
# between two different numbers
 
# Function to print number of subarrays
def numberOfSubarrays(arr, n):
 
    Next = [[0 for i in range(2)] for j in range(n)]
    next_to_next = [[0 for i in range(2)] for j in range(n)]
 
    f = -1
    s = -1
 
    for i in range(n - 1, -1, -1) :
     
        Next[i][0] = arr[i]
 
        next_to_next[i][0] = arr[i]
 
        # Check if number is divisible by 2
        if (arr[i] % 2 == 0) :
     
            s = f
            f = i
 
        # Store the position
        # of the next element
        Next[i][1] = f
 
        # Store the position of
        # next to next element
        # which is multiple of 2
        next_to_next[i][1] = s
 
    total = 0
 
    for i in range(n) :
 
        calculate = 0
 
        # Check if the element is divisible
        # is divisible by 4
        if (Next[i][0] % 4 == 0) :
         
            calculate = n - i
            total += calculate
 
        # Check if current element
        # is an odd number
        elif ((Next[i][0] & 1) == 1) :
         
            if (Next[i][1] == -1) :
              
                calculate = n - i
                total += calculate
 
            else :
             
                # Check if after the current element
                # only 1 element exist which is a
                # multiple of only 2 but not 4
                if (next_to_next[i][1] == -1 and Next[Next[i][1]][0] % 4 != 0) :
             
                    calculate = Next[i][1] - i
                    total += calculate
 
                # Check if after the current element
                # an element exist which is multiple
                # of only 2 and not 4 and after that
                # an element also exist which is
                # multiple of 2
                elif (next_to_next[i][1] != -1 and Next[Next[i][1]][0] % 4 != 0) :
                 
                    calculate = n - i
                    total += calculate
                    total -= next_to_next[i][1] - Next[i][1]
 
                # All subarrays can be formed
                # by current element
                else :
                 
                    calculate = n - i
                    total = total + calculate
 
        # Condition for an even number
        else :
             
            # Check if next element does not
            # exist which is multiple of 2
            if (next_to_next[i][1] == -1) :
                total = total
 
            # Check if next element exist
            # which is multiple of 2
            else :
 
                calculate = n - i
                total += calculate
                total = total - next_to_next[i][1] + i
 
    # Print the output
    print(total)
 
# Array initialisation
arr = [ 2, 5, 6 ]
 
size = len(arr)
 
numberOfSubarrays(arr, size)
 
# This code is contributed by divyesh072019

C#




// C# program to find count of 
// subarrays whose product can be 
// represented as the difference 
// between two different numbers 
using System;
class GFG{
     
// Function to print number
// of subarrays 
static void numberOfSubarrays(int[] arr,
                              int n) 
  int[,] next = new int[n, 2]; 
  int[,] next_to_next = new int[n, 2];
  int f = -1; 
  int s = -1; 
 
  for(int i = n - 1; i >= 0; i--)
  
    next[i, 0] = arr[i]; 
    next_to_next[i, 0] = arr[i]; 
 
    // Check if number is
    // divisible by 2 
    if (arr[i] % 2 == 0)
    
      s = f; 
      f = i; 
    
 
    // Store the position 
    // of the next element 
    next[i, 1] = f; 
 
    // Store the position of 
    // next to next element 
    // which is multiple of 2 
    next_to_next[i, 1] = s; 
  
 
  int total = 0; 
 
  for(int i = 0; i < n; i++)
  
    int calculate; 
 
    // Check if the element is
    // divisible is divisible by 4 
    if (next[i, 0] % 4 == 0) 
    
      calculate = n - i; 
      total += calculate; 
    
 
    // Check if current element 
    // is an odd number 
    else if ((next[i, 0] & 1) == 1)
    
      if (next[i, 1] == -1) 
      
        calculate = n - i; 
        total += calculate; 
      
      else
      {
        // Check if after the current element 
        // only 1 element exist which is a 
        // multiple of only 2 but not 4 
        if (next_to_next[i, 1] == -1 && 
            next[next[i, 1], 0] % 4 != 0) 
        
          calculate = next[i, 1] - i; 
          total += calculate; 
        
 
        // Check if after the current element
        // an element exist which is multiple
        // of only 2 and not 4 and after that 
        // an element also exist which is 
        // multiple of 2 
        else if (next_to_next[i, 1] != -1 &&
                 next[next[i, 1], 0] % 4 != 0)
        
          calculate = n - i; 
          total += calculate; 
          total -= next_to_next[i, 1] - 
            next[i, 1]; 
        
 
        // All subarrays can be formed
        // by current element 
        else
        
          calculate = n - i; 
          total = total + calculate; 
        
      
    
 
    // Condition for an even number 
    else
    
      // Check if next element does not 
      // exist which is multiple of 2 
      if (next_to_next[i, 1] == -1)
      {
        //total = total;
      }
       
      // Check if next element exist 
      // which is multiple of 2 
      else
      
        calculate = n - i; 
        total += calculate; 
        total = total -
                next_to_next[i, 1] + i; 
      
    
  
 
  // Print the output 
  Console.WriteLine(total); 
 
static void Main()
{
 
  // Array initialisation 
  int[] arr = {2, 5, 6}; 
 
  int size = arr.Length; 
 
  numberOfSubarrays(arr, size); 
}
}
 
// This code is contributed by divyeshrabadiya07

 
 



Output: 
2

 

 

Time complexity: O(N)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :