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.
Examples:
Input: str = “125”
Output: 176
Explanation:
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 = 176Input: str = “9999999999”
Output: 12656242944
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:
Python3
# Python program to implement # the above approach # Function to find sum of all expressions by # inserting '+' operator at all possible indices def findSumOfExpressions(S, N): # Stores sum of all expressions by inserting # '+' operator at all possible indices sumOfExp = 0 # Generate all possible subset # of indices iteratively for i in range ( 2 * * (N - 1 )): # Stores sum of # current expressions ans_sub = 0 # Stores numbers of # current expressions subst = S[ 0 ] # Traverse the string at insert + at # current subset of indices for j in range (N - 1 ): # If current index exists # in the current subset if (i >> j) & 1 : # Update ans_sub ans_sub + = int (subst) # Update subst subst = S[j + 1 ] else : # Update subst subst + = S[j + 1 ] # + can't be inserted after # the last index if j = = N - 2 : ans_sub + = int (subst) # Update ans sumOfExp + = ans_sub # Base case if N = = 1 : print ( int (S)) else : # Print answer print (sumOfExp) # Driver Code if __name__ = = '__main__' : # Given string S = "9999999999" # Length of the string N = len (S) # Function call findSumOfExpressions(S, N) |
12656242944
Time Complexity: O(2N * N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.