unknown Interview Question
PersonnelsCountry: India
In the solution above, to find the max and min, the program has to compare 2n times. as we know, the lower bound of select max and min is (3/2)n-2. So we can reduce the compare times to (3/2)n requiring one more space.
min = queue.head.val
max = queue.head.val
prior.
queue.head = queue.head.next
for node in queue
prior = node.val;
node = node.next;
if(prior>node.val)
{
max=prior?max:prior>max;
....
}
else
{
....
}
I think the "trick" part of this question is to use the QUEUE operations (enqueue/dequeue) and you are not allowed to iterate through the linked list!
- Selmeczy, Péter February 14, 2012So the solution is that one step in the iteration should read the first-out entry (dequeue), compare and then enqueue it. After all items are examined the queue is in the same state as it was.