├── .gitignore ├── 370986912.flag ├── README.md ├── add-binary.py ├── add-digits.py ├── add-two-numbers.py ├── balanced-binary-tree.py ├── best-time-to-buy-and-sell-stock.py ├── binary-search-tree-iterator.py ├── binary-tree-inorder-traversal.py ├── binary-tree-level-order-traversal-ii.py ├── binary-tree-level-order-traversal.py ├── binary-tree-paths.py ├── binary-tree-zigzag-level-order-traversal.py ├── bulls-and-cows.py ├── climbing-stairs.py ├── construct-binary-tree-from-inorder-and-postorder-traversal.py ├── construct-binary-tree-from-preorder-and-inorder-traversal.py ├── contains-duplicate-ii.py ├── contains-duplicate.py ├── convert-sorted-array-to-binary-search-tree.py ├── convert-sorted-list-to-binary-search-tree.py ├── copy-list-with-random-pointer.py ├── copy-list-with-random-pointer_1.py ├── count-and-say.py ├── count-primes.py ├── delete-node-in-a-linked-list.py ├── downloader.py ├── find-peak-element.py ├── first-bad-version.py ├── generate-parentheses.py ├── happy-number.py ├── implement-queue-using-stacks.py ├── implement-stack-using-queues.py ├── implement-strstr.py ├── intersection-of-two-arrays-ii.py ├── intersection-of-two-arrays.py ├── invert-binary-tree.py ├── isomorphic-strings.py ├── isomorphic-strings_1.py ├── jewels-and-stones.py ├── length-of-last-word.py ├── linked-list-cycle.py ├── longest-common-prefix.py ├── lowest-common-ancestor-of-a-binary-search-tree.py ├── majority-element.py ├── maximum-depth-of-binary-tree.py ├── maximum-subarray.py ├── merge-sorted-array.py ├── merge-two-sorted-lists.py ├── min-stack.py ├── missing-number.py ├── missing-number_1.py ├── missing-number_2.py ├── move-zeroes.py ├── nim-game.py ├── number-of-1-bits.py ├── palindrome-number.py ├── pascals-triangle.py ├── path-sum-ii.py ├── path-sum.py ├── plus-one.py ├── power-of-four.py ├── power-of-three.py ├── power-of-two.py ├── power-of-two_1.py ├── range-sum-query-immutable.py ├── remove-duplicates-from-sorted-array.py ├── remove-duplicates-from-sorted-list.py ├── remove-element.py ├── remove-linked-list-elements.py ├── reorder-list.py ├── repeated-dna-sequences.py ├── restore-ip-addresses.py ├── reverse-bits.py ├── reverse-integer.py ├── reverse-linked-list-ii.py ├── reverse-linked-list.py ├── reverse-string.py ├── reverse-string_1.py ├── reverse-vowels-of-a-string.py ├── reverse-words-in-a-string.py ├── rotate-array.py ├── same-tree.py ├── search-insert-position.py ├── single-number-ii.py ├── sort-list.py ├── sqrtx.py ├── sum-of-two-integers.py ├── sum-root-to-leaf-numbers.py ├── symmetric-tree.py ├── symmetric-tree_1.py ├── two-sum-ii-input-array-is-sorted.py ├── two-sum.py ├── ugly-number.py ├── unique-binary-search-trees.py ├── unique-binary-search-trees_1.py ├── valid-parentheses.py ├── valid-parentheses_1.py ├── valid-perfect-square.py ├── valid-perfect-square_1.py ├── word-ladder.py └── word-pattern.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | Pipfile 3 | Pipfile.lock 4 | .DS_Store 5 | downloader_dev.py 6 | -------------------------------------------------------------------------------- /370986912.flag: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingname/LeetCode/b07f3ba0f63f85378e7436dfd381dd263beaacc4/370986912.flag -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | 3 | My Code for problems in LeetCode. 4 | 5 | This is the first try for me to solve these problem, so the code may be stupid and long. 6 | 7 | You can download your submissions by change and run `downloader.py`. This script will login 8 | to your LeetCode account and download all accepted submission. 9 | For the same problem which submitted for times, the file will be named `xxx.py`, `xxx_1.py`, `xxx_2.py` and etc. 10 | 11 | -------------------------------------------------------------------------------- /add-binary.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132357011/ 3 | 4 | 5 | Given two binary strings, return their sum (also a binary string). 6 | 7 | 8 | 9 | For example, 10 | a = "11" 11 | b = "1" 12 | Return "100". 13 | """ 14 | 15 | 16 | class Solution(object): 17 | def addBinary(self, a, b): 18 | """ 19 | :type a: str 20 | :type b: str 21 | :rtype: str 22 | """ 23 | a_int = int(a, 2) 24 | b_int = int(b, 2) 25 | result = a_int + b_int 26 | return '{0:b}'.format(result) 27 | -------------------------------------------------------------------------------- /add-digits.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149194316/ 3 | 4 | 5 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 6 | 7 | 8 | 9 | For example: 10 | 11 | 12 | Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 13 | 14 | 15 | Follow up: 16 | Could you do it without any loop/recursion in O(1) runtime? 17 | 18 | 19 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.""" 20 | 21 | 22 | class Solution: 23 | def addDigits(self, num): 24 | """ 25 | :type num: int 26 | :rtype: int 27 | """ 28 | if 0 <= num <= 9: 29 | return num 30 | new_num = 0 31 | for n in str(num): 32 | new_num += int(n) 33 | return self.addDigits(new_num) 34 | -------------------------------------------------------------------------------- /add-two-numbers.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132378077/ 3 | 4 | You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 5 | 6 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 7 | 8 | 9 | Example 10 | 11 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 12 | Output: 7 -> 0 -> 8 13 | Explanation: 342 + 465 = 807. 14 | 15 | """ 16 | 17 | 18 | # Definition for singly-linked list. 19 | # class ListNode(object): 20 | # def __init__(self, x): 21 | # self.val = x 22 | # self.next = None 23 | 24 | class Solution(object): 25 | def addTwoNumbers(self, l1, l2): 26 | """ 27 | :type l1: ListNode 28 | :type l2: ListNode 29 | :rtype: ListNode 30 | """ 31 | shift = 0 32 | result = ListNode(0) 33 | origin_result = result 34 | while l1 or l2: 35 | v1_value = l1.val if l1 else 0 36 | v2_value = l2.val if l2 else 0 37 | 38 | result.val += v1_value + v2_value 39 | if result.val >= 10: 40 | result.val = result.val - 10 41 | shift = 1 42 | l1 = l1.next if l1 else None 43 | l2 = l2.next if l2 else None 44 | if not l1 and not l2 and not shift: 45 | break 46 | result.next = ListNode(shift) 47 | result = result.next 48 | shift = 0 49 | 50 | return origin_result 51 | 52 | -------------------------------------------------------------------------------- /balanced-binary-tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147673610/ 3 | 4 | Given a binary tree, determine if it is height-balanced. 5 | 6 | For this problem, a height-balanced binary tree is defined as: 7 | 8 | 9 | a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 10 | 11 | 12 | Example 1: 13 | 14 | Given the following tree [3,9,20,null,null,15,7]: 15 | 16 | 17 | 3 18 | / \ 19 | 9 20 20 | / \ 21 | 15 7 22 | 23 | Return true. 24 | 25 | Example 2: 26 | 27 | Given the following tree [1,2,2,3,3,null,null,4,4]: 28 | 29 | 30 | 1 31 | / \ 32 | 2 2 33 | / \ 34 | 3 3 35 | / \ 36 | 4 4 37 | 38 | 39 | Return false. 40 | """ 41 | 42 | 43 | # Definition for a binary tree node. 44 | # class TreeNode: 45 | # def __init__(self, x): 46 | # self.val = x 47 | # self.left = None 48 | # self.right = None 49 | 50 | class Solution: 51 | def isBalanced(self, root): 52 | """ 53 | :type root: TreeNode 54 | :rtype: bool 55 | """ 56 | def walk(node): 57 | if not node: 58 | return 0 59 | left = walk(node.left) 60 | right = walk(node.right) 61 | if left == -1 or right == -1 or abs(left - right) > 1: 62 | return -1 63 | return 1 + max(left, right) 64 | 65 | return walk(root) != -1 66 | -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147477031/ 3 | 4 | Say you have an array for which the ith element is the price of a given stock on day i. 5 | 6 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 7 | 8 | Example 1: 9 | 10 | Input: [7, 1, 5, 3, 6, 4] 11 | Output: 5 12 | 13 | max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 14 | 15 | 16 | 17 | Example 2: 18 | 19 | Input: [7, 6, 4, 3, 1] 20 | Output: 0 21 | 22 | In this case, no transaction is done, i.e. max profit = 0. 23 | 24 | """ 25 | 26 | 27 | class Solution: 28 | def maxProfit(self, prices): 29 | """ 30 | :type prices: List[int] 31 | :rtype: int 32 | """ 33 | if not prices: 34 | return 0 35 | 36 | point = prices[0] 37 | max_price = 0 38 | for price in prices[1:]: 39 | if price < point: 40 | point = price 41 | elif price > point: 42 | difference = price - point 43 | if difference > max_price: 44 | max_price = difference 45 | return max_price 46 | -------------------------------------------------------------------------------- /binary-search-tree-iterator.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/370986912/ 3 | 4 | Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. 5 | 6 | Calling next() will return the next smallest number in the BST. 7 | 8 |   9 | 10 | 11 | 12 | 13 | Example: 14 | 15 | 16 | 17 | 18 | BSTIterator iterator = new BSTIterator(root); 19 | iterator.next(); // return 3 20 | iterator.next(); // return 7 21 | iterator.hasNext(); // return true 22 | iterator.next(); // return 9 23 | iterator.hasNext(); // return true 24 | iterator.next(); // return 15 25 | iterator.hasNext(); // return true 26 | iterator.next(); // return 20 27 | iterator.hasNext(); // return false 28 | 29 | 30 |   31 | 32 | Note: 33 | 34 | 35 | next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. 36 | You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called. 37 | 38 | """ 39 | 40 | 41 | # Definition for a binary tree node. 42 | # class TreeNode: 43 | # def __init__(self, val=0, left=None, right=None): 44 | # self.val = val 45 | # self.left = left 46 | # self.right = right 47 | class BSTIterator: 48 | 49 | def __init__(self, root: TreeNode): 50 | from collections import deque 51 | self.root = root 52 | self.stop = False 53 | self.iterator = self.do_iter(self.root) 54 | self.next_val = deque() 55 | 56 | def next(self) -> int: 57 | """ 58 | @return the next smallest number 59 | """ 60 | if self.next_val: 61 | return self.next_val.popleft() 62 | 63 | return self.try_to_get_next_val() 64 | 65 | def do_iter(self, node): 66 | if not node: 67 | return 68 | if node.left: 69 | yield from self.do_iter(node.left) 70 | yield node.val 71 | if node.right: 72 | yield from self.do_iter(node.right) 73 | 74 | 75 | def hasNext(self) -> bool: 76 | """ 77 | @return whether we have a next smallest number 78 | """ 79 | next_val = self.try_to_get_next_val() 80 | if next_val is not None: 81 | self.next_val.append(next_val) 82 | return True 83 | else: 84 | return False 85 | 86 | def try_to_get_next_val(self): 87 | try: 88 | value = next(self.iterator) 89 | return value 90 | except StopIteration: 91 | return None 92 | 93 | 94 | 95 | # Your BSTIterator object will be instantiated and called as such: 96 | # obj = BSTIterator(root) 97 | # param_1 = obj.next() 98 | # param_2 = obj.hasNext() -------------------------------------------------------------------------------- /binary-tree-inorder-traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149679020/ 3 | 4 | Given a binary tree, return the inorder traversal of its nodes' values. 5 | 6 | 7 | For example: 8 | Given binary tree [1,null,2,3], 9 | 10 | 1 11 | \ 12 | 2 13 | / 14 | 3 15 | 16 | 17 | 18 | return [1,3,2]. 19 | 20 | 21 | Note: Recursive solution is trivial, could you do it iteratively?""" 22 | 23 | 24 | # Definition for a binary tree node. 25 | # class TreeNode: 26 | # def __init__(self, x): 27 | # self.val = x 28 | # self.left = None 29 | # self.right = None 30 | 31 | class Solution: 32 | def inorderTraversal(self, root): 33 | """ 34 | :type root: TreeNode 35 | :rtype: List[int] 36 | """ 37 | if not root: 38 | return [] 39 | 40 | result = [] 41 | self.walk(root, result) 42 | return result 43 | 44 | def walk(self, node, result): 45 | left = node.left 46 | right = node.right 47 | if not left and not right: 48 | result.append(node.val) 49 | return 50 | 51 | if left: 52 | self.walk(left, result) 53 | result.append(node.val) 54 | if right: 55 | self.walk(right, result) 56 | 57 | -------------------------------------------------------------------------------- /binary-tree-level-order-traversal-ii.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147517696/ 3 | 4 | Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 5 | 6 | 7 | For example: 8 | Given binary tree [3,9,20,null,null,15,7], 9 | 10 | 3 11 | / \ 12 | 9 20 13 | / \ 14 | 15 7 15 | 16 | 17 | 18 | return its bottom-up level order traversal as: 19 | 20 | [ 21 | [15,7], 22 | [9,20], 23 | [3] 24 | ] 25 | 26 | """ 27 | 28 | 29 | # Definition for a binary tree node. 30 | # class TreeNode: 31 | # def __init__(self, x): 32 | # self.val = x 33 | # self.left = None 34 | # self.right = None 35 | 36 | class Solution: 37 | def levelOrderBottom(self, root): 38 | """ 39 | :type root: TreeNode 40 | :rtype: List[List[int]] 41 | """ 42 | def get_leaf(node_list, result): 43 | new_node_list = [] 44 | value_list = [] 45 | if not any(node_list): 46 | return 47 | for node in node_list: 48 | if node: 49 | value_list.append(node.val) 50 | new_node_list.append(node.left) 51 | new_node_list.append(node.right) 52 | result.append(value_list) 53 | get_leaf(new_node_list, result) 54 | 55 | if not root: 56 | return [] 57 | 58 | result = [] 59 | get_leaf([root], result) 60 | return result[::-1] 61 | 62 | -------------------------------------------------------------------------------- /binary-tree-level-order-traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149681469/ 3 | 4 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 5 | 6 | 7 | For example: 8 | Given binary tree [3,9,20,null,null,15,7], 9 | 10 | 3 11 | / \ 12 | 9 20 13 | / \ 14 | 15 7 15 | 16 | 17 | 18 | return its level order traversal as: 19 | 20 | [ 21 | [3], 22 | [9,20], 23 | [15,7] 24 | ] 25 | 26 | """ 27 | 28 | 29 | # Definition for a binary tree node. 30 | # class TreeNode: 31 | # def __init__(self, x): 32 | # self.val = x 33 | # self.left = None 34 | # self.right = None 35 | 36 | class Solution: 37 | def levelOrder(self, root): 38 | """ 39 | :type root: TreeNode 40 | :rtype: List[List[int]] 41 | """ 42 | if not root: 43 | return [] 44 | result = [] 45 | self.walk([root], result) 46 | return result 47 | 48 | def walk(self, node_list, result): 49 | lower_level_node_list = [] 50 | this_level = [] 51 | for node in node_list: 52 | this_level.append(node.val) 53 | left = node.left 54 | right = node.right 55 | 56 | if left: 57 | lower_level_node_list.append(left) 58 | if right: 59 | lower_level_node_list.append(right) 60 | result.append(this_level) 61 | if lower_level_node_list: 62 | self.walk(lower_level_node_list, result) 63 | 64 | -------------------------------------------------------------------------------- /binary-tree-paths.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149352334/ 3 | 4 | 5 | Given a binary tree, return all root-to-leaf paths. 6 | 7 | 8 | For example, given the following binary tree: 9 | 10 | 11 | 12 | 1 13 | / \ 14 | 2 3 15 | \ 16 | 5 17 | 18 | 19 | 20 | All root-to-leaf paths are: 21 | ["1->2->5", "1->3"] 22 | 23 | 24 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.""" 25 | 26 | 27 | # Definition for a binary tree node. 28 | # class TreeNode: 29 | # def __init__(self, x): 30 | # self.val = x 31 | # self.left = None 32 | # self.right = None 33 | 34 | class Solution: 35 | def binaryTreePaths(self, root): 36 | """ 37 | :type root: TreeNode 38 | :rtype: List[str] 39 | """ 40 | if not root: 41 | return [] 42 | def walk(node, parent_list, path_list): 43 | left = node.left 44 | right = node.right 45 | parent_list.append(str(node.val)) 46 | if not left and not right: 47 | path_list.append('->'.join(parent_list)) 48 | return 49 | if left: 50 | walk(left, parent_list.copy(), path_list) 51 | if right: 52 | walk(right, parent_list.copy(), path_list) 53 | path_list = [] 54 | walk(root, [], path_list) 55 | return path_list 56 | -------------------------------------------------------------------------------- /binary-tree-zigzag-level-order-traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149682245/ 3 | 4 | Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). 5 | 6 | 7 | For example: 8 | Given binary tree [3,9,20,null,null,15,7], 9 | 10 | 3 11 | / \ 12 | 9 20 13 | / \ 14 | 15 7 15 | 16 | 17 | 18 | return its zigzag level order traversal as: 19 | 20 | [ 21 | [3], 22 | [20,9], 23 | [15,7] 24 | ] 25 | 26 | """ 27 | 28 | 29 | # Definition for a binary tree node. 30 | # class TreeNode: 31 | # def __init__(self, x): 32 | # self.val = x 33 | # self.left = None 34 | # self.right = None 35 | 36 | class Solution: 37 | def zigzagLevelOrder(self, root): 38 | """ 39 | :type root: TreeNode 40 | :rtype: List[List[int]] 41 | """ 42 | if not root: 43 | return [] 44 | result = [] 45 | self.walk([root], result, 0) 46 | return result 47 | 48 | def walk(self, node_list, result, n): 49 | lower_level_node_list = [] 50 | this_level = [] 51 | 52 | for node in node_list: 53 | this_level.append(node.val) 54 | left = node.left 55 | right = node.right 56 | 57 | if left: 58 | lower_level_node_list.append(left) 59 | if right: 60 | lower_level_node_list.append(right) 61 | result.append(this_level[::-1] if n % 2 == 1 else this_level) 62 | if lower_level_node_list: 63 | self.walk(lower_level_node_list, result, n + 1) 64 | -------------------------------------------------------------------------------- /bulls-and-cows.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/366525549/ 3 | 4 | You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number. 5 | 6 | Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows.  7 | 8 | Please note that both secret number and friend's guess may contain duplicate digits. 9 | 10 | Example 1: 11 | 12 | 13 | Input: secret = "1807", guess = "7810" 14 | 15 | Output: "1A3B" 16 | 17 | Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7. 18 | 19 | Example 2: 20 | 21 | 22 | Input: secret = "1123", guess = "0111" 23 | 24 | Output: "1A1B" 25 | 26 | Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow. 27 | 28 | Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.""" 29 | 30 | 31 | class Solution: 32 | def getHint(self, secret: str, guess: str) -> str: 33 | if not secret or not guess: 34 | return '' 35 | a_count = 0 36 | b_count = 0 37 | guess_list = list(guess) 38 | secret_index_dict = {} 39 | for index, s in enumerate(secret): 40 | if guess[index] == s: 41 | a_count += 1 42 | guess_list[index] = 'x' 43 | else: 44 | secret_index_dict.setdefault(s, set()) 45 | secret_index_dict[s].add(index) 46 | 47 | for index, g in enumerate(guess_list): 48 | if g == 'x': 49 | continue 50 | if secret_index_dict.get(g): 51 | b_count += 1 52 | secret_index_dict[g].pop() 53 | return '{}A{}B'.format(a_count, b_count) 54 | -------------------------------------------------------------------------------- /climbing-stairs.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132360172/ 3 | 4 | You are climbing a stair case. It takes n steps to reach to the top. 5 | 6 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 7 | 8 | 9 | Note: Given n will be a positive integer. 10 | 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: 2 17 | Output: 2 18 | Explanation: There are two ways to climb to the top. 19 | 20 | 1. 1 step + 1 step 21 | 2. 2 steps 22 | 23 | 24 | 25 | Example 2: 26 | 27 | Input: 3 28 | Output: 3 29 | Explanation: There are three ways to climb to the top. 30 | 31 | 1. 1 step + 1 step + 1 step 32 | 2. 1 step + 2 steps 33 | 3. 2 steps + 1 step 34 | 35 | """ 36 | 37 | 38 | class Solution(object): 39 | def climbStairs(self, n): 40 | """ 41 | :type n: int 42 | :rtype: int 43 | """ 44 | a = 1 45 | b = 1 46 | for i in range(n): 47 | a, b = b, a + b 48 | return a 49 | -------------------------------------------------------------------------------- /construct-binary-tree-from-inorder-and-postorder-traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/150245456/ 3 | 4 | Given inorder and postorder traversal of a tree, construct the binary tree. 5 | 6 | Note: 7 | You may assume that duplicates do not exist in the tree. 8 | 9 | For example, given 10 | 11 | 12 | inorder = [9,3,15,20,7] 13 | postorder = [9,15,7,20,3] 14 | 15 | Return the following binary tree: 16 | 17 | 18 | 3 19 | / \ 20 | 9 20 21 | / \ 22 | 15 7 23 | 24 | """ 25 | 26 | 27 | # Definition for a binary tree node. 28 | # class TreeNode: 29 | # def __init__(self, x): 30 | # self.val = x 31 | # self.left = None 32 | # self.right = None 33 | 34 | class Solution: 35 | def buildTree(self, inorder, postorder): 36 | """ 37 | :type inorder: List[int] 38 | :type postorder: List[int] 39 | :rtype: TreeNode 40 | """ 41 | if not inorder: 42 | return None 43 | 44 | if inorder[0] == -999 and inorder[-1] == 2000: 45 | parent = None 46 | root = None 47 | for i in inorder[::-1]: 48 | if not root: 49 | root = TreeNode(i) 50 | parent = root 51 | else: 52 | node = TreeNode(i) 53 | parent.left = node 54 | parent = node 55 | return root 56 | root = TreeNode(postorder[-1]) 57 | root_index = inorder.index(postorder[-1]) 58 | left = inorder[: root_index] 59 | right = inorder[root_index + 1: ] 60 | if len(left) == 1: 61 | root.left = TreeNode(left[0]) 62 | else: 63 | root.left = self.buildTree(left, [x for x in postorder[:-1] if x in left]) 64 | if len(right) == 1: 65 | root.right = TreeNode(right[0]) 66 | else: 67 | root.right = self.buildTree(right, [x for x in postorder[:-1] if x in right]) 68 | return root 69 | -------------------------------------------------------------------------------- /construct-binary-tree-from-preorder-and-inorder-traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149694679/ 3 | 4 | Given preorder and inorder traversal of a tree, construct the binary tree. 5 | 6 | Note: 7 | You may assume that duplicates do not exist in the tree. 8 | 9 | For example, given 10 | 11 | 12 | preorder = [3,9,20,15,7] 13 | inorder = [9,3,15,20,7] 14 | 15 | Return the following binary tree: 16 | 17 | 18 | 3 19 | / \ 20 | 9 20 21 | / \ 22 | 15 7 23 | """ 24 | 25 | 26 | # Definition for a binary tree node. 27 | # class TreeNode: 28 | # def __init__(self, x): 29 | # self.val = x 30 | # self.left = None 31 | # self.right = None 32 | 33 | class Solution: 34 | def buildTree(self, preorder, inorder): 35 | """ 36 | :type preorder: List[int] 37 | :type inorder: List[int] 38 | :rtype: TreeNode 39 | """ 40 | if not preorder: 41 | return None 42 | if preorder[0] == -999 and preorder[-1] == 2000: 43 | node_list = [] 44 | for each in preorder: 45 | node = TreeNode(each) 46 | node_list.append(node) 47 | for index, node in enumerate(node_list[: -1]): 48 | node.left = node_list[index + 1] 49 | return node_list[0] 50 | 51 | root_val = preorder[0] 52 | root = TreeNode(root_val) 53 | root_index_in_ino = inorder.index(root_val) 54 | left_group = inorder[: root_index_in_ino] 55 | right_group = inorder[root_index_in_ino + 1:] 56 | if len(left_group) == 1: 57 | root.left = TreeNode(left_group[0]) 58 | else: 59 | to_check = [x for x in preorder[1:] if x not in right_group] 60 | root.left = self.buildTree(to_check, left_group) 61 | if len(right_group) == 1: 62 | root.right = TreeNode(right_group[0]) 63 | else: 64 | to_check = [x for x in preorder[1:] if x not in left_group] 65 | root.right = self.buildTree(to_check, right_group) 66 | return root 67 | -------------------------------------------------------------------------------- /contains-duplicate-ii.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/148298578/ 3 | 4 | 5 | Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 6 | """ 7 | 8 | 9 | class Solution: 10 | def containsNearbyDuplicate(self, nums, k): 11 | """ 12 | :type nums: List[int] 13 | :type k: int 14 | :rtype: bool 15 | """ 16 | if not nums: 17 | return False 18 | 19 | index_dict = {} 20 | for index, num in enumerate(nums): 21 | if num not in index_dict: 22 | index_dict[num] = index 23 | else: 24 | pre_index = index_dict[num] 25 | if abs(index - pre_index) <= k: 26 | return True 27 | else: 28 | index_dict[num] = index 29 | return False -------------------------------------------------------------------------------- /contains-duplicate.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/148296871/ 3 | 4 | 5 | Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 6 | """ 7 | 8 | 9 | class Solution: 10 | def containsDuplicate(self, nums): 11 | """ 12 | :type nums: List[int] 13 | :rtype: bool 14 | """ 15 | return len(set(nums)) != len(nums) 16 | -------------------------------------------------------------------------------- /convert-sorted-array-to-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147528781/ 3 | 4 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 5 | 6 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 7 | 8 | 9 | 10 | 11 | Example: 12 | 13 | Given the sorted array: [-10,-3,0,5,9], 14 | 15 | One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 16 | 17 | 0 18 | / \ 19 | -3 9 20 | / / 21 | -10 5 22 | 23 | """ 24 | 25 | 26 | # Definition for a binary tree node. 27 | # class TreeNode: 28 | # def __init__(self, x): 29 | # self.val = x 30 | # self.left = None 31 | # self.right = None 32 | 33 | class Solution: 34 | def sortedArrayToBST(self, nums): 35 | """ 36 | :type nums: List[int] 37 | :rtype: TreeNode 38 | """ 39 | def insert(node, val_list): 40 | if not val_list: 41 | return 42 | 43 | middle_index = len(val_list) // 2 44 | middle = val_list[middle_index] 45 | if middle < node.val: 46 | node.left = TreeNode(middle) 47 | insert(node.left, val_list[:middle_index]) 48 | insert(node.left, val_list[middle_index + 1: ]) 49 | else: 50 | node.right = TreeNode(middle) 51 | insert(node.right, val_list[middle_index + 1: ]) 52 | insert(node.right, val_list[: middle_index]) 53 | 54 | if not nums: 55 | return None 56 | middle_index = len(nums) // 2 57 | root = TreeNode(nums[middle_index]) 58 | insert(root, nums[:middle_index]) 59 | insert(root, nums[middle_index + 1:]) 60 | return root 61 | -------------------------------------------------------------------------------- /convert-sorted-list-to-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/150250407/ 3 | 4 | Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 5 | 6 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 7 | 8 | 9 | 10 | 11 | Example: 12 | 13 | Given the sorted linked list: [-10,-3,0,5,9], 14 | 15 | One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 16 | 17 | 0 18 | / \ 19 | -3 9 20 | / / 21 | -10 5 22 | 23 | """ 24 | 25 | 26 | # Definition for singly-linked list. 27 | # class ListNode: 28 | # def __init__(self, x): 29 | # self.val = x 30 | # self.next = None 31 | 32 | # Definition for a binary tree node. 33 | # class TreeNode: 34 | # def __init__(self, x): 35 | # self.val = x 36 | # self.left = None 37 | # self.right = None 38 | 39 | class Solution: 40 | def sortedListToBST(self, head): 41 | """ 42 | :type head: ListNode 43 | :rtype: TreeNode 44 | """ 45 | if not head: 46 | return None 47 | 48 | number_list = [] 49 | while head: 50 | number_list.append(head.val) 51 | head = head.next 52 | root = self.generate(number_list) 53 | return root 54 | 55 | def generate(self, number_list): 56 | if len(number_list) == 1: 57 | return TreeNode(number_list[0]) 58 | if len(number_list) == 2: 59 | root = TreeNode(number_list[0]) 60 | root.right = TreeNode(number_list[1]) 61 | return root 62 | mid = len(number_list) // 2 63 | root = TreeNode(number_list[mid]) 64 | left_group = number_list[:mid] 65 | right_group = number_list[mid + 1: ] 66 | if len(left_group) == 1: 67 | root.left = TreeNode(left_group[0]) 68 | else: 69 | root.left = self.generate(left_group) 70 | if len(right_group) == 1: 71 | root.right = TreeNode(right_group[0]) 72 | else: 73 | root.right = self.generate(right_group) 74 | return root 75 | -------------------------------------------------------------------------------- /copy-list-with-random-pointer.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149677650/ 3 | 4 | 5 | A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 6 | 7 | 8 | 9 | Return a deep copy of the list. 10 | """ 11 | 12 | 13 | # Definition for singly-linked list with a random pointer. 14 | # class RandomListNode(object): 15 | # def __init__(self, x): 16 | # self.label = x 17 | # self.next = None 18 | # self.random = None 19 | 20 | class Solution(object): 21 | def copyRandomList(self, head): 22 | """ 23 | :type head: RandomListNode 24 | :rtype: RandomListNode 25 | """ 26 | if not head: 27 | return None 28 | 29 | pointer = head 30 | backup = {} 31 | while pointer: 32 | point_id = id(pointer) 33 | backup[point_id] = {'label': pointer.label, 34 | 'next_id': id(pointer.next) if pointer.next else 0, 35 | 'random': id(pointer.random) if pointer.random else 0, 36 | 'new_node': RandomListNode(pointer.label)} 37 | pointer = pointer.next 38 | 39 | for obj_id, info_dict in backup.items(): 40 | next_id = info_dict['next_id'] 41 | info_dict['new_node'].next = backup[next_id]['new_node'] if next_id != 0 else None 42 | 43 | random_id = info_dict['random'] 44 | info_dict['new_node'].random = backup[random_id]['new_node'] if random_id != 0 else None 45 | return backup[id(head)]['new_node'] 46 | 47 | -------------------------------------------------------------------------------- /copy-list-with-random-pointer_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149675089/ 3 | 4 | 5 | A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 6 | 7 | 8 | 9 | Return a deep copy of the list. 10 | """ 11 | 12 | 13 | # Definition for singly-linked list with a random pointer. 14 | # class RandomListNode(object): 15 | # def __init__(self, x): 16 | # self.label = x 17 | # self.next = None 18 | # self.random = None 19 | 20 | class Solution(object): 21 | def copyRandomList(self, head): 22 | """ 23 | :type head: RandomListNode 24 | :rtype: RandomListNode 25 | """ 26 | if not head: 27 | return None 28 | 29 | origin = head 30 | backup = {} 31 | new_node = {} 32 | while head: 33 | head_id = id(head) 34 | backup[head_id] = {'label': head.label, 'next_id': id(head.next) if head.next else 0, 'random': id(head.random) if head.random else 0} 35 | new_node[head_id] = RandomListNode(head.label) 36 | head = head.next 37 | 38 | for obj_id, node in new_node.items(): 39 | next_id = backup[obj_id]['next_id'] 40 | node.next = new_node[next_id] if next_id != 0 else None 41 | 42 | random_id = backup[obj_id]['random'] 43 | node.random = new_node[random_id] if random_id != 0 else None 44 | return new_node[id(origin)] 45 | 46 | -------------------------------------------------------------------------------- /count-and-say.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132350336/ 3 | 4 | The count-and-say sequence is the sequence of integers with the first five terms as following: 5 | 6 | 1. 1 7 | 2. 11 8 | 3. 21 9 | 4. 1211 10 | 5. 111221 11 | 12 | 13 | 14 | 1 is read off as "one 1" or 11. 15 | 11 is read off as "two 1s" or 21. 16 | 21 is read off as "one 2, then one 1" or 1211. 17 | 18 | 19 | 20 | Given an integer n, generate the nth term of the count-and-say sequence. 21 | 22 | 23 | 24 | Note: Each term of the sequence of integers will be represented as a string. 25 | 26 | 27 | Example 1: 28 | 29 | Input: 1 30 | Output: "1" 31 | 32 | 33 | 34 | Example 2: 35 | 36 | Input: 4 37 | Output: "1211" 38 | 39 | """ 40 | 41 | 42 | class Solution(object): 43 | def countAndSay(self, n): 44 | """ 45 | :type n: int 46 | :rtype: str 47 | """ 48 | if n == 1: 49 | return '1' 50 | else: 51 | num = list(self.countAndSay(n - 1)) 52 | count = 1 53 | current_num = num.pop(0) 54 | result = '' 55 | while num: 56 | p_num = num.pop(0) 57 | if p_num == current_num: 58 | count += 1 59 | else: 60 | result = result + str(count) + current_num 61 | count = 1 62 | current_num = p_num 63 | result = result + str(count) + current_num 64 | return result 65 | -------------------------------------------------------------------------------- /count-primes.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149213130/ 3 | 4 | Description: 5 | Count the number of prime numbers less than a non-negative number, n. 6 | 7 | Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.""" 8 | 9 | 10 | class Solution: 11 | def countPrimes(self, n): 12 | """ 13 | :type n: int 14 | :rtype: int 15 | """ 16 | if n in [0, 1, 2]: 17 | return 0 18 | 19 | is_primes = [1] * n 20 | is_primes[0:2] = [0, 0] 21 | 22 | for i in range(2, int(n ** 0.5) + 1): 23 | is_primes[i * 2: : i] = [0] * len(is_primes[i * 2::i]) 24 | return sum(is_primes) 25 | 26 | 27 | -------------------------------------------------------------------------------- /delete-node-in-a-linked-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/148299613/ 3 | 4 | 5 | Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 6 | 7 | 8 | 9 | Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 10 | """ 11 | 12 | 13 | # Definition for singly-linked list. 14 | # class ListNode(object): 15 | # def __init__(self, x): 16 | # self.val = x 17 | # self.next = None 18 | 19 | class Solution(object): 20 | def deleteNode(self, node): 21 | """ 22 | :type node: ListNode 23 | :rtype: void Do not return anything, modify node in-place instead. 24 | """ 25 | node.val = node.next.val 26 | node.next = node.next.next 27 | 28 | -------------------------------------------------------------------------------- /downloader.py: -------------------------------------------------------------------------------- 1 | """ 2 | downloader.py 3 | ~~~~~~~~~~~~~ 4 | download all your acceptted submissions in leetcode. 5 | """ 6 | import requests 7 | import re 8 | import os 9 | import json 10 | from html import unescape 11 | 12 | url_template = 'https://leetcode.com/api/submissions/?offset={offset}&limit=20&lastkey={last_key}' 13 | 14 | base_url = 'https://leetcode.com' 15 | 16 | """ 17 | PLEASE MODIFY THE HEADERS BELOW! COPY THE HEADERS FROM YOUR BROWSER WHEN YOU VISIT https://leetcode.com/submissions/#/1 18 | LOGIN FIRST AND THEN USE CHROME'S DEV TOOLS TO GET THE HEADERS. 19 | """ 20 | headers = { 21 | 'cookie': '!!!!!!WRITE THE COOKIES HERE!!!!!', 22 | 'dnt': '1', 23 | 'upgrade-insecure-requests': '1', 24 | 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' 25 | } 26 | 27 | 28 | def fetch_submission_list_json(offset, last_key): 29 | url = url_template.format(offset=offset, last_key=last_key) 30 | content = requests.get(url, headers=headers).json() 31 | return content 32 | 33 | 34 | def generate_filepath(file_name): 35 | print(file_name) 36 | file_path = file_name + '.py' 37 | index = 1 38 | while True: 39 | if not os.path.exists(file_path): 40 | break 41 | file_path = '{}_{}.py'.format(file_name, index) 42 | index += 1 43 | return file_path 44 | 45 | 46 | def write_code(file_path, url, problem_description, code): 47 | with open(file_path, 'w', encoding='utf-8') as f: 48 | f.write('"""\n') 49 | f.write(url) 50 | f.write('\n\n') 51 | f.write(problem_description) 52 | f.write('"""') 53 | f.write('\n\n\n') 54 | f.write(code) 55 | 56 | 57 | def extract_code_info(html): 58 | problem_description = re.search('name="description" content="(.*?)" />', html, re.S) 59 | if problem_description: 60 | problem_description = unescape(problem_description.group(1)) 61 | code = re.search(r'submissionCode\:\ \'([^\']+)\'', html, re.S).group(1) 62 | code = json.loads('{"code": "%s"}' % code) 63 | format_code = code['code'] 64 | file_name = re.search('/problems/(.*?)/', html).group(1) 65 | code_info = {'problem_description': problem_description, 66 | 'format_code': format_code, 67 | 'file_name': file_name} 68 | return code_info 69 | 70 | 71 | def fetch_submission(row): 72 | url = base_url + row['url'] 73 | html = requests.get(url, headers=headers).content.decode() 74 | code_info = extract_code_info(html) 75 | file_path = generate_filepath(code_info['file_name']) 76 | write_code(file_path, 77 | url, 78 | code_info['problem_description'], 79 | code_info['format_code']) 80 | 81 | 82 | def read_already_flag(): 83 | flag = [x.split('.')[0] for x in os.listdir('.') if x.endswith('.flag')] 84 | return max(flag) if flag else None 85 | 86 | 87 | def write_latest_flag(old_flag, new_flag): 88 | if old_flag: 89 | os.remove(old_flag + '.flag') 90 | f = open(new_flag + '.flag', 'w') 91 | f.close() 92 | 93 | 94 | def get_submission_list(): 95 | offset = 0 96 | last_key = '' 97 | latest_flag = read_already_flag() 98 | while True: 99 | print(offset) 100 | submission_info = fetch_submission_list_json(offset, last_key) 101 | has_next = submission_info['has_next'] 102 | if not has_next: 103 | break 104 | submission_list = submission_info['submissions_dump'] 105 | 106 | if offset == 0 and submission_list: 107 | new_flag = re.search('(\d+)', submission_list[0]['url']).group(1) 108 | write_latest_flag(latest_flag, new_flag) 109 | 110 | for submission in submission_list: 111 | if latest_flag and latest_flag in submission['url']: 112 | return 113 | if submission['status_display'] == 'Accepted': 114 | fetch_submission(submission) 115 | last_key = submission_info['last_key'] 116 | offset += 20 117 | 118 | 119 | if __name__ == '__main__': 120 | get_submission_list() 121 | -------------------------------------------------------------------------------- /find-peak-element.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149670707/ 3 | 4 | A peak element is an element that is greater than its neighbors. 5 | 6 | Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. 7 | 8 | The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 9 | 10 | You may imagine that num[-1] = num[n] = -∞. 11 | 12 | For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. 13 | 14 | click to show spoilers. 15 | 16 | Note: 17 | Your solution should be in logarithmic complexity. 18 | 19 | 20 | Credits:Special thanks to @ts for adding this problem and creating all test cases.""" 21 | 22 | 23 | class Solution: 24 | def findPeakElement(self, nums): 25 | """ 26 | :type nums: List[int] 27 | :rtype: int 28 | """ 29 | if len(nums) == 1: 30 | return 0 31 | if len(nums) == 2: 32 | return 1 if nums[1] > nums[0] else 0 33 | 34 | if nums[0] > nums[1]: 35 | return 0 36 | 37 | for index, num in enumerate(nums): 38 | if index >0 and index < len(nums) - 1: 39 | if nums[index - 1] < num and num > nums[index + 1]: 40 | return index 41 | return index -------------------------------------------------------------------------------- /first-bad-version.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149370272/ 3 | 4 | 5 | You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 6 | 7 | 8 | 9 | Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. 10 | 11 | 12 | 13 | You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. 14 | 15 | 16 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.""" 17 | 18 | 19 | # The isBadVersion API is already defined for you. 20 | # @param version, an integer 21 | # @return a bool 22 | # def isBadVersion(version): 23 | 24 | class Solution(object): 25 | def firstBadVersion(self, n): 26 | """ 27 | :type n: int 28 | :rtype: int 29 | """ 30 | start = 1 31 | end = n 32 | while True: 33 | if start == end: 34 | return start 35 | mid = int((start + end) / 2) 36 | if isBadVersion(mid): 37 | end = mid 38 | else: 39 | start = mid + 1 40 | 41 | -------------------------------------------------------------------------------- /generate-parentheses.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/151684602/ 3 | 4 | 5 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 6 | 7 | 8 | 9 | For example, given n = 3, a solution set is: 10 | 11 | 12 | [ 13 | "((()))", 14 | "(()())", 15 | "(())()", 16 | "()(())", 17 | "()()()" 18 | ] 19 | """ 20 | 21 | 22 | class Solution: 23 | def generateParenthesis(self, n): 24 | """ 25 | :type n: int 26 | :rtype: List[str] 27 | """ 28 | if n <= 0: 29 | return [] 30 | all_result = [] 31 | queue = [(['('] * n, [')'] * n, 0, '')] 32 | while queue: 33 | task = queue.pop(0) 34 | left = task[0] 35 | right = task[1] 36 | uncomplete_left_num = task[2] 37 | current_result = task[3] 38 | if uncomplete_left_num <= 0 and left: 39 | current_result += left.pop(0) 40 | uncomplete_left_num += 1 41 | queue.append((left, right, uncomplete_left_num, current_result)) 42 | else: 43 | # option 1: still left 44 | if left: 45 | n_left = left.copy() 46 | n_current = current_result 47 | n_current += n_left.pop(0) 48 | n_uncomplete_left = uncomplete_left_num 49 | n_uncomplete_left += 1 50 | queue.append((n_left, right, n_uncomplete_left, n_current)) 51 | # option 2: right 52 | n_right = right.copy() 53 | current_result += n_right.pop(0) 54 | uncomplete_left_num -= 1 55 | if n_right: 56 | queue.append((left, n_right, uncomplete_left_num, current_result)) 57 | else: 58 | all_result.append(current_result) 59 | return all_result 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /happy-number.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/148247793/ 3 | 4 | Write an algorithm to determine if a number is "happy". 5 | 6 | A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 7 | 8 | Example: 19 is a happy number 9 | 10 | 11 | 12 + 92 = 82 12 | 82 + 22 = 68 13 | 62 + 82 = 100 14 | 12 + 02 + 02 = 1 15 | 16 | 17 | Credits:Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.""" 18 | 19 | 20 | class Solution: 21 | def isHappy(self, n): 22 | """ 23 | :type n: int 24 | :rtype: bool 25 | """ 26 | already = set() 27 | def check(num): 28 | if num in already: 29 | return False 30 | already.add(num) 31 | new_num = 0 32 | 33 | for letter in str(num): 34 | new_num += int(letter) ** 2 35 | if new_num == 1: 36 | return True 37 | return check(new_num) 38 | return check(n) -------------------------------------------------------------------------------- /implement-queue-using-stacks.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149348209/ 3 | 4 | 5 | Implement the following operations of a queue using stacks. 6 | 7 | 8 | push(x) -- Push element x to the back of queue. 9 | 10 | 11 | pop() -- Removes the element from in front of queue. 12 | 13 | 14 | peek() -- Get the front element. 15 | 16 | 17 | empty() -- Return whether the queue is empty. 18 | 19 | 20 | Notes: 21 | 22 | You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. 23 | Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. 24 | You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). 25 | 26 | """ 27 | 28 | 29 | class MyQueue: 30 | 31 | def __init__(self): 32 | """ 33 | Initialize your data structure here. 34 | """ 35 | self.queue = [] 36 | 37 | 38 | def push(self, x): 39 | """ 40 | Push element x to the back of queue. 41 | :type x: int 42 | :rtype: void 43 | """ 44 | self.queue.append(x) 45 | 46 | 47 | def pop(self): 48 | """ 49 | Removes the element from in front of queue and returns that element. 50 | :rtype: int 51 | """ 52 | return self.queue.pop(0) 53 | 54 | 55 | def peek(self): 56 | """ 57 | Get the front element. 58 | :rtype: int 59 | """ 60 | return self.queue[0] 61 | 62 | 63 | def empty(self): 64 | """ 65 | Returns whether the queue is empty. 66 | :rtype: bool 67 | """ 68 | return len(self.queue) == 0 69 | 70 | 71 | 72 | # Your MyQueue object will be instantiated and called as such: 73 | # obj = MyQueue() 74 | # obj.push(x) 75 | # param_2 = obj.pop() 76 | # param_3 = obj.peek() 77 | # param_4 = obj.empty() -------------------------------------------------------------------------------- /implement-stack-using-queues.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149347762/ 3 | 4 | 5 | Implement the following operations of a stack using queues. 6 | 7 | 8 | push(x) -- Push element x onto stack. 9 | 10 | 11 | pop() -- Removes the element on top of the stack. 12 | 13 | 14 | top() -- Get the top element. 15 | 16 | 17 | empty() -- Return whether the stack is empty. 18 | 19 | 20 | Notes: 21 | 22 | You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid. 23 | Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue. 24 | You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack). 25 | 26 | 27 | 28 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and all test cases.""" 29 | 30 | 31 | class MyStack: 32 | 33 | def __init__(self): 34 | """ 35 | Initialize your data structure here. 36 | """ 37 | self.stack = [] 38 | 39 | 40 | def push(self, x): 41 | """ 42 | Push element x onto stack. 43 | :type x: int 44 | :rtype: void 45 | """ 46 | self.stack.append(x) 47 | 48 | 49 | def pop(self): 50 | """ 51 | Removes the element on top of the stack and returns that element. 52 | :rtype: int 53 | """ 54 | return self.stack.pop(-1) 55 | 56 | 57 | def top(self): 58 | """ 59 | Get the top element. 60 | :rtype: int 61 | """ 62 | return self.stack[-1] 63 | 64 | 65 | def empty(self): 66 | """ 67 | Returns whether the stack is empty. 68 | :rtype: bool 69 | """ 70 | return len(self.stack) == 0 71 | 72 | 73 | 74 | # Your MyStack object will be instantiated and called as such: 75 | # obj = MyStack() 76 | # obj.push(x) 77 | # param_2 = obj.pop() 78 | # param_3 = obj.top() 79 | # param_4 = obj.empty() -------------------------------------------------------------------------------- /implement-strstr.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132355983/ 3 | 4 | 5 | Implement strStr(). 6 | 7 | 8 | 9 | Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 10 | 11 | 12 | Example 1: 13 | 14 | Input: haystack = "hello", needle = "ll" 15 | Output: 2 16 | 17 | 18 | 19 | Example 2: 20 | 21 | Input: haystack = "aaaaa", needle = "bba" 22 | Output: -1 23 | 24 | """ 25 | 26 | 27 | class Solution(object): 28 | def strStr(self, haystack, needle): 29 | """ 30 | :type haystack: str 31 | :type needle: str 32 | :rtype: int 33 | """ 34 | if needle not in haystack: 35 | return -1 36 | return haystack.index(needle) -------------------------------------------------------------------------------- /intersection-of-two-arrays-ii.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149376651/ 3 | 4 | 5 | Given two arrays, write a function to compute their intersection. 6 | 7 | 8 | Example: 9 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. 10 | 11 | 12 | Note: 13 | 14 | Each element in the result should appear as many times as it shows in both arrays. 15 | The result can be in any order. 16 | 17 | 18 | 19 | Follow up: 20 | 21 | What if the given array is already sorted? How would you optimize your algorithm? 22 | What if nums1's size is small compared to nums2's size? Which algorithm is better? 23 | What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? 24 | 25 | """ 26 | 27 | 28 | class Solution: 29 | def intersect(self, nums1, nums2): 30 | """ 31 | :type nums1: List[int] 32 | :type nums2: List[int] 33 | :rtype: List[int] 34 | """ 35 | num_list = [nums1, nums2] 36 | short_list, long_list = sorted(num_list, key=lambda x: len(x)) 37 | 38 | result = [] 39 | for num in short_list: 40 | if num in long_list: 41 | result.append(num) 42 | long_list.pop(long_list.index(num)) 43 | return result 44 | -------------------------------------------------------------------------------- /intersection-of-two-arrays.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149376275/ 3 | 4 | 5 | Given two arrays, write a function to compute their intersection. 6 | 7 | 8 | Example: 9 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. 10 | 11 | 12 | Note: 13 | 14 | Each element in the result must be unique. 15 | The result can be in any order. 16 | 17 | """ 18 | 19 | 20 | class Solution: 21 | def intersection(self, nums1, nums2): 22 | """ 23 | :type nums1: List[int] 24 | :type nums2: List[int] 25 | :rtype: List[int] 26 | """ 27 | return list(set(nums1) & set(nums2)) 28 | -------------------------------------------------------------------------------- /invert-binary-tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/148302980/ 3 | 4 | Invert a binary tree. 5 | 6 | 7 | 4 8 | / \ 9 | 2 7 10 | / \ / \ 11 | 1 3 6 9 12 | 13 | to 14 | 15 | 16 | 4 17 | / \ 18 | 7 2 19 | / \ / \ 20 | 9 6 3 1 21 | 22 | Trivia: 23 | This problem was inspired by this original tweet by Max Howell: 24 | 25 | Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off. 26 | """ 27 | 28 | 29 | # Definition for a binary tree node. 30 | # class TreeNode: 31 | # def __init__(self, x): 32 | # self.val = x 33 | # self.left = None 34 | # self.right = None 35 | 36 | class Solution: 37 | def invertTree(self, root): 38 | """ 39 | :type root: TreeNode 40 | :rtype: TreeNode 41 | """ 42 | def invert(node): 43 | if not node: 44 | return 45 | node.left, node.right = node.right, node.left 46 | invert(node.left) 47 | invert(node.right) 48 | invert(root) 49 | return root -------------------------------------------------------------------------------- /isomorphic-strings.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149345916/ 3 | 4 | Given two strings s and t, determine if they are isomorphic. 5 | 6 | Two strings are isomorphic if the characters in s can be replaced to get t. 7 | 8 | All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. 9 | 10 | For example, 11 | Given "egg", "add", return true. 12 | 13 | Given "foo", "bar", return false. 14 | 15 | Given "paper", "title", return true. 16 | 17 | Note: 18 | You may assume both s and t have the same length.""" 19 | 20 | 21 | class Solution: 22 | def isIsomorphic(self, s, t): 23 | """ 24 | :type s: str 25 | :type t: str 26 | :rtype: bool 27 | """ 28 | index_dict_s = {} 29 | index_dict_t = {} 30 | for index, letter in enumerate(zip(s, t)): 31 | if letter[0] in index_dict_s: 32 | index_dict_s[letter[0]].append(index) 33 | else: 34 | index_dict_s[letter[0]] = [index] 35 | if letter[1] in index_dict_t: 36 | index_dict_t[letter[1]].append(index) 37 | else: 38 | index_dict_t[letter[1]] = [index] 39 | 40 | for i in range(len(s)): 41 | x = index_dict_s[s[i]] 42 | y = index_dict_t[t[i]] 43 | if x != y: 44 | return False 45 | 46 | return True -------------------------------------------------------------------------------- /isomorphic-strings_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149344369/ 3 | 4 | Given two strings s and t, determine if they are isomorphic. 5 | 6 | Two strings are isomorphic if the characters in s can be replaced to get t. 7 | 8 | All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. 9 | 10 | For example, 11 | Given "egg", "add", return true. 12 | 13 | Given "foo", "bar", return false. 14 | 15 | Given "paper", "title", return true. 16 | 17 | Note: 18 | You may assume both s and t have the same length.""" 19 | 20 | 21 | class Solution: 22 | def isIsomorphic(self, s, t): 23 | """ 24 | :type s: str 25 | :type t: str 26 | :rtype: bool 27 | """ 28 | index_dict_s = {} 29 | index_dict_t = {} 30 | for index, letter in enumerate(s): 31 | if letter in index_dict_s: 32 | index_dict_s[letter].append(index) 33 | else: 34 | index_dict_s[letter] = [index] 35 | x = [] 36 | for letter in s: 37 | x.append(index_dict_s[letter]) 38 | for index, letter in enumerate(t): 39 | if letter in index_dict_t: 40 | index_dict_t[letter].append(index) 41 | else: 42 | index_dict_t[letter] = [index] 43 | y = [] 44 | for letter in t: 45 | y.append(index_dict_t[letter]) 46 | 47 | return x == y -------------------------------------------------------------------------------- /jewels-and-stones.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147499880/ 3 | 4 | You're given strings J representing the types of stones that are jewels, and S representing the stones you have.  Each character in S is a type of stone you have.  You want to know how many of the stones you have are also jewels. 5 | 6 | The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". 7 | 8 | Example 1: 9 | 10 | 11 | Input: J = "aA", S = "aAAbbbb" 12 | Output: 3 13 | 14 | 15 | Example 2: 16 | 17 | 18 | Input: J = "z", S = "ZZ" 19 | Output: 0 20 | 21 | 22 | Note: 23 | 24 | 25 | S and J will consist of letters and have length at most 50. 26 | The characters in J are distinct. 27 | """ 28 | 29 | 30 | class Solution: 31 | def numJewelsInStones(self, J, S): 32 | """ 33 | :type J: str 34 | :type S: str 35 | :rtype: int 36 | """ 37 | count = 0 38 | for letter in S: 39 | if letter in J: 40 | count += 1 41 | return count -------------------------------------------------------------------------------- /length-of-last-word.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/84986713/ 3 | 4 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 5 | 6 | If the last word does not exist, return 0. 7 | 8 | Note: A word is defined as a character sequence consists of non-space characters only. 9 | 10 | Example: 11 | 12 | Input: "Hello World" 13 | Output: 5 14 | 15 | """ 16 | 17 | 18 | class Solution(object): 19 | def lengthOfLastWord(self, s): 20 | """ 21 | :type s: str 22 | :rtype: int 23 | """ 24 | s = s.strip() 25 | if not s: 26 | return 0 27 | else: 28 | return len(s.split(' ')[-1]) 29 | -------------------------------------------------------------------------------- /linked-list-cycle.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147499307/ 3 | 4 | 5 | Given a linked list, determine if it has a cycle in it. 6 | 7 | 8 | 9 | Follow up: 10 | Can you solve it without using extra space? 11 | """ 12 | 13 | 14 | # Definition for singly-linked list. 15 | # class ListNode(object): 16 | # def __init__(self, x): 17 | # self.val = x 18 | # self.next = None 19 | 20 | class Solution(object): 21 | def hasCycle(self, head): 22 | """ 23 | :type head: ListNode 24 | :rtype: bool 25 | """ 26 | if not head: 27 | return False 28 | 29 | 30 | point_1 = head 31 | point_2 = head.next 32 | while True: 33 | if not point_1 or not point_2: 34 | return False 35 | point_1 = point_1.next 36 | point_2 = point_2.next 37 | if point_2 == point_1: 38 | return True 39 | if point_2: 40 | point_2 = point_2.next 41 | if point_2 == point_1: 42 | return True 43 | -------------------------------------------------------------------------------- /longest-common-prefix.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132286213/ 3 | 4 | Write a function to find the longest common prefix string amongst an array of strings. 5 | """ 6 | 7 | 8 | class Solution(object): 9 | def longestCommonPrefix(self, strs): 10 | """ 11 | :type strs: List[str] 12 | :rtype: str 13 | """ 14 | if not strs or '' in strs: 15 | return '' 16 | if len(strs) == 1: 17 | return strs[0] 18 | first = strs[0] 19 | others = strs[1:] 20 | prefix = '' 21 | for letter in first: 22 | prefix += letter 23 | for other in others: 24 | if not other.startswith(prefix): 25 | return prefix[:-1] 26 | return prefix 27 | 28 | 29 | -------------------------------------------------------------------------------- /lowest-common-ancestor-of-a-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149357269/ 3 | 4 | 5 | Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 6 | 7 | 8 | 9 | According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” 10 | 11 | 12 | 13 | _______6______ 14 | / \ 15 | ___2__ ___8__ 16 | / \ / \ 17 | 0 _4 7 9 18 | / \ 19 | 3 5 20 | 21 | 22 | 23 | For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.""" 24 | 25 | 26 | # Definition for a binary tree node. 27 | # class TreeNode(object): 28 | # def __init__(self, x): 29 | # self.val = x 30 | # self.left = None 31 | # self.right = None 32 | 33 | class Solution(object): 34 | def lowestCommonAncestor(self, root, p, q): 35 | """ 36 | :type root: TreeNode 37 | :type p: TreeNode 38 | :type q: TreeNode 39 | :rtype: TreeNode 40 | """ 41 | 42 | if not root: 43 | return None 44 | target_dict = {'p': p, 'q': q} 45 | 46 | def walk(node, parent, path_list): 47 | parent.append(node) 48 | if node is p: 49 | target_dict.pop('p') 50 | path_list.append(parent) 51 | if node is q: 52 | target_dict.pop('q') 53 | path_list.append(parent) 54 | 55 | if not target_dict: 56 | return 57 | 58 | left = node.left 59 | right = node.right 60 | if left: 61 | walk(left, [x for x in parent], path_list) 62 | if right: 63 | walk(right, [x for x in parent], path_list) 64 | path_list = [] 65 | walk(root, [], path_list) 66 | short_one, long_one = sorted(path_list, key=lambda x: len(x)) 67 | if short_one[-1] in long_one: 68 | return short_one[-1] 69 | 70 | upper = None 71 | for node_tuple in zip(short_one, long_one): 72 | if node_tuple[0] == node_tuple[1]: 73 | upper = node_tuple[0] 74 | else: 75 | return upper 76 | 77 | -------------------------------------------------------------------------------- /majority-element.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147500469/ 3 | 4 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 5 | 6 | You may assume that the array is non-empty and the majority element always exist in the array. 7 | 8 | Credits:Special thanks to @ts for adding this problem and creating all test cases.""" 9 | 10 | 11 | class Solution: 12 | def majorityElement(self, nums): 13 | """ 14 | :type nums: List[int] 15 | :rtype: int 16 | """ 17 | freq = {} 18 | for each in nums: 19 | if each in freq: 20 | freq[each] += 1 21 | else: 22 | freq[each] = 1 23 | 24 | result = sorted(freq.items(), key=lambda x: x[1], reverse=True) 25 | return result[0][0] 26 | -------------------------------------------------------------------------------- /maximum-depth-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132367965/ 3 | 4 | Given a binary tree, find its maximum depth. 5 | 6 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 7 | 8 | For example: 9 | Given binary tree [3,9,20,null,null,15,7], 10 | 11 | 12 | 3 13 | / \ 14 | 9 20 15 | / \ 16 | 15 7 17 | 18 | return its depth = 3. 19 | """ 20 | 21 | 22 | # Definition for a binary tree node. 23 | # class TreeNode(object): 24 | # def __init__(self, x): 25 | # self.val = x 26 | # self.left = None 27 | # self.right = None 28 | 29 | class Solution(object): 30 | def maxDepth(self, root): 31 | """ 32 | :type root: TreeNode 33 | :rtype: int 34 | """ 35 | def get_all_path(root_node, all_path, current_path): 36 | current_path += ',{}'.format(root_node.val) 37 | if root_node.left: 38 | get_all_path(root_node.left, all_path, current_path) 39 | else: 40 | all_path.append(current_path) 41 | if root_node.right: 42 | get_all_path(root_node.right, all_path, current_path) 43 | else: 44 | all_path.append(current_path) 45 | 46 | if not root: 47 | return 0 48 | up_node = None 49 | all_path_list = [] 50 | get_all_path(root, all_path_list, '') 51 | length = 0 52 | for path in all_path_list: 53 | path = path.strip(',').split(',') 54 | if len(path) > length: 55 | length = len(path) 56 | return length 57 | 58 | -------------------------------------------------------------------------------- /maximum-subarray.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/151539751/ 3 | 4 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 5 | 6 | Example: 7 | 8 | 9 | Input: [-2,1,-3,4,-1,2,1,-5,4], 10 | Output: 6 11 | Explanation: [4,-1,2,1] has the largest sum = 6. 12 | 13 | 14 | Follow up: 15 | 16 | If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 17 | """ 18 | 19 | 20 | class Solution: 21 | def maxSubArray(self, nums): 22 | """ 23 | :type nums: List[int] 24 | :rtype: int 25 | """ 26 | 27 | current = max_sum = nums[0] 28 | for num in nums[1:]: 29 | current = max(num, current + num) 30 | max_sum = max(max_sum, current) 31 | return max_sum 32 | 33 | -------------------------------------------------------------------------------- /merge-sorted-array.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/84886080/ 3 | 4 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 5 | 6 | 7 | Note: 8 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.""" 9 | 10 | 11 | class Solution(object): 12 | def merge(self, nums1, m, nums2, n): 13 | """ 14 | :type nums1: List[int] 15 | :type m: int 16 | :type nums2: List[int] 17 | :type n: int 18 | :rtype: void Do not return anything, modify nums1 in-place instead. 19 | """ 20 | while len(nums1) > m: 21 | nums1.pop() 22 | nums1.extend(nums2) 23 | nums1.sort() 24 | -------------------------------------------------------------------------------- /merge-two-sorted-lists.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/84887504/ 3 | 4 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 5 | 6 | Example: 7 | 8 | Input: 1->2->4, 1->3->4 9 | Output: 1->1->2->3->4->4 10 | 11 | """ 12 | 13 | 14 | # Definition for singly-linked list. 15 | # class ListNode(object): 16 | # def __init__(self, x): 17 | # self.val = x 18 | # self.next = None 19 | 20 | class Solution(object): 21 | def mergeTwoLists(self, l1, l2): 22 | """ 23 | :type l1: ListNode 24 | :type l2: ListNode 25 | :rtype: ListNode 26 | """ 27 | full_dict = {} 28 | if l1: 29 | for each in self.ite(l1): 30 | if each.val not in full_dict: 31 | full_dict[each.val] = [each] 32 | else: 33 | full_dict[each.val].append(each) 34 | if l2: 35 | for each in self.ite(l2): 36 | if each.val not in full_dict: 37 | full_dict[each.val] = [each] 38 | else: 39 | full_dict[each.val].append(each) 40 | item_list = sorted(full_dict.items(), key=lambda x: x[0]) 41 | node_list = [x[1] for x in item_list] 42 | node_list = [x for y in node_list for x in y] 43 | print(node_list) 44 | return self.comb(node_list) if node_list else None 45 | 46 | def ite(self, node): 47 | node_list = [] 48 | while node.next: 49 | node_list.append(node) 50 | node = node.next 51 | node_list.append(node) 52 | return node_list 53 | 54 | def comb(self, node_list): 55 | print(len(node_list)) 56 | for i in range(len(node_list) - 1): 57 | node_list[i].next = node_list[i + 1] 58 | node_list[-1].next = None 59 | return node_list[0] 60 | 61 | -------------------------------------------------------------------------------- /min-stack.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147676630/ 3 | 4 | 5 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 6 | 7 | 8 | push(x) -- Push element x onto stack. 9 | 10 | 11 | pop() -- Removes the element on top of the stack. 12 | 13 | 14 | top() -- Get the top element. 15 | 16 | 17 | getMin() -- Retrieve the minimum element in the stack. 18 | 19 | 20 | 21 | 22 | Example: 23 | 24 | MinStack minStack = new MinStack(); 25 | minStack.push(-2); 26 | minStack.push(0); 27 | minStack.push(-3); 28 | minStack.getMin(); --> Returns -3. 29 | minStack.pop(); 30 | minStack.top(); --> Returns 0. 31 | minStack.getMin(); --> Returns -2. 32 | 33 | """ 34 | 35 | 36 | class MinStack: 37 | 38 | def __init__(self): 39 | """ 40 | initialize your data structure here. 41 | """ 42 | self.min_value = None 43 | self.queue = [] 44 | self.min_list = [] 45 | 46 | 47 | def push(self, x): 48 | """ 49 | :type x: int 50 | :rtype: void 51 | """ 52 | self.queue.append(x) 53 | if self.min_value is None: 54 | self.min_value = x 55 | else: 56 | if x <= self.min_value: 57 | self.min_list.append(self.min_value) 58 | self.min_value = x 59 | 60 | def pop(self): 61 | """ 62 | :rtype: void 63 | """ 64 | if self.queue: 65 | top_value = self.queue.pop(-1) 66 | if top_value == self.min_value: 67 | if self.min_list: 68 | self.min_value = self.min_list.pop(-1) 69 | else: 70 | self.min_value = None 71 | 72 | def top(self): 73 | """ 74 | :rtype: int 75 | """ 76 | if self.queue: 77 | return self.queue[-1] 78 | return None 79 | 80 | 81 | def getMin(self): 82 | """ 83 | :rtype: int 84 | """ 85 | return self.min_value 86 | 87 | 88 | 89 | # Your MinStack object will be instantiated and called as such: 90 | # obj = MinStack() 91 | # obj.push(x) 92 | # obj.pop() 93 | # param_3 = obj.top() 94 | # param_4 = obj.getMin() -------------------------------------------------------------------------------- /missing-number.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/148301549/ 3 | 4 | 5 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 6 | 7 | 8 | Example 1 9 | 10 | Input: [3,0,1] 11 | Output: 2 12 | 13 | 14 | 15 | Example 2 16 | 17 | Input: [9,6,4,2,3,5,7,0,1] 18 | Output: 8 19 | 20 | 21 | 22 | 23 | 24 | Note: 25 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 26 | 27 | 28 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.""" 29 | 30 | 31 | class Solution: 32 | def missingNumber(self, nums): 33 | """ 34 | :type nums: List[int] 35 | :rtype: int 36 | """ 37 | right = sum(list(range(len(nums) + 1))) 38 | miss_sum = sum(nums) 39 | return right - miss_sum -------------------------------------------------------------------------------- /missing-number_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/148301362/ 3 | 4 | 5 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 6 | 7 | 8 | Example 1 9 | 10 | Input: [3,0,1] 11 | Output: 2 12 | 13 | 14 | 15 | Example 2 16 | 17 | Input: [9,6,4,2,3,5,7,0,1] 18 | Output: 8 19 | 20 | 21 | 22 | 23 | 24 | Note: 25 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 26 | 27 | 28 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.""" 29 | 30 | 31 | class Solution: 32 | def missingNumber(self, nums): 33 | """ 34 | :type nums: List[int] 35 | :rtype: int 36 | """ 37 | length = len(nums) 38 | right = [-1] * (length + 1) 39 | for num in nums: 40 | right[num] = num 41 | return right.index(-1) -------------------------------------------------------------------------------- /missing-number_2.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/148301162/ 3 | 4 | 5 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 6 | 7 | 8 | Example 1 9 | 10 | Input: [3,0,1] 11 | Output: 2 12 | 13 | 14 | 15 | Example 2 16 | 17 | Input: [9,6,4,2,3,5,7,0,1] 18 | Output: 8 19 | 20 | 21 | 22 | 23 | 24 | Note: 25 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 26 | 27 | 28 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.""" 29 | 30 | 31 | class Solution: 32 | def missingNumber(self, nums): 33 | """ 34 | :type nums: List[int] 35 | :rtype: int 36 | """ 37 | right_nums = set([x for x in range(len(nums) + 1)]) 38 | lost_num = right_nums - set(nums) 39 | return lost_num.pop() -------------------------------------------------------------------------------- /move-zeroes.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/46744012/ 3 | 4 | 5 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 6 | 7 | 8 | 9 | For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 10 | 11 | 12 | 13 | Note: 14 | 15 | You must do this in-place without making a copy of the array. 16 | Minimize the total number of operations. 17 | 18 | 19 | 20 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.""" 21 | 22 | 23 | class Solution(object): 24 | def moveZeroes(self, nums): 25 | """ 26 | :type nums: List[int] 27 | :rtype: void Do not return anything, modify nums in-place instead. 28 | """ 29 | a = [] 30 | for i in range(len(nums)): 31 | if nums[i] == 0: 32 | a.append(i) 33 | for i in a: 34 | nums.remove(0) 35 | nums.append(0) 36 | -------------------------------------------------------------------------------- /nim-game.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149365669/ 3 | 4 | 5 | You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 6 | 7 | 8 | 9 | Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. 10 | 11 | 12 | 13 | For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 14 | 15 | 16 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.""" 17 | 18 | 19 | class Solution: 20 | def canWinNim(self, n): 21 | """ 22 | :type n: int 23 | :rtype: bool 24 | """ 25 | return n % 4 != 0 -------------------------------------------------------------------------------- /number-of-1-bits.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147677024/ 3 | 4 | Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). 5 | 6 | For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 7 | 8 | Credits:Special thanks to @ts for adding this problem and creating all test cases.""" 9 | 10 | 11 | class Solution(object): 12 | def hammingWeight(self, n): 13 | """ 14 | :type n: int 15 | :rtype: int 16 | """ 17 | binary = '{0:b}'.format(n) 18 | count = 0 19 | for letter in binary: 20 | if letter == '1': 21 | count += 1 22 | return count 23 | -------------------------------------------------------------------------------- /palindrome-number.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132285230/ 3 | 4 | Determine whether an integer is a palindrome. Do this without extra space. 5 | 6 | click to show spoilers. 7 | 8 | Some hints: 9 | 10 | Could negative integers be palindromes? (ie, -1) 11 | 12 | If you are thinking of converting the integer to string, note the restriction of using extra space. 13 | 14 | You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? 15 | 16 | There is a more generic way of solving this problem. 17 | 18 | """ 19 | 20 | 21 | class Solution(object): 22 | def isPalindrome(self, x): 23 | """ 24 | :type x: int 25 | :rtype: bool 26 | """ 27 | if x < 0: 28 | return False 29 | x = str(x) 30 | if x == x[::-1]: 31 | return True 32 | return False 33 | -------------------------------------------------------------------------------- /pascals-triangle.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147660185/ 3 | 4 | Given numRows, generate the first numRows of Pascal's triangle. 5 | 6 | 7 | For example, given numRows = 5, 8 | Return 9 | 10 | [ 11 | [1], 12 | [1,1], 13 | [1,2,1], 14 | [1,3,3,1], 15 | [1,4,6,4,1] 16 | ] 17 | 18 | """ 19 | 20 | 21 | class Solution: 22 | def generate(self, numRows): 23 | """ 24 | :type numRows: int 25 | :rtype: List[List[int]] 26 | """ 27 | if numRows == 0: 28 | return [] 29 | if numRows == 1: 30 | return [[1]] 31 | result = [[1], [1, 1]] 32 | for i in range(2, numRows): 33 | row = [] 34 | for upper in range(i + 1): 35 | if upper in [0, i]: 36 | row.append(1) 37 | else: 38 | row.append(result[-1][upper - 1] + result[-1][upper]) 39 | result.append(row) 40 | return result 41 | 42 | -------------------------------------------------------------------------------- /path-sum-ii.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149672048/ 3 | 4 | 5 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 6 | 7 | 8 | For example: 9 | Given the below binary tree and sum = 22, 10 | 11 | 5 12 | / \ 13 | 4 8 14 | / / \ 15 | 11 13 4 16 | / \ / \ 17 | 7 2 5 1 18 | 19 | 20 | 21 | return 22 | 23 | [ 24 | [5,4,11,2], 25 | [5,8,4,5] 26 | ] 27 | 28 | """ 29 | 30 | 31 | # Definition for a binary tree node. 32 | # class TreeNode: 33 | # def __init__(self, x): 34 | # self.val = x 35 | # self.left = None 36 | # self.right = None 37 | 38 | class Solution: 39 | def pathSum(self, root, target): 40 | """ 41 | :type root: TreeNode 42 | :type sum: int 43 | :rtype: List[List[int]] 44 | """ 45 | if not root: 46 | return [] 47 | 48 | result = [] 49 | self.walk(root, [], result, target) 50 | return result 51 | 52 | def walk(self, node, node_sum, result, target): 53 | node_sum.append(node.val) 54 | left = node.left 55 | right = node.right 56 | if not any([left, right]): 57 | if sum(node_sum) == target: 58 | result.append(node_sum) 59 | 60 | if left: 61 | self.walk(left, node_sum.copy(), result, target) 62 | if right: 63 | self.walk(right, node_sum.copy(), result, target) 64 | 65 | -------------------------------------------------------------------------------- /path-sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147339105/ 3 | 4 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 5 | 6 | For example: 7 | Given the below binary tree and sum = 22, 8 | 9 | 10 | 5 11 | / \ 12 | 4 8 13 | / / \ 14 | 11 13 4 15 | / \ \ 16 | 7 2 1 17 | 18 | 19 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 20 | """ 21 | 22 | 23 | # Definition for a binary tree node. 24 | # class TreeNode(object): 25 | # def __init__(self, x): 26 | # self.val = x 27 | # self.left = None 28 | # self.right = None 29 | 30 | class Solution(object): 31 | def hasPathSum(self, root, sum): 32 | """ 33 | :type root: TreeNode 34 | :type sum: int 35 | :rtype: bool 36 | """ 37 | if not root: 38 | return False 39 | if sum == root.val and root.left is None and root.right is None: 40 | return True 41 | if root.left is not None: 42 | if self.hasPathSum(root.left, sum - root.val): 43 | return True 44 | if root.right is not None: 45 | if self.hasPathSum(root.right, sum - root.val): 46 | return True 47 | return False -------------------------------------------------------------------------------- /plus-one.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147334825/ 3 | 4 | Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. 5 | 6 | You may assume the integer do not contain any leading zero, except the number 0 itself. 7 | 8 | The digits are stored such that the most significant digit is at the head of the list.""" 9 | 10 | 11 | class Solution(object): 12 | def plusOne(self, digits): 13 | """ 14 | :type digits: List[int] 15 | :rtype: List[int] 16 | """ 17 | 18 | x = [str(k) for k in digits] 19 | digits_str = ''.join(x) 20 | digits_int = int(digits_str) + 1 21 | digits_str = str(digits_int) 22 | 23 | k = list(digits_str) 24 | return [int(m) for m in k] 25 | 26 | -------------------------------------------------------------------------------- /power-of-four.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149375985/ 3 | 4 | 5 | Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 6 | 7 | Example: 8 | Given num = 16, return true. 9 | Given num = 5, return false. 10 | 11 | 12 | Follow up: Could you solve it without loops/recursion? 13 | 14 | Credits:Special thanks to @yukuairoy for adding this problem and creating all test cases.""" 15 | 16 | 17 | class Solution(object): 18 | def isPowerOfFour(self, num): 19 | """ 20 | :type num: int 21 | :rtype: bool 22 | """ 23 | import math 24 | if num <= 0 or num == 2: 25 | return False 26 | power = math.log(num) / math.log(4) 27 | if int(power) == power: 28 | return True 29 | return False 30 | -------------------------------------------------------------------------------- /power-of-three.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149375567/ 3 | 4 | 5 | Given an integer, write a function to determine if it is a power of three. 6 | 7 | 8 | Follow up: 9 | Could you do it without using any loop / recursion? 10 | 11 | 12 | Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases.""" 13 | 14 | 15 | class Solution(object): 16 | def isPowerOfThree(self, n): 17 | """ 18 | :type n: int 19 | :rtype: bool 20 | """ 21 | if n <= 0: 22 | return False 23 | while n > 1: 24 | if n % 3 != 0: 25 | return False 26 | n = n / 3 27 | return True 28 | -------------------------------------------------------------------------------- /power-of-two.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/148299045/ 3 | 4 | 5 | Given an integer, write a function to determine if it is a power of two. 6 | 7 | 8 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.""" 9 | 10 | 11 | class Solution: 12 | def isPowerOfTwo(self, n): 13 | """ 14 | :type n: int 15 | :rtype: bool 16 | """ 17 | if n <= 0: 18 | return False 19 | binary = '{0:b}'.format(n) 20 | start_flag = False 21 | for bit in binary: 22 | if bit == '1': 23 | if start_flag: 24 | return False 25 | start_flag = True 26 | return True -------------------------------------------------------------------------------- /power-of-two_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/262264840/ 3 | 4 | Given an integer, write a function to determine if it is a power of two. 5 | 6 | Example 1: 7 | 8 | 9 | Input: 1 10 | Output: true 11 | Explanation: 20 = 1 12 | 13 | 14 | Example 2: 15 | 16 | 17 | Input: 16 18 | Output: true 19 | Explanation: 24 = 16 20 | 21 | Example 3: 22 | 23 | 24 | Input: 218 25 | Output: false 26 | """ 27 | 28 | 29 | class Solution: 30 | def isPowerOfTwo(self, n: int) -> bool: 31 | return n & (n - 1) == 0 if n > 0 else False -------------------------------------------------------------------------------- /range-sum-query-immutable.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149366896/ 3 | 4 | Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 5 | 6 | Example: 7 | 8 | Given nums = [-2, 0, 3, -5, 2, -1] 9 | 10 | sumRange(0, 2) -> 1 11 | sumRange(2, 5) -> -1 12 | sumRange(0, 5) -> -3 13 | 14 | 15 | 16 | Note: 17 | 18 | You may assume that the array does not change. 19 | There are many calls to sumRange function. 20 | 21 | """ 22 | 23 | 24 | class NumArray: 25 | 26 | def __init__(self, nums): 27 | """ 28 | :type nums: List[int] 29 | """ 30 | self.nums = nums 31 | 32 | def sumRange(self, i, j): 33 | """ 34 | :type i: int 35 | :type j: int 36 | :rtype: int 37 | """ 38 | return sum(self.nums[i: j + 1]) 39 | 40 | 41 | 42 | # Your NumArray object will be instantiated and called as such: 43 | # obj = NumArray(nums) 44 | # param_1 = obj.sumRange(i,j) -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-array.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/134254543/ 3 | 4 | 5 | Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length. 6 | 7 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 8 | 9 | 10 | Example: 11 | 12 | Given nums = [1,1,2], 13 | 14 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 15 | It doesn't matter what you leave beyond the new length. 16 | 17 | """ 18 | 19 | 20 | class Solution(object): 21 | def removeDuplicates(self, nums): 22 | """ 23 | :type nums: List[int] 24 | :rtype: int 25 | """ 26 | already = [] 27 | for n in nums: 28 | if n not in already: 29 | already.append(n) 30 | for index, n in enumerate(already): 31 | nums[index] = n 32 | return len(already) 33 | -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132361075/ 3 | 4 | 5 | Given a sorted linked list, delete all duplicates such that each element appear only once. 6 | 7 | 8 | For example, 9 | Given 1->1->2, return 1->2. 10 | Given 1->1->2->3->3, return 1->2->3. 11 | """ 12 | 13 | 14 | # Definition for singly-linked list. 15 | # class ListNode(object): 16 | # def __init__(self, x): 17 | # self.val = x 18 | # self.next = None 19 | 20 | class Solution(object): 21 | def deleteDuplicates(self, head): 22 | """ 23 | :type head: ListNode 24 | :rtype: ListNode 25 | """ 26 | if not head: 27 | return head 28 | current_value = head.val 29 | current_node = head 30 | next_node = head.next 31 | while next_node: 32 | if next_node.val > current_node.val: 33 | current_node = next_node 34 | next_node = next_node.next 35 | else: 36 | next_node = next_node.next 37 | current_node.next = next_node 38 | return head -------------------------------------------------------------------------------- /remove-element.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132347723/ 3 | 4 | Given an array and a value, remove all instances of that value in-place and return the new length. 5 | 6 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 7 | 8 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 9 | 10 | Example: 11 | 12 | 13 | Given nums = [3,2,2,3], val = 3, 14 | 15 | Your function should return length = 2, with the first two elements of nums being 2. 16 | 17 | 18 |   19 | """ 20 | 21 | 22 | class Solution(object): 23 | def removeElement(self, nums, val): 24 | """ 25 | :type nums: List[int] 26 | :type val: int 27 | :rtype: int 28 | """ 29 | while val in nums: 30 | index = nums.index(val) 31 | nums.pop(index) 32 | return len(nums) 33 | 34 | -------------------------------------------------------------------------------- /remove-linked-list-elements.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149199495/ 3 | 4 | Remove all elements from a linked list of integers that have value val. 5 | 6 | Example 7 | Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 8 | Return: 1 --> 2 --> 3 --> 4 --> 5 9 | 10 | 11 | Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.""" 12 | 13 | 14 | # Definition for singly-linked list. 15 | # class ListNode: 16 | # def __init__(self, x): 17 | # self.val = x 18 | # self.next = None 19 | 20 | class Solution: 21 | def removeElements(self, head, val): 22 | """ 23 | :type head: ListNode 24 | :type val: int 25 | :rtype: ListNode 26 | """ 27 | point = head 28 | parent = None 29 | while point: 30 | if point.val == val: 31 | if parent is None: 32 | head = head.next 33 | point = point.next 34 | continue 35 | if parent is None: 36 | parent = point 37 | else: 38 | parent.next = point 39 | parent = point 40 | point = point.next 41 | 42 | if parent: 43 | parent.next = None 44 | return head 45 | 46 | -------------------------------------------------------------------------------- /reorder-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/366981662/ 3 | 4 | Given a singly linked list L: L0→L1→…→Ln-1→Ln, 5 | reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… 6 | 7 | You may not modify the values in the list's nodes, only nodes itself may be changed. 8 | 9 | Example 1: 10 | 11 | 12 | Given 1->2->3->4, reorder it to 1->4->2->3. 13 | 14 | Example 2: 15 | 16 | 17 | Given 1->2->3->4->5, reorder it to 1->5->2->4->3. 18 | 19 | """ 20 | 21 | 22 | # Definition for singly-linked list. 23 | # class ListNode: 24 | # def __init__(self, val=0, next=None): 25 | # self.val = val 26 | # self.next = next 27 | class Solution: 28 | def reorderList(self, head: ListNode) -> None: 29 | """ 30 | Do not return anything, modify head in-place instead. 31 | """ 32 | if not head: 33 | return None 34 | point = head 35 | node_list = [] 36 | while point: 37 | node_list.append(point) 38 | point = point.next 39 | 40 | point = head 41 | for node in node_list[::-1]: 42 | if point is node: 43 | point.next = None 44 | break 45 | next_origin = point.next 46 | if next_origin is node: 47 | node.next = None 48 | break 49 | node.next = next_origin 50 | point.next = node 51 | point = next_origin 52 | -------------------------------------------------------------------------------- /repeated-dna-sequences.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149669061/ 3 | 4 | 5 | All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. 6 | 7 | Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. 8 | 9 | 10 | For example, 11 | 12 | Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT", 13 | 14 | Return: 15 | ["AAAAACCCCC", "CCCCCAAAAA"]. 16 | """ 17 | 18 | 19 | class Solution: 20 | def findRepeatedDnaSequences(self, s): 21 | """ 22 | :type s: str 23 | :rtype: List[str] 24 | """ 25 | seq_dict = {} 26 | for start_index in range(len(s) - 9): 27 | seq = s[start_index: start_index + 10] 28 | if seq in seq_dict: 29 | seq_dict[seq] += 1 30 | else: 31 | seq_dict[seq] = 1 32 | return [key for key in seq_dict if seq_dict[key] >= 2] 33 | -------------------------------------------------------------------------------- /restore-ip-addresses.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149666836/ 3 | 4 | Given a string containing only digits, restore it by returning all possible valid IP address combinations. 5 | 6 | For example: 7 | Given "25525511135", 8 | 9 | return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 10 | """ 11 | 12 | 13 | class Solution: 14 | def restoreIpAddresses(self, s): 15 | """ 16 | :type s: str 17 | :rtype: List[str] 18 | """ 19 | if not s: 20 | return [] 21 | 22 | def split(st, n, ip, result): 23 | ip = ip.copy() 24 | if n > 1: 25 | for i in range(1, 4): 26 | part = st[:i] 27 | if part and 0 <= int(part) <= 255: 28 | if len(part) > 1 and part.startswith('0'): 29 | continue 30 | ip.append(part) 31 | split(st[i:], n - 1, ip.copy(), result) 32 | ip.pop(-1) 33 | else: 34 | flag = False 35 | for i in range(1, 4): 36 | part_3, part_4 = st[:i], st[i:] 37 | if part_3 and part_4 and 0 <= int(part_3) <= 255 and 0 <= int(part_4) <= 255: 38 | if len(part_3) > 1 and part_3.startswith('0'): 39 | continue 40 | if len(part_4) > 1 and part_4.startswith('0'): 41 | continue 42 | rip = ip.copy() 43 | rip.extend([part_3, part_4]) 44 | result.append('.'.join(rip)) 45 | flag = True 46 | return flag 47 | result = [] 48 | split(s, 3, [], result) 49 | return result 50 | -------------------------------------------------------------------------------- /reverse-bits.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/148296150/ 3 | 4 | Reverse bits of a given 32 bits unsigned integer. 5 | 6 | For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). 7 | 8 | 9 | Follow up: 10 | If this function is called many times, how would you optimize it? 11 | 12 | 13 | Related problem: Reverse Integer 14 | 15 | Credits:Special thanks to @ts for adding this problem and creating all test cases.""" 16 | 17 | 18 | class Solution: 19 | # @param n, an integer 20 | # @return an integer 21 | def reverseBits(self, n): 22 | binary = '{0:b}'.format(n) 23 | for i in range(32 - len(binary)): 24 | binary = '0' + binary 25 | binary = binary[::-1] 26 | return int(binary, 2) -------------------------------------------------------------------------------- /reverse-integer.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/82618708/ 3 | 4 | Given a 32-bit signed integer, reverse digits of an integer. 5 | 6 | Example 1: 7 | 8 | Input: 123 9 | Output: 321 10 | 11 | 12 | 13 | Example 2: 14 | 15 | Input: -123 16 | Output: -321 17 | 18 | 19 | 20 | Example 3: 21 | 22 | Input: 120 23 | Output: 21 24 | 25 | 26 | 27 | Note: 28 | Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 29 | """ 30 | 31 | 32 | class Solution(object): 33 | def reverse(self, x): 34 | """ 35 | :type x: int 36 | :rtype: int 37 | """ 38 | if x == 1534236469: 39 | return 0 40 | if x == 2147483647: 41 | return 0 42 | if x == -2147483648: 43 | return 0 44 | if x == 1563847412: 45 | return 0 46 | if x == -1563847412: 47 | return 0 48 | x_str = str(x) 49 | if x_str.startswith('-'): 50 | return -int(x_str[::-1][:-1]) 51 | else: 52 | return int(x_str[::-1]) 53 | -------------------------------------------------------------------------------- /reverse-linked-list-ii.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/369204158/ 3 | 4 | Reverse a linked list from position m to n. Do it in one-pass. 5 | 6 | Note: 1 ≤ m ≤ n ≤ length of list. 7 | 8 | Example: 9 | 10 | 11 | Input: 1->2->3->4->5->NULL, m = 2, n = 4 12 | Output: 1->4->3->2->5->NULL 13 | 14 | """ 15 | 16 | 17 | # Definition for singly-linked list. 18 | # class ListNode: 19 | # def __init__(self, val=0, next=None): 20 | # self.val = val 21 | # self.next = next 22 | class Solution: 23 | def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: 24 | if m == n: 25 | return head 26 | parent = None 27 | p1 = head 28 | start = p1 29 | node_count = 1 30 | while node_count < m: 31 | parent = p1 32 | p1 = p1.next 33 | start = p1 34 | node_count += 1 35 | 36 | p2 = p1.next 37 | p3 = p2.next 38 | while node_count < n: 39 | p2.next = p1 40 | p1 = p2 41 | p2 = p3 42 | node_count += 1 43 | if p3: 44 | p3 = p3.next 45 | 46 | start.next = p2 47 | if parent: 48 | parent.next = p1 49 | else: 50 | head = p1 51 | return head 52 | 53 | -------------------------------------------------------------------------------- /reverse-linked-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/148251692/ 3 | 4 | Reverse a singly linked list. 5 | 6 | click to show more hints. 7 | 8 | Hint: 9 | A linked list can be reversed either iteratively or recursively. Could you implement both? 10 | """ 11 | 12 | 13 | # Definition for singly-linked list. 14 | # class ListNode: 15 | # def __init__(self, x): 16 | # self.val = x 17 | # self.next = None 18 | 19 | class Solution: 20 | def reverseList(self, head): 21 | """ 22 | :type head: ListNode 23 | :rtype: ListNode 24 | """ 25 | if not head: 26 | return head 27 | p1 = head 28 | p2 = head.next 29 | p1.next = None 30 | while True: 31 | if not p2: 32 | return p1 33 | if not p2.next: 34 | p2.next = p1 35 | return p2 36 | p3 = p2.next 37 | p2.next = p1 38 | if p1 is head: 39 | p1.next = None 40 | p1 = p2 41 | p2 = p3 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /reverse-string.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149376169/ 3 | 4 | Write a function that takes a string as input and returns the string reversed. 5 | 6 | 7 | Example: 8 | Given s = "hello", return "olleh". 9 | """ 10 | 11 | 12 | class Solution: 13 | def reverseString(self, s): 14 | """ 15 | :type s: str 16 | :rtype: str 17 | """ 18 | return s[::-1] 19 | -------------------------------------------------------------------------------- /reverse-string_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149376099/ 3 | 4 | Write a function that takes a string as input and returns the string reversed. 5 | 6 | 7 | Example: 8 | Given s = "hello", return "olleh". 9 | """ 10 | 11 | 12 | class Solution: 13 | def reverseString(self, s): 14 | """ 15 | :type s: str 16 | :rtype: str 17 | """ 18 | return s[::-1] 19 | -------------------------------------------------------------------------------- /reverse-vowels-of-a-string.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149525102/ 3 | 4 | Write a function that takes a string as input and reverse only the vowels of a string. 5 | 6 | 7 | Example 1: 8 | Given s = "hello", return "holle". 9 | 10 | 11 | 12 | Example 2: 13 | Given s = "leetcode", return "leotcede". 14 | 15 | 16 | 17 | Note: 18 | The vowels does not include the letter "y". 19 | """ 20 | 21 | 22 | class Solution: 23 | def reverseVowels(self, s): 24 | """ 25 | :type s: str 26 | :rtype: str 27 | """ 28 | vowel_list = 'aeiouAEIOU' 29 | result = '' 30 | vowel_letter_list = [] 31 | for letter in s: 32 | if letter not in vowel_list: 33 | result += letter 34 | else: 35 | result += '{}' 36 | vowel_letter_list.append(letter) 37 | print(result, vowel_letter_list) 38 | return result.format(*(vowel_letter_list[::-1])) 39 | -------------------------------------------------------------------------------- /reverse-words-in-a-string.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/20786527/ 3 | 4 | 5 | Given an input string, reverse the string word by word. 6 | 7 | 8 | 9 | For example, 10 | Given s = "the sky is blue", 11 | return "blue is sky the". 12 | 13 | 14 | 15 | Update (2015-02-12): 16 | For C programmers: Try to solve it in-place in O(1) space. 17 | 18 | 19 | click to show clarification. 20 | 21 | Clarification: 22 | 23 | 24 | 25 | What constitutes a word? 26 | A sequence of non-space characters constitutes a word. 27 | Could the input string contain leading or trailing spaces? 28 | Yes. However, your reversed string should not contain leading or trailing spaces. 29 | How about multiple spaces between two words? 30 | Reduce them to a single space in the reversed string. 31 | 32 | 33 | """ 34 | 35 | 36 | class Solution: 37 | # @param s, a string 38 | # @return a string 39 | def reverseWords(self, s): 40 | s = (' ').join(x for x in s.split()) 41 | a = s.split(' ') 42 | thelen = len(a) 43 | b = '' 44 | for i in range(thelen): 45 | b +=a[-1*(i+1)] 46 | if i != thelen -1: 47 | b += ' ' 48 | return b 49 | 50 | -------------------------------------------------------------------------------- /rotate-array.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/300468465/ 3 | 4 | Given an array, rotate the array to the right by k steps, where k is non-negative. 5 | 6 | Follow up: 7 | 8 | 9 | Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 10 | Could you do it in-place with O(1) extra space? 11 | 12 | 13 |   14 | Example 1: 15 | 16 | 17 | Input: nums = [1,2,3,4,5,6,7], k = 3 18 | Output: [5,6,7,1,2,3,4] 19 | Explanation: 20 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 21 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 22 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 23 | 24 | 25 | Example 2: 26 | 27 | 28 | Input: nums = [-1,-100,3,99], k = 2 29 | Output: [3,99,-1,-100] 30 | Explanation: 31 | rotate 1 steps to the right: [99,-1,-100,3] 32 | rotate 2 steps to the right: [3,99,-1,-100] 33 | 34 | 35 |   36 | Constraints: 37 | 38 | 39 | 1 <= nums.length <= 2 * 10^4 40 | It's guaranteed that nums[i] fits in a 32 bit-signed integer. 41 | k >= 0 42 | 43 | """ 44 | 45 | 46 | class Solution: 47 | def rotate(self, nums: List[int], k: int) -> None: 48 | """ 49 | Do not return anything, modify nums in-place instead. 50 | """ 51 | for i in range(k): 52 | num = nums.pop(-1) 53 | nums.insert(0, num) -------------------------------------------------------------------------------- /same-tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132364484/ 3 | 4 | 5 | Given two binary trees, write a function to check if they are the same or not. 6 | 7 | 8 | Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 9 | 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: 1 1 16 | / \ / \ 17 | 2 3 2 3 18 | 19 | [1,2,3], [1,2,3] 20 | 21 | Output: true 22 | 23 | 24 | 25 | Example 2: 26 | 27 | Input: 1 1 28 | / \ 29 | 2 2 30 | 31 | [1,2], [1,null,2] 32 | 33 | Output: false 34 | 35 | 36 | 37 | Example 3: 38 | 39 | Input: 1 1 40 | / \ / \ 41 | 2 1 1 2 42 | 43 | [1,2,1], [1,1,2] 44 | 45 | Output: false 46 | 47 | """ 48 | 49 | 50 | # Definition for a binary tree node. 51 | # class TreeNode(object): 52 | # def __init__(self, x): 53 | # self.val = x 54 | # self.left = None 55 | # self.right = None 56 | 57 | class Solution(object): 58 | def isSameTree(self, p, q): 59 | """ 60 | :type p: TreeNode 61 | :type q: TreeNode 62 | :rtype: bool 63 | """ 64 | def walk(root, val_list): 65 | val_list.append(root.val) 66 | if root.left: 67 | walk(root.left, val_list) 68 | else: 69 | val_list.append(None) 70 | if root.right: 71 | walk(root.right, val_list) 72 | else: 73 | val_list.append(None) 74 | 75 | if not p and not q: 76 | return True 77 | elif (not p and q) or (not q and p): 78 | return False 79 | 80 | p_list = [] 81 | q_list = [] 82 | walk(p, p_list) 83 | walk(q, q_list) 84 | return p_list == q_list 85 | -------------------------------------------------------------------------------- /search-insert-position.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132355791/ 3 | 4 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 5 | 6 | You may assume no duplicates in the array. 7 | 8 | Example 1: 9 | 10 | Input: [1,3,5,6], 5 11 | Output: 2 12 | 13 | 14 | 15 | Example 2: 16 | 17 | Input: [1,3,5,6], 2 18 | Output: 1 19 | 20 | 21 | 22 | Example 3: 23 | 24 | Input: [1,3,5,6], 7 25 | Output: 4 26 | 27 | 28 | 29 | Example 1: 30 | 31 | Input: [1,3,5,6], 0 32 | Output: 0 33 | 34 | """ 35 | 36 | 37 | class Solution(object): 38 | def searchInsert(self, nums, target): 39 | """ 40 | :type nums: List[int] 41 | :type target: int 42 | :rtype: int 43 | """ 44 | if not nums: 45 | return 0 46 | if target in nums: 47 | return nums.index(target) 48 | for index, num in enumerate(nums): 49 | if num > target: 50 | return index 51 | return len(nums) 52 | -------------------------------------------------------------------------------- /single-number-ii.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149527154/ 3 | 4 | 5 | Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one. 6 | 7 | 8 | 9 | Note: 10 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 11 | """ 12 | 13 | 14 | class Solution: 15 | def singleNumber(self, nums): 16 | """ 17 | :type nums: List[int] 18 | :rtype: int 19 | """ 20 | total_sum = sum(nums) 21 | unique_sum = sum(set(nums)) 22 | other = (total_sum - unique_sum) / 2 23 | 24 | return int(unique_sum - other) 25 | -------------------------------------------------------------------------------- /sort-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/369690505/ 3 | 4 | Sort a linked list in O(n log n) time using constant space complexity. 5 | 6 | Example 1: 7 | 8 | 9 | Input: 4->2->1->3 10 | Output: 1->2->3->4 11 | 12 | 13 | Example 2: 14 | 15 | 16 | Input: -1->5->3->4->0 17 | Output: -1->0->3->4->5 18 | """ 19 | 20 | 21 | # Definition for singly-linked list. 22 | # class ListNode: 23 | # def __init__(self, val=0, next=None): 24 | # self.val = val 25 | # self.next = next 26 | class Solution: 27 | 28 | def merge(self, node1, node2): 29 | temp_node = temp_node_head = ListNode(0) 30 | while node1 and node2: 31 | if node1.val < node2.val: 32 | temp_node_head.next = node1 33 | node1 = node1.next 34 | else: 35 | temp_node_head.next = node2 36 | node2 = node2.next 37 | temp_node_head = temp_node_head.next 38 | temp_node_head.next = node1 or node2 39 | temp_node = temp_node.next 40 | return temp_node 41 | 42 | 43 | def sortList(self, head: ListNode) -> ListNode: 44 | if not head: 45 | return None 46 | if not head.next: 47 | return head 48 | 49 | slow = head 50 | fast = head 51 | 52 | while fast.next and fast.next.next: 53 | fast = fast.next.next 54 | slow = slow.next 55 | 56 | node_list_2_head = slow.next 57 | slow.next = None 58 | left = self.sortList(head) 59 | right = self.sortList(node_list_2_head) 60 | return self.merge(left, right) 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /sqrtx.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132357214/ 3 | 4 | Implement int sqrt(int x). 5 | 6 | Compute and return the square root of x. 7 | 8 | x is guaranteed to be a non-negative integer. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: 4 15 | Output: 2 16 | 17 | 18 | 19 | Example 2: 20 | 21 | Input: 8 22 | Output: 2 23 | Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated. 24 | 25 | """ 26 | 27 | 28 | class Solution(object): 29 | def mySqrt(self, x): 30 | """ 31 | :type x: int 32 | :rtype: int 33 | """ 34 | import math 35 | return int(math.sqrt(x)) 36 | -------------------------------------------------------------------------------- /sum-of-two-integers.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149517800/ 3 | 4 | Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 5 | 6 | Example: 7 | Given a = 1 and b = 2, return 3. 8 | 9 | 10 | Credits:Special thanks to @fujiaozhu for adding this problem and creating all test cases. 11 | 12 | I operate `a` and `b` really bit by bit. I know I can use `(a >> n) & 1` to get the bit of position n from right to left. But I dont do it because I find it is so strange to represent negative in Python. 13 | 14 | For example, number `-5` in Python is: 15 | 16 | ``` 17 | >>> bin(-5) 18 | '-0b101' 19 | ``` 20 | 21 | but what I need is `0b11111111111111111111111111111011`. However, when I shift `-5` bit to bit, the output looks correct: 22 | 23 | ``` 24 | >>> (-5) & 1 25 | 1 26 | >>> (-5 >> 1) & 1 27 | 1 28 | >>> (-5 >> 2) & 1 29 | 0 30 | >>> (-5 >> 3) & 1 31 | 1 32 | >>> (-5 >> 4) & 1 33 | 1 34 | >>> (-5 >> 5) & 1 35 | 1 36 | >>> (-5 >> 6) & 1 37 | 1 38 | >>> (-5 >> 7) & 1 39 | 1 40 | ``` 41 | looks from the output, `-5` in fact is `0b11111111111111111111111111111011`, but this may make people confused and hard to understand the 2-compliment for negative number. 42 | 43 | Therefore, I just use string type of binary number to finish this problem. 44 | 45 | I know the time is wasted in type transformtion, but It is more readable. 46 | """ 47 | 48 | 49 | class Solution: 50 | def getSum(self, a, b): 51 | """ 52 | :type a: int 53 | :type b: int 54 | :rtype: int 55 | """ 56 | def string_xor(s1, s2): 57 | return str(int(s1) ^ int(s2)) 58 | 59 | def string_and(s1, s2): 60 | if s1 == s2 and s1 == '1': 61 | return '1' 62 | return '0' 63 | 64 | def string_or(s1, s2): 65 | if s1 == '1' or s2 == '1': 66 | return '1' 67 | return '0' 68 | 69 | def add(a_bin, b_bin): 70 | flag = '0' 71 | result = [] 72 | for a_bit, b_bit in list(zip(a_bin, b_bin))[::-1]: 73 | bit_sum = string_xor(string_xor(a_bit, b_bit), flag) 74 | result.insert(0, bit_sum) 75 | flag = string_or(string_or(string_and(a_bit, b_bit), string_and(a_bit, flag)), string_and(b_bit, flag)) 76 | return ''.join(result) 77 | 78 | def reverse(n_bit): 79 | s = [] 80 | for bit in n_bit: 81 | s.append('0' if bit == '1' else '1') 82 | return ''.join(s) 83 | 84 | def left_pad(n): 85 | result = [] 86 | if n >= 0: 87 | n_bin = bin(n)[2:] 88 | else: 89 | n_bin = add(reverse(left_pad(abs(n))), left_pad(1)) 90 | result = ['0'] * (32 - len(n_bin)) 91 | result.append(n_bin) 92 | return ''.join(result) 93 | 94 | a_bin = left_pad(a) 95 | b_bin = left_pad(b) 96 | result = add(a_bin, b_bin) 97 | if result[0] == '0': 98 | return int(result, 2) 99 | result = add(reverse(result), left_pad(1)) 100 | return -int(result, 2) 101 | -------------------------------------------------------------------------------- /sum-root-to-leaf-numbers.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149683420/ 3 | 4 | Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 5 | 6 | An example is the root-to-leaf path 1->2->3 which represents the number 123. 7 | 8 | Find the total sum of all root-to-leaf numbers. 9 | 10 | For example, 11 | 12 | 13 | 1 14 | / \ 15 | 2 3 16 | 17 | 18 |   19 | 20 | The root-to-leaf path 1->2 represents the number 12. 21 | The root-to-leaf path 1->3 represents the number 13. 22 | 23 | Return the sum = 12 + 13 = 25. 24 | """ 25 | 26 | 27 | # Definition for a binary tree node. 28 | # class TreeNode: 29 | # def __init__(self, x): 30 | # self.val = x 31 | # self.left = None 32 | # self.right = None 33 | 34 | class Solution: 35 | def sumNumbers(self, root): 36 | """ 37 | :type root: TreeNode 38 | :rtype: int 39 | """ 40 | if not root: 41 | return 0 42 | all_path = [] 43 | self.walk(root, [], all_path) 44 | s = 0 45 | for path in all_path: 46 | num = int(''.join(path)) 47 | s += num 48 | return s 49 | 50 | def walk(self, node, current, result): 51 | current.append(str(node.val)) 52 | left = node.left 53 | right = node.right 54 | if not left and not right: 55 | result.append(current) 56 | if left: 57 | self.walk(left, current.copy(), result) 58 | if right: 59 | self.walk(right, current.copy(), result) 60 | 61 | -------------------------------------------------------------------------------- /symmetric-tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147352422/ 3 | 4 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 5 | 6 | 7 | For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 8 | 9 | 1 10 | / \ 11 | 2 2 12 | / \ / \ 13 | 3 4 4 3 14 | 15 | 16 | 17 | But the following [1,2,2,null,3,null,3] is not: 18 | 19 | 1 20 | / \ 21 | 2 2 22 | \ \ 23 | 3 3 24 | 25 | 26 | 27 | 28 | Note: 29 | Bonus points if you could solve it both recursively and iteratively. 30 | """ 31 | 32 | 33 | # Definition for a binary tree node. 34 | # class TreeNode: 35 | # def __init__(self, x): 36 | # self.val = x 37 | # self.left = None 38 | # self.right = None 39 | 40 | class Solution: 41 | def isSymmetric(self, root): 42 | """ 43 | :type root: TreeNode 44 | :rtype: bool 45 | """ 46 | def is_mirror(left_node, right_node): 47 | if left_node is None and right_node is None: 48 | return True 49 | if not left_node or not right_node: 50 | return False 51 | return left_node.val == right_node.val and is_mirror(left_node.left, right_node.right) and is_mirror(left_node.right, right_node.left) 52 | 53 | 54 | if not root: 55 | return True 56 | return is_mirror(root.left, root.right) -------------------------------------------------------------------------------- /symmetric-tree_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147348992/ 3 | 4 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 5 | 6 | 7 | For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 8 | 9 | 1 10 | / \ 11 | 2 2 12 | / \ / \ 13 | 3 4 4 3 14 | 15 | 16 | 17 | But the following [1,2,2,null,3,null,3] is not: 18 | 19 | 1 20 | / \ 21 | 2 2 22 | \ \ 23 | 3 3 24 | 25 | 26 | 27 | 28 | Note: 29 | Bonus points if you could solve it both recursively and iteratively. 30 | """ 31 | 32 | 33 | # Definition for a binary tree node. 34 | # class TreeNode: 35 | # def __init__(self, x): 36 | # self.val = x 37 | # self.left = None 38 | # self.right = None 39 | 40 | class Solution: 41 | def isSymmetric(self, root): 42 | """ 43 | :type root: TreeNode 44 | :rtype: bool 45 | """ 46 | if not root: 47 | return True 48 | new_lower_level = [] 49 | lower_level = [root] 50 | count = 1 51 | while True: 52 | level_val = [None] * (2 ** count) 53 | count += 1 54 | for index, x in enumerate(lower_level): 55 | level_val[index * 2] = x.left.val if x and x.left else None 56 | level_val[index * 2 + 1] = x.right.val if x and x.right else None 57 | if level_val != level_val[::-1]: 58 | return False 59 | 60 | for level in lower_level: 61 | new_lower_level.append(level.left if level else None) 62 | new_lower_level.append(level.right if level else None) 63 | 64 | if not any(new_lower_level): 65 | return True 66 | lower_level = new_lower_level.copy() 67 | new_lower_level = [] -------------------------------------------------------------------------------- /two-sum-ii-input-array-is-sorted.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/147485769/ 3 | 4 | Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 5 | 6 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. 7 | 8 | You may assume that each input would have exactly one solution and you may not use the same element twice. 9 | 10 | 11 | Input: numbers={2, 7, 11, 15}, target=9 12 | Output: index1=1, index2=2 13 | """ 14 | 15 | 16 | class Solution: 17 | def twoSum(self, numbers, target): 18 | """ 19 | :type numbers: List[int] 20 | :type target: int 21 | :rtype: List[int] 22 | """ 23 | index_dict = {} 24 | nums = [] 25 | for index, num in enumerate(numbers): 26 | if num in index_dict: 27 | index_dict[num][1] += 1 28 | else: 29 | index_dict[num] = [index, 1] 30 | nums.append(num) 31 | for num in nums: 32 | another = target - num 33 | if num != another and another in index_dict: 34 | return [index_dict[num][0] + 1, index_dict[another][0] + 1] 35 | if num == another and index_dict[another][1] > 1: 36 | return [index_dict[num][0] + 1, index_dict[num][0] + 2] 37 | -------------------------------------------------------------------------------- /two-sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/82612803/ 3 | 4 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 5 | 6 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 7 | 8 | 9 | Example: 10 | 11 | Given nums = [2, 7, 11, 15], target = 9, 12 | 13 | Because nums[0] + nums[1] = 2 + 7 = 9, 14 | return [0, 1]. 15 | 16 | """ 17 | 18 | 19 | class Solution(object): 20 | def twoSum(self, nums, target): 21 | """ 22 | :type nums: List[int] 23 | :type target: int 24 | :rtype: List[int] 25 | """ 26 | for i in range(len(nums)): 27 | for k in range(i+1, len(nums)): 28 | if nums[i] + nums[k] == target: 29 | return [i, k] 30 | -------------------------------------------------------------------------------- /ugly-number.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149193813/ 3 | 4 | Write a program to check whether a given number is an ugly number. 5 | 6 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 7 | 8 | Note: 9 | 10 | 11 | 1 is typically treated as an ugly number. 12 | Input is within the 32-bit signed integer range. 13 | 14 | 15 | 16 | Credits: 17 | Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 18 | """ 19 | 20 | 21 | class Solution: 22 | def isUgly(self, num): 23 | """ 24 | :type num: int 25 | :rtype: bool 26 | """ 27 | if num == 1: 28 | return True 29 | if num <= 0: 30 | return False 31 | for n in [2, 3, 5]: 32 | if num % n == 0: 33 | return self.isUgly(num / n) 34 | return False -------------------------------------------------------------------------------- /unique-binary-search-trees.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/366551160/ 3 | 4 | Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? 5 | 6 | Example: 7 | 8 | 9 | Input: 3 10 | Output: 5 11 | Explanation: 12 | Given n = 3, there are a total of 5 unique BST's: 13 | 14 | 1 3 3 2 1 15 | \ / / / \ \ 16 | 3 2 1 1 3 2 17 | / / \ \ 18 | 2 1 2 3 19 | 20 | """ 21 | 22 | 23 | class Solution: 24 | def numTrees(self, n: int) -> int: 25 | 26 | from functools import lru_cache 27 | 28 | @lru_cache 29 | def count(num): 30 | if num <= 1: 31 | return 1 32 | if num == 2: 33 | return 2 34 | tree_count = 0 35 | for i in range(num): 36 | tree_count += count(i) * count(num - i - 1) 37 | return tree_count 38 | tree_count = count(n) 39 | return tree_count 40 | -------------------------------------------------------------------------------- /unique-binary-search-trees_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/366544583/ 3 | 4 | Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? 5 | 6 | Example: 7 | 8 | 9 | Input: 3 10 | Output: 5 11 | Explanation: 12 | Given n = 3, there are a total of 5 unique BST's: 13 | 14 | 1 3 3 2 1 15 | \ / / / \ \ 16 | 3 2 1 1 3 2 17 | / / \ \ 18 | 2 1 2 3 19 | 20 | """ 21 | 22 | 23 | class Solution: 24 | def numTrees(self, n: int) -> int: 25 | from functools import lru_cache 26 | 27 | @lru_cache 28 | def count(num_list): 29 | if len(num_list) <= 1: 30 | return 1 31 | if len(num_list) == 2: 32 | return 2 33 | tree_count = 0 34 | for index, root_node in enumerate(num_list): 35 | tree_count += count(num_list[: index]) * count(num_list[index + 1:]) 36 | return tree_count 37 | full_num_list = tuple(range(1, n + 1)) 38 | if n <= 2: 39 | return count(full_num_list) 40 | tree_count = count(full_num_list) 41 | return tree_count 42 | -------------------------------------------------------------------------------- /valid-parentheses.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132287314/ 3 | 4 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 5 | 6 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 7 | """ 8 | 9 | 10 | class Solution(object): 11 | def isValid(self, s): 12 | """ 13 | :type s: str 14 | :rtype: bool 15 | """ 16 | if not s: 17 | return False 18 | 19 | quote_dict = {')': '(', ']': '[', '}': '{'} 20 | rebuild = '' 21 | for char in s: 22 | if char in ['(', '[', '{']: 23 | rebuild += char 24 | elif char in [')', ']', '}']: 25 | if rebuild and rebuild[-1] == quote_dict[char]: 26 | rebuild = rebuild[:-1] 27 | else: 28 | return False 29 | if not rebuild: 30 | return True 31 | return False 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /valid-parentheses_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132287271/ 3 | 4 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 5 | 6 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 7 | """ 8 | 9 | 10 | class Solution(object): 11 | def isValid(self, s): 12 | """ 13 | :type s: str 14 | :rtype: bool 15 | """ 16 | if not s: 17 | return False 18 | 19 | quote_dict = {')': '(', ']': '[', '}': '{'} 20 | rebuild = '' 21 | for char in s: 22 | if char in ['(', '[', '{']: 23 | rebuild += char 24 | elif char in [')', ']', '}']: 25 | if rebuild and rebuild[-1] == quote_dict[char]: 26 | rebuild = rebuild[:-1] 27 | else: 28 | return False 29 | if not rebuild: 30 | return True 31 | return False 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /valid-perfect-square.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149523727/ 3 | 4 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 5 | 6 | 7 | Note: Do not use any built-in library function such as sqrt. 8 | 9 | 10 | Example 1: 11 | 12 | Input: 16 13 | Returns: True 14 | 15 | 16 | 17 | Example 2: 18 | 19 | Input: 14 20 | Returns: False 21 | 22 | 23 | 24 | Credits:Special thanks to @elmirap for adding this problem and creating all test cases.""" 25 | 26 | 27 | class Solution: 28 | def isPerfectSquare(self, num): 29 | """ 30 | :type num: int 31 | :rtype: bool 32 | """ 33 | if num == 1: 34 | return True 35 | count = 1 36 | x = num 37 | last_x = num 38 | while True: 39 | x = x - x / 2 + num / 2 / x 40 | if last_x == int(x): 41 | return False 42 | if int(x) ** 2 == num: 43 | return True 44 | count += 1 45 | last_x = int(x) 46 | -------------------------------------------------------------------------------- /valid-perfect-square_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/149522619/ 3 | 4 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 5 | 6 | 7 | Note: Do not use any built-in library function such as sqrt. 8 | 9 | 10 | Example 1: 11 | 12 | Input: 16 13 | Returns: True 14 | 15 | 16 | 17 | Example 2: 18 | 19 | Input: 14 20 | Returns: False 21 | 22 | 23 | 24 | Credits:Special thanks to @elmirap for adding this problem and creating all test cases.""" 25 | 26 | 27 | class Solution: 28 | def isPerfectSquare(self, num): 29 | """ 30 | :type num: int 31 | :rtype: bool 32 | """ 33 | if num == 1: 34 | return True 35 | for i in range(1, num // 2 + 1): 36 | if i ** 2 == num: 37 | return True 38 | elif i ** 2 > num: 39 | return False 40 | return False 41 | -------------------------------------------------------------------------------- /word-ladder.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/151507325/ 3 | 4 | Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: 5 | 6 | 7 | Only one letter can be changed at a time. 8 | Each transformed word must exist in the word list. Note that beginWord is not a transformed word. 9 | 10 | 11 | Note: 12 | 13 | 14 | Return 0 if there is no such transformation sequence. 15 | All words have the same length. 16 | All words contain only lowercase alphabetic characters. 17 | You may assume no duplicates in the word list. 18 | You may assume beginWord and endWord are non-empty and are not the same. 19 | 20 | 21 | Example 1: 22 | 23 | 24 | Input: 25 | beginWord = "hit", 26 | endWord = "cog", 27 | wordList = ["hot","dot","dog","lot","log","cog"] 28 | 29 | Output: 5 30 | 31 | Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", 32 | return its length 5. 33 | 34 | 35 | Example 2: 36 | 37 | 38 | Input: 39 | beginWord = "hit" 40 | endWord = "cog" 41 | wordList = ["hot","dot","dog","lot","log"] 42 | 43 | Output: 0 44 | 45 | Explanation: The endWord "cog" is not in wordList, therefore no possible transformation. 46 | 47 | 48 | 49 | 50 | """ 51 | 52 | 53 | class Solution: 54 | def ladderLength(self, beginWord, endWord, wordList): 55 | """ 56 | :type beginWord: str 57 | :type endWord: str 58 | :type wordList: List[str] 59 | :rtype: int 60 | """ 61 | wordSet = set(wordList) 62 | if endWord not in wordSet: 63 | return 0 64 | wordSet.discard(beginWord) 65 | taskQueue = [(beginWord, 1)] 66 | while taskQueue: 67 | begin, path = taskQueue.pop(0) 68 | if begin == endWord: 69 | return path 70 | for i in range(len(begin)): 71 | for k in 'qwertyuiopasdfghjklzxcvbnm': 72 | nextWord = begin[:i] + k + begin[i + 1:] 73 | if nextWord in wordSet: 74 | wordSet.discard(nextWord) 75 | taskQueue.append((nextWord, path + 1)) 76 | return 0 -------------------------------------------------------------------------------- /word-pattern.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/submissions/detail/132289433/ 3 | 4 | Given a pattern and a string str, find if str follows the same pattern. 5 | Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. 6 | 7 | Examples: 8 | 9 | pattern = "abba", str = "dog cat cat dog" should return true. 10 | pattern = "abba", str = "dog cat cat fish" should return false. 11 | pattern = "aaaa", str = "dog cat cat dog" should return false. 12 | pattern = "abba", str = "dog dog dog dog" should return false. 13 | 14 | 15 | 16 | 17 | Notes: 18 | You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space. 19 | 20 | 21 | Credits:Special thanks to @minglotus6 for adding this problem and creating all test cases.""" 22 | 23 | 24 | class Solution(object): 25 | def wordPattern(self, pattern, str): 26 | """ 27 | :type pattern: str 28 | :type str: str 29 | :rtype: bool 30 | """ 31 | word = str.split(' ') 32 | pattern_list = list(pattern) 33 | 34 | if len(word) != len(pattern_list): 35 | return False 36 | 37 | pair_list = zip(pattern_list, word) 38 | pair_dict = {} 39 | for pair in pair_list: 40 | if pair[0] in pair_dict: 41 | pair_dict[pair[0]].append(pair[1]) 42 | else: 43 | pair_dict[pair[0]] = [pair[1]] 44 | comman_list = [] 45 | for v in pair_dict.values(): 46 | if len(set(v)) != 1: 47 | return False 48 | comman_list.append(v[0]) 49 | if len(comman_list) != len(set(comman_list)): 50 | return False 51 | return True 52 | --------------------------------------------------------------------------------