Substring Counting with Minimal Valid Window in Java

🔥 Day 83/100 of Code – Substrings Containing All Three Characters: Counting with Minimal Valid Window! Today solved a substring counting problem by leveraging the "minimal valid window" property: ✅ Problem 1358: Number of Substrings Containing All Three Characters Task: Count substrings containing at least one a, b, and c. Approach: Sliding window with earliest valid start tracking: For each ending index r, find the smallest l such that s[l..r] contains all three chars Once found, all substrings starting from 0..l and ending at r are valid → add l+1 to count Use a frequency map or array to track counts of a,b,c and shrink window when possible Key Insight: If the minimal valid window ending at r starts at minStart, then any substring starting before minStart and ending at r also contains all three characters — giving minStart + 1 valid substrings per r. Complexity: O(n) time, O(1) space — efficient single pass. A smart counting trick that turns a "contain all" constraint into an elegant O(n) accumulation! 🔤🔢 #100DaysOfCode #LeetCode #Java #SlidingWindow #String #SubstringCounting #Algorithm

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories