Balanced prefixes in a permutation
I was asked this
No reports yet. Sign in to say where you were asked it.
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-
pis a permutation of1..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 isk = 1? - Is the input guaranteed to be a permutation, or should I validate it?
- Is
n = 1simply"1"?
What a strong answer covers
- Records the position of every value, then scans
kfrom 1 tonkeeping the minimum and maximum position of values1..k. - Marks
kbalanced exactly whenmax - min == k - 1: the span holdskcells and allkvalues 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 balancedk. - Count the subarrays that are permutations of
1..lenfor any length. - Answer the same question after swaps of two elements.
Where it's asked
- Uber · Online assessment · Last asked Apr 202690 min · Two problems on a HackerRank-based platform, camera and screen share on · No AI
- Microsoft · HackerRank assessment · Last asked Mar 202690 min · Two problems in a locked full-screen browser
What it tests
arrays · permutations · two pointers
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.

