💡
Exercise 26

Longest Common Prefix 20 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

LeetCode #14: Longest Common Prefix

Given an array of strings, find the longest common prefix shared by all strings.

Example:
["flower", "flow", "flight"]"fl"

Approach: Use the first string as a reference. For each character position, check if ALL strings have that same character.

💭 Go for it! Apply the approach above in your own code. If you get stuck, use the hint below! 🔥

Complexity: Time O(S) where S is sum of all characters, Space O(1)

📋 Instructions
Implement `longestCommonPrefix(strs)` that returns the longest common prefix string. If there is no common prefix, return an empty string `""`.
Start with 'if not strs: return ""'. Loop 'for i in range(len(strs[0]))'. Get char = strs[0][i]. Check each string: 'for s in strs[1:]: if i >= len(s) or s[i] != char: return strs[0][:i]'. After loop: return strs[0].
⚠️ Try solving it yourself first — you'll learn more!
def longestCommonPrefix(strs):
    if not strs:
        return ""
    for i in range(len(strs[0])):
        char = strs[0][i]
        for s in strs[1:]:
            if i >= len(s) or s[i] != char:
                return strs[0][:i]
    return strs[0]
🧪 Test Cases
Input
longestCommonPrefix(["flower","flow","flight"])
Expected
fl
Test case 1
Input
longestCommonPrefix(["dog","racecar","car"])
Expected
Test case 2
Input
longestCommonPrefix(["interspecies","interstellar","interstate"])
Expected
inters
Test case 3
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.