All problems
0483MediumHash TableStringCounting

Total Spread Across Every Stretch of the Log

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1781Sum of Beauty of All Substrings

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A machine shop writes its shift log as the string log, one lowercase letter per job, in the order the jobs ran.

A stretch is any run of consecutive letters of the log; a stretch is picked out by where it starts and where it ends, so two stretches at different places count separately even when they read the same. The spread of a stretch is how many times its busiest letter occurs in it, less how many times its quietest letter occurs in it, counting only letters that occur in that stretch at all.

Return the spreads of every stretch of log added together.

Examples

Example 1

Input
log = "ppqqp"
Output
4

Most stretches here even out to nothing. The stretch `"ppq"` contributes 1 and the whole log contributes 1, and the remaining contributions are similarly small.

Example 2

Input
log = "xyz"
Output
0

Every letter of this log is different, so no stretch has a busier letter than its quietest one.

Example 3

Input
log = "mmmnnm"
Output
9

The long run of `"m"` at the front leaves several stretches lopsided, and their contributions add up to the figure returned.

Constraints

  • 1 <= log.length <= 500
  • log consists of lowercase English letters only.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def total_spread(log: str) -> int:
Java
public int totalSpread(String log)
September 7
Apply