Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion 1-Two-Sum.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
prevMap = {} # val -> index

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function Solution.twoSum:

for i, n in enumerate(nums):
diff = target - n
if diff in prevMap:
Expand Down
8 changes: 4 additions & 4 deletions 10-Regular-Expression-Matching.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
# BOTTOM-UP Dynamic Programming
class Solution:
def isMatch(self, s: str, p: str) -> bool:
cache = [[False] * (len(p) + 1) for i in range(len(s) + 1)]
cache = [[False] * (len(p) + 1) for _ in range(len(s) + 1)]
cache[len(s)][len(p)] = True

for i in range(len(s), -1, -1):
for j in range(len(p) - 1, -1 ,-1):
match = i < len(s) and (s[i] == p[j] or p[j] == ".")

if (j + 1) < len(p) and p[j + 1] == "*":
cache[i][j] = cache[i][j + 2]
if match:
cache[i][j] = cache[i + 1][j] or cache[i][j]
elif match:
cache[i][j] = cache[i+1][j+1]

Comment on lines -4 to +17
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Solution.isMatch refactored with the following changes:

return cache[0][0]


Expand Down
13 changes: 9 additions & 4 deletions 100-Same-Tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@

class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q: return True
if p and q and p.val == q.val:
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
else: return False
if p or q:
return (
self.isSameTree(p.left, q.left)
and self.isSameTree(p.right, q.right)
if p and q and p.val == q.val
else False
)

else: return True
Comment on lines -10 to +18
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Solution.isSameTree refactored with the following changes:

6 changes: 3 additions & 3 deletions 102-Binary-Tree-Level-Order-Traversal.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
q = collections.deque()
if root: q.append(root)

while q:
val = []
for i in range(len(q)):

for _ in range(len(q)):
Comment on lines -13 to +17
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Solution.levelOrder refactored with the following changes:

node = q.popleft()
val.append(node.val)
if node.left: q.append(node.left)
Expand Down
17 changes: 9 additions & 8 deletions 104-Maximum-Depth-of-Binary-Tree.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
# RECURSIVE DFS
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0

return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
return (
1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
if root
else 0
)
Comment on lines -4 to +8
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Solution.maxDepth refactored with the following changes:


# ITERATIVE DFS
class Solution:
def maxDepth(self, root: TreeNode) -> int:
stack = [[root, 1]]
res = 0

while stack:
node, depth = stack.pop()

Comment on lines -14 to +18
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function Solution.maxDepth:

if node:
res = max(res, depth)
stack.append([node.left, depth + 1])
Expand All @@ -26,12 +27,12 @@ class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0

level = 0
q = deque([root])
while q:

for i in range(len(q)):
for _ in range(len(q)):
Comment on lines -29 to +35
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Solution.maxDepth refactored with the following changes:

node = q.popleft()
if node.left:
q.append(node.left)
Expand Down
4 changes: 2 additions & 2 deletions 11-Container-With-Most-Water.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ class Solution:
def maxArea(self, height: List[int]) -> int:
l, r = 0, len(height) - 1
res = 0

while l < r:
res = max(res, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
elif height[r] <= height[l]:
else:
Comment on lines -5 to +10
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Solution.maxArea refactored with the following changes:

r -= 1
return res
6 changes: 3 additions & 3 deletions 1143-Longest-Common-Subsequence.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
dp = [[0 for j in range(len(text2) + 1)] for i in range(len(text1) + 1)]
dp = [[0 for _ in range(len(text2) + 1)] for _ in range(len(text1) + 1)]

for i in range(len(text1) - 1, -1, -1):
for j in range(len(text2) - 1, -1, -1):
if text1[i] == text2[j]:
dp[i][j] = 1 + dp[i + 1][j + 1]
else:
dp[i][j] = max(dp[i][j + 1], dp[i + 1][j])

Comment on lines -3 to +11
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Solution.longestCommonSubsequence refactored with the following changes:

return dp[0][0]
4 changes: 2 additions & 2 deletions 115-Distinct-Subsequences.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
class Solution:
def numDistinct(self, s: str, t: str) -> int:
cache = {}

for i in range(len(s) + 1):
cache[(i, len(t))] = 1
for j in range(len(t)):
cache[(len(s), j)] = 0

Comment on lines -4 to +9
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function Solution.numDistinct:

for i in range(len(s) - 1, -1, -1):
for j in range(len(t) - 1, -1, -1):
if s[i] == t[j]:
Expand Down
2 changes: 1 addition & 1 deletion 121-Best-Time-To-Buy-and-Sell-Stock.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class Solution:
def maxProfit(self, prices: List[int]) -> int:
res = 0

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function Solution.maxProfit:

l = 0
for r in range(1, len(prices)):
if prices[r] < prices[l]:
Expand Down
12 changes: 6 additions & 6 deletions 127-Word-Ladder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,24 @@ class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0

nei = collections.defaultdict(list)
wordList.append(beginWord)
for word in wordList:
for j in range(len(word)):
pattern = word[:j] + "*" + word[j + 1:]
pattern = f"{word[:j]}*{word[j + 1:]}"
nei[pattern].append(word)
visit = set([beginWord])

visit = {beginWord}
q = deque([beginWord])
res = 1
while q:
for i in range(len(q)):
for _ in range(len(q)):
word = q.popleft()
if word == endWord:
return res
for j in range(len(word)):
pattern = word[:j] + "*" + word[j + 1:]
pattern = f"{word[:j]}*{word[j + 1:]}"
Comment on lines -5 to +22
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Solution.ladderLength refactored with the following changes:

for neiWord in nei[pattern]:
if neiWord not in visit:
visit.add(neiWord)
Expand Down
2 changes: 1 addition & 1 deletion 128-Longest-consecutive-sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
numSet = set(nums)
longest = 0

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function Solution.longestConsecutive:

for n in nums:
# check if its the start of a sequence
if (n - 1) not in numSet:
Expand Down
2 changes: 1 addition & 1 deletion 138-Copy-List-With-Random-Pointer.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
oldToCopy = { None : None }

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function Solution.copyRandomList:

cur = head
while cur:
copy = Node(cur.val)
Expand Down
2 changes: 1 addition & 1 deletion 141-Linked-List-Cycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
class Solution:
def hasCycle(self, head: ListNode) -> bool:
slow, fast = head, head

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function Solution.hasCycle:

while fast and fast.next:
slow = slow.next
fast = fast.next.next
Expand Down
2 changes: 1 addition & 1 deletion 146-LRU-Cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.cache = {} # map key to node

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function LRUCache.__init__:

self.left, self.right = Node(0, 0), Node(0, 0)
self.left.next, self.right.prev = self.right, self.left

Expand Down
4 changes: 2 additions & 2 deletions 15-3Sum.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()

for i, a in enumerate(nums):
if i > 0 and a == nums[i - 1]:
continue

Comment on lines -5 to +9
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function Solution.threeSum:

l, r = i + 1, len(nums) - 1
while l < r:
threeSum = a + nums[l] + nums[r]
Expand Down
6 changes: 3 additions & 3 deletions 150-Evaluate-Reverse-Polish-Notation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for c in tokens:
if c == "+":
if c == "*":
stack.append(stack.pop() * stack.pop())
elif c == "+":
stack.append(stack.pop() + stack.pop())
elif c == "-":
a, b = stack.pop(), stack.pop()
stack.append(b - a)
elif c == "*":
stack.append(stack.pop() * stack.pop())
Comment on lines -5 to -11
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Solution.evalRPN refactored with the following changes:

  • Simplify conditional into switch-like form (switch)

elif c == "/":
a, b = stack.pop(), stack.pop()
stack.append(int(b / a))
Expand Down
4 changes: 2 additions & 2 deletions 152-Maximum-Product-Subarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ def maxProduct(self, nums: List[int]) -> int:
# O(n)/O(1) : Time/Memory
res = max(nums)
curMin, curMax = 1, 1

for n in nums:

Comment on lines -6 to +8
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function Solution.maxProduct:

tmp = curMax * n
curMax = max(n * curMax, n * curMin, n)
curMin = min(tmp, n * curMin, n)
Expand Down
2 changes: 1 addition & 1 deletion 1584-Min-Cost-to-Connect-all-Points.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ def minCostConnectPoints(self, points: List[List[int]]) -> int:
dist = abs(x1 - x2) + abs(y1 - y2)
adj[i].append([dist, j])
adj[j].append([dist, i])

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function Solution.minCostConnectPoints:

# Prim's
res = 0
visit = set()
Expand Down
2 changes: 1 addition & 1 deletion 1851-Minimum-Interval-to-Include-Each-Query.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[in
l, r = intervals[i]
heapq.heappush(minHeap, (r - l + 1, r))
i += 1

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function Solution.minInterval:

while minHeap and minHeap[0][1] < q:
heapq.heappop(minHeap)
res[q] = minHeap[0][0] if minHeap else -1
Expand Down
11 changes: 5 additions & 6 deletions 199-Binary-Tree-Right-Side-View.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,16 @@ class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
res = []
q = collections.deque([root])

while q:
rightSide = None
qLen = len(q)

for i in range(qLen):
node = q.popleft()
if node:

for _ in range(qLen):
if node := q.popleft():
rightSide = node
q.append(node.left)
q.append(node.right)
if rightSide:
res.append(rightSide.val)
res.append(rightSide.val)
Comment on lines -11 to +22
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Solution.rightSideView refactored with the following changes:

return res
6 changes: 3 additions & 3 deletions 2-Add-Two-Numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@ class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode()
cur = dummy

carry = 0
while l1 or l2 or carry:
v1 = l1.val if l1 else 0
v2 = l2.val if l2 else 0

# new digit
val = v1 + v2 + carry
carry = val // 10
val = val % 10
cur.next = ListNode(val)

Comment on lines -10 to +21
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function Solution.addTwoNumbers:

# update ptrs
cur = cur.next
l1 = l1.next if l1 else None
Expand Down
4 changes: 2 additions & 2 deletions 20-Valid-Parentheses.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ class Solution:
def isValid(self, s: str) -> bool:
Map = { ")":"(", "]":"[", "}":"{" }
stack = []

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function Solution.isValid:

for c in s:
if c not in Map:
stack.append(c)
continue
if not stack or stack[-1] != Map[c]:
return False
stack.pop()

return not stack
4 changes: 2 additions & 2 deletions 202-Happy-Number.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
class Solution:
def isHappy(self, n: int) -> bool:
slow, fast = n, self.sumSquareDigits(n)

while slow != fast:
fast = self.sumSquareDigits(fast)
fast = self.sumSquareDigits(fast)
slow = self.sumSquareDigits(slow)

return True if fast == 1 else False
return fast == 1
Comment on lines -4 to +10
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Solution.isHappy refactored with the following changes:


def sumSquareDigits(self, n):
output = 0
Expand Down
6 changes: 3 additions & 3 deletions 208-Implement-Trie.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def insert(self, word: str) -> None:
curr = self.root
for c in word:
i = ord(c)-ord("a")
if curr.children[i] == None:
if curr.children[i] is None:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Trie.insert refactored with the following changes:

curr.children[i] = TrieNode()
curr = curr.children[i]
curr.end = True
Expand All @@ -31,7 +31,7 @@ def search(self, word: str) -> bool:
curr = self.root
for c in word:
i = ord(c)-ord("a")
if curr.children[i] == None:
if curr.children[i] is None:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Trie.search refactored with the following changes:

return False
curr = curr.children[i]
return curr.end
Expand All @@ -43,7 +43,7 @@ def startsWith(self, prefix: str) -> bool:
curr = self.root
for c in prefix:
i = ord(c)-ord("a")
if curr.children[i] == None:
if curr.children[i] is None:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Trie.startsWith refactored with the following changes:

return False
curr = curr.children[i]
return True
Loading