Example
Input
s = 'pqpqs', k = 2
Output
12
There are 12 substrings of 'pqpqs' that contain at most 2 distinct characters.
Full lesson preview
Count how many substrings of a string contain at most K distinct characters using a sliding-window technique that counts valid end positions.
Problem statement
Task
Examples
Input
s = 'pqpqs', k = 2
Output
12
There are 12 substrings of 'pqpqs' that contain at most 2 distinct characters.
Input format
Output format
Constraints
Samples
Input
s = 'abc', k = 2
Output
5
Substrings with <=2 distinct: 'a','ab','b','bc','c' -> 5 total.