
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Additive Number in C++
We are given a string containing only digits from 0 to 9, and we need to check whether it is an additive number. An additive number is a string that can form an additive sequence, where each number (starting from the third) is the sum of the previous two. For the sequence to be valid, it must have at least three numbers.
Let's look at the example scenarios to understand the problem clearly:
Scenario 1
Input: "112358" Output: true Explanation: The digits can form the sequence: 1, 1, 2, 3, 5, 8 Here, 1 + 1 = 2 1 + 2 = 3 2 + 3 = 5 3 + 5 = 8 Since each number is the sum of the previous two, this is a valid additive sequence.
Scenario 2
Input: "11246" Output: false Explanation: The digits can form the sequence: 1, 1, 2, 4, 6 1 + 1 = 2 (valid) 1 + 2 = 3 (but the next number is 4, not 3 -> sequence breaks) So, it is not an additive sequence.
Checking an Additive Number
To check if a string can form an additive number, we use recursion with backtracking. Recursion means calling the same function again on a smaller part of the input, and backtracking means going back and trying a different option when the current conditions fail.
We first try all possible pairs for the first two numbers by breaking the string at different positions. Then we use recursion to check if the rest of the string follows the additive rule, where each number is the sum of the previous two. If not, we go back and try another starting pair.
Algorithm
Below are the steps:
- First, we use two nested loops to try every possible way to split the first and second numbers.
- We skip any pair that has leading zeros, like "01" or "002", since they are not valid.
- For each valid pair, we call a recursive function that adds the two numbers and checks if the next part of the string starts with their sum.
- If it matches, we keep checking the rest of the string using the same process.
- If the sum doesn't match, we backtrack and try another pair.
- If we reach the end of the string while matching all sums correctly, we return true.
- If no valid sequence is found after trying all combinations, we return false.
C++ Program to Check an Additive Number
Below is a complete C++ program where we implement the above steps to check if a given string is an additive number.
#include <bits/stdc++.h> using namespace std; typedef long long int lli; class Solution { public: // recursive function to check if the sequence continues correctly bool ok(string s, int idx, lli prev1, lli prev2) { if (idx >= s.size()) return true; lli req = prev1 + prev2; string num = to_string(req); string x = ""; for (int i = idx; i < s.size(); i++) { x += s[i]; // If the current part matches the required sum, go deeper if (x == num && ok(s, i + 1, prev2, stol(x))) return true; } return false; //backtracks } bool isAdditiveNumber(string num) { int n = num.size(); for (int i = 1; i < n - 1; i++) { for (int j = 1; j <= i; j++) { string s1 = num.substr(0, j); string s2 = num.substr(j, i - j + 1); // Skip cases with leading zeros if ((s1[0] == '0' && s1.size() > 1) || (s2[0] == '0' && s2.size() > 1)) continue; // to make sure enough digits remain int x = max((int)s1.size(), (int)s2.size()); if (x > n - i) continue; if (ok(num, i + 1, stol(s1), stol(s2))) return true; } } return false; } }; int main() { Solution ob; string input = "112358"; cout << "Input number: " << input << endl; if (ob.isAdditiveNumber(input)) cout << "Output: It is a valid additive sequence." << endl; else cout << "Output: It is not a valid additive sequence." << endl; }
The output of the above program is given below. It shows whether the input string is a valid additive sequence or not.
Input number: 112358 Output: It is a valid additive sequence.
Time Complexity: O(n^3) because we try all possible pairs of first and second numbers using two loops and then use recursion to validate the remaining string.
Space Complexity: O(n), because of the recursive call stack and temporary string creation in each recursive call.
Conclusion
In this article, we learned how to check if a string forms an additive sequence using recursion and backtracking. We tried all possible starting pairs and checked if each number is the sum of the previous two, with a time complexity of O(n^3) and a space complexity of O(n).