← Questions

Which prefixes of 1..n appear as a contiguous block

0
UberCoding

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
  • p is a permutation of 1..n
  • Aim for better than O(n^2).

Example 1

p = [3, 1, 4, 2] returns "1001".

  • k = 1: [1] works.
  • k = 2: 1 and 2 are at indices 1 and 3, so no window of length 2 holds both.
  • k = 3: any window holding 1, 2, 3 also holds 4.
  • 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 p guaranteed to be a permutation, or should the input be checked?
  • Is the result indexed so that the first character is for k = 1?
  • Can n be 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..k form a contiguous block exactly when max_pos - min_pos + 1 == k, since the block then holds exactly those k values 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 small n.

Follow-ups

  • Count, for every k, how many windows of length k are 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

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