Sponsored
Sponsored
The key idea is to use a stack to simulate the push and pop operations. We iterate over each element in the pushed array, pushing them onto the stack. After each push, we check the top of the stack to see if it matches the next element in the popped array. If it does, we pop the stack. By the end of both arrays, if all operations are valid, the stack should be empty.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(n), for the stack storage used during the process.
1using System.Collections.Generic;
2
3public class Solution {
4 public bool ValidateStackSequences(int[] pushed, int[] popped) {
5 Stack<int> stack = new Stack<int>();
6 int j = 0;
7 foreach (int x in pushed) {
8 stack.Push(x);
9 while (stack.Count > 0 && stack.Peek() == popped[j]) {
10 stack.Pop();
11 j++;
12 }
13 }
14 return stack.Count == 0;
15 }
16}
In this C# solution, Stack
from the System.Collections.Generic namespace is used, similar to other implementations, following the same logic to validate the sequences.
In this approach, you can use two pointers to bypass the use of an explicit stack. You iterate over the pushed
array with one pointer while another pointer operates over the popped
array. Match elements and mimic stack operations conceptually.
Time Complexity: O(n), where n is the length of the arrays.
Space Complexity: O(1), as no extra space is used aside from input arrays.
1
This C implementation utilizes a two-pointer technique by reusing the pushed
array to simulate stack operations through in-place modifications using indexes. It keeps track of elements using two index pointers.