Professional Documents
Culture Documents
ADRIJA RAY
Input : Queue[] = { 5, 1, 2, 6, 3, 4 }
Output : No
Push 5 to stack.
Pop 1, 2 from given Queue and push it to another Queue.
Pop 6 from given Queue and push to stack.
Pop 3, 4 from given Queue and push to second Queue.
Now, from using any of above operation, we cannot push 5
into the second Queue because it is below the 6 in the stack.
METHODOLOGY
Observe, second Queue (which will contain the sorted element) takes inputs (or enqueue
elements) either from given Queue or Stack. So, the next expected (which will initially be 1)
element must be present as a front element of a given Queue or top element of the Stack. So,
simply simulate the process for the second Queue by initializing the expected element as 1.
And check if we can get the expected element from the front of the given Queue or from the
top of the Stack. If we cannot take it from either of them then pop the front element of the
given Queue and push it in the Stack.
Also, observe, that the stack must also be sorted at each instance i.e the element at the top of
the stack must be the smallest in the stack. For eg. let x > y, then x will always be expected
before y. So, x cannot be pushed before y in the stack. Therefore, we cannot push an element
with a higher value on the top of the element having a lesser value.
Algorithm:
else {
// if stack is empty, push the element
if (st.empty()) {
st.push(fnt);
}
return false;
}
// Driven Program
int main()
{
queue<int> q;
q.push(5);
q.push(1);
q.push(2);
q.push(3);
q.push(4);
int n = q.size();
return 0;
}
Output
Yes
Output
Yes
Complexity Analysis:
Time Complexity:
O(n): Where ‘n’ stands for number of elements
Reason: As we traversed the entire input, the time complexity is O(N). The algorithm's time
complexity is linear, where n is the size.
Space Complexity:
O(n): Where ‘n’ stands for number of elements.
Reason: Because the items are held in a queue or stack, the space complexity is O(N). The
algorithm is linear in space, where n is the size.
CONCLUSION
This report has determined whether a queue can be sorted into another queue using a stack.
REFERENCES
https://www.geeksforgeeks.org/check-queue-can-sorted-another-queue-using-stack/
https://www.codingninjas.com/codestudio/library/check-if-a-queue-can-be-sorted-into-
another-queue-using-a-stack