
Problem 15: Longest Common Prefix
Hey everyone! π Today, we're solving a popular string manipulation problem: Longest Common Prefix . The Problem The goal is to write a function that finds the longest common prefix among a list of strings. A prefix is a substring that occurs at the beginning of a string. The function should return the longest common string that all words in the list start with. If there is no common prefix, it should return an empty string "" . Examples: longest_common_prefix(['flower', 'flow', 'flight']) β Should return 'fl' longest_common_prefix(['dog', 'racecar', 'car']) β Should return "" (no common prefix) longest_common_prefix(['interspecies', 'interstellar']) β Should return 'inters' The Solution Here is the Python implementation: def longest_common_prefix ( strings ): """ Finds the longest common prefix among a list of strings. """ # Check for empty or invalid input if not strings : return "" # Set the first string as the initial prefix prefix = strings [ 0 ] # Iterate through the remaining str
Continue reading on Dev.to Python
Opens in a new tab



