# Find common elements of Stack and Queue

• Last Updated : 27 May, 2022

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]
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 = 
=> 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 = 
=> 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 

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

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

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 ` `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.ArrayList;`   `class` `GFG` `{` `  `  `    ``// Function to find common element` `    ``// of stack and queue` `    ``static` `ArrayList` `    ``findCommonElement(ArrayList St,` `                      ``ArrayList Q)` `    ``{`   `        ``// Initialize size of queue Q to 0` `        ``int` `Size = ``0``;` `        ``ArrayList v = ``new` `ArrayList();`   `        ``// Put every element of queue into stack` `        ``// and calculate size of queue` `        ``while` `(Q.size() != ``0``) {` `            ``St.add(Q.get(``0``));` `            ``Q.remove(``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.get(St.size() - ``1``));` `            ``St.remove(St.size() - ``1``);` `            ``Size--;` `        ``}`   `        ``// Traverse while stack and queue is not` `        ``// empty` `        ``while` `(St.size() != ``0` `&& Q.size() != ``0``) {`   `            ``// Top element of stack` `            ``int` `a = St.get(St.size() - ``1``);`   `            ``// Front element of queue` `            ``int` `b = Q.get(``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.remove(St.size() - ``1``);` `            ``else` `                ``Q.remove(``0``);` `        ``}` `        ``return` `v;` `    ``}` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``// Driver Code` `        ``ArrayList St = ``new` `ArrayList();` `        ``ArrayList Q = ``new` `ArrayList();`   `        ``// 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 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);` `            ``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;`   `            ``// 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

 ``

Output

`5 1 `

Time Complexity: O(M+N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up
Recommended Articles
Page :