Minimum Unique Word Abbreviation Problem

Problem

A string such as "word" contains the following abbreviations:

1
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]

Given a target string and a set of strings in a dictionary, find an abbreviation of this target string with the smallest possible length such that it does not conflict with abbreviations of the strings in the dictionary.

Each number or letter in the abbreviation is considered length = 1. For example, the abbreviation “a32bc” has length = 4.

Note:

  • In the case of multiple answers as shown in the second example below, you may return any one of them.
  • Assume length of target string = m, and dictionary size = n. You may assume that m ≤ 21n ≤ 1000, and log2(n) + m ≤ 20.

Examples

1
"apple", ["blade"] -> "a4" (because "5" or "4e" conflicts with "blade")
1
"apple", ["plain", "amber", "blade"] -> "1p3" (other valid answers include "ap3", "a3e", "2p2", "3le", "3l1").

Solution

Method 1 – Bitmask Backtracking

Intuition

We want the shortest abbreviation of the target that does not conflict with any abbreviation of the dictionary words. We can use bitmasks to represent which positions are kept as letters and which are abbreviated as numbers, and check for conflicts efficiently.

Approach

  1. For each word in the dictionary with the same length as the target, compute a bitmask of positions where the word differs from the target.
  2. For all possible abbreviation masks, check if the abbreviation is unique (i.e., for every mask, there is at least one differing position with every dictionary word).
  3. For each valid mask, compute the abbreviation length.
  4. Return the abbreviation with the minimum length.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public:
    string minAbbreviation(string target, vector<string>& dictionary) {
        int m = target.size();
        vector<int> diffs;
        for (auto& word : dictionary) {
            if (word.size() != m) continue;
            int diff = 0;
            for (int i = 0; i < m; ++i) {
                if (word[i] != target[i]) diff |= (1 << i);
            }
            diffs.push_back(diff);
        }
        int min_len = m + 1, res_mask = 0;
        for (int mask = 0; mask < (1 << m); ++mask) {
            bool valid = true;
            for (int d : diffs) {
                if ((mask & d) == 0) { valid = false; break; }
            }
            if (valid) {
                int len = 0, cnt = 0;
                for (int i = 0; i < m; ++i) {
                    if (mask & (1 << i)) {
                        if (cnt) { ++len; cnt = 0; }
                        ++len;
                    } else {
                        ++cnt;
                        if (i == m-1 || (mask & (1 << (i+1)))) { ++len; cnt = 0; }
                    }
                }
                if (len < min_len) { min_len = len; res_mask = mask; }
            }
        }
        string ans;
        int cnt = 0;
        for (int i = 0; i < m; ++i) {
            if (res_mask & (1 << i)) {
                if (cnt) { ans += to_string(cnt); cnt = 0; }
                ans += target[i];
            } else {
                ++cnt;
                if (i == m-1 || (res_mask & (1 << (i+1)))) { ans += to_string(cnt); cnt = 0; }
            }
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
func MinAbbreviation(target string, dictionary []string) string {
    m := len(target)
    diffs := []int{}
    for _, word := range dictionary {
        if len(word) != m { continue }
        diff := 0
        for i := 0; i < m; i++ {
            if word[i] != target[i] {
                diff |= 1 << i
            }
        }
        diffs = append(diffs, diff)
    }
    minLen, resMask := m+1, 0
    for mask := 0; mask < 1<<m; mask++ {
        valid := true
        for _, d := range diffs {
            if mask&d == 0 {
                valid = false
                break
            }
        }
        if valid {
            len, cnt := 0, 0
            for i := 0; i < m; i++ {
                if mask&(1<<i) != 0 {
                    if cnt > 0 { len++; cnt = 0 }
                    len++
                } else {
                    cnt++
                    if i == m-1 || mask&(1<<(i+1)) != 0 { len++; cnt = 0 }
                }
            }
            if len < minLen {
                minLen = len
                resMask = mask
            }
        }
    }
    ans := ""
    cnt := 0
    for i := 0; i < m; i++ {
        if resMask&(1<<i) != 0 {
            if cnt > 0 { ans += fmt.Sprintf("%d", cnt); cnt = 0 }
            ans += string(target[i])
        } else {
            cnt++
            if i == m-1 || resMask&(1<<(i+1)) != 0 {
                ans += fmt.Sprintf("%d", cnt)
                cnt = 0
            }
        }
    }
    return ans
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
    public String minAbbreviation(String target, String[] dictionary) {
        int m = target.length();
        List<Integer> diffs = new ArrayList<>();
        for (String word : dictionary) {
            if (word.length() != m) continue;
            int diff = 0;
            for (int i = 0; i < m; i++) {
                if (word.charAt(i) != target.charAt(i)) diff |= (1 << i);
            }
            diffs.add(diff);
        }
        int minLen = m + 1, resMask = 0;
        for (int mask = 0; mask < (1 << m); mask++) {
            boolean valid = true;
            for (int d : diffs) {
                if ((mask & d) == 0) { valid = false; break; }
            }
            if (valid) {
                int len = 0, cnt = 0;
                for (int i = 0; i < m; i++) {
                    if ((mask & (1 << i)) != 0) {
                        if (cnt > 0) { len++; cnt = 0; }
                        len++;
                    } else {
                        cnt++;
                        if (i == m-1 || (mask & (1 << (i+1))) != 0) { len++; cnt = 0; }
                    }
                }
                if (len < minLen) { minLen = len; resMask = mask; }
            }
        }
        StringBuilder ans = new StringBuilder();
        int cnt = 0;
        for (int i = 0; i < m; i++) {
            if ((resMask & (1 << i)) != 0) {
                if (cnt > 0) { ans.append(cnt); cnt = 0; }
                ans.append(target.charAt(i));
            } else {
                cnt++;
                if (i == m-1 || (resMask & (1 << (i+1))) != 0) { ans.append(cnt); cnt = 0; }
            }
        }
        return ans.toString();
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
    fun minAbbreviation(target: String, dictionary: Array<String>): String {
        val m = target.length
        val diffs = mutableListOf<Int>()
        for (word in dictionary) {
            if (word.length != m) continue
            var diff = 0
            for (i in 0 until m) {
                if (word[i] != target[i]) diff = diff or (1 shl i)
            }
            diffs.add(diff)
        }
        var minLen = m + 1
        var resMask = 0
        for (mask in 0 until (1 shl m)) {
            var valid = true
            for (d in diffs) {
                if (mask and d == 0) { valid = false; break }
            }
            if (valid) {
                var len = 0
                var cnt = 0
                for (i in 0 until m) {
                    if (mask and (1 shl i) != 0) {
                        if (cnt > 0) { len++; cnt = 0 }
                        len++
                    } else {
                        cnt++
                        if (i == m-1 || mask and (1 shl (i+1)) != 0) { len++; cnt = 0 }
                    }
                }
                if (len < minLen) { minLen = len; resMask = mask }
            }
        }
        val ans = StringBuilder()
        var cnt = 0
        for (i in 0 until m) {
            if (resMask and (1 shl i) != 0) {
                if (cnt > 0) { ans.append(cnt); cnt = 0 }
                ans.append(target[i])
            } else {
                cnt++
                if (i == m-1 || resMask and (1 shl (i+1)) != 0) { ans.append(cnt); cnt = 0 }
            }
        }
        return ans.toString()
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from typing import List
class Solution:
    def minAbbreviation(self, target: str, dictionary: List[str]) -> str:
        m = len(target)
        diffs = []
        for word in dictionary:
            if len(word) != m:
                continue
            diff = 0
            for i in range(m):
                if word[i] != target[i]:
                    diff |= (1 << i)
            diffs.append(diff)
        min_len, res_mask = m + 1, 0
        for mask in range(1 << m):
            valid = True
            for d in diffs:
                if (mask & d) == 0:
                    valid = False
                    break
            if valid:
                length, cnt = 0, 0
                for i in range(m):
                    if mask & (1 << i):
                        if cnt:
                            length += 1
                            cnt = 0
                        length += 1
                    else:
                        cnt += 1
                        if i == m - 1 or mask & (1 << (i + 1)):
                            length += 1
                            cnt = 0
                if length < min_len:
                    min_len = length
                    res_mask = mask
        ans = ''
        cnt = 0
        for i in range(m):
            if res_mask & (1 << i):
                if cnt:
                    ans += str(cnt)
                    cnt = 0
                ans += target[i]
            else:
                cnt += 1
                if i == m - 1 or res_mask & (1 << (i + 1)):
                    ans += str(cnt)
                    cnt = 0
        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
impl Solution {
    pub fn min_abbreviation(target: String, dictionary: Vec<String>) -> String {
        let m = target.len();
        let target_bytes = target.as_bytes();
        let mut diffs = Vec::new();
        for word in &dictionary {
            if word.len() != m { continue; }
            let word_bytes = word.as_bytes();
            let mut diff = 0;
            for i in 0..m {
                if word_bytes[i] != target_bytes[i] { diff |= 1 << i; }
            }
            diffs.push(diff);
        }
        let mut min_len = m + 1;
        let mut res_mask = 0;
        for mask in 0..(1 << m) {
            let mut valid = true;
            for &d in &diffs {
                if mask & d == 0 { valid = false; break; }
            }
            if valid {
                let mut len = 0;
                let mut cnt = 0;
                for i in 0..m {
                    if mask & (1 << i) != 0 {
                        if cnt > 0 { len += 1; cnt = 0; }
                        len += 1;
                    } else {
                        cnt += 1;
                        if i == m-1 || mask & (1 << (i+1)) != 0 { len += 1; cnt = 0; }
                    }
                }
                if len < min_len { min_len = len; res_mask = mask; }
            }
        }
        let mut ans = String::new();
        let mut cnt = 0;
        for i in 0..m {
            if res_mask & (1 << i) != 0 {
                if cnt > 0 { ans += &cnt.to_string(); cnt = 0; }
                ans.push(target_bytes[i] as char);
            } else {
                cnt += 1;
                if i == m-1 || res_mask & (1 << (i+1)) != 0 {
                    ans += &cnt.to_string(); cnt = 0;
                }
            }
        }
        ans
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
    minAbbreviation(target: string, dictionary: string[]): string {
        const m = target.length;
        const diffs: number[] = [];
        for (const word of dictionary) {
            if (word.length !== m) continue;
            let diff = 0;
            for (let i = 0; i < m; i++) {
                if (word[i] !== target[i]) diff |= (1 << i);
            }
            diffs.push(diff);
        }
        let minLen = m + 1, resMask = 0;
        for (let mask = 0; mask < (1 << m); mask++) {
            let valid = true;
            for (const d of diffs) {
                if ((mask & d) === 0) { valid = false; break; }
            }
            if (valid) {
                let len = 0, cnt = 0;
                for (let i = 0; i < m; i++) {
                    if (mask & (1 << i)) {
                        if (cnt) { len++; cnt = 0; }
                        len++;
                    } else {
                        cnt++;
                        if (i === m-1 || (mask & (1 << (i+1)))) { len++; cnt = 0; }
                    }
                }
                if (len < minLen) { minLen = len; resMask = mask; }
            }
        }
        let ans = '';
        let cnt = 0;
        for (let i = 0; i < m; i++) {
            if (resMask & (1 << i)) {
                if (cnt) { ans += cnt.toString(); cnt = 0; }
                ans += target[i];
            } else {
                cnt++;
                if (i === m-1 || (resMask & (1 << (i+1)))) {
                    ans += cnt.toString(); cnt = 0;
                }
            }
        }
        return ans;
    }
}

Complexity

  • ⏰ Time complexity: O(m * 2^m * n) — For each mask, check all dictionary words and compute abbreviation length.
  • 🧺 Space complexity: O(n + m) — For storing bitmasks and intermediate results.