AceYourInterviews
Checking sign-in…

151. Longest Common Prefix

EasyShrink a shared prefix boundary

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 <= 200
  • 0 <= 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.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Shorten a shared prefix

["plane","plant","plate"]
"pla"