
- 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
Check if moves in a stack or queue are possible or nots in Python
Suppose we have one binary list, where 1 denotes push operation and 0 denotes a pop operation on a stack or a queue. We have to check whether the possible set of operations are valid or not.
So, if the input is like nums = [1,0,1,1,0,1], then the output will be True as the sequence is [Push,Pop,Push,Push,Pop,Push] as we are not popping element from empty list so these operations are valid.
To solve this, we will follow these steps −
- push_count := 0
- for i in range 0 to size of nums - 1, do
- if nums[i] is 1, then
- push_count := push_count + 1
- otherwise,
- push_count := push_count - 1
- if push_count < 0, then
- return False
- if nums[i] is 1, then
- return True
Example
Let us see the following implementation to get better understanding −
def solve(nums): push_count = 0 for i in range (len(nums)): if nums[i]: push_count += 1 else: push_count -= 1 if push_count < 0: return False return True nums = [1,0,1,1,0,1] print(solve(nums))
Input
[1,0,1,1,0,1]
Output
True
- Related Articles
- Check whether K-th bit is set or nots in Python
- Check if a queue can be sorted into another queue using a stack in Python
- Check if Queue Elements are pairwise consecutive in Python
- Stack and Queue in Python using queue Module
- Heap queue (or heapq) in Python
- Check if it is possible to serve customer queue with different notes in Python
- Check whether a Stack is empty or not in Java
- Check if the elements of stack are pairwise sorted in Python
- Check if a string is Isogram or not in Python
- Is it possible in Android to check if a notification is visible or canceled?
- What is Heap queue (or heapq) in Python?
- Check if strings are rotations of each other or not in Python
- Check if all the 1s in a binary string are equidistant or not in Python
- Check if a word exists in a grid or not in Python
- Check if list is sorted or not in Python

Advertisements