Longest Repeat-Free Concatenation, Lexicographically Smallest
StringsAuto-graded · 22 test casesLast updated
Pick words and order them to form the longest string with no repeated character, breaking ties by smallest lexicographic order; tests subset backtracking with disjoint-set pruning.
Longest Repeat-Free Concatenation
You are given a list of strings words. Choose any subset of the list entries (possibly none), put the chosen strings in any order, and join them end to end into a single string.
A joined string is valid if no character appears more than once in it. Characters are compared exactly (case-sensitive, so "a" and "A" are different characters).
What to return
Consider every valid string obtainable by any choice of subset and any ordering of it. Return the one that is best under these rules, applied in order:
- It has the greatest length.
- Among strings of that greatest length, it is the lexicographically smallest. Strings are compared character by character using character code points (Python's default
<onstr).
If the only valid string is the empty string (for example, every word repeats a character), return "".
Precise rules
- Each list entry may be used at most once. If the same word appears twice in the list, those are two separate entries, but two copies of a non-empty word can never both be chosen, since their characters would repeat.
- A word that contains a repeated character by itself can never be chosen.
- An empty word
""is a legal entry. Choosing it changes nothing in the resulting string. - Only the final string is returned. The same string may arise from different subsets or orders, which is fine.
- The tie-break is over the final strings, across all subsets and all orderings. It is not just a tie-break between subsets. For a fixed subset, you must use the ordering that gives the smallest string, and then compare these across subsets.
- Different subsets with the same total length can yield different strings, for example
["un", "iq", "ue"]can give"iqun"or"ique". Return the smaller one. - The answer is a string of distinct characters, so its length never exceeds the number of distinct characters in the input.
Input
words: a list of strings.
Output
- A string: the longest valid concatenation, with ties broken by smallest lexicographic order, or
""if none is non-empty.
Constraints
1 <= len(words) <= 16- Words may be empty. Words may contain repeated characters.
- Characters are compared by code point. Do not assume the input is only lowercase letters, and do not hard-code a 26-letter alphabet.
- Total length of all words is small (at most a few hundred characters).
Examples
Example 1
Input: longest_unique_concat_smallest(['un', 'iq', 'ue'])
Output: 'ique'
Example 2
Input: longest_unique_concat_smallest(['aa', 'bc', 'd'])
Output: 'bcd'
Example 3
Input: longest_unique_concat_smallest(['ab', 'cd', 'ef'])
Output: 'abcdef'
Example 4
Input: longest_unique_concat_smallest(['a', 'b', 'c', 'ab'])
Output: 'abc'
Hints
Hint 1
Discard any word that repeats a character internally. For the rest, only the set of characters in each word matters for checking compatibility; do not assume lowercase only.
Hint 2
With at most 16 words there are at most 65,536 subsets. Recurse over indices in increasing order, adding a word only if it shares no character with the characters already used.
Hint 3
For a fixed subset, the smallest string comes from sorting its words so that a goes before b when a+b < b+a. Then compare each subset's result with the best so far by length first, and by lexicographic order if the lengths are equal.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Drop unusable words. A word containing a repeated character can never appear in a valid string, so keep only words where
len(set(w)) == len(w). - Reduce to subset selection. Reordering words never changes which characters appear, so validity depends only on which entries are chosen. A choice is valid exactly when the chosen words' character sets are pairwise disjoint.
- Backtrack over subsets. Walk the words by increasing index. At each step, try adding a later word, but only if it shares no character with the characters already used. Each subset is generated once, and any branch with a conflict is cut off immediately.
- Score each valid subset. For a chosen subset, build its smallest concatenation by sorting the words with the comparator "
abeforebifa + b < b + a". Then compare it to the best so far: longer wins, and for equal length the lexicographically smaller string wins.
Why it is correct
- Completeness: every valid selection is a set of usable words with pairwise-disjoint characters, and the recursion visits every such set. Only conflicting sets are pruned, and those are invalid anyway.
- Soundness: a word is added only if it is disjoint from the used characters, and each word has no internal repeats, so every candidate string has all-distinct characters.
- Optimality and tie-break: for each subset, the comparator-sorted order gives its smallest possible concatenation. Taking the best over all subsets by (length, then lexicographic order) gives the globally best string over all subsets and orderings. The empty subset gives
"", which covers the case where nothing is usable.
Because the words in a chosen subset are character-disjoint, any two non-empty ones differ at their first character, so the comparator effectively sorts by first character. The general comparator is still correct, and it handles empty words too (they compare equal and add nothing).
Using sets of characters rather than a 26-bit mask means the solution works for any characters, not just lowercase letters.
Complexity
- Time: at most 2^n visited subsets (n <= 16). Each valid subset is sorted and joined once. Pruning usually cuts the visited count far below 2^n.
- Space: O(n + A) for the recursion, the chosen list, and the used-character set, where A is the number of distinct characters.
Reference solution
from functools import cmp_to_key
from typing import List
def longest_unique_concat_smallest(words: List[str]) -> str:
# Words with an internal repeat can never be used.
usable = [w for w in words if len(set(w)) == len(w)]
best = ""
def cmp(a: str, b: str) -> int:
if a + b < b + a:
return -1
if a + b > b + a:
return 1
return 0
def evaluate(chosen: List[str]) -> None:
nonlocal best
candidate = "".join(sorted(chosen, key=cmp_to_key(cmp)))
if len(candidate) > len(best) or (
len(candidate) == len(best) and candidate < best
):
best = candidate
def dfs(start: int, used: set, chosen: List[str]) -> None:
evaluate(chosen)
for i in range(start, len(usable)):
w = usable[i]
if used.isdisjoint(w):
chosen.append(w)
used.update(w)
dfs(i + 1, used, chosen)
for ch in w:
used.remove(ch)
chosen.pop()
dfs(0, set(), [])
return best