Block Sequence

You are given an array: a[1..n]

You may delete any elements from the array.

A sequence is called beautiful if it consists of blocks, where:

  • the first element of a block is its length
  • then exactly that many elements follow in that block

Example block: 3 x y z

means the block length is 3, so there must be 3 elements after it.

Your task is to find the minimum number of elements to remove so the sequence becomes beautiful.

Example 1:

Input : n = 4 , a = [3,5,6,7]

Output : 0

Explanation : The first element is 3, meaning the block must contain: 3 5 6 7

Structure: [length] + 3 elements

This exactly forms a valid block, so the sequence is already beautiful.

Minimum deletions = 0.

Example 2:

Input: n = 5 , a = [1, 2, 3, 4, 5]

Output: 2

Explanation: Possible valid construction: 1 2

Block: length = 1 followed by 1 element

Remaining elements: 3 4 5

3 can start a block: 3 4 5

which needs 3 elements after it, but only 2 exist, so that block cannot be used.

The best approach deletes two elements so that valid blocks remain.

Minimum deletions = 2.

Now Your Turn!

Pick the correct output for the given input

Input: n = 5 , a = [10, 1, 2, 3, 4]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 ≤ n ≤ 2 * 105
  • 1 ≤ a[i] ≤ 106

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int minRemovals(int n, vector<int>& a) {
// Write your code here
return 0;
}
};
Test Case

Input:

A