

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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 Questions & Answers
- Check if all elements of the array are palindrome or nots in Python
- Check if a queue can be sorted into another queue using a stack in Python
- Check whether K-th bit is set or nots in Python
- Check if Queue Elements are pairwise consecutive in Python
- Heap queue (or heapq) in Python
- Stack and Queue in Python using queue Module
- Check whether a Stack is empty or not in Java
- Check if a string is Isogram or not in Python
- Check if strings are rotations of each other or not in Python
- Is it possible in Android to check if a notification is visible or canceled?
- Check if it is possible to serve customer queue with different notes in Python
- Python Pandas - Check if the dataframe objects are equal or not
- Check if the elements of stack are pairwise sorted in Python
- Check if a word exists in a grid or not in Python
- Check if all the 1s in a binary string are equidistant or not in Python
Advertisements