Check Repeated Chars
Less than 1 minuteTC-Medium
Check Repeated Chars
Problem
Implement CheckRepeatedChars<S> which will return whether type S contains repeated characters.
type CheckRepeatedChars<'abc'> // false
type CheckRepeatedChars<'aba'> // trueSolution
Approach: Track Seen Characters
Peel characters one by one and check against the set of already-seen characters.
type CheckRepeatedChars<
S extends string,
Seen extends string = never
> = S extends `${infer C}${infer Rest}`
? C extends Seen
? true
: CheckRepeatedChars<Rest, Seen | C>
: falseHow it works:
- Extract the first character
C. - Check if
C extends Seen(i.e.,Cis already in the seen set). - If yes, return
true— a repeat was found. - Otherwise, add
CtoSeenand recurse onRest. - If we exhaust the string without finding a repeat, return
false.
Key Takeaways
- Accumulating a union of seen characters (
Seen) is the type-level equivalent of aSet. C extends Seenchecks membership in the union — works because'a' extends 'a' | 'b'istrue.- The
Seen = neverdefault initializes to an empty set.
