Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Longest Common Prefix

Data Structures, Operators & Stringshard

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 128: Working With Strings - Part 1

Implement `longestCommonPrefix(strs)` returning the longest common prefix shared by all strings, or an empty string if there is none.

Sample tests

Input: longestCommonPrefix(["flower","flow","flight"])
Output: "fl"
Input: longestCommonPrefix(["dog","cat"])
Output: ""

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Returning early without checking all strings.
  • Not handling the empty input list.

Learning resources

  • MDN: String
Approach & explanation (try first)

Shrinking a candidate prefix until all strings share it yields the longest common prefix.

Loading...
⌘/Ctrl + Enter

Run your code to see results.