Back

Longest Common Prefix

easy

Write a function to find the longest common prefix string amongst an array of strings.

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

Test Cases

Copy an input into the main harness and Run to verify
Input
strs = ["flower","flow","flight"]
Expected Output
"fl"
Input
strs = ["dog","racecar","car"]
Expected Output
""

Explanation: There is no common prefix among the input strings.

Constraints

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

Hints

Hint 1 — click to reveal

The answer can never be longer than the shortest string in the array.

Hint 2 — click to reveal

Compare character by character across all strings at the same position, and stop at the first mismatch.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.