
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
int atMost(int* nums, int numsSize, int k) {
int left = 0, right = 0, count = 0, oddCount = 0;
for (right = 0; right < numsSize; right++) {
if (nums[right] % 2 != 0) oddCount++;
while (oddCount > k) {
if (nums[left] % 2 != 0) oddCount--;
left++;
}
count += right - left + 1;
}
return count;
}
int numberOfNiceSubarrays(int* nums, int numsSize, int k) {
return atMost(nums, numsSize, k) - atMost(nums, numsSize, k - 1);
}
int main() {
int nums[] = {1,1,2,1,1};
int k = 3;
int size = sizeof(nums) / sizeof(nums[0]);
int result = numberOfNiceSubarrays(nums, size, k);
printf("Number of nice subarrays: %d\n", result); // Output: 2
return 0;
}| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(n) | The algorithm processes each element of the array once using a sliding window. Even in the best case, it must scan all elements to maintain the window and count valid subarrays. |
| Average Case | O(n) | In the average case, the algorithm maintains a window using two pointers and counts valid subarrays by scanning each element exactly once. Thus, the time complexity is linear with respect to the size of the input array. |
| Worst Case | O(n) | Even in the worst case (e.g., every element is odd), the window still expands and contracts by moving each pointer at most n times. Hence, the total number of operations is proportional to n. |