Problem · Array
Balanced Numbers
Learn this problemProblem statement
Given a permutation p of length n, a number k is balanced if there are two indices l and r with 1 <= l <= r <= n such that the numbers p[l], p[l + 1], ..., p[r] form a permutation of the numbers 1, 2, ..., k.
For each k with 1 <= k <= n, determine whether it is balanced. Return a binary string of length n whose k-th character is '1' if k is balanced and '0' otherwise.
A permutation of length n contains each integer from 1 to n exactly once, in any order.
Function
countBalancedNumbers(p: int[]) → StringExamples
Example 1
p = [4,1,3,2]return = "1011"- For
k = 1, choosel = 2andr = 2. The subarray is[1]. - For
k = 2, no subarray forms a permutation of[1, 2]. - For
k = 3, choosel = 2andr = 4. The subarray is[1, 3, 2]. - For
k = 4, choosel = 1andr = 4. The subarray is[4, 1, 3, 2].
Therefore, the answer is "1011".
Constraints
1 <= n <= 2 * 10^51 <= p[i] <= n- All values in
pare distinct.