Skip to content
Related Articles

Related Articles

Queue Operations

Improve Article
Save Article
  • Last Updated : 24 Nov, 2022
Improve Article
Save Article

Given N integers, the task is to insert those elements in the queue. Also, given M integers, the task is to find the frequency of each number in the Queue.

Examples:

Input: 
N = 8 
1 2 3 4 5 2 3 1  (N integers)
M = 5
1 3 2 9 10  (M integers)
Output:
2 2 2 -1 -1

Explanation:
After inserting 1, 2, 3, 4, 5, 2, 3, 1 into the queue,  frequency of 1 is 2, 3 is 2, 2 is 2, 9 is -1 and 10 is -1 (since, 9 and 10 is not there in the queue).

Input:
N = 5 
5 2 2 4 5   (N integers)
M = 5
2 3 4 5 1   (M integers)
Output:
2 -1 1 2 -1

Approach: The given problem can be solved by using a simple queue. The idea is to insert N integers one by one into the queue and then check the frequency of M integers. Separate functions will be created to perform both operations. Follow the steps below to solve the problem.

  • Create a queue and push all given integers into the queue.
  • After pushing all the elements into the queue create another function for counting the frequency of given M elements one by one.
  • Take a variable cntFrequency to keep track of frequency of current element.
  • Pop all the elements from queue till its size and each time check if current element in queue is equal to element for which we are checking for frequency.
    – if both are equal, increment cntFrequency by 1
    – else, do nothing.
  • Push the current element back to the queue so that for next case queue will not get disturbed.
  • Print the frequency of each element found.

Below is the implementation of the above approach:

C++




// C++ Program to implement above approach
#include <bits/stdc++.h>
using namespace std;
 
// Helper class Geeks to implement
// insert() and findFrequency()
class Geeks
{
 
  // Function to insert
  // element into the queue
  public:
  void insert(queue<int> &q, int k)
  {
 
    // adding N integers into the Queue
    q.push(k);
  }
  // Function to find frequency of an element
  // return the frequency of k
  int findFrequency(queue<int> &q, int k)
  {
 
    // to count frequency of elements
    int cntFrequency = 0;
 
    // storing size of queue in a variable
    int h = q.size();
 
    // running loop until size becomes zero
    while (h)
    {
      h = h - 1;
 
      // storing and deleting
      // first element from queue
      int x = q.front();
      q.pop();
      // comparing if it's equal to integer K
      // that belongs to M
      if (x == k)
      {
 
        // increment count
        cntFrequency += 1;
      }
      // add element back to queue because
      // we also want N integers
      q.push(x);
    }
    // return the count
    return cntFrequency;
  }
};
 
// Driver code
 
int main()
{
  queue<int> q;
  int N = 8;
  int a[N] = {1, 2, 3, 4, 5, 2, 3, 1};
  int M = 5;
  int b[M] = {1, 3, 2, 9, 10};
 
  // Invoking object of Geeks class
  Geeks obj;
 
  for (int i = 0; i < N; i++)
  {
 
    // calling insert()
    // to add elements in queue
    obj.insert(q, a[i]);
  }
 
  for (int i = 0; i < M; i++)
  {
 
    // calling findFrequency()
    int f = obj.findFrequency(q, b[i]);
    if (f != 0)
    {
 
      // variable f
      // will have final frequency
      cout << f << " ";
    }
    else
    {
      cout << ("-1") << " ";
    }
  }
}
 
// This code is contributed by adityamaharshi21.


Java




// Java Program to implement above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Driver code
    public static void main(String[] args)
    {
        // Declaring Queue
        Queue<Integer> q = new LinkedList<>();
        int N = 8;
        int[] a = new int[] { 1, 2, 3, 4, 5, 2, 3, 1 };
        int M = 5;
        int[] b = new int[] { 1, 3, 2, 9, 10 };
 
        // Invoking object of Geeks class
        Geeks obj = new Geeks();
 
        for (int i = 0; i < N; i++) {
            // calling insert()
            // to add elements in queue
            obj.insert(q, a[i]);
        }
 
        for (int i = 0; i < M; i++) {
            // calling findFrequency()
            int f = obj.findFrequency(q, b[i]);
            if (f != 0) {
                // variable f
                // will have final frequency
                System.out.print(f + " ");
            }
            else {
                System.out.print("-1"
                                 + " ");
            }
        }
    }
}
 
// Helper class Geeks to implement
// insert() and findFrequency()
class Geeks {
 
    // Function to insert
    // element into the queue
    static void insert(Queue<Integer> q, int k)
    {
        // adding N integers into the Queue
        q.add(k);
    }
 
    // Function to find frequency of an element
    // return the frequency of k
    static int findFrequency(Queue<Integer> q, int k)
    {
        // to count frequency of elements
        int cntFrequency = 0;
 
        // storing size of queue in a variable
        int size = q.size();
 
        // running loop until size becomes zero
        while (size-- != 0) {
 
            // storing and deleting
            // first element from queue
            int x = q.poll();
 
            // comparing if it's equal to integer K
            // that belongs to M
            if (x == k) {
                // increment count
                cntFrequency++;
            }
            // add element back to queue because
            // we also want N integers
            q.add(x);
        }
        // return the count
        return cntFrequency;
    }
}


Python3




# Python Program to implement above approach
import collections
 
# Helper class Geeks to implement
# insert() and findFrequency()
class Geeks:
 
    # Function to insert
    # element into the queue
    def insert(self, q, k):
       
        # adding N integers into the Queue
        q.append(k)
 
    # Function to find frequency of an element
    # return the frequency of k
    def findFrequency(self, q, k):
       
        # to count frequency of elements
        cntFrequency = 0
 
        # storing size of queue in a variable
        size = len(q)
 
        # running loop until size becomes zero
        while (size):
            size = size - 1
             
            # storing and deleting
            # first element from queue
            x = q.popleft()
 
            # comparing if it's equal to integer K
            # that belongs to M
            if (x == k):
               
                # increment count
                cntFrequency += 1
                 
            # add element back to queue because
            # we also want N integers
            q.append(x)
 
        # return the count
        return cntFrequency
 
# Declaring Queue
q = collections.deque()
N = 8
a = [1, 2, 3, 4, 5, 2, 3, 1]
M = 5
b = [1, 3, 2, 9, 10]
 
# Invoking object of Geeks class
obj = Geeks()
 
for i in range(N):
 
    # calling insert()
    # to add elements in queue
    obj.insert(q, a[i])
 
for i in range(M):
 
    # calling findFrequency()
    f = obj.findFrequency(q, b[i])
    if (f != 0):
       
        # variable f
        # will have final frequency
        print(f, end=" ")
    else:
        print("-1", end=" ")
print(" ")
 
# This code is contributed by gfgking.


C#




// C# Program to implement above approach
using System;
using System.Collections.Generic;
 
public class GFG {
   
  // Helper class Geeks to implement
// insert() and findFrequency()
public class Geeks {
 
    // Function to insert
    // element into the queue
   public void insert(Queue<int> q, int k)
    {
        // adding N integers into the Queue
        q.Enqueue(k);
    }
 
    // Function to find frequency of an element
    // return the frequency of k
    public int findFrequency(Queue<int> q, int k)
    {
        // to count frequency of elements
        int cntFrequency = 0;
 
        // storing size of queue in a variable
        int size = q.Count;
 
        // running loop until size becomes zero
        while (size-- != 0) {
 
            // storing and deleting
            // first element from queue
            int x = q.Peek();
            q.Dequeue();
 
            // comparing if it's equal to integer K
            // that belongs to M
            if (x == k) {
                // increment count
                cntFrequency++;
            }
            // add element back to queue because
            // we also want N integers
            q.Enqueue(x);
        }
        // return the count
        return cntFrequency;
    }
}
 
    // Driver code
    public static void Main()
    {
       
        // Declaring Queue
        Queue<int> q = new Queue<int>();
        int N = 8;
        int[] a = new int[] { 1, 2, 3, 4, 5, 2, 3, 1 };
        int M = 5;
        int[] b = new int[] { 1, 3, 2, 9, 10 };
 
        // Invoking object of Geeks class
        Geeks obj = new Geeks();
 
        for (int i = 0; i < N; i++)
        {
           
            // calling insert()
            // to add elements in queue
            obj.insert(q, a[i]);
        }
 
        for (int i = 0; i < M; i++)
        {
           
            // calling findFrequency()
            int f = obj.findFrequency(q, b[i]);
            if (f != 0)
            {
               
                // variable f
                // will have final frequency
                Console.Write(f + " ");
            }
            else {
                Console.Write("-1"
                                 + " ");
            }
        }
    }
}
 
// This code is contributed by SURENDRA_GANGWAR.


Javascript




// JS Program to implement above approach
 
// Helper class Geeks to implement
// insert() and findFrequency()
class Geeks {
 
    // Function to insert
    // element into the queue
    insert(q, k) {
 
        // adding N integers into the Queue
        q.unshift(k);
    }
    // Function to find frequency of an element
    // return the frequency of k
    findFrequency(q, k) {
 
        // to count frequency of elements
        let cntFrequency = 0;
 
        // storing size of queue in a variable
        let size = q.length;
 
        // running loop until size becomes zero
        while (size) {
            size = size - 1;
 
            // storing and deleting
            // first element from queue
            let x = q.pop();
 
            // comparing if it's equal to integer K
            // that belongs to M
            if (x == k) {
 
                // increment count
                cntFrequency += 1;
            }
            // add element back to queue because
            // we also want N integers
            q.unshift(x);
        }
        // return the count
        return cntFrequency;
    }
}
 
 
// Driver code
 
let q = new Array;
let N = 8;
let a = [1, 2, 3, 4, 5, 2, 3, 1];
let M = 5;
let b = [1, 3, 2, 9, 10];
 
// Invoking object of Geeks class
let obj = new Geeks;
 
for (let i = 0; i < N; i++) {
 
    // calling insert()
    // to add elements in queue
    obj.insert(q, a[i]);
}
 
for (let i = 0; i < M; i++) {
 
    // calling findFrequency()
    f = obj.findFrequency(q, b[i]);
    if (f != 0) {
 
        // variable f
        // will have final frequency
        console.log(f);
    }
    else {
        console.log("-1");
    }
}
 
// This code is contributed by adityamaharshi21.


Output

2 2 2 -1 -1 

Time Complexity: O(N*M)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!