Problem 285069 · hard · Phase 02 Linear Data Structures

Three-Way Tie Stretches

hash maps · prefix counts · difference keys

A three-way race is logged as a string log: each character names the runner who took the lead for one lap, 'a', 'b' or 'c'. Any other character (such as '-', a lap with no change) counts for nobody. A stretch is a non-empty run of consecutive laps log[i:j]. A stretch is a three-way tie if 'a', 'b' and 'c' occur in it the same number of times (zero of each is allowed, so a stretch made only of '-' is a tie). Return the number of three-way tie stretches.

Examples

Input:  log = "abcab"
Output: 3
Explanation: "abc" (laps 0-2), "bca" (laps 1-3) and "cab" (laps 2-4).

Input:  log = "a-bc"
Output: 2
Explanation: "-" on its own, and "a-bc".

Constraints

  • 0 <= len(log) <= 10**5
  • Target complexity: O(n) time.

Goals

  • Turn 'three counts are equal' into 'two differences are unchanged'
  • Count matching prefix states with a dictionary
  • Seed the table with the empty prefix
Starting Python…