Longest Increasing Subsequence

Challenge You are given an integer array called nums, your task is to return the longest increasing subsequence. E.g [0,1,2,7] is the longest subsequence of the array [0,3,1,6,2,2,7] Solution 1 - Recursion class Solution: def first_solution(self, nums, index, prev, ct): if index > len(nums): self.m = max(self.m, ct) return self.first_solution(nums, index + 1, prev, ct) if index < len(nums) and nums[index] > prev: self.first_solution(nums, index + 1, nums[index], ct + 1) return ct def lengthOfLIS(self, nums: List[int]) -> int: self.m = 0 self.first_solution(tuple(nums), 0, float("-inf"), 0) return self.m Time complexity: O(n^2) ...

October 1, 2021 · 2 min · Nolan

Recover BST

Challenge You are given the root of a binary search tree, where exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. 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 in_order_traversal(self, root): if root is None: return self.in_order_traversal(root.left) self.arr.append([root.val, root]) self.in_order_traversal(root.right) def recoverTree(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ self.arr = [] self.in_order_traversal(root) i = 0 to_move = [] orderone = sorted([e[0] for e in self.arr]) while i < len(self.arr): if self.arr[i][0] != orderone[i]: to_move.append(self.arr[i]) i += 1 if len(to_move)>1: if to_move[0] > to_move[1]: to_move[0][1].val, to_move[1][1].val = to_move[1][1].val, to_move[0][1].val return Time complexity: O(n) Space complexity: O(n) ...

September 24, 2021 · 1 min · Nolan

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

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: " [ = a 2 > b , a 3 1 a , " 4 , 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