Leetcode 3042. Count Prefix and Suffix Pairs I
You are given two arrays of strings words1
and words2
. A string words1[i]
from words1
is a prefix of a string words2[j]
from words2
if they both share the same starting characters. Similarly, words1[i]
is a suffix of words2[j]
if they both share the same ending characters.
Return the number of pairs (i, j)
such that words1[i]
is a prefix or a suffix of words2[j]
.
Example:
Input: words1 = ["a", "abc"], words2 = ["abcdef", "abc", "de"]
Output: 4
Explanation: There are 4 pairs: (0, 0), (0, 1), (1, 0), (1, 1)
- "a" is a prefix of "abcdef"
- "a" is a prefix of "abc"
- "abc" is a prefix of "abcdef"
- "abc" is a prefix of "abc"
words1
or words2
be empty?words1
and for each word, iterate through each word in words2
.(i, j)
, check:
words1[i]
is a prefix of words2[j]
words1[i]
is a suffix of words2[j]
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// Helper function to check if a is a prefix of b
bool isPrefix(const string &a, const string &b) {
if (a.size() > b.size()) return false;
return b.compare(0, a.size(), a) == 0;
}
// Helper function to check if a is a suffix of b
bool isSuffix(const string &a, const string &b) {
if (a.size() > b.size()) return false;
return b.compare(b.size() - a.size(), a.size(), a) == 0;
}
int countPrefixSuffixPairs(const vector<string> &words1, const vector<string> &words2) {
int count = 0;
for (const string &w1 : words1) {
for (const string &w2 : words2) {
if (isPrefix(w1, w2) || isSuffix(w1, w2)) {
count++;
}
}
}
return count;
}
int main() {
vector<string> words1 = {"a", "abc"};
vector<string> words2 = {"abcdef", "abc", "de"};
int result = countPrefixSuffixPairs(words1, words2);
cout << "Count of prefix and suffix pairs: " << result << endl;
return 0;
}
Let’s denote the length of words1
as m
and the length of words2
as n
. Also, let L
denote the average length of the strings in words1
and words2
.
O(m * n)
iterations.O(L)
time.Thus, the time complexity is O(m * n * L)
.
This means the function can efficiently handle typical input sizes encountered in practical scenarios while ensuring correctness.
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?