[LeetCode] Count Residue Prefixes

3803. Count Residue Prefixes

You are given a string s consisting only of lowercase English letters.

A prefix of s is called a residue if the number of distinct characters in the prefix is equal to len(prefix) % 3.

Return the count of residue prefixes in s.

prefix

non-empty substring

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int residuePrefixes(string s) {
int res = 0;
unordered_set<char> us;
for(int i = 0; i < s.length(); i++) {
us.insert(s[i]);
res += us.size() == ((i + 1) % 3);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/count-residue-prefixes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.