
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to check given push pop sequences are proper or not 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
- Related Articles
- Program to check whether leaves sequences are same of two leaves or not in python
- C# program to check whether two sequences are the same or not
- Program to check given string is pangram or not in Python
- Program to check given point in inside or boundary of given polygon or not in python
- Program to check whether given graph is bipartite or not in Python
- Program to check whether given password meets criteria or not in Python
- Program to check whether given words are maintaining given pattern or not in C++
- C++ Program to check if given numbers are coprime or not
- Program to check whether parentheses are balanced or not in Python
- Program to check whether given matrix is Toeplitz Matrix or not in Python
- Program to check whether given number is Narcissistic number or not in Python
- Program to check given string is anagram of palindromic or not in Python
- Program to check whether given tree is symmetric tree or not in Python
- Python program to check whether a given string is Heterogram or not
- Python program to check if a given string is Keyword or not

Advertisements