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 INPUT nums array: 3 ODD 4 EVEN 1 ODD 2 EVEN 6 EVEN [0] [1] [2] [3] [4] Query: [0, 4] Check subarray [0..4] Legend: = Odd = Even Special: adjacent pairs have different parity Problem: 2 and 6 both EVEN! ALGORITHM STEPS 1 Build Prefix Array Track parity violations 2 Check Adjacent Pairs Mark same parity pairs 3 Prefix Sum Count violations in range 4 Query Answer If violations=0: true Parity Check: 3-4 4-1 1-2 2-6 OK OK OK FAIL Violation at index 3-4 prefix[4] - prefix[0] = 1 1 violation found! FINAL RESULT Query [0,4] Result: false Subarray is NOT special Why false? nums[3] = 2 (EVEN) nums[4] = 6 (EVEN) Same parity = violation! Output Array: [false] Key Insight: Use prefix sum to count parity violations. For each adjacent pair with same parity, increment counter. A subarray [from, to] is special if prefix[to] - prefix[from] = 0 (no violations in range). TutorialsPoint - Special Array II | Optimal Solution (Prefix Sum)
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