Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if subarray with given product exists in an array in Python
When working with arrays containing positive and negative numbers, we sometimes need to check if there's a subarray whose product equals a target value. A subarray is a contiguous sequence of elements within an array.
For example, given nums = [-2, -1, 1, 3, 5, 8] and k = 6, we need to find if any subarray has a product of 6. The subarray [-2, -1, 3] gives us (-2) × (-1) × 3 = 6, so the answer is True.
Algorithm Approach
We use Kadane's algorithm modified for products instead of sums. The key insight is tracking both maximum and minimum products at each position, since negative numbers can turn a small product into a large one.
The algorithm follows these steps ?
- Initialize minimum and maximum product trackers with the first element
- For each subsequent element:
- If the current number is negative, swap minimum and maximum (since multiplying by negative flips the relationship)
- Update maximum as the larger of current element or maximum × current element
- Update minimum as the smaller of current element or minimum × current element
- Check if either minimum or maximum equals our target k
- Return
Trueif target found,Falseotherwise
Implementation
def has_subarray_with_product(nums, k):
if not nums:
return False
minimum = nums[0]
maximum = nums[0]
# Check if first element itself is the target
if minimum == k:
return True
for i in range(1, len(nums)):
# If current number is negative, swap min and max
if nums[i] < 0:
maximum, minimum = minimum, maximum
# Update maximum and minimum products ending at current position
maximum = max(nums[i], maximum * nums[i])
minimum = min(nums[i], minimum * nums[i])
# Check if we found the target product
if minimum == k or maximum == k:
return True
return False
# Test with the given example
nums = [-2, -1, 1, 3, 5, 8]
k = 6
result = has_subarray_with_product(nums, k)
print(f"Array: {nums}")
print(f"Target product: {k}")
print(f"Subarray with product {k} exists: {result}")
Array: [-2, -1, 1, 3, 5, 8] Target product: 6 Subarray with product 6 exists: True
How It Works
Let's trace through the example step by step ?
def trace_algorithm(nums, k):
print(f"Finding subarray with product {k} in {nums}")
print("-" * 50)
minimum = maximum = nums[0]
print(f"Initial: min={minimum}, max={maximum}")
if minimum == k:
return True
for i in range(1, len(nums)):
print(f"\nProcessing nums[{i}] = {nums[i]}")
if nums[i] < 0:
maximum, minimum = minimum, maximum
print(f" Negative number: swapped min={minimum}, max={maximum}")
maximum = max(nums[i], maximum * nums[i])
minimum = min(nums[i], minimum * nums[i])
print(f" Updated: min={minimum}, max={maximum}")
if minimum == k or maximum == k:
print(f" ? Found target product {k}!")
return True
return False
# Trace the example
nums = [-2, -1, 1, 3, 5, 8]
k = 6
trace_algorithm(nums, k)
Finding subarray with product 6 in [-2, -1, 1, 3, 5, 8] -------------------------------------------------- Initial: min=-2, max=-2 Processing nums[1] = -1 Negative number: swapped min=-2, max=-2 Updated: min=-2, max=2 Processing nums[2] = 1 Updated: min=-2, max=2 Processing nums[3] = 3 Updated: min=-6, max=6 ? Found target product 6!
Additional Examples
# Test with different cases
test_cases = [
([2, 3, -2, 4], 6), # Product of [2, 3]
([1, 2, 3, 4], 24), # Product of entire array
([-1, -2, -3], -6), # Product of [-1, -2, -3]
([1, 2, 3], 10), # No subarray with product 10
]
for nums, k in test_cases:
result = has_subarray_with_product(nums, k)
print(f"nums={nums}, k={k} ? {result}")
nums=[2, 3, -2, 4], k=6 ? True nums=[1, 2, 3, 4], k=24 ? True nums=[-1, -2, -3], k=-6 ? True nums=[1, 2, 3], k=10 ? False
Time and Space Complexity
- Time Complexity: O(n) - single pass through the array
- Space Complexity: O(1) - only using a few variables
Conclusion
This algorithm efficiently finds subarrays with a target product by tracking minimum and maximum products at each position. The key insight is swapping min/max when encountering negative numbers, since they flip the magnitude relationships in products.
