Google | Onsite | Number of Valid Strings
3603

Given an int n, output number of valid strings of length n consisting of letters A, B and C. Any continuous three letters containing all three letters A, B, C make the whole string invalid. For example, BACCA is not a valid string because of the first three characters, but CCCACCAABBB is a valid string.

Example 1:

Input: n = 0
Output: 0

Example 2:

Input: n = 1
Output: 3
Explanation: A, B, C

Example 3:

Input: n = 2
Output: 9
Explanation: AA, AB, AC, BA, BB, BC, CA, CB, CC

Example 4:

Input: n = 3
Output: 21
Explanation: 3^3 - 6 (ABC, ACB, BAC, BCA, CBA, CAB)

Example 5:

Input: n = 4
Output: 51
Challenge

O(1) space solution.

Comments (14)