Problem · Array
Count Sawtooth Subarrays
Learn this problemProblem statement
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.
Function
countSawtoothSubarrays(nums: int[]) → intExamples
Example 1
nums = [1,2,3]return = 6All 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.
Example 2
nums = [1,1]return = 2[1] and [1] are valid (single elements). [1,1] has the same parity (odd, odd) so it is not a sawtooth sequence. Total = 2.
More Tiktok problems
- Can Reach the Exit with TeleportsOA · Seen Jul 2026
- Check Monotonic TriplesOA · Seen Jul 2026
- Shift Every K-th ConsonantOA · Seen Jul 2026
- Count Access Code PairsOA · Seen Jul 2026
- Count Key ChangesOA · Seen Jul 2026
- Sort Matrix BordersOA · Seen Jul 2026
- Travel Distance on ScootersOA · Seen Jul 2026
- Validate 3x3 Digit WindowsOA · Seen Jul 2026