|
| 1 | +# 946. Validate Stack Sequences |
| 2 | +# 🟠 Medium |
| 3 | +# |
| 4 | +# https://leetcode.com/problems/validate-stack-sequences/ |
| 5 | +# |
| 6 | +# Tags: Array - Stack - Simulation |
| 7 | + |
| 8 | +import timeit |
| 9 | +from typing import List |
| 10 | + |
| 11 | + |
| 12 | +# Use an extra stack of memory and simulate the operations that took |
| 13 | +# place, push the next element, then, while the top of the stack matches |
| 14 | +# the next element that needs to be popped, pop it. |
| 15 | +# |
| 16 | +# Time complexity: O(n) - We visit each element on the pushed array and |
| 17 | +# do amortized O(1) for each. |
| 18 | +# Space complexity: O(n) - The stack can grow to the same size as the |
| 19 | +# input. |
| 20 | +# |
| 21 | +# Runtime 57 ms Beats 99.86% |
| 22 | +# Memory 14.1 MB Beats 85.31% |
| 23 | +class Solution: |
| 24 | + def validateStackSequences( |
| 25 | + self, pushed: List[int], popped: List[int] |
| 26 | + ) -> bool: |
| 27 | + # Try to simulate the stack, we pop when we can and push |
| 28 | + # when we cannot pop. |
| 29 | + n, stack, next_pop = len(pushed), [], 0 |
| 30 | + for el in pushed: |
| 31 | + # Push the next element. |
| 32 | + stack.append(el) |
| 33 | + # Pop all elements that match. |
| 34 | + while stack and next_pop < n and stack[-1] == popped[next_pop]: |
| 35 | + stack.pop() |
| 36 | + next_pop += 1 |
| 37 | + # If the sequence is valid, we would have popped everything. |
| 38 | + return next_pop == n |
| 39 | + |
| 40 | + |
| 41 | +def test(): |
| 42 | + executors = [Solution] |
| 43 | + tests = [ |
| 44 | + [[1, 2, 3, 4, 5], [4, 5, 3, 2, 1], True], |
| 45 | + [[1, 2, 3, 4, 5], [4, 3, 5, 1, 2], False], |
| 46 | + ] |
| 47 | + for executor in executors: |
| 48 | + start = timeit.default_timer() |
| 49 | + for _ in range(1): |
| 50 | + for col, t in enumerate(tests): |
| 51 | + sol = executor() |
| 52 | + result = sol.validateStackSequences(t[0], t[1]) |
| 53 | + exp = t[2] |
| 54 | + assert result == exp, ( |
| 55 | + f"\033[93m» {result} <> {exp}\033[91m for" |
| 56 | + + f" test {col} using \033[1m{executor.__name__}" |
| 57 | + ) |
| 58 | + stop = timeit.default_timer() |
| 59 | + used = str(round(stop - start, 5)) |
| 60 | + cols = "{0:20}{1:10}{2:10}" |
| 61 | + res = cols.format(executor.__name__, used, "seconds") |
| 62 | + print(f"\033[92m» {res}\033[0m") |
| 63 | + |
| 64 | + |
| 65 | +test() |
0 commit comments