class Solution: def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode: def dfs(root: TreeNode) -> (TreeNode, int): if root is None: return root, 0 L = dfs(root.left) R = dfs(root.right) if L[1] > R[1]: return L[0], L[1] + 1 if R[1] > L[1]: return R[0], R[1] + 1 return root, L[1] + 1 return dfs(root)[0] root = TreeNode(3) root.left = TreeNode(5) root.left.left = TreeNode(6) root.left.right = TreeNode(2) root.left.right.left = TreeNode(7) root.left.right.right = TreeNode(4) root.right = TreeNode(1) root.right.left = TreeNode(0) root.right.right = TreeNode(8) tests = [(root, TreeNode(2, TreeNode(7), TreeNode(4)))] run_functional_tests(Solution().subtreeWithAllDeepest, tests)
""" class Solution: def hasPathSum(self, root: TreeNode, sum: int) -> bool: if root is None: return False if root.left is None and root.right is None: return sum == root.val if self.hasPathSum(root.left, sum - root.val): return True return self.hasPathSum(root.right, sum - root.val) t1 = TreeNode(5) t1.left = TreeNode(4) t1.right = TreeNode(8) t1.left.left = TreeNode(11) t1.left.left.left = TreeNode(7) t1.left.left.right = TreeNode(2) t1.right.left = TreeNode(13) t1.right.right = TreeNode(4) t1.right.right.right = TreeNode(1) tests = [ (t1, 22, True) ] run_functional_tests(Solution().hasPathSum, tests)
from Common.ObjectTestingUtils import run_functional_tests # Runtime: 3688 ms, faster than 44.27% of Python3 online submissions for Ones and Zeroes. # Memory Usage: 14.3 MB, less than 95.49% of Python3 online submissions for Ones and Zeroes. class Solution: def findMaxForm(self, strs: List[str], m: int, n: int) -> int: c = len(strs) dp = [[0] * (n + 1) for _ in range(m + 1)] def count(si: str) -> List[int]: res = [0, 0] for t in si: res[ord(t) - ord('0')] += 1 return res for si in strs: ci = count(si) for i in range(m, ci[0] - 1, -1): for j in range(n, ci[1] - 1, -1): dp[i][j] = max(dp[i][j], dp[i - ci[0]][j - ci[1]] + 1) return dp[m][n] tests = [(["10", "0001", "111001", "1", "0"], 5, 3, 4), (["10", "0", "1"], 1, 1, 2)] run_functional_tests(Solution().findMaxForm, tests)
prev, first, second = None, None, None def inorder(node: TreeNode): nonlocal prev, first, second if node.left: inorder(node.left) if not first and (not prev or node.val < prev.val): first = prev if first and (not prev or node.val < prev.val): second = node prev = node if node.right: inorder(node.right) inorder(root) first.val, second.val = second.val, first.val tests = [[ TreeNode(1, TreeNode(3, null, TreeNode(2))), TreeNode(3, TreeNode(1, null, TreeNode(2))) ], [ TreeNode(3, TreeNode(1), TreeNode(4, TreeNode(2))), TreeNode(2, TreeNode(1), TreeNode(4, TreeNode(3))) ]] run_functional_tests(in_place_to_function(Solution().recoverTree), tests)
Memory Usage: 14.8 MB, less than 56.27% of Python3 online submissions for Burst Balloons. """ from typing import List from Common.ObjectTestingUtils import run_functional_tests class Solution: def maxCoins(self, nums: List[int]) -> int: A = [1] + nums + [1] n = len(A) dp: List[List[int]] = [[0] * n for i in range(n)] for l in range(n+1): for i in range(n-l): mx = 0 j = i + l for k in range(i+1, j): v = A[i] * A[k] * A[j] + dp[i][k] + dp[k][j] mx = max(mx, v) dp[i][j] = mx return dp[0][n-1] tests = [ ([3,1,5,8], 167) ] run_functional_tests(Solution().maxCoins, tests)
path[i] is either 'N', 'S', 'E', or 'W'. """ from Common.ObjectTestingUtils import run_functional_tests # Runtime: 60 ms, faster than 5.75% of Python3 online submissions for Path Crossing. # Memory Usage: 14.2 MB, less than 93.66% of Python3 online submissions for Path Crossing. class Solution: def isPathCrossing(self, path: str) -> bool: visited = set() x, y = 0, 0 visited.add((x, y)) for p in path: if p == 'N': y -= 1 elif p == 'S': y += 1 elif p == 'E': x += 1 elif p == 'W': x -= 1 if (x, y) in visited: return True visited.add((x, y)) return False tests = [["NESWW", True]] run_functional_tests(Solution().isPathCrossing, tests)
# Memory Usage: 16.1 MB, less than 63.08% of Python3 online submissions for N-ary Tree Preorder Traversal. class Solution: def preorder(self, root: 'Node') -> List[int]: result = [] st = [] if root: st.append(root) while st: node = st.pop() result.append(node.val) if node.children: for child in node.children[::-1]: st.append(child) return result tests = [[ Node(1, [Node(3, [Node(5), Node(6)]), Node(2), Node(4)]), [1, 3, 5, 6, 2, 4] ], [ Node(1, [ Node(2), Node(3, [Node(6), Node(7, [Node(11, [Node(14)])])]), Node(4, [Node(8, [Node(12)])]), Node(5, [Node(9, [Node(13)]), Node(10)]) ]), [1, 2, 3, 6, 7, 11, 14, 4, 8, 12, 5, 9, 13, 10] ]] run_functional_tests(Solution().preorder, tests)
1 <= c <= 100 a != b, b != c, c != a """ from typing import List # Runtime: 28 ms, faster than 83.08% of Python3 online submissions for Moving Stones Until Consecutive. # Memory Usage: 14.1 MB, less than 94.03% of Python3 online submissions for Moving Stones Until Consecutive. from Common.ObjectTestingUtils import run_functional_tests class Solution: def numMovesStones(self, a: int, b: int, c: int) -> List[int]: a, b, c = sorted([a, b, c]) # print(a, b, c) mn = 2 if b - a == 1 and c - b == 1: mn = 0 elif b - a <= 2 or c - b <= 2: mn = 1 # mx = c - b - 1 + b - a - 1 mx = c - a - 2 return [mn, mx] tests = [(1, 2, 5, [1, 2]), (4, 3, 2, [0, 0]), (3, 5, 1, [1, 2])] run_functional_tests(Solution().numMovesStones, tests)
# class Solution: # def minCostClimbingStairs(self, cost: List[int]) -> int: # n = len(cost) # cost += [0] # dp = [0] * (n+1) # dp[0], dp[1] = cost[0], cost[1] # for i in range(2, n+1): # dp[i] = cost[i] + min(dp[i-1], dp[i-2]) # return dp[n] # Runtime: 92 ms, faster than 5.57% of Python3 online submissions for Min Cost Climbing Stairs. # Memory Usage: 14.4 MB, less than 44.78% of Python3 online submissions for Min Cost Climbing Stairs. class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: n = len(cost) cost += [0] dp0, dp1, dp2 = cost[0], cost[1], 0 for i in range(2, n+1): dp2 = cost[i] + min(dp0, dp1) dp0, dp1 = dp1, dp2 return dp2 tests = [ [[10,15,20], 15], [[1,100,1,1,1,100,1,1,100,1], 6] ] run_functional_tests(Solution().minCostClimbingStairs, tests)
# return "".join('*' if c in 'aeiou' else c for c in w) # # words_base = set(wordlist) # words1 = {} # words2 = {} # # for w in wordlist: # wl = w.lower() # words1.setdefault(wl, w) # words2.setdefault(devowel(wl), w) # # def solve(q): # if q in words_base: # return q # ql = q.lower() # if ql in words1: # return words1[ql] # qlv = devowel(ql) # if qlv in words2: # return words2[qlv] # return "" # # return map(solve, queries) tests = [(["KiTe", "kite", "hare", "Hare"], [ "kite", "Kite", "KiTe", "Hare", "HARE", "Hear", "hear", "keti", "keet", "keto" ], ["kite", "KiTe", "KiTe", "Hare", "hare", "", "", "KiTe", "", "KiTe"])] run_functional_tests(Solution().spellchecker, tests)
# for i in range(1, n): # for j in range(i): # if envelopes[j][0] < envelopes[i][0] and envelopes[j][1] < envelopes[i][1]: # dp[i] = max(dp[i], dp[j] + 1) # result = max(result, dp[i]) # return result # Runtime: 148 ms, faster than 82.41% of Python3 online submissions for Russian Doll Envelopes. # Memory Usage: 16.5 MB, less than 57.77% of Python3 online submissions for Russian Doll Envelopes. class Solution: def maxEnvelopes(self, envelopes: List[List[int]]) -> int: n = len(envelopes) envelopes.sort(key=lambda x: (x[0], -x[1])) dp = [] for (w, h) in envelopes: l = bisect_left(dp, h) if l == len(dp): dp.append(h) else: dp[l] = h return len(dp) tests = [([[8, 3], [3, 20], [15, 5], [11, 2], [19, 6], [9, 18], [1, 19], [13, 3], [14, 20], [6, 7]], 4), ([[5, 4], [6, 4], [6, 7], [2, 3]], 3), ([[1, 1], [1, 1], [1, 1]], 1)] run_functional_tests(Solution().maxEnvelopes, tests)
return 0 dl = dr = 0 if root.left: dl = self.minDepth(root.left) if root.right: dr = self.minDepth(root.right) if dl > 0 and dr > 0: return 1 + min(dl, dr) if dl > 0: return dl + 1 return dr + 1 tree1 = TreeNode(3) tree1.left = TreeNode(9) tree1.right = TreeNode(20) tree1.right.left = TreeNode(15) tree1.right.right = TreeNode(7) tree2 = TreeNode(1) tree2.left = TreeNode(2) tests = [(tree1, 2), (tree2, 2)] run_functional_tests(Solution().minDepth, tests)
def get_order(order: str) -> Dict[str, int]: result = {} for i, c in enumerate(order): result[c] = i return result def is_less(s1: str, s2: str, ordd: Dict[str, int]) -> bool: n1 = len(s1) n2 = len(s2) n = min(n1, n2) for i in range(n): if ordd.get(s1[i]) > ordd.get(s2[i]): return False if ordd.get(s1[i]) < ordd.get(s2[i]): return True return n1 <= n2 ordd = get_order(order) n = len(words) for i in range(1, n): if not is_less(words[i - 1], words[i], ordd): return False return True tests = [(["hello", "leetcode"], "hlabcdefgijkmnopqrstuvwxyz", True), (["word", "world", "row"], "worldabcefghijkmnpqstuvxyz", False)] run_functional_tests(Solution().isAlienSorted, tests)
# Runtime: 68 ms, faster than 48.89% of Python3 online submissions for Evaluate Reverse Polish Notation. # Memory Usage: 14.3 MB, less than 96.45% of Python3 online submissions for Evaluate Reverse Polish Notation. class Solution: def evalRPN(self, tokens: List[str]) -> int: st = [] for token in tokens: if token in ['+', '-', '*', '/']: v2 = st.pop() v1 = st.pop() if token == '+': st.append(v1 + v2) elif token == '-': st.append(v1 - v2) elif token == '*': st.append(v1 * v2) elif token == '/': st.append(int(v1 / v2)) else: st.append(int(token)) return st[0] if st else 0 tests = [ # [["2","1","+","3","*"], 9], # [["4","13","5","/","+"], 6], [["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"], 22] ] run_functional_tests(Solution().evalRPN, tests)
A_used[i] = True j += 1 for i in range(n): if A_used[i]: continue result[Bt[j][1]] = A[i] A_used[i] = True j += 1 return result def checkAdvantage(A: List[int], B: List[int]): return sum([1 if ai > bi else 0 for (ai, bi) in zip(A, B)]) def customCheck(test, result) -> bool: B = test[1] expected = test[2] return checkAdvantage(expected, B) == checkAdvantage(result, B) tests = [([2, 0, 4, 1, 2], [1, 3, 0, 0, 2], [2, 0, 2, 1, 4]), ([2, 7, 11, 15], [1, 10, 4, 11], [2, 11, 7, 15]), ([12, 24, 8, 32], [13, 25, 32, 11], [24, 32, 8, 12])] run_functional_tests(Solution().advantageCount, tests, custom_check=customCheck)
# min_cost_i = min(min_cost_i, prevLevel[i]) # current_level[i] = triangle[level][i] + min_cost_i # min_cost = min(current_level[i], min_cost) # prevLevel = current_level # return min_cost # Runtime: 52 ms, faster than 94.36% of Python3 online submissions for Triangle. # Memory Usage: 15.2 MB, less than 26.73% of Python3 online submissions for Triangle class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: n_levels = len(triangle) for level in range(n_levels-2, -1, -1): for i in range(level+1): best_below = min(triangle[level+1][i], triangle[level+1][i+1]) triangle[level][i] += best_below return triangle[0][0] tests = [ [ [[2],[3,4],[6,5,7],[4,1,8,3]], 11 ], [ [[-10]], -10 ] ] run_functional_tests(Solution().minimumTotal, tests)
0 <= indices[i] < n All values of indices are unique (i.e. indices is a permutation of the integers from 0 to n - 1). """ from typing import List from Common.ObjectTestingUtils import run_functional_tests # Runtime: 64 ms, faster than 12.45% of Python3 online submissions for Shuffle String. # Memory Usage: 14.4 MB, less than 18.54% of Python3 online submissions for Shuffle String. # class Solution: # def restoreString(self, s: str, indices: List[int]) -> str: # return "".join(c for i, c in sorted([i, c] for i, c in zip(indices, s))) # Runtime: 96 ms, faster than 5.05% of Python3 online submissions for Shuffle String. # Memory Usage: 14.1 MB, less than 92.21% of Python3 online submissions for Shuffle String. class Solution: def restoreString(self, s: str, indices: List[int]) -> str: result = [' '] * len(s) for i in indices: result[indices[i]] = s[i] return "".join(result) tests = [["codeleet", [4, 5, 6, 7, 0, 2, 1, 3], "leetcode"], ["abc", [0, 1, 2], "abc"], ["aiohn", [3, 1, 4, 2, 0], "nihao"], ["aaiougrt", [4, 0, 2, 6, 7, 3, 1, 5], "arigatou"], ["art", [1, 0, 2], "rat"]] run_functional_tests(Solution().restoreString, tests)
def averageOfLevels(self, root: TreeNode) -> List[float]: levels = [] def walkLevels(root: TreeNode, level: int): if not root: return nonlocal levels if len(levels) <= level: levels.append([root.val, 1]) else: levels[level][0] += root.val levels[level][1] += 1 walkLevels(root.left, level + 1) walkLevels(root.right, level + 1) walkLevels(root, 0) return [s / c for s, c in levels] root1 = TreeNode(3) root1.left = TreeNode(9) root1.right = TreeNode(20) root1.right.left = TreeNode(15) root1.right.right = TreeNode(7) tests = [(root1, [3, 14.5, 11])] run_functional_tests(Solution().averageOfLevels, tests)
Output: [1, 2, 3] Explanation: The [1, 2, 3] has three different positive integers ranging from 1 to 3, and the [1, 1] has exactly 1 distinct integer: 1. Example 2: Input: n = 3, k = 2 Output: [1, 3, 2] Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3, and the [2, 1] has exactly 2 distinct integers: 1 and 2. Note: The n and k are in the range 1 <= k < n <= 104. """ from typing import List from Common.ObjectTestingUtils import run_functional_tests # Runtime: 48 ms, faster than 60.67% of Python3 online submissions for Beautiful Arrangement II. # Memory Usage: 15.2 MB, less than 51.33% of Python3 online submissions for Beautiful Arrangement II. class Solution: def constructArray(self, n: int, k: int) -> List[int]: result = list(range(1, n - k)) for i in range(k + 1): if i % 2 == 0: result.append(n - k + i // 2) else: result.append(n - i // 2) return result tests = [(3, 1, [1, 2, 3]), (3, 2, [1, 3, 2]), (6, 3, [1, 2, 3, 6, 4, 5])] run_functional_tests(Solution().constructArray, tests)
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: n = len(nums) if n < 2: return n prevdiff = nums[1] - nums[0] result = 1 if prevdiff == 0 else 2 for i in range(2, n): diff = nums[i] - nums[i-1] if diff > 0 and prevdiff <= 0 or diff < 0 and prevdiff >= 0: result += 1 prevdiff = diff return result tests = [ ([3,3,3,2,5], 3), ([1, 4, 5, 7, 5, 5, 7, 2, 3], 6), ([0, 0], 1), ([0,0,0], 1), ([1,7,4,9,2,5], 6), ([1,17,5,10,13,15,10,5,16,8], 7), ([1,2,3,4,5,6,7,8,9], 2) ] run_functional_tests(Solution().wiggleMaxLength, tests)
for j in range(i+1, n): p = nums[i] * nums[j] products[p] = products.get(p, 0) + 1 cnt = 0 for k in products.keys(): v = products[k] cnt += 4 * v * (v - 1) return cnt tests = [ [ [2,3,4,6], 8 ], [ [1,2,4,5,10], 16 ], [ [2,3,4,6,8,12], 40 ], [ [2,3,5,7], 0 ] ] run_functional_tests(Solution().tupleSameProduct, tests)
# dic = defaultdict(lambda: set()) # for i in range(n): # for c in words[i]: # dic[c].add(i) # for i in range(n): # for j in range(i+1, n): # if not any(j in dic[c] for c in words[i]): # max_p = max(max_p, len(words[i]) * len(words[j])) # return max_p # Runtime: 488 ms, faster than 67.49% of Python3 online submissions for Maximum Product of Word Lengths. # Memory Usage: 14.4 MB, less than 96.88% of Python3 online submissions for Maximum Product of Word Lengths. class Solution: def maxProduct(self, words: List[str]) -> int: res, dic = 0, defaultdict(int) for w in words: for c in w: dic[w] |= 1 << (ord(c) - ord('a')) for w1, w2 in combinations(dic.keys(), 2): if dic[w1] & dic[w2] == 0: res = max(res, len(w1) * len(w2)) return res tests = [[["abcw", "baz", "foo", "bar", "xtfn", "abcdef"], 16], [["a", "ab", "abc", "d", "cd", "bcd", "abcd"], 4], [["a", "aa", "aaa", "aaaa"], 0]] run_functional_tests(Solution().maxProduct, tests)
# Runtime: 664 ms, faster than 97.10% of Python3 online submissions for Course Schedule III. # Memory Usage: 19.4 MB, less than 50.65% of Python3 online submissions for Course Schedule III. class Solution: def scheduleCourse(self, courses: List[List[int]]) -> int: courses.sort(key=lambda x: x[1]) n = len(courses) time, count = 0, 0 prev_courses = [] for i in range(n): duration, end = courses[i] if time + duration <= end: time += duration count += 1 heapq.heappush(prev_courses, -duration) else: if prev_courses and -prev_courses[0] > duration: prev_duration = -heapq.heappop(prev_courses) time += duration - prev_duration heapq.heappush(prev_courses, -duration) return count tests = [[[[1, 2], [2, 3]], 2], [[[100, 200], [200, 1300], [1000, 1250], [2000, 3200]], 3], [[[1, 2]], 1], [[[3, 2], [4, 3]], 0]] run_functional_tests(Solution().scheduleCourse, tests)
# tvisit[curr] = fup[curr] = self.timer # for child in graph[curr]: # if child == par: # continue # if marked[child]: # fup[curr] = min(fup[curr], tvisit[child]) # else: # dfs(child, curr) # fup[curr] = min(fup[curr], fup[child]) # if fup[child] > tvisit[curr]: # result.append([curr, child]) # # for i, j in connections: # graph[i].append(j) # graph[j].append(i) # # for i in range(n): # if not marked[i]: # dfs(i) # # return result tests = [ [4, [[0,1],[1,2],[2,0],[1,3]], [[1,3]]] ] run_functional_tests(Solution().criticalConnections, tests)
def letterCombinations(self, digits: str) -> List[str]: if not digits: return [] tr = { "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz" } result = [""] for d in digits: current = result result = [] for s in current: for dd in tr.get(d): result.append(s + dd) return result tests = [ ("23", ["ad","ae","af","bd","be","bf","cd","ce","cf"]), ("", []), ("2", ["a","b","c"]) ] run_functional_tests(Solution().letterCombinations, tests)
Note: 1 <= rooms.length <= 1000 0 <= rooms[i].length <= 1000 The number of keys in all rooms combined is at most 3000. """ from typing import List from Common.ObjectTestingUtils import run_functional_tests # Runtime: 68 ms, faster than 52.75% of Python3 online submissions for Keys and Rooms. # Memory Usage: 15 MB, less than 38.28% of Python3 online submissions for Keys and Rooms. class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: n = len(rooms) visited = set() toVisit = [0] while toVisit: i = toVisit.pop() visited.add(i) for j in rooms[i]: if j not in visited: toVisit.append(j) return len(visited) == n tests = [([[1], [2], [3], []], True), ([[1, 3], [3, 0, 1], [2], [0]], False)] run_functional_tests(Solution().canVisitAllRooms, tests)
2 <= s.length <= 500 The string s consists of characters '0' and '1' only. """ from Common.ObjectTestingUtils import run_functional_tests # Runtime: 32 ms, faster than 82.95% of Python3 online submissions for Maximum Score After Splitting a String. # Memory Usage: 14.1 MB, less than 73.40% of Python3 online submissions for Maximum Score After Splitting a String. class Solution: def maxScore(self, s: str) -> int: max_score = 0 s0 = 0 s1 = sum(1 for c in s if c == '1') n = len(s) for i in range(n-1): if s[i] == '0': s0 += 1 else: s1 -= 1 max_score = max(max_score, s0 + s1) return max_score tests = [ ["011101", 5], ["00111", 5], ["1111", 3] ] run_functional_tests(Solution().maxScore, tests)
if str.isdigit(s[i]): current = 10 * current + (ord(s[i]) - ord('0')) if i == n-1 or not str.isdigit(s[i]) and not str.isspace(s[i]): op = s[i] if operation == '-': result += last last = -current elif operation == '+': result += last last = current elif operation == '*': last = last * current else: last = int(last / current) operation = op current = 0 i += 1 result += last return result tests = [ ("14-3/2", 13), ("3+2*2", 7), (" 3/2 ", 1), (" 3+5 / 2 ", 5) ] run_functional_tests(Solution().calculate, tests)
# # for x in numbers: # for y in [x-1, x+1]: # if y in numbers: # union(find_set(numbers[x]), find_set(numbers[y])) # # return max(w) # Runtime: 180 ms, faster than 41.47% of Python3 online submissions for Longest Consecutive Sequence. # Memory Usage: 25.7 MB, less than 24.14% of Python3 online submissions for Longest Consecutive Sequence. class Solution: def longestConsecutive(self, nums: List[int]) -> int: result = 0 numbers = set(nums) for x in numbers: if x - 1 not in numbers: current = x current_streak = 1 while current + 1 in numbers: current += 1 current_streak += 1 result = max(result, current_streak) return result tests = [[[1, 3, 5, 2, 4], 5], [[], 0], [[100, 4, 200, 1, 3, 2], 4], [[0, 3, 7, 2, 5, 8, 4, 6, 0, 1], 9]] run_functional_tests(Solution().longestConsecutive, tests)
from Common.ObjectTestingUtils import run_functional_tests # Runtime: 244 ms, faster than 49.40% of Python3 online submissions for Palindromic Substrings. # Memory Usage: 21.8 MB, less than 39.18% of Python3 online submissions for Palindromic Substrings. class Solution: def countSubstrings(self, s: str) -> int: cnt = 0 n = len(s) dp = [[False] * n for _ in range(n)] for i in range(n): dp[i][i] = True cnt += 1 if i > 0 and s[i - 1] == s[i]: dp[i - 1][i] = True cnt += 1 for l in range(3, n + 1): for i in range(0, n - l + 1): j = i + l - 1 if s[i] == s[j] and dp[i + 1][j - 1]: dp[i][j] = True cnt += 1 return cnt tests = [("abc", 3), ("aaa", 6)] run_functional_tests(Solution().countSubstrings, tests)