Open In App

Check if the given push and pop sequences of Stack is valid or not

Given push[] and pop[] sequences with distinct values. The task is to check if this could have been the result of a sequence of push and pop operations on an initially empty stack. Return “True” if it otherwise returns “False”.

Examples: 

Input: pushed = { 1, 2, 3, 4, 5 }, popped = { 4, 5, 3, 2, 1 }
Output: True
Following sequence can be performed:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Input: pushed = { 1, 2, 3, 4, 5 }, popped = { 4, 3, 5, 1, 2 }
Output: False
1 can't be popped before 2.

Approach: 

  • If the element X has been pushed to the stack then check if the top element in the pop[] sequence is X or not. 
  • If it is X then pop it right now else top of the push[] sequence will be changed and make the sequences invalid. So, similarly, do the same for all the elements and check if the stack is empty or not in the last. 
  • If empty then print True else print False.

Below is the implementation of above approach:




// C++ implementation of above approach
#include <iostream>
#include <stack>
 
using namespace std;
 
// Function to check validity of stack sequence
bool validateStackSequence(int pushed[], int popped[], int len){
     
    // maintain count of popped elements
    int j = 0;
     
    // an empty stack
    stack <int> st;
    for(int i = 0; i < len; i++){
        st.push(pushed[i]);
         
        // check if appended value is next to be popped out
        while (!st.empty() && j < len && st.top() == popped[j]){
            st.pop();
            j++;
        }
    }
     
    return j == len;
}
 
// Driver code
int main()
{
   int pushed[] = {1, 2, 3, 4, 5};
   int popped[] = {4, 5, 3, 2, 1};
   int len = sizeof(pushed)/sizeof(pushed[0]);
    
   cout << (validateStackSequence(pushed, popped, len) ? "True" : "False");
    
   return 0;
}
 
// This code is contributed by Rituraj Jain




// Java program for above implementation
import java.util.*;
 
class GfG
{
 
    // Function to check validity of stack sequence
    static boolean validateStackSequence(int pushed[],
                                        int popped[], int len)
    {
 
        // maintain count of popped elements
        int j = 0;
 
        // an empty stack
        Stack<Integer> st = new Stack<>();
        for (int i = 0; i < len; i++)
        {
            st.push(pushed[i]);
 
            // check if appended value
            // is next to be popped out
            while (!st.empty() && j < len &&
                    st.peek() == popped[j])
            {
                st.pop();
                j++;
            }
        }
 
        return j == len;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int pushed[] = {1, 2, 3, 4, 5};
        int popped[] = {4, 5, 3, 2, 1};
        int len = pushed.length;
 
        System.out.println((validateStackSequence(pushed, popped, len) ? "True" : "False"));
    }
}
 
/* This code contributed by PrinciRaj1992 */




# Function to check validity of stack sequence
def validateStackSequence(pushed, popped):
    # maintain count of popped elements
    j = 0
 
    # an empty stack
    stack = []
 
    for x in pushed:
        stack.append(x)
 
        # check if appended value is next to be popped out
        while stack and j < len(popped) and stack[-1] == popped[j]:
            stack.pop()
            j = j + 1
 
    return j == len(popped)
 
 
# Driver code
pushed = [1, 2, 3, 4, 5]
popped = [4, 5, 3, 2, 1]
print(validateStackSequence(pushed, popped))




// C# program for above implementation
using System;
using System.Collections.Generic;
 
class GfG
{
 
    // Function to check validity of stack sequence
    static bool validateStackSequence(int []pushed,
                                        int []popped, int len)
    {
 
        // maintain count of popped elements
        int j = 0;
 
        // an empty stack
        Stack<int> st = new Stack<int>();
        for (int i = 0; i < len; i++)
        {
            st.Push(pushed[i]);
 
            // check if appended value
            // is next to be popped out
            while (st.Count != 0 && j < len &&
                    st.Peek() == popped[j])
            {
                st.Pop();
                j++;
            }
        }
 
        return j == len;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int []pushed = {1, 2, 3, 4, 5};
        int []popped = {4, 5, 3, 2, 1};
        int len = pushed.Length;
 
        Console.WriteLine((validateStackSequence(pushed,
                        popped, len) ? "True" : "False"));
    }
}
 
// This code contributed by Rajput-Ji




<script>
 
// Javascript implementation of above approach
 
function validateStackSequence( pushed, popped, len)
{
     
    // maintain count of popped elements
    var j = 0;
     
    // an empty stack
    var st=[];
    for(var i = 0; i < len; i++){
        st.push(pushed[i]);
         
        // check if appended value is next
        // to be popped out
        while (!st.length==0 && j < len &&
        st[st.length-1] == popped[j])
        {
            st.pop();
            j++;
        }
    }
     
    return j == len;
}
 
var pushed = [1, 2, 3, 4, 5];
   var popped = [4, 5, 3, 2, 1];
   var len = pushed.length;
    
  document.write( (validateStackSequence(pushed, popped, len)
  ? "True" : "False"));
 
 
// This code is contributed by SoumikMondal
 
</script>




<?php
// PHP implementation of above approach
 
// Function to check validity of stack sequence
function validateStackSequence($pushed, $popped, $len)
{
     
    // maintain count of popped elements
    $j = 0;
     
    // an empty stack
    $st = array();
    for($i = 0; $i < $len; $i++)
    {
        array_push($st, $pushed[$i]);
         
        // check if appended value is next
        // to be popped out
        while (!empty($st) && $j < $len &&
            $st[count($st) - 1] == $popped[$j])
        {
            array_pop($st);
            $j++;
        }
    }
     
    return $j == $len;
}
 
// Driver code
$pushed = array(1, 2, 3, 4, 5);
$popped = array(4, 5, 3, 2, 1);
$len = count($pushed);
     
echo (validateStackSequence($pushed,
                   $popped, $len) ? "True" : "False");
     
// This code is contributed by mits
?>

Output
True






Time Complexity: O(N), where N is size of stack.

Approach (without extra space):

This approach simulates the stack operations using the pushed array and checks if the final stack state matches the popped array. If the sequence is valid, the program returns True, else it returns False.

Step-by-step approach:

  1. Two integer variables i and j are initialized to 0, representing the indices of the pushed and popped arrays, respectively.
  2. For each element val in the pushed[] array, the program first pushes it onto the simulated stack by incrementing the i index and setting the value of pushed[i] to val.
  3. The program then checks if the top element of the simulated stack (pushed[i-1]) is equal to the next element to be popped (popped[j]). If they are equal, it means that the top element of the simulated stack matches the next element to be popped, so the program pops the element from the simulated stack by decrementing the i index and incrementing the j index.
  4. Steps 2-3 are repeated for each element in the pushed array.
  5. If the pushed array has been fully processed and the simulated stack is empty (i == 0), then the sequence is valid and the function returns True. Otherwise, the sequence is invalid and the function returns False.

Note: this approach does not use an actual stack data structure, but instead simulates the stack using the pushed array itself, which acts as a stack. The program uses two pointers i and j to keep track of the current state of the simulated stack and the next element to be popped, respectively.

Below is the implementation of the above approach:




#include <iostream>
#include <stack>
 
using namespace std;
 
// Function to check validity of stack sequence using
// simulation
bool validateStackSequence(int pushed[], int popped[],
                           int len)
{
    // Intialise one pointer pointing on pushed array
    int i = 0;
 
    // Intialise one pointer pointing on popped array
    int j = 0;
 
    for (int k = 0; k < len; k++) {
        int val = pushed[k];
 
        // Using pushed as the stack.
        pushed[i++] = val;
 
        while (i > 0 && pushed[i - 1] == popped[j]) {
            i--; // Decrement i
            j++; // Increment j
        }
    }
 
    // Since pushed is a permutation of popped so at the end
    // we are supposed to be left with an empty stack
    return i == 0;
}
 
// Driver code
int main()
{
    // sample inputs
    int pushed[] = { 1, 2, 3, 4, 5 };
    int popped[] = { 4, 5, 3, 2, 1 };
    int len = sizeof(pushed) / sizeof(pushed[0]);
 
    // validate stack sequence
    if (validateStackSequence(pushed, popped, len)) {
        cout << "True";
    }
    else {
        cout << "False";
    }
 
    return 0;
}




import java.util.*;
 
public class Main {
    // Function to check validity of stack sequence using
    // simulation
    public static boolean
    validateStackSequence(int[] pushed, int[] popped,
                          int len)
    {
        // Initialize one pointer pointing on pushed array
        int i = 0;
 
        // Initialize one pointer pointing on popped array
        int j = 0;
 
        for (int k = 0; k < len; k++) {
            int val = pushed[k];
 
            // Using pushed as the stack.
            pushed[i++] = val;
 
            while (i > 0 && pushed[i - 1] == popped[j]) {
                i--; // Decrement i
                j++; // Increment j
            }
        }
 
        // Since pushed is a permutation of popped so at the
        // end we are supposed to be left with an empty
        // stack
        return i == 0;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // Sample inputs
        int[] pushed = { 1, 2, 3, 4, 5 };
        int[] popped = { 4, 5, 3, 2, 1 };
        int len = pushed.length;
 
        // Validate stack sequence
        if (validateStackSequence(pushed, popped, len)) {
            System.out.println("True");
        }
        else {
            System.out.println("False");
        }
    }
}




# Function to check validity of stack sequence using simulation
def validate_stack_sequence(pushed, popped, length):
    i = 0  # Initialize one pointer pointing on pushed array
    j = 0  # Initialize one pointer pointing on popped array
 
    for k in range(length):
        val = pushed[k]
 
        # Using pushed as the stack.
        pushed[i] = val
        i += 1
 
        while i > 0 and pushed[i - 1] == popped[j]:
            i -= 1  # Decrement i
            j += 1  # Increment j
 
    # Since pushed is a permutation of popped, at the end
    # we are supposed to be left with an empty stack
    return i == 0
 
# Driver code
if __name__ == "__main__":
    # Sample inputs
    pushed = [1, 2, 3, 4, 5]
    popped = [4, 5, 3, 2, 1]
    length = len(pushed)
 
    # Validate stack sequence
    if validate_stack_sequence(pushed, popped, length):
        print("True")
    else:
        print("False")
         
 # This code is contributed by akshitaguprzj3




using System;
 
class Program {
    // Function to check the validity of stack sequence
    // using simulation
    static bool ValidateStackSequence(int[] pushed,
                                      int[] popped, int len)
    {
        // Initialize two pointers pointing to the pushed
        // and popped arrays
        int i = 0; // Pointer for the pushed array
        int j = 0; // Pointer for the popped array
 
        for (int k = 0; k < len; k++) {
            int val = pushed[k];
 
            // Using pushed as the stack.
            pushed[i++] = val;
 
            while (i > 0 && pushed[i - 1] == popped[j]) {
                i--; // Decrement i
                j++; // Increment j
            }
        }
 
        // Since pushed is a permutation of popped, at the
        // end we are supposed to be left with an empty
        // stack
        return i == 0;
    }
 
    // Driver code
    static void Main()
    {
        // Sample inputs
        int[] pushed = { 1, 2, 3, 4, 5 };
        int[] popped = { 4, 5, 3, 2, 1 };
        int len = pushed.Length;
 
        // Validate stack sequence
        if (ValidateStackSequence(pushed, popped, len)) {
            Console.WriteLine("True");
        }
        else {
            Console.WriteLine("False");
        }
    }
}




// Javascript program for the above approach
function validateStackSequence(pushed, popped, len) {
  let i = 0; // Pointer for pushed array
  let j = 0; // Pointer for popped array
 
  for (let i = 0; i < len; i++) {
    const val = pushed[i];
 
    pushed[i++] = val; // Use pushed as the stack
 
    while (i > 0 && pushed[i - 1] === popped[j]) {
      i--; // Decrement i
      j++; // Increment j
    }
  }
 
  // Since pushed is a permutation of popped, at the end
  // we should have an empty stack
  return i === 0;
}
 
// Driver code
const pushed = [1, 2, 3, 4, 5];
const popped = [4, 5, 3, 2, 1];
const len = pushed.length;
 
// Validate stack sequence
if (validateStackSequence(pushed, popped, len)) {
  console.log("True");
} else {
  console.log("False");
}
// THIS CODE IS CONTRIBUTED BY PIYUSH AGARWAL

Output
True






Time Complexity: O(N)
Auxiliary Space: O(1)


Article Tags :