35045-medium-longest-common-prefix

Back

type LongestCommonPrefix<T extends string[], P extends string = ''>
  = T extends [`${P}${infer Next}${any}`, ...any]
  ? T extends `${P}${Next}${any}`[]
    ? LongestCommonPrefix<T, `${P}${Next}`>
    : P // the longest
  : P   // T is empty or end of T[0]

Playground

type LongestCommonPrefix<T extends string[], P extends string = ''>
  = T extends `${P}${infer Next}${any}`[]
  ? {} extends {[P in Next as Exclude<Next, P>]: 1}
    ? LongestCommonPrefix<T, `${P}${Next}`>
    : P // Next is union, return P
  : P   // T is empty or all empty string

Playground

Solution by teamchong #35251