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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read