Word Abbreviation Problem
Description
LeetCode Problem 527.
Given an array of distinct strings words, return the minimal possible abbreviations for every word.
The following are the rules for a string abbreviation:
- The initial abbreviation for each word is: the first character, then the number of characters in between, followed by the last character.
- If more than one word shares the same abbreviation, then perform the following operation:
- Increase the prefix (characters in the first part) of each of their abbreviations by
1.- For example, say you start with the words
["abcdef","abndef"]both initially abbreviated as"a4f". Then, a sequence of operations would be["a4f","a4f"]->["ab3f","ab3f"]->["abc2f","abn2f"].
- For example, say you start with the words
- This operation is repeated until every abbreviation is unique.
- Increase the prefix (characters in the first part) of each of their abbreviations by
- At the end, if an abbreviation did not make a word shorter, then keep it as the original word.
Example 1:
Input: words = ["like","god","internal","me","internet","interval","intension","face","intrusion"]
Output: ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"]
Example 2:
Input: words = ["aa","aaa"]
Output: ["aa","aaa"]
Constraints:
1 <= words.length <= 4002 <= words[i].length <= 400words[i]consists of lowercase English letters.- All the strings of
wordsare unique.
Solution
Approach: Group by Length and Last Letter, then a Trie
An abbreviation with a prefix of length p looks like w[:p] + (len(w) - p - 1) + w[-1]. From it you can read the word's length (the prefix, the number and the last letter add up to it) and its last letter. So two words can only end up with the same abbreviation if they have the same length and the same last letter. Words in different groups never collide, whatever prefixes they use.
Within one group, two abbreviations with the same prefix length are equal exactly when the prefixes are equal. The repeated "increase the prefix" rule therefore stops, for each word, at the shortest prefix that no other word in its group shares. (Words that collide grow together; once a word's prefix is unique it stops growing, and any word that still shares it would also have to share all shorter prefixes.)
A trie finds those prefixes quickly. For each group, insert all its words into a trie where each node counts how many words pass through it. Then, for each word, walk down its path: the first node with count 1 is where the word separates from all the others, and its depth is the prefix length p.
Finally, build the abbreviation and keep it only if it is shorter than the word; otherwise return the word itself. That check matters for short words: "god" would become "g1d", which is not shorter, and in Example 2 both "aa" and "aaa" stay as they are.
Complexity: O(L) time and space, where L is the total length of all words: each character is inserted into a trie once and walked once.
class Trie:
def __init__(self):
self.children = [None] * 26
self.count = 0 # how many words pass through this node
def insert(self, word: str) -> None:
node = self
for c in word:
i = ord(c) - ord("a")
if node.children[i] is None:
node.children[i] = Trie()
node = node.children[i]
node.count += 1
def unique_prefix(self, word: str) -> int:
"""Length of the shortest prefix of word that no other word in this trie shares."""
node = self
for length, c in enumerate(word, 1):
node = node.children[ord(c) - ord("a")]
if node.count == 1:
return length
return len(word)
class Solution:
def wordsAbbreviation(self, words: List[str]) -> List[str]:
# only words with the same length and last letter can share an abbreviation
tries = {}
for w in words:
tries.setdefault((len(w), w[-1]), Trie()).insert(w)
ans = []
for w in words:
p = tries[(len(w), w[-1])].unique_prefix(w)
abbr = w[:p] + str(len(w) - p - 1) + w[-1]
ans.append(abbr if len(abbr) < len(w) else w)
return ans