FastPrepLongest Common Prefix

Longest Common Prefix

Kotak Mahindra Bank logoKotak Mahindra Bank● EasyFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given a nonempty array of 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"

Every word starts with fl, and the next characters differ.

Example 2

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

The first characters do not match.

Constraints

  • 1 <= words.length <= 10000.
  • 0 <= words[i].length <= 1000.
  • Every word contains lowercase English letters.
  • The total number of characters is at most 100000.

Source note: Author-written prompt excerpt retained for source fidelity.

More Kotak Mahindra Bank problems

See Kotak Mahindra Bank hiring insights
public String longestCommonPrefix(String[] words) {
    // Write your code here.
}
words["flower","flow","flight"]
expected"fl"
Checking account…