636. Every Abbreviation

A word can be shortened by choosing some of its letters and replacing each maximal run of consecutive chosen letters by the length of that run. For example, choosing the middle three letters of planet gives p3t, and choosing the first and the last letter gives 1ane1. Choosing no letter leaves the word unchanged, and choosing all letters gives the word length.

Return every distinct abbreviation of word that can be produced this way, one per choice of letters, in any order. (Different choices always give different strings, so there are exactly 2^n of them.)

Example 1

Input:
word = "go"
Output:
["2","1o","g1","go"]
Explanation:

The four choices of letters give go (none chosen), 1o (g chosen), g1 (o chosen) and 2 (both chosen).

Example 2

Input:
word = "a"
Output:
["1","a"]
Explanation:

Either keep the letter (a) or abbreviate it (1).

Example 3

Input:
word = "bed"
Output:
["3","2d","1e1","1ed","b2","b1d","be1","bed"]
Explanation:

There are 2^3 = 8 choices: bed, 1ed, b1d, 2d, be1, 1e1, b2 and 3.

Constraints

  • 1 ≤ word.length ≤ 8
  • word consists of lowercase English letters.

How this problem is judged

Answers
The outer list may be in any order. Everything inside each item must match exactly.

Expected complexity

Time
O(n * 2^n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…