24. Sum of All Substrings of a Number
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given a string s
representing an integer number, return the sum of all possible substrings of this string interpreted as integers.
Each substring is formed by selecting a continuous sequence of characters from the original string. You must return the sum of all such substrings.
๐ก The number may contain leading zeros and the result will always fit in a 32-bit signed integer.
๐ Examples
Example 1:
Input:
s = "6759"
Output:
8421
Explanation:
Substrings: 6
, 7
, 5
, 9
, 67
, 75
, 59
, 675
, 759
, 6759
Sum = 6 + 7 + 5 + 9 + 67 + 75 + 59 + 675 + 759 + 6759 = 8421
Example 2:
Input:
s = "421"
Output:
491
Explanation:
Substrings: 4
, 2
, 1
, 42
, 21
, 421
Sum = 4 + 2 + 1 + 42 + 21 + 421 = 491
๐ Constraints
$1 \leq |s| \leq 9$
โ
My Approach
One-Pass Dynamic Contribution
The idea is to use dynamic programming to compute the cumulative contribution of each digit to all substrings ending at its position.
Let f(i)
be the sum of all substrings ending at index i
. Then we observe that:
f(0) = int(s[0])
f(i) = f(i-1) * 10 + (i+1) * int(s[i])
We maintain a running total of the result and update the current contribution using the above formula.
Algorithm Steps:
Initialize
res = 0
andf = 0
Traverse the string from index
0
ton-1
:Convert
s[i]
to integer and update:f = f * 10 + (i + 1) * digit
Add
f
to the result.
Return
res
.
๐งฎ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we iterate through the string once and perform constant-time operations at each step.
Expected Auxiliary Space Complexity: O(1), as we only use a fixed number of variables (
res
,f
, and loop index), regardless of input size.
๐งโ๐ป Code (C++)
class Solution {
public:
int sumSubstrings(string &s) {
long long res=0,f=0;
for(int i=0;i<s.size();++i){
f=f*10+(s[i]-'0')*(i+1);
res+=f;
}
return (int)res;
}
};
๐งโ๐ป Code (Java)
class Solution {
public static int sumSubstrings(String s) {
long res=0,f=0;
for(int i=0;i<s.length();++i){
f=f*10+(s.charAt(i)-'0')*(i+1);
res+=f;
}
return (int)res;
}
}
๐ Code (Python)
class Solution:
def sumSubstrings(self,s):
res=f=0
for i,ch in enumerate(s):
f=f*10+int(ch)*(i+1)
res+=f
return res
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Letโs make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated