Problem Description
Given an integer array nums and a series of queries, each query represented by a pair [from, to], determine if the subarray nums[from...to] is "special". An array is "special" if every adjacent pair in the subarray consists of one odd and one even integer. Return a boolean array where each element corresponds to whether the respective subarray is special.
Key Insights
- The subarray is "special" if for every adjacent pair the numbers have different parities.
- For a single element subarray, it is trivially special.
- Precompute a helper array that marks for each adjacent pair in nums whether they have the same parity.
- Build a prefix sum over this helper array to quickly count "invalid" pairs (pairs with same parity) in any queried range.
- For each query [L, R], if there is any adjacent pair with the same parity (prefix sum difference > 0), the subarray is not special.
Space and Time Complexity
Time Complexity: O(n + q) where n is the number of elements in nums and q is the number of queries. Space Complexity: O(n) for the helper (prefix sum) array.
Solution
The solution uses a prefix sum technique to efficiently answer each query. First, iterate through the array to determine for each index i (from 0 to n-2) if nums[i] and nums[i+1] have the same parity. Store a value of 1 in a helper array for an invalid pair (same parity) and 0 otherwise. Then, compute the prefix sum of this helper array. For each query [L, R], check if there is any invalid adjacent pair between L and R-1 by subtracting the appropriate prefix sums. If the sum is 0, then the subarray is special; otherwise, it is not.