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.
Input : s = “235813” Output : true 2 + 3 = 5, 3 + 5 = 8, 5 + 8 = 13 Input : s = “199100199” Output : true 1 + 99 = 100, 99 + 100 = 199 Input : s = “12345678” Output : false
This problem can be solved recursively, note that number of digits in added value can’t be smaller than digits in any of its operand that is why we will loop till (length of string)/2 for first number and (length of string – first number’s length)/ 2 for second number to ignore invalid result.
Next thing to note is, first and second number can’t start with 0, which is checked in below code by isValid method. When we call recursively, we check that sum of first and second number is exactly equal to rest of string. If yes then direct return the result else check that sum string is prefix of rest of string or not, If yes then call recursively with second number, sum string and rest of string after removing sum string from rest of string and if sum string is not prefix of rest of string then no solution in available.
Below is C++ implementation.
2 3 5 8 13 1 99 100 199
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Convert String into Binary Sequence
- Lexicographically largest sub-sequence of the given string
- Replace every consonant sequence with its length in the given string
- Longest sub-sequence of a binary string divisible by 3
- Check if there exists any sub-sequence in a string which is not palindrome
- Check whether frequency of characters in a string makes Fibonacci Sequence
- Number of ways to divide string in sub-strings such to make them in lexicographically increasing sequence
- Convert an unbalanced bracket sequence to a balanced sequence
- Look-and-Say Sequence
- Recaman's sequence
- De Bruijn sequence | Set 1
- Thue-Morse sequence
- Second most repeated word in a sequence
- Moser-de Bruijn Sequence
- Generate a sequence with the given operations