[Python] Longest common prefix code using counter returns inccorect prefix for edge cases

Discussão em 'Python' iniciado por Stack, Agosto 25, 2025.

  1. Stack

    Stack Membro Participativo

    I wrote a brute force code to extract the longest common prefix from several input strings. It works for most of the test cases, however fails for an edge case such as strs = ["reflower","flow","flight"].

    This is my code:

    from collections import Counter
    class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
    if len(strs) == 1:
    return strs[0]
    mini =[]
    for i in strs:
    l = len(i)
    print(l)
    mini.append(l)
    print("minimum",min(mini))
    minimum = min(mini)
    strs.sort(key=len)
    print(strs)
    #pointer initialization
    l = 0
    r = len(strs)-1

    cp = []
    while l<r:
    l1 = strs[l]
    r1 = strs[r]
    for i in range(minimum):
    if l1 == r1:
    cp.append(l1)
    else:
    break
    r-=1
    if not cp:
    return ""

    counter = Counter(cp)
    max_frequency = max(counter.values())
    most_frequent =[k for k,v in counter.items() if v==max_frequency]
    ans = ''.join(most_frequent)
    # print(ans)
    return ans


    The problem occurs in the while block. The result from the code should be "" but for some reason it returns "fl".

    Why does the code fail in this case?

    Continue reading...

Compartilhe esta Página