Algorithmscharacter set membership check
Character Set Membership Check (Allowed Alphabets)
TT
Testlaa Team
May 14, 2026•1 min read
Set membership asks whether a character belongs to an allowed alphabet—ch in allowed with a set for O(1) average lookups after you pay the build cost.
Why this shows up in the real world
Base64 validators ensure only A-Za-z0-9+/= appear. Hex color pickers restrict to [0-9a-fA-F] per slot.
Core idea (explained for students)
ALLOWED = set('abc'); ch in ALLOWED. For static ASCII classes, sometimes a boolean chain is faster to type in contests, but sets scale when the alphabet grows.
Try this in Python
BASE64 = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=")
def is_base64_char(ch: str) -> bool:
return len(ch) == 1 and ch in BASE64
print(is_base64_char("Z"), is_base64_char("?"))
Common mistakes
- Building a new set inside a tight loop—hoist construction outside.
- Case sensitivity:
'a' in {'A'}is false unless normalized.
Key takeaways
- Precompute frozen sets for immutable allowed alphabets in hot paths.
- Pair membership checks with normalization (
lower) when rules ignore case.
Tags:
StringsPythonStudents
