411. Minimum Unique Word Abbreviation
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method: Generate and Test with Bitmasks
This problem asks for the shortest unique abbreviation of a target string. An abbreviation is unique if it cannot also be an abbreviation for any word in a given dictionary. This suggests a two-part strategy: first, generating all possible abbreviations of target, and second, checking each one for uniqueness against the dictionary. Since we need the shortest one, we should process abbreviations in increasing order of their length.
Solution
Minimum Unique Word Abbreviation in Python
class Solution:
def minAbbreviation(self, target: str, dictionary: List[str]) -> str:
m = len(target)
diffs = []
# 1. Pre-process dictionary to get diff masks for words of the same length.
# A '1' in the diff_mask at bit 'i' means target[i] != word[i].
for word in dictionary:
if len(word) == m:
diff_mask = 0
for i in range(m):
if target[i] != word[i]:
diff_mask |= (1 << i)
diffs.append(diff_mask)
if not diffs:
return str(m)
# 2. Generate all abbreviation masks and store with their lengths.
# We use the convention: 1 = keep character, 0 = abbreviate character.
abbrs = []
for i in range(1 << m):
length = 0
consecutive_zeros = 0
for j in range(m):
if (i >> j) & 1:
if consecutive_zeros > 0:
length += 1
consecutive_zeros = 0
length += 1
else:
consecutive_zeros += 1
if consecutive_zeros > 0:
length += 1
abbrs.append((length, i))
# 3. Sort abbreviations by length.
abbrs.sort()
# 4. Find the first valid abbreviation.
for _, abbr_mask in abbrs:
has_conflict = False
# An abbreviation conflicts if it's also a valid abbreviation for a dictionary word.
# This happens if for all kept characters, they match the dictionary word.
# In terms of masks, this is (abbr_mask & diff_mask) == 0.
for d in diffs:
if (abbr_mask & d) == 0:
has_conflict = True
break
if not has_conflict:
# 5. Construct and return the abbreviation string.
res = []
count = 0
for j in range(m):
if (abbr_mask >> j) & 1:
if count > 0:
res.append(str(count))
count = 0
res.append(target[j])
else:
count += 1
if count > 0:
res.append(str(count))
return "".join(res)
return "" # Should not be reached
Minimum Unique Word Abbreviation in Java
class Solution {
public String minAbbreviation(String target, String[] dictionary) {
int m = target.length();
List<Integer> diffs = new ArrayList<>();
// 1. Pre-process dictionary to get diff masks for words of the same length.
// A '1' in the diff_mask at bit 'i' means target[i] != word[i].
for (String word : dictionary) {
if (word.length() == m) {
int diff_mask = 0;
for (int i = 0; i < m; i++) {
if (target.charAt(i) != word.charAt(i)) {
diff_mask |= (1 << i);
}
}
diffs.add(diff_mask);
}
}
if (diffs.isEmpty()) {
return Integer.toString(m);
}
// 2. Generate all abbreviation masks and store with their lengths.
// We use the convention: 1 = keep character, 0 = abbreviate character.
List<int[]> abbrs = new ArrayList<>();
for (int i = 0; i < (1 << m); i++) {
int len = 0;
int consecutive_zeros = 0;
for (int j = 0; j < m; j++) {
if (((i >> j) & 1) == 1) { // Bit is 1, character is kept
if (consecutive_zeros > 0) {
len++; // For the number representing the abbreviated part
}
consecutive_zeros = 0;
len++; // For the character itself
} else { // Bit is 0, character is abbreviated
consecutive_zeros++;
}
}
if (consecutive_zeros > 0) {
len++; // For the last number
}
abbrs.add(new int[]{len, i});
}
// 3. Sort abbreviations by length.
Collections.sort(abbrs, (a, b) -> Integer.compare(a[0], b[0]));
// 4. Find the first valid abbreviation.
for (int[] p : abbrs) {
int abbr_mask = p[1];
boolean hasConflict = false;
// An abbreviation conflicts if it's also a valid abbreviation for a dictionary word.
// This happens if for all kept characters, they match the dictionary word.
// In terms of masks, this is (abbr_mask & diff_mask) == 0.
for (int d : diffs) {
if ((abbr_mask & d) == 0) {
hasConflict = true;
break;
}
}
if (!hasConflict) {
// 5. Construct and return the abbreviation string.
StringBuilder res = new StringBuilder();
int count = 0;
for (int j = 0; j < m; j++) {
if (((abbr_mask >> j) & 1) == 1) { // Kept character
if (count > 0) {
res.append(count);
count = 0;
}
res.append(target.charAt(j));
} else { // Abbreviated character
count++;
}
}
if (count > 0) {
res.append(count);
}
return res.toString();
}
}
return ""; // Should not be reached
}
}
Minimum Unique Word Abbreviation in C++
class Solution {
public:
string minAbbreviation(string target, vector<string>& dictionary) {
int m = target.length();
vector<int> diffs;
// 1. Pre-process dictionary to get diff masks for words of the same length.
// A '1' in the diff_mask at bit 'i' means target[i] != word[i].
for (const string& word : dictionary) {
if (word.length() == m) {
int diff_mask = 0;
for (int i = 0; i < m; ++i) {
if (target[i] != word[i]) {
diff_mask |= (1 << i);
}
}
diffs.push_back(diff_mask);
}
}
if (diffs.empty()) {
return to_string(m);
}
// 2. Generate all abbreviation masks and store with their lengths.
// We use the convention: 1 = keep character, 0 = abbreviate character.
vector<pair<int, int>> abbrs;
for (int i = 0; i < (1 << m); ++i) {
int len = 0;
int consecutive_zeros = 0;
for (int j = 0; j < m; ++j) {
if ((i >> j) & 1) { // Bit is 1, character is kept
if (consecutive_zeros > 0) {
len++; // For the number representing the abbreviated part
}
consecutive_zeros = 0;
len++; // For the character itself
} else { // Bit is 0, character is abbreviated
consecutive_zeros++;
}
}
if (consecutive_zeros > 0) {
len++; // For the last number
}
abbrs.push_back({len, i});
}
// 3. Sort abbreviations by length.
sort(abbrs.begin(), abbrs.end());
// 4. Find the first valid abbreviation.
for (const auto& p : abbrs) {
int abbr_mask = p.second;
bool has_conflict = false;
// An abbreviation conflicts if it's also a valid abbreviation for a dictionary word.
// This happens if for all kept characters, they match the dictionary word.
// In terms of masks, this is (abbr_mask & diff_mask) == 0.
for (int d : diffs) {
if ((abbr_mask & d) == 0) {
has_conflict = true;
break;
}
}
if (!has_conflict) {
// 5. Construct and return the abbreviation string.
string res = "";
int count = 0;
for (int j = 0; j < m; ++j) {
if ((abbr_mask >> j) & 1) { // Kept character
if (count > 0) {
res += to_string(count);
count = 0;
}
res += target[j];
} else { // Abbreviated character
count++;
}
}
if (count > 0) {
res += to_string(count);
}
return res;
}
}
return ""; // Should not be reached
}
};
Minimum Unique Word Abbreviation in TypeScript
function minAbbreviation(target: string, dictionary: string[]): string {
const m = target.length;
const diffs: number[] = [];
// 1. Pre-process dictionary to get diff masks for words of the same length.
// A '1' in the diff_mask at bit 'i' means target[i] != word[i].
for (const word of dictionary) {
if (word.length === m) {
let diff_mask = 0;
for (let i = 0; i < m; i++) {
if (target[i] !== word[i]) {
diff_mask |= (1 << i);
}
}
diffs.push(diff_mask);
}
}
if (diffs.length === 0) {
return String(m);
}
// 2. Generate all abbreviation masks and store with their lengths.
// We use the convention: 1 = keep character, 0 = abbreviate character.
const abbrs: [number, number][] = [];
for (let i = 0; i < (1 << m); i++) {
let len = 0;
let consecutive_zeros = 0;
for (let j = 0; j < m; j++) {
if ((i >> j) & 1) { // Bit is 1, character is kept
if (consecutive_zeros > 0) {
len++; // For the number representing the abbreviated part
}
consecutive_zeros = 0;
len++; // For the character itself
} else { // Bit is 0, character is abbreviated
consecutive_zeros++;
}
}
if (consecutive_zeros > 0) {
len++; // For the last number
}
abbrs.push([len, i]);
}
// 3. Sort abbreviations by length.
abbrs.sort((a, b) => a[0] - b[0]);
// 4. Find the first valid abbreviation.
for (const [, abbr_mask] of abbrs) {
let hasConflict = false;
// An abbreviation conflicts if it's also a valid abbreviation for a dictionary word.
// This happens if for all kept characters, they match the dictionary word.
// In terms of masks, this is (abbr_mask & diff_mask) == 0.
for (const d of diffs) {
if ((abbr_mask & d) === 0) {
hasConflict = true;
break;
}
}
if (!hasConflict) {
// 5. Construct and return the abbreviation string.
let res = '';
let count = 0;
for (let j = 0; j < m; j++) {
if ((abbr_mask >> j) & 1) { // Kept character
if (count > 0) {
res += count;
count = 0;
}
res += target[j];
} else { // Abbreviated character
count++;
}
}
if (count > 0) {
res += count;
}
return res;
}
}
return ""; // Should not be reached
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.