Sum of all possible expressions of a numeric string possible by inserting addition operators
Given a numeric string str of length N, the task is to find the sum of all possible expressions by inserting the ‘+’ operator between the characters of the string any number of times.
Input: str = “125”
Inserting “+” after 1st index modifies str to “1+25” and value = 26
Inserting “+” after 2nd index modifies str to “12+5” and value = 17
Inserting “+” after both 1st and 2nd index modifies str to “1+2+5” and value = 8
Therefore, the total sum of all possible expression is 125 + 26 + 17 + 8 = 176
Input: str = “9999999999”
Approach: The idea is to insert the ‘+’ operator at all possible index of the string in all possible ways and calculate the sum. Finally, print the total sum obtained. Follow the steps below to solve the problem:
- Initialize a variable say, sumOfExp to store the sum of all possible expression by inserting the ‘+’ operator at all possible indices of the string.
- Generate all possible subset of indices of the string iteratively. For every subset of indices inserts the ‘+’ operator at elements of the subset and increment sumOfExp by the sum of the current expression.
- Finally, print the value of sumOfExp.
Below is the implementation of the above approach:
Time Complexity: O(2N * N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.