Check if the elements of stack are pairwise sorted in Python


Suppose we have a stack of numbers; we have to check whether values in the stack are pairwise consecutive or not. These pairs can be increasing or decreasing. If the stack has an odd number of values, the top element is left out of a pair. And we should retain the original stack content after checking. 

To solve this problem, we can use three operations on stack called push, pop and check whether stack is empty or not.

So, if the input is like stk = [5, 6, -4, -5, 12, 11, 6, 7, 22], then the output will be True as after removing top element 22, the pairs are [(5, 6), (-4, -5), (12, 11), (6, 7)] all are consecutive.

To solve this, we will follow these steps −

  • temp := pop elements from stk and push into temp
  • clear the stack stk
  • flag := True
  • while size of temp > 1, do
    • item_first, item_second := top two elements of temp and pop them
    • if |item_first - item_second| is not 1, then
      • flag := False
    • push item_first and item_second into stk
  • if size of temp is same as 1, then
    • push top of temp into stk
  • return flag

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def solve(stk):
   temp = stk[::-1]
   stk.clear()
 
   flag = True
   while len(temp) > 1: 
      item_first = temp[-1] 
      temp.pop() 
      item_second = temp[-1] 
      temp.pop() 
      if abs(item_first - item_second) != 1: 
         flag = False
 
      stk.append(item_first) 
      stk.append(item_second)
 
    if len(temp) == 1: 
      stk.append(temp[-1]) 
 
   return flag
   
stk = [5, 6, -4, -5, 12, 11, 6, 7, 22]
print(solve(stk))

Input

[5, 6, -4, -5, 12, 11, 6, 7, 22]

Output

True

Updated on: 15-Jan-2021

206 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements