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.