Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.
Example 1:
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
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2] Output: false Explanation: 1 cannot be popped before 2.
Constraints:
1 <= pushed.length <= 10000 <= pushed[i] <= 1000pushed are unique.popped.length == pushed.lengthpopped is a permutation of pushed.Problem summary: Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Stack
[1,2,3,4,5] [4,5,3,2,1]
[1,2,3,4,5] [4,3,5,1,2]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #946: Validate Stack Sequences
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Deque<Integer> stk = new ArrayDeque<>();
int i = 0;
for (int x : pushed) {
stk.push(x);
while (!stk.isEmpty() && stk.peek() == popped[i]) {
stk.pop();
++i;
}
}
return i == popped.length;
}
}
// Accepted solution for LeetCode #946: Validate Stack Sequences
func validateStackSequences(pushed []int, popped []int) bool {
stk := []int{}
i := 0
for _, x := range pushed {
stk = append(stk, x)
for len(stk) > 0 && stk[len(stk)-1] == popped[i] {
stk = stk[:len(stk)-1]
i++
}
}
return i == len(popped)
}
# Accepted solution for LeetCode #946: Validate Stack Sequences
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stk = []
i = 0
for x in pushed:
stk.append(x)
while stk and stk[-1] == popped[i]:
stk.pop()
i += 1
return i == len(popped)
// Accepted solution for LeetCode #946: Validate Stack Sequences
impl Solution {
pub fn validate_stack_sequences(pushed: Vec<i32>, popped: Vec<i32>) -> bool {
let mut stk: Vec<i32> = Vec::new();
let mut i = 0;
for &x in &pushed {
stk.push(x);
while !stk.is_empty() && *stk.last().unwrap() == popped[i] {
stk.pop();
i += 1;
}
}
i == popped.len()
}
}
// Accepted solution for LeetCode #946: Validate Stack Sequences
function validateStackSequences(pushed: number[], popped: number[]): boolean {
const stk: number[] = [];
let i = 0;
for (const x of pushed) {
stk.push(x);
while (stk.length && stk.at(-1)! === popped[i]) {
stk.pop();
i++;
}
}
return i === popped.length;
}
Use this to step through a reusable interview workflow for this problem.
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.