Special Array II Problem
Description
LeetCode Problem 3152.
An array is considered special if every pair of its adjacent elements contains two numbers with different parity.
You are given an array of integer nums and a 2D integer matrix queries, where for queries[i] = [from_i, to_i] your task is to check that subarray nums[from_i..to_i] is special or not.
Return an array of booleans answer such that answer[i] is true if nums[from_i..to_i] is special.
Example 1:
Input: nums = [3,4,1,2,6], queries = [[0,4]]
Output: [false]
Explanation:
The subarray is [3,4,1,2,6]. 2 and 6 are both even.
Example 2:
Input: nums = [4,3,1,6], queries = [[0,2],[2,3]]
Output: [false,true]
Explanation:
1. The subarray is [4,3,1]. 3 and 1 are both odd. So the answer to this query is false.
2. The subarray is [1,6]. There is only one pair: (1,6) and it contains numbers with different parity. So the answer to this query is true.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^51 <= queries.length <= 10^5queries[i].length == 20 <= queries[i][0] <= queries[i][1] <= nums.length - 1
Solution
Approach: Start of the Alternating Run
For each index i, let d[i] be the start of the alternating-parity run that ends at i. Begin with d[i] = i, and when nums[i] and nums[i-1] have different parity set d[i] = d[i-1]. A query [from, to] is special exactly when the run ending at to reaches back to from, that is, d[to] <= from.
Complexity: O(n + q) time and O(n) extra space, where q is the number of queries.
class Solution:
def isArraySpecial(self, nums: List[int], queries: List[List[int]]) -> List[bool]:
n = len(nums)
d = list(range(n))
for i in range(1, n):
if nums[i] % 2 != nums[i - 1] % 2:
d[i] = d[i - 1]
return [d[t] <= f for f, t in queries]