Smallest pair of indices with product of subarray co-prime with product of the subarray on the left or right
Last Updated :
02 Aug, 2022
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++
// 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;
}
C
// C program for the above approach
#include <stdio.h>
// 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;
printf("(%d, %d)", i - 1, j + 1);
break;
}
}
if (flag == 1)
break;
}
// If no such pair is found, then print -1
if (flag == 0)
printf("-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;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// 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
Python3
# 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 print -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
C#
// 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
JavaScript
<script>
// Javascript program for the above approach
// Function to calculate GCD
// of two integers
function 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
function findPair(A, N)
{
// Stores the suffix product
// of array elements
let right_prod = [];
// Set 0/1 if pair satisfies the
// given condition or not
let flag = 0;
// Initialize array right_prod[]
right_prod[N - 1] = A[N - 1];
// Update the suffix product
for(let i = N - 2; i >= 0; i--)
right_prod[i] = right_prod[i + 1] * A[i];
// Stores product of all elements
let total_prod = right_prod[0];
// Stores the product of subarray
// in between the pair of indices
let product;
// Iterate through every pair of
// indices (i, j)
for(let i = 1; i < N - 1; i++)
{
product = 1;
for(let 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;
document.write("(" + (i - 1) + ", " +
(j + 1) + ")");
break;
}
}
if (flag == 1)
break;
}
// If no such pair is found,
// then print -1
if (flag == 0)
document.write(-1);
}
// Driver code
let arr = [ 2, 4, 1, 3, 7 ];
let N = arr.length;
// Function Call
findPair(arr, N);
// This code is contributed by code_hunt
</script>
Time Complexity: O(N2*log(M)), where M is the product of all elements in the array
Auxiliary Space: O(N)
Similar Reads
Count pairs with product of indices equal to the product of elements present at those indices
Given an array arr[] consisting of N integers, the task is to count the number of distinct pairs of array elements having the product of indices equals the product of elements at that indices. The pairs (x, y) and (y, x) are considered as the same pairs. Examples: Input: arr[] = {1, 0, 3, 2, 6}Outpu
5 min read
Minimum index to split array into subarrays with co-prime products
Given an array arr[] consisting of N integers, the task is to find the maximum index K such that the product of subarrays {arr[0], arr[K]} and {arr[K + 1], arr[N - 1]} are co-prime. If no such index exists, then print "-1". Examples: Input: arr[] = {2, 3, 4, 5}Output: 2Explanation:Smallest index for
15 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4,
12 min read
Count of Pairs such that modulo of product of one with their XOR and X is 1
Given two arrays A[] and B[] of length N and M respectively and a prime number X, the task is to find the number of ordered pair of indices (i, j) that satisfies the following conditions: 1 ? i ? N and 1 ? j ? M( Ai ? Bj ) < X(( Ai ? ( Ai ? Bj )) ? 1) % X = 0 Note: ? is XOR operator. Examples: In
8 min read
Length of the Smallest Subarray that must be removed in order to Maximise the GCD
Given an array arr[] of N elements, the task is to find the length of the smallest subarray such that when this subarray is removed from the array, the GCD of the resultant array is maximum. Note: The resulting array should be non-empty.Examples: Input: N = 4, arr[] = {3, 6, 1, 2} Output: 2 Explanat
7 min read
Smallest index that splits an array into two subarrays with equal product
Given an array(1-based indexing) arr[] consisting of N non zero integers, the task is to find the leftmost index i such that the product of all the elements of the subarrays arr[1, i] and arr[i + 1, N] is the same. Examples: Input: arr[] = {1, 2, 3, 3, 2, 1}Output: 3Explanation: Index 3 generates su
10 min read
Minimize the Sum of all the subarrays made up of the products of same-indexed elements
Given two arrays arr[] and arr2[] of length N, the task is to find the minimum sum of all the subarrays made up of the products of the same indexed elements of both the arrays after rearranging the second array. Note: Since the answer can be very large, print the answer modulo 109 + 7. Examples: Inp
7 min read
Split array into three continuous subarrays with negative, 0 and positive product respectively
Given an array arr[] size N such that each array element is either -1, 0, or 1, the task is to check if is it possible to split the array into 3 contiguous subarrays such that the product of the first, second and third subarrays is negative, 0 and positive respectively. Examples: Input: arr[] = {-1,
10 min read
Smallest subarray whose product leaves remainder K when divided by size of the array
Given an array arr[] of N integers and an integer K, the task is to find the length of the smallest subarray whose product when divided by N gives remainder K. If no such subarray exists the print "-1". Examples: Input: N = 3, arr = {2, 2, 6}, K = 1 Output: 2 Explanation: All possible subarrays are:
6 min read
Smallest subarray having an element with frequency greater than that of other elements
Given an array arr of positive integers, the task is to find the smallest length subarray of length more than 1 having an element occurring more times than any other element. Examples: Input: arr[] = {2, 3, 2, 4, 5} Output: 2 3 2 Explanation: The subarray {2, 3, 2} has an element 2 which occurs more
15+ min read