Program to check given push pop sequences are proper or not in python

When working with stack operations, we often need to validate whether a given sequence of push and pop operations is possible. This problem involves checking if two sequences represent valid stack push and pop actions.

Given two lists pushes and pops, we need to determine if we can simulate the push operations in order while achieving the exact pop sequence specified.

Example Scenario

If we have pushes = [1, 2, 5, 7, 9] and pops = [2, 1, 9, 7, 5], this is valid because we can:

  • Push 1, then push 2, then pop 2, then pop 1
  • Push 5, then push 7, then push 9
  • Pop 9, then pop 7, then pop 5

Algorithm

The solution uses a simulation approach with these steps ?

  • Use a stack to simulate the push/pop operations
  • Iterate through each element in the push sequence
  • For each push, add the element to the stack
  • After each push, check if the top of stack matches the next expected pop
  • If it matches, pop from stack and move to next expected pop
  • Finally, check if the stack is empty (all elements were popped successfully)

Implementation

class Solution:
    def solve(self, pushes, pops):
        stack = []
        pop_index = 0
        
        for element in pushes:
            stack.append(element)
            
            while len(stack) > 0 and pops[pop_index] == stack[-1]:
                stack.pop()
                pop_index += 1
        
        return len(stack) == 0

# Test the solution
ob = Solution()
pushes = [1, 2, 5, 7, 9]
pops = [2, 1, 9, 7, 5]
print(ob.solve(pushes, pops))
True

How It Works

The algorithm simulates the actual stack operations:

  1. Push phase: Add each element from pushes to the stack in order
  2. Pop check: After each push, check if the top element matches the next expected pop
  3. Pop phase: If it matches, pop the element and move to the next expected pop
  4. Validation: If the stack is empty at the end, all pops were successful

Additional Example

# Test with an invalid sequence
pushes = [1, 2, 3, 4]
pops = [4, 1, 3, 2]

ob = Solution()
result = ob.solve(pushes, pops)
print(f"Pushes: {pushes}")
print(f"Pops: {pops}")
print(f"Valid sequence: {result}")
Pushes: [1, 2, 3, 4]
Pops: [4, 1, 3, 2]
Valid sequence: False

Conclusion

This algorithm efficiently validates push-pop sequences by simulating actual stack operations. The key insight is to push elements in order while checking if we can immediately pop the next expected element, ensuring the sequence is achievable.

Updated on: 2026-03-25T12:56:53+05:30

289 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements