
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Given Push-Pop Sequences in Python
Suppose we have a list of numbers called pushes, and another list of numbers called pops, we have to check whether this is a valid sequence of stack push and pop actions or not.
So, if the input is like pushes = [1, 2, 5, 7, 9] pops = [2, 1, 9, 7, 5], then the output will be True, as we can push [1, 2] first then pop them both. Then push [5, 7, 9] and pop them all.
To solve this, we will follow these steps −
- s := a new stack
- i := 0
- for each ele in pushes, do
- push ele into s
- while size of s > 0 and pops[i] is same top element of s, do
- delete top element from s
- i := i + 1
- return true when size of s is same as 0, otherwise false
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, pushes, pops): s = [] i = 0 for ele in pushes: s.append(ele) while len(s) > 0 and pops[i] == s[-1]: s.pop() i += 1 return len(s) == 0 ob = Solution() pushes = [1, 2, 5, 7, 9] pops = [2, 1, 9, 7, 5] print(ob.solve(pushes, pops))
Input
[1, 2, 5, 7, 9], [2, 1, 9, 7, 5]
Output
True
Advertisements