cswork / libraryOpen practice workspace

Coding questions · Microsoft

Find all balanced k in a permutation

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}.

You are given a permutation pp of length nn containing each integer from 11 to nn exactly once.

For each kk where 1≤k≤n1 \le k \le n, determine whether there exists a contiguous subarray of pp whose elements are exactly the set {1,2,…,k}\{1,2,\dots,k\} (in any order).

  • If such a subarray exists, call kk balanced.
  • Output a binary string ss of length nn where s[k]s[k] (1-based) is '1' if kk is balanced, otherwise '0'.

Input

  • Integer nn
  • Array pp of length nn, a permutation of [1..n][1..n]

Output

  • A string of length nn consisting of '0' and '1'

Notes / expectations

  • Aim for an efficient algorithm (e.g., O(n)O(n) or O(nlog⁡n)O(n \log n)), not enumerating all subarrays.

Find All Balanced k in a Permutation

Constraints

  • 1 <= n <= 2 * 10^5
  • p is a permutation of the integers from 1 to n

Examples

Example 1

Input: (5, [3, 1, 2, 5, 4])
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.

Example 2

Input: (5, [2, 1, 4, 3, 5])
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.

Hints

  1. Instead of checking every subarray, think about where each value 1, 2, ..., k appears in the permutation.
  2. For a fixed k, the values 1 through k form a valid contiguous subarray exactly when their minimum and maximum positions span a segment of length k.