#35045Medium

Longest Common Prefix

### Longest Common Prefix Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement LongestCommonPrefix, a type that finds the longest common prefix string shared among all strings in a given tuple, returning an empty string if no common prefix exists.

Challenge Instructions: Longest Common Prefix

Medium

Longest Common Prefix

Write a type, LongestCommonPrefix that returns the longest common prefix string amongst a tuple of strings.

If there is no common prefix, return an empty string "".

type Common = LongestCommonPrefix<["flower", "flow", "flight"]>
//   ?^ "fl"
 
type Uncommon = LongestCommonPrefix<["dog", "racecar", "race"]>
//   ?^ ""

Inspired by LeetCode 14. Longest Common Prefix

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type cases = [
  Expect<Equal<LongestCommonPrefix<['flower', 'flow', 'flight']>, 'fl'>>,
  Expect<Equal<LongestCommonPrefix<['dog', 'racecar', 'race']>, ''>>,
  Expect<Equal<LongestCommonPrefix<['', '', '']>, ''>>,
  Expect<Equal<LongestCommonPrefix<['a', '', '']>, ''>>,
  Expect<Equal<LongestCommonPrefix<['', 'a', '']>, ''>>,
  Expect<Equal<LongestCommonPrefix<['', '', 'a']>, ''>>,
  Expect<Equal<LongestCommonPrefix<['a', 'a', '']>, ''>>,
  Expect<Equal<LongestCommonPrefix<['a', '', 'a']>, ''>>,
  Expect<Equal<LongestCommonPrefix<['', 'a', 'a']>, ''>>,
  Expect<Equal<LongestCommonPrefix<['a',

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

type LongestCommonPrefix<
  T extends string[],
  Prefix extends string = ''
> = T extends [infer First extends string, ...infer Rest extends string[]]
  ? First extends `${Prefix}${infer C}${string}`
    ? AllStartWith<Rest, `${Prefix}${C}`> extends true
      ? LongestCommonPrefix<T, `${Prefix}${C}`>
      : Prefix
    : Prefix
  : Prefix;
 
type AllStartWith<T extends string[], P extends string> =
  T extends [infer First extends string, ...infer Rest extends string[]]
    ? First extends `${P}${string}`
      ? AllStartWith<Rest, P>
      : false
    : true;

How it works:

This challenge helps you understand recursive template literal type manipulation and tuple iteration, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge