# [Leetcode][946. Validate Stack Sequences] 4 Approaches: Stack, Array and Greedy

**By Long Luo**

This article is the solution of Problem 946. Validate Stack Sequences.

1 | 946. Validate Stack Sequences |

# Solution 1 Using Stack and Greedy

## Idea

All elements must be **pushed** in in order. The key is how to pop them out?

Assuming that the value of the current top element of the stack is `1`

, and the next value to be popped in the corresponding popped sequence is also `1`

, then this value must be popped out immediately. Because the subsequent push will change the top element of the stack to a value other than `2`

, so the popped sequence of the popped numbers does not correspond.

Pushes each number in the pushed queue onto the stack, checking to see if the number is the next value to be popped in the popped sequence, and pops it if so.

Finally, check that not all the popped values are popped.

1 | public boolean validateStackSequences(int[] pushed, int[] popped) { |

## Analysis

**Time Complexity**: $O(N)$**Space Complexity**: $O(N)$

# Solution 2 Using Stack

Solution `1`

uses `2`

circles and hard to understand.

We can simulate the operation. We use `2`

indices to the pushed and poped array.

There comes `3`

cases:

- pushed[i] != poped[j], i++
- pushed[i] == poped[j], i++, j++
- i == len, popped[j] == stack.peek(), j++
- i == len, j < len, popped[j] == stack.peek() --> break the circle.

## Code

1 | public static boolean validateStackSequences(int[] pushed, int[] popped) { |

## Analysis

**Time Complexity**: $O(N)$**Space Complexity**: $O(N)$

# Solution 3 Using Array

Use the array to realize the function of the stack, and simulate the operation of popping and pushing the stack. **size** represents the size of the stack, and **size-1** is the position of the top of the stack.

Although access is faster, using an array to implement a stack is not recommended in most cases.

Especially when the pushed array may be very large, the array stack as the stack will also be very large.

But in fact, there are not many elements in the stack at the same time, which is a great waste.

1 | public boolean validateStackSequences(int[] pushed, int[] popped) { |

## Analysis

**Time Complexity**: $O(N)$**Space Complexity**: $O(N)$

# Solution 4 Optimize Method 3

In fact, we can optimize the Solution `3`

, we can find that stack is redundant.

When traversing the pushed array, `pushed[i]`

is actually the element at the top of the stack.

At this time, `pushed[i-1]`

, `push[i-2]`

… These positions are already “free”, so they are completely The role of stack can be replaced by array push.

1 | public boolean validateStackSequences(int[] pushed, int[] popped) { |

## Analysis

**Time Complexity**: $O(N)$**Space Complexity**: $O(1)$

All suggestions are welcome.

If you have any query or suggestion please comment below.

Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗