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.