Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 14 · Prefix / Misc

Longest Common Prefix

LeetCode 14 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Shrink a candidate prefix until every word starts with it.

எளிதுArrayStringTrie
LeetCode இல் திற ↗

நான் Longest Common Prefix (LeetCode 14) ஐ இப்படித் தீர்த்தேன் — Prefix / Misc பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Start with the first word as the candidate prefix. For each other word, chop characters off the end of the candidate until the word starts with it. Whatever survives every word is the answer.

Approach

  1. 1

    prefix = strs[0].

  2. 2

    For each word, while it doesn't start with prefix, drop the last character.

  3. 3

    Empty prefix → return ''.

நான் எப்படித் தீர்த்தேன்

Shrinking prefixPythonO(S) time
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        i=1
        prefix = strs[0]
        while i<len(strs):
            cur_word = strs[i]
            while not cur_word.startswith(prefix):
                prefix=prefix[:len(prefix)-1]
                if not prefix:
                    return ""
            i+=1
        return prefix
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Longest Common Prefix — அடிக்கடி கேட்கப்படும் கேள்விகள்

Longest Common Prefix பின்னாலுள்ள intuition என்ன?

Start with the first word as the candidate prefix. For each other word, chop characters off the end of the candidate until the word starts with it. Whatever survives every word is the answer.

Longest Common Prefix (LeetCode 14) ஐ எப்படித் தீர்ப்பது?

1. prefix = strs[0]. 2. For each word, while it doesn't start with prefix, drop the last character. 3. Empty prefix → return ''.

Longest Common Prefix இன் time மற்றும் space complexity என்ன?

Time: O(S) — total characters. Space: O(1). (Accepted approach: Shrinking prefix.)

Longest Common Prefix இல் பொதுவான தவறுகள் என்ன?

Return early when the prefix becomes empty.