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.
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.
Using a min-heap is the best way. It is tailor made for this application.
Algorithm (Largest element)Create a variable max and initialize it with INT_MIN. Traverse through the list and for every node, compare its data with max. If the current node's data is greater than max, then store the value of the current node's data in max. In the end, max will contain the largest element of the list.
First,
O(1) storage is not the same as an a single register. It means constant space usage.
Second,
I am going to call your LL a constant size queue (CSQ).
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.
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.
Clearly O(1). Just return the head of the min heap.
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