Word Abbreviation - Problem
You're building a smart text compression system that creates minimal unique abbreviations for words. Given an array of distinct strings, your goal is to generate the shortest possible abbreviations for each word while ensuring all abbreviations remain unique.
How abbreviations work:
- Start with:
first_char + count_of_middle_chars + last_char - Example:
"hello"→"h3o"(h + 3 middle chars + o)
Conflict resolution: When multiple words share the same abbreviation, incrementally increase the prefix length until all abbreviations become unique.
Special rule: If the final abbreviation isn't shorter than the original word, keep the original word instead.
Example walkthrough:
For ["abcdef", "abndef"]:
- Initial: both become
"a4f"❌ (conflict!) - Expand prefix: both become
"ab3f"❌ (still conflict!) - Expand again:
"abc2f"and"abn2f"✅ (unique!)
Input & Output
example_1.py — Basic Conflict Resolution
$
Input:
["internal", "internet", "interstate", "interval"]
›
Output:
["int4l", "i6t", "i8e", "int4l"]
💡 Note:
"internal" and "interval" both initially become "i6l", so we expand prefixes until they become unique: "int4l" for both (but they're different words). "internet" becomes "i6t" and "interstate" becomes "i8e" with no conflicts.
example_2.py — No Conflicts Needed
$
Input:
["apple", "banana", "cherry"]
›
Output:
["a3e", "b4a", "c4y"]
💡 Note:
All words have different first and last characters, so no conflicts occur. Each gets abbreviated to first + middle_count + last format.
example_3.py — Abbreviation Not Shorter
$
Input:
["dog", "cat", "rat"]
›
Output:
["dog", "cat", "rat"]
💡 Note:
These 3-letter words would abbreviate to 3-character strings (like "d1g"), which aren't shorter than originals, so we keep the original words.
Constraints
- 1 ≤ words.length ≤ 1000
- 1 ≤ words[i].length ≤ 20
- words[i] consists of lowercase English letters only
- All strings in words are distinct
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code