Skip to content

Commit 63d1c54

Browse files
committed
feat(python): solutions
1 parent dca19f7 commit 63d1c54

15 files changed

+581
-46
lines changed

JavaScript/0122. Best Time to Buy and Sell Stock II.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,14 @@
3030
* @return {number}
3131
*/
3232

33-
// 1)
33+
// 1) Two Pointers
3434
const maxProfit1 = (prices) => {
3535
let res = 0;
3636
let slow = 0;
3737
let fast = 1;
3838

39-
while (slow < prices.length) {
40-
while (prices[fast] > prices[fast - 1]) {
39+
while (fast < prices.length) {
40+
while ( prices[fast - 1] < prices[fast]) {
4141
fast++;
4242
}
4343
res += prices[fast - 1] - prices[slow];

JavaScript/0130. Surrounded Regions.js

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
* @return {void} Do not return anything, modify board in-place instead.
2525
*/
2626

27+
// DFS
28+
//
2729
// Idea
2830
// 1) Check four borders. If it is O, change it and all its neighbor to temporary #
2931
// 2) Change all O to X
@@ -54,24 +56,24 @@ const solve = (board) => {
5456
}
5557
};
5658

57-
// change every square connected to left and right borders from O to temporary #
59+
// Change every square connected to left and right borders from O to temporary #
5860
for (let i = 0; i < h; i++) {
5961
go(i, 0);
6062
go(i, w - 1);
6163
}
6264

63-
// change every square connected to top and bottom borders from O to temporary #
65+
// Change every square connected to top and bottom borders from O to temporary #
6466
for (let i = 1; i < w - 1; i++) {
6567
go(0, i);
6668
go(h - 1, i);
6769
}
6870

6971
for (let i = 0; i < h; i++) {
7072
for (let j = 0; j < w; j++) {
71-
// change the rest of O to X
73+
// Change the rest of O to X
7274
if (board[i][j] === 'O') board[i][j] = 'X';
7375

74-
// change temporary # back to O
76+
// Change temporary # back to O
7577
if (board[i][j] === '#') board[i][j] = 'O';
7678
}
7779
}

Python/0079. Word Search.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,19 +30,19 @@ def exist(self, board: List[List[str]], word: str) -> bool:
3030
if not board or not board[0]:
3131
return False
3232
m, n = len(board), len(board[0])
33-
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
33+
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
3434

3535
def go(i, j, k):
3636
if k == len(word):
3737
return True
38-
if i < 0 or i >= m or j < 0 or j >= n or board[i][j] != word[k]:
38+
if 0 <= i < m and 0 <= j < n and board[i][j] == word[k]:
39+
c = board[i][j]
40+
board[i][j] = "#" # mark visited
41+
for dir in dirs:
42+
if go(i + dir[0], j + dir[1], k + 1):
43+
return True
44+
board[i][j] = c # reset
3945
return False
40-
c = board[i][j]
41-
board[i][j] = "#" # mark visited
42-
for dir in dirs:
43-
if go(i + dir[0], j + dir[1], k + 1):
44-
return True
45-
board[i][j] = c # reset
4646
return False
4747

4848
for i in range(m):

Python/0102. Binary Tree Level Order Traversal.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,12 @@ def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
7171
q = [root]
7272

7373
while q:
74+
nodes = q.copy()
75+
q = []
7476
row = []
7577

76-
# Note cannot use "while q" here because q changes.
77-
# len(q) stands for the number of nodes in the current level.
78-
for _ in range(len(q)):
79-
node = q.pop(0)
78+
while nodes:
79+
node = nodes.pop(0)
8080
row.append(node.val)
8181
if node.left:
8282
q.append(node.left)
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
2+
#
3+
# Example 1:
4+
#
5+
# Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
6+
# Output: [3,9,20,null,null,15,7]
7+
#
8+
# Example 2:
9+
#
10+
# Input: preorder = [-1], inorder = [-1]
11+
# Output: [-1]
12+
#
13+
# Constraints:
14+
#
15+
# 1 <= preorder.length <= 3000
16+
# inorder.length == preorder.length
17+
# -3000 <= preorder[i], inorder[i] <= 3000
18+
# preorder and inorder consist of unique values.
19+
# Each value of inorder also appears in preorder.
20+
# preorder is guaranteed to be the preorder traversal of the tree.
21+
# inorder is guaranteed to be the inorder traversal of the tree.
22+
23+
24+
# Definition for a binary tree node.
25+
# class TreeNode:
26+
# def __init__(self, val=0, left=None, right=None):
27+
# self.val = val
28+
# self.left = left
29+
# self.right = right
30+
31+
32+
# preorder: (3) 9 20 15 7
33+
# inorder: 9 (3) 15 20 7
34+
# 3
35+
# / \
36+
# 9 20
37+
# / \
38+
# 15 7
39+
class Solution:
40+
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
41+
if not preorder or not inorder:
42+
return None
43+
44+
def build(l, r):
45+
if l > r:
46+
return None
47+
val = preorder.pop(0)
48+
i = inorder.index(val)
49+
50+
node = TreeNode(val)
51+
node.left = build(l, i - 1)
52+
node.right = build(i + 1, r)
53+
return node
54+
55+
return build(0, len(inorder) - 1)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
2+
# A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
3+
#
4+
# Example 1:
5+
#
6+
# Input: nums = [-10,-3,0,5,9]
7+
# Output: [0,-3,9,-10,null,5]
8+
# Explanation: [0,-10,5,null,-3,null,9] is also accepted:
9+
#
10+
# Example 2:
11+
#
12+
# Input: nums = [1,3]
13+
# Output: [3,1]
14+
# Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.
15+
#
16+
# Constraints:
17+
#
18+
# 1 <= nums.length <= 10^4
19+
# -10^4 <= nums[i] <= 10^4
20+
# nums is sorted in a strictly increasing order.
21+
22+
23+
# Definition for a binary tree node.
24+
# class TreeNode:
25+
# def __init__(self, val=0, left=None, right=None):
26+
# self.val = val
27+
# self.left = left
28+
# self.right = right
29+
30+
31+
class Solution:
32+
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
33+
if not nums:
34+
return None
35+
m = len(nums) // 2
36+
root = TreeNode(nums[m])
37+
root.left = self.sortedArrayToBST(nums[:m])
38+
root.right = self.sortedArrayToBST(nums[m + 1 :])
39+
return root
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
2+
#
3+
# struct Node {
4+
# int val;
5+
# Node *left;
6+
# Node *right;
7+
# Node *next;
8+
# }
9+
#
10+
# Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
11+
# Initially, all next pointers are set to NULL.
12+
#
13+
# Example 1:
14+
#
15+
# Input: root = [1,2,3,4,5,6,7]
16+
# Output: [1,#,2,3,#,4,5,6,7,#]
17+
# Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
18+
#
19+
# Example 2:
20+
#
21+
# Input: root = []
22+
# Output: []
23+
#
24+
# Constraints:
25+
#
26+
# The number of nodes in the tree is in the range [0, 212 - 1].
27+
# -1000 <= Node.val <= 1000
28+
#
29+
# Follow-up:
30+
#
31+
# You may only use constant extra space.
32+
# The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
33+
34+
35+
"""
36+
# Definition for a Node.
37+
class Node:
38+
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
39+
self.val = val
40+
self.left = left
41+
self.right = right
42+
self.next = next
43+
"""
44+
45+
# 1)
46+
# Time O(n)
47+
# Space O(1)
48+
class Solution:
49+
def connect(self, root: "Optional[Node]") -> "Optional[Node]":
50+
if not root:
51+
return None
52+
if root.left:
53+
root.left.next = root.right
54+
if root.right:
55+
root.right.next = root.next.left if root.next else None
56+
self.connect(root.left)
57+
self.connect(root.right)
58+
return root
59+
60+
61+
# 2) BFS - level-order traversal
62+
# Similar
63+
# 102. Binary Tree Level Order Traversal
64+
# 116. Populating Next Right Pointers in Each Node
65+
#
66+
# Time O(n)
67+
class Solution:
68+
def connect(self, root: "Optional[Node]") -> "Optional[Node]":
69+
if not root:
70+
return None
71+
72+
q = [root]
73+
74+
while q:
75+
nodes = q.copy()
76+
q = []
77+
while nodes:
78+
node = nodes.pop(0)
79+
node.next = nodes[0] if nodes else None
80+
if node.left:
81+
q.append(node.left)
82+
if node.right:
83+
q.append(node.right)
84+
return root

Python/0118. Pascal's Triangle.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Given an integer numRows, return the first numRows of Pascal's triangle.
2+
# In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
3+
#
4+
# Example 1:
5+
#
6+
# Input: numRows = 5
7+
# Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
8+
#
9+
# Example 2:
10+
#
11+
# Input: numRows = 1
12+
# Output: [[1]]
13+
#
14+
# Constraints:
15+
#
16+
# 1 <= numRows <= 30
17+
18+
19+
# Dynamic programming
20+
# Time O(numRows^2), consider how many overall loop iterations there are. The outer loop obviously runs numRows times, but for each iteration of the outer loop, the inner loop runs rowNum times
21+
# Therefore, the overall number of triangle updates that occur is 1 + 2 + 3 + ... + numRows, which, according to Gauss' formula, is (1 + numRows) * numRows / 2 -> O(numRows^2)
22+
# Space O(numRows^2), we need to store each number that we update in triangle, so the space requirement is the same as the time complexity
23+
class Solution:
24+
def generate(self, numRows: int) -> List[List[int]]:
25+
if numRows == 0:
26+
return []
27+
if numRows == 1:
28+
return [[1]]
29+
if numRows == 2:
30+
return [[1], [1, 1]]
31+
32+
res = [[1], [1, 1]]
33+
for i in range(2, numRows):
34+
row = [1]
35+
for j in range(1, i):
36+
row.append(res[i - 1][j - 1] + res[i - 1][j])
37+
row.append(1)
38+
res.append(row)
39+
return res
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# You are given an array prices where prices[i] is the price of a given stock on the ith day.
2+
# You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
3+
# Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
4+
#
5+
# Example 1:
6+
#
7+
# Input: prices = [7,1,5,3,6,4]
8+
# Output: 5
9+
# Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
10+
# Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
11+
#
12+
# Example 2:
13+
#
14+
# Input: prices = [7,6,4,3,1]
15+
# Output: 0
16+
# Explanation: In this case, no transactions are done and the max profit = 0.
17+
#
18+
# Constraints:
19+
#
20+
# 1 <= prices.length <= 10^5
21+
# 0 <= prices[i] <= 10^4
22+
23+
24+
# 1) Brute force (time limit exceeded)
25+
# Time O(n^2)
26+
# Space O(1)
27+
class Solution:
28+
def maxProfit(self, prices: List[int]) -> int:
29+
mx = 0
30+
for i in range(len(prices)):
31+
for j in range(i + 1, len(prices)):
32+
mx = max(mx, prices[j] - prices[i])
33+
return mx
34+
35+
36+
# 2) One pass using min and max
37+
# Time O(n)
38+
# Space O(1)
39+
class Solution:
40+
def maxProfit(self, prices: List[int]) -> int:
41+
if len(prices) < 2:
42+
return 0
43+
mn = float("inf")
44+
mx = float("-inf")
45+
for p in prices:
46+
mn = min(mn, p)
47+
mx = max(mx, p - mn)
48+
return mx

0 commit comments

Comments
 (0)