Find duplicate subtrees

Challenge Given the root of a binary tree, return all duplicate subtrees. You only need to return the root of any of them. Solution # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def __init__(self): self.all_node = [] self.ans = [] self.s = set() def preorder(self, root, arr): arr.append(root.val) if root.left: self.preorder(root.left, arr) else: arr.append(None) if root.right: self.preorder(root.right, arr ) else: arr.append(None) return arr def get_subtree(self, root): res = [self.preorder(root, []), root] current, root = res if current in self.all_node and tuple(current) not in self.s: self.ans.append(root) self.s.add(tuple(current)) else: self.all_node.append(current) def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]: queue = [root] while queue: node = queue.pop(0) self.get_subtree(node) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return self.ans Time Complexity: O(n^2) ...

September 10, 2021 · 1 min · Nolan

Valid Word Abbreviation

Challenge Given two params a word and it’s abbreviation return True if the abbreviation is valid. Examples: "kubernetes" "k8s" => True "apple" "a2e" => False Solution This is the kind of implementation challenges easy to get wrong and/or forgot edge cases… class Solution: def validWordAbbreviation(self, word: str, abbr: str) -> bool: i = 0 tmp = "" if len(abbr) > 1 and abbr.isdecimal(): return False index = 0 while i < len(abbr): number = "" while i < len(abbr) and abbr[i].isdigit(): number += abbr[i] i += 1 if number: if number[0] == "0": return False if index + int(number) > len(word): return False tmp += word[index:index+ int(number)] index = len(tmp) elif i < len(abbr): tmp += abbr[i] i += 1 index = len(tmp) return tmp == word Time Complexity: O(n) Space Complexity: O(n) ...

September 9, 2021 · 1 min · Nolan

Linked list sort

Challenge Given a linked list, your task is to sort it in ascending order. Solution 1 - TLE Using a bubble sort approach. class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: not_sorted = True if not head: return while not_sorted: tmp = head not_sorted = False while tmp.next: if tmp.val > tmp.next.val: tmp.val, tmp.next.val = tmp.next.val, tmp.val not_sorted = True tmp = tmp.next return head Time Complexity: O(n^2) Solution 2 Using a merge sort approach sort approach. ...

September 1, 2021 · 2 min · Nolan

House Robber

Challenge The array nums represent the value inside each house. What is stopping you to rob everything is that you cannot rob two consecutive houses without triggering the alarm. Determine the maxium amout of money you can rob without triggering the alarm. Solution 1 - Recursion class Solution: def helper(self, index, nums, val): if index > len(nums)-1: self.m = max(self.m, val) return self.helper(index+1, nums, val) self.helper(index+2, nums, nums[index] + val) def rob(self, nums: List[int]) -> int: self.m = float("-inf") self.helper(0, nums, 0) return self.m Time Complexity: O(2^n) ...

August 23, 2021 · 1 min · Nolan

Minimum Deletion Cost to Avoid Repeating Letters

Challenge Given a String S and and an array representing the cost of each deletion. You goal is to minimize the cost needed to remove all consecutive repetive characters. Example 1: "aba" [2,3,4] => 0 Example 2: "abaa" [2,3,4,1] => 1 Solution 1 - Brute Force - TLE class Solution: def no_consecutive_letters(self, s): t = "" for e in s: if e !="#": t += e for i in range(1,len(t)): if t[i-1] == t[i]: return False return True def helper(self, s, current_cost, cost, index): if self.no_consecutive_letters(s): self.min_cost = min(current_cost, self.min_cost) return 0 if index > self.s_len: return 0 self.helper(s[:index] + "#" +s[index+1:] , current_cost + cost[index], cost,index+1) self.helper(s, current_cost, cost,index+1) return 0 def minCost(self, s: str, cost: List[int]) -> int: self.s_len = len(s)-1 self.min_cost = float("inf") self.helper(s, 0, cost, 0) return self.min_cost Solution 2 - Greedy class Solution: def remove_n_max(self, n, cost): c = sorted(cost) res = [] for i in range(0, n-1): res.append(c[i]) return sum(res) def minCost(self, s: str, cost: List[int]) -> int: total = 0 i = 0 while i < len(s): arr = [] current = 0 in_loop = False tmp = [] while i < len(s)-1 and s[i] == s[i+1]: arr.append(cost[i]) in_loop = True current +=1 tmp.append(s[i]) i += 1 if in_loop is True: arr.append(cost[i]) total += self.remove_n_max(current+1, arr) i += 1 return total

August 21, 2021 · 2 min · Nolan

Valid Move

Challenge You are given a board 8 x 8, a position(x,y) as well of a color. You task is to determine if this move is valid. A move is considered valid, if you have can have (vertically, horizontally or in digonal), starting from this position, a structure like so: color given then opposite N colors then color given. For example [“B”,“W”,“W”,“B”] or [“W”,“B”,“W”] is valid in any direction. This [“B”,“B”,“W”] or [“W”,"."] is invalid. ...

August 18, 2021 · 2 min · Nolan

Rod Cutting

Challenge Given a rod of length N. You are also given an array that represents the revenue of each cut size. You want to maximize revenue. E.g : [2,3,7,8], piece of length 1 gets you 2$. Solution Top down with Memoization: class Solution: def helper(self, n, cost): if n < 0: return 0 if n == 0: return cost if n in self.memo: return self.memo[n] res = 0 for i in range(1, len(self.cost)+1): res = max(res, self.helper(n-i, cost + self.cost[i])) self.memo[n] = res return self.memo[n] def rodCutting(self, n, cuts): self.res = 0 self.memo = {} cost = {} for i, e in enumerate(cuts): cost[i+1] = e self.cost = cost return self.helper(n, 0)

August 6, 2021 · 1 min · Nolan

Catalan Number

Challenge Your task is to print the Nth catalan number. catalan(5) = 42 Solution Bottom up def catalan(n): res = [0 for i in range(n+1)] res[0] = 1 s = 0 for i in range(1, n+1): for j in range(0, i): res[i] += res[j] * res[i-j-1] return res[n] Time Complexity: O(n^2) Top Down def catalan(n): if n == 0 or n ==1: return 1 s = 0 for i in range(n): s += catalan(i) * catalan(n-1-i) return s Time Complexity: O(n!) Application Find the number of unique BST.

August 5, 2021 · 1 min · Nolan

Partition List

Challenge Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. The order of the initial linked list must be preserved. Solution from copy import deepcopy class Solution: def add_to_list(self, head, node,x): node.next = None if head is None and node.val < x: self.left_part = node self.left_tail = node return elif head is None and node.val >= x: self.right_part = node self.right_tail = node return if head == self.left_part: self.left_tail.next = node self.left_tail = node if head == self.right_part: self.right_tail.next = node self.right_tail = node def partition(self, head: ListNode, x: int) -> ListNode: self.left_part = None self.right_part = None tmp = head while tmp: tmp_cpy = deepcopy(tmp) if tmp.val < x: self.add_to_list(self.left_part, tmp_cpy,x) else: self.add_to_list(self.right_part, tmp_cpy,x) tmp = tmp.next tmp = self.left_part if not tmp: return self.right_part self.left_tail.next = self.right_part return self.left_part Time complexity: O(n) Space complexity: O(1) ...

August 2, 2021 · 1 min · Nolan

Jump Game

Challenge Given an array of positive intege, each element represents the max length, you need to find the min number of jump in order to reach the end of the array. Input: nums = [2,4,1,1,17] Output: 2 # reach to index 1 and then from there last index. Solution - Recursion (TLE) class Solution: def helper(self, nums, current_index, steps, l, previous): # ending recursion early if already above if len(previous) >= self.m: return if current_index >=l-1: self.m = min(self.m, len(previous)) return for i in range(1, steps + 1): if current_index + i < l: self.helper(nums, current_index + i, nums[current_index + i],l, previous + [1]) def min_jump(self, nums: List[int]): if not nums: return 0 self.m = float('inf') previous = [] self.helper(nums, 0, nums[0], len(nums), previous) return self.m Solution 2 - Memoization class Solution: def helper(self, nums, current_index): if current_index >= len(nums)-1: return 0 if current_index in self.memo: return self.memo[current_index] steps = nums[current_index] for i in range(1, steps+1): self.m = min(self.m, 1 + self.helper(nums, current_index + i)) self.memo[current_index] = self.m return self.m def min_jump(self, nums: List[int]): if not nums: return 0 self.m = float('inf') self.memo = {} return self.helper(nums, 0)

August 1, 2021 · 1 min · Nolan