I'm reading the book Cracking the Code.
The answer for this question suggests a solution using timestamps and two separate queues. This is straightforward and involves simply enqueuing into the appropriate queues. Dequeuing oldest involves checking timestamps of front of both queues and removing the oldest.
I'm wondering if there is a way to do this without using an additional timestamp field.
My approach is to use two queues, main
and backup
Enqueue
I simply push into backup
Dequeue Dog/Cat aka. specific type dequeue
I check if front of main
has this type. If not or if main
is empty, then I go to backup
.
If backup
contains the right type, dequeue
it
If backup
does not contain it, then shift from backup
to main
i.e. dequeue
from backup
and enqueue
to main
Dequeue oldest pet
dequeue
from main
if main
has elements
If main
is empty, dequeue
from backup
dogs
queue and acats
queue, its that simple. $\endgroup$