Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 1358 · Counting Subarrays (Exactly K = AtMost K − AtMost K−1)

Number of Substrings Containing All Three Characters

LeetCode 1358 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Ending at i, valid starts = 1 + min(last a, last b, last c).

मध्यमHash TableStringSliding Window

मी 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. 1

    last index of a, b, c start at −1.

  2. 2

    Update the index of s[i].

  3. 3

    If all three have appeared, add 1 + min(last indices).

  4. 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 count
स्टेप-थ्रू लोड होत आहे…

Number 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.