diff --git a/non-overlapping-intervals/printjin-gmailcom.py b/non-overlapping-intervals/printjin-gmailcom.py new file mode 100644 index 000000000..c1d8114bc --- /dev/null +++ b/non-overlapping-intervals/printjin-gmailcom.py @@ -0,0 +1,13 @@ +from typing import List + +class Solution: + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: + intervals.sort(key=lambda x: x[1]) + count = 0 + end = float('-inf') + for start, finish in intervals: + if start < end: + count += 1 + else: + end = finish + return count diff --git a/number-of-connected-components-in-an-undirected-graph/printjin-gmailcom.py b/number-of-connected-components-in-an-undirected-graph/printjin-gmailcom.py new file mode 100644 index 000000000..a18a6a461 --- /dev/null +++ b/number-of-connected-components-in-an-undirected-graph/printjin-gmailcom.py @@ -0,0 +1,18 @@ +from typing import ( + List, +) + +class Solution: + def count_components(self, n: int, edges: List[List[int]]) -> int: + parent = [i for i in range(n)] + def find(x): + if parent[x] != x: + parent[x] = find(parent[x]) + return parent[x] + for a, b in edges: + root_a = find(a) + root_b = find(b) + if root_a != root_b: + parent[root_a] = root_b + n -= 1 + return n diff --git a/remove-nth-node-from-end-of-list/printjin-gmailcom.py b/remove-nth-node-from-end-of-list/printjin-gmailcom.py new file mode 100644 index 000000000..854f68b8d --- /dev/null +++ b/remove-nth-node-from-end-of-list/printjin-gmailcom.py @@ -0,0 +1,11 @@ +class Solution: + def removeNthFromEnd(self, head, n): + dummy = ListNode(0, head) + fast = slow = dummy + for _ in range(n): + fast = fast.next + while fast.next: + fast = fast.next + slow = slow.next + slow.next = slow.next.next + return dummy.next diff --git a/same-tree/printjin-gmailcom.py b/same-tree/printjin-gmailcom.py new file mode 100644 index 000000000..c9a451f77 --- /dev/null +++ b/same-tree/printjin-gmailcom.py @@ -0,0 +1,9 @@ +class Solution: + def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: + if not p and not q: + return True + if not p or not q: + return False + if p.val != q.val: + return False + return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) diff --git a/serialize-and-deserialize-binary-tree/printjin-gmailcom.py b/serialize-and-deserialize-binary-tree/printjin-gmailcom.py new file mode 100644 index 000000000..df79e56df --- /dev/null +++ b/serialize-and-deserialize-binary-tree/printjin-gmailcom.py @@ -0,0 +1,26 @@ +class Codec: + def serialize(self, root): + def dfs(node): + if not node: + vals.append("None") + return + vals.append(str(node.val)) + dfs(node.left) + dfs(node.right) + + vals = [] + dfs(root) + return ",".join(vals) + + def deserialize(self, data): + def dfs(): + val = next(vals) + if val == "None": + return None + node = TreeNode(int(val)) + node.left = dfs() + node.right = dfs() + return node + + vals = iter(data.split(",")) + return dfs()