EDIT:
This isn’t as trivial as
you think. Consider the fact that each
addition of a new number pushes out an
old number from the linkedlist.The solution doesn’t seem to be as
simple as keeping track of a min
number with a variable. What if the
minimum gets pushed out of the
linkedlist? Then what? How do you know
what the new min is?
I heard this interview question:
You have a fixed length linked list.
-
At time t=0, the linkedlist is filled
with random numbers. -
At each increment in time, one new
number is fed into the head of the
linkedlist, and one number is pushed
out from the tail. -
You are allowed only ONE traversal before the first time interval.
- This means one traversal ever. Not once at every time t.
.
- This means one traversal ever. Not once at every time t.
-
O(1) storage.
Your task is to be able to return the min of the linkedlist at every time interation.
What is an algorithm that would be able to do this?
Interesting note:
Since there’s no information regarding time complexity, you are allowed to use sort operations. The only problem then is: sorting takes more than one iteration.
First,
Second,
When initializing your queue, also initialize a min-heap where all elements of the queue keep a reference (pointer) to the heap node corresponding to them.
1 op on CSQ
The above operations guarentee that the heap size will always remain in sync with the queue size –hence O(1). The heap can be constructed in a single travesal.
Finding min
Clearly O(1). Just return the head of the min heap.