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.