Stack data structure strictly follows the principle of LIFO (Last In, First Out), which means that the element that is pushed last should be the one to pop first.
Given a sequence of elements that are pushed in a stack and a sequence of elements that are popped, one may need to validate if the popped sequence could have been possibly obtained from the pushed sequence. This problem is largely encountered in a subsection of Stack problems in Data Structures.
Here’s how you can validate a sequence of pushed and popped elements in a stack:
The algorithm uses a temporary stack to hold the elements. It iterates the pushed sequence and push the elements into the temporary stack one by one. During each push, it checks if the top element of the stack is equal to the leading elements of the popped sequence.
If the two elements are equal, it pops the top element from the stack, and moves the leading pointer of the popped sequence forward. This process repeats until the top element of the stack is not equal to the leading element of popped sequence.
After iterating the pushed sequence, if there are still elements left in the stack, it checks if the stack elements are popped off in the order of the rest of the popped sequence. If the popped sequences are the same, then the popped sequence is valid, otherwise not.
It is worth noting that if all elements can be popped off from the stack to empty it, it indicates the sequence of popped is valid, otherwise it’s invalid.
Here’s the Python code that validates a sequence of pushed and popped elements:
def validateStackSequences(pushed, popped):
j = 0
stack = []
for num in pushed:
stack.append(num)
while stack and j<len(popped) and stack[-1] == popped[j]:
stack.pop()
j += 1
return j == len(popped)
This function takes two parameters: ‘pushed‘ and ‘popped‘, which are list of integers. It returns a boolean value depending on whether the ‘popped‘ sequence is valid or not.
Let’s validate the function with the pushed sequence of [1,2,3,4,5] and the popped sequence of [4,5,3,2,1].
print(validateStackSequences([1,2,3,4,5], [4,5,3,2,1]))
This will output ‘True‘, indicating that the popped sequence [4,5,3,2,1] matches the pushing sequence [1,2,3,4,5].