Problem 398794 · medium · Level 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 = [-4, 3, -2, 5]
Output: 4
Explanation: [3], [5], [-4, 3, -2] and [-4, 3, -2, 5].

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…