Implementing a Queue where you can insert elements at a specific position while enqueuing/dequeuing in constant time?

J. Doe :

Sample input:

2
3 101 102 103
3 201 202 203
ENQUEUE 101
ENQUEUE 201
ENQUEUE 102
ENQUEUE 202
ENQUEUE 103
ENQUEUE 203
DEQUEUE
DEQUEUE
DEQUEUE
DEQUEUE
DEQUEUE
DEQUEUE
STOP

First line = Number of "groups", N

Following N lines = First number is # of elements in the group K, following K numbers are the elements themselves (in the range 0...999999)

All lines until a STOP input = Either an Enqueue or Dequeue query. If Enqueue, you're queuing the element currently being processed, E, at either A. at the end of the queue if there's no element in the queue that belongs to the same "group" as E or B. right behind the last element which belongs to the same "group" as E

Dequeue is straightforward, just remove the first element from the queue. For every Dequeue query, output the element that is dequeued.

Enqueuing and dequeuing of an element should only take constant time

Output would be:

101
102
103
201
202
203

I'm initially thinking about some kind of a 2D nested structure, like an array of Queues or something, but enqueueing/dequeueing wouldn't take constant time, so I'm not sure.

Also, the fact that I'm given the elements themselves before the queries should be a hint, but towards what I'm not sure.

Abstraction :

If groups don't intersect, elements from every group are always clustered together. In other words, you have a queue of queues:

  • For every group, create an (initially empty) queue;
  • Create an index structure for a constant-time search of the group corresponding to the number entered (brute force solution is an array with 1000000 references, can change to HashSet);
  • Create a queue of queue references ("main" queue).

Now for ENQUEUE X

  • Find the corresponding queue for X;
  • Add X to it; if it was empty, enqueue the queue into the main queue.

For DEQUEUE

  • Take the first queue in the main queue, dequeue element from it;
  • If it's empty, dequeue the queue from the main queue.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=152059&siteId=1