Unique Word Abbreviation — LeetCode 288 Python Solution
- Problem
- #288
- Pattern
- Hash Map
- Reading time
- 4 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.