Minimum Unique Word Abbreviation Problem
Description
LeetCode Problem 411.
A string can be abbreviated by replacing any number of non-adjacent substrings with their lengths. For example, a string such as "substitution" could be abbreviated as (but not limited to):
"s10n"("s ubstitutio n")"sub4u4"("sub stit u tion")"12"("substitution")"su3i1u2on"("su bst i t u ti on")"substitution"(no substrings replaced)
Note that "s55n" ("s ubsti tutio n") is not a valid abbreviation of "substitution" because the replaced substrings are adjacent.
The length of an abbreviation is the number of letters that were not replaced plus the number of substrings that were replaced. For example, the abbreviation "s10n" has a length of 3 (2 letters + 1 substring) and "su3i1u2on" has a length of 9 (6 letters + 3 substrings).
Given a target string target and an array of strings dictionary, return an abbreviation of target with the shortest possible length such that it is not an abbreviation of any string in dictionary. If there are multiple shortest abbreviations, return any of them.
Example 1:
Input: target = "apple", dictionary = ["blade"]
Output: "a4"
Explanation: The shortest abbreviation of "apple" is "5", but this is also an abbreviation of "blade".
The next shortest abbreviations are "a4" and "4e". "4e" is an abbreviation of blade while "a4" is not.
Hence, return "a4".
Example 2:
Input: target = "apple", dictionary = ["blade","plain","amber"]
Output: "1p3"
Explanation: "5" is an abbreviation of both "apple" but also every word in the dictionary.
"a4" is an abbreviation of "apple" but also "amber".
"4e" is an abbreviation of "apple" but also "blade".
"1p3", "2p2", and "3l1" are the next shortest abbreviations of "apple".
Since none of them are abbreviations of words in the dictionary, returning any of them is correct.
Constraints:
m == target.lengthn == dictionary.length1 <= m <= 210 <= n <= 10001 <= dictionary[i].length <= 100log_2(n) + m <= 21ifn > 0targetanddictionary[i]consist of lowercase English letters.dictionarydoes not containtarget.
Solution
Approach: Difference Masks + Branch and Bound
Which words matter. An abbreviation always stands for a word of one fixed length, so only dictionary words with the same length m as target can conflict. All other words can be ignored. If none are left, the answer is just the number m (length 1).
When a word is ruled out. An abbreviation of target is fully described by which letters it keeps; every other position is covered by a number. A dictionary word w of length m matches the abbreviation exactly when it agrees with target on every kept letter. So for each w build a bitmask diff of the positions where w and target differ. A set of kept positions mask rules w out if and only if mask & diff != 0, meaning it keeps at least one letter where w is different. We want a mask that hits every diff, with the shortest abbreviation.
Searching. The length of an abbreviation is the number of kept letters plus the number of runs of replaced letters. A depth-first search builds abbreviations from left to right. At position pos it either keeps target[pos] (length + 1), or replaces target[pos..end) with one number and then keeps target[end] (length + 2), or replaces everything to the end (length + 1). Requiring a kept letter after each number guarantees two numbers are never adjacent.
The search starts with the full word as the best answer: it always works, because target is not in the dictionary, so every diff is non-zero. Any branch that cannot beat the best length found so far is cut off. Trying the longest replacements first finds short answers early, which makes the cut-offs effective. Only when a complete abbreviation is shorter than the best do we test it against all the masks.
The constraint log2(n) + m <= 21 keeps the work small. When the dictionary is large, m is small, so there are few masks. When m is large, there are few words, so a short answer exists and the search stops early.
Finally, turn the best mask back into a string: write each kept letter as is and each run of replaced letters as its count.
Complexity: O(2m · k) time in the worst case, where k is the number of distinct difference masks (at most n), plus O(n · m) to build them. O(k + m) extra space.
class Solution:
def minAbbreviation(self, target: str, dictionary: List[str]) -> str:
m = len(target)
# Only words of the same length can share an abbreviation with target. For each one, keep the set of
# positions where it differs: an abbreviation rules the word out iff it keeps one of those letters.
diffs = set()
for word in dictionary:
if len(word) == m:
diff = 0
for i in range(m):
if word[i] != target[i]:
diff |= 1 << i
diffs.add(diff)
diffs = list(diffs)
# Spelling out the whole word always works (target is not in the dictionary).
best_len, best_mask = m, (1 << m) - 1
def dfs(pos: int, mask: int, length: int) -> None:
"""Abbreviations of target[pos:]; mask has a bit for every kept letter so far."""
nonlocal best_len, best_mask
if length + (pos < m) >= best_len:
return
if pos == m:
if all(mask & diff for diff in diffs):
best_len, best_mask = length, mask
return
# Replace target[pos:end] by its length, longest first; the letter after it must then be kept.
for end in range(m, pos, -1):
if end == m:
dfs(m, mask, length + 1)
else:
dfs(end + 1, mask | 1 << end, length + 2)
dfs(pos + 1, mask | 1 << pos, length + 1) # keep target[pos]
dfs(0, 0, 0)
# Turn the mask back into a string: kept letters as they are, each run of others as its length.
parts, run = [], 0
for i in range(m):
if best_mask >> i & 1:
if run:
parts.append(str(run))
run = 0
parts.append(target[i])
else:
run += 1
if run:
parts.append(str(run))
return "".join(parts)