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.
Examples
01 · 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.
02 · 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
- LRU Cache with TTL ExpirationONSITE INTERVIEW · Seen May 2026
- Maximum Candies with At Most Two Types in a LineONSITE INTERVIEW · Seen May 2026
- Top-K KOLs by Total LikesONSITE INTERVIEW · Seen May 2026
- Compute Walking DistanceSeen Mar 2026
- Format TextSeen Mar 2026
- Memory AllocatorSeen Mar 2026
- TikTok Shopping SpreeSeen Mar 2025
- TikTok Video Relevance AdjustmentSeen Mar 2025
public int countSawtoothSubarrays(int[] nums) {
// write your code here
}
nums[1,2,3]
expected6
sign in to submit