|
| 1 | +#!/usr/bin/python3 |
| 2 | +""" |
| 3 | +Given two sequences pushed and popped with distinct values, return true if and |
| 4 | +only if this could have been the result of a sequence of push and pop operations |
| 5 | +on an initially empty stack. |
| 6 | +
|
| 7 | +Example 1: |
| 8 | +
|
| 9 | +Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] |
| 10 | +Output: true |
| 11 | +Explanation: We might do the following sequence: |
| 12 | +push(1), push(2), push(3), push(4), pop() -> 4, |
| 13 | +push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 |
| 14 | +Example 2: |
| 15 | +
|
| 16 | +Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2] |
| 17 | +Output: false |
| 18 | +Explanation: 1 cannot be popped before 2. |
| 19 | +
|
| 20 | +
|
| 21 | +Note: |
| 22 | +
|
| 23 | +0 <= pushed.length == popped.length <= 1000 |
| 24 | +0 <= pushed[i], popped[i] < 1000 |
| 25 | +pushed is a permutation of popped. |
| 26 | +pushed and popped have distinct values. |
| 27 | +""" |
| 28 | +from typing import List |
| 29 | + |
| 30 | + |
| 31 | +class Solution: |
| 32 | + def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: |
| 33 | + """ |
| 34 | + maintain a stack and iterate through pushed |
| 35 | + """ |
| 36 | + j = 0 |
| 37 | + n = len(pushed) |
| 38 | + stk = [] |
| 39 | + for i in range(n): |
| 40 | + stk.append(pushed[i]) |
| 41 | + while j < n and stk and stk[-1] == popped[j]: |
| 42 | + stk.pop() |
| 43 | + j += 1 |
| 44 | + |
| 45 | + return j == n |
| 46 | + |
| 47 | + def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: |
| 48 | + """ |
| 49 | + maintain a stack |
| 50 | + """ |
| 51 | + i = 0 |
| 52 | + j = 0 |
| 53 | + stk = [] |
| 54 | + n = len(pushed) |
| 55 | + while i < n and j < n: |
| 56 | + while i < n and (not stk or stk[-1] != popped[j]): |
| 57 | + stk.append(pushed[i]) |
| 58 | + i += 1 |
| 59 | + |
| 60 | + stk.pop() |
| 61 | + j += 1 |
| 62 | + |
| 63 | + while j < n and stk and stk[-1] == popped[j]: |
| 64 | + stk.pop() |
| 65 | + j += 1 |
| 66 | + |
| 67 | + return not stk |
0 commit comments