Skip to content
Optimal Lab

Strings · 098Easy

Longest Common Prefix

Write a function to find the longest common prefix string among an array of strings. If there is no common prefix, return the empty string.

Constraints

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of lowercase English letters.

Examples

longestCommonPrefix(["flower","flow","flight"])                    ->  "fl"
longestCommonPrefix(["dog","racecar","car"])                       ->  ""
longestCommonPrefix(["a"])                                         ->  "a"
longestCommonPrefix(["ab","ab"])                                   ->  "ab"   // identical
longestCommonPrefix(["ab",""])                                     ->  ""     // "" forces ""
longestCommonPrefix(["interspecies","interstellar","interstate"])  ->  "inters"

Edge cases

  • An empty string anywhere in the array forces an empty result.
  • A single string is its own prefix.
  • The prefix can never exceed the shortest string's length.
Show the target complexity (spoiler)
Naive
O(n * m) but wasteful — compare all strings fully before truncating.
Target
O(total characters) time — scan character positions across all strings, stopping at the first mismatch or the shortest string's end.

Solve it

By hand, in your editor. The runner checks answers and timing.

git clone https://github.com/sarmadkung/optimal-round
cd optimal-round
# open problems/15-strings/098-longest-common-prefix.js
./practice c 098