[AlgoExpert] Numbers In Pi

Numbers In Pi

  • Time : O(m * len(n))
  • Space : O(k)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <vector>
using namespace std;

vector<int> PI(string& p) {
int n = p.length();
vector<int> pi(n);
for(int i = 1, j = 0; i < n; i++) {
while(j > 0 and p[j] != p[i]) j = pi[j-1];
if(p[i] == p[j])
pi[i] = ++j;
}
return pi;
}

vector<int> kmp(string& s, string& p) {
int n = s.length(), m = p.length();
auto pi = PI(p);
vector<int> res;
for(int i = 0, j = 0; i < n; i++) {
while(j > 0 and s[i] != p[j]) j = pi[j-1];
if(s[i] == p[j]) {
if(++j == m) {
res.push_back(i - m + 1);
j = pi[j-1];
}
}
}
return res;
}

int numbersInPi(string pi, vector<string> numbers) {
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> intervals;

for(auto& n : numbers) {
auto pos = kmp(pi, n);
for(auto& p : pos)
intervals.push({p, p + n.length()});
}

int p = 0, res = -1, n = pi.length(), ma = 0;
while(!intervals.empty() and p < n) {
while(!intervals.empty() and p >= intervals.top().first) {
ma = max(intervals.top().second, ma);
intervals.pop();
}
if(ma > p) {
p = ma;
res++;
} else return -1;
}
return p == n ? res : -1;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/numbers-in-pi/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.