The single-pass constraint is what makes this non-trivial.
Use a single pass to track the most recent index of 1 and 2. At each step, if the current element is 1 or 2, update the minimum difference if the other value has been seen, then update the last seen index for the current value. This ensures O(n) time and O(1) space.
Pro tip: Clarify that the array can contain only 0, 1, and 2, and that we only care about pairs of 1 and 2. Mention that the single pass is possible because we only need the closest pair, which must be adjacent in the sequence of non-zero elements.
Restate the problem: find minimum |i-j| where one index has 1 and the other has 2. Note the single linear pass requirement and that 0s are irrelevant.
Set last1 and last2 to -1 (or None) to track the most recent indices of 1 and 2. Initialize min_diff to a large value (e.g., infinity).
For each index i and value v: if v is 1, check if last2 is set, update min_diff with i - last2, then set last1 = i. If v is 2, check if last1 is set, update min_diff with i - last1, then set last2 = i. Ignore 0s.
After the loop, if min_diff is still infinity, return -1; otherwise return min_diff.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.