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.
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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
