2dbi

Subarrays with at Most One Odd Number

viaLeetCode

Problem Given an integer array, return every contiguous subarray containing at most one odd number.

Input / Output

  • Input: int array nums.
  • Output: all qualifying subarrays (or their count — clarify which).

Constraints

  • Output can be O(n^2) in size when listing; the counting variant should run O(n).

Example

  • nums = {2,3,5,6,8} → {2}, {2,3}, {3}, {5}, {5,6}, {5,6,8}, {6}, {6,8}, {8}.

Expected approach

  • Sliding window over "number of odds ≤ 1": extend right, and while the window holds 2 odds, advance left. Every window ending at r with the invariant intact contributes (r − l + 1) subarrays — sum these for the count, or enumerate them when listing is required. O(n) for counting; listing costs the output size. Generalizes directly to "at most K odds" — worth stating.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account