Which prefixes of 1..n appear as a contiguous block
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Uber. It tests arrays, permutations and two pointers.
You are given an array p of length n that is a permutation of the integers 1..n (each value appears exactly once).
For every k from 1 to n, decide whether p has a contiguous subarray of length exactly k whose elements are the values 1, 2, ..., k in some order.
Implement:
def prefix_permutation(p: list[int]) -> str:
...
Return a string of length n whose k-th character (1-indexed) is '1' if such a subarray exists for k, and '0' otherwise.
Constraints
1 <= n <= 2 * 10^5-
pis a permutation of1..n - Aim for better than
O(n^2).
Example 1
p = [3, 1, 4, 2] returns "1001".
-
k = 1:[1]works. -
k = 2:1and2are at indices 1 and 3, so no window of length 2 holds both. -
k = 3: any window holding1, 2, 3also holds4. -
k = 4: the whole array works.
Example 2
p = [4, 2, 1, 3, 5] returns "11111": the windows [1], [2, 1], [2, 1, 3], [4, 2, 1, 3] and the whole array all work.
Clarifying questions
- Is
pguaranteed to be a permutation, or should the input be checked? - Is the result indexed so that the first character is for
k = 1? - Can
nbe 1?
What a strong answer covers
- Records the position of each value, then adds values
1, 2, ...in order while keeping the smallest and largest position seen. - Sees that values
1..kform a contiguous block exactly whenmax_pos - min_pos + 1 == k, since the block then holds exactly thosekvalues and no others. - O(n) time and O(n) space, with no window search.
- Tests: both examples, the identity permutation (all
'1'), the reverse permutation,n = 1, and a brute force over all windows for smalln.
Follow-ups
- Count, for every
k, how many windows of lengthkare permutations of some range of values (not necessarily starting at 1). - The array is not a permutation and may have duplicates.
- Answer the same question after swaps of two elements.
Where it's asked
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.
