Open In App

Maximize product of lengths of strings having no common characters

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N strings, the task is to find the maximum product of the length of the strings arr[i] and arr[j] for all unique pairs (i, j), where the strings arr[i] and arr[j] contain no common characters.

Examples: 

Input: arr[] = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"}
Output: 16
Explanation: The strings "abcw" and "xtfn" have no common characters in it. Therefore, the product of the length of both the strings = 4 * 4 = 16, which is maximum among all possible pairs.

Input: arr[] = {"a", "aa", "aaa", "aaaa"}
Output: 0

Naive Approach: The idea is to generate all the pairs of strings and use a map to find the common character between them, if there are no common character between them, then use the product of their length to maximize the result.

Follow the steps below to implement the above idea:

  • Generate all pairs of strings say, s1 and s2.
  • Use a map to find the common character between the strings s1 and s2.
  • Check if there is any common character between them:
    • If there is no common character between them then use the product of their length and maximize the result.
  • Finally, return the result.

Below is the implementation of the above approach:

C++
// C++ program to find the find the maximum product of the
// length of the strings arr[i] and arr[j] for all unique
// pairs (i, j), where the strings arr[i] and arr[j] contain
// no common characters.
#include <bits/stdc++.h>
using namespace std;

// Function to find the maximum product of the length of the
// strings
int maximizeProduct(vector<string>& arr)
{
    int n = arr.size();

    // This store the maximum product of string's length
    int result = 0;

    // Iterate to find the 1st string
    for (int i = 0; i < n; i++) {
        string s1 = arr[i];
        int len1 = arr[i].size();

        // Map to store the unique character
        unordered_map<char, int> unmap;
        for (auto c1 : s1)
            unmap[c1]++;

        // Iterate to find the 2nd string
        for (int j = i + 1; j < n; j++) {
            string s2 = arr[j];
            int len2 = arr[j].size();

            bool flag = false;

            for (int k = 0; k < s2.size(); k++) {

                // Check if the characters of s2 are common
                // with s1 characters or not
                if (unmap.count(s2[k])) {
                    flag = true;
                    break;
                }
            }

            // This verify that there is no common character
            // between s1 and s2.
            if (flag == false) {
                result = max(result, len1 * len2);
            }
        }
    }

    return result;
}

// Driver code
int main()
{
    vector<string> arr
        = { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" };

    int result = maximizeProduct(arr);

    // Print the output
    cout << result;

    return 0;
}
Java
/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;

class GFG {
    // Java program to find the find the maximum product of
    // the length of the strings arr[i] and arr[j] for all
    // unique pairs (i, j), where the strings arr[i] and
    // arr[j] contain no common characters.

    // Function to find the maximum product of the length of
    // the strings
    static int maximizeProduct(String[] arr)
    {
        int n = arr.length;

        // This store the maximum product of string's length
        int result = 0;

        // Iterate to find the 1st string
        for (int i = 0; i < n; i++) {
            String s1 = arr[i];
            int len1 = arr[i].length();

            // Map to store the unique character
            HashMap<Character, Integer> unmap
                = new HashMap<>();
            for (char c : s1.toCharArray()) {
                if (unmap.containsKey(c)) {
                    unmap.put(c, unmap.get(c) + 1);
                }
                else
                    unmap.put(c, 1);
            }
            // Iterate to find the 2nd string
            for (int j = i + 1; j < n; j++) {
                String s2 = arr[j];
                int len2 = arr[j].length();

                boolean flag = false;

                for (int k = 0; k < s2.length(); k++) {

                    // Check if the characters of s2 are
                    // common with s1 characters or not
                    if (unmap.containsKey(s2.charAt(k))) {
                        flag = true;
                        break;
                    }
                }

                // This verify that there is no common
                // character between s1 and s2.
                if (flag == false) {
                    result = Math.max(result, len1 * len2);
                }
            }
        }

        return result;
    }

    // Driver Code
    public static void main(String args[])
    {
        String[] arr = { "abcw", "baz",  "foo",
                         "bar",  "xtfn", "abcdef" };

        int result = maximizeProduct(arr);

        // Print the output
        System.out.println(result);
    }
}
Python
# Python3 program to find the find the maximum product of the
# length of the strings arr[i] and arr[j] for all unique
# pairs (i, j), where the strings arr[i] and arr[j] contain
# no common characters.

# Function to find the maximum product of the length of the
# strings


def maximizeProduct(arr):

    n = len(arr)

    # This store the maximum product of string's length
    result = 0

    # Iterate to find the 1st string
    for i in range(n):
        s1 = arr[i]
        len1 = len(arr[i])

        # Map to store the unique character
        unmap = {}
        for c in s1:
            if(c in unmap):
                unmap[c] += 1

            unmap[c] = 1

        # Iterate to find the 2nd string
        for j in range(i+1, n):
            s2 = arr[j]
            len2 = len(arr[j])

            flag = False

            for k in range(len(s2)):

                # Check if the characters of s2 are common
                # with s1 characters or not
                if (s2[k] in unmap):
                    flag = True
                    break

            # This verify that there is no common character
            # between s1 and s2.
            if (flag == False):
                result = max(result, len1 * len2)

    return result


# Driver code
arr = ["abcw", "baz",  "foo",  "bar",  "xtfn", "abcdef"]
result = maximizeProduct(arr)

# Print the output
print(result)

# This code is contributed by shinjanpatra
C#
// C# program to find the find the maximum product of the
// length of the strings arr[i] and arr[j] for all unique
// pairs (i, j), where the strings arr[i] and arr[j] contain
// no common characters.
using System;
using System.Collections.Generic;

public class Test {

    // Function to find the maximum product of the length of
    // the strings
    static int maximizeProduct(List<string> arr)
    {
        int n = arr.Count;

        // This store the maximum product of string's length
        int result = 0;

        // Iterate to find the 1st string
        for (int i = 0; i < n; i++) {
            string s1 = arr[i];
            int len1 = arr[i].Length;

            // Map to store the unique character
            Dictionary<char, int> unmap
                = new Dictionary<char, int>();
            foreach(char c in s1)
            {
                if (unmap.ContainsKey(c))
                    unmap[c]++;
                else
                    unmap.Add(c, 1);
            }

            // Iterate to find the 2nd string
            for (int j = i + 1; j < n; j++) {
                string s2 = arr[j];
                int len2 = arr[j].Length;
                bool flag = false;
                for (int k = 0; k < s2.Length; k++) {

                    // Check if the characters of s2 are
                    // common with s1 characters or not
                    if (unmap.ContainsKey(s2[k])) {
                        flag = true;
                        break;
                    }
                }

                // This verify that there is no common
                // character between s1 and s2.
                if (flag == false) {
                    result = Math.Max(result, len1 * len2);
                }
            }
        }
        return result;
    }

    // Driver code
    public static void Main()
    {
        List<string> arr
            = new List<string>{ "abcw", "baz",  "foo",
                                "bar",  "xtfn", "abcdef" };
        int result = maximizeProduct(arr);

        // Print the output
        Console.WriteLine(result);
    }
}

// This code is contributed by ishankhandelwals.
JavaScript
<script>

// JavaScript program to find the find the maximum product of the
// length of the strings arr[i] and arr[j] for all unique
// pairs (i, j), where the strings arr[i] and arr[j] contain
// no common characters.

// Function to find the maximum product of the length of the
// strings
function maximizeProduct(arr)
{
    let n = arr.length;

    // This store the maximum product of string's length
    let result = 0;

    // Iterate to find the 1st string
    for (let i = 0; i < n; i++) {
        let s1 = arr[i];
        let len1 = arr[i].length;

        // Map to store the unique character
        let unmap = new Map();
        for (let c of s1){
            if(unmap.has(c)){
                unmap.set(c,unmap.get(c)+1);
            }
            unmap.set(c,1);
        }

        // Iterate to find the 2nd string
        for (let j = i + 1; j < n; j++) {
            let s2 = arr[j];
            let len2 = arr[j].length;

            let flag = false;

            for (let k = 0; k < s2.length; k++) {

                // Check if the characters of s2 are common
                // with s1 characters or not
                if (unmap.has(s2[k])) {
                    flag = true;
                    break;
                }
            }

            // This verify that there is no common character
            // between s1 and s2.
            if (flag == false) {
                result = Math.max(result, len1 * len2);
            }
        }
    }

    return result;
}

// Driver code
let arr = [ "abcw", "baz",  "foo",  "bar",  "xtfn", "abcdef" ];
let result = maximizeProduct(arr);

// Print the output
document.write(result,"</br>");

// This code is contributed by shinjanpatra

</script>

Output
16

Time Complexity: O(N2 * M), where M is the maximum length of the string.
Auxiliary Space: O(M)

Optimized Approach for Maximizing Product of Lengths of Strings with No Common Characters

Bitmasking and Efficient Pairing

To optimize the naive approach, we can use bitmasking to represent the characters of each string. This allows us to quickly check for common characters between two strings by using bitwise operations.

Explanation:

  • Bitmask Representation: Each string is represented by a 26-bit integer where each bit corresponds to a character (from 'a' to 'z'). If a character is present in the string, the corresponding bit is set to 1.
  • Preprocessing: Convert each string in the array to its bitmask representation and store it along with its length.
  • Efficient Pair Checking: Use the bitmask representation to check for common characters between pairs of strings using bitwise AND operation. If the result is zero, the strings have no common characters.
C++
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

// Function to calculate the bitmask for a given string
int getBitmask(const std::string& s)
{
    int bitmask = 0;
    for (char ch : s) {
        // Update bitmask with the position of the character
        bitmask |= 1 << (ch - 'a');
    }
    return bitmask;
}

// Function to find the maximum product of the lengths of
// two strings that do not share any common characters
int maximizeProduct(const std::vector<std::string>& arr)
{
    int n = arr.size();
    std::vector<std::pair<int, int> > bitmaskLengthPairs;

    // Preprocess strings to bitmask and lengths
    for (const auto& str : arr) {
        int bitmask = getBitmask(str);
        int length = str.length();
        bitmaskLengthPairs.push_back({ bitmask, length });
    }

    int maxProduct = 0;

    // Iterate over all unique pairs of strings
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            int bitmask1 = bitmaskLengthPairs[i].first;
            int len1 = bitmaskLengthPairs[i].second;
            int bitmask2 = bitmaskLengthPairs[j].first;
            int len2 = bitmaskLengthPairs[j].second;

            // Check if they have no common characters
            if ((bitmask1 & bitmask2) == 0) {
                // Update maxProduct if the product of
                // lengths is greater
                maxProduct
                    = std::max(maxProduct, len1 * len2);
            }
        }
    }

    return maxProduct;
}

int main()
{
    std::vector<std::string> arr
        = { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" };
    int result = maximizeProduct(arr);
    std::cout << result << std::endl; // Output the result
    return 0;
}
Java
public class MaximizeProduct {

    // Helper function to convert a string to a bitmask
    private static int getBitmask(String s)
    {
        int bitmask = 0;
        for (char c : s.toCharArray()) {
            bitmask |= 1 << (c - 'a');
        }
        return bitmask;
    }

    public static int maximizeProduct(String[] arr)
    {
        int n = arr.length; // Get the length of the input
                            // array
        int[][] bitmaskLengthPairs
            = new int[n][2]; // Array to store bitmask and
                             // length pairs

        // Preprocess strings to bitmask and lengths
        for (int i = 0; i < n; i++) {
            bitmaskLengthPairs[i][0]
                = getBitmask(arr[i]); // Store bitmask
            bitmaskLengthPairs[i][1]
                = arr[i].length(); // Store length
        }

        int maxProduct = 0;

        // Iterate over all unique pairs
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int bitmask1 = bitmaskLengthPairs[i][0];
                int bitmask2 = bitmaskLengthPairs[j][0];
                int len1 = bitmaskLengthPairs[i][1];
                int len2 = bitmaskLengthPairs[j][1];

                // Check if they have no common characters
                if ((bitmask1 & bitmask2) == 0) {
                    maxProduct
                        = Math.max(maxProduct, len1 * len2);
                }
            }
        }

        return maxProduct; // Return the maximum product
                           // found
    }

    public static void main(String[] args)
    {
        // Example usage
        String[] arr = { "abcw", "baz",  "foo",
                         "bar",  "xtfn", "abcdef" };
        int result = maximizeProduct(arr);
        System.out.println(result); // Output the result
    }
}
Python
def maximizeProduct(arr):
    def get_bitmask(s):
        bitmask = 0
        for char in s:
            bitmask |= 1 << (ord(char) - ord('a'))
        return bitmask

    # Preprocess strings to bitmask and lengths
    n = len(arr)
    bitmask_length_pairs = [(get_bitmask(arr[i]), len(arr[i]))
                            for i in range(n)]

    max_product = 0

    # Iterate over all unique pairs
    for i in range(n):
        for j in range(i + 1, n):
            bitmask1, len1 = bitmask_length_pairs[i]
            bitmask2, len2 = bitmask_length_pairs[j]

            # Check if they have no common characters
            if bitmask1 & bitmask2 == 0:
                max_product = max(max_product, len1 * len2)

    return max_product


# Example usage
arr = ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
result = maximizeProduct(arr)
print(result)
JavaScript
// Helper function to convert a string to a bitmask
function getBitmask(s) {
    let bitmask = 0;
    for (let i = 0; i < s.length; i++) {
        bitmask |= 1 << (s.charCodeAt(i) - 'a'.charCodeAt(0));
    }
    return bitmask;
}

function maximizeProduct(arr) {
    const n = arr.length; // Get the length of the input array
    const bitmaskLengthPairs = new Array(n).fill().map(() => [0, 0]); // Array to store bitmask and length pairs

    // Preprocess strings to bitmask and lengths
    for (let i = 0; i < n; i++) {
        bitmaskLengthPairs[i][0] = getBitmask(arr[i]); // Store bitmask
        bitmaskLengthPairs[i][1] = arr[i].length; // Store length
    }

    let maxProduct = 0;

    // Iterate over all unique pairs
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            const bitmask1 = bitmaskLengthPairs[i][0];
            const bitmask2 = bitmaskLengthPairs[j][0];
            const len1 = bitmaskLengthPairs[i][1];
            const len2 = bitmaskLengthPairs[j][1];

            // Check if they have no common characters
            if ((bitmask1 & bitmask2) === 0) {
                maxProduct = Math.max(maxProduct, len1 * len2);
            }
        }
    }

    return maxProduct; // Return the maximum product found
}

// Example usage
const arr = ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"];
const result = maximizeProduct(arr);
console.log(result); // Output the result

Output
16

Time Complexity: O(N^2)

Auxiliary Space: O(N)


Similar Reads