Problem · Array

Get Balanced String

MediumUberFULLTIMEOA
See Uber hiring insights

Given an array arr of length n which is a permutation of 1, 2, ..., n, a number k is called balanced if there exist two indices i and j such that arr[i], arr[i+1], ..., arr[j] is a permutation of 1, 2, ..., k.

Return a binary string of length n, where the character at 0-indexed position k-1 is '1' if k is balanced, and '0' otherwise.

Examples
01 · Example 1
arr = [4, 1, 3, 2]
return = 1011

k=1: subarray [1] is a permutation of {1} → balanced.
k=2: no contiguous subarray equals {1, 2} → not balanced.
k=3: subarray [1, 3, 2] is a permutation of {1, 2, 3} → balanced.
k=4: full array [4, 1, 3, 2] is a permutation of {1, 2, 3, 4} → balanced.

02 · Example 2
arr = [1, 2, 3]
return = 111

For every k from 1 to 3, the prefix arr[0..k-1] is already a permutation of {1, ..., k}.

03 · Example 3
arr = [2, 3, 1]
return = 101

k=1: subarray [1] exists → balanced.
k=2: no contiguous subarray is exactly {1, 2} — elements 1 and 2 are separated by 3 → not balanced.
k=3: full array [2, 3, 1] is a permutation of {1, 2, 3} → balanced.

04 · Example 4
arr = [1]
return = 1
Constraints
  • 1 ≤ n ≤ 105
  • arr is a permutation of 1, 2, ..., n
More Uber problems
drafts saved locally
public String getBalancedString(int[] arr) {
    // write your code here
}
arr[4, 1, 3, 2]
expected"1011"
sign in to submit