Sum of all substrings of a string representing a number | (Constant Extra Space)
Last Updated :
21 May, 2025
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
Explanation: sum = 6 + 7 + 5 + 9 + 67 + 75 +
59 + 675 + 759 + 6759
= 8421
Input: s = "16"
Output: 23
Explanation: sum = 1 + 6 + 16 = 23
Approach
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 number represented as a string
#include <bits/stdc++.h>
using namespace std;
// Returns sum of all substring of num
int sumOfSubstrings(string s){
int sum = 0;
// Here traversing the array in reverse
// order.Initializing loop from last element.
// mf is multiplying factor.
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 number represented as a string
import java.util.Arrays;
class GfG {
// Returns sum of all substring of num
static int sumOfSubstrings(String s){
// Initialize result
int sum = 0;
// Here traversing the array in reverse
// order.Initializing loop from last
// element.
// mf is multiplying factor.
int 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));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python
# Python3 program to print sum of all substring of
# a number represented as a string
# Returns sum of all substring of num
def sumOfSubstrings(s):
# 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(s) - 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(s[i])) * (i + 1) * mf
# Making new multiplying factor as
# explained above.
mf = mf * 10 + 1
return sum
# Driver Code
if __name__=='__main__':
s = "6759"
print(sumOfSubstrings(s))
C#
// C# program to print sum of all substring of
// a number represented as a string
using System;
class GfG {
// Returns sum of all substring of num
static int sumOfSubstrings(string s){
int sum = 0;
// Here traversing the array in reverse
// order.Initializing loop from last
// element.
// mf is multiplying factor.
int 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));
}
}
// This code is contributed by Sam007.
JavaScript
// Function returns sum of all substring of num
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), where n is size of the s.
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: 8421Explanation: sum = 6 + 7 + 5 + 9 + 67 + 75 + 59 + 675 + 759 + 6759 = 8421Input: s = "16"Output: 23Explanation: sum = 1 + 6 + 16 = 23ApproachThe main idea is
6 min read
Sum of all substrings of a string representing a number | Set 1 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: 8421Explanation: sum = 6 + 7 + 5 + 9 + 67 + 75 + 59 + 675 + 759 + 6759 = 842
14 min read
Count number of substrings of a string consisting of same characters Given a string. The task is to find out the number of substrings consisting of the same characters. Examples: Input: abba Output: 5 The desired substrings are {a}, {b}, {b}, {a}, {bb} Input: bbbcbb Output: 10 Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of su
6 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
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
Count of substrings of a binary string containing K ones Given a binary string of length N and an integer K, we need to find out how many substrings of this string are exist which contains exactly K ones. Examples: Input : s = â10010â K = 1 Output : 9 The 9 substrings containing one 1 are, â1â, â10â, â100â, â001â, â01â, â1â, â10â, â0010â and â010âRecommen
7 min read
Number of substrings divisible by 6 in a string of integers Given a string consisting of integers 0 to 9. The task is to count the number of substrings which when convert into integer are divisible by 6. Substring does not contain leading zeroes. Examples: Input : s = "606". Output : 5 Substrings "6", "0", "6", "60", "606" are divisible by 6. Input : s = "48
9 min read
Count the sum of count of distinct characters present in all Substrings Given a string S consisting of lowercase English letters of size N where (1 <= N <= 105), the task is to print the sum of the count of distinct characters N where (1 <= N <= 105)in all the substrings. Examples: Input: str = "abbca"Output: 28Explanation: The following are the substrings o
8 min read
Count distinct substrings of a string using Rabin Karp algorithm Given a string, return the number of distinct substrings using Rabin Karp Algorithm. Examples: Input : str = âabaâOutput : 5Explanation :Total number of distinct substring are 5 - "a", "ab", "aba", "b" ,"ba" Input : str = âabcdâOutput : 10Explanation :Total number of distinct substring are 10 - "a",
9 min read
Count the number of vowels occurring in all the substrings of given string Given a string of length N of lowercase characters containing 0 or more vowels, the task is to find the count of vowels that occurred in all the substrings of the given string. Examples: Input: str = "abc" Output: 3The given string "abc" contains only one vowel = 'a' Substrings of "abc" are = {"a",
12 min read