KatInterview

Longest Non-Overlapping Character Chain

Math & Bit ManipulationAuto-graded · 20 test cases
MediumAuto-gradedMath & Bit Manipulationbacktrackingbit-manipulationrecursion

Last updated

Tests backtracking or bitmask optimization to select a subset of strings whose combined characters are all distinct.

You are given an array of strings words. Your task is to select any subset of these strings and concatenate them together. The goal is to maximize the total length of the concatenated result, under the constraint that no character appears more than once in the final string.

Return the maximum length achievable.

Rules

  • You may choose any subset of the input strings, including none at all.
  • The order in which you concatenate the chosen strings does not matter for the purpose of counting distinct characters.
  • If a string in words contains a repeated character within itself, that string cannot be part of any valid selection.
  • A character must appear at most once across the entire concatenated result.

Constraints

  • 1 <= words.length <= 16
  • 1 <= words[i].length <= 26
  • Each words[i] consists only of lowercase English letters.

Examples

Example 1

Input: longest_unique_concat(['un', 'iq', 'ue'])

Output: 4

Example 2

Input: longest_unique_concat(['cha', 'r', 'act', 'ers'])

Output: 6

Hints

Hint 1

A string containing duplicate letters within itself can never be used in any valid subset.

Hint 2

Use a bitmask to represent which letters are present in a word or combination—this makes checking for overlaps a single bitwise AND operation.

Hint 3

With at most 16 words, exploring all possible subsets is feasible; use backtracking to avoid generating duplicate combinations.