Yuzhe's Blog

yuzhes

Check Repeated Chars

Check Repeated Chars

Problem Link

Problem

Implement CheckRepeatedChars<S> which will return whether type S contains repeated characters.

type CheckRepeatedChars<'abc'>   // false
type CheckRepeatedChars<'aba'>   // true

Solution

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>
  : false

How it works:

  1. Extract the first character C.
  2. Check if C extends Seen (i.e., C is already in the seen set).
  3. If yes, return true — a repeat was found.
  4. Otherwise, add C to Seen and recurse on Rest.
  5. If we exhaust the string without finding a repeat, return false.

Key Takeaways