Skip to content
Related Articles
Open in App
Not now

Related Articles

Find common elements of Stack and Queue

Improve Article
Save Article
  • Last Updated : 15 Dec, 2022
Improve Article
Save Article

Given a stack of M elements and a queue of N elements in sorted order. The task is to find out the common elements of the stack and the queue.

Examples:

Input: stack = [1, 3, 5, 7], queue = [1, 2, 5, 9]
Output: 5, 1
Explanation: 1 and 5 is present in both stack and queue.

Input: stack = [1, 3], queue = [2, 4]
Output: Not Found
Explanation: There is no common element.

Approach: The given problem can be solved with the help of the following idea:

As both are sorted, the top element of the stack will be the maximum and the front of the queue will be the minimum. So reverse any of them and compare the elements in top of stack and front of queue to find the common elements.

Follow the illustration below for a better understanding.

Illustration:

Say, stack = [1, 3, 5, 7] where 7 is at the top and 
the queue = [1, 2, 5, 9] where 1 is at the front.

Say we are reversing the queue. Do the following to reverse the queue:

  • In first step:
    One by one pop the element from the queue(i.e., all the elements of queue) and push into stack.
            => After First Iteration, Stack = [1, 3, 5, 7, 1] and Queue = [2, 5, 9]
            => After Second Iteration, Stack = [1, 3, 5, 7, 1, 2] and Queue = [5, 9]
            => After Third Iteration, Stack = [1, 3, 5, 7, 1, 2, 5] and Queue = [9]
            => After Fourth Iteration, Stack = [1, 3, 5, 7, 1, 2, 5, 9] and Queue = []
  • In second step:
           => One by one pop the element from the stack(i.e., coming from queue)  and push into queue.
           => After First Iteration, Stack = [1, 3, 5, 7, 1, 2, 5] and Queue = [9]
           => After Second Iteration, Stack = [1, 3, 5, 7, 1, 2] and Queue = [9, 5]
           => After Third Iteration, Stack = [1, 3, 5, 7, 1] and Queue = [9, 5, 2]
           => After Fourth Iteration, Stack = [1, 3, 5, 7] and Queue = [9, 5, 2, 1]

Now the following for finding the common elements.

1st Step:
        => stack top < queue front.
        => Pop queue front.
        => So stack is [1, 3, 5, 7] and queue [5, 2, 1]

2nd step:
        => stack top > queue front
        => Pop stack top
        => So stack [1, 3, 5] and queue [5, 2, 1]

3rd step:
        => stack top = queue front
        => Pop stack top and queue front
        => So stack [1, 3] and queue [2, 1]
        => Common elements [5]

4th step:
        => stack top > queue front
        => Pop stack top
        => So stack [1] and queue [2, 1]

5th Step:
        => stack top < queue front.
        => Pop queue front.
        => So stack is [1] and queue [1]

6th step:
        => stack top = queue front
        => Pop stack top and queue front
        => So stack [] and queue []
        => Common elements [5, 1].

Follow the below steps to solve the problem:

  • Reverse the Queue.
  • Traverse stack and queue while stack and queue do not become empty.
    • If top of stack = front of queue that is a common element.
    • Else if, top of stack > front of queue, pop the top element of the stack.
    • Else, top of stack < front of queue, pop the front element of the stack.
  • Print the common elements.

Below is the implementation of the above approach:

C++

// C++ code to implement the above approach

#include <bits/stdc++.h>
using namespace std;

// Function to find common element
// of stack and queue
vector<int> findCommonElement(stack<int>& St,
                              queue<int>& Q)
{
    // Initialize size of queue Q to 0
    int Size = 0;
    vector<int> v;

    // Put every element of queue into stack
    // and calculate size of queue
    while (!Q.empty()) {
        St.push(Q.front());
        Q.pop();
        Size++;
    }

    // Put extra element of stack into queue
    // again extra element of stack is the
    // element coming from queue. Now, the
    // queue is reverse
    while (Size != 0) {
        Q.push(St.top());
        St.pop();
        Size--;
    }

    // Traverse while stack and queue is not
    // empty
    while (!St.empty() && !Q.empty()) {
        // Top element of stack
        int a = St.top();

        // Front element of queue
        int b = Q.front();

        // Push the common element
        // in vector if a = b
        if (a == b)
            v.push_back(a);

        // Else pop the larger value
        // from its container
        (a > b) ? St.pop() : Q.pop();
    }
    return v;
}

// Driver Code
int main()
{
    stack<int> St;
    queue<int> Q;

    // Fill element into stack
    St.push(1);
    St.push(3);
    St.push(5);
    St.push(7);

    // Fill element into queue
    Q.push(1);
    Q.push(2);
    Q.push(5);
    Q.push(9);

    // Find common element if exists
    vector<int> v = findCommonElement(St, Q);

    if (v.size() == 0)
        cout << "Not Found" << endl;
    for (auto i : v)
        cout << i << " ";
    return 0;
}

Java

// Java code to implement the above approach
import java.util.*;

class GFG
{
  
    // Function to find common element
    // of stack and queue
    static ArrayList<Integer>
    findCommonElement(Stack<Integer> st,
                      Queue<Integer> q)
    {

        // Initialize size of queue Q to 0
        int Size = 0;
        ArrayList<Integer> commonElements = new ArrayList<Integer>();

        // Put every element of queue into stack
        // and calculate size of queue
        while (q.size() > 0) {
            st.push(q.poll());
            Size++;
        }

        // Put extra element of stack into queue
        // again extra element of stack is the
        // element coming from queue. Now, the
        // queue is reverse
        while (Size != 0) {
            q.add(st.pop());
            Size--;
        }

        // Traverse while stack and queue is not
        // empty
        while (!st.isEmpty() && q.size() != 0) {

            // Top element of stack
            int a = st.peek();

            // Front element of queue
            int b = q.peek();

            // Push the common element
            // in vector if a = b
            if (a == b)
                commonElements.add(a);

            // Else pop the larger value
            // from its container
            if (a > b)
                st.pop();
            else
                q.poll();
        }
      
        return commonElements;
    }
    public static void main(String[] args)
    {
        // Driver Code
        Stack<Integer> St = new Stack<Integer>();
        Queue<Integer> Q = new LinkedList<Integer>();

        // Fill element into stack
        St.add(1);
        St.add(3);
        St.add(5);
        St.add(7);

        // Fill element into queue
        Q.add(1);
        Q.add(2);
        Q.add(5);
        Q.add(9);

        // Find common element if exists
        ArrayList<Integer> v = findCommonElement(St, Q);

        if (v.size() == 0)
            System.out.print("Not Found");
        for (int i = 0; i < v.size(); i++)
            System.out.print(v.get(i) + " ");
    }
}

// this code is contributed by phasing17

Python3

# Python code to implement the above approach

# Function to find common element
# of stack and queue
def findCommonElement(St, Q):

    # Initialize size of queue Q to 0
    Size = 0
    v = []

    # Put every element of queue into stack
    # and calculate size of queue
    while len(Q) != 0:
        St.append(Q[0])
        Q = Q[1:]
        Size += 1

    # Put extra element of stack into queue
    # again extra element of stack is the
    # element coming from queue. Now, the
    # queue is reverse
    while (Size != 0):
        Q.append(St[len(St) - 1])
        St.pop()
        Size -= 1

    # Traverse while stack and queue is not
    # empty
    while (len(St) != 0 and len(Q) != 0): 
            
        # Top element of stack
        a = St[len(St) - 1]

        # Front element of queue
        b = Q[0]

        # append the common element
        # in vector if a = b
        if (a == b):
            v.append(a)

        # Else pop the larger value
        # from its container
        if (a > b):
            St.pop()
        else:
            Q = Q[1:]
    return v

# Driver Code

St = []
Q = []

# Fill element into stack
St.append(1)
St.append(3)
St.append(5)
St.append(7)

# Fill element into queue
Q.append(1)
Q.append(2)
Q.append(5)
Q.append(9)

# Find common element if exists
v = findCommonElement(St, Q)

if (len(v) == 0):
    print("Not Found")
for i in v:
    print(i,end=" ")

# This code is contributed by shinjanpatra

C#

// C# code to implement the above approach
using System;
using System.Collections.Generic;

public class GFG
{
  
    // Function to find common element
    // of stack and queue
    public static List<int> findCommonElement(List<int> St,
                                              List<int> Q)
    {

        // Initialize size of queue Q to 0
        int Size = 0;
        List<int> v = new List<int>();

        // Put every element of queue into stack
        // and calculate size of queue
        while (Q.Count != 0) {
            St.Add(Q[0]);
            Q.RemoveAt(0);
            Size++;
        }

        // Put extra element of stack into queue
        // again extra element of stack is the
        // element coming from queue. Now, the
        // queue is reverse
        while (Size != 0) {
            Q.Add(St[St.Count - 1]);
            St.RemoveAt(St.Count - 1);
            Size--;
        }

        // Traverse while stack and queue is not
        // empty
        while (St.Count != 0 && Q.Count != 0) {

            // Top element of stack
            int a = St[St.Count - 1];

            // Front element of queue
            int b = Q[0];

            // Push the common element
            // in vector if a = b
            if (a == b)
                v.Add(a);

            // Else pop the larger value
            // from its container
            if (a > b)
                St.RemoveAt(St.Count - 1);
            else
                Q.RemoveAt(0);
        }
        return v;
    }
    public static void Main(string[] args)
    {

        // Driver Code

        List<int> St = new List<int>();
        List<int> Q = new List<int>();

        // Fill element into stack
        St.Add(1);
        St.Add(3);
        St.Add(5);
        St.Add(7);

        // Fill element into queue
        Q.Add(1);
        Q.Add(2);
        Q.Add(5);
        Q.Add(9);

        // Find common element if exists
        List<int> v = findCommonElement(St, Q);

        if (v.Count == 0)
            Console.WriteLine("Not Found");
        foreach(var ele in v) Console.Write(ele + " ");
    }
}

//This code is contributed by phasing17

Javascript

    <script>
        // JavaScript code to implement the above approach

        // Function to find common element
        // of stack and queue
        const findCommonElement = (St, Q) => {
        
            // Initialize size of queue Q to 0
            let Size = 0;
            let v = [];

            // Put every element of queue into stack
            // and calculate size of queue
            while (Q.length != 0) {
                St.push(Q[0]);
                Q.shift();
                Size++;
            }

            // Put extra element of stack into queue
            // again extra element of stack is the
            // element coming from queue. Now, the
            // queue is reverse
            while (Size != 0) {
                Q.push(St[St.length - 1]);
                St.pop();
                Size--;
            }

            // Traverse while stack and queue is not
            // empty
            while (St.length != 0 && Q.length != 0) 
            {
            
                // Top element of stack
                let a = St[St.length - 1];

                // Front element of queue
                let b = Q[0];

                // Push the common element
                // in vector if a = b
                if (a == b)
                    v.push(a);

                // Else pop the larger value
                // from its container
                (a > b) ? St.pop() : Q.shift();
            }
            return v;
        }

        // Driver Code

        let St = [];
        let Q = [];

        // Fill element into stack
        St.push(1);
        St.push(3);
        St.push(5);
        St.push(7);

        // Fill element into queue
        Q.push(1);
        Q.push(2);
        Q.push(5);
        Q.push(9);

        // Find common element if exists
        let v = findCommonElement(St, Q);

        if (v.length == 0)
            document.write("Not Found");
        for (let i in v)
            document.write(`${v[i]} `);

        // This code is contributed by rakeshsahni

    </script>
Output

5 1 

Time Complexity: O(M+N) where M =size of the queue and N = size of the stack
Auxiliary Space: O(M) to reverse elements of queue 

Approach Using Set

  • Insert all queue elements into the set
  • Now start removing elements one by one from the stack and check if the element exists in the set
    • If the element exists in the set, then it is a common element
    • if the element does not exist in the set, it is not a common element

C++

// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to find common element
// of stack and queue
vector<int> findCommonElement(stack<int> st, queue<int> q)
{

  // Initialize size of queue Q to 0
  int sz = 0;
  vector<int> commonElements;
  set<int> s;

  // Insert All queue element into set
  while (!q.empty()) {
    s.insert(q.front());
    q.pop();
  }

  // Insert all stack elements into set and check element
  // if inserted into set then it is not present in queue
  // and if it is not inserted then it also preset in
  // queue so, add in into commonElements list.
  while (!st.empty()) {
    int temp = st.top();
    st.pop();
    if (s.find(temp) != s.end()) {
      commonElements.push_back(temp);
    }
  }

  return commonElements;
}
int main()
{
  stack<int> st;
  queue<int> q;

  // Fill element into stack
  st.push(1);
  st.push(3);
  st.push(5);
  st.push(7);

  // Fill element into queue
  q.push(1);
  q.push(2);
  q.push(5);
  q.push(9);

  // Find common element if exists
  vector<int> v = findCommonElement(st, q);

  if (v.size() == 0)
    cout << "Not Found";

  for (int i = 0; i < v.size(); i++)
    cout << v[i] << " ";

  return 0;
}

// This code is contributed by muditj148.

Java

// Java code to implement the above approach
import java.util.*;

class GFG
{
  
    // Function to find common element
    // of stack and queue
    static ArrayList<Integer>
    findCommonElement(Stack<Integer> st,
                      Queue<Integer> q)
    {

        // Initialize size of queue Q to 0
        int Size = 0;
        ArrayList<Integer> commonElements = new ArrayList<Integer>();
        Set<Integer> set = new HashSet<>();
      
      // Insert All queue element into set
      while(q.size()>0){
          set.add(q.poll());
      }
      
      // Insert all stack elements into set and check element if 
      // inserted into set then it is not present in queue
      // and if it is not inserted then it also preset in queue
      // so, add in into commonElements list.
      while(!st.isEmpty()){
        int temp = st.pop();
          if(!set.add(temp)){
            commonElements.add(temp);
        }
      }
      
        
        return commonElements;
    }
    public static void main(String[] args)
    {
        // Driver Code
        Stack<Integer> St = new Stack<Integer>();
        Queue<Integer> Q = new LinkedList<Integer>();

        // Fill element into stack
        St.push(1);
        St.push(3);
        St.push(5);
        St.push(7);

        // Fill element into queue
        Q.add(1);
        Q.add(2);
        Q.add(5);
        Q.add(9);

        // Find common element if exists
        ArrayList<Integer> v = findCommonElement(St, Q);

        if (v.size() == 0)
            System.out.print("Not Found");
        for (int i = 0; i < v.size(); i++)
            System.out.print(v.get(i) + " ");
    }
}

// this code is contributed by phasing17

Python3

# Python3 code to implement the above approach

# Function to find common element
# of stack and queue
def findCommonElement(st, q):
    # Initialize size of queue Q to 0
    sz = 0
    commonElements = []
    s  = set()

    # Insert All queue element into set
    while (len(q)>0):
        s.add(q[0])
        q.pop(0)

    # Insert all stack elements into set and check element
    # if inserted into set then it is not present in queue
    # and if it is not inserted then it also preset in
    # queue so, add in into commonElements list.
    while (len(st) > 0):
        temp = st[len(st)-1]
        st.pop(len(st)-1)
        if temp in s:
            commonElements.append(temp)

    return commonElements


st = []
q = []

# Fill element into stack
st.append(1)
st.append(3)
st.append(5)
st.append(7)

# Fill element into queue
q.append(1)
q.append(2)
q.append(5)
q.append(9)

# Find common element if exists
v = findCommonElement(st, q)

if (len(v) == 0):
    print("Not Found")

print(v)

# This code is contributed by akashish__

C#

using System;
using System.Collections;
using System.Collections.Generic;

public class GFG{
  
    // Function to find common element
    // of stack and queue
    static ArrayList findCommonElement(Stack<int> st,Queue q)
    {
        
        ArrayList commonElements = new ArrayList();
        HashSet<int> sett = new HashSet<int>();
      
      // Insert All queue element into set
      while(q.Count != 0){
          sett.Add((int)q.Dequeue());
      }
      
      // Insert all stack elements into set and check element if 
      // inserted into set then it is not present in queue
      // and if it is not inserted then it also preset in queue
      // so, add in into commonElements list.
      while(st.Count != 0){
        int temp = st.Pop();
          if(!sett.Add(temp)){
            commonElements.Add(temp);
        }
      }
      
      return commonElements;
    }

    static public void Main (){

        // Code
      // Driver Code
        Stack<int> St = new Stack<int>();
        Queue Q = new Queue();

        // Fill element into stack
        St.Push(1);
        St.Push(3);
        St.Push(5);
        St.Push(7);

        // Fill element into queue
        Q.Enqueue(1);
        Q.Enqueue(2);
        Q.Enqueue(5);
        Q.Enqueue(9);

        // Find common element if exists
        ArrayList v = findCommonElement(St, Q);

        if (v.Count == 0)
          Console.WriteLine("Not Found");
        foreach(int i in v)
        {
            Console.Write(i + " ");
        }
    }
}

// This code is contributed by saurabhdalal0001.

Javascript

// JS code to implement the above approach

// Function to find common element
// of stack and queue
function findCommonElement(st,q)
{

// Initialize size of queue Q to 0
// let sz = 0;
let commonElements=[];
let s = new Set;

// Insert All queue element into set
while (q.length != 0) {
    s.add(q[0]);
    q.shift();
}

// Insert all stack elements into set and check element
// if inserted into set then it is not present in queue
// and if it is not inserted then it also preset in
// queue so, add in into commonElements list.
while (st.length != 0) {
    let temp = st[0];
    st.shift();
    if (s.has(temp)) {
    commonElements.push(temp);
    }
}

return commonElements;
}
let st=[];
let q=[];

// Fill element into stack
st.push(1);
st.push(3);
st.push(5);
st.push(7);

// Fill element into queue
q.push(1);
q.push(2);
q.push(5);
q.push(9);

// Find common element if exists
let v = findCommonElement(st, q);

if (v.length == 0)
    console.log("Not Found");

for (let i = v.length-1; i>=0 ; i--)
    console.log(v[i]);

// This code is contributed by adityamaharshi21.
Output

5 1 

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!