Problem 226068 · easy · Phase 02 Linear Data Structures

Longest Shared Prefix

strings · prefix · iteration

Write shared_prefix(words) that returns the longest string that every word in the list starts with. Return "" if the list is empty or the words share no common start. Comparison is case-sensitive.

Examples

Input:  words = ["flower", "flow", "flight"]
Output: "fl"

Input:  words = ["dog", "racecar"]
Output: ""

Input:  words = ["alone"]
Output: "alone"

Constraints

  • 0 <= len(words) <= 2000, each word of length at most 5000, printable ASCII
  • Target: O(total characters)

Goals

  • Compare characters column by column across several strings
  • Stop at the first mismatch or the shortest string
  • Handle empty lists and empty strings
Starting Python…