← Boston Consulting Group Interview Insights
The length-1 edge case is the kind of thing you skip over mentally and then get burned by.
Clarify the problem and edge cases, then propose an O(n) single-pass solution that tracks the length of the current alternating run and adds it to the total count. Explain why this works and discuss trade-offs with a brute-force approach.
Pro tip: Emphasize that each new element extends all valid subarrays ending at the previous position if the alternation condition holds, so you can count them in constant time per element. This shows you understand the combinatorial insight behind the linear solution.
Confirm definitions: contiguous subarray, strict alternation between odd and even, and that length-1 subarrays always count. Ask about input size, possible negative numbers, and expected output type.
Mention that checking all O(n^2) subarrays and verifying alternation would be O(n^3) or O(n^2) with optimization, but it's inefficient for large inputs.
Observe that if the current element alternates with the previous one, it extends all valid subarrays ending at the previous position, plus itself. Maintain a running length of the current alternating run.
Initialize total = 1 and run_length = 1. For each subsequent element, if it alternates with the previous, increment run_length; otherwise reset to 1. Add run_length to total. Return total.
State O(n) time and O(1) space. Test with empty array, single element, all same parity, and alternating array to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.