- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements