imashutosh51

Sort a stack

Feb 14th, 2026 (edited)
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.87 KB | None | 0 0
  1. """
  2. We use a temporary stack to keep elements in descending order.
  3. In temp, the largest element stays at the bottom and the smallest stays on the top.
  4. For each popped element x from the original stack, we pop all smaller elements from temp
  5. (and push those elements back into the original stack) until x can be placed correctly, then push x into temp.
  6. Finally, we move all elements from temp back to st to get the sorted stack.
  7.  
  8. T.C=O(N^2) because in already reverse sorted array you will have to do N^2 times.Like for every element, you will pop the temp till the end so N*N ie. O(N^2)
  9. """
  10.  
  11. class Solution:
  12.     def sortStack(self, st):
  13.         temp=[]
  14.         while st:
  15.             x=st.pop()
  16.             while temp and x>temp[-1]:
  17.                 st.append(temp.pop())
  18.             temp.append(x)
  19.         while temp:
  20.             st.append(temp.pop())
  21.         return st
  22.  
Advertisement
Add Comment
Please, Sign In to add comment