Loading W Code...
Master pattern matching, manipulation, and classic interview problems.
6
Topics
50
Minutes
O(N)
KMP Search
2
Visualizers
2. C-Style Strings (char[])
- Fixed size arrays.
- Must be Null Terminated (\0).
- Manual memory management (easy to cause overflow).
Key Operations:
- Length: s.length() or s.size()
- Substring: s.substr(pos, len)
- Find: s.find("pattern") -> returns index or string::npos
- Concat: s1 + s2
#include <string>
using namespace std;
string s = "Hello";
int len = s.length(); // 5
string sub = s.substr(0,2); // "He"
int idx = s.find("ll"); // 2Two Pointer Approach:
1. Initialize left = 0 and right = n - 1.
2. While left < right:
- If s[left] != s[right], return false.
- Increment left, Decrement right.
3. If loop finishes, return true.
bool isPalindrome(string s) {
int l = 0, r = s.length() - 1;
while (l < r) {
if (s[l] != s[r]) return false;
l++;
r--;
}
return true;
}The KMP Solution:
KMP uses an LPS (Longest Prefix Suffix) array to skip unnecessary comparisons.
- LPS[i] tells us the length of the longest proper prefix that is also a suffix.
- If we mismatch at index j, we don't start over. We jump j to LPS[j-1].
Time Complexity: O(N + M) (Linear Time!)
// Compute LPS
vector<int> computeLPS(string& pat) {
int m = pat.size();
vector<int> lps(m, 0);
int len = 0, i = 1;
while(i < m) {
if(pat[i] == pat[len]) {
lps[i++] = ++len;
} else {
if(len != 0) len = lps[len-1];
else lps[i++] = 0;
}
}
return lps;
}Concept:
1. Compute the Hash of the pattern.
2. Compute the Hash of the current window in text.
3. If Hashes match, compare actual characters (to avoid collisions).
4. Rolling Hash: Update the window hash in O(1) by subtracting the leaving char and adding the entering char.
Why use it?
Great for multiple pattern search (Plagiarism detection).
// Rolling Hash Formula
hash(s) = (s[0]*p^(n-1) + ... + s[n-1]*p^0) % MOD
// Update Hash
newHash = (oldHash - oldChar*bigPower) * p + newCharApproaches:
1. Sorting: Sort both strings and compare. Time: O(N log N).
2. Frequency Array: Use an array of size 26 (for 'a'-'z') to count frequencies.
- Increment for string 1.
- Decrement for string 2.
- If all counts are 0, they are anagrams. Time: O(N).
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
vector<int> count(26, 0);
for (char c : s) count[c - 'a']++;
for (char c : t) count[c - 'a']--;
for (int i : count) if (i != 0) return false;
return true;
}Application:
To search pattern P in text T:
1. Concatenate: S = P + "$" + T
2. Compute Z-array for S.
3. If Z[i] == P.length(), then pattern occurs at that position.
It is an alternative to KMP, often simpler to implement for certain problems.
// Z-Function Logic
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = min(r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]])
++z[i];
if (i + z[i] - 1 > r)
l = i, r = i + z[i] - 1;
}