Python 1248.py
class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
result = 0
have = 0 # current number of odd numbers in subarray [left, right]
left = 0
nice = 0 # nice subarrays in current sliding window
for right, n in enumerate(nums):
# new odd number
if n & 1:
have += 1
nice = 0
# found a nice array, shift out odd number
while have == k:
have -= nums[left] & 1
nice += 1
left += 1
if nice > 0:
result += nice
return result
Difficulty
and has an acceptance rate of about 75% (600k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Math
- Prefix Sum
- Sliding Window
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The routine implements a sliding-window algorithm that counts how many contiguous sub-arrays contain exactly k odd numbers. It iterates through the input list once, maintaining a dynamic window [left, right] and a running tally of qualifying sub-arrays. The design avoids nested loops and extra data structures, delivering a linear-time solution with O(1) auxiliary memory.
Core Logic
At the start the function creates four integer variables.
result = 0
have = 0 # number of odd elements currently inside the window
left = 0
nice = 0 # how many sub-arrays ending at the current right index satisfy the condition
result accumulates the final answer, have tracks the count of odd numbers inside the current window, left marks the window’s left boundary, and nice records how many valid sub-arrays end at the current right position.
Sliding Window Expansion
The main loop walks through the list with enumerate, exposing both the index (right) and the element (n).
for right, n in enumerate(nums):
...
Each iteration expands the window by including n at the right edge.
Handling a New Odd Number
When the newly added element is odd, the algorithm increments have and resets nice to zero because any previously counted sub-arrays that ended before this odd number are no longer valid for the current window. The odd test uses a bitwise AND, which is faster than a modulo operation.
if n & 1:
have += 1
nice = 0
Contracting the Window When the Target Is Met
If the window now contains exactly k odd numbers, the inner while loop shifts the left boundary to the right, one element at a time, until the count of odd numbers drops below k. Each shift that still leaves have equal to k represents a new sub-array that satisfies the requirement, so nice is incremented. The expression nums[left] & 1 extracts the oddness of the element being removed without extra branching.
while have == k:
have -= nums[left] & 1
nice += 1
left += 1
When the loop exits, nice holds the number of sub-arrays that end at the current right index and contain exactly k odd numbers.
Accumulating the Result
If any qualifying sub-arrays were found for the current right, they are added to the global total.
if nice > 0:
result += nice
The final value of result is returned after the loop finishes.
Edge Cases Managed
The implementation gracefully handles an empty input list because the for loop simply never executes, leaving result at zero. When k is zero, the condition have == k becomes true only when the window holds no odd numbers; the inner loop then slides left past any even elements, counting sub-arrays consisting solely of evens. A list composed entirely of even numbers therefore yields the combinatorial count of all possible sub-arrays, while a list of only odd numbers produces zero unless k matches the length of the sub-array being examined. The reset of nice on encountering a new odd element ensures that sub-arrays crossing that odd element are not mistakenly counted for earlier windows.
Performance Optimizations
The algorithm uses a single pass over the input, updating counters in constant time per element, which eliminates the overhead of recomputing odd counts for each possible sub-array. The use of bitwise & 1 for odd detection is a micro-optimization that avoids the slower modulo operator. By maintaining nice as the count of valid sub-arrays ending at the current right index, the code avoids an inner accumulation loop; each valid sub-array is accounted for exactly once when the left boundary moves. All auxiliary variables are simple integers, so the extra memory footprint stays constant regardless of input size.
ELI5 - Simplified Explanation
Imagine a very long train made of many colorful toy cars. Some cars are painted with odd numbers, and some have even numbers. The goal is to find all the special groups of cars that have exactly the right amount of odd-numbered cars, which is the number called k.
Everything starts at the very front of the train. A helper moves along the train car by car, looking at each one. When the helper sees an odd-numbered car, the count of odd cars goes up. Whenever the helper realizes that the current group has exactly k odd cars, it becomes a special group.
To find all the possible groups, the helper also looks at the side of the train. If there are extra even-numbered cars sitting right before the special group, those even cars can be included to make even more special groups. The helper keeps track of how many of these extra even cars there are and quietly remembers them. Every time the helper finds a way to make a special group with the right number of odd cars, those remembered even cars help count up all the different ways to build that specific group. The process repeats until the helper reaches the very last car at the back of the train.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | TS | ||||
| MemoryLimitExceeded | C++ | Python | |||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| qiyuangong | C++ | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| qiyuangong | C++ | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 2261: K Divisible Elements Subarrays
- problem 2750: Ways to Split Array Into Good Subarrays
- problem 2845: Count of Interesting Subarrays
Solved On The Same Day
- problem 1358: Number of Substrings Containing All Three Characters
- problem 1371: Find the Longest Substring Containing Vowels in Even Counts
- problem 1410: HTML Entity Parser
- problem 1481: Least Number of Unique Integers after K Removals
- problem 1600: Throne Inheritance
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality