Answer parity-alternation range queries
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to reason about array properties and design efficient range-query processing for alternating-parity subarrays, and is commonly asked to assess algorithmic performance and scalability under large n and q.
Constraints
- 1 <= len(nums) <= 2 * 10^5
- 1 <= len(queries) <= 2 * 10^5
- 0 <= l <= r < len(nums) for every query [l, r]
- -10^9 <= nums[i] <= 10^9
Examples
Input: ([3, 2, 5, 8, 9], [[0, 4], [0, 2], [1, 3], [2, 4], [3, 3]])
Expected Output: [True, True, True, True, True]
Explanation: The entire array alternates odd/even/odd/even/odd, so every queried subarray is alternating-parity. A single-element range is always alternating-parity.
Input: ([4, 6, 7, 9, 10], [[0, 1], [1, 2], [1, 4], [3, 4], [2, 4]])
Expected Output: [False, True, False, True, False]
Explanation: Pairs (4,6) and (7,9) have the same parity, so any query containing one of those adjacent pairs is False.
Input: ([42], [[0, 0]])
Expected Output: [True]
Explanation: A subarray of length 1 has no adjacent pairs, so it is alternating-parity by definition.
Input: ([-3, -2, -4, -5, 0], [[0, 1], [0, 2], [2, 4], [1, 3], [4, 4]])
Expected Output: [True, False, True, False, True]
Explanation: Negative numbers are handled by parity normally. The adjacent pair (-2, -4) is even-even, making ranges containing it non-alternating.
Input: ([7, 7, 8, 8, 9], [[0, 0], [0, 1], [1, 2], [2, 3], [3, 4], [1, 4]])
Expected Output: [True, False, True, False, True, False]
Explanation: Duplicate odd values 7 and 7 form a bad odd-odd pair, and 8 and 8 form a bad even-even pair.
Hints
- Instead of checking an entire range, mark each adjacent pair as good or bad depending on whether the two numbers have the same parity.
- Use a prefix sum over the bad adjacent pairs so you can count how many bad pairs exist inside any query range in O(1).