Leetcode 2744. Find Maximum Number of String Pairs
You are given an array of strings words
. Each string in words
is a pair of lowercase English letters.
A pair of two different strings from words
is a special substring if they have no common characters.
Return the maximum number of special substrings from the input array words
.
words
?Input: words = ["ab", "bc", "cd", "de"]
Output: 2
import java.util.HashSet;
import java.util.Set;
public class MaximumStringPairs {
public int maxSpecialSubstrings(String[] words) {
int maxPairs = 0;
for (int i = 0; i < words.length - 1; i++) {
for (int j = i + 1; j < words.length; j++) {
if (noCommonCharacters(words[i], words[j])) {
maxPairs++;
}
}
}
return maxPairs;
}
private boolean noCommonCharacters(String word1, String word2) {
Set<Character> charsInWord1 = new HashSet<>();
for (char c : word1.toCharArray()) {
charsInWord1.add(c);
}
for (char c : word2.toCharArray()) {
if (charsInWord1.contains(c)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
MaximumStringPairs solution = new MaximumStringPairs();
String[] words = {"ab", "bc", "cd", "de"};
System.out.println(solution.maxSpecialSubstrings(words)); // Output: 2
}
}
The time complexity of the solution can be analyzed as follows:
words.length - 1
.Thus, the overall time complexity is O(n^2), where n
is the length of the words
array.
This solution ensures that all possible pairs are checked optimally without additional space complexity considerations beyond the fixed-length input strings.
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?