Leetcode 1343: Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold

grid47
grid47
Exploring patterns and algorithms
Jun 25, 2024 5 min read

Given an array of integers arr and two integers k and threshold, return the number of subarrays of size k whose average is greater than or equal to the threshold.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of integers and two integers, k and threshold.
Example: arr = [1,3,5,7,9,10,12], k = 3, threshold = 7
Constraints:
• 1 <= arr.length <= 10^5
• 1 <= arr[i] <= 10^4
• 1 <= k <= arr.length
• 0 <= threshold <= 10^4
Output: Return the number of subarrays of size k whose average is greater than or equal to the threshold.
Example: For arr = [1,3,5,7,9,10,12], k = 3, threshold = 7, the output will be 4.
Constraints:
• The answer will be a non-negative integer.
Goal: Count how many subarrays of size k have an average greater than or equal to the threshold.
Steps:
• 1. Use a sliding window of size k to calculate the sum of each subarray.
• 2. Compute the average by dividing the sum of the subarray by k.
• 3. Count the number of subarrays whose average is greater than or equal to the threshold.
Goal: The solution should efficiently handle large input sizes.
Steps:
• The number of elements in the array is at most 10^5.
• The values in the array and threshold are bounded by 10^4.
Assumptions:
• The array will always have at least one subarray of the given size k.
• The array elements and threshold are non-negative integers.
Input: Example 1: arr = [1, 3, 5, 7, 9, 10, 12], k = 3, threshold = 7
Explanation: Subarrays of size 3 are checked, and their averages are compared to the threshold to count the valid subarrays.

Input: Example 2: arr = [2, 2, 2, 2, 5, 5, 5, 8], k = 3, threshold = 4
Explanation: The subarrays are evaluated based on their averages, and only those meeting or exceeding the threshold are counted.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus