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++
#include <bits/stdc++.h>
using namespace std;
vector< int > findCommonElement(stack< int >& St,
queue< int >& Q)
{
int Size = 0;
vector< int > v;
while (!Q.empty()) {
St.push(Q.front());
Q.pop();
Size++;
}
while (Size != 0) {
Q.push(St.top());
St.pop();
Size--;
}
while (!St.empty() && !Q.empty()) {
int a = St.top();
int b = Q.front();
if (a == b)
v.push_back(a);
(a > b) ? St.pop() : Q.pop();
}
return v;
}
int main()
{
stack< int > St;
queue< int > Q;
St.push(1);
St.push(3);
St.push(5);
St.push(7);
Q.push(1);
Q.push(2);
Q.push(5);
Q.push(9);
vector< int > v = findCommonElement(St, Q);
if (v.size() == 0)
cout << "Not Found" << endl;
for ( auto i : v)
cout << i << " " ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static ArrayList<Integer>
findCommonElement(Stack<Integer> st,
Queue<Integer> q)
{
int Size = 0 ;
ArrayList<Integer> commonElements = new ArrayList<Integer>();
while (q.size() > 0 ) {
st.push(q.poll());
Size++;
}
while (Size != 0 ) {
q.add(st.pop());
Size--;
}
while (!st.isEmpty() && q.size() != 0 ) {
int a = st.peek();
int b = q.peek();
if (a == b)
commonElements.add(a);
if (a > b)
st.pop();
else
q.poll();
}
return commonElements;
}
public static void main(String[] args)
{
Stack<Integer> St = new Stack<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
St.add( 1 );
St.add( 3 );
St.add( 5 );
St.add( 7 );
Q.add( 1 );
Q.add( 2 );
Q.add( 5 );
Q.add( 9 );
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) + " " );
}
}
|
Python3
def findCommonElement(St, Q):
Size = 0
v = []
while len (Q) ! = 0 :
St.append(Q[ 0 ])
Q = Q[ 1 :]
Size + = 1
while (Size ! = 0 ):
Q.append(St[ len (St) - 1 ])
St.pop()
Size - = 1
while ( len (St) ! = 0 and len (Q) ! = 0 ):
a = St[ len (St) - 1 ]
b = Q[ 0 ]
if (a = = b):
v.append(a)
if (a > b):
St.pop()
else :
Q = Q[ 1 :]
return v
St = []
Q = []
St.append( 1 )
St.append( 3 )
St.append( 5 )
St.append( 7 )
Q.append( 1 )
Q.append( 2 )
Q.append( 5 )
Q.append( 9 )
v = findCommonElement(St, Q)
if ( len (v) = = 0 ):
print ( "Not Found" )
for i in v:
print (i,end = " " )
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
public static List< int > findCommonElement(List< int > St,
List< int > Q)
{
int Size = 0;
List< int > v = new List< int >();
while (Q.Count != 0) {
St.Add(Q[0]);
Q.RemoveAt(0);
Size++;
}
while (Size != 0) {
Q.Add(St[St.Count - 1]);
St.RemoveAt(St.Count - 1);
Size--;
}
while (St.Count != 0 && Q.Count != 0) {
int a = St[St.Count - 1];
int b = Q[0];
if (a == b)
v.Add(a);
if (a > b)
St.RemoveAt(St.Count - 1);
else
Q.RemoveAt(0);
}
return v;
}
public static void Main( string [] args)
{
List< int > St = new List< int >();
List< int > Q = new List< int >();
St.Add(1);
St.Add(3);
St.Add(5);
St.Add(7);
Q.Add(1);
Q.Add(2);
Q.Add(5);
Q.Add(9);
List< int > v = findCommonElement(St, Q);
if (v.Count == 0)
Console.WriteLine( "Not Found" );
foreach ( var ele in v) Console.Write(ele + " " );
}
}
|
Javascript
<script>
const findCommonElement = (St, Q) => {
let Size = 0;
let v = [];
while (Q.length != 0) {
St.push(Q[0]);
Q.shift();
Size++;
}
while (Size != 0) {
Q.push(St[St.length - 1]);
St.pop();
Size--;
}
while (St.length != 0 && Q.length != 0)
{
let a = St[St.length - 1];
let b = Q[0];
if (a == b)
v.push(a);
(a > b) ? St.pop() : Q.shift();
}
return v;
}
let St = [];
let Q = [];
St.push(1);
St.push(3);
St.push(5);
St.push(7);
Q.push(1);
Q.push(2);
Q.push(5);
Q.push(9);
let v = findCommonElement(St, Q);
if (v.length == 0)
document.write( "Not Found" );
for (let i in v)
document.write(`${v[i]} `);
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
vector< int > findCommonElement(stack< int > st, queue< int > q)
{
int sz = 0;
vector< int > commonElements;
set< int > s;
while (!q.empty()) {
s.insert(q.front());
q.pop();
}
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;
st.push(1);
st.push(3);
st.push(5);
st.push(7);
q.push(1);
q.push(2);
q.push(5);
q.push(9);
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;
}
|
Java
import java.util.*;
class GFG
{
static ArrayList<Integer>
findCommonElement(Stack<Integer> st,
Queue<Integer> q)
{
int Size = 0 ;
ArrayList<Integer> commonElements = new ArrayList<Integer>();
Set<Integer> set = new HashSet<>();
while (q.size()> 0 ){
set.add(q.poll());
}
while (!st.isEmpty()){
int temp = st.pop();
if (!set.add(temp)){
commonElements.add(temp);
}
}
return commonElements;
}
public static void main(String[] args)
{
Stack<Integer> St = new Stack<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
St.push( 1 );
St.push( 3 );
St.push( 5 );
St.push( 7 );
Q.add( 1 );
Q.add( 2 );
Q.add( 5 );
Q.add( 9 );
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) + " " );
}
}
|
Python3
def findCommonElement(st, q):
sz = 0
commonElements = []
s = set ()
while ( len (q)> 0 ):
s.add(q[ 0 ])
q.pop( 0 )
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 = []
st.append( 1 )
st.append( 3 )
st.append( 5 )
st.append( 7 )
q.append( 1 )
q.append( 2 )
q.append( 5 )
q.append( 9 )
v = findCommonElement(st, q)
if ( len (v) = = 0 ):
print ( "Not Found" )
print (v)
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
public class GFG{
static ArrayList findCommonElement(Stack< int > st,Queue q)
{
ArrayList commonElements = new ArrayList();
HashSet< int > sett = new HashSet< int >();
while (q.Count != 0){
sett.Add(( int )q.Dequeue());
}
while (st.Count != 0){
int temp = st.Pop();
if (!sett.Add(temp)){
commonElements.Add(temp);
}
}
return commonElements;
}
static public void Main (){
Stack< int > St = new Stack< int >();
Queue Q = new Queue();
St.Push(1);
St.Push(3);
St.Push(5);
St.Push(7);
Q.Enqueue(1);
Q.Enqueue(2);
Q.Enqueue(5);
Q.Enqueue(9);
ArrayList v = findCommonElement(St, Q);
if (v.Count == 0)
Console.WriteLine( "Not Found" );
foreach ( int i in v)
{
Console.Write(i + " " );
}
}
}
|
Javascript
function findCommonElement(st,q)
{
let commonElements=[];
let s = new Set;
while (q.length != 0) {
s.add(q[0]);
q.shift();
}
while (st.length != 0) {
let temp = st[0];
st.shift();
if (s.has(temp)) {
commonElements.push(temp);
}
}
return commonElements;
}
let st=[];
let q=[];
st.push(1);
st.push(3);
st.push(5);
st.push(7);
q.push(1);
q.push(2);
q.push(5);
q.push(9);
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]);
|
Time Complexity: O(M+N) where M =size of the queue and N = size of the stack.
Space Complexity: O(N) Where N is extra space as we are using set.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
26 Feb, 2023
Like Article
Save Article