You are given a list of words, strs. Find the longest string that every word in the list starts with.
If the words do not all start with the same letter, the answer is the empty string "".
Example 1
Input: strs = ["stamp", "stack", "stair"] Output: "sta" Why: all three begin with s, t, a; then m, c, i differ
2 more examples and the constraints
Example 2
Input: strs = ["mango", "apple", "kiwi"] Output: "" Why: the first letters already differ
Example 3
Input: strs = ["alone"] Output: "alone" Why: a single word is its own prefix
Constraints
- 1 ≤ number of words ≤ 200
- 0 ≤ length of each word ≤ 200
- Words use only lower-case English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Shrink a candidateO(S)
- Column by columnO(S)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Letters read for 200 words of 200 letters | Verdict |
|---|---|---|---|
| Shrink a candidate | O(S) | Passes; can over-read | |
| Column by column | O(S) | Best; stops at the first break |
S = total number of letters in all the words. Both are linear; the column scan never reads past the shortest prefix.
Edge cases to test
- One word. ["alone"] returns "alone": no other word can cut it.
- An empty word. Any empty word makes the answer "", wherever it sits in the list.
- A shorter word later. ["prefix", "pre"] gives "pre": stop when a word runs out, not only on a mismatch.
- All words equal. ["same", "same", "same"] returns the whole word.
Common mistakes
- Reading
word[i]before checking thatiis still inside the word, which crashes on a shorter word. - Returning the prefix of the first two words only, without checking the rest.
- Sorting the list first and then forgetting that only the first and last words need comparing, doing extra work for nothing.
How to talk through it
- 1Clarify. Can a word be empty? Is there always at least one word? Only lower-case letters?
- 2Give the simple version. Start from the first word and cut it down against each other word. Say it is linear.
- 3Turn it sideways. Read column by column across all words; the first bad column ends the answer.
- 4Code the column scan. Check the word length before reading its letter, and say why.
- 5Test out loud. Run ["alone"], ["", "abc"] and ["prefix", "pre"] before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?