Additive Number - Problem

An additive number is a string whose digits can form an additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.

Given a string containing only digits, return true if it is an additive number or false otherwise.

Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Input & Output

Example 1 — Valid Additive Number
$ Input: num = "112358"
Output: true
💡 Note: The digits can form additive sequence: 1, 1, 2, 3, 5, 8. 1+1=2, 1+2=3, 2+3=5, 3+5=8
Example 2 — Invalid Sequence
$ Input: num = "199100199"
Output: true
💡 Note: The additive sequence is: 1, 99, 100, 199. 1+99=100, 99+100=199
Example 3 — No Valid Sequence
$ Input: num = "1023"
Output: false
💡 Note: Cannot form a valid additive sequence without leading zeros

Constraints

  • 1 ≤ num.length ≤ 35
  • num consists only of digits

Visualization

Tap to expand
Additive Number - Optimized Backtracking INPUT String: num = "112358" 1 i=0 1 i=1 2 i=2 3 i=3 5 i=4 8 i=5 Find if digits form additive sequence Rules: - At least 3 numbers - Each num = prev1 + prev2 - No leading zeros Length: 6 characters ALGORITHM STEPS 1 Pick first number Try all lengths: "1" 2 Pick second number Try all lengths: "1" 3 Validate sequence Check: n3 = n1 + n2 4 Backtrack with pruning Skip if leading zero Sequence Discovery: 1 + 1 = 2 OK 1 + 2 = 3 OK 2 + 3 = 5 OK FINAL RESULT Valid Additive Sequence Found! Sequence: 1 , 1 , 2 , 3 5 , 8 Output: true Verification: 1+1=2, 1+2=3, 2+3=5, 3+5=8 All conditions satisfied! Key Insight: Backtracking with pruning efficiently explores all possible first two number combinations. Once we fix the first two numbers, the rest of the sequence is deterministic (each next = sum of previous two). We prune invalid paths early: skip numbers with leading zeros, and stop when sum exceeds remaining string length. TutorialsPoint - Additive Number | Optimized Backtracking with Pruning
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
28.5K Views
Medium Frequency
~25 min Avg. Time
756 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