Problem 398794 · medium · Phase 03 Linear Management & Searching

Stretches With a Positive Product

prefix parity · counting pairs · hashing tricks

Every entry of factors is a non-zero integer. Count the non-empty contiguous stretches whose product is positive. The product itself can be enormous, so do not compute it.

Examples

Input:  factors = [2, -3, -1, 4]
Output: 6
Explanation: [2], [2, -3, -1], [2, -3, -1, 4], [-3, -1], [-3, -1, 4] and [4].

Input:  factors = [-5]
Output: 0

Constraints

  • 1 <= len(factors) <= 10**5
  • -10**9 <= factors[i] <= 10**9, factors[i] != 0
  • Target complexity: O(n) time, O(1) extra space.

Goals

  • Reduce a product's sign to the parity of negative factors
  • Count equal-parity prefix pairs with two counters
Starting Python…