Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Even and odd integers alternate. Every pair of consecutive integers contributes one odd number, and an unpaired extra position contributes another odd only when both interval endpoints are odd.
Approach
Compute the inclusive interval length high - low + 1. If both endpoints are odd, return half the length rounded upward; otherwise return half rounded downward. This handles equal endpoints as well: a single odd contributes one, while a single even contributes zero. No enumeration is needed because parity determines the count completely.
class Solution:
def countOdds(self, low: int, high: int) -> int:
if low % 2 == 1 and high % 2 == 1:
return ceil((high - low + 1) / 2)
else:
return (high - low + 1) // 2Complexity analysis
The parity formula uses O(1) time and O(1) auxiliary space.
