Check if subarray with given product exists in an array
Last Updated :
21 Jul, 2024
Given an array of both positive and negative integers and a number K., The task is to check if any subarray with product K is present in the array or not.
Examples:
Input: arr[] = {-2, -1, 3, -4, 5}, K = 2
Output: YES
Input: arr[] = {3, -1, -1, -1, 5}, K = 3
Output: YES
Approach: The code provided seeks to determine if an array arr contains a contiguous subarray whose product of elements equals a particular number k. Using a brute-force method, the algorithm calculates the products of every conceivable subarray to see if any of them equal k.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to check if there exists a subarray with a product equal to k
bool hasSubarrayWithProduct(int* arr, int n, int k) {
// Iterate over all possible starting points of subarrays
for (int start = 0; start < n; ++start) {
int product = 1; // Initialize the product for the current subarray
// Iterate over all possible end points for subarrays starting at 'start'
for (int end = start; end < n; ++end) {
product *= arr[end]; // Update the product for the current subarray
// Check if the current subarray product is equal to k
if (product == k) {
return true; // Return true if such subarray is found
}
}
}
return false; // Return false if no subarray with product k is found
}
int main() {
int arr[] = {1, 2, -5, -4}; // Input array
int product = -10; // Target product value
int n = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements in the array
// Check if there is a subarray with the given product and print the result
if (hasSubarrayWithProduct(arr, n, product)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
return 0; // Exit the program
}
Java
public class Main {
// Function to check if there exists a subarray with a product equal to k
public static boolean hasSubarrayWithProduct(int[] arr, int k) {
int n = arr.length;
// Iterate over all possible starting points of subarrays
for (int start = 0; start < n; ++start) {
int product = 1; // Initialize the product for the current subarray
// Iterate over all possible end points for subarrays starting at 'start'
for (int end = start; end < n; ++end) {
product *= arr[end]; // Update the product for the current subarray
// Check if the current subarray product is equal to k
if (product == k) {
return true; // Return true if such subarray is found
}
}
}
return false; // Return false if no subarray with product k is found
}
public static void main(String[] args) {
int[] arr = {1, 2, -5, -4}; // Input array
int product = -10; // Target product value
// Check if there is a subarray with the given product and print the result
if (hasSubarrayWithProduct(arr, product)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
Python
def has_subarray_with_product(arr, k):
n = len(arr)
# Iterate over all possible starting points of subarrays
for start in range(n):
product = 1 # Initialize the product for the current subarray
# Iterate over all possible end points for subarrays starting at 'start'
for end in range(start, n):
product *= arr[end] # Update the product for the current subarray
# Check if the current subarray product is equal to k
if product == k:
return True # Return true if such subarray is found
return False # Return false if no subarray with product k is found
# Input array
arr = [1, 2, -5, -4]
# Target product value
product = -10
# Check if there is a subarray with the given product and print the result
if has_subarray_with_product(arr, product):
print("YES")
else:
print("NO")
C#
using System;
public class Program {
// Function to check if there exists a subarray with a product equal to k
public static bool HasSubarrayWithProduct(int[] arr, int k) {
int n = arr.Length;
// Iterate over all possible starting points of subarrays
for (int start = 0; start < n; ++start) {
int product = 1; // Initialize the product for the current subarray
// Iterate over all possible end points for subarrays starting at 'start'
for (int end = start; end < n; ++end) {
product *= arr[end]; // Update the product for the current subarray
// Check if the current subarray product is equal to k
if (product == k) {
return true; // Return true if such subarray is found
}
}
}
return false; // Return false if no subarray with product k is found
}
public static void Main() {
int[] arr = {1, 2, -5, -4}; // Input array
int product = -10; // Target product value
// Check if there is a subarray with the given product and print the result
if (HasSubarrayWithProduct(arr, product)) {
Console.WriteLine("YES");
} else {
Console.WriteLine("NO");
}
}
}
Javascript
function hasSubarrayWithProduct(arr, k) {
const n = arr.length;
// Iterate over all possible starting points of subarrays
for (let start = 0; start < n; ++start) {
let product = 1; // Initialize the product for the current subarray
// Iterate over all possible end points for subarrays starting at 'start'
for (let end = start; end < n; ++end) {
product *= arr[end]; // Update the product for the current subarray
// Check if the current subarray product is equal to k
if (product === k) {
return true; // Return true if such subarray is found
}
}
}
return false; // Return false if no subarray with product k is found
}
// Input array
const arr = [1, 2, -5, -4];
// Target product value
const product = -10;
// Check if there is a subarray with the given product and print the result
if (hasSubarrayWithProduct(arr, product)) {
console.log("YES");
} else {
console.log("NO");
}
Time Complexity: O(n2)
Auxiliary Space: O(1)
Efficient Approach:
we use the two-pointer technique (sliding window), but adapt it to handle products.
Here is a way to approach it:
- Initialize two pointers, start and end.
- Use a variable product to keep track of the product of elements in the current window.
- Expand the window by moving end to the right and update the product.
- If the product exceeds k, move start to the right until the product is less than or equal to k.
- Check if the product matches k.
Below is the implementation of above idea.
C++
#include <iostream>
using namespace std;
// Function to check if there exists a subarray with a product equal to k
bool hasSubarrayWithProduct(int* arr, int n, int k) {
int start = 0;
int product = 1;
for (int end = 0; end < n; ++end) {
product *= arr[end];
// If the product becomes zero and k is not zero, move the start to skip zero
while (start <= end && product == 0 && k != 0) {
start++;
product = 1;
for (int i = start; i <= end; ++i) {
product *= arr[i];
}
}
// If product exceeds k, move the start pointer to reduce the product
while (start <= end && product != 0 && abs(product) > abs(k)) {
product /= arr[start];
start++;
}
// Check if the current product is equal to k
if (product == k) {
return true;
}
}
return false; // If no subarray with product k is found, return false
}
int main() {
int arr[] = {1, 2, -5, -4}; // Input array
int product = -10; // Target product value
int n = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements in the array
// Check if there is a subarray with the given product and print the result
if (hasSubarrayWithProduct(arr, n, product)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
return 0; // Exit the program
}
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Check if a pair with given product exists in a Matrix Given an NxM matrix and a product K. The task is to check if a pair with the given product exists in the matrix or not. Examples: Input: mat[N][M] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; K = 42 Output: YES Input: mat[N][M] = {{1, 2, 3, 4}, {5, 6, 7, 8}}; K = 150 Output: NO
6 min read
Check if a subarray exists with sum greater than the given Array Given an array of integers arr, the task is to check if there is a subarray (except the given array) such that the sum of its elements is greater than or equal to the sum of elements of the given array. If no such subarray is possible, print No, else print Yes.Examples: Input: arr = {5, 6, 7, 8} Out
7 min read
Check if product of every pair exists in an array Given a array of n integers, we need to check whether for every pair of numbers a[i] & a[j] there exists a a[k] such that a[k] = a[i]*a[j] where k can be equal to i or j too. Examples : Input : arr[] = {0. 1} Output : Yes Here a[0]*a[1] is equal to a[0] Input : arr[] = {5, 6} Output : No An arra
7 min read
Check if a Subarray exists with sums as a multiple of k Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer. Note: The length of the array won't exceed 10,000. You may assume th
8 min read
Check if there exists any subarray with the given conditions Given two integers N and X. Then the task is to return YES or NO by checking whether there exists a subarray in any permutation of length N such that it contains a subarray, where A*B is equal to the X. Here A and B denote the number of elements in sub-array and the first element of sorted subarray
5 min read
Check if permutation of N exists with product of atleast 1 subarray's size and min as K Given two integers N and K, the task is to check if it is possible to form a permutation of N integers such that it contains atleast 1 subarray such that the product of length of that subarray with minimum element present in it is K. A permutation of size N have all the integers from 1 to N present
7 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
Find an element which divides the array in two subarrays with equal product Given, an array of size N. Find an element which divides the array into two sub-arrays with equal product. Print -1 if no such partition is not possible. Examples : Input : 1 4 2 1 4 Output : 2 If 2 is the partition, subarrays are : {1, 4} and {1, 4} Input : 2, 3, 4, 1, 4, 6 Output : 1 If 1 is the p
12 min read
Check if a non-contiguous subsequence same as the given subarray exists or not Given an array arr[] consisting of N integers and two integer values L and R, indicating the starting and ending indices of a subarray, the task is to check if there exists a non-contiguous subsequence which is same as the given subarray or not. If found to be true, print "Yes". Otherwise, print "No
7 min read