← Microsoft Interview Insights
My first instinct was to just scan for each k and check all subarrays, which is obviously too slow.
For each k, the elements {1..k} must form a contiguous subarray. This is equivalent to the condition that the maximum position among elements 1..k minus the minimum position among elements 1..k equals k-1. We can compute this efficiently by iterating k from 1 to n, maintaining the min and max positions seen so far, and checking the condition in O(1) per k, giving O(n) total time.
Pro tip: Mention that the condition is necessary and sufficient because a set of k distinct integers occupies k consecutive positions if and only if the difference between the maximum and minimum positions is exactly k-1. This insight shows you understand the underlying combinatorial property and can avoid more complex data structures.
Restate the definition: for each k, check if there exists a contiguous subarray containing exactly the numbers 1 through k. Clarify that the subarray must contain all these numbers and no others from the permutation.
Observe that since the numbers 1..k are distinct, they form a contiguous block if and only if the difference between their maximum and minimum positions is k-1. This is because k distinct positions within an interval of length k must exactly fill that interval.
Iterate k from 1 to n. Maintain the minimum and maximum positions of the elements 1..k seen so far. For each k, update these with the position of k, then check if maxPos - minPos == k-1. If true, output '1'; else '0'.
The algorithm runs in O(n) time and O(n) space to store the permutation and positions. This is optimal since we must read the input and produce n outputs.
Walk through a small example, such as permutation [2,4,1,3] for n=4, to verify the condition and outputs. For k=1: pos of 1 is 3, max-min=0, balanced. k=2: positions 3 and 1, diff=2, not balanced. k=3: positions 3,1,4, diff=3, balanced. k=4: positions 3,1,4,2, diff=3, balanced. Output: 1 0 1 1.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.