Can someone give me ideas for the following problem?
Given an array ar[] of length n, and some queries, each query is of the form a, b, c, find the number with the smallest index i such that the index lies in the range [c, n] and such that a < ar[i] < b. There are (n - 1) in total, c goes from 1 to n - 1. The expected complexity for each query should be about O(log n), and a precomputation of complexity at most O(n log n) is suitable. Intuitively, segment tree came up to my mind, but I couldn’t think of a way of building it, nor what to keep in each node.
I’ve modified Mason Bryant’s technique to something that works. The problems were more bugs in FindLowestIndex and a more major bug searching the tree (it can return multiple results).
Despite doing that work, it still doesn’t actually solve the problem.
O(n log n)time setting up is easy enough, but using this technique I’m only able to getO((log n)^2)query time. I wonder if you have a link to the original problem in case there are more clarifications there? Or I wonder if the problem is really solvable. Or maybeO((log n)^2)is “about”O(log n)as the problem requests, it’s less thanO(n)anyway.The technique is to store our array in a typical segment tree, but along with the usual segment information we also store, in order, all the indexes of the elements under each node. This extra storage only takes an extra
O(n log n)time/space if you add it up properly (n items stored at each of log n levels), so it doesn’t hurt our setup time in any way that matters. Then we query the tree to find the minimum set of nodes that are contained by our range of (a, b). This query takes about the same time as a typical segment tree query (O(log n)) and finds at most about 2*log n matching segments. As we query, we find the lowest index in each matching segment that matches our constraint c. We can use a binary search to find this index since we kept the indices in order, so it takesO(log n)time worst case for each matching node. When we add it all up appropriately, the total time isO((log n)^2).Let me know whichever steps you’d like clarified.
C# Code: