Problem: Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] Output: true Explanation: We might do the following sequence: 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 Explanation: 1 cannot be popped before 2.
Approach: We can use stack itself :) to see if the sequence of pushes and pops are valid or not. Once we use stack, the approach is straight forward. It looks like:
- popIndex = 0
- FOR i = 0 to n - 1
- Stack.Push(pushed[i])
- WHILE Stack not empty AND Stack.Top == popped[popIndex]
- Stack.Pop()
- popIndex = popIndex + 1
- RETURN popIndex == n
That's all!
Implementation in C#:
public bool ValidateStackSequences(int[] pushed, int[] popped)
{
int j = 0;
Stack<int> stack = new Stack<int>();
foreach (int num in pushed)
{
stack.Push(num);
while (stack.Count > 0 && stack.Peek() == popped[j])
{
stack.Pop();
++j;
}
}
return j == popped.Length;
}
Complexity: O(n)
No comments:
Post a Comment