![]() |
VOOZH | about |
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:
100 10 1 234 2 3 4 134 1 3 4 124 1 2 4 123 1 2 3 34 3 4 14 1 4 12 1 2 4 4 1 1 0 0 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:
Below is the implementation of the above approach:
680
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1)