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

PythonServer Side ProgrammingProgramming

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
return
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:
recur()
return ans

Let us see the following implementation to get better understanding:

Example

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))
return

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

recur()
return ans

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

Input

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

Output

9
Published on 10-Nov-2020 08:36:22