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.