151. Longest Common Prefix
Find the longest string that is a prefix of every string in strs. Return an empty string when no character is shared at the beginning.
A prefix begins at position zero; a shared substring elsewhere does not qualify.
Example 1
Input
strs = ["plane","plant","plate"]
Output
"pla"
Explanation: All three strings start with pla. The next position differs, so the prefix cannot be extended.
Example 2
Input
strs = ["cat","dog"]
Output
""
Explanation: The first characters differ, leaving no shared nonempty prefix.
Constraints
1 <= strs.length <= 2000 <= strs[i].length <= 200- Each nonempty string contains only lowercase English letters.
Hints
Hint 1
The answer must be a prefix of the first string.
Hint 2
Adding a string can shorten the current candidate but cannot lengthen it.
Hint 3
Keep an ending index and compare from the first character each time.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Shorten a shared prefix
["plane","plant","plate"]
"pla"