FastPrepFastPrep
Problem Brief

Count Sawtooth Subarrays

FULLTIMEOA

Given an integer array, count the number of contiguous subarrays that form a sawtooth sequence — one where adjacent elements have alternating parity (even and odd alternate throughout the subarray).

A single element is also considered a valid sawtooth sequence.

Approach hint: Traverse the array and maintain the current length cur of the alternating sequence ending at each index. If the current and previous elements have different parity, increment cur; otherwise reset cur = 1. Add cur to the result at each step, since it represents the number of valid subarrays ending at the current index.

1Example 1

Input
nums = [1,2,3]
Output
6
Explanation
All 6 subarrays are valid sawtooth sequences: [1], [2], [3] (single elements), [1,2] (odd→even), [2,3] (even→odd), [1,2,3] (odd→even→odd). Total = 6.

2Example 2

Input
nums = [1,1]
Output
2
Explanation
[1] and [1] are valid (single elements). [1,1] has the same parity (odd, odd) so it is not a sawtooth sequence. Total = 2.
public int countSawtoothSubarrays(int[] nums) {
  // write your code here
}
Input

nums

[1,2,3]

Output

6

Sign in to submit your solution.