Skip to content

Commit 86c3181

Browse files
committed
Sync LeetCode submission Runtime - 15 ms (42.30%), Memory - 18.7 MB (76.51%)
1 parent b39bcf2 commit 86c3181

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<p>Given an array of <strong>unique</strong> integers <code>preorder</code>, return <code>true</code> <em>if it is the correct preorder traversal sequence of a binary search tree</em>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/12/preorder-tree.jpg" style="width: 292px; height: 302px;" />
6+
<pre>
7+
<strong>Input:</strong> preorder = [5,2,1,3,6]
8+
<strong>Output:</strong> true
9+
</pre>
10+
11+
<p><strong class="example">Example 2:</strong></p>
12+
13+
<pre>
14+
<strong>Input:</strong> preorder = [5,2,6,1,3]
15+
<strong>Output:</strong> false
16+
</pre>
17+
18+
<p>&nbsp;</p>
19+
<p><strong>Constraints:</strong></p>
20+
21+
<ul>
22+
<li><code>1 &lt;= preorder.length &lt;= 10<sup>4</sup></code></li>
23+
<li><code>1 &lt;= preorder[i] &lt;= 10<sup>4</sup></code></li>
24+
<li>All the elements of <code>preorder</code> are <strong>unique</strong>.</li>
25+
</ul>
26+
27+
<p>&nbsp;</p>
28+
<p><strong>Follow up:</strong> Could you do it using only constant space complexity?</p>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Approach 1: Monotonic Stack
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def verifyPreorder(self, preorder: List[int]) -> bool:
8+
min_limit = -inf
9+
stack = []
10+
11+
for num in preorder:
12+
while stack and stack[-1] < num:
13+
min_limit = stack.pop()
14+
15+
if num <= min_limit:
16+
return False
17+
18+
stack.append(num)
19+
20+
return True

0 commit comments

Comments
 (0)