Skip to main content

Longest Common Prefix

Easy
Data Structures and Algorithms
Editorial
Topics:
Array
String
String Matching

Given strs, a list of strings, find the longest common prefix shared by every string in the list. A prefix is a contiguous sequence of characters beginning at index 0 of a string; the empty string is also a valid prefix.

The returned prefix must appear at the beginning of every string in strs. If no character is shared by all strings, return the empty string. If all strings are identical, return the entire string.

Implement longestCommonPrefix in the Solution class and return the required prefix as a string.

Example 1:

Input: strs = ["starlight","start","staple"]
Output: "sta"
Explanation: All three strings begin with sta, but their next characters differ.

Example 2:

Input: strs = ["copper","silver","gold"]
Output: ""
Explanation: There is no character at the beginning of all three strings that matches.

Example 3:

Input: strs = ["orbit","orbit","orbit"]
Output: "orbit"
Explanation: Since every string is identical, the whole string is their longest common prefix.

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] contains only lowercase English letters

Need help or want more practice?

Practise in an interviewGet AI Coach help