Count Good Strings Problem
Description
LeetCode Problem 4073.
You are given an integer n.
A string is considered good if it consists only of the characters 'a' and 'b', and one of the following holds:
- It contains exactly one distinct character, and its length is odd.
- It can be written as
s = s1 + s2, wheres1ands2are non-empty good strings, and the last character ofs1is different from the first character ofs2.
Return the number of good strings of length n, modulo 10^9 + 7.
Here, + denotes string concatenation.
Example 1:
Input: n = 4
Output: 6
Explanation:
- The good strings are "aaab", "abbb", "baaa", "bbba", "abab", and "baba".
- For example, "aaab" = "aaa" + "b". Both parts are good because each contains one distinct character and has odd length, and their characters at the boundary are different.
- Also, "ab" = "a" + "b" is good, so "abab" = "ab" + "ab" is good because the boundary characters are different.
- Thus, the answer is 6.
Example 2:
Input: n = 3
Output: 4
Explanation:
The good strings are "aaa", "bbb", "aba", and "bab". Thus, the answer is 4.
Example 3:
Input: n = 2
Output: 2
Explanation:
The good strings are "ab" and "ba". Thus, the answer is 2.
Constraints:
1 <= n <= 10^15
Solution
Approach: Odd runs and Fibonacci numbers
Join two good strings whose boundary characters differ, and the maximal blocks of equal characters (runs) of the parts stay intact. So a good string is exactly a string of a and b in which every run has odd length (brute force over small n agrees).
Such a string is determined by its first character (2 choices) and by how n is split into an ordered list of odd run lengths. The number of compositions of n into odd parts is the Fibonacci number F(n) (F(1) = F(2) = 1), because the first part is either 1 (leaving n - 1) or at least 3, and counting the second case as "add 2 to the first part of a composition of n - 2" gives F(n) = F(n-1) + F(n-2).
The answer is 2 * F(n) mod (10^9 + 7). With n up to 10^15, compute F(n) with fast doubling:
F(2k) = F(k) * (2 * F(k+1) - F(k))F(2k+1) = F(k)^2 + F(k+1)^2
Complexity: O(log n) time and O(1) extra space (Python uses O(log n) for recursion).
class Solution:
def countGoodStrings(self, n: int) -> int:
mod = 10**9 + 7
def fib(k: int):
# returns (F(k), F(k + 1)) by fast doubling
if k == 0:
return 0, 1
a, b = fib(k >> 1)
c = a * ((2 * b - a) % mod) % mod
d = (a * a + b * b) % mod
return (d, (c + d) % mod) if k & 1 else (c, d)
return 2 * fib(n)[0] % mod