Minimum Unique Word Abbreviation - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: target = "apple", dictionary = ["blade"]
Output: "a4"
💡 Note: The abbreviation "a4" (representing "apple") is unique because "blade" cannot be abbreviated to "a4" since it doesn't start with 'a'
Example 2 — Need Longer Abbreviation
$ Input: target = "apple", dictionary = ["plain", "amber", "blade"]
Output: "1p3"
💡 Note: "5" would conflict with "plain", "a4" would conflict with "amber", so "1p3" is the shortest unique abbreviation
Example 3 — No Abbreviation Needed
$ Input: target = "apple", dictionary = ["aple"]
Output: "apple"
💡 Note: Any abbreviation of "apple" would also match "aple", so we return the full word

Constraints

  • 1 ≤ target.length ≤ 21
  • 0 ≤ dictionary.length ≤ 1000
  • 1 ≤ dictionary[i].length ≤ 100
  • target and dictionary[i] consist of lowercase English letters
  • dictionary does not contain target

Visualization

Tap to expand
Minimum Unique Word Abbreviation: target="apple", dictionary=["blade"]appleTarget wordbladeDictionaryGenerate abbreviations: apple → 5, a4, 1p3, ap2, ...5Too generica4Unique ✓Result: "a4" (shortest unique abbreviation)
Understanding the Visualization
1
Input
Target word and dictionary of conflicting words
2
Generate
Create all possible abbreviations of target
3
Filter
Find shortest abbreviation unique from dictionary
Key Takeaway
🎯 Key Insight: Generate all possible abbreviations systematically and filter for shortest unique one
Asked in
Google 15 Facebook 8
28.5K Views
Medium Frequency
~45 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen