Related Articles

Related Articles

Smallest pair of indices with product of subarray co-prime with product of the subarray on the left or right
  • Last Updated : 07 Dec, 2020

Given an array arr[] of length N, the task is to find the smallest pair of indices (i, j) such that the product of elements in the subarray arr[i + 1, j – 1] is co-prime with either the product of the subarray arr[0, i] or that of the subarray arr[j, N]. If no such pair exists, the print “-1”.

Examples:

Input: arr[] = {2, 4, 1, 3, 7}
Output: (0, 2)
Explanation: The product of the subarray {arr[1], arr[1]} is 4. The product of right subarray = 1 * 3 * 7 = 21. Since 4 and 21 are co-primes, then print the range (0, 2) as the answer.

Input: arr[] = {21, 3, 11, 7, 18}
Output: (1, 3)
Explanation: The product of the subarray {arr[1], arr[2]} is 11. The product of right subarray is 7 * 18 = 126. Since 11 and 126 are co-primes, then print the range (1, 3) as the answer.

Naive Approach: The simplest approach is to iterate through every possible pair of indices (i, j) and for each pair, find the product of subarray arr[0, i] and arr[j, N] and check if it is co-prime with the product of the subarray arr[i + 1, j – 1] or not. If found to be true, then print those pair of indices. If no such pair exists, then print “-1”



Time Complexity: O((N3)*log(M)), where M is the product of all elements of the array.
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to use an auxiliary array to store the suffix product of the array elements. Follow the steps below to solve the problem:

  • Store the product of suffix elements in rightProd[], where rightProd[i] stores the product of elements from arr[i], arr[N – 1].
  • Find the product of all elements in the array as totalProd.
  • Traverse the given array using the variable i and perform the following operations:
    • Initialize a variable, say product.
    • Iterate through the array using variable j from the range [i, N – 1].
    • Update product by multiplying product by arr[j].
    • Initialize leftProduct as total/right_prod[i].
    • Check if the product is co-prime with one of the leftProduct or rightProduct or not. If found to be true, then print the pair (i – 1, j + 1) and break out of the loop.
  • After the above steps, if no such pair exists then print “-1”.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate GCD
// of two integers
int gcd(int a, int b)
{
    if (b == 0)
        return a;
 
    // Recursively calculate GCD
    return gcd(b, a % b);
}
 
// Function to find the lexicographically
// smallest pair of indices whose product
// is co-prime with the product of the
// subarrays on its left and right
void findPair(int A[], int N)
{
    // Stores the suffix product
    // of array elements
    int right_prod[N];
 
    // Set 0/1 if pair satisfies the
    // given condition or not
    int flag = 0;
 
    // Initialize array right_prod[]
    right_prod[N - 1] = A[N - 1];
 
    // Update the suffix product
    for (int i = N - 2; i >= 0; i--)
        right_prod[i] = right_prod[i + 1]
                        * A[i];
 
    // Stores product of all elements
    int total_prod = right_prod[0];
 
    // Stores the product of subarray
    // in between the pair of indices
    int product;
 
    // Iterate through every pair of
    // indices (i, j)
    for (int i = 1; i < N - 1; i++) {
 
        product = 1;
        for (int j = i; j < N - 1; j++) {
 
            // Store product of A[i, j]
            product *= A[j];
 
            // Check if product is co-prime
            // to product of either the left
            // or right subarrays
            if (gcd(product,
                    right_prod[j + 1])
                    == 1
                || gcd(product,
                       total_prod
                           / right_prod[i])
                       == 1) {
 
                flag = 1;
                cout << "(" << i - 1
                     << ", " << j + 1
                     << ")";
                break;
            }
        }
        if (flag == 1)
            break;
    }
 
    // If no such pair is found,
    // then print -1
    if (flag == 0)
        cout << -1;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 4, 1, 3, 7 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    findPair(arr, N);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to calculate GCD
// of two integers
static int gcd(int a, int b)
{
    if (b == 0)
        return a;
 
    // Recursively calculate GCD
    return gcd(b, a % b);
}
 
// Function to find the lexicographically
// smallest pair of indices whose product
// is co-prime with the product of the
// subarrays on its left and right
static void findPair(int A[], int N)
{
     
    // Stores the suffix product
    // of array elements
    int right_prod[] = new int[N];
 
    // Set 0/1 if pair satisfies the
    // given condition or not
    int flag = 0;
 
    // Initialize array right_prod[]
    right_prod[N - 1] = A[N - 1];
 
    // Update the suffix product
    for(int i = N - 2; i >= 0; i--)
        right_prod[i] = right_prod[i + 1] * A[i];
 
    // Stores product of all elements
    int total_prod = right_prod[0];
 
    // Stores the product of subarray
    // in between the pair of indices
    int product;
 
    // Iterate through every pair of
    // indices (i, j)
    for(int i = 1; i < N - 1; i++)
    {
        product = 1;
        for(int j = i; j < N - 1; j++)
        {
             
            // Store product of A[i, j]
            product *= A[j];
 
            // Check if product is co-prime
            // to product of either the left
            // or right subarrays
            if (gcd(product, right_prod[j + 1]) == 1 ||
                gcd(product, total_prod /
                    right_prod[i]) == 1)
            {
                flag = 1;
                System.out.println("(" + (i - 1) + ", " +
                                         (j + 1) + ")");
                break;
            }
        }
         
        if (flag == 1)
            break;
    }
 
    // If no such pair is found,
    // then print -1
    if (flag == 0)
        System.out.print(-1);
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 4, 1, 3, 7 };
    int N = arr.length;
 
    // Function Call
    findPair(arr, N);
}
}
 
// This code is contributed by chitranayal

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to calculate GCD
# of two integers
def gcd(a, b):
     
    if (b == 0):
        return a
 
    # Recursively calculate GCD
    return gcd(b, a % b)
 
# Function to find the lexicographically
# smallest pair of indices whose product
# is co-prime with the product of the
# subarrays on its left and right
def findPair(A, N):
     
    # Stores the suffix product
    # of array elements
    right_prod = [0] * N
 
    # Set 0/1 if pair satisfies the
    # given condition or not
    flag = 0
     
    # Initialize array right_prod
    right_prod[N - 1] = A[N - 1]
 
    # Update the suffix product
    for i in range(N - 2, 0, -1):
        right_prod[i] = right_prod[i + 1] * A[i]
 
    # Stores product of all elements
    total_prod = right_prod[0]
 
    # Stores the product of subarray
    # in between the pair of indices
    product = 1
 
    # Iterate through every pair of
    # indices (i, j)
    for i in range(1, N - 1):
        product = 1
        for j in range(i, N - 1):
             
            # Store product of A[i, j]
            product *= A[j]
             
            # Check if product is co-prime
            # to product of either the left
            # or right subarrays
            if (gcd(product, right_prod[j + 1]) == 1 or
                gcd(product, total_prod /
                             right_prod[i]) == 1):
                flag = 1
                print("(" , (i - 1) , ", " ,
                            (j + 1) ,")")
                break
 
        if (flag == 1):
            break
 
    # If no such pair is found,
    # then pr-1
    if (flag == 0):
        print(-1)
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 2, 4, 1, 3, 7 ]
    N = len(arr)
 
    # Function Call
    findPair(arr, N)
 
# This code is contributed by Amit Katiyar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
 
class GFG{
     
// Function to calculate GCD
// of two integers
static int gcd(int a, int b)
{
    if (b == 0)
        return a;
 
    // Recursively calculate GCD
    return gcd(b, a % b);
}
 
// Function to find the lexicographically
// smallest pair of indices whose product
// is co-prime with the product of the
// subarrays on its left and right
static void findPair(int []A, int N)
{
     
    // Stores the suffix product
    // of array elements
    int []right_prod = new int[N];
 
    // Set 0/1 if pair satisfies the
    // given condition or not
    int flag = 0;
 
    // Initialize array right_prod[]
    right_prod[N - 1] = A[N - 1];
 
    // Update the suffix product
    for(int i = N - 2; i >= 0; i--)
        right_prod[i] = right_prod[i + 1] * A[i];
 
    // Stores product of all elements
    int total_prod = right_prod[0];
 
    // Stores the product of subarray
    // in between the pair of indices
    int product;
 
    // Iterate through every pair of
    // indices (i, j)
    for(int i = 1; i < N - 1; i++)
    {
        product = 1;
         
        for(int j = i; j < N - 1; j++)
        {
             
            // Store product of A[i, j]
            product *= A[j];
             
            // Check if product is co-prime
            // to product of either the left
            // or right subarrays
            if (gcd(product, right_prod[j + 1]) == 1 ||
                gcd(product, total_prod /
                    right_prod[i]) == 1)
            {
                flag = 1;
                Console.WriteLine("(" + (i - 1) + ", " +
                                        (j + 1) + ")");
                break;
            }
        }
         
        if (flag == 1)
            break;
    }
 
    // If no such pair is found,
    // then print -1
    if (flag == 0)
        Console.Write(-1);
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 2, 4, 1, 3, 7 };
    int N = arr.Length;
     
    // Function Call
    findPair(arr, N);
}
}
 
// This code is contributed by Princi Singh

chevron_right


Output: 

(0, 2)

 

Time Complexity: O(N2*log(M)), where M is the product of all elements in the array
Auxiliary Space: 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 :