VOOZH about

URL: https://www.geeksforgeeks.org/dsa/string-with-additive-sequence/

⇱ String with additive sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

String with additive sequence

Last Updated : 15 May, 2026

Given a string, the task is to find whether it contains an additive sequence or not. A string contains an additive sequence if its digits can make a sequence of numbers in which every number is addition of previous two numbers. A valid string should contain at least three digit to make one additive sequence. 

Examples: 

Input : s = ā€œ235813ā€
Output : true
Explanation: 2 + 3 = 5, 3 + 5 = 8, 5 + 8 = 13

Input : s = ā€œ199100199ā€
Output : true
Explanation: 1 + 99 = 100, 99 + 100 = 199

Input : s = ā€œ12345678ā€
Output : false

[Naive Approach] Using Recursion + String Addition – O(n³) Time and O(n) Space

The idea is to try all possible ways to split the string into the first two numbers, then check if the string after the two is sum of the two and recursively verify whether the rest of the string follows the additive sequence property.

  • Run two nested loops for i and j to try all possible combinations of first two strings of lengths i and j respectively.
  • Check if sum of substring from 0 to i-1 and i to i+j-1 is present at the index starting from i+j.
  • Recursively check if remaining string follows sum pattern
  • Return true if any valid sequence is found, otherwise false

Output
true

[Better Approach] Using Iteration + String Simulation – O(n³) Time and O(n) Space

The idea is to avoid deep recursion and instead simulate the additive sequence iteratively. We try all possible splits for the first two numbers and then keep generating the next number using string addition. At each step, we check whether the generated sum matches the corresponding substring in the original string. If the sequence continues till the end, it is valid.

  • Try all possible splits for first and second numbers
  • Iteratively generate next numbers using string addition
  • Check if generated sum matches the next part of the string
  • Continue until string ends or mismatch occurs and return result

Output
true
Comment
Article Tags: