Skip to content

Commit 19a3ffe

Browse files
committed
submissions until 2019/12/22
1 parent b150f3a commit 19a3ffe

6 files changed

+291
-3
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
"""
2+
987. Vertical Order Traversal of a Binary Tree
3+
Medium
4+
5+
Given a binary tree, return the vertical order traversal of its nodes values.
6+
For each node at position (X, Y), its left and right children respectively will be at positions
7+
(X-1, Y-1) and (X+1, Y-1).
8+
Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes,
9+
we report the values of the nodes in order from top to bottom (decreasing Y coordinates).
10+
If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.
11+
Return an list of non-empty reports in order of X coordinate. Every report will have a list of values of nodes.
12+
13+
Example 1:
14+
Input: [3,9,20,null,null,15,7]
15+
Output: [[9],[3,15],[20],[7]]
16+
Explanation:
17+
Without loss of generality, we can assume the root node is at position (0, 0):
18+
Then, the node with value 9 occurs at position (-1, -1);
19+
The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2);
20+
The node with value 20 occurs at position (1, -1);
21+
The node with value 7 occurs at position (2, -2).
22+
23+
Example 2:
24+
Input: [1,2,3,4,5,6,7]
25+
Output: [[4],[2],[1,5,6],[3],[7]]
26+
Explanation:
27+
The node with value 5 and the node with value 6 have the same position according to the given scheme.
28+
However, in the report "[1,5,6]", the node value of 5 comes first since 5 is smaller than 6.
29+
30+
Note:
31+
The tree will have between 1 and 1000 nodes.
32+
Each node's value will be between 0 and 1000.
33+
34+
Details
35+
Runtime: 28 ms, faster than 94.75% of Python3 online submissions for Vertical Order Traversal of a Binary Tree.
36+
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Vertical Order Traversal of a Binary Tree.
37+
38+
T ~ O(N + h*log(h) * v*log(v) * k*log(k)), where k is max number of nodes with the same vertical level
39+
"""
40+
41+
from collections import defaultdict
42+
from typing import List
43+
44+
45+
class TreeNode:
46+
def __init__(self, x):
47+
self.val = x
48+
self.left = None
49+
self.right = None
50+
51+
52+
class Solution:
53+
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
54+
vl_hl_dict = defaultdict(lambda: defaultdict(list))
55+
56+
hl = 0
57+
q, p_item = [(root, 0), None], None
58+
while True:
59+
item = q.pop(0)
60+
61+
if item is None:
62+
if p_item is None:
63+
break
64+
hl += 1
65+
q.append(None)
66+
else:
67+
node, vl = item
68+
vl_hl_dict[vl][hl].append(node.val)
69+
70+
if node.left:
71+
q.append((node.left, vl - 1))
72+
if node.right:
73+
q.append((node.right, vl + 1))
74+
p_item = item
75+
76+
result = []
77+
for vl, hl_dict in sorted(vl_hl_dict.items(), key=lambda x: x[0]):
78+
vl_values = []
79+
for hl, values in sorted(hl_dict.items(), key=lambda x: x[0]):
80+
vl_values.extend(sorted(values))
81+
result.append(vl_values)
82+
83+
return result
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
"""
2+
103. Binary Tree Zigzag Level Order Traversal
3+
Medium
4+
5+
Given a binary tree, return the zigzag level order traversal of its nodes' values.
6+
(ie, from left to right, then right to left for the next level and alternate between).
7+
8+
For example:
9+
Given binary tree [3,9,20,null,null,15,7],
10+
3
11+
/ \
12+
9 20
13+
/ \
14+
15 7
15+
return its zigzag level order traversal as:
16+
[
17+
[3],
18+
[20,9],
19+
[15,7]
20+
]
21+
22+
Details
23+
Runtime: 24 ms, faster than 98.09% of Python3 online submissions for Binary Tree Zigzag Level Order Traversal.
24+
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Binary Tree Zigzag Level Order Traversal.
25+
"""
26+
27+
# Definition for a binary tree node.
28+
from typing import List
29+
30+
31+
class TreeNode:
32+
def __init__(self, x):
33+
self.val = x
34+
self.left = None
35+
self.right = None
36+
37+
38+
class Solution:
39+
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
40+
if not root:
41+
return []
42+
43+
q = [root, None]
44+
paths, path = [], []
45+
is_left_to_right_order = True
46+
p_node = None
47+
48+
while True:
49+
node = q.pop(0)
50+
51+
if node is None:
52+
if p_node is None:
53+
break
54+
55+
if is_left_to_right_order:
56+
paths.append(path)
57+
else:
58+
paths.append(path[::-1])
59+
60+
path = []
61+
is_left_to_right_order = not is_left_to_right_order
62+
q.append(None)
63+
else:
64+
path.append(node.val)
65+
if node.left:
66+
q.append(node.left)
67+
if node.right:
68+
q.append(node.right)
69+
70+
p_node = node
71+
return paths

ok_find_all_anagrams_in_a_string.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@
2525
The substring with start index = 1 is "ba", which is an anagram of "ab".
2626
The substring with start index = 2 is "ab", which is an anagram of "ab".
2727
28-
Runtime: 108 ms, faster than 82.22% of Python3 online submissions for Find All Anagrams in a String.
29-
Memory Usage: 13.7 MB, less than 100.00% of Python3 online submissions for Find All Anagrams in a String.
28+
Runtime: 96 ms, faster than 93.15% of Python3 online submissions for Find All Anagrams in a String.
29+
Memory Usage: 13.6 MB, less than 100.00% of Python3 online submissions for Find All Anagrams in a String.
3030
"""
3131

3232
from collections import defaultdict
@@ -40,7 +40,7 @@ def findAnagrams(self, s: str, p: str) -> List[int]:
4040
1. Iterate over m - len(p) characters in s and count unique characters
4141
1.2. If unique characters == unique characters in p, then save index
4242
43-
Note: T~O(m*N)
43+
Note: T~O(N+M)
4444
"""
4545
p_unique_chs_count = defaultdict(int)
4646
for ch in p:
@@ -49,6 +49,9 @@ def findAnagrams(self, s: str, p: str) -> List[int]:
4949
m, n = len(p), len(s)
5050
indexs = []
5151

52+
if n - m < 0:
53+
return indexs
54+
5255
subset = s[:m]
5356
subset_unique_chs_count = defaultdict(int)
5457
for ch in subset:

ok_jewels_and_stones.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
771. Jewels and Stones
3+
Easy
4+
5+
You're given strings J representing the types of stones that are jewels, and S representing the stones you have.
6+
Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
7+
The letters in J are guaranteed distinct, and all characters in J and S are letters.
8+
Letters are case sensitive, so "a" is considered a different type of stone from "A".
9+
10+
Example 1:
11+
Input: J = "aA", S = "aAAbbbb"
12+
Output: 3
13+
14+
Example 2:
15+
Input: J = "z", S = "ZZ"
16+
Output: 0
17+
Note:
18+
19+
S and J will consist of letters and have length at most 50.
20+
The characters in J are distinct.
21+
22+
Details
23+
Runtime: 20 ms, faster than 99.02% of Python3 online submissions for Jewels and Stones.
24+
Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Jewels and Stones.
25+
"""
26+
27+
from collections import defaultdict
28+
29+
30+
class Solution:
31+
def numJewelsInStones(self, J: str, S: str) -> int:
32+
unique_jewels = set(J)
33+
unique_stone_counts = defaultdict(int)
34+
35+
for stone in S:
36+
unique_stone_counts[stone] += 1
37+
38+
return sum([unique_stone_counts[key] for key in unique_stone_counts.keys()
39+
if key in unique_jewels])
File renamed without changes.
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
"""
2+
84. Largest Rectangle in Histogram
3+
Hard
4+
5+
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1,
6+
find the area of largest rectangle in the histogram.
7+
8+
Example:
9+
10+
Input: [2,1,5,6,2,3]
11+
Output: 10
12+
"""
13+
from typing import List
14+
15+
16+
class Solution:
17+
def largestRectangleArea(self, heights: List[int]) -> int:
18+
19+
# This function calulates maximum
20+
# rectangular area under given
21+
# histogram with n bars
22+
23+
# Create an empty stack. The stack
24+
# holds indexes of histogram[] list.
25+
# The bars stored in the stack are
26+
# always in increasing order of
27+
# their heights.
28+
stack = list()
29+
30+
max_area = 0 # Initialize max area
31+
32+
# Run through all bars of
33+
# given histogram
34+
index = 0
35+
histogram = heights
36+
while index < len(histogram):
37+
38+
# If this bar is higher
39+
# than the bar on top
40+
# stack, push it to stack
41+
42+
if (not stack) or (histogram[stack[-1]] <= histogram[index]):
43+
stack.append(index)
44+
index += 1
45+
46+
# If this bar is lower than top of stack,
47+
# then calculate area of rectangle with
48+
# stack top as the smallest (or minimum
49+
# height) bar.'i' is 'right index' for
50+
# the top and element before top in stack
51+
# is 'left index'
52+
else:
53+
# pop the top
54+
top_of_stack = stack.pop()
55+
56+
# Calculate the area with
57+
# histogram[top_of_stack] stack
58+
# as smallest bar
59+
area = (histogram[top_of_stack] *
60+
((index - stack[-1] - 1)
61+
if stack else index))
62+
63+
# update max area, if needed
64+
max_area = max(max_area, area)
65+
66+
# Now pop the remaining bars from
67+
# stack and calculate area with
68+
# every popped bar as the smallest bar
69+
while stack:
70+
# pop the top
71+
top_of_stack = stack.pop()
72+
73+
# Calculate the area with
74+
# histogram[top_of_stack]
75+
# stack as smallest bar
76+
area = (histogram[top_of_stack] *
77+
((index - stack[-1] - 1)
78+
if stack else index))
79+
80+
# update max area, if needed
81+
max_area = max(max_area, area)
82+
83+
# Return maximum area under
84+
# the given histogram
85+
return max_area
86+
87+
88+
if __name__ == '__main__':
89+
heights = [2, 1, 5, 6, 2, 3]
90+
target = 10
91+
output = Solution().largestRectangleArea(heights)
92+
assert target == output, f'Expected: {target}, but got {output}'

0 commit comments

Comments
 (0)