NeetCode #353LC-946MediumStack
← Back to All Problems#353 · #946 · Validate Stack Sequences(验证栈序列)
📌 Problem Statement & Constraints
Given two integer arrays
pushed and popped representing the push and pop sequences of a stack, return true if they could have been produced by a valid sequence of stack operations. All values are distinct. Constraints: 1 <= pushed.length == popped.length <= 1000.💡 Core Algorithmic Approaches
- Simulate: push elements from
pushedone at a time, and after each push pop as many elements as match the current position inpopped. - If the simulation ends with an empty stack, the sequences are consistent.
- The greedy popping is safe because a distinct-valued stack has exactly one possible top at any moment.
- The
jpointer intopoppedmust be bounds-checked, since it can reach the end before the loop finishes.
💻 Benchmark Python3 Implementation
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
st = []
j = 0
for x in pushed:
st.append(x)
# pop while the top matches the next expected output
while st and j < len(popped) and st[-1] == popped[j]:
st.pop()
j += 1
return not st # everything must have been popped⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each element is pushed once and popped at most once.
💾 Space Complexity
O(n) for the stack.
⚠️ Interview Pitfalls & Follow-ups
- Forgetting the
j < len(popped)guard: the index would run past the end once all elements have been matched. - Popping only once per push: a single push can trigger a cascade of pops.
- Checking
j == len(popped)instead ofnot st: both work given equal lengths, but the empty-stack test is the direct statement of correctness. - Assuming values can repeat: the problem guarantees distinct values, which is what makes the greedy unambiguous.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Stack Problems
中文速览与面试要点
验证栈序列
给定 pushed 和 popped 两个序列,每个序列中的 值都不重复 ,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列执行的结果时,返回 true;否则,返回 false。约束:1 ≤ pushed.length == popped.length ≤ 1000;0 ≤ pushed[i], popped[i] < 1000;pushed 是 popped 的排列;pushed 和 popped 中的所有元素 互不相同 。
核心要点
- 模拟栈操作(标准解) :按 pushed 顺序依次压栈;每压入一个元素后,就检查栈顶是否等于 popped 的当前待弹出元素,若是则循环弹出并推进 popped 指针。
- 为什么这样是正确的 :pushed 的顺序是唯一的入栈顺序,因此模拟过程是确定的。只要最终栈为空,说明 popped 是合法的出栈序列。
- 终止判定 :遍历完 pushed 后,若栈为空则返回 True,否则 False。
- 复杂度 :O(n)。每个元素入栈出栈各一次。
常见陷阱
- 每压入一个元素后只检查一次 :栈顶可能连续匹配多个 popped 元素,必须用 while 循环。
- j 越界访问 : popped[j] 在 j == n 时会越界。由于 pushed 与 popped 长度相同且元素相同,当 j 达到 n 时栈必为空, while stack 条件会先失败,因此安全。
- 忘记最后检查栈空 :只检查「j 是否走到末尾」也可以,但 not stack 更直观。
- 枚举所有可能的入栈出栈序列 :这是卡特兰数级别(指数级),完全不可行。必须模拟。
参考实现
class Solution:
def validateStackSequences(self, pushed: list[int], popped: list[int]) -> bool:
stack = []
j = 0 # popped 的待弹出位置
for x in pushed:
stack.append(x)
# 尽可能多地弹出匹配的元素
while stack and stack[-1] == popped[j]:
stack.pop()
j += 1
return not stack # 全部弹出则序列合法