Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 14 · Prefix / Misc

Longest Common Prefix

LeetCode 14 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Shrink a candidate prefix until every word starts with it.

सोपाArrayStringTrie

मी 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.