Special Array II - Problem

An array is considered special if every pair of adjacent elements has different parity (one even, one odd). You're given an array of integers nums and a 2D array queries, where each query [from_i, to_i] asks you to check if the subarray nums[from_i..to_i] is special.

Goal: Return a boolean array where each element indicates whether the corresponding query subarray is special.

Example: Array [4, 3, 1, 6] is special because: 4(even)→3(odd)→1(odd)→6(even) has alternating parity, but [2, 4, 6] is not special because all elements are even.

Input & Output

example_1.py — Basic Special Array
$ Input: nums = [3,4,1,2,6], queries = [[0,4]]
Output: [false]
💡 Note: The subarray is [3,4,1,2,6]. Between 1 and 2 there are two consecutive numbers with the same parity (both odd), so this subarray is not special.
example_2.py — Mixed Queries
$ Input: nums = [4,3,1,6], queries = [[0,2],[2,3]]
Output: [false, true]
💡 Note: Query [0,2]: subarray [4,3,1] has consecutive elements 3,1 (both odd), so not special. Query [2,3]: subarray [1,6] has different parity (odd,even), so special.
example_3.py — Single Element
$ Input: nums = [1], queries = [[0,0]]
Output: [true]
💡 Note: Single element arrays are always special since there are no adjacent pairs to check.

Constraints

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

Visualization

Tap to expand
4Leadidx 03Followidx 11Followidx 26Leadidx 3Dance Sequence Validation010Violations: 0, 1, 00011Prefix Sum: [0, 0, 1, 1]Query ProcessingQuery [1, 3]: Check range indices 1 to 3Violations in range = prefix[3] - prefix[1] = 1 - 0 = 1Result: 1 > 0 → NOT SPECIAL ✗⚡ Constant time O(1) per query!Prefix sum approach enables instant range violation checking
Understanding the Visualization
1
Identify Violations
Mark all positions where adjacent dancers have the same role (both lead or both follow)
2
Build Prefix Sum
Count cumulative violations from start to each position
3
Answer Queries
For any dance sequence range, check if violation count is zero using prefix sum difference
Key Takeaway
🎯 Key Insight: By precomputing a prefix sum of violations, we transform O(n) range checks into O(1) lookups, making the solution optimal for multiple queries.
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
28.9K Views
Medium Frequency
~15 min Avg. Time
847 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