Count and Say
LeetCode 38 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Term n = run-length encoding of term n−1.
मैंने Count and Say (LeetCode 38) ऐसे हल किया — Parsing / Conversion पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Each term describes the previous one: read it as runs of equal digits and write 'count then digit' for each run. Recursively get term n−1 and run-length encode it.
Approach
- 1
Base: n = 1 → '1'.
- 2
Get say = term(n−1).
- 3
Scan runs: count equal neighbours, append count + digit.
मैंने कैसे हल किया
Recursive run-length encodingPythonO(L) per term
class Solution:
def countAndSay(self, n):
if n == 1:
return "1"
say = self.countAndSay(n - 1)
result = ""
i = 0
while i < len(say):
char = say[i]
count = 1
while i < len(say) - 1 and say[i] == say[i + 1]:
count += 1
i += 1
result += str(count) + char
i += 1
return resultCount and Say — अक्सर पूछे जाने वाले प्रश्न
Count and Say के पीछे intuition क्या है?
Each term describes the previous one: read it as runs of equal digits and write 'count then digit' for each run. Recursively get term n−1 and run-length encode it.
Count and Say (LeetCode 38) कैसे हल करें?
1. Base: n = 1 → '1'. 2. Get say = term(n−1). 3. Scan runs: count equal neighbours, append count + digit.
Count and Say की time और space complexity क्या है?
Time: O(total length)। Space: O(total length)। (Accepted approach: Recursive run-length encoding।)
Count and Say में आम गलतियाँ क्या हैं?
Build the result with a list in Python; repeated string concatenation is slower.