This post is completed by 1 user
|
Add to List |
262. Count and print all Subarrays with product less than K in O(n)
Objective: Given an array of positive integers and integer ‘K’. Write an algorithm to count all the possible sub arrays where product of all the elements in the sub array is less than k.
Example:
Int [] nums = {10, 4, 2, 6}; K = 100 Output: 9 Sub arrays: [10], [10 4], [10, 4, 2], [4], [4, 2], [4, 2, 6], [2], [2, 6], [6]
Approach:
- Calculate all the possible subarrays as discussed here (Print all subarrays of a given array).
- Find out which array has elements has product less than k.
Time complexity: O(n^3)
Output:
10 10 4 10 4 2 4 4 2 4 2 6 2 2 6 6 Sub arrays has sum less than k=100 are: 9
Use Sliding window approach: O(n)
- We recommend to read about "Sliding Window Algorithm" before continue.
- Every time any new element is added to the sub array then there are possibilities either the product of the elements will be less than k or greater than equal to k.
- Start with first element and keep adding elements till the product of elements are less than K.
- Once the product is greater than k than, start dividing the product with elements of sub-array, from the start index of that particular sub-array.
- Repeat the above 2 steps till we navigate the entire array.
- Now let’s discuss how will count the sub arrays.
- If product of all the elements in array is less than K that means all the subarrays will also have product less than K.
- Let’s say we have 3 elements in the subarray where product is less than k and after adding the 4th element in subarray, product is still less then we will have 3 more subarrays(same as the previous size of array) in our result see the explanation below
- [1, 2, 3], K = 40. Add another element 4 so new window with product less than 40 is [1, 2, 3, 4]. So all the new subarrays with product less than 40 will be - {1, 2, 3, 4}, {2, 3, 4}, {3, 4}, {4}.
Let’s take one Example, have 2 pointers start and end to track the sliding window
int [] nums = {10, 4, 2, 6}; K = 100 count = 0 (will be our final result) __________________________________________________________ start = 0, end = 1: [10], product = 10 <100, count = count + end-start = 0 + 1 = 1 __________________________________________________________ start = 0, end = 2: [10, 4], product = 10*4 = 40 <100, count = count + end-start = 1 + 2 = 3 (new ones are {10, 4}, {4}) ___________________________________________________________ start = 0, end = 3: [10, 4, 2], product = 40*2 = 80 <100, count = count + end-start = 3 + 3 = 6 (new ones are {10, 4, 2}, {4, 2}, {2}) ___________________________________________________________ start = 0, end = 4: [10, 4, 2, 6], product = 80*6 = 480 > 100 => remove 10 and product = 480/10 = 48, start = 1 ___________________________________________________________ start = 1, end = 4: [4, 2, 6], product = 48<100, count = count + end-start =6 + 4 – 1 = 9
Output:
No of sub arrays has sum less than k=100 are: 9