#3803

Count Residue Prefixes

Easy
Hash TableStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We maintain a set to track distinct characters as we build prefixes, allowing us to check the condition in constant time.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a set to keep track of distinct characters and a count for residue prefixes.
  2. 2Step 2: Iterate through the string, adding each character to the set.
  3. 3Step 3: Check if the size of the set equals the current index + 1 modulo 3, and update the count accordingly.
solution.py8 lines
1def countResiduePrefixes(s):
2    count = 0
3    distinct_chars = set()
4    for i, char in enumerate(s):
5        distinct_chars.add(char)
6        if len(distinct_chars) == (i + 1) % 3:
7            count += 1
8    return count

Complexity note: We traverse the string once, maintaining a set of distinct characters, leading to O(n) complexity.

  • 1Distinct character count must match length modulo 3.
  • 2Set operations allow efficient tracking of distinct characters.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.