stack - Data structure that deletes all elements of a set less than or equal to x in O(1) time -
i self studying algorithms course, , trying solve following problem:
describe data structure store set of real numbers, can perform each of following operations in o(1) amortized time:
insert(x) : deletes elements not greater x, , adds x set.
findmin() : find minimum value of set.
i realize findmin kind of becomes trivial once have insert, , see how linked list implementation, delete multiple elements simultaneously (ie o(1)), finding out link delete (aka x goes) seems o(n) or o(log n) operation, not o(1). problem gave hint: consider using stack, don't see how helpful.
any appreciated.
the original question below:
note goal o(1) amortized time, not o(1) time. means can work you'd per operation long n operations don't take more o(n) time.
here's simple solution. store elements in stack in ascending order. insert element, keep popping stack until it's empty or until top element greater x, push x onto stack. find-min, read top of stack.
find-min runs in time o(1). let @ insert. intuitively, each element pushed , popped @ once, can spread work of expensive insert across cheaper inserts. more formally, let potential n, number of elements on stack. each time insert, you'll number of pops (say, k) , potential increases 1 - k (one new element added, k removed). amortized cost k + 1 + 1 - k, 2. therefore, insert amortized o(1).
hope helps!
Comments
Post a Comment