Sum of all substrings of a string representing a number | Set 1

08 Jul, 2022
Given an integer represented as a string, we need to get the sum of all possible substrings of this string.
Examples:  
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 by using dynamic programming. We can write a summation of all substrings on basis of the digit at which they are ending in that case, Sum of all substrings = sumofdigit[0] + sumofdigit[1] + sumofdigit[2] ... + sumofdigit[n-1] where n is length of string.Where sumofdigit[i] stores the sum of all substring ending at ith index digit, in the above example, 
Example : num = "1234"
sumofdigit[0] = 1 = 1
sumofdigit[1] = 2 + 12  = 14
sumofdigit[2] = 3 + 23  + 123 = 149
sumofdigit[3] = 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[3] = 4 + 34 + 234 + 1234
           = 4 + 30 + 4 + 230 + 4 + 1230 + 4
           = 4*4 + 10*(3 + 23 +123)
           = 4*4 + 10*(sumofdigit[2])
In general, 
sumofdigit[i]  =  (i+1)*num[i] + 10*sumofdigit[i-1]
Using the above relation we can solve the problem in linear time. In the below code a complete array is taken to store sumofdigit, as each sumofdigit value requires just the previous value, we can solve this problem without allocating the complete array also. 
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print sum of all substring of// a number represented as a string#include <bits/stdc++.h>using namespace std; // Utility method to convert character digit to// integer digitint toDigit(char ch){    return (ch - '0');} // Returns sum of all substring of numint sumOfSubstrings(string num){    int n = num.length();     // allocate memory equal to length of string    int sumofdigit[n];     // initialize first value with first digit    sumofdigit[0] = toDigit(num[0]);    int res = sumofdigit[0];     // loop over all digits of string    for (int i = 1; i < n; i++) {        int numi = toDigit(num[i]);         // update each sumofdigit from previous value        sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1];         // add current value to the result        res += sumofdigit[i];    }     return res;} // Driver code to test above methodsint main(){    string num = "1234";    cout << sumOfSubstrings(num) << endl;    return 0;}
// Java program to print sum of all substring of// a number represented as a stringimport java.util.Arrays; class GFG {     // Returns sum of all substring of num    public static int sumOfSubstrings(String num)    {        int n = num.length();         // allocate memory equal to length of string        int sumofdigit[] = new int[n];         // initialize first value with first digit        sumofdigit[0] = num.charAt(0) - '0';        int res = sumofdigit[0];         // loop over all digits of string        for (int i = 1; i < n; i++) {            int numi = num.charAt(i) - '0';             // update each sumofdigit from previous value            sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1];             // add current value to the result            res += sumofdigit[i];        }         return res;    }     // Driver code to test above methods    public static void main(String[] args)    {        String num = "1234";         System.out.println(sumOfSubstrings(num));    }}// This code is contributed by Arnav Kr. Mandal.
# Python program to print# sum of all substring of# a number represented as# a string # Returns sum of all# substring of numdef sumOfSubstrings(num):    n = len(num)     # allocate memory equal    # to length of string    sumofdigit = []     # initialize first value    # with first digit    sumofdigit.append(int(num[0]))    res = sumofdigit[0]     # loop over all    # digits of string    for i in range(1, n):        numi = int(num[i])         # update each sumofdigit        # from previous value        sumofdigit.append((i + 1) *                        numi + 10 * sumofdigit[i - 1])         # add current value        # to the result        res += sumofdigit[i]     return res # Driver codenum = "1234"print(sumOfSubstrings(num)) # This code is contributed# by Sanjit_Prasad
// C# program to print sum of// all substring of a number// represented as a stringusing System; class GFG {     // Returns sum of all    // substring of num    public static int sumOfSubstrings(String num)    {        int n = num.Length;         // allocate memory equal to        // length of string        int[] sumofdigit = new int[n];         // initialize first value        // with first digit        sumofdigit[0] = num[0] - '0';        int res = sumofdigit[0];         // loop over all digits        // of string        for (int i = 1; i < n; i++) {            int numi = num[i] - '0';             // update each sumofdigit            // from previous value            sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1];             // add current value            // to the result            res += sumofdigit[i];        }         return res;    }     // Driver code    public static void Main()    {        String num = "1234";         Console.Write(sumOfSubstrings(num));    }} // This code is contributed by Nitin Mittal.
<?php// PHP program to print sum of all// substring of a number represented// as a string // Method to convert character// digit to integer digitfunction toDigit($ch){    return ($ch - '0');} // Returns sum of all// substring of numfunction sumOfSubstrings($num){    $n = strlen($num);     // allocate memory equal to    // length of string    $sumofdigit[$n] = 0;     // initialize first value    // with first digit    $sumofdigit[0] = toDigit($num[0]);    $res = $sumofdigit[0];     // loop over all digits of string    for($i = 1; $i < $n; $i++)    {        $numi = toDigit($num[$i]);         // update each sumofdigit        // from previous value        $sumofdigit[$i] = ($i + 1) * $numi + 10 *                              $sumofdigit[$i - 1];         // add current value to the result        $res += $sumofdigit[$i];    }     return $res;}     // Driver Code    $num = "1234";    echo sumOfSubstrings($num) ;     // This code is contributed by nitin mittal.?>
<script>     // Javascript program to print sum of    // all substring of a number    // represented as a string         // Returns sum of all    // substring of num    function sumOfSubstrings(num)    {        let n = num.length;          // allocate memory equal to        // length of string        let sumofdigit = new Array(n);          // initialize first value        // with first digit        sumofdigit[0] = num[0].charCodeAt() - '0'.charCodeAt();        let res = sumofdigit[0];          // loop over all digits        // of string        for (let i = 1; i < n; i++) {            let numi = num[i].charCodeAt() - '0'.charCodeAt();              // update each sumofdigit            // from previous value            sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1];              // add current value            // to the result            res += sumofdigit[i];        }          return res;    }         let num = "1234";        document.write(sumOfSubstrings(num));     </script>
1670
 
Time Complexity: O(n) where n is the length of the input string. Auxiliary Space: O(n)
Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
O(1) space approach:
The approach is the same as described above. What we have observed that at the current index we are dependent on the current sum + previous index sum so instead of storing in a dp array we can store it in two variables current and prev.
Implementation:
C++14
Java
Python3
C#
Javascript
// C++ program to print sum of all substring of// a number represented as a string#include <bits/stdc++.h>using namespace std; // Utility method to convert character digit to// integer digitint toDigit(char ch){    return (ch - '0');} // Returns sum of all substring of numint sumOfSubstrings(string num){    int n = num.length();     // storing prev value    int prev = toDigit(num[0]);     int res = prev; // ans     int current = 0;     // substrings sum upto current index    // loop over all digits of string    for (int i = 1; i < n; i++) {        int numi = toDigit(num[i]);         // update each sumofdigit from previous value        current = (i + 1) * numi + 10 * prev;         // add current value to the result        res += current;        prev = current; // update previous    }     return res;} // Driver code to test above methodsint main(){    string num = "1234";    cout << sumOfSubstrings(num) << endl;    return 0;}
// Java program to print// sum of all subString of// a number represented as a Stringimport java.util.*;class GFG{ // Utility method to// convert character// digit to integer digitstatic int toDigit(char ch){  return (ch - '0');} // Returns sum of all subString of numstatic int sumOfSubStrings(String num){  int n = num.length();   // Storing prev value  int prev = toDigit(num.charAt(0));   int res = prev;   int current = 0;   // SubStrings sum upto current index  // loop over all digits of String  for (int i = 1; i < n; i++)  {    int numi = toDigit(num.charAt(i));     // Update each sumofdigit    // from previous value    current = (i + 1) * numi + 10 * prev;     // Add current value to the result    res += current;         // Update previous    prev = current;  }  return res;} // Driver code to test above methodspublic static void main(String[] args){  String num = "1234";  System.out.print(sumOfSubStrings(num) + "\n");}} // This code is contributed by gauravrajput1
# Python3 program to print sum of all substring of# a number represented as a string # Returns sum of all substring of numdef sumOfSubstrings(num) :     n = len(num)      # storing prev value    prev = int(num[0])      res = prev # ans      current = 0      # substrings sum upto current index    # loop over all digits of string    for i in range(1, n) :        numi = int(num[i])          # update each sumofdigit from previous value        current = (i + 1) * numi + 10 * prev          # add current value to the result        res += current        prev = current # update previous      return res     num = "1234"print(sumOfSubstrings(num)) # This code is contributed by divyeshrabadiya07
// C# program to print sum of all substring of// a number represented as a stringusing System;class GFG {       // Utility method to    // convert character    // digit to integer digit    static int toDigit(char ch)    {      return (ch - '0');    }          // Returns sum of all subString of num    static int sumOfSubStrings(string num)    {      int n = num.Length;            // Storing prev value      int prev = toDigit(num[0]);            int res = prev;            int current = 0;            // SubStrings sum upto current index      // loop over all digits of String      for (int i = 1; i < n; i++)      {        int numi = toDigit(num[i]);              // Update each sumofdigit        // from previous value        current = (i + 1) * numi + 10 * prev;              // Add current value to the result        res += current;                  // Update previous        prev = current;      }      return res;    }   static void Main() {    string num = "1234";    Console.WriteLine(sumOfSubStrings(num));  }} // This code is contributed by divyesh072019
<script> // JavaScript program to print// sum of all subString of// a number represented as a String // Utility method to// convert character// digit to integer digitfunction toDigit(ch){  return (ch - '0');} // Returns sum of all subString of numfunction sumOfSubStrings(num){  let n = num.length;   // Storing prev value  let prev = toDigit(num[0]);   let res = prev;   let current = 0;   // SubStrings sum upto current index  // loop over all digits of String  for (let i = 1; i < n; i++)  {    let numi = toDigit(num[i]);     // Update each sumofdigit    // from previous value    current = (i + 1) * numi + 10 * prev;     // Add current value to the result    res += current;         // Update previous    prev = current;  }  return res;} // Driver Code         let num = "1234";  document.write(sumOfSubStrings(num) + "\n"); </script>
1670
 
Time complexity: O(n)Auxiliary Space: O(1)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
nitin mittal
Sanjit_Prasad
md1844
Akanksha_Rai
GauravRajput1
divyesh072019
divyeshrabadiya07
mukesh07
sanjoy_62
simranarora5sos
surbhikumaridav
hardikkoriintern
number-digits
Dynamic Programming
Strings
Strings
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Floyd Warshall Algorithm | DP-16
Sieve of Eratosthenes
Matrix Chain Multiplication | DP-8
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack