
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 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
Advertisements