Author: Trung Nguyen
Tester and Editorialist: Alei Reyes ## Problem Link
Practice
Difficulty
Easy-Medium
PREREQUISITES:
Data Structure
Problem
We are given an array A with some elements and some unknowns. The goal is to find the number of possible arrays with numbers from 1 to k that satisfies certain constraints. Every constraint forces us to make some interval either strictly increasing or strictly decreasing in steps of one.
Explanation
Let’s store the information of constraints in another way. Let dx[i] = how much we have to add to A[i] to get A[i+1].
- If interval from L to R should be increasing, then dx[L] = dx[L + 1] = ... = dx[R - 1] = 1;
- If interval from L to R should be decreasing, then dx[L] = dx[L + 1] = ... = dx[R - 1] = -1;
For some elements there are no constraints and we have more freedom, for sake of simplicity let’s define its dx value as 0.
Note that all information about constraints is stored in dx. Moreover the structure of dx is as follows: [C][0][C][0][C][0]… Where each [C] represent a block of contiguos cells with values either 1 or -1, and [0] represents a block were dx is 0.
Let’s see in how many ways is possible to complete the array A for every type of block.
-
Blocks of type [C]:
If array A contains at least one known element in the block, then all the elements are determined, and we only have to check their values.
Otherwise, suppose that the first element is 0, and calculate the maximum and minimum values in the block (this can be done by adding the values of dx). We can generate new possibilities by adding some constant c to all the elements of the block, however c + minimum ≥ 1, and c + maximum ≤ k (remember that all numbers should be between 1 and k).
-
Blocks of type [0]
In this case, we have more freedom and we can set any value between 1 and k. Except for the first element, it can be uniquely determined if the previous element of dx is 1 or -1.
The only question that remains is how to generate array dx. If we iterate over every constraint it is quadratic. However, if constraints are not overlapping it is linear.
Note that is not necessary to store overlapping intervals (constraints). For example, if segments [3, 5] and [4, 6] should be increasing, then is the same as saying that [3,6] is increasing. Therefore we can merge intervals and get only non-overlapping intervals.
There are many ways of merging intervals. For example, we can keep a set of disjoint intervals. Let’s say that interval [l1, r1] is smaller than [l2, r2] iff r1 < l2. When we add a new interval to the set, we have to remove all the intervals that intersect it (we can find them with binary search) and add a new interval. Every interval is added and removed at most once, so it is asymptotically efficient.