I was asked this question in an interview recently, I still cannot come up with a solution.
There are N slots in a river. An array P is given where each index denotes the time at which the stone at that position will appear. I have to come up with an algorithm to find the earliest time at which there will be K contiguous empty slots. For E.G.
N = 5
P = [2,5,1,4,3]
K = 2
Initially: [0,0,0,0,0]
All the slots are empty.
Now at:
Time t = 1, second stone will appear --> [0,1,0,0,0]
Time t = 2, fifth stone will appear --> [0,1,**0,0**,1]
Time t = 3, first stone will appear --> [1,1,0,0,1]
Time t = 4, fourth stone will appear --> [1,1,0,1,1]
Time t = 5, third stone will appear --> [1,1,1,1,1]
So the answer for above case is 2
, because at time 2
there are (k = 2) continuous empty slots.
An Optimized Solution is to find k elements in O (Logn + k) time. The idea is to use Binary Search to find the crossover point. Once we find index of crossover point, we can print k closest elements in O (k) time. The time complexity of this method is O (Logn + k).
The objects that are returned from the search are not full Active Directory objects, so you need to iterate through them and use the GetDirectoryEntry () method to retrieve the group object. You can then get a count of the members. In this technique, an empty group returns a NULL result. Convert that to zero—it is much easier to read and work with.
In this technique, an empty group returns a NULL result. Convert that to zero—it is much easier to read and work with. The same previous hash table structure is used to create the output object, and a final sort displays the data with the empty groups at the top of the list.
I finally found the O(n) time complexity and O(n) space complexity solution on leetcode. To explain briefly:
The idea is to use an array
days[]
to record each position flower's blooming day. That meansdays[i]
is the blooming day of the flower in positioni+1
. We just need to find a subarraydays[left, left+1,...,left+k-1, right]
which satisfies: for anyi = left+1,..., left+k-1
, we can havedays[left] < days[i] && days[right] < days[i]
. Then, the result ismax(days[left], days[right])
.
Here is the link to the exact solution: https://discuss.leetcode.com/topic/104771/java-c-simple-o-n-solution
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With