Check if subarray with given product exists in an array
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:
#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
}
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");
}
}
}
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")
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");
}
}
}
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");
}
Output
YES
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.
#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
}
Output
YES
Time Complexity: O(n)
Auxiliary Space: O(1)