Sum of all substrings of a string representing a number
Last Updated :
21 May, 2025
Given an integer represented as a string, we need to get the sum of all possible substrings of this string.
Note: It is guaranteed that sum of all substring will fit within a 32-bit integer.
Examples:
Input: s = "6759"
Output: 8421
Explanation: sum = 6 + 7 + 5 + 9 + 67 + 75 +
59 + 675 + 759 + 6759
= 8421
Input: s = "16"
Output: 23
Explanation: sum = 1 + 6 + 16 = 23
Input: s = “421”
Output: 491
Explanation: Sum = 4 + 2 + 1 + 42 + 21 + 421 = 491
[Better Approach] Using Dynamic-Programming - O(n) Time and O(n) Space
To solve the problem follow the below idea:
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: s = "6759"
sumofdigit[0] = 6 = 6
sumofdigit[1] = 7 + 67 = 74
sumofdigit[2] = 5 + 75 + 675 = 755
sumofdigit[3] = 9 + 59 + 759 + 6759 = 7586
Result = 8421
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] = 9 + 59 + 759 + 6759
= 9 + 50 + 9 + 750 + 9 + 6750 + 9
= 9*4 + 10*(5 + 75 + 675)
= 9*4 + 10*(sumofdigit[2])
In general, sumofdigit[i] = (i+1)*s[i] + 10*sumofdigit[i-1]
Follow the given steps to solve the problem:
- Declare an array of size n to store the sum of previous digits, processed so far, and a variable result
- Traverse over the string and for every character
- Set sumOfDigit[i] = (i + 1) * toDigit(s[i]) + 10 * sumOfDigit[i-1]
- Add the value of sumOfDigit[i] to result
- Return result
C++
// C++ program to print sum of all substring of
// a sber represented as a string
#include <bits/stdc++.h>
using namespace std;
// Utility method to convert character digit to
// integer digit
int toDigit(char ch) { return (ch - '0'); }
// Returns sum of all substring of s
int sumOfSubstrings(string s){
int n = s.length();
// allocate memory equal to length of string
int sumofdigit[n];
// initialize first value with first digit
sumofdigit[0] = toDigit(s[0]);
int res = sumofdigit[0];
// loop over all digits of string
for (int i = 1; i < n; i++) {
int si = toDigit(s[i]);
// update each sumofdigit from previous value
sumofdigit[i]
= (i + 1) * si + 10 * sumofdigit[i - 1];
// add current value to the result
res += sumofdigit[i];
}
return res;
}
// Driver code
int main(){
string s = "6759";
// Function call
cout << sumOfSubstrings(s) << endl;
return 0;
}
Java
// Java program to print sum of all substring of
// a sber represented as a string
import java.util.Arrays;
class GfG {
// Returns sum of all substring of s
static int sumOfSubstrings(String s){
int n = s.length();
// allocate memory equal to length of string
int sumofdigit[] = new int[n];
// initialize first value with first digit
sumofdigit[0] = s.charAt(0) - '0';
int res = sumofdigit[0];
// loop over all digits of string
for (int i = 1; i < n; i++) {
int si = s.charAt(i) - '0';
// update each sumofdigit from previous value
sumofdigit[i]
= (i + 1) * si + 10 * sumofdigit[i - 1];
// add current value to the result
res += sumofdigit[i];
}
return res;
}
// Driver Code
public static void main(String[] args){
String s = "6759";
// Function call
System.out.println(sumOfSubstrings(s));
}
}
Python
# Python3 program to print
# sum of all substring of
# a sber represented as
# a string
# Returns sum of all
# substring of s
def sumOfSubstrings(s):
n = len(s)
# allocate memory equal
# to length of string
sumofdigit = []
# initialize first value
# with first digit
sumofdigit.append(int(s[0]))
res = sumofdigit[0]
# loop over all
# digits of string
for i in range(1, n):
si = int(s[i])
# update each sumofdigit
# from previous value
sumofdigit.append((i + 1) *
si + 10 * sumofdigit[i - 1])
# add current value
# to the result
res += sumofdigit[i]
return res
# Driver Code
if __name__ == '__main__':
s = "6759"
print(sumOfSubstrings(s))
C#
// C# program to print sum of
// all substring of a sber
// represented as a string
using System;
class GfG {
// Returns sum of all
// substring of s
static int sumOfSubstrings(String s){
int n = s.Length;
// allocate memory equal to
// length of string
int[] sumofdigit = new int[n];
// initialize first value
// with first digit
sumofdigit[0] = s[0] - '0';
int res = sumofdigit[0];
// loop over all digits
// of string
for (int i = 1; i < n; i++) {
int si = s[i] - '0';
// update each sumofdigit
// from previous value
sumofdigit[i]
= (i + 1) * si + 10 * sumofdigit[i - 1];
// add current value
// to the result
res += sumofdigit[i];
}
return res;
}
// Driver code
public static void Main(){
String s = "6759";
// Function call
Console.Write(sumOfSubstrings(s));
}
}
JavaScript
// Returns sum of all
// substring of s
function sumOfSubstrings(s)
{
let n = s.length;
// allocate memory equal to
// length of string
let sumofdigit = new Array(n);
// initialize first value
// with first digit
sumofdigit[0] = s[0].charCodeAt() - "0".charCodeAt();
let res = sumofdigit[0];
// loop over all digits
// of string
for (let i = 1; i < n; i++) {
let si = s[i].charCodeAt() - "0".charCodeAt();
// update each sumofdigit
// from previous value
sumofdigit[i]
= (i + 1) * si + 10 * sumofdigit[i - 1];
// add current value
// to the result
res += sumofdigit[i];
}
return res;
}
// Driver Code
let s = "6759";
console.log(sumOfSubstrings(s));
Time Complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(n)
[Expected Approach] Within Constant Space - O(n) Time and O(n) Space
The main idea is to analyze how each digit contributes to the sum of all substrings by observing its position and place value.
Let number be s = "6759".
1 10 100 1000
6 1 1 1 1
7 2 2 2
5 3 3
9 4
The above table indicates that, when all the substrings are converted further to the ones, tens, hundreds etc.. form, each index of the string will have some fixed occurrence. The 0'th index will have 1 occurrence each of ones, tens etc. The 1st will have 2, 2nd will have 3 and so on. Each digit at index i
appears in exactly (i + 1)
substrings ending at that digit. Additionally, its contribution is scaled by powers of 10 based on its position from the right.
So the total sum of all substrings can be expressed by evaluating how each digit contributes based on its position. For the string s = "6759"
, the sum becomes:
sum = 6*(1*1 + 1*10 + 1*100 + 1*1000) + 7*(2*1 + 2*10 + 2*100) +
5*(3*1 + 3*10) + 9*(4*1)
= 6*1*(1111) + 7*2*(111) + 5*3*(11) + 9*4*(1)
= 6666 + 1554 + 165 + 36
= 8421
Now, to handle the multiplication we will be having a multiplying factor which starts from 1. It's clear from the example that the multiplying factor(in reverse) is 1, 11, 111, ... and so on. So the multiplication will be based on three factors. number, its index, and a multiplying factor.
C++
// C++ program to print sum of all substring of
// a sber represented as a string
#include <bits/stdc++.h>
using namespace std;
// Returns sum of all substring of s
int sumOfSubstrings(string s){
long long int sum = 0;
// Here traversing the array in reverse
// order.Initializing loop from last element.
// mf is multiplying factor.
long long int mf = 1;
for (int i=s.size()-1; i>=0; i--){
// Each time sum is added to its previous
// sum. Multiplying the three factors as explained above.
// s[i]-'0' is done to convert char to int.
sum += (s[i]-'0')*(i+1)*mf;
// Making new multiplying factor as explained above.
mf = mf*10 + 1;
}
return sum;
}
// Driver code
int main(){
string s = "6759";
cout << sumOfSubstrings(s) << endl;
return 0;
}
Java
// Java program to print sum of all substring of
// a sber represented as a string
import java.util.Arrays;
class GfG {
// Returns sum of all substring of s
public static long sumOfSubstrings(String s){
// Initialize result
long sum = 0;
// Here traversing the array in reverse
// order.Initializing loop from last
// element.
// mf is multiplying factor.
long mf = 1;
for (int i = s.length() - 1; i >= 0; i --){
// Each time sum is added to its previous
// sum. Multiplying the three factors as
// explained above.
// s[i]-'0' is done to convert char to int.
sum += (s.charAt(i) - '0') * (i + 1) * mf;
// Making new multiplying factor as
// explained above.
mf = mf * 10 + 1;
}
return sum;
}
// Driver Code
public static void main(String[] args){
String s = "6759";
System.out.println(sumOfSubstrings(s));
}
}
Python
# Python3 program to print sum of all substring of
# a stdber represented as a string
# Returns sum of all substring of std
def sumOfSubstrings(std):
# Initialize result
sum = 0
# Here traversing the array in reverse
# order.Initializing loop from last
# element.
# mf is multiplying factor.
mf = 1
for i in range(len(std) - 1, -1, -1):
# Each time sum is added to its previous
# sum. Multiplying the three factors as
# explained above.
# int(s[i]) is done to convert char to int.
sum = sum + (int(std[i])) * (i + 1) * mf
# Making new multiplying factor as
# explained above.
mf = mf * 10 + 1
return sum
# Driver Code
if __name__=='__main__':
std = "6759"
print(sumOfSubstrings(std))
C#
// C# program to print sum of all substring of
// a sber represented as a string
using System;
class GfG {
// Returns sum of all substring of s
public static long sumOfSubstrings(string s){
long sum = 0;
// Here traversing the array in reverse
// order.Initializing loop from last
// element.
// mf is multiplying factor.
long mf = 1;
for (int i = s.Length - 1; i >= 0; i --)
{
// Each time sum is added to its previous
// sum. Multiplying the three factors as
// explained above.
// s[i]-'0' is done to convert char to int.
sum += (s[i] - '0') * (i + 1) * mf;
// Making new multiplying factor as
// explained above.
mf = mf * 10 + 1;
}
return sum;
}
// Driver Code
public static void Main() {
string s = "6759";
Console.WriteLine(sumOfSubstrings(s));
}
}
JavaScript
// Function returns sum of all substring of s
function sumOfSubstrings(s){
let sum = 0;
// Here traversing the array in reverse
// order.Initializing loop from last
// element.
// mf is multiplying factor.
let mf = 1;
for (let i = s.length - 1; i >= 0; i--) {
// Each time sum is added to its previous
// sum. Multiplying the three factors as
// explained above.
// s[i]-'0' is done to convert char to int.
sum += (s[i].charCodeAt() - "0".charCodeAt())
* (i + 1) * mf;
// Making new multiplying factor as
// explained above.
mf = mf * 10 + 1;
}
return sum;
}
// Driver Code
let s = "6759";
console.log(sumOfSubstrings(s));
Time complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
Given a string representing a number, we need to get the sum of all possible sub strings of this string. Examples : Input : s = "6759" Output : 8421 sum = 6 + 7 + 5 + 9 + 67 + 75 + 59 + 675 + 759 + 6759 = 8421 Input : s = "16" Output : 23 sum = 1 + 6 + 16 = 23Recommended PracticeSum of all substring
7 min read
Number of substrings of a string
Find total number of non-empty substrings of a string with N characters. Input : str = "abc" Output : 6 Every substring of the given string : "a", "b", "c", "ab", "bc", "abc" Input : str = "abcd" Output : 10 Every substring of the given string : "a", "b", "c", "d", "ab", "bc", "cd", "abc", "bcd" and
3 min read
Calculate sum of all numbers present in a string
Given a string S containing alphanumeric characters, The task is to calculate the sum of all numbers present in the string. Examples: Input: 1abc23Output: 24Explanation: 1 + 23 = 24 Input: geeks4geeksOutput: 4 Input: 1abc2x30yz67Output: 100 Recommended PracticeSum of numbers in stringTry It!Approach
13 min read
Sub-strings of a string that are prefix of the same string
Given a string str, the task is to count all possible sub-strings of the given string that are prefix of the same string. Examples: Input: str = "ababc" Output: 7 All possible sub-string are "a", "ab", "aba", "abab", "ababc", "a" and "ab" Input: str = "abdabc" Output: 8 Approach: Traverse the string
10 min read
Maximum number of set bits count in a K-size substring of a Binary String
Given a binary string S of size N and an integer K. The task is to find the maximum number of set bit appears in a substring of size K. Examples: Input: S = "100111010", K = 3 Output: 3 Explanation: The substring "111" contains 3 set bits. Input:S = "0000000", K = 4 Output: 0 Explanation: S doesn't
10 min read
Sum of all prefixes of given numeric string
Given string str having N characters representing an integer, the task is to calculate the sum of all possible prefixes of the given string. Example: Input: str = "1225"Output: 1360Explanation: The prefixes of the given string are 1, 12, 122, and 1225 and their sum will be 1 + 12 + 122 + 1225 = 1360
8 min read
Number of even substrings in a string of digits
Given a string of digits 0 - 9. The task is to count a number of substrings which when converting into integer form an even number. Examples : Input : str = "1234".Output : 6"2", "4", "12", "34", "234", "1234" are 6 substring which are even.Input : str = "154".Output : 3Input : str = "15".Output : 0
9 min read
Split the binary string into substrings with equal number of 0s and 1s
Given a binary string str of length N, the task is to find the maximum count of consecutive substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1.Example: Input
8 min read
Sum of all possible strings obtained by removal of non-empty substrings
Given numerical string str consisting of N integers, the task is to find the sum of all possible resulting strings after removing non-empty substrings.Examples:Input: str = "205"Output: 57Explanation: Substrings that can be removed are "2", "0", "5", "20", "05", "205". The resultant strings are "05"
8 min read
Number of substrings with odd decimal value in a binary string
Given a binary string containing only 0's and 1's. Write a program to find number of sub-strings of this string whose decimal representation is odd. Examples : Input : 101 Output : 3 Explanation : Substrings with odd decimal representation are: {1, 1, 101} Input : 1101 Output : 6 Explanation : Subst
6 min read