#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).

Loading...

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

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount