Leetcode #527: Word Abbreviation
In this guide, we solve Leetcode #527 Word Abbreviation in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Greedy, Trie, Array, String, Sorting
Intuition
A locally optimal choice leads to a globally optimal result for this structure.
That means we can commit to decisions as we scan without backtracking.
Approach
Sort or preprocess if needed, then repeatedly take the best available local choice.
Maintain the minimal state necessary to validate the greedy decision.
Steps:
- Sort or preprocess as needed.
- Iterate and pick the best local option.
- Track the current solution.
Example
Input: words = ["like","god","internal","me","internet","interval","intension","face","intrusion"]
Output: ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"]
Python Solution
class Trie:
__slots__ = ["children", "cnt"]
def __init__(self):
self.children = [None] * 26
self.cnt = 0
def insert(self, w: str):
node = self
for c in w:
idx = ord(c) - ord("a")
if not node.children[idx]:
node.children[idx] = Trie()
node = node.children[idx]
node.cnt += 1
def search(self, w: str) -> int:
node = self
cnt = 0
for c in w:
cnt += 1
idx = ord(c) - ord("a")
node = node.children[idx]
if node.cnt == 1:
return cnt
return len(w)
class Solution:
def wordsAbbreviation(self, words: List[str]) -> List[str]:
tries = {}
for w in words:
m = len(w)
if (m, w[-1]) not in tries:
tries[(m, w[-1])] = Trie()
tries[(m, w[-1])].insert(w)
ans = []
for w in words:
cnt = tries[(len(w), w[-1])].search(w)
ans.append(
w if cnt + 2 >= len(w) else w[:cnt] + str(len(w) - cnt - 1) + w[-1]
)
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.