[InterviewBit] Substring Concatenation

Substring Concatenation

  • Time : O(B + |A|)
  • Space : O(B)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
vector<int> Solution::findSubstring(string A, const vector<string> &B) {
int len = B[0].length(), n = A.length(), m = B.size();
if(n < len * m) return {};
unordered_map<string, int> freq;
for(auto& b : B) freq[b]++;

vector<int> res;
for(int i = 0; i < len; i++) {
unordered_map<string, int> window;
int match = 0;
for(int j = 0; i + (j + 1) * len <= n; j++) {
string sub = A.substr(i+j*len, len);
if(freq.count(sub) and ++window[sub] == freq[sub]) match++;
if(j >= m) {
string rsub = A.substr(i + (j-m)*len, len);
if(freq.count(rsub) and --window[rsub] + 1 == freq[rsub]) match--;
}
if(match == freq.size()) res.push_back(i + (j-m+1)*len);
}
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/31/PS/interviewbit/substring-concatenation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.