Longest Common Prefix
LeetCode 14 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Shrink a candidate prefix until every word starts with it.
నేను 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
prefix = strs[0].
- 2
For each word, while it doesn't start with prefix, drop the last character.
- 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 prefixLongest 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.