Problems

Longest Common Prefix

easy
easy
strings

Given an array of strings, return the longest prefix shared by every string. Return an empty string when the list is empty or no common prefix exists.

Input / output

  • Input: strs: string[]
  • Output: common prefix string

Examples

  1. ["flower", "flow", "flight"] returns "fl".
  2. ["dog", "racecar", "car"] returns "".

Constraints

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • Comparisons are case-sensitive.

Follow-up Compare horizontal scanning with sorting and a trie. Which is best when queries repeat over a fixed corpus?

Examples

Example 1

Input: strs = ["start","stair","stop"]
Output: "st"

Example 1

Input: strs = ["cat","dog","mouse"]
Output: ""

Example 3

Input: strs = ["very long string","very long string","very long string"]
Output: "very long string"
🔒 8 hidden

Running will execute all 11 cases, including 8 hidden ones.