Given a integer represented as a string, we need to get the sum of all possible substrings of this string.
Input : num = “1234” Output : 1670 Sum = 1 + 2 + 3 + 4 + 12 + 23 + 34 + 123 + 234 + 1234 = 1670 Input : num = “421” Output : 491 Sum = 4 + 2 + 1 + 42 + 21 + 421 = 491
We can solve this problem using dynamic programming. We can write summation of all substrings on basis of digit at which they are ending in that case,
Sum of all substrings = sumofdigit + sumofdigit + sumofdigit … + sumofdigit[n-1] where n is length of string.
Where sumofdigit[i] stores sum of all substring ending at ith index digit, in above example,
Example : num = "1234" sumofdigit = 1 = 1 sumofdigit = 2 + 12 = 14 sumofdigit = 3 + 23 + 123 = 149 sumofdigit = 4 + 34 + 234 + 1234 = 1506 Result = 1670
Now we can get the relation between sumofdigit values and can solve the question iteratively. Each sumofdigit can be represented in terms of previous value as shown below,
For above example, sumofdigit = 4 + 34 + 234 + 1234 = 4 + 30 + 4 + 230 + 4 + 1230 + 4 = 4*4 + 10*(3 + 23 +123) = 4*4 + 10*(sumofdigit) In general, sumofdigit[i] = (i+1)*num[i] + 10*sumofdigit[i-1]
Using above relation we can solve the problem in linear time. In below code a complete array is taken to store sumofdigit, as each sumofdigit value requires just previous value, we can solve this problem without allocating complete array also.
Time Complexity : O(n) where n is length of input string.
Auxiliary Space : O(n)
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.
- Program to print all substrings of a given string
- Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
- Find number of endless points
- Number of subsequences of the form a^i b^j c^k
- Lexicographically first palindromic string
- Count substrings with same first and last characters
- Modify array to maximize sum of adjacent differences
- Count of strings that can be formed using a, b and c under given constraints
- Gold Mine Problem
- Calculate sum of all numbers present in a string
- Count number of ways to reach a given score in a game
- Given two strings, find if first string is a subsequence of second
- Longest Common Substring | DP-29
- Coin Change | DP-7
- Longest Common Subsequence | DP-4