Problem 226068 · easy · Level 02 Linear Data Structures

The Common Start of Every Name

strings · prefix · iteration

A filing clerk wants the label for a drawer that holds several names. Write shared_prefix(words) that returns the longest run of characters at the very start that all the names in words have in common. Return "" if the list is empty or the names do not even share their first character. Capital and small letters are different characters.

Examples

Input:  words = ["planetary", "plane", "planet"]
Output: "plane"

Input:  words = ["cobalt", "nickel"]
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…