Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum length of non-sharing words in Python
Given a list of lowercase alphabetical strings, we need to find the maximum sum of lengths of two distinct words that do not share any common letters. This problem can be efficiently solved using bit manipulation to represent character sets.
Problem Understanding
For the input words = ["abcd", "mno", "abdcmno", "amno"], we need to find two words with no common letters. The words "abcd" and "mno" share no common letters, giving us a total length of 4 + 3 = 7.
Algorithm Approach
We use bit manipulation where each bit position represents a letter (a=0, b=1, c=2, etc.). If two words have no common letters, the bitwise AND of their signatures will be 0.
Step-by-Step Process
- Create a signature function that converts each word to a bitmask
- For each character in a word, set the corresponding bit position
- Compare all pairs of words using bitwise AND operation
- If AND result is 0, the words share no common letters
- Track the maximum sum of lengths
Implementation
class Solution:
def sign(self, word):
"""Create bitmask signature for a word"""
value = 0
for c in word:
value = value | (1 << (ord(c) - ord('a')))
return value
def solve(self, words):
"""Find maximum length of non-sharing words"""
signature = [self.sign(x) for x in words]
ans = 0
for i in range(len(words)):
for j in range(i + 1, len(words)):
if signature[i] & signature[j] == 0:
ans = max(ans, len(words[i]) + len(words[j]))
return ans
# Test the solution
ob = Solution()
words = ["abcd", "mno", "abdcmno", "amno"]
result = ob.solve(words)
print(f"Maximum length: {result}")
Maximum length: 7
How the Bitmask Works
Let's trace through the signature creation for our example ?
def demonstrate_bitmask():
words = ["abcd", "mno"]
for word in words:
signature = 0
print(f"Word: '{word}'")
for char in word:
bit_position = ord(char) - ord('a')
bit_value = 1 << bit_position
signature |= bit_value
print(f" '{char}' -> position {bit_position} -> bit value {bit_value}")
print(f" Final signature: {signature} (binary: {bin(signature)})")
print()
demonstrate_bitmask()
Word: 'abcd' 'a' -> position 0 -> bit value 1 'b' -> position 1 -> bit value 2 'c' -> position 2 -> bit value 4 'd' -> position 3 -> bit value 8 Final signature: 15 (binary: 0b1111) Word: 'mno' 'm' -> position 12 -> bit value 4096 'n' -> position 13 -> bit value 8192 'o' -> position 14 -> bit value 16384 Final signature: 28672 (binary: 0b111000000000000)
Verification
Since 15 & 28672 = 0, the words "abcd" and "mno" share no common letters, confirming our solution works correctly.
Time and Space Complexity
- Time Complexity: O(n² + m) where n is the number of words and m is the total number of characters
- Space Complexity: O(n) for storing the signatures
Conclusion
This solution efficiently uses bit manipulation to represent character sets as bitmasks. The bitwise AND operation quickly determines if two words share common letters, making the algorithm both elegant and performant.
