Unique Word Abbreviation - Problem

The abbreviation of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an abbreviation of itself.

For example:

  • dog → d1g because there is one letter between the first letter 'd' and the last letter 'g'.
  • internationalization → i18n because there are 18 letters between the first letter 'i' and the last letter 'n'.
  • it → it because any word with only two characters is an abbreviation of itself.

Implement the ValidWordAbbr class:

  • ValidWordAbbr(String[] dictionary) Initializes the object with a dictionary of words.
  • boolean isUnique(string word) Returns true if either of the following conditions are met (otherwise returns false):
    • There is no word in dictionary whose abbreviation is equal to word's abbreviation.
    • For any word in dictionary whose abbreviation is equal to word's abbreviation, that word and word are the same.

Input & Output

Example 1 — Basic Dictionary Operations
$ Input: dictionary = ["deer", "door", "cake", "card"], operations = ["dear", "cart", "cane", "make"]
Output: [false, true, false, true]
💡 Note: dear→d2r conflicts with deer and door. cart→c2t is unique. cane→c2e conflicts with cake. make→m2e is unique.
Example 2 — Word Matches Dictionary
$ Input: dictionary = ["hello", "world"], operations = ["hello", "hallo"]
Output: [true, false]
💡 Note: hello is in dictionary with abbreviation h3o, so it's unique to itself. hallo→h3o conflicts with hello.
Example 3 — Short Words
$ Input: dictionary = ["it", "is"], operations = ["it", "at"]
Output: [true, true]
💡 Note: Short words are their own abbreviations: it→it, is→is, at→at. All unique.

Constraints

  • 1 ≤ dictionary.length ≤ 3 × 104
  • 1 ≤ dictionary[i].length ≤ 20
  • dictionary[i] consists of lowercase English letters
  • 1 ≤ operations.length ≤ 5 × 103
  • 1 ≤ word.length ≤ 20
  • word consists of lowercase English letters

Visualization

Tap to expand
Unique Word Abbreviation ProblemDictionary WordsdeerdoorcakecardGenerateAbbreviationsd2rd2rc2ec2dQueryQuery: deardear → d2rConflicts with deer, doorRule: Abbreviation is unique if:1. No dictionary word has same abbreviation, OR2. All words with same abbreviation are identical to queryResult: [false, true, false, true]
Understanding the Visualization
1
Input
Dictionary words and query operations
2
Process
Generate abbreviations and check for conflicts
3
Output
Boolean array indicating uniqueness
Key Takeaway
🎯 Key Insight: Use hash map to group dictionary words by abbreviation for O(1) uniqueness checks
Asked in
Google 15 Facebook 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
890 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