Skip to content

Commit eb257fe

Browse files
committed
max product word length
1 parent 689831b commit eb257fe

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.interview.bits;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Date 04/21/2016
7+
* @author Tushar Roy
8+
*
9+
* Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words
10+
* do not share common letters. You may assume that each word will contain only lower case letters.
11+
* If no such two words exist, return 0.
12+
*
13+
* Space complexity O(n)
14+
* Time complexity O(n^2)
15+
*
16+
* https://leetcode.com/problems/maximum-product-of-word-lengths/
17+
*/
18+
public class MaxProductWordLength {
19+
public int maxProduct(String[] words) {
20+
int max = 0;
21+
22+
Arrays.sort(words, (a, b) -> b.length() - a.length());
23+
24+
int[] masks = new int[words.length]; // alphabet masks
25+
26+
for(int i = 0; i < masks.length; i++){
27+
for(char c: words[i].toCharArray()){
28+
masks[i] |= 1 << (c - 'a');
29+
}
30+
}
31+
32+
for(int i = 0; i < masks.length; i++){
33+
if(words[i].length() * words[i].length() <= max) {
34+
break; //prunning
35+
}
36+
for(int j = i + 1; j < masks.length; j++){
37+
if((masks[i] & masks[j]) == 0){
38+
max = Math.max(max, words[i].length() * words[j].length());
39+
break; //prunning
40+
}
41+
}
42+
}
43+
44+
return max;
45+
}
46+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.interview.bits;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
public class MaxProductWordLengthTest {
7+
8+
@Test
9+
public void testDifferentCases() {
10+
MaxProductWordLength maxProductWordLength = new MaxProductWordLength();
11+
String[] words1 = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"};
12+
Assert.assertEquals(16, maxProductWordLength.maxProduct(words1));
13+
14+
String[] words2 = {"a", "ab", "abc", "d", "cd", "bcd", "abcd"};
15+
Assert.assertEquals(4, maxProductWordLength.maxProduct(words2));
16+
}
17+
}

0 commit comments

Comments
 (0)