All problems
0819MediumHash TableStringBit ManipulationPrefix Sum

Nearly Even Telemetry Stretches

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1915Number of Wonderful 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 probe reports ten kinds of event, written as the lowercase letters a through j. One session of reports arrives as the string stream, one character per event, in the order they happened.

A stretch is any non-empty contiguous run of the session. A stretch is nearly even when at most one of the ten kinds occurs an odd number of times inside it, so either every kind present occurs an even number of times, or exactly one kind occurs an odd number of times and all the others occur an even number of times.

Return how many nearly even stretches the session contains. Two stretches that cover different positions count separately even when they read the same.

Examples

Example 1

Input
stream = "efe"
Output
4

Four stretches are nearly even: each of the three single events, where the one kind present occurs once, and the whole session `efe`, where `e` occurs twice and `f` once.

Example 2

Input
stream = "gghg"
Output
7

Seven stretches are nearly even: the four single events, the stretch `gg` at indices 0 and 1 where `g` occurs twice, and the stretches `ggh` and `ghg`, each holding `g` twice and `h` once.

Example 3

Input
stream = "hiih"
Output
8

Eight stretches are nearly even, among them the whole session, where `h` occurs twice and `i` occurs twice, so no kind at all occurs an odd number of times.

Constraints

  • 1 <= stream.length <= 10^5
  • stream consists of the lowercase letters 'a' through 'j' only.
  • The count can exceed the range of a signed 32-bit integer; it stays below 10^11.

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 count_nearly_even(stream: str) -> int:
Java
public long countNearlyEven(String stream)
September 7
Apply