KatInterview

Prefix Value Blocks in a Shuffled Sequence

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingpermutationindex-mappingrunning-min-max

Last updated

Decide, for every k, whether the values 1..k occupy a contiguous block of a permutation, using value positions and a running span instead of scanning subarrays.

You are given an integer n and a list arr of length n that is a permutation of the integers 1 through n (each value appears exactly once).

For each k from 1 to n, decide whether arr contains a contiguous block of positions whose values, taken together, are exactly the set {1, 2, ..., k}. The values may appear in any order inside the block, and the block must contain no other values.

Call such a k good.

Return a string s of length n made of the characters '0' and '1'. The k-th character of s (1-based, so the first character corresponds to k = 1) is '1' if k is good, and '0' otherwise.

Your solution should be efficient: enumerating every subarray for every k is too slow.

Constraints

  • 1 <= n, and n can be large enough that an O(n^2) approach is too slow.
  • arr contains each integer from 1 to n exactly once.
  • The returned string has exactly n characters, each '0' or '1'.
  • If n = 0 (empty input), return the empty string.

Examples

Example 1

Input: prefix_block_flags(1, [1])

Output: '1'

Example 2

Input: prefix_block_flags(5, [1, 2, 3, 4, 5])

Output: '11111'

Example 3

Input: prefix_block_flags(3, [1, 3, 2])

Output: '101'

Example 4

Input: prefix_block_flags(4, [3, 1, 4, 2])

Output: '1001'

Hints

Hint 1

Instead of looking at which values lie inside a subarray, record where each value lives: build an array giving the index of every value.

Hint 2

For a fixed k, any block that holds all of 1..k must cover the leftmost and rightmost positions among those k values. What is the shortest such block, and how long is it?

Hint 3

Since all values are distinct, a block with the right values has exactly k cells. Compare (max position - min position + 1) with k, and update the min and max incrementally as k grows.