Strings String basics
126. Longest Common Prefix
You are given a list of lowercase words, words. Return the longest string that every word in the list
starts with.
A prefix of a word is its first few letters, from none of them up to all of them: "car", "c" and the
empty string are all prefixes of "car". You are looking for the longest string that is a prefix of every
word at once. If the words do not even share their first letter, the answer is the empty string "".
Answers are shown in double quotes, so an empty answer shows as "".
Example 1
Input: words = ["carpet", "carpool", "card", "care"]
"car"Explanation: "carpet" and "carpool" both start with "carp", but "card" and "care" break off after "car". All four words start with "car", and no longer string fits all of them.
Example 2
Input: words = ["night", "nightly", "nightfall"]
"night"Explanation: The other two words both begin with the whole of "night", so the answer is that entire word.
Example 3
Input: words = ["mango", "melon", "grape"]
""Explanation: "mango" and "melon" share their first letter, but "grape" starts with a "g". No letter is shared by all three, so the answer is the empty string.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ words.length ≤ 1050 ≤ words[i].length, and all the words together hold at most106letterswords[i]holds only lowercase English letters
Clarifying questions
What you would ask an interviewer before writing any code.