-1

Continuing this question: Job Interview Question Using Trees, What data to save?

Now, I am looking for an algorithm that does the following:

IsWorstSince(d1,d2): check wither d2 is the day with most new infected people since d1. Return:

false if there is one day between both days such that the number of infected people in that day is bigger than d2.

true, If we can verify for sure that from all days between d1 and d2 (Not only those who were inserted) none has bigger number of infected people than d2.

unknown, if there is some data missing, For example if some days weren't inserted into the data structure.

Time Complexity: O(log n)

We can assume that d1<d2 and that both days do exist in the data structure.


I think this question is really related to the previous one. but not sure how to use it.

Note: In the previous one we implemented WorseBefore(d) that return the last day (between those which were inserted to the DS) before d which had more infected people than there is in day d.

1 Answers1

1

This is actually very similar to the solution I posted to your first question: https://stackoverflow.com/a/65378902

Let's assume we have the same data structure and auxiliary information as in the first question, and let's assume d1 < d2.

Let x = Sick(d2), which we can find in O(log n) by searching for d2 in the tree.

Now ask yourself: where in the tree are the nodes that are greater than d1?

  1. The right subtree of d1. So if maxRightSick(d1) > x, return false, because then there is a day that is greater than d1 but which is worse than d2.

  2. Find the next successor of d1: traverse the tree upwards towards the root until you find a node (which could be d1 itself) that is the left child of another node, and then select the parent of that node. For example, in this image (provided by the OP), the next successor of 0012 would be 0014, of 0014 would be 0023, and of 0038 would be 0039. Some nodes don't have a next successor, e.g. 0043 or 0039.

If the next successor of d1 does not exist, return true, because in that case maxRightSick(d1) must be equal to x and d2 is somewhere in the right subtree of d1.

Otherwise, return the boolean value of the condition Sick(nextSuccessor) < x and maxRightSick(nextSuccessor) < x, because iff the condition is satisfied, all nodes within the subtree of the next successor are not worse than d2.

Mo B.
  • 5,307
  • 3
  • 25
  • 42