Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Finding the Longest Common Prefix in an Array of Strings

Tech May 14 1

The task is to identify the longest common prefix shared among all strings in a given array. For instance, with an input like ['abc', 'abcd', 'abd'], the result should be 'ab'.

Approach 1: Brute Force Itertaion

A straightforward method involves incrementally building prefixes and verifying each one against every string in the collection. We start with the shortest possible prefix and extend it character by character until we find a mismatch.

class Solution:
    def longestCommonPrefix(self, strings):
        if not strings:
            return ''
        
        base = strings[0]
        result = ''
        
        for position in range(len(base)):
            candidate = base[:position + 1]
            if all(s.startswith(candidate) for s in strings):
                result = candidate
            else:
                break
        
        return result

This approach has O(n²) time complexity, where n represents the combined length of all strings, as we check each prefix against every string in the array.

Approach 2: Sorting-Based Optimization

A more efficient strategy leverages sorted order. After sorting the strings lexicographically, the longest common prefix must exist between the first and last elements. This is because strings that share common characters will cluster to gether, and comparing only the extremes eliminates unnecessary comparisons.

class Solution:
    def longestCommonPrefix(self, strings):
        if not strings or not strings[0]:
            return ''
        
        sorted_strings = sorted(strings)
        first_item = sorted_strings[0]
        last_item = sorted_strings[-1]
        
        common = ''
        for idx in range(len(first_item)):
            segment = first_item[:idx + 1]
            if segment == last_item[:idx + 1]:
                common = segment
            else:
                break
        
        return common

The sorting step operates in O(n log n) time complexity using Python's Timsort algorithm. The subsequent prefix comparison runs in O(n) time, making this approach significantly faster for large datasets.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.