Maximize product of lengths of strings having no common characters
Last Updated :
23 Jul, 2025
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>
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
Time Complexity: O(N^2)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem