

- 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 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
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
- Related Questions & Answers
- Check if Queue Elements are pairwise consecutive in Python
- Check if a Linked List is Pairwise Sorted in C++
- Check if a given array is pairwise sorted or not in C++
- Check if array elements are consecutive in Python
- Check if a queue can be sorted into another queue using a stack in Python
- Check if given array is almost sorted (elements are at-most one position away) in Python
- Check if all array elements are distinct in Python
- Check if all elements of the array are palindrome or not in Python
- Check if elements of Linked List are present in pair in Python
- Python – Check if elements index are equal for list elements
- Python - Check if all elements in a List are same
- Python - Check if all elements in a list are identical
- Check if moves in a stack or queue are possible or nots in Python
- Check if list is sorted or not in Python
- Check if some elements of array are equal JavaScript
Advertisements