Skip to content
LC-1524 Medium LeetCode

1524. Number of Sub-arrays With Odd Sum

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 56% Topics: Array, Math, Dynamic Programming, Prefix Sum
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(1)

class Solution(object):
    def numOfSubarrays(self, arr):
        """
        :type arr: List[int]
        :rtype: int
        """
        MOD = 10**9+7
        result, accu = 0, 0
        dp = [1, 0]
        for x in arr:
            accu ^= x&1
            dp[accu] += 1
            result = (result + dp[accu^1]) % MOD
        return result

Solution from kamyu104/LeetCode-Solutions · MIT