LeetCode 1343: Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold Solution
Master LeetCode problem 1343 (Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
Problem Explanation
Explanation:
To solve this problem, we can use a sliding window approach. We will maintain a window of size k and compute the sum of elements within this window. If the average of this window is greater than or equal to the threshold, we increment a counter. We slide the window by removing the leftmost element and adding the rightmost element iteratively to check for all possible sub-arrays.
Algorithm:
- Initialize variables
sumto store the sum of the current window andcountto store the count of sub-arrays meeting the criteria. - Iterate through the array from index 0 to n-1:
- Add the current element to
sum. - If the window size is greater than
k, subtract the leftmost element fromsum. - If the window size is equal to
k, check if the average of the window is greater than or equal tothreshold. If true, incrementcount.
- Add the current element to
- Return the final
count.
Time Complexity:
The time complexity of this algorithm is O(n), where n is the number of elements in the input array.
Space Complexity:
The space complexity is O(1) as we are using only a constant amount of extra space.
:
Solution Code
class Solution {
public int numOfSubarrays(int[] arr, int k, int threshold) {
int sum = 0, count = 0;
int n = arr.length;
for (int i = 0; i < n; i++) {
sum += arr[i];
if (i >= k) {
sum -= arr[i - k];
}
if (i >= k - 1) {
if (sum / k >= threshold) {
count++;
}
}
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1343 (Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold)?
This page provides optimized solutions for LeetCode problem 1343 (Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1343 (Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold)?
The time complexity for LeetCode 1343 (Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1343 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1343 in Java, C++, or Python.