Question:
Using pairs of words from a dictionary with no letters in common, find a pair that maximizes the sum of the words' lengths
Example Dictionary: mouse, cow, join, key, dog
dog and key share no letters and have a sum of 3+3 = 6
mouse does not work with cow, join, or dog because they all share the letter 'o'
join and key share no letters and have a sum of 4+3 = 7
I had this question in an interview, my solution I came up with is outlined below. I was wondering if there is any way to make it more efficient? I used two BitSets
to map the alphabet of two words and AND them together to see if they contain the same letters. I think my algorithm has a complexity is o(n!) which is inefficient, is there a better way to optimize my algorithm?
public static void maximumSum (String[] dictionary) {
// ascii of a = 97
BitSet word1 = new BitSet(26);
BitSet word2 = new BitSet(26);
String maxWord1 = "";
String maxWord2 = "";
int maxSum = -1;
for(int i = 0; i<dictionary.length; i++) {
for(int j = i+1; j<dictionary.length; j++) {
String s1 = dictionary[i];
String s2 = dictionary[j];
for(int k = 0; k<s1.length(); k++) {
word1.set(s1.charAt(k)-97);
}
for(int k = 0; k<s2.length(); k++) {
word2.set(s2.charAt(k)-97);
}
word1.and(word2);
if(word1.cardinality() == 0) {
if(maxSum < s1.length()+s2.length()) {
maxWord1 = s1;
maxWord2 = s2;
maxSum = s1.length()+s2.length();
}
}
word1.clear();
word2.clear();
}
}
if(maxSum == -1)
System.out.println("All the words have letters in common.");
else
System.out.println("'"+maxWord1+"' and '"+maxWord2+"'
have a maximum sum of "+maxSum);
}
public static void main(String[] args) {
String[] dictionary = {"mouse", "cow", "join", "key", "dog"};
maximumSum(dictionary);
}
output:
'join' and 'key' have a maximum sum of 7