Problem · String

Generate All Valid Word Abbreviations

Learn this problem
MediumSalesforce logoSalesforceFULLTIMEONSITE INTERVIEW
See Salesforce hiring insights

Problem statement

Given a lowercase word, generate every valid abbreviation of that word.

  • Each character is either kept literally or replaced by a count of consecutive abbreviated characters.
  • Adjacent abbreviated characters must be merged into one decimal count.
  • Every distinct abbreviation appears exactly once.

Return all abbreviations in ascending lexicographic order.

Function

generateAbbreviations(word: String) → String[]

Examples

Example 1

word = "ab"return = ["1b","2","a1","ab"]

The four keep-or-abbreviate choices produce 1b, 2, a1, and ab after sorting.

Example 2

word = "a"return = ["1","a"]

The single character can be abbreviated as 1 or kept as a.

Constraints

  • 1 <= word.length <= 15.
  • word contains lowercase English letters.
  • Lexicographic comparison uses ordinary character-code order.

More Salesforce problems

drafts saved locally
public String[] generateAbbreviations(String word) {
    // TODO: generate each abbreviation once and return the sorted results.
}
word"ab"
expected["1b", "2", "a1", "ab"]
checking account