Generalized Abbreviation - Problem
Imagine you're creating a smart text compression system that can abbreviate words in multiple creative ways! ๐ฏ
A word's generalized abbreviation can be constructed by taking any number of non-overlapping and non-adjacent substrings and replacing them with their respective lengths.
Example: The word "abcde" can be abbreviated into:
"a3e"- Replace "bcd" with "3""1bcd1"- Replace "a" and "e" with "1" each"5"- Replace entire word with "5""abcde"- No replacement (original word)
Invalid abbreviations:
"23"โ Adjacent substrings ("ab" โ "2" and "cde" โ "3")"22de"โ Overlapping substrings ("ab" โ "2" and "bc" โ "2")
Goal: Given a string word, return all possible generalized abbreviations. The order doesn't matter!
Input & Output
example_1.py โ Basic Word
$
Input:
word = "word"
โบ
Output:
["4", "3d", "2rd", "2r1", "1ord", "1or1", "1o1d", "wo2", "wo1d", "wor1", "word"]
๐ก Note:
We can abbreviate any non-overlapping and non-adjacent substrings. Each combination gives a unique abbreviation pattern.
example_2.py โ Single Character
$
Input:
word = "a"
โบ
Output:
["1", "a"]
๐ก Note:
For a single character, we can either abbreviate it to '1' or keep it as 'a'.
example_3.py โ Two Characters
$
Input:
word = "hi"
โบ
Output:
["2", "1i", "h1", "hi"]
๐ก Note:
With two characters, we can abbreviate both ('2'), first only ('1i'), second only ('h1'), or neither ('hi'). Note that we cannot have adjacent abbreviations.
Constraints
- 1 โค word.length โค 15
- word consists of only lowercase English letters
- No adjacent abbreviations allowed
- No overlapping substrings can be abbreviated
Visualization
Tap to expand
Understanding the Visualization
1
Start Journey
Begin at the first character with two possible routes
2
Make Choice
Either keep the character (scenic route) or abbreviate (shortcut)
3
Apply Constraints
If you took a shortcut last time, you must take the scenic route this time
4
Continue Journey
Repeat the process for each remaining character
5
Collect Results
Each complete path gives you a unique abbreviation
Key Takeaway
๐ฏ Key Insight: Backtracking naturally prevents adjacent abbreviations by tracking the previous choice, making it more efficient than generating all combinations and filtering invalid ones.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code