Sum of all substrings of a string representing a number
Last Updated :
23 Jul, 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
[Naive Approach] Using Nested Loop - O(n^2) Time and O(1) Space
Generates every possible substring of the numeric string and treats each substring as a number (not just as characters). Then it adds the value of each such number to a running total.
C++
#include <iostream>
using namespace std;
// Function to calculate the sum of all substrings of a numeric string
int sumSubstrings(string &s) {
// Final answer to store the sum of all substrings
int ans = 0;
// Length of the input string
int n = s.size();
// Iterate through each starting index of substring
for (int i = 0; i < n; i++) {
// Temporary variable to hold current substring value
int temp = 0;
// Generate all substrings starting from index i
for (int j = i; j < n; j++) {
// Shift the previous value by one digit to the left
temp *= 10;
// Add current digit to form the number
temp += (s[j] - '0');
// Add the current substring number to the answer
ans += temp;
}
}
return ans;
}
// Driver code to test the function
int main() {
string s = "6759";
// Output the sum of all substrings
cout << sumSubstrings(s) << endl;
return 0;
}
Java
class GfG{
// Function to calculate the sum of all substrings of a numeric string
static int sumSubstrings(String s) {
// Final answer to store the sum of all substrings
int ans = 0;
// Length of the input string
int n = s.length();
// Iterate through each starting index of substring
for (int i = 0; i < n; i++) {
// Temporary variable to hold current substring value
int temp = 0;
// Generate all substrings starting from index i
for (int j = i; j < n; j++) {
// Shift the previous value by one digit to the left
temp *= 10;
// Add current digit to form the number
temp += (s.charAt(j) - '0');
// Add the current substring number to the answer
ans += temp;
}
}
// Return the final result
return ans;
}
// Main method to test the function
public static void main(String[] args) {
// Input numeric string
String s = "6759";
// Output the sum of all substrings
System.out.println(sumSubstrings(s));
}
}
Python
def sumSubstrings(s):
# Final answer to store the sum of all substrings
ans = 0
# Length of the input string
n = len(s)
for i in range(n):
# Temporary variable to hold current substring value
temp = 0
for j in range(i, n):
# Shift the previous value by one digit to the left
temp *= 10
# Add current digit to form the number
temp += int(s[j])
# Add the current substring number to the answer
ans += temp
return ans
if __name__ == "__main__":
s = "6759"
# Output the sum of all substrings
print(sumSubstrings(s))
C#
using System;
class GfG{
// Function to calculate the sum of all substrings of a numeric string
static int sumSubstrings(string s){
// Final answer to store the sum of all substrings
int ans = 0;
// Length of the input string
int n = s.Length;
// Iterate through each starting index of substring
for (int i = 0; i < n; i++){
// Temporary variable to hold current substring value
int temp = 0;
// Generate all substrings starting from index i
for (int j = i; j < n; j++){
// Shift the previous value by one digit to the left
temp *= 10;
// Add current digit to form the number
temp += (s[j] - '0');
// Add the current substring number to the answer
ans += temp;
}
}
// Return the final result
return ans;
}
// Main method to test the function
public static void Main(){
// Input numeric string
string s = "6759";
// Output the sum of all substrings
Console.WriteLine(sumSubstrings(s));
}
}
JavaScript
function sumSubstrings(s) {
// Final answer to store the sum of all substrings
let ans = 0;
// Length of the input string
let n = s.length;
for (let i = 0; i < n; i++) {
// Temporary variable to hold current substring value
let temp = 0;
for (let j = i; j < n; j++) {
// Shift the previous value by one digit to the left
temp *= 10;
// Add current digit to form the number
temp += (s[j] - '0');
// Add the current substring number to the answer
ans += temp;
}
}
return ans;
}
// Driver code to test the function
let s = "6759";
// Output the sum of all substrings
console.log(sumSubstrings(s));
[Better Approach] Using Dynamic Programming - O(n) Time and O(n) Space
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 sumSubstrings(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 << sumSubstrings(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 sumSubstrings(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(sumSubstrings(s));
}
}
Python
# Python3 program to print
# sum of all substring of
# a sber represented as
# a string
def sumSubstrings(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(sumSubstrings(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 sumSubstrings(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(sumSubstrings(s));
}
}
JavaScript
// Returns sum of all
// substring of s
function sumSubstrings(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(sumSubstrings(s));
[Expected Approach] Within Constant Space - O(n) Time and O(n) Space
After analyse 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 sumSubstrings(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 << sumSubstrings(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 sumSubstrings(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(sumSubstrings(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 sumSubstrings(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(sumSubstrings(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 sumSubstrings(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(sumSubstrings(s));
}
}
JavaScript
// Function returns sum of all substring of s
function sumSubstrings(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(sumSubstrings(s));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem