Program to find maximum length of non-sharing words in Python


Suppose we have a list of lowercase alphabetical strings called words, we have to find the maximum sum of the lengths of two distinct words that do not share a common letter. So, if the input is like words = ["abcd", "mno", "abdcmno", "amno"], then the output will be 7, as the words do not share any common letters are ["abcd", "mno"], total length is 7.

To solve this, we will follow these steps −

  • Define a function sign() . This will take word
  • value := 0
  • for each c in word, do
    • value := value OR (2^(ASCII of c - ASCII of 'a'))
  • return value
  • From the main method, do the following
  • signature := a list with sign(x) for each x in words
  • ans := 0
  • for i in range 0 to size of words, do
    • for j in range i + 1 to size of words, do
      • if signature[i] AND signature[j] is same as 0, then
        • ans := maximum of ans and size of words[i] + size of words[j]
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def sign(self, word):
      value = 0
      for c in word:
         value = value | (1 << (ord(c) - 97))
      return value
   def solve(self, 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
ob = Solution()
words = ["abcd", "mno", "abdcmno", "amno"]
print(ob.solve(words))

Input

["abcd", "mno", "abdcmno", "amno"]

Output

7

Updated on: 19-Oct-2020

154 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements