
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 goal) {
int left = 0, count = 0, sum = 0;
for (int right = 0; right < numsSize; right++) {
sum += nums[right];
while (sum > goal) {
sum -= nums[left++];
}
count += right - left + 1;
}
return count;
}
int numSubarraysWithSum(int* nums, int numsSize, int goal) {
return atMost(nums, numsSize, goal) - atMost(nums, numsSize, goal - 1);
}
int main() {
int nums[] = {1,0,1,0,1};
int goal = 2;
int size = sizeof(nums) / sizeof(nums[0]);
int result = numSubarraysWithSum(nums, size, goal);
printf("%d\n", result); // Output: 4
return 0;
}| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(n) | In the best case, the algorithm must traverse the entire array once in the helper function to compute the subarrays with sum ≤ goal and again for goal - 1. Each element is processed in amortized constant time due to the sliding window, resulting in linear time. |
| Average Case | O(n) | On average, each element is added and removed from the sliding window at most once for both helper function calls, leading to a total linear time complexity. |
| Worst Case | O(n) | Even in the worst case, the two-pointer sliding window ensures that each element is visited at most twice — once by the right pointer and once by the left — for both calls to the helper function. Hence, time complexity remains O(n). |