Ctrl K

Distinct Word Shorthands

Hard
You are given an array of distinct words words. Give every word a shorthand by the following rules. The shorthand with a prefix of length p is the first p letters of the word, then the number of letters skipped in the middle, then the last letter. For example, internal with p = 1 becomes i6l, and with p = 3 it becomes int4l. All words start with p = 1. While several words share the same shorthand, each of those words increases its p by 1; this repeats until all shorthands are different. If the final shorthand is not shorter than the word itself, the whole word is used instead. Return the array of final shorthands in the same order as words.
Example 1
words=['apple', 'ample', 'angle', 'ankle'] → ['ap2e', 'am2e', 'angle', 'ankle']

All four words start out as "a3e", so the prefix grows. With two letters "ap2e" and "am2e" are already unique, while "angle" and "ankle" differ only at the third letter: "ang1e" and "ank1e" are no shorter than the words, so those stay as they are.

Example 2
words=['moon', 'mean', 'star'] → ['moon', 'mean', 's2r']

"moon" and "mean" clash on "m2n", and "mo1n" and "me1n" are no shorter than the words. "star" becomes "s2r".

Example 3
words=['ok', 'yes'] → ['ok', 'yes']

The shorthands "o0k" and "y1s" are no shorter than the words, so both stay unchanged.

Constraints
  • 1 ≤ words.length ≤ 400
  • 2 ≤ words[i].length ≤ 400
  • words[i] consists of lowercase English letters only
  • all words in words are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBiggest Number From Pieces MediumMost Searched Words MediumWord Grown Letter by Letter MediumWords Hidden in a Text MediumRound Prices to a Total Medium
loading Python…
Input
words=['apple', 'ample', 'angle', 'ankle']
Expected
['ap2e', 'am2e', 'angle', 'ankle']

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