JS Built-ins
Algorithmsadvanced

Longest Common Prefix

πŸ“– Usage Example
function longestCommonPrefix(strs) {
  if (!strs.length) return '';
  let prefix = strs[0];
  for (const s of strs) while (!s.startsWith(prefix)) prefix = prefix.slice(0, -1);
  return prefix;
}
longestCommonPrefix(['flower', 'flow', 'flight']); // 'fl'

Find the longest common prefix by progressively trimming the candidate string.

Longest Common Prefix

Find the longest common prefix among an array of strings. A prefix is a substring that appears at the start of multiple strings.

["flower", "flow", "flight"] β†’ "fl"
["dog", "racecar", "car"] β†’ ""
["interspecies", "interstellar", "interstate"] β†’ "inters"

Algorithm:

  1. Start with the first string as the prefix
  2. For each string, truncate the prefix until it matches the start of that string
function longestCommonPrefix(strs: string[]): string {
  // Return the longest common prefix
}

longestCommonPrefix(['flower', 'flow', 'flight']) // "fl"
πŸ’‘ Hints (5)
  • β€’ Start with the first string as the prefix.
  • β€’ For each subsequent string, check if it starts with the prefix.
  • β€’ If not, trim the last character from the prefix using `slice(0, -1)`.
  • β€’ Repeat until the prefix matches all strings or becomes empty.
  • β€’ Use `startsWith()` to check prefix match.