Sum of all possible strings obtained by removal of non-empty substrings
Last Updated :
17 Sep, 2024
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: 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 10x = (\Sigma(n - x - 2) * (x + 1) + str[n - x - 1] * (n - x - 1)th term of Triangular Number) * 10x
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:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
const int N = 10;
int pref[N], power[N];
// Function to convert a character
// to its equivalent digit
int toDigit(char ch)
{
return (ch - '0');
}
// Function to precompute powers of 10
void powerOf10()
{
power[0] = 1;
for (int i = 1; i < N; i++)
power[i] = power[i - 1] * 10;
}
// Function to precompute prefix sum
// of numerical strings
void precomputePrefix(string str, int n)
{
pref[0] = str[0] - '0';
for (int i = 1; i < n; i++)
pref[i] = pref[i - 1]
+ toDigit(str[i]);
}
// Function to return the i-th
// term of Triangular Number
int triangularNumber(int i)
{
int res = i * (i + 1) / 2;
return res;
}
// Function to return the sum
// of all resulting strings
int sumOfSubstrings(string str)
{
int n = str.size();
// Precompute powers of 10
powerOf10();
// Precompute prefix sum
precomputePrefix(str, n);
// Initialize result
int ans = 0;
for (int i = 0; i < n - 1; i++) {
// Apply the above general
// formula for every i
ans += (pref[n - i - 2] * (i + 1)
+ toDigit(str[n - i - 1])
* triangularNumber(
n - i - 1))
* power[i];
}
// Return the answer
return ans;
}
// Driver Code
int main()
{
string str = "1234";
// Function Call
cout << sumOfSubstrings(str);
return 0;
}
Java
// Java program for the
// above approach
import java.util.*;
class GFG{
static int N = 10;
static int []pref = new int[N];
static int[] power = new int[N];
// Function to convert a
// character to its equivalent
// digit
static int toDigit(char ch)
{
return (ch - '0');
}
// Function to precompute
// powers of 10
static void powerOf10()
{
power[0] = 1;
for (int i = 1; i < N; i++)
power[i] = power[i - 1] * 10;
}
// Function to precompute prefix sum
// of numerical Strings
static void precomputePrefix(char[] str,
int n)
{
pref[0] = str[0] - '0';
for (int i = 1; i < n; i++)
pref[i] = pref[i - 1] +
toDigit(str[i]);
}
// Function to return the i-th
// term of Triangular Number
static int triangularNumber(int i)
{
int res = i * (i + 1) / 2;
return res;
}
// Function to return the sum
// of all resulting Strings
static int sumOfSubStrings(String str)
{
int n = str.length();
// Precompute powers of 10
powerOf10();
// Precompute prefix sum
precomputePrefix(
str.toCharArray(), n);
// Initialize result
int ans = 0;
for (int i = 0; i < n - 1; i++)
{
// Apply the above general
// formula for every i
ans += (pref[n - i - 2] * (i + 1) +
toDigit(str.charAt(n - i - 1)) *
triangularNumber(n - i - 1)) *
power[i];
}
// Return the answer
return ans;
}
// Driver Code
public static void main(String[] args)
{
String str = "1234";
// Function Call
System.out.print(sumOfSubStrings(str));
}
}
// This code is contributed by 29AjayKumar
Python
# Python 3 program for the
# above approach
N = 10
pref = [0] * N
power = [0] * N
# Function to convert a
# character to its equivalent
# digit
def toDigit(ch):
return (ord(ch) -
ord('0'))
# Function to precompute
# powers of 10
def powerOf10():
power[0] = 1
for i in range(1, N):
power[i] = power[i - 1] * 10
# Function to precompute prefix sum
# of numerical strings
def precomputePrefix(st, n):
pref[0] = (ord(st[0]) -
ord('0'))
for i in range(1, n):
pref[i] = (pref[i - 1] +
toDigit(st[i]))
# Function to return the i-th
# term of Triangular Number
def triangularNumber(i):
res = i * (i + 1) // 2
return res
# Function to return the sum
# of all resulting strings
def sumOfSubstrings(st):
n = len(st)
# Precompute powers
# of 10
powerOf10()
# Precompute prefix
# sum
precomputePrefix(st, n)
# Initialize result
ans = 0
for i in range(n - 1):
# Apply the above general
# formula for every i
ans += ((pref[n - i - 2] * (i + 1) +
toDigit(st[n - i - 1]) *
triangularNumber(n - i - 1)) *
power[i])
# Return the answer
return ans
# Driver Code
if __name__ == "__main__":
st = "1234"
# Function Call
print(sumOfSubstrings(st))
# This code is contributed by Chitranayal
C#
// C# program for the
// above approach
using System;
class GFG{
static int N = 10;
static int []pref = new int[N];
static int[] power = new int[N];
// Function to convert a
// character to its equivalent
// digit
static int toDigit(char ch)
{
return (ch - '0');
}
// Function to precompute
// powers of 10
static void powerOf10()
{
power[0] = 1;
for (int i = 1; i < N; i++)
power[i] = power[i - 1] * 10;
}
// Function to precompute prefix sum
// of numerical Strings
static void precomputePrefix(char[] str,
int n)
{
pref[0] = str[0] - '0';
for (int i = 1; i < n; i++)
pref[i] = pref[i - 1] +
toDigit(str[i]);
}
// Function to return the i-th
// term of Triangular Number
static int triangularNumber(int i)
{
int res = i * (i + 1) / 2;
return res;
}
// Function to return the sum
// of all resulting Strings
static int sumOfSubStrings(String str)
{
int n = str.Length;
// Precompute powers of 10
powerOf10();
// Precompute prefix sum
precomputePrefix(str.ToCharArray(), n);
// Initialize result
int ans = 0;
for (int i = 0; i < n - 1; i++)
{
// Apply the above general
// formula for every i
ans += (pref[n - i - 2] * (i + 1) +
toDigit(str[n - i - 1]) *
triangularNumber(n - i - 1)) *
power[i];
}
// Return the answer
return ans;
}
// Driver Code
public static void Main(String[] args)
{
String str = "1234";
// Function Call
Console.Write(sumOfSubStrings(str));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program for the
// above approach
var N = 10;
var pref = new Array(N).fill(0);
var power = new Array(N).fill(0);
// Function to convert a
// character to its equivalent
// digit
function toDigit(ch) {
return ch - "0";
}
// Function to precompute
// powers of 10
function powerOf10() {
power[0] = 1;
for (var i = 1; i < N; i++)
power[i] = power[i - 1] * 10;
}
// Function to precompute prefix sum
// of numerical Strings
function precomputePrefix(str, n) {
pref[0] = str[0] - "0";
for (var i = 1; i < n; i++)
pref[i] = pref[i - 1] + toDigit(str[i]);
}
// Function to return the i-th
// term of Triangular Number
function triangularNumber(i) {
var res = parseInt((i * (i + 1)) / 2);
return res;
}
// Function to return the sum
// of all resulting Strings
function sumOfSubStrings(str) {
var n = str.length;
// Precompute powers of 10
powerOf10();
// Precompute prefix sum
precomputePrefix(str.split(""), n);
// Initialize result
var ans = 0;
for (var i = 0; i < n - 1; i++) {
// Apply the above general
// formula for every i
ans +=
(pref[n - i - 2] * (i + 1) +
toDigit(str[n - i - 1]) *
triangularNumber(n - i - 1)) *
power[i];
}
// Return the answer
return ans;
}
// Driver Code
var str = "1234";
// Function Call
document.write(sumOfSubStrings(str));
</script>
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1)
Similar Reads
Print all Substrings of length n possible from the given String Given a string str and an integer N, the task is to print all possible sub-strings of length N. Examples: Input: str = âgeeksforgeeksâ, N = 3Output: gee eek eks ksf sfo for org rge gee eek eksExplanations: All possible sub-strings of length 3 are âgeeâ, âeekâ, âeksâ, âksfâ, âsfoâ, âforâ, âorgâ, ârge
8 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
All possible strings of any length that can be formed from a given string Given a string of distinct characters, print all possible strings of any length that can be formed from given string characters. Examples: Input: abcOutput: a b c abc ab ac bc bac bca cb ca ba cab cba acbInput: abcdOutput: a b ab ba c ac ca bc cb abc acb bac bca cab cba d ad da bd db abd adb bad bda
10 min read
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
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