FastPrepCount Sawtooth Subarrays
Problems/Count Sawtooth Subarrays

Count Sawtooth Subarrays

TikTok logoTikTok● EasyFULLTIMEOA
QuestionFunctionExamples

Problem 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[]) → int

Examples

Example 1

nums = [1,2,3]return = 6

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.

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

  • Minimum Cost of Every K-Capable Model SetOA · Seen Nov 2026
  • Longest Substring Without Repeating CharactersPHONE SCREEN · Seen Oct 2026
  • Next Greater Indices and Maximum GapPHONE SCREEN · Seen Oct 2026
All TikTok interview questionsSee TikTok hiring insights
Saved
class Solution {
    public int countSawtoothSubarrays(int[] nums) {
      // write your code here
    }

}
Checking account…