
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>
#include <string.h>
int countSubstrings(char* s) {
int count[3] = {0, 0, 0};
int left = 0, total = 0, n = strlen(s);
int unique = 0;
for (int right = 0; right < n; right++) {
count[s[right] - 'a']++;
if (count[s[right] - 'a'] == 1) unique++;
while (unique == 3) {
total += n - right;
count[s[left] - 'a']--;
if (count[s[left] - 'a'] == 0) unique--;
left++;
}
}
return total;
}
int main() {
char s[] = "abcabc";
int result = countSubstrings(s);
printf("%d\n", result); // 10
return 0;
}| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(n) | In the best case, the sliding window still needs to examine each character at least once with the right pointer and may increment the left pointer as well. Since each character is processed at most twice (once by right, once by left), the time complexity remains linear. |
| Average Case | O(n) | Both pointers (left and right) traverse the string once. For every character added by the right pointer, the left pointer may be moved forward to maintain the window. So, the number of total operations is proportional to the length of the string. |
| Worst Case | O(n) | Even in the worst case, each character is visited a constant number of times (once by the right pointer and at most once by the left), resulting in O(n) total time complexity. |