[InterviewBit] Stringoholics

Stringoholics

  • Time : O(sum(|s|) + factor * log(pow))
  • Space : O(factor)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
vector<int> PI(string p) {
vector<int> pi(p.length());
for(int i = 1, j = 0; i < p.length(); i++) {
while(j and p[i] != p[j]) j = pi[j-1];
if(p[i] == p[j]) pi[i] = ++j;
}
return pi;
}

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

long long helper(string s) {
if(s.length() == 1) return 1;
string ss = s + s;
ss.pop_back();
unordered_set<int> us = kmp(ss, s);
long long now = 1, loop = 1;
while(!us.count(now)) {
now = (now + ++loop) % s.length();
}
return loop;
}

long long modpow(long long n, long long p, long long mod) {
if(p == 1) return n;
long long res = modpow(n, p/2, mod);
res = (res * res) % mod;
if(p & 1) res = (res * n) % mod;
return res;
}

int Solution::solve(vector<string> &A) {
long long res = 1, mod = 1e9 + 7;
unordered_map<long long, long long> factors;
for(auto& a : A) {
long long now = helper(a);
for(long long i = 2; i <= sqrt(now); i++) {
if(now % i) continue;
long long cnt = 0;
while(now % i == 0) {
cnt++;
now /= i;
}
factors[i] = max(factors[i], cnt);
}
if(now != 1) factors[now] = max(factors[now], 1ll);
}
for(auto& [f,p] : factors) {
res = res * modpow(f,p,mod) % mod;
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/06/PS/interviewbit/stringoholics/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.