We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Sam and substrings
Sam and substrings
Sort by
recency
|
208 Discussions
|
Please Login in order to post a comment
I am not sure if others used the same logic, but the idea is that for the current sum, we multiply the previous sum by 10 and then add "extra". This "extra" grows each iteration, specially by the 1-based index of the current digit times the current digit value. For example, if the current digit is 3 and the 1-based index of this digit is 4, then the "extra" would increase by 12. So at any given digit, the sum is: currentSum = previousSum*10 + (previousExtra + (index * currentDigit)).
Here's how to solve the problem:
Approach
Understanding Contributions:
123
, digit2
contributes to substrings12
,23
, and2
itself.Mathematical Insight:
Efficient Calculation:
Steps to Implement the Solution
Precompute Contributions:
Modulo Operation:
Here’s how you can implement this in PHP:
Explanation:
Initialization:
totalSum
to accumulate the final result.multiplier
is used to track the multiplier for each digit based on its position.sum
keeps track of the cumulative sum of contributions for the current position.Iteration:
multiplier
.sum
to include this digit's contribution.totalSum
to include the updatedsum
.multiplier
for the next digit.Modulo Operation:
This approach is efficient with a time complexity of (O(n)), where (n) is the length of the number, and handles large numbers gracefully by using modulo operations.
js
Kotlin solution:
To help understand the above solution, I'm posting a slower solution, where the "frontier" represents the set of all subsets ending at the current "last" character. Note that when encountering a new character, a new frontier is formed by appending the new charater to every element of the old frontier (plus, the lone character itself, set of one character). While doing that, the numerical sum of the old frontier is added to the result. The fast solution transforms the frontier from a set to a number (representing the set's sum). Instead of adding a new character to the end of every element of the frontier, we calculate the new sum directly. You can do that by multiplying the old frontier's sum by 10 (because every digit is shifted left by one position), plus adding the new digit n times (once to each element of the old frontier, plus the lone digit itself, the set of one character).