Get the Maximum Length of a Concatenated String with Unique Characters in Python

0 min read 197 words

The problem

Given an array of strings arr. String s is a concatenation of a sub-sequence of arr which have unique characters.

Return the maximum possible length of s.

Example test-cases

Example 1:

Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique".
Maximum length is 4.

Example 2:

Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible solutions are "chaers" and "acters".

Example 3:

Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26

Constraints

  • 1 <= arr.length <= 16
  • 1 <= arr[i].length <= 26
  • arr[i] contains only lower case English letters.

How to write the code

def maxLength(arr: List[str]) -> int:
  result = [float('-inf')]

  unique_char("", arr, 0, result)

  if not result[0] == float('-inf'):
    return result[0]
  return 0


def unique_char(cur, arr, index, result):
  # End of the array
  if index == len(arr):
    return

  # Iterating from the current word to the end of the array
  for index in range(index,len(arr)):

    # If current word + next word have all unique characters
    if len(set(cur + arr[index])) == len(list(cur + arr[index])):
      # Compare the actual lenth with the previous max
      result[0] = max(result[0],len(cur + arr[index]))
      # Make a new call with concatenate words
      unique_char(cur + arr[index], arr, index + 1,result)
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags