Similar Problems

Similar Problems not available

Subarray With Elements Greater Than Varying Threshold - Leetcode Solution

Companies:

LeetCode:  Subarray With Elements Greater Than Varying Threshold Leetcode Solution

Difficulty: Hard

Topics: union-find stack array  

Problem Statement: Given an array of integers and a variable threshold, find the number of subarrays in which all the elements are greater than the threshold.

Example: Input: nums = [3,4,1,2] threshold = 2

Output: 6

Explanation: There are 6 subarrays that have all elements greater than 2: [3,4], [4], [3,4,1], [3,4,1,2], [4,1,2], [1,2].

Solution: This problem can be solved using a sliding window technique. We can start by initializing two pointers, left and right, both pointing to the first element of the array.

We then move the right pointer to the right until the sum of elements between left and right is less than or equal to the threshold. At this point, we can add the number of subarrays with all elements greater than the threshold, which is (right - left).

We then move the left pointer to the right until the sum of elements between left and right is greater than the threshold. We subtract (left - 1) from the total count of subarrays to get all subarrays with elements greater than the threshold that end at the current index.

We repeat this process until the right pointer has reached the end of the array.

Code: Here's the implementation of the above approach in Python:

def numOfSubarrays(nums, threshold): left, right = 0, 0 total_sum, count = 0, 0 while right < len(nums): total_sum += nums[right] while total_sum > (threshold * (right - left + 1)): total_sum -= nums[left] left += 1 count += (right - left + 1) right += 1 return count

Time Complexity: The time complexity of this solution is O(n) since we iterate the array only once.

Space Complexity: The space complexity of this solution is O(1) since we use only a constant amount of extra space.

Subarray With Elements Greater Than Varying Threshold Solution Code

1