VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-of-all-possible-strings-obtained-by-removal-of-non-empty-substrings/

⇱ Sum of all possible strings obtained by removal of non-empty substrings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of all possible strings obtained by removal of non-empty substrings

Last Updated : 23 Jul, 2025

Given numerical stringstr 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: 57
Explanation: Substrings that can be removed are "2", "0", "5", "20", "05", "205". The resultant strings are "05", "25", "20", "5", "2", "0" respectively. Therefore, the sum will be 57.

Input: str = "1234"
Output: 680
Explanation: Substrings that can be removed are "1", "2", "3", "4", "12", "23", "34", "123", "234", "1234". The resultant strings are "234", "134", "124", "123", "34", "14", "12", "4", "1", "0" respectively. Therefore, the sum will be 680.

Approach: To solve the problem, the following observations need to be made:

Illustration:
Let str = "1234" 
All strings possible by removal of non-empty substrings and position of each character in these strings are as follows:

100101
234234
134134
124124
123123
3434
1414
1212
44
11
00

From the above table, get the contribution at every index, for exampleContribution at 1 -> ((1 + 2 + 3) * 1 + 4 * 6) * 1

Contribution at 10 -> ((1 + 2) * 2 + 3 * 3) * 10

Contribution at 100 -> ((1) * 3 + 2 * 1) * 100

Thus, generate a general formula for every index, i.e

Contribution at 1

Follow the steps below to solve the problem:  

  • Pre-compute powers of 10 and store in an array powers[].
  • Store the prefix sum of the digits of the given numerical string in array pref[].
  • Applying the above formula obtained, for every x from 0 to N - 1, calculate the sum.

Below is the implementation of the above approach:


Output
680

Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1)

Comment