Given a stack of integers, write a function pairWiseConsecutive() that checks whether numbers in the stack are pairwise consecutive or not. The pairs can be increasing or decreasing, and if the stack has an odd number of elements, the element at the top is left out of a pair. The function should retain the original stack content.
Only following standard operations are allowed on stack.
- push(X): Enter a element X on top of stack.
- pop(): Removes top element of the stack.
- empty(): To check if stack is empty.
Input : stack = [4, 5, -2, -3, 11, 10, 5, 6, 20] Output : Yes Each of the pairs (4, 5), (-2, -3), (11, 10) and (5, 6) consists of consecutive numbers. Input : stack = [4, 6, 6, 7, 4, 3] Output : No (4, 6) are not consecutive.
The idea is to use another stack.
- Create an auxiliary stack aux.
- Transfer contents of given stack to aux.
- Traverse aux. While traversing fetch top two elements and check if they are consecutive or not. After checking put these elements back to original stack.
# Python3 program to check if successive
# pair of numbers in the stack are
# consecutive or not
# Function to check if elements are
# pairwise consecutive in stack
# Transfer elements of s to aux.
aux = 
while (len(s) != 0):
# Traverse aux and see if elements
# are pairwise consecutive or not.
# We also need to make sure that
# original content is retained.
result = True
while (len(aux) > 1):
# Fetch current top two
# elements of aux and check
# if they are consecutive.
x = aux[-1]
y = aux[-1]
if (abs(x – y) != 1):
result = False
# append the elements to
# original stack.
if (len(aux) == 1):
# Driver Code
if __name__ == ‘__main__’:
s = 
print(“Stack content (from top)”,
“after function call”)
while (len(s) != 0):
print(s[-1], end = ” “)
# This code is contributed by PranchalK
Yes Stack content (from top) after function call 20 6 5 10 11 -3 -2 5 4
Time complexity: O(n).
Auxiliary Space : O(n).
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
This article is attributed to GeeksforGeeks.org