hi, let Avik connect you.


** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.

** You can check all the posts on the Posts page.

** More about me in the About Me section.

N Queue Using Array


🡆 The problem is supposed to implement Queue with Array. Since it is in Easy tag I did it using Queue STL. Will share the array based implementation soon.


  • Approach:

    1. The problem is said to build an array of N amount of Queue of maximum size S.

    2. The condition not mentioned in the statement is - "Overall elements in all the N queues should not exceed the size S".

    3. Now, initiate an array of N queues.

    4. Add and Delete elements by validating the given conditions. Also, check the condition mentioned in Step 2.

    5. Return necessary verdict from each function.


  • Time and Space Complexity:

    • Time Complexity: O(1) for Insertion, O(1) for Deletion.

                  • For Q queries, O(Q) overall.

    • Space Complexity: O(N*S), where N = number of Queues and S = size of each Queue.


Code [C++]

#include <bits/stdc++.h>

class NQueue{

public:

queue<int> nQueue[1005];

int N, S, totalElement = 0;

NQueue(int n, int s){

N = n, S = s, totalElement = 0;

}


// Enqueues 'X' into the Mth queue. Returns true if it gets pushed into the queue, and false otherwise.

bool enqueue(int x, int m){

if(m > N || totalElement >= S || nQueue[m].size() >= S) return false;

nQueue[m].push(x);

totalElement++;

return true;

}


// Dequeues top element from Mth queue. Returns -1 if the queue is empty, otherwise returns the popped element.

int dequeue(int m){

if(m>N || totalElement == 0 || nQueue[m].size() == 0) return -1;

int top = nQueue[m].front();

totalElement--;

nQueue[m].pop();

return top;

}

};