Using word pairs from a dictionary without common letters, find a pair that maximizes the sum of the words β€œlength”

Question:

Using word pairs from a dictionary without common letters, find a pair that maximizes the sum of the words β€œlength”

Dictionary example: mouse, cow, compound, key, dog

dog and do not have common letters and have the sum of 3 + 3 = 6

the mouse does not work with cows , join or a dog because they all share the letter 'o

join and do not have common letters and have a sum of 4 + 3 = 7

I had this question in an interview, my solution that I came up with is outlined below. I was wondering if there is a way to make it more efficient? I used two BitSetsto match the two-word alphabet and AND together to see if they contain the same letters. I believe my algorithm has o (n!) Complexity, 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
+4
source share
2 answers

You can do this in O (N ^ 2 * 26) (26 represents the number of characters in your dictionary, probably the English alphabet).

FIRST Create an array of 2D bool, D [i] [j].

i is an integer

j - 'a' 'z' ( ASCII )

D [i] [j] = 1, , i, j, D [i] [j] = 0;

, 2D-, , ( , ). , .

0

, O(n*avg), , , O(n*avg+a*2^a), a - , n - , avg - , . , , , , . , SOWPODS, Scrabble, 267000 . Quora.

w l (w) s (w).

2 ^ - , , w s (w) l (w).

2 ^ - , . O(a*2^a), k k k-1 . , k-1 .

, , , , .

, - . 20 - Q, X, J Z, , , . , , r , . O(n*avg+(a-b)2^(a-b)). , O(r^2*a). , , , r , , . O(r*avg), . , , O(n*avg+(a-b)2^(a-b)+r^2*avg). , , , .

0

All Articles