Additive Number - Problem
Additive Number is a fascinating string validation problem that tests your ability to find patterns in digit sequences.
An additive number is a string whose digits can be partitioned to form an additive sequence - similar to the famous Fibonacci sequence! The rules are:
๐ข At least three numbers must be in the sequence
โ Each number (after the first two) must equal the sum of the two preceding numbers
๐ซ No leading zeros allowed (except for the number "0" itself)
For example:
But
Goal: Return
An additive number is a string whose digits can be partitioned to form an additive sequence - similar to the famous Fibonacci sequence! The rules are:
๐ข At least three numbers must be in the sequence
โ Each number (after the first two) must equal the sum of the two preceding numbers
๐ซ No leading zeros allowed (except for the number "0" itself)
For example:
"112358" โ [1, 1, 2, 3, 5, 8] (Fibonacci!)But
"199100199" โ [199, 100, 299] won't work because 199 + 100 = 299, not 199Goal: Return
true if the string can form a valid additive sequence, false otherwise. Input & Output
example_1.py โ Basic Fibonacci
$
Input:
"112358"
โบ
Output:
true
๐ก Note:
Can be split as [1, 1, 2, 3, 5, 8] where 1+1=2, 1+2=3, 2+3=5, 3+5=8 (Fibonacci sequence)
example_2.py โ Invalid Sequence
$
Input:
"199100199"
โบ
Output:
false
๐ก Note:
Cannot form valid additive sequence. 199+100=299, not 199. No other valid splits exist.
example_3.py โ Leading Zeros
$
Input:
"101"
โบ
Output:
true
๐ก Note:
Can be split as [1, 0, 1] where 1+0=1. The number '0' itself is valid, but '01' would not be.
Visualization
Tap to expand
Understanding the Visualization
1
Choose First Gene
Select the length of the first number in the sequence
2
Choose Second Gene
Select the length of the second number, ensuring no leading zeros
3
Predict Pattern
Generate the expected additive sequence: next = first + second
4
Validate Match
Check if the predicted sequence matches the remaining digits
5
Continue or Backtrack
If match found, continue; otherwise try next combination
Key Takeaway
๐ฏ Key Insight: Once you fix the first two numbers, the entire sequence is determined! The challenge is efficiently trying different splits while respecting the no-leading-zeros constraint.
Time & Space Complexity
Time Complexity
O(nยณ)
O(nยฒ) for trying all pairs of first two numbers, O(n) for validating each sequence
โ Quadratic Growth
Space Complexity
O(n)
Space for storing the generated sequence and recursive call stack
โก Linearithmic Space
Constraints
- 1 โค num.length โค 35
- num consists only of digits
- No leading zeros allowed except for the number "0" itself
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code