Program to find length of concatenated string of unique characters in Python?

Suppose we have a list of strings words. We have to make a string that is constructed by concatenating a subsequence of words such that each letter is unique. We have to finally find the length of the longest such concatenation.

So, if the input is like words = ["xyz", "xyw", "wab", "cde"], then the output will be 9, as we cannot pick any word since they contain duplicate characters.

To solve this, we will follow these steps

ans := 0

Define a function recur() . This will take i:= 0, cur:= blank string

if i is same as size of words , then
   ans := maximum of ans and size of cur
recur(i + 1, cur)
if all characters in words[i] are unique and all characters in (cur + words[i]) are unique, then
   recur(i + 1, cur + words[i])
From the main method do the following:
return ans

Let us see the following implementation to get better understanding:


class Solution:
   def solve(self, words):
      ans = 0

      def is_all_unique(s):
         return len(set(s)) == len(s)

      def recur(i=0, cur=""):
         nonlocal ans
         if i == len(words):
            ans = max(ans, len(cur))

         recur(i + 1, cur)
         if is_all_unique(words[i]) and is_all_unique(cur + words[i]):
            recur(i + 1, cur + words[i])

      return ans

ob = Solution()
words = ["xyz", "xyw", "wab", "cde"]


["xyz", "xyw", "wab", "cde"]



Updated on: 10-Nov-2020


Kickstart Your Career

Get certified by completing the course

Get Started