Ctrl K

Shortest Unambiguous Shorthand

Hard
A word can be shortened by replacing some non-overlapping, non-adjacent stretches of letters with their lengths. For example, transport can be shortened to t7t, tr2sp3, 9, or left as transport, while t25t is not allowed: the replaced stretches "ran" and "sport" touch each other. The length of a shorthand is the number of letters kept plus the number of replaced stretches: t7t has length 3, tr2sp3 has length 6. A shorthand fits a word if it can be produced from that word in the way described. You are given a word word and a list vocabulary. Find a shorthand of word of the smallest length that fits none of the vocabulary words. If several shortest ones exist, return the one that hides letters as far left as possible: compare two candidates position by position from the left, and at the first difference pick the one whose letter at that position is hidden inside a number.
Example 1
word='cat', vocabulary=['cut'] → '1a1'

"3", "c2" and "2t" also fit "cut". Among shorthands of length 3, the tie rule puts "1a1" first: it hides the first letter, and "cut" does not fit it because it has u where the a is.

Example 2
word='apple', vocabulary=[] → '5'

The vocabulary is empty, so the shortest shorthand of all, a single number, will do.

Example 3
word='plan', vocabulary=['plum', 'clan'] → 'p2n'

Every shorthand of length 2 fits one of the vocabulary words. Of the length-3 shorthands only "p2n" is free of clashes: "plum" ends in m and "clan" starts with c.

Constraints
  • 1 ≤ word.length ≤ 21
  • 0 ≤ vocabulary.length ≤ 1000
  • If k is the number of vocabulary words as long as word, then k · 2^word.length ≤ 2²¹
  • 1 ≤ vocabulary[i].length ≤ 100
  • All words consist of lowercase English letters
  • word is not in the vocabulary
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBest Word Set From Tiles HardEvery Way to Space the Words HardWords Hidden in a Letter Grid HardMirror Word Blocks HardSettle Up in the Fewest Transfers Hard
loading Python…
Input
word='cat', vocabulary=['cut']
Expected
'1a1'

Run checks the first 3 tests in your browser. Submit checks all 43 tests on the server, hidden ones included.