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
  • return True

Example

Let us see the following implementation to get better understanding −

 Live Demo

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

Updated on: 19-Jan-2021

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements