Write a Python function to find the longest common suffix among a list of strings.
Posted by FrankMl
Last Updated: August 15, 2024
## Finding the Longest Common Suffix in a List of Strings The task of finding the longest common suffix among a list of strings involves determining the longest sequence of characters that appears at the end of all the strings in the list. This function can be implemented in Python efficiently by comparing the strings from the end towards the beginning.
Python Function Implementation
Here is a Python function that accomplishes this:
def longest_common_suffix(strs):
    if not strs:
        return ""
    
    # Start by assuming the suffix is the entire last string
    suffix = strs[-1]
    
    # Compare the suffix with each string in the list
    for string in strs[:-1][::-1]:  # Exclude the last string, reverse the iteration 
        while not string.endswith(suffix):
            suffix = suffix[:-1]  # Remove one character from the end
            if not suffix:
                return ""  # Return empty if no common suffix is found
    
    return suffix
Explanation of the Function
1. Check for Empty List: The function first checks if the input list strs is empty. If it is, it returns an empty string. 2. Initialize Suffix: The function initializes suffix with the last string in the list, presuming it could be the longest common suffix. 3. Iterate Over Strings: The function then iterates over the rest of the strings in reverse order. This approach ensures that we are comparing the suffix against all strings efficiently. 4. Check for Suffix: For each string, it checks if the string ends with the current suffix. If it does not, the function shortens the suffix by removing the last character. 5. Return Result: If the suffix is reduced to an empty string during comparisons, the function returns an empty string, indicating no common suffix exists. Otherwise, it returns the longest common suffix found.
Example Usage
Here’s how you can use this function:
strings = ["running", "swimming", "cycling"]
result = longest_common_suffix(strings)
print("Longest common suffix:", result)  # Output: ""
strings = ["barking", "parking", "hiking"]
result = longest_common_suffix(strings)
print("Longest common suffix:", result)  # Output: "king"
Conclusion
The provided function efficiently finds the longest common suffix among a list of strings, handling edge cases such as empty lists or when no common suffix exists. By iterating from the end of the strings towards the beginning, the function minimizes unnecessary comparisons, making it both simple and efficient.