LeetCode Entry
1358. Number of Substrings Containing All Three Characters
Substrings with 3 letters
1358. Number of Substrings Containing All Three Characters medium substack youtube
https://dmitrysamoylenko.com/leetcode/

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1406
Problem TLDR
Substrings with 3 letters
Intuition
Sum of substrings ending at position i. Count all prefixes.
Approach
- just remember the latest position of each letter, the min would be the prefix
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\)
Code
fun numberOfSubstrings(s: String) = IntArray(3).run {
s.indices.sumOf { i -> set(s[i]-'a', i+1); min() }
}
pub fn number_of_substrings(s: String) -> i32 {
s.bytes().zip(1..).fold(([0;3],0),|(mut j,mut s),(b,i)|{
j[b as usize%3]=i;(j,s+j[0].min(j[1]).min(j[2]))}).1
}
Comments