← Bytedance Interview Insights
The O(n) trick here is to keep a running length counter and add it to your total at each position.
Start by clarifying the problem and edge cases, then propose an O(n) solution that tracks the length of the current alternating subarray ending at each index. Explain how each new element extends the previous alternating run or starts a new one, and sum these lengths to get the total count.
Pro tip: Mention that this is a classic 'count subarrays with property' problem where maintaining a running length avoids O(n^2) enumeration, and emphasize that you can solve it in one pass with O(1) extra space.
Confirm that a single element is always valid, and that 'strictly alternate' means odd-even-odd or even-odd-even with no two adjacent elements having the same parity.
Let 'length' be the number of valid alternating subarrays ending at the current index. Initialize length = 1 for the first element and total = 1.
For each subsequent element, check if its parity differs from the previous element. If so, increment length; otherwise, reset length to 1. Add length to total.
After processing all elements, return total as the count of valid contiguous subarrays.
State that the algorithm runs in O(n) time and uses O(1) extra space, which is optimal for this problem.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.