Number of Substrings Containing All Three Characters
LeetCode 1358 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Ending at i, valid starts = 1 + min(last a, last b, last c).
நான் Number of Substrings Containing All Three Characters (LeetCode 1358) ஐ இப்படித் தீர்த்தேன் — Counting Subarrays (Exactly K = AtMost K − AtMost K−1) பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Track the latest index where each of a, b and c appeared. For a substring ending at i to contain all three, it must start at or before the smallest of those indices — so there are min(last) + 1 valid starts.
Approach
- 1
last index of a, b, c start at −1.
- 2
Update the index of s[i].
- 3
If all three have appeared, add 1 + min(last indices).
- 4
Earlier versions: O(n²) set scans.
நான் எப்படித் தீர்த்தேன்
Last-seen indicesPythonO(n) time · O(1) space
class Solution:
def numberOfSubstrings(self, s):
mpp = {'a': -1, 'b': -1, 'c': -1}
count = 0
for i in range(len(s)):
mpp[s[i]] = i
if mpp['a'] != -1 and mpp['b'] != -1 and mpp['c'] != -1:
count = count + (1 + min(mpp['a'], mpp['b'], mpp['c']))
return countNumber of Substrings Containing All Three Characters — அடிக்கடி கேட்கப்படும் கேள்விகள்
Number of Substrings Containing All Three Characters பின்னாலுள்ள intuition என்ன?
Track the latest index where each of a, b and c appeared. For a substring ending at i to contain all three, it must start at or before the smallest of those indices — so there are min(last) + 1 valid starts.
Number of Substrings Containing All Three Characters (LeetCode 1358) ஐ எப்படித் தீர்ப்பது?
1. last index of a, b, c start at −1. 2. Update the index of s[i]. 3. If all three have appeared, add 1 + min(last indices). 4. Earlier versions: O(n²) set scans.
Number of Substrings Containing All Three Characters இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(1). (Accepted approach: Last-seen indices.)
Number of Substrings Containing All Three Characters இல் பொதுவான தவறுகள் என்ன?
Count by end position to avoid double-counting.