Unique Word Abbreviation — LeetCode 288 Python Solution

MediumLeetCode PremiumDesignArrayHash TableString
Problem
#288
Pattern
Hash Map
Reading time
4 min

The 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.

Example

Input
["ValidWordAbbr", "isUnique", "isUnique", "isUnique", "isUnique", "isUnique"]
Output
[null, false, true, false, true, true]
Explanation
ValidWordAbbr validWordAbbr = new ValidWordAbbr(["deer", "door", "cake", "card"]);

Python solution

Python
class ValidWordAbbr:
    def __init__(self, dictionary: List[str]):
        self.d = defaultdict(set)
        for s in dictionary:
            self.d[self.abbr(s)].add(s)

    def isUnique(self, word: str) -> bool:
        s = self.abbr(word)
        return s not in self.d or all(word == t for t in self.d[s])

    def abbr(self, s: str) -> str:
        return s if len(s) < 3 else s[0] + str(len(s) - 2) + s[-1]


# Your ValidWordAbbr object will be instantiated and called as such:
# obj = ValidWordAbbr(dictionary)
# param_1 = obj.isUnique(word)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 288. Unique Word Abbreviation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 288. Unique Word Abbreviation?
LeetCode 288. Unique Word Abbreviation is rated Medium on LeetCode.
What is the time complexity of LeetCode 288. Unique Word Abbreviation?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 288. Unique Word Abbreviation?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 288. Unique Word Abbreviation cover?
LeetCode 288. Unique Word Abbreviation is tagged Design, Array, Hash Table and String on LeetCode.
Is LeetCode 288. Unique Word Abbreviation a premium problem?
Yes. LeetCode 288. Unique Word Abbreviation is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview