Maximum product of word lengths in Java

Given string array words, find the maximum value of length(word[i])*length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
package com.algorithm.length;

public class WordsLength {

    public static void main(String[] args) {
        String str[] = {"abc","def"};

    public static int maxProduct(String[] words) {
        if(words==null || words.length==0)
            return 0;
        int[] arr = new int[words.length];
        for(int i=0; i<words.length; i++){
            for(int j=0; j<words[i].length(); j++){
                char c = words[i].charAt(j);
                arr[i] |= (1 << (c-'a'));
        int result = 0;
        for(int i=0; i<words.length; i++){
            for(int j=i+1; j<words.length; j++){
                if((arr[i] & arr[j]) == 0){
                    result = Math.max(result, words[i].length()*words[j].length());
        return result;

Test Cases:
1. We have passed two words are “abc” and “def”. Those words don’t have any common letters. So, the output will be 9.
2. If we pass any words which have any common letters, the program has to return 0.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s