LeetCode 0318. Maximum Product of Word Lengths Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0318. Maximum Product of Word Lengths

Description

Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.

 

Example 1:

Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: The two words can be "abcw", "xtfn".

Example 2:

Input: words = ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4
Explanation: The two words can be "ab", "cd".

Example 3:

Input: words = ["a","aa","aaa","aaaa"]
Output: 0
Explanation: No such pair of words.

 

Constraints:

  • 2 <= words.length <= 1000
  • 1 <= words[i].length <= 1000
  • words[i] consists only of lowercase English letters.

Solutions

Solution 1: Bit Manipulation

The problem requires us to find two strings without common letters, so that their length product is maximized. We can represent each string with a binary number mask[i], where each bit of this binary number indicates whether the string contains a certain letter. If two strings do not have common letters, then the bitwise AND result of the two binary numbers corresponding to these strings is 0, that is, mask[i] & mask[j] = 0.

We traverse each string. For the current string words[i] we are traversing, we first calculate the corresponding binary number mask[i], and then traverse all strings words[j] where j ∈ [0, i). We check whether mask[i] & mask[j] = 0 holds. If it holds, we update the answer to max(ans, |words[i]| × |words[j]|).

After the traversal, we return the answer.

The time complexity is O(n^2 + L), and the space complexity is O(n). Here, n is the length of the string array words, and L is the sum of the lengths of all strings in the string array.

PythonJavaC++GoTypeScript
class Solution: def maxProduct(self, words: List[str]) -> int: mask = [0] * len(words) ans = 0 for i, s in enumerate(words): for c in s: mask[i] |= 1 << (ord(c) - ord("a")) for j, t in enumerate(words[:i]): if (mask[i] & mask[j]) == 0: ans = max(ans, len(s) * len(t)) return ans(code-box)

Solution 2

PythonJavaC++GoTypeScript
class Solution: def maxProduct(self, words: List[str]) -> int: mask = defaultdict(int) ans = 0 for s in words: a = len(s) x = 0 for c in s: x |= 1 << (ord(c) - ord("a")) for y, b in mask.items(): if (x & y) == 0: ans = max(ans, a * b) mask[x] = max(mask[x], a) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !