KatInterview

Contiguous Smallest-Value Blocks in a Shuffled Sequence

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingpermutationarrayssweep

Last updated

Given a permutation of 1..N, decide for each k whether the values 1..k occupy a contiguous block of positions, using a running min/max position sweep.

Contiguous Smallest-Value Blocks

You are given a list perm that is a permutation of the integers 1 through N (each number appears exactly once).

For every k from 1 to N, look at the k entries of perm whose values are 1, 2, ..., k. Decide whether the indices where these entries sit form one unbroken run of adjacent indices, that is, whether they fill a segment of the list with no gaps. The order of the values inside the segment does not matter.

Return a string of length N made of the characters '1' and '0':

  • The character at index k - 1 is '1' if the entries with values 1..k occupy a contiguous segment of perm.
  • Otherwise it is '0'.

Constraints

  • 1 <= N <= 10^5, where N = len(perm).
  • perm contains every integer from 1 to N exactly once.
  • The result must be a string consisting only of '0' and '1', of length N.
  • For k = 1 and k = N the answer is always '1'.

Examples

Example 1

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

Output: '1011'

Example 2

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

Output: '11111'

Example 3

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

Output: '11111'

Example 4

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

Output: '1101'

Hints

Hint 1

For a fixed k, the k positions are all distinct. What single quantity computed from the smallest and largest of them tells you whether there are gaps?

Hint 2

Going from k to k + 1 adds exactly one new position: the index of the value k + 1. You do not need to recompute anything from scratch.

Hint 3

Precompute where each value lives, then sweep k upward while maintaining the minimum and maximum index seen. The block is contiguous exactly when max - min + 1 equals k.