Leetcode 3042. Count Prefix and Suffix Pairs I
Given two strings s1
and s2
, you are asked to count the number of pairs (i, j)
such that the prefix of s1
ending at index i
and the suffix of s2
starting at index j
are the same. Note that a prefix of s1
ending at index i
is the substring of s1
from the start up to i
, and a suffix of s2
starting at index j
is the substring of s2
from j
to the end.
s1
and s2
can be of any length within typical constraints.s1
.s2
.s1
and check if they appear as suffixes in s2
.import java.util.HashMap;
import java.util.Map;
public class Solution {
public int countPrefixSuffixPairs(String s1, String s2) {
// Edge cases
if (s1 == null || s2 == null || s1.length() == 0 || s2.length() == 0) {
return 0;
}
// Maps to store the counts of prefixes and suffixes
Map<String, Integer> prefixMap = new HashMap<>();
Map<String, Integer> suffixMap = new HashMap<>();
// Populate prefix map
for (int i = 0; i < s1.length(); i++) {
String prefix = s1.substring(0, i + 1);
prefixMap.put(prefix, prefixMap.getOrDefault(prefix, 0) + 1);
}
// Populate suffix map
for (int j = s2.length() - 1; j >= 0; j--) {
String suffix = s2.substring(j);
suffixMap.put(suffix, suffixMap.getOrDefault(suffix, 0) + 1);
}
// Count matching prefix-suffix pairs
int count = 0;
for (Map.Entry<String, Integer> entry : prefixMap.entrySet()) {
String prefix = entry.getKey();
if (suffixMap.containsKey(prefix)) {
count += entry.getValue() * suffixMap.get(prefix);
}
}
return count;
}
public static void main(String[] args) {
Solution solution = new Solution();
String s1 = "abcde";
String s2 = "cdeabc";
System.out.println(solution.countPrefixSuffixPairs(s1, s2)); // Output: 3
}
}
s1
and suffixes of s2
both take O(n) where n
is the length of the string.n
prefixes and m
suffixes for strings of length n
and m
respectively.n
is the length of s1
and m
is the length of s2
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?