Problem solution · Python

Count Subarrays with Even Odd Ratio II

Count Subarrays with Even Odd Ratio II: a Python solution using segment tree or range structure. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Segment tree or range structure
Source
Kamyu LeetCode Solutions
Length
43 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Segment tree or range structure

For Count Subarrays with Even Odd Ratio II, the implementation stores interval information in a range-query data structure so updates and queries avoid rescanning the full input.

  1. Choose the aggregate stored for each interval or prefix.
  2. Build or initialize the structure from the input.
  3. Apply updates and combine the affected nodes to answer each query.

Code notes

  • 43 lines of Python from the credited upstream file count-subarrays-with-even-odd-ratio-ii.py.
  • The implementation visibly relies on sequence storage, ordered lookup.
  • No explicit loop blocks detected.

Complexity

Count the build once, then multiply the logarithmic update or query path by the number of operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeCount Subarrays with Even Odd Ratio II · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(nlogn)# Space: O(n) # prefix sum, sort, coordinate compression, fenwick treeclass BIT(object):  # 0-indexed.    def __init__(self, n):        self.__bit = [0]*(n+1)  # Extra one for dummy node.     def add(self, i, val):        i += 1  # Extra one for dummy node.        while i < len(self.__bit):            self.__bit[i] += val            i += (i & -i)     def query(self, i):        i += 1  # Extra one for dummy node.        ret = 0        while i > 0:            ret += self.__bit[i]            i -= (i & -i)        return ret  class Solution(object):    def countRatioSubarrays(self, nums, a, b):        """        :type nums: List[int]        :type a: int        :type b: int        :rtype: int        """        prefix = [0]*(len(nums)+1)        for i in xrange(len(nums)):            prefix[i+1] = prefix[i]+(b if nums[i]%2 == 0 else -a)        val_to_idx = {x:i for i, x in enumerate(sorted(set(prefix)))}        bit = BIT(len(val_to_idx))        result = 0        for i in xrange(len(prefix)):            idx = val_to_idx[prefix[i]]            result += i-bit.query(idx-1)            bit.add(idx, 1)        return result 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗