FastPrepLongest Common Prefix

Longest Common Prefix

Wells Fargo logoWells Fargo● MediumINTERNOA
Learn

Problem statement

Given a nonempty array of lowercase strings words, return the longest string that is a prefix of every word.

If the words share no nonempty prefix, return the empty string.

Function

longestCommonPrefix(words: String[]) → String

Examples

Example 1

words = ["flower","flow","flight"]return = "fl"

All three words begin with fl, but their third characters differ.

Example 2

words = ["dog","racecar","car"]return = ""

The first characters are not all equal.

Example 3

words = ["interview","internet","internal"]return = "inter"

The shared prefix ends before the sixth character.

Constraints

  • 1 <= words.length <= 10^5.
  • 1 <= words[i].length <= 10^5.
  • The sum of all string lengths is at most 2 * 10^5.
  • Every string contains lowercase English letters.

More Wells Fargo problems

See Wells Fargo hiring insights
public String longestCommonPrefix(String[] words) {
  // write your code here
}
words["flower","flow","flight"]
expected"fl"
Checking account…