Answer range queries for alternating parity subarrays
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of array manipulation, parity properties, efficient range-query processing, and preprocessing techniques for handling multiple queries.
Constraints
- 1 <= n, q <= 2 * 10^5
- Values in nums may be negative or positive; parity = abs(nums[i]) % 2
- Each query [l, r] satisfies 0 <= l <= r <= n - 1
- A subarray of length 0 or 1 is always alternating parity
Examples
Input: ([1, 2, 3, 4], [[0, 3], [0, 1], [1, 2]])
Expected Output: [True, True, True]
Explanation: Parities are odd, even, odd, even — fully alternating, so every queried subarray is alternating parity.
Input: ([1, 3, 2, 4], [[0, 3], [0, 1], [2, 3]])
Expected Output: [False, False, False]
Explanation: Parities are odd, odd, even, even. [0,3] has same-parity boundaries; [0,1] is 1,3 (both odd); [2,3] is 2,4 (both even) — none alternate.
Input: ([2, 4, 6, 8], [[0, 0], [0, 3], [1, 2]])
Expected Output: [True, False, False]
Explanation: All values are even. A single element [0,0] is trivially alternating; any length>=2 range has same-parity neighbors, so it is False.
Input: ([5], [[0, 0]])
Expected Output: [True]
Explanation: A single-element subarray is always alternating parity.
Input: ([-1, 2, -3, 4, -5], [[0, 4], [1, 3], [0, 0]])
Expected Output: [True, True, True]
Explanation: Parities (by abs) are odd, even, odd, even, odd — perfectly alternating, so all ranges qualify. Negatives are handled via abs(x)%2.
Input: ([1, 1, 2, 3], [[0, 3], [1, 3], [2, 3], [0, 1]])
Expected Output: [False, True, True, False]
Explanation: Parities are odd, odd, even, odd. The bad boundary is between index 0 and 1 (1,1 both odd). Ranges that avoid it ([1,3] and [2,3]) are alternating; ranges including it are not.
Input: ([10, 20, 30, 41, 52], [[0, 4], [3, 4], [0, 2]])
Expected Output: [False, True, False]
Explanation: Parities are even, even, even, odd, even. [0,4] and [0,2] contain even-even boundaries (False); [3,4] is 41(odd),52(even) which alternates (True).
Hints
- Whether a whole subarray is alternating depends only on adjacent pairs. Precompute, for each adjacent pair (i-1, i), whether they have the SAME parity (a 'bad' boundary).
- Build a prefix-sum of bad boundaries. A subarray [l, r] is alternating iff there is no bad boundary strictly between l and r — i.e. among indices l+1..r.
- With the prefix sum, the number of bad boundaries in (l, r] is bad_prefix[r+1] - bad_prefix[l+1]; the answer is True iff that count is 0. Treat r <= l (length 0 or 1) as always True.