InterviewHubPRO
Section Overview
Q13

Question 13 of 100

Part 2: Arrays, Strings & Hash Maps (6 - 18)

13%
DSA Patterns (Multi-Lang)•Part 2: Arrays, Strings & Hash Maps (6 - 18)

Longest Common Prefix.

In Simple Words: Compare characters vertically across all strings at index $0, 1, 2, \dots$. The moment any string ends or a character mismatch occurs, return prefix up to that point.

  • Time: $O(N \cdot M)$ | Space: $O(1)$
Multi-Language Solutions
Switch tabs or choose All
def longestCommonPrefix(strs: list[str]) -> str:
    if not strs:
        return ""
    for i in range(len(strs[0])):
        c = strs[0][i]
        for s in strs[1:]:
            if i == len(s) or s[i] != c:
                return strs[0][:i]
    return strs[0]