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: "112358" โ†’ [1, 1, 2, 3, 5, 8] (Fibonacci!)
But "199100199" โ†’ [199, 100, 299] won't work because 199 + 100 = 299, not 199

Goal: 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
๐Ÿงฌ DNA Sequence Pattern DetectionInput DNA Sequence: "112358"Goal: Find if this can be split into additive patternStep 1-2: Try Different Gene Splits112358โŒ 1+12=13 โ‰  35112358โœ… Perfect match!Step 3-4: Validate Additive Pattern1+121+232+35๐ŸŽฏ Pattern Found: [1,1,2,3,5,8] - Classic Fibonacci!Result: true
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

n
2n
โš  Quadratic Growth
Space Complexity
O(n)

Space for storing the generated sequence and recursive call stack

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค num.length โ‰ค 35
  • num consists only of digits
  • No leading zeros allowed except for the number "0" itself
Asked in
Google 15 Amazon 8 Meta 6 Microsoft 4
27.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen