1783. No Echo Words

Medium3.5 points estimatedBacktrackingStringEnumeration

A password generator uses only the letters a, b and c, and it rejects any word that contains an echo: a block of one or more letters that is immediately followed by an identical copy of itself, such as aa, bcbc or abcabc appearing anywhere inside the word.

Given the length n, return every word of length exactly n over the alphabet "abc" that contains no echo. The words must be sorted in ascending alphabetical order and contain no duplicates. For example, aba is allowed but abab is not. Build words one letter at a time with backtracking; because the shorter prefix was already echo-free, only blocks that end at the newly added letter need to be checked. There are at most 264 words. Intended complexity: roughly O(W * n^2) time for W output words and O(n) extra space.

Example 1

Input:
n = 1
Output:
["a","b","c"]
Explanation:

A single letter cannot repeat a block, so the words are a, b and c.

Example 2

Input:
n = 2
Output:
["ab","ac","ba","bc","ca","cb"]
Explanation:

Of the 9 words of length 2, the three with doubled letters (aa, bb, cc) are removed, leaving 6.

Example 3

Input:
n = 3
Output:
["aba","abc","aca","acb","bab","bac","bca","bcb","cab","cac","cba","cbc"]
Explanation:

Words such as aba and abc survive, but aab, abb and any word containing a doubled letter do not; 12 words remain.

Constraints

1 ≤ n ≤ 12 (at most 264 words)

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(W * n^2)
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…