KatInterview

Zigzag Parity Check on Subarray Ranges

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingprefix-sumrange-queriesparity

Last updated

Answer many range queries asking whether neighbors in a subarray always differ in odd/even parity, using prefix counts of same-parity adjacent pairs.

Zigzag Parity Check on Subarray Ranges

You are given a list of integers nums and a list of range queries. A contiguous segment of nums is called a zigzag segment if every two neighboring elements inside it have opposite parity: one is even and the other is odd.

Each query is a pair [left, right] (both indices inclusive). For every query, decide whether the segment nums[left..right] is a zigzag segment.

Return a list of booleans, one per query and in the same order as the queries. An entry is True if the corresponding segment is a zigzag segment and False otherwise.

Rules

  • A segment with a single element (left == right) has no neighboring pairs, so it is always a zigzag segment.
  • Zero counts as even. Negative numbers follow the usual meaning of parity (for example, -3 is odd and -4 is even).
  • Only pairs of neighbors that lie fully inside [left, right] matter. The element just before left and the element just after right are ignored.

Constraints

  • 1 <= len(nums) <= 10^5
  • 1 <= len(queries) <= 10^5
  • 0 <= left <= right < len(nums)
  • Each query is a pair of integers [left, right].
  • Integers in nums may be negative, zero or positive.

Examples

Example 1

Input: zigzag_parity_queries([1, 2, 3, 4, 5], [[0, 2], [0, 4], [1, 4]])

Output: [True, True, True]

Example 2

Input: zigzag_parity_queries([1, 3, 5], [[0, 1], [1, 2]])

Output: [False, False]

Hints

Hint 1

Rephrase the condition: a segment fails only if it contains at least one pair of neighbors with the same parity. So count such violations instead of checking parities one by one.

Hint 2

Define a marker for each position i >= 1 that is 1 when nums[i-1] and nums[i] share parity. Build prefix sums over these markers so any range of markers can be summed in O(1).

Hint 3

For the query [left, right], the neighbor pairs inside it are those ending at left+1 through right. The pair ending at left involves nums[left-1], which is outside the segment, so it must not be counted.