Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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. We should retain the original stack content after checking.
To solve this problem, we can use basic stack operations: push, pop and check if the stack is empty.
Example
If the input is like stk = [5, 6, -4, -5, 12, 11, 6, 7, 22], then the output will be True. After removing the top element 22, the pairs are [(7, 6), (11, 12), (-5, -4), (6, 5)] and all are consecutive.
Algorithm
To solve this, we will follow these steps −
- Create a temporary stack by reversing the original stack
- Clear the original stack
- Set flag to True
- While temp stack has more than 1 element:
- Pop two elements and check if their absolute difference is 1
- If not consecutive, set flag to False
- Push both elements back to original stack
- If one element remains in temp, push it to original stack
- Return flag
Implementation
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
# Test the function
stk = [5, 6, -4, -5, 12, 11, 6, 7, 22]
result = solve(stk)
print("Are elements pairwise consecutive?", result)
print("Original stack restored:", stk)
Are elements pairwise consecutive? True Original stack restored: [5, 6, -4, -5, 12, 11, 6, 7, 22]
How It Works
The algorithm processes pairs from the bottom of the stack upward. For the stack [5, 6, -4, -5, 12, 11, 6, 7, 22]:
- Top element 22 is left unpaired (odd number of elements)
- Pairs checked: (7,6), (11,12), (-5,-4), (6,5)
- All pairs have absolute difference of 1, so result is True
- Original stack is restored after processing
Alternative Example
# Example with non-consecutive pairs
stk2 = [1, 3, 5, 6, 8, 10]
result2 = solve(stk2)
print("Are elements pairwise consecutive?", result2)
print("Stack content:", stk2)
Are elements pairwise consecutive? False Stack content: [1, 3, 5, 6, 8, 10]
Conclusion
This algorithm efficiently checks if stack elements form pairwise consecutive numbers while preserving the original stack. The time complexity is O(n) and space complexity is O(n) for the temporary stack.
