↓Skip to main content
  1. LeetCode/

LeetCode 3803: Count Residue Prefixes

·1 min· ·
LeetCode Easy Hash-Table String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2026-01-11

  • Submissions: Accepted (first try)

Approach
#

The prefix grows one character at a time, so maintain its distinct characters in a set (String Template 4). Its length is i + 1; compare len(seen) == (i + 1) % 3.

My Solution
#

class Solution:
    def residuePrefixes(self, s: str) -> int:
        seen, res = set(), 0
        for i, ch in enumerate(s):
            seen.add(ch)
            res += len(seen) == (i + 1) % 3
        return res

Complexity
#

Time O(n), space O(1) (at most 26 characters).

Mistakes to Avoid
#

  • The length is i + 1, not i.

Interview Explanation
#

I scan left to right with a set of the prefix’s characters and compare its size to the prefix length mod 3 at each step. Time O(n). Since length % 3 is at most 2, once the prefix has more than 2 distinct characters it can never hold again, so the scan can stop early.

Related

LeetCode 3090: Maximum Length Substring With Two Occurrences
·1 min
LeetCode Easy Sliding-Window Hash-Table String
LeetCode 3090 note: a longest-window slide that shrinks the left whenever the newly added character appears more than twice
LeetCode 3545: Minimum Deletions for At Most K Distinct Characters
·1 min
LeetCode Easy Greedy Hash-Table String Sorting Counting
LeetCode 3545 note: reducing the number of kinds means deleting whole kinds, starting from the least frequent
LeetCode 3541: Find Most Frequent Vowel and Consonant
·1 min
LeetCode Easy Hash-Table String Counting
LeetCode 3541 note: count characters, take the maximum among vowels and among consonants and add them; a missing class counts as 0
LeetCode 3120: Count the Number of Special Characters I
·1 min
LeetCode Easy Hash-Table String
LeetCode 3120 note: collect the letters seen in lowercase and in uppercase; the size of their intersection is the answer
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 min
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 note: a word is formable when none of its character counts exceeds chars’; sum the lengths of such words
LeetCode 804: Unique Morse Code Words
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 804 note: translate each word into a Morse string and count the distinct results with a set