A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1392. Longest Happy Prefix, the solution in this repository is mainly a prefix sums solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: prefix sums.
The notes already sitting in the source point us in the right direction:
- 69 / 72 test cases passed.
Guide
When?
Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are longestPrefix, preprocess, lps, power.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- Substring checks are convenient but not free, so they are part of the real complexity story.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//either Time Limit Exceeded or Memory Limit Exceeded
02//69 / 72 test cases passed.
03class Solution {
04public:
05 string longestPrefix(string s) {
06 int N = s.size();
07 int SEGMENT = 10000;
08
09 //l starts from N-1(substring cannot be itself)
10 for(int l = N-1; l >= 1; l--){
11 // cout << l << endl;
12 // string prefix = s.substr(0, l);
13 // string suffix = s.substr(N-l);
14
15 // bool same = true;
16 // for(int i = 0; i < prefix.size(); i++){
17 // if(prefix[i] != suffix[i]){
18 // same = false;
19 // break;
20 // }
21 // }
22 // if(same){
23 // return prefix;
24 // }
25 // if(prefix == suffix){
26 // return prefix;
27 // }
28
29
30 bool same = true;
31 for(int i = 0; i <= l/SEGMENT; i++){
32 //partPrefix could exceed the boundary
33 string partPrefix = s.substr(0+i*SEGMENT, SEGMENT);
34 string partSuffix = s.substr(N-l+i*SEGMENT, SEGMENT);
35 //partPrefix could exceed the boundary
36 if(partPrefix.size() != partSuffix.size()){
37 partPrefix = partPrefix.substr(0, partSuffix.size());
38 }
39
40 for(int i = 0; i < partPrefix.size(); i++){
41 if(partPrefix[i] != partSuffix[i]){
42 same = false;
43 break;
44 }
45 }
46
47 if(same == false){
48 break;
49 }
50
51 // if(partPrefix != partSuffix){
52 // same = false;
53 // break;
54 // }
55 }
56
57 if(same){
58 return s.substr(0, l);
59 }
60 }
61
62 return "";
63 }
64};
65
66//KMP
67//Runtime: 48 ms, faster than 28.57% of C++ online submissions for Longest Happy Prefix.
68//Memory Usage: 19 MB, less than 100.00% of C++ online submissions for Longest Happy Prefix.
69class Solution {
70public:
71 vector<int> preprocess(string& pattern){
72 int n = pattern.size();
73 vector<int> lps(n, 0);
74
75 for(int i = 1, len = 0; i < n; ){
76 if(pattern[i] == pattern[len]){
77 len++;
78 lps[i] = len;
79 i++;
80 }else if(len > 0){
81 len = lps[len-1];
82 }else{
83 i++;
84 }
85 }
86
87 return lps;
88 };
89
90 string longestPrefix(string s) {
91 vector<int> lps = preprocess(s);
92 // for(int e : lps){
93 // cout << e;
94 // }
95 // cout << endl;
96
97 // int length = *max_element(lps.begin(), lps.end());
98 int length = lps[lps.size()-1];
99 return s.substr(0, length);
100 }
101};
102
103//Rolling hash
104//https://leetcode.com/problems/longest-happy-prefix/discuss/547448/Python-rolling-hash
105//Runtime: 296 ms, faster than 14.29% of C++ online submissions for Longest Happy Prefix.
106//Memory Usage: 14.3 MB, less than 100.00% of C++ online submissions for Longest Happy Prefix.
107class Solution {
108public:
109 //https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/
110 long long int power(long long int x, long long int y, long long int p){
111 long long int res = 1;
112
113 // Update x if it is more than or equal to p
114 x = x % p;
115
116 while(y > 0){
117 // If y is odd, multiply x with result
118 if(y & 1){
119 res = (res*x) % p;
120 }
121
122 // y must be even now
123 y >>= 1;
124 x = (x*x) % p;
125 }
126
127 return res;
128 };
129
130 string longestPrefix(string s) {
131 int N = s.size();
132 if(N == 1) return "";
133 long long int mod = pow(10, 9) + 7;
134
135 long long int prefixHash = 0, suffixHash = 0;
136
137 int res = -1;
138
139 //i cannot be N-1 because we only want the proper substrings
140 for(int i = 0; i < N-1; i++){
141 // prefixHash += (s[i]-'a') * ((long long int)pow(26, i) % mod);
142 prefixHash += (s[i]-'a') * power(26, i, mod);
143 prefixHash %= mod;
144
145 //Note it's s[N-1-i] here!
146 suffixHash = suffixHash * 26 + (s[N-1-i] - 'a');
147 suffixHash %= mod;
148
149 // cout << i << " " << prefixHash << " " << suffixHash << endl;
150
151 if(prefixHash == suffixHash){
152 res = i;
153 }
154 }
155
156 return (res == -1) ? "" : s.substr(0, res+1);
157 }
158};
Cost