[AlgoExpert] Smallest Substring Containing

Smallest Substring Containing

  • Time : O(n + m)
  • Space : O(m)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using namespace std;

string smallestSubstringContaining(string bigString, string smallString) {
unordered_map<char, int> smp, bmp;
for(auto& ch : smallString)
smp[ch]++;
int len = INT_MAX, n = bigString.length(), count = smp.size(), pos = -1, l = 0, r = 0;

while(r < n) {
while(r < n and count > 0) {
char ch = bigString[r++];
if(smp.count(ch) and smp[ch] == ++bmp[ch]) count--;
}
while(l < r and count == 0) {
if(len > r - l) {
pos = l; len = r - l;
}
char ch = bigString[l++];
if(smp.count(ch) and smp[ch] == bmp[ch]--) count++;
}
}
return pos == -1 ? "" : bigString.substr(pos, len);
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/smallest-substring-containing/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.