Special Array II - Problem

An array is considered special if every pair of its adjacent elements contains two numbers with different parity (one even, one odd).

You are given an array of integers 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.

Input & Output

Example 1 — Mixed Parity Array
$ Input: nums = [3,4,1,2,6], queries = [[0,4]]
Output: [false]
💡 Note: Checking subarray [3,4,1,2,6]: 3(odd),4(even)✓, 4(even),1(odd)✓, 1(odd),2(even)✓, 2(even),6(even)✗ - last pair has same parity
Example 2 — Perfect Alternating
$ Input: nums = [4,3,1,6], queries = [[0,2],[2,3]]
Output: [false,true]
💡 Note: Query [0,2] checks [4,3,1]: 4(even),3(odd)✓, 3(odd),1(odd)✗. Query [2,3] checks [1,6]: 1(odd),6(even)✓
Example 3 — Single Element
$ Input: nums = [1], queries = [[0,0]]
Output: [true]
💡 Note: Single element subarray is always special since there are no adjacent pairs to check

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105
  • 1 ≤ queries.length ≤ 105
  • queries[i].length == 2
  • 0 ≤ queries[i][0] ≤ queries[i][1] ≤ nums.length - 1

Visualization

Tap to expand
Special Array II: Check Alternating Parity in RangesInput Array:43126evenoddoddevenevenQuery [0,3]:Checking range [4,3,1,2]Pair Check:4,3 ✓3,1 ✗1,2 ✓Result: [false]Found pair withsame parity
Understanding the Visualization
1
Input
Array with integers and query ranges
2
Check Parity
Verify adjacent elements have different parity (even/odd)
3
Output
Boolean array indicating which ranges are special
Key Takeaway
🎯 Key Insight: Use prefix sums to precompute bad pair positions for O(1) query answering
Asked in
Google 23 Amazon 18 Microsoft 15 Meta 12
28.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen