← Instacart Interview Insights
The negative number thing is where I fumbled first.
Use a single pass through the array, maintaining the length of the current alternating parity run ending at the previous index. For each element, if its parity differs from the previous element, extend the run; otherwise, reset the run to 1. Add the run length to a running total, as each new element contributes that many valid subarrays ending at its position.
Pro tip: Clarify that 'strictly alternate' means adjacent elements must have different parity, and explicitly state that length-1 subarrays always count. Then walk through a small example to demonstrate the O(n) logic and catch off-by-one errors.
Confirm that parity means odd/even, that alternation is strict (no two adjacent same parity), and that single-element subarrays are always valid. Ask if the array can be empty or contain zeros (zero is even).
Maintain a variable `run` representing the length of the longest alternating parity subarray ending at the current index. Initialize `run = 1` for the first element and `total = 1`.
For each subsequent element, compare its parity with the previous element. If different, increment `run`; otherwise, reset `run` to 1. Add `run` to `total`.
After the loop, `total` holds the count of all valid contiguous subarrays. Return it.
Explain that the algorithm uses O(1) extra space and runs in O(n) time because it processes each element exactly once.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.