? Top 10 String & Pattern Matching
? Top 10 String & Pattern Matching
Given a string S, reverse the order of words without reversing individual words.
Determine if a given string S is a palindrome (reads the same forward and backward).
Given two strings S1 and S2, check if they are anagrams (contain the same characters in any order).
Given a string S and a pattern P, implement KMP (Knuth-Morris-Pratt) algorithm to find all
occurrences of P in S efficiently.
Given a string S and a pattern P, implement Rabin-Karp algorithm to search for P in S using hashing.
Given an array of strings, find the longest common prefix among them.
Given a text S and pattern P, use Z-Algorithm to efficiently find all occurrences of P in S.
Construct a suffix array for a given string S, which helps in efficient pattern matching.
📌 10. Find the Longest Repeated Substring Using Suffix Arrays & LCP
Asked in: Google, Facebook, Microsoft
Given a string S, find the longest repeated substring using suffix arrays and LCP (Longest Common
Prefix).
📌 1. Reverse Words in a String Asked in: Amazon, Google, TCS Given a string S,
reverse the order of words without reversing individual words.
C++ Solution
#include <bits/stdc++.h>
using namespace std;
string reverseWords(string s) {
stringstream ss(s);
string word, result = "";
vector<string> words;
reverse([Link](), [Link]());
int main() {
string s = "Hello World from Syntax Error";
cout << reverseWords(s) << endl;
return 0;
}
Java Solution
import [Link].*;
Python Solution
def reverse_words(s):
words = [Link]()
return " ".join(reversed(words))
# Example usage
s = "Hello World from Syntax Error"
print(reverse_words(s))
Determine if a given string S is a palindrome (reads the same forward and backward).
C++ Solution
#include <bits/stdc++.h>
using namespace std;
string reverseWords(string s) {
stringstream ss(s);
string word, result = "";
vector<string> words;
reverse([Link](), [Link]());
int main() {
string s = "Hello World from Syntax Error";
cout << reverseWords(s) << endl;
return 0;
}
Java Solution
import [Link].*;
Python Solution
def reverse_words(s):
words = [Link]()
return " ".join(reversed(words))
# Example usage
s = "Hello World from Syntax Error"
print(reverse_words(s))
Given two strings S1 and S2, check if they are anagrams (contain the same characters in any order).
C++ Solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s1 = "listen", s2 = "silent";
if (areAnagrams(s1, s2))
cout << "Anagrams" << endl;
else
cout << "Not Anagrams" << endl;
return 0;
}
Java Solution
import [Link];
Python Solution
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)
# Example usage
s1, s2 = "listen", "silent"
if are_anagrams(s1, s2):
print("Anagrams")
else:
print("Not Anagrams")
string longestPalindrome(string s) {
if ([Link]()) return "";
string longest = "";
for (int i = 0; i < [Link](); i++) {
string odd = expandFromCenter(s, i, i); // Odd-length
palindrome
string even = expandFromCenter(s, i, i + 1); // Even-length
palindrome
if ([Link]() > [Link]()) longest = odd;
if ([Link]() > [Link]()) longest = even;
}
return longest;
}
int main() {
string s = "babad";
cout << "Longest Palindromic Substring: " << longestPalindrome(s) <<
endl;
return 0;
}
def longest_palindrome(s):
longest = ""
for i in range(len(s)):
odd = expand_from_center(s, i, i) # Odd-length palindrome
even = expand_from_center(s, i, i + 1) # Even-length palindrome
longest = max(longest, odd, even, key=len)
return longest
# Example usage
s = "babad"
print("Longest Palindromic Substring:", longest_palindrome(s))
Given a string S and a pattern P, implement KMP (Knuth-Morris-Pratt) algorithm to find all occurrences of P
in S efficiently
C++ Solution
#include <bits/stdc++.h>
using namespace std;
while (i < m) {
if (pattern[i] == pattern[len]) {
lps[i++] = ++len;
} else {
if (len) len = lps[len - 1];
else lps[i++] = 0;
}
}
return lps;
}
int main() {
string text = "ababcababcabc", pattern = "abc";
KMP(text, pattern);
return 0;
}
Java Solution
import [Link].*;
while (i < m) {
if ([Link](i) == [Link](len)) {
lps[i++] = ++len;
} else {
len = (len != 0) ? lps[len - 1] : 0;
if (len == 0) lps[i++] = 0;
}
}
return lps;
}
int i = 0, j = 0;
while (i < n) {
if ([Link](i) == [Link](j)) {
i++; j++;
}
if (j == m) {
[Link]("Pattern found at index " + (i - j));
j = lps[j - 1];
} else if (i < n && [Link](i) != [Link](j)) {
j = (j != 0) ? lps[j - 1] : i++;
}
}
}
Python Solution
def compute_lps(pattern):
m = len(pattern)
lps = [0] * m
length, i = 0, 1
while i < m:
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
return lps
i, j = 0, 0
while i < n:
if text[i] == pattern[j]:
i, j = i + 1, j + 1
if j == m:
print(f"Pattern found at index {i - j}")
j = lps[j - 1]
elif i < n and text[i] != pattern[j]:
j = lps[j - 1] if j != 0 else i + 1
# Example Usage
text, pattern = "ababcababcabc", "abc"
kmp(text, pattern)
Given a string S and a pattern P, implement Rabin-Karp algorithm to search for P in S using hashing.
C++ Solution
#include <bits/stdc++.h>
using namespace std;
long long recalculateHash(string str, int oldIndex, int newIndex, long long
oldHash, int patternLength) {
oldHash -= str[oldIndex];
oldHash /= PRIME;
oldHash += str[newIndex] * pow(PRIME, patternLength - 1);
return oldHash;
}
if (i < n - m)
textHash = recalculateHash(text, i, i + m, textHash, m);
}
}
int main() {
string text = "ababcabcabc", pattern = "abc";
RabinKarp(text, pattern);
return 0;
}
Java Solution
import [Link].*;
if (i < n - m)
textHash = recalculateHash(text, i, i + m, textHash, m);
}
}
Python Solution
PRIME = 101 # Prime number for hashing
if i < n - m:
text_hash = recalculate_hash(text, i, i + m, text_hash, m)
# Example Usage
text, pattern = "ababcabcabc", "abc"
rabin_karp(text, pattern)
Given an array of strings, find the longest common prefix among them.
int main() {
vector<string> strs = {"flower", "flow", "flight"};
cout << "Longest Common Prefix: " << longestCommonPrefix(strs) << endl;
return 0;
}
prefix = strs[0]
for s in strs[1:]:
while not [Link](prefix):
prefix = prefix[:-1]
if not prefix:
return ""
return prefix
# Example Usage
strs = ["flower", "flow", "flight"]
print("Longest Common Prefix:", longest_common_prefix(strs))
Given a text S and pattern P, use Z-Algorithm to efficiently find all occurrences of P in S.
C++ Solution
#include <bits/stdc++.h>
using namespace std;
if (i + Z[i] - 1 > R) {
L = i;
R = i + Z[i] - 1;
}
}
return Z;
}
int main() {
string text = "ababcababcab";
string pattern = "abc";
return 0;
}
Java Solution
import [Link].*;
if (i + Z[i] - 1 > R) {
L = i;
R = i + Z[i] - 1;
}
}
return Z;
}
Python Solution
def compute_z(s):
n = len(s)
Z = [0] * n
L, R = 0, 0
if i + Z[i] - 1 > R:
L, R = i, i + Z[i] - 1
return Z
return occurrences
# Example usage
text = "ababcababcab"
pattern = "abc"
result = find_pattern(text, pattern)
for index in result:
print(f"Pattern found at index: {index}")
📌 9. Build a Suffix Array for a Given String
Asked in: Google, Microsoft, Amazon
Construct a suffix array for a given string S, which helps in efficient pattern matching.
C++ Solution
#include <bits/stdc++.h>
using namespace std;
// Update ranks
tempRank[suffixArray[0]] = 0;
for (int i = 1; i < n; i++) {
tempRank[suffixArray[i]] = tempRank[suffixArray[i - 1]] +
cmp(suffixArray[i - 1], suffixArray[i]);
}
rank = tempRank;
}
return suffixArray;
}
// Driver Code
int main() {
string s = "banana";
vector<int> suffixArray = buildSuffixArray(s);
return 0;
}
Java Solution
import [Link].*;
public class SuffixArray {
// Function to build suffix array
public static int[] buildSuffixArray(String s) {
int n = [Link]();
Integer[] suffixArray = new Integer[n];
int[] rank = new int[n];
int[] tempRank = new int[n];
// Update ranks
tempRank[suffixArray[0]] = 0;
for (int i = 1; i < n; i++) {
tempRank[suffixArray[i]] = tempRank[suffixArray[i - 1]] +
(rank[suffixArray[i - 1]] != rank[suffixArray[i]]
||
((suffixArray[i - 1] + length < n ?
rank[suffixArray[i - 1] + length] : -1) !=
(suffixArray[i] + length < n ? rank[suffixArray[i]
+ length] : -1)) ? 1 : 0);
}
rank = [Link](tempRank, n);
}
return
[Link](suffixArray).mapToInt(Integer::intValue).toArray();
}
// Driver Code
public static void main(String[] args) {
String s = "banana";
int[] suffixArray = buildSuffixArray(s);
Python Solution
def build_suffix_array(s):
n = len(s)
suffix_array = list(range(n))
rank = list(map(ord, s))
temp_rank = [0] * n
# Update ranks
temp_rank[suffix_array[0]] = 0
for i in range(1, n):
prev = suffix_array[i - 1]
curr = suffix_array[i]
temp_rank[curr] = temp_rank[prev] + (
rank[prev] != rank[curr] or
(rank[prev + length] if prev + length < n else -1) !=
(rank[curr + length] if curr + length < n else -1)
)
rank = temp_rank[:]
length *= 2
return suffix_array
# Example usage
s = "banana"
suffix_array = build_suffix_array(s)
print("Suffix Array:", suffix_array)
📌 10. Find the Longest Repeated Substring Using Suffix Arrays & LCP
Asked in: Google, Facebook, Microsoft
Given a string S, find the longest repeated substring using suffix arrays and LCP (Longest Common
Prefix).
C++ Solution
#include <bits/stdc++.h>
using namespace std;
// Update ranks
tempRank[suffixArray[0]] = 0;
for (int i = 1; i < n; i++) {
tempRank[suffixArray[i]] = tempRank[suffixArray[i - 1]] +
cmp(suffixArray[i - 1], suffixArray[i]);
}
rank = tempRank;
}
return suffixArray;
}
int h = 0;
for (int i = 0; i < n; i++) {
if (rank[i] > 0) {
int j = suffixArray[rank[i] - 1];
while (i + h < n && j + h < n && s[i + h] == s[j + h]) {
h++;
}
lcp[rank[i]] = h;
if (h > 0) h--;
}
}
return lcp;
}
// Driver Code
int main() {
string s = "banana";
string result = longestRepeatedSubstring(s);
cout << "Longest Repeated Substring: " << result << endl;
return 0;
}
Java Solution
import [Link].*;
// Update ranks
tempRank[suffixArray[0]] = 0;
for (int i = 1; i < n; i++) {
tempRank[suffixArray[i]] = tempRank[suffixArray[i - 1]] +
(rank[suffixArray[i - 1]] != rank[suffixArray[i]]
||
((suffixArray[i - 1] + length < n ?
rank[suffixArray[i - 1] + length] : -1) !=
(suffixArray[i] + length < n ? rank[suffixArray[i]
+ length] : -1)) ? 1 : 0);
}
rank = [Link](tempRank, n);
}
return
[Link](suffixArray).mapToInt(Integer::intValue).toArray();
}
// Driver Code
public static void main(String[] args) {
String s = "banana";
String result = longestRepeatedSubstring(s);
[Link]("Longest Repeated Substring: " + result);
}
}
Python Solution
def build_suffix_array(s):
n = len(s)
suffix_array = sorted(range(n), key=lambda i: s[i:])
return suffix_array
h = 0
for i in range(n):
if rank[i] > 0:
j = suffix_array[rank[i] - 1]
while i + h < n and j + h < n and s[i + h] == s[j + h]:
h += 1
lcp[rank[i]] = h
if h > 0:
h -= 1
return lcp
def longest_repeated_substring(s):
suffix_array = build_suffix_array(s)
lcp = build_lcp_array(s, suffix_array)
max_length = max(lcp)
index = [Link](max_length)
return s[suffix_array[index]:suffix_array[index] + max_length]
# Example usage
s = "banana"
print("Longest Repeated Substring:", longest_repeated_substring(s))
🎉 Congratulations! 🎉
You've successfully completed this PDF and taken one step closer to mastering coding
challenges! Your dedication and hard work will surely pay off. Keep pushing your limits and
sharpening your skills! 💻🔥
For more coding content, problem-solving techniques, and valuable insights, follow
@SYNTAX_ERROR on Instagram! 🚀📚