Leetcode 2744. Find Maximum Number of String Pairs
The problem requires finding the maximum number of string pairs (s1, s2)
in a given array of strings such that one string is the reverse of the other. Each string can be paired with at most one other string. The aim is to return the maximum number of such pairs.
To ensure a clear understanding of the problem, here are some questions that could be asked:
Assuming standard constraints: the input can be a mixture of uppercase and lowercase letters and the comparisons are case-sensitive. The constraints are such that we can efficiently handle them in typical coding interview settings.
Here’s how the implementation might look in C++:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
int findMaxStringPairs(vector<string>& strings) {
unordered_map<string, int> stringCount;
int pairCount = 0;
// Populate the hash map with the count of each string
for (const string& str : strings) {
stringCount[str]++;
}
// Iterate through each string to find pairs
for (const string& str : strings) {
string reversedStr = str;
reverse(reversedStr.begin(), reversedStr.end());
// Check if this string can form a valid pair
if (stringCount[str] > 0 && stringCount[reversedStr] > 0) {
// Skip if they are the same string but there is only one instance of it
if (str == reversedStr && stringCount[str] < 2) {
continue;
}
// Form a pair and decrease the count
pairCount++;
stringCount[str]--;
stringCount[reversedStr]--;
}
}
return pairCount;
}
int main() {
vector<string> strings = {"ab", "ba", "abc", "cba", "xy", "yx", "z", "zz"};
cout << "Maximum number of string pairs: " << findMaxStringPairs(strings) << endl;
return 0;
}
Therefore, the overall time complexity is O(N * M), which is generally efficient for typical constraints found in coding interviews.
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?