← Questions

Balanced prefixes in a permutation

0
UberMicrosoftCodingLast asked Apr 2026

A coding interview question asked in Uber's online assessment and at Microsoft, last asked Apr 2026. It tests arrays, permutations and two pointers.

You are given a permutation p of length n: every integer from 1 to n appears exactly once, in some order.

Call a number k (with 1 <= k <= n) balanced if some contiguous subarray p[l..r] contains exactly the values 1, 2, ..., k, each once, in any order.

Implement:

def balanced_numbers(p: list[int]) -> str

Return a string of length n whose k-th character (1-indexed) is '1' if k is balanced and '0' otherwise.

Constraints

  • 1 <= n <= 2 * 10^5
  • p is a permutation of 1..n
  • Aim for better than O(n²).

Example 1

p = [3, 1, 2, 5, 4]
output: "11101"
  • k = 1: [1] works.
  • k = 2: [1, 2] works.
  • k = 3: [3, 1, 2] works.
  • k = 4: the values 1..4 are spread over indices 0..4, and that range also holds 5, so no window works.
  • k = 5: the whole array works.

Example 2

p = [2, 4, 1, 3]
output: "1001"

For k = 2, the shortest window that holds both 1 and 2 is [2, 4, 1], which also contains 4.

Clarifying questions

  • Is the output 1-indexed by k, so the first character is k = 1?
  • Is the input guaranteed to be a permutation, or should I validate it?
  • Is n = 1 simply "1"?

What a strong answer covers

  • Records the position of every value, then scans k from 1 to n keeping the minimum and maximum position of values 1..k.
  • Marks k balanced exactly when max - min == k - 1: the span holds k cells and all k values are inside it, so nothing else fits.
  • Runs in O(n) time and memory, against O(n^2) for checking windows.
  • Tests both examples, an increasing and a decreasing permutation (all ones), and n = 1.

Follow-ups

  • Return the window [l, r] for each balanced k.
  • Count the subarrays that are permutations of 1..len for any length.
  • Answer the same question after swaps of two elements.

Where it's asked

What it tests

arrays · permutations · two pointers

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding