Problem 216222 · hard · Phase 02 Linear Data Structures

Three Fair Legs of the Relay

arrays · prefix sums · counting

A relay course is a line of segments; effort[i] is the effort score of segment i (downhill segments score negative). Three runners share the course: runner A takes a first block of segments, runner B the next block, runner C the rest. Every block must hold at least one segment. A split is fair when all three blocks have the same total effort. Return the number of fair splits. Two splits differ if either cut is in a different place.

Examples

Input:  effort = [1, 2, 3, 0, 3]
Output: 2
Explanation: [1, 2] [3] [0, 3] and [1, 2] [3, 0] [3] each give 3, 3, 3.

Input:  effort = [0, 0, 0, 0]
Output: 3

Input:  effort = [2, -1, 2]
Output: 0

Constraints

  • 0 <= len(effort) <= 10**5
  • -10**4 <= effort[i] <= 10**4
  • Target: O(n) time. Trying every pair of cut points is far too slow for the largest tests.

Goals

  • Describe a split by the prefix totals at its two cut points
  • Count valid pairs of cuts in one pass with a running counter
  • Handle negative values and a zero total
Starting Python…