FastPrepUnique Word Abbreviations

Unique Word Abbreviations

Google logoGoogle● MediumINTERNONSITE INTERVIEW
Learn

Problem statement

Given an array of distinct lowercase words, return one unique abbreviation for every word in the same order.

An abbreviation keeps a nonempty prefix, replaces the omitted middle characters with their decimal count, and keeps the final character. For example, using a one-character prefix turns localization into l10n.

For each word, use the shortest prefix that makes its abbreviation different from every other returned abbreviation. If that abbreviation is not strictly shorter than the original word, return the original word instead.

Function

abbreviateWords(words: String[]) → String[]

Examples

Example 1

words = ["like","god","internal","me","internet","interval","intension","face","intrusion"]return = ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"]

Conflicting words receive longer prefixes. Short words or abbreviations that would not save space remain unchanged.

Example 2

words = ["apple","blade"]return = ["a3e","b3e"]

The one-letter prefixes already distinguish the two abbreviations.

Constraints

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 400
  • The words are distinct and contain only lowercase English letters.
  • The sum of all word lengths is at most 10^5.

More Google problems

See Google hiring insights
public String[] abbreviateWords(String[] words) {
    // Write your code here.
}
words["like","god","internal","me","internet","interval","intension","face","intrusion"]
expected["l2e", "god", "internal", "me", "i6t", "interval", "inte4n", "f2e", "intr4n"]
Checking account…