Find all balanced k in a permutation
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of permutations, array range reasoning, index mapping, and efficient algorithm design for detecting contiguous subarrays that exactly contain the prefix set {1..k}.
Constraints
- 1 <= n <= 2 * 10^5
- p is a permutation of the integers from 1 to n
Examples
Input: (5, [3, 1, 2, 5, 4])
Expected Output: '11101'
Explanation: For k = 1, 2, and 3, the positions of {1..k} form contiguous segments. For k = 4 they do not. For k = 5, the whole array works.
Input: (5, [2, 1, 4, 3, 5])
Expected Output: '11011'
Explanation: The sets {1}, {1,2}, {1,2,3,4}, and {1,2,3,4,5} each occupy contiguous positions, but {1,2,3} does not.
Input: (4, [2, 4, 1, 3])
Expected Output: '1001'
Explanation: Only k = 1 and k = 4 are balanced. The values {1,2} and {1,2,3} are too spread out.
Input: (1, [1])
Expected Output: '1'
Explanation: The only value forms a contiguous subarray by itself.
Input: (6, [1, 2, 3, 4, 5, 6])
Expected Output: '111111'