├── Python ├── .vscode │ └── settings.json ├── Easy │ ├── 1. Two Sum.py │ ├── 100. Same Tree.py │ ├── 1002. Find Common Characters.py │ ├── 101. Symmetric Tree.py │ ├── 104. Maximum Depth of Binary Tree.py │ ├── 1047. Remove All Adjacent Duplicates In String.py │ ├── 107. Binary Tree Level Order Traversal II.py │ ├── 108. Convert Sorted Array to Binary Search Tree.py │ ├── 1086. High Five.py │ ├── 110. Balanced Binary Tree.py │ ├── 1108. Defanging an IP Address.py │ ├── 111. Minimum Depth of Binary Tree.py │ ├── 112. Path Sum.py │ ├── 1122. Relative Sort Array.py │ ├── 1160. Find Words That Can Be Formed by Characters.py │ ├── 118. Pascal's Triangle.py │ ├── 119. Pascal's Triangle II.py │ ├── 121. Best Time to Buy and Sell Stock.py │ ├── 122. Best Time to Buy and Sell Stock II.py │ ├── 1221. Split a String in Balanced Strings.py │ ├── 125. Valid Palindrome.py │ ├── 1281. Subtract the Product and Sum of Digits of an Integer.py │ ├── 13. Roman to Integer.py │ ├── 136. Single Number.py │ ├── 14. Longest Common Prefix.py │ ├── 141. Linked List Cycle.py │ ├── 155. Min Stack.py │ ├── 160. Intersection of Two Linked Lists.py │ ├── 163. Missing Ranges.py │ ├── 167. Two Sum II - Input array is sorted.py │ ├── 168. Excel Sheet Column Title.py │ ├── 169. Majority Element.py │ ├── 171. Excel Sheet Column Number.py │ ├── 172. Factorial Trailing Zeroes.py │ ├── 190. Reverse Bits.py │ ├── 191. Number of 1 Bits.py │ ├── 198. House Robber.py │ ├── 20. Valid Parentheses.py │ ├── 202. Happy Number.py │ ├── 203. Remove Linked List Elements.py │ ├── 204. Count Primes.py │ ├── 205. Isomorphic Strings.py │ ├── 21. Merge Two Sorted Lists.py │ ├── 217. Contains Duplicate.py │ ├── 219. Contains Duplicate II.py │ ├── 225. Implement Stack using Queues.py │ ├── 226. Invert Binary Tree.py │ ├── 228. Summary Ranges.py │ ├── 231. Power of Two.py │ ├── 232. Implement Queue using Stacks.py │ ├── 235. Lowest Common Ancestor of a Binary Search Tree.py │ ├── 243. Shortest Word Distance.py │ ├── 246. Strobogrammatic Number.py │ ├── 252. Meeting Rooms.py │ ├── 256. Paint House.py │ ├── 257. Binary Tree Paths.py │ ├── 258. Add Digits.py │ ├── 26. Remove Duplicates from Sorted Array.py │ ├── 263. Ugly Number.py │ ├── 266. Palindrome Permutation.py │ ├── 268. Missing Number.py │ ├── 27. Remove Element.py │ ├── 270. Closest Binary Search Tree Value.py │ ├── 276. Paint Fence.py │ ├── 278. First Bad Version.py │ ├── 28. Implement strStr().py │ ├── 283. Move Zeroes.py │ ├── 290. Word Pattern.py │ ├── 292. Nim Game.py │ ├── 293. Flip Game.py │ ├── 339. Nested List Weight Sum.py │ ├── 344. Reverse String.py │ ├── 346. Moving Average from Data Stream.py │ ├── 35. Search Insert Position.py │ ├── 359. Logger Rate Limiter.py │ ├── 38. Count and Say.py │ ├── 404. Sum of Left Leaves.py │ ├── 408. Valid Word Abbreviation.py │ ├── 448. Find All Numbers Disappeared in an Array.py │ ├── 453. Minimum Moves to Equal Array Elements.py │ ├── 459. Repeated Substring Pattern.py │ ├── 463. Island Perimeter.py │ ├── 496. Next Greater Element I.py │ ├── 509. Fibonacci Number.py │ ├── 516. Longest Palindromic Subsequence.py │ ├── 53. Maximum Subarray.py │ ├── 543. Diameter of Binary Tree.py │ ├── 557. Reverse Words in a String III.py │ ├── 561. Array Partition I.py │ ├── 58. Length of Last Word.py │ ├── 617. Merge Two Binary Trees.py │ ├── 669. Trim a Binary Search Tree.py │ ├── 67. Add Binary.py │ ├── 69. Sqrt(x).py │ ├── 7. Reverse Integer.py │ ├── 70. Climbing Stairs.py │ ├── 700. Search in a Binary Search Tree.py │ ├── 709. To Lower Case.py │ ├── 771. Jewels and Stones.py │ ├── 821. Shortest Distance to a Character.py │ ├── 83. Remove Duplicates from Sorted List.py │ ├── 852. Peak Index in a Mountain Array.py │ ├── 876. Middle of the Linked List.py │ ├── 88. Merge Sorted Array.py │ ├── 9. Palindrome Number.py │ ├── 905. Sort Array By Parity.py │ ├── 938. Range Sum of BST.py │ └── 977. Squares of a Sorted Array.py ├── Hard │ ├── 124. Binary Tree Maximum Path Sum.py │ ├── 126. Word Ladder II.py │ ├── 140. Word Break II.py │ ├── 154. Find Minimum in Rotated Sorted Array II.py │ ├── 1771. Maximize Palindrome Length From Subsequences.py │ ├── 212. Word Search II.py │ ├── 23. Merge k Sorted Lists.py │ ├── 239. Sliding Window Maximum.py │ ├── 265. Paint House II.py │ ├── 297. Serialize and Deserialize Binary Tree.py │ ├── 30. Substring with Concatenation of All Words.py │ ├── 41. First Missing Positive.py │ ├── 42. Trapping Rain Water.py │ ├── 57. Insert Interval.py │ ├── 65. Valid Number.py │ ├── 685. Redundant Connection II.py │ ├── 759. Employee Free Time.py │ ├── 76. Minimum Window Substring.py │ └── 84. Largest Rectangle in Histogram.py ├── Medium │ ├── 102. Binary Tree Level Order Traversal.py │ ├── 103. Binary Tree Zigzag Level Order Traversal.py │ ├── 105. Construct Binary Tree from Preorder and Inorder Traversal.py │ ├── 106. Construct Binary Tree from Inorder and Postorder Traversal.py │ ├── 109. Convert Sorted List to Binary Search Tree.py │ ├── 11. Container With Most Water.py │ ├── 113. Path Sum II.py │ ├── 114. Flatten Binary Tree to Linked List.py │ ├── 116. Populating Next Right Pointers in Each Node.py │ ├── 117. Populating Next Right Pointers in Each Node II.py │ ├── 12. Integer to Roman.py │ ├── 120. Triangle.py │ ├── 127. Word Ladder.py │ ├── 129. Sum Root to Leaf Numbers.py │ ├── 130. Surrounded Regions.py │ ├── 131. Palindrome Partitioning.py │ ├── 133. Clone Graph.py │ ├── 134. Gas Station.py │ ├── 1353. Maximum Number of Events That Can Be Attended.py │ ├── 137. Single Number II.py │ ├── 138. Copy List with Random Pointer.py │ ├── 139. Word Break.py │ ├── 142. Linked List Cycle II.py │ ├── 143. Reorder List.py │ ├── 144. Binary Tree Preorder Traversal.py │ ├── 145. Binary Tree Postorder Traversal.py │ ├── 146. LRU Cache.py │ ├── 147. Insertion Sort List.py │ ├── 148. Sort List.py │ ├── 15. 3Sum.py │ ├── 150. Evaluate Reverse Polish Notation.py │ ├── 152. Maximum Product Subarray.py │ ├── 153. Find Minimum in Rotated Sorted Array.py │ ├── 156. Binary Tree Upside Down.py │ ├── 159. Longest Substring with At Most Two Distinct Characters.py │ ├── 16. 3Sum Closest.py │ ├── 161. One Edit Distance.py │ ├── 162. Find Peak Element.py │ ├── 165. Compare Version Numbers.py │ ├── 17. Letter Combinations of a Phone Number.py │ ├── 173. Binary Search Tree Iterator.py │ ├── 1770. Maximum Score from Performing Multiplication Operations.py │ ├── 179. Largest Number.py │ ├── 18. 4Sum.py │ ├── 186. Reverse Words in a String II.py │ ├── 187. Repeated DNA Sequences.py │ ├── 19. Remove Nth Node From End of List.py │ ├── 198. House Robber.py │ ├── 199. Binary Tree Right Side View.py │ ├── 2. Add Two Numbers.py │ ├── 200. Number of Islands.py │ ├── 201. Bitwise AND of Numbers Range.py │ ├── 207. Course Schedule.py │ ├── 208. Implement Trie (Prefix Tree).py │ ├── 209. Minimum Size Subarray Sum.py │ ├── 210. Course Schedule II.py │ ├── 213. House Robber II.py │ ├── 215. Kth Largest Element in an Array.py │ ├── 216. Combination Sum III.py │ ├── 22. Generate Parentheses.py │ ├── 220. Contains Duplicate III.py │ ├── 221. Maximal Square.py │ ├── 222. Count Complete Tree Nodes.py │ ├── 223. Rectangle Area.py │ ├── 227. Basic Calculator II.py │ ├── 229. Majority Element II.py │ ├── 230. Kth Smallest Element in a BST.py │ ├── 236. Lowest Common Ancestor of a Binary Tree.py │ ├── 238. Product of Array Except Self.py │ ├── 24. Swap Nodes in Pairs.py │ ├── 240. Search a 2D Matrix II.py │ ├── 241. Different Ways to Add Parentheses.py │ ├── 244. Shortest Word Distance II.py │ ├── 245. Shortest Word Distance III.py │ ├── 247. Strobogrammatic Number II.py │ ├── 249. Group Shifted Strings.py │ ├── 250. Count Univalue Subtrees.py │ ├── 251. Flatten 2D Vector.py │ ├── 253. Meeting Rooms II.py │ ├── 254. Factor Combinations.py │ ├── 255. Verify Preorder Sequence in Binary Search Tree.py │ ├── 256. Paint House.py │ ├── 259. 3Sum Smaller.py │ ├── 260. Single Number III.py │ ├── 261. Graph Valid Tree.py │ ├── 264. Ugly Number II.py │ ├── 267. Palindrome Permutation II.py │ ├── 271. Encode and Decode Strings.py │ ├── 274. H-Index.py │ ├── 275. H-Index II.py │ ├── 277. Find the Celebrity.py │ ├── 279. Perfect Squares.py │ ├── 280. Wiggle Sort.py │ ├── 281. Zigzag Iterator.py │ ├── 284. Peeking Iterator.py │ ├── 285. Inorder Successor in BST.py │ ├── 286. Walls and Gates.py │ ├── 287. Find the Duplicate Number.py │ ├── 288. Unique Word Abbreviation.py │ ├── 289. Game of Life.py │ ├── 29. Divide Two Integers.py │ ├── 294. Flip Game II.py │ ├── 298. Binary Tree Longest Consecutive Sequence.py │ ├── 3. Longest Substring Without Repeating Characters.py │ ├── 300. Longest Increasing Subsequence.py │ ├── 305. Number of Islands II.py │ ├── 31. Next Permutation.py │ ├── 322. Coin Change.py │ ├── 33. Search in Rotated Sorted Array.py │ ├── 337. House Robber III.py │ ├── 338. Counting Bits.py │ ├── 34. Find First and Last Position of Element in Sorted Array.py │ ├── 340. Longest Substring with At Most K Distinct Characters.py │ ├── 347. Top K Frequent Elements.py │ ├── 36. Valid Sudoku.py │ ├── 378. Kth Smallest Element in a Sorted Matri.py │ ├── 39. Combination Sum.py │ ├── 394. Decode String.py │ ├── 399. Evaluate Division.py │ ├── 40. Combination Sum II.py │ ├── 400. Nth Digit.py │ ├── 402. Remove K Digits.py │ ├── 416. Partition Equal Subset Sum.py │ ├── 43. Multiply Strings.py │ ├── 435. Non-overlapping Intervals.py │ ├── 436. Find Right Interval.py │ ├── 437. Path Sum III.py │ ├── 438. Find All Anagrams in a String.py │ ├── 442. Find All Duplicates in an Array.py │ ├── 449. Serialize and Deserialize BST.py │ ├── 450. Delete Node in a BST.py │ ├── 451. Sort Characters By Frequency.py │ ├── 452. Minimum Number of Arrows to Burst Balloons.py │ ├── 454. 4Sum II.py │ ├── 46. Permutations.py │ ├── 462. Minimum Moves to Equal Array Elements II.py │ ├── 47. Permutations II.py │ ├── 48. Rotate Image.py │ ├── 49. Group Anagrams.py │ ├── 494. Target Sum.py │ ├── 498. Diagonal Traverse.py │ ├── 5. Longest Palindromic Substring.py │ ├── 50. Pow(x, n).py │ ├── 503. Next Greater Element II.py │ ├── 516. Longest Palindromic Subsequence.py │ ├── 54. Spiral Matrix.py │ ├── 55. Jump Game.py │ ├── 556. Next Greater Element III.py │ ├── 56. Merge Intervals.py │ ├── 560. Subarray Sum Equals K.py │ ├── 581. Shortest Unsorted Continuous Subarray.py │ ├── 59. Spiral Matrix II.py │ ├── 6. ZigZag Conversion.py │ ├── 60. Permutation Sequence.py │ ├── 61. Rotate List.py │ ├── 611. Valid Triangle Number.py │ ├── 62. Unique Paths.py │ ├── 621. Task Scheduler.py │ ├── 63. Unique Paths II.py │ ├── 64. Minimum Path Sum.py │ ├── 647. Palindromic Substrings.py │ ├── 677. Map Sum Pairs.py │ ├── 680. Valid Palindrome II.py │ ├── 684. Redundant Connection.py │ ├── 71. Simplify Path.py │ ├── 721. Accounts Merge.py │ ├── 73. Set Matrix Zeroes.py │ ├── 737. Sentence Similarity II.py │ ├── 739. Daily Temperatures.py │ ├── 74. Search a 2D Matrix.py │ ├── 75. Sort Colors.py │ ├── 763. Partition Labels.py │ ├── 77. Combinations.py │ ├── 78. Subsets.py │ ├── 79. Word Search.py │ ├── 8. String to Integer (atoi).py │ ├── 80. Remove Duplicates from Sorted Array II.py │ ├── 81. Search in Rotated Sorted Array II.py │ ├── 82. Remove Duplicates from Sorted List II.py │ ├── 86. Partition List.py │ ├── 863. All Nodes Distance K in Binary Tree.py │ ├── 89. Gray Code.py │ ├── 90. Subsets II.py │ ├── 91. Decode Ways.py │ ├── 92. Reverse Linked List II.py │ ├── 93. Restore IP Addresses.py │ ├── 94. Binary Tree Inorder Traversal.py │ ├── 95. Unique Binary Search Trees II.py │ ├── 96. Unique Binary Search Trees.py │ ├── 98. Validate Binary Search Tree.py │ └── 986. Interval List Intersections.py └── readme.md ├── README.md └── SQL ├── Easy ├── 1068. Product Sales Analysis I.sql ├── 1142. User Activity for the Past 30 Days II.sql ├── 1251. Average Selling Price.sql ├── 1350. Students With Invalid Departments.sql ├── 176. Second Highest Salary.sql ├── 182. Duplicate Emails.sql ├── 196. Delete Duplicate Emails.sql ├── 197. Rising Temperature.sql ├── 597. Friend Requests I - Overall Acceptance Rate.sql ├── 603. Consecutive Available Seats.sql └── 610. Triangle Judgement.sql ├── Hard ├── 1097. Game Play Analysis V.sql ├── 1127. User Purchase Platform.sql ├── 1159. Market Analysis II.sql ├── 1194. Tournament Winners.sql ├── 1225. Report Contiguous Dates.sql ├── 1412. Find the Quiet Students in All Exams.sql ├── 1479. Sales by Day of the Week.sql ├── 262. Trips and Users.sql ├── 569. Median Employee Salary.sql ├── 571. Find Median Given Frequency of Numbers.sql ├── 579. Find Cumulative Salary of an Employee.sql ├── 601. Human Traffic of Stadium.sql ├── 615. Average Salary Departments VS Company.sql └── 618. Students Report By Geography.sql ├── Medium ├── 1045. Customers Who Bought All Products.sql ├── 1077. Project Employees III.sql ├── 1098. Unpopular Books.sql ├── 1112. Highest Grade For Each Student.sql ├── 1132. Reported Posts II.sql ├── 1158. Market Analysis I.sql ├── 1164. Product Price at a Given Date.sql ├── 1193. Monthly Transactions I.sql ├── 1212. Team Scores in Football Tournament.sql ├── 1270. All People Report to the Given Manager.sql ├── 1321. Restaurant Growth.sql ├── 1341. Movie Rating.sql ├── 1355. Activity Participants.sql ├── 1369. Get the Second Most Recent Activity.sql ├── 1393. Capital Gain Loss.sql ├── 1398. Customers Who Bought Products A and B but Not C.sql ├── 1421. NPV Queries.sql ├── 1445. Apples & Oranges.sql ├── 1454. Active Users.sql ├── 1501. Countries You Can Safely Invest In.sql ├── 1532. The Most Recent Three Orders.sql ├── 1549. The Most Recent Orders for Each Product.sql ├── 180. Consecutive Numbers.sql ├── 184. Department Highest Salary.sql ├── 534. Game Play Analysis III.sql ├── 550. Game Play Analysis IV.sql ├── 570. Managers with at Least 5 Direct Reports.sql ├── 574. Winning Candidate.sql ├── 602. Friend Requests II -- Who Has the Most Friends.sql ├── 608. Tree Node.sql ├── 612. Shortest Distance in a Plane.sql ├── 614. Second Degree Follower.sql └── 626. Exchange Seats.sql └── readme.md /Python/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "C:\\programs\\Anaconda3\\python.exe" 3 | } -------------------------------------------------------------------------------- /Python/Easy/1. Two Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | h = {} 4 | for i, num in enumerate(nums): 5 | if target-num in h: 6 | return [h[target-num],i] 7 | else: 8 | h[num]=i 9 | -------------------------------------------------------------------------------- /Python/Easy/100. Same Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: 9 | if not p and not q: 10 | return True 11 | if ( p and not q ) or (q and not p): 12 | return False 13 | if p.val != q.val: 14 | return False 15 | 16 | 17 | return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 18 | 19 | -------------------------------------------------------------------------------- /Python/Easy/1002. Find Common Characters.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def commonChars(self, A: List[str]) -> List[str]: 4 | n = Counter(A[0]) 5 | ans = [] 6 | for a in A[1:]: 7 | n = n & Counter(a) 8 | for i in n: 9 | ans.extend([i]*n[i]) 10 | return ans 11 | # retrun list(n.elements()) 12 | 13 | #without Counter 14 | def commonChars(self,A): 15 | check = list(A[0]) 16 | for word in A: 17 | newCheck = [] 18 | for c in word: 19 | if c in check: 20 | newCheck.append(c) 21 | check.remove(c) 22 | check = newCheck 23 | 24 | return check -------------------------------------------------------------------------------- /Python/Easy/101. Symmetric Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def isSymmetric(self, root: TreeNode) -> bool: 10 | if not root: 11 | return True 12 | return self.symmetric(root.left, root.right) 13 | 14 | def symmetric(self, left, right): 15 | if not left and not right: 16 | return True 17 | elif (not left and right) or (not right and left): 18 | return False 19 | 20 | elif left.val != right.val: 21 | return False 22 | 23 | res = self.symmetric(left.left, right.right) and self.symmetric(left.right, right.left) 24 | 25 | return res 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Python/Easy/104. Maximum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def maxDepth(self, root: TreeNode) -> int: 10 | if not root: 11 | return 0 12 | 13 | return 1 + max(self.maxDepth(root.left),self.maxDepth(root.right)) 14 | 15 | #without using recursive 16 | def maxDepth(self, root): 17 | """ 18 | :type root: TreeNode 19 | :rtype: int 20 | """ 21 | depth = 0 22 | level = [root] if root else [] 23 | while level: 24 | depth += 1 25 | queue = [] 26 | for el in level: 27 | if el.left: 28 | queue.append(el.left) 29 | if el.right: 30 | queue.append(el.right) 31 | level = queue 32 | 33 | return depth -------------------------------------------------------------------------------- /Python/Easy/1047. Remove All Adjacent Duplicates In String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, S: str) -> str: 3 | ans = [] 4 | for c in S: 5 | if ans and ans[-1] == c: 6 | ans.pop() 7 | else: 8 | ans.append(c) 9 | 10 | return "".join(ans) -------------------------------------------------------------------------------- /Python/Easy/107. Binary Tree Level Order Traversal II.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: 9 | if not root: 10 | return [] 11 | tmp = deque([root]) 12 | res = [] 13 | while tmp: 14 | cur_res = [] 15 | for i in range(len(tmp)): 16 | cur = tmp.popleft() 17 | cur_res.append(cur.val) 18 | if cur.left: 19 | tmp.append(cur.left) 20 | if cur.right: 21 | tmp.append(cur.right) 22 | res.append(cur_res) 23 | 24 | return res[::-1] -------------------------------------------------------------------------------- /Python/Easy/108. Convert Sorted Array to Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def sortedArrayToBST(self, nums: List[int]) -> TreeNode: 9 | if nums == []: 10 | return None 11 | left, right = 0, len(nums)-1 12 | mid = (left+right) // 2 13 | 14 | root = TreeNode(nums[mid]) 15 | left_node = self.sortedArrayToBST(nums[:mid]) 16 | right_node = self.sortedArrayToBST(nums[mid+1:]) 17 | root.left = left_node 18 | root.right = right_node 19 | 20 | return root 21 | -------------------------------------------------------------------------------- /Python/Easy/1108. Defanging an IP Address.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def defangIPaddr(self, address: str) -> str: 3 | return address.replace('.',"[.]") -------------------------------------------------------------------------------- /Python/Easy/111. Minimum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def minDepth(self, root: TreeNode) -> int: 9 | if not root: 10 | return 0 11 | if not root.left and not root.right: 12 | return 1 13 | 14 | left, right = float('inf'), float('inf') 15 | 16 | if root.left: 17 | left = self.minDepth(root.left) 18 | if root.right: 19 | right = self.minDepth(root.right) 20 | 21 | return 1+min( left, right) 22 | -------------------------------------------------------------------------------- /Python/Easy/112. Path Sum.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def hasPathSum(self, root: TreeNode, sum: int) -> bool: 9 | 10 | if not root: 11 | return False 12 | if root.val == sum and not root.left and not root.right: 13 | return True 14 | 15 | return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val) 16 | 17 | -------------------------------------------------------------------------------- /Python/Easy/1122. Relative Sort Array.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: 5 | 6 | c1 = Counter(arr1) 7 | ans = [] 8 | diff = [] 9 | 10 | for i in arr2: 11 | ans.extend([i]*c1[i]) 12 | 13 | for i in arr1: 14 | if i not in arr2: 15 | diff.append(i) 16 | diff.sort() 17 | 18 | return ans+diff 19 | 20 | #simpler version 21 | c2={i:j for j,i in enumerate(arr2)} 22 | return sorted(arr1,key=lambda a : c2.get(a,1000+a)) -------------------------------------------------------------------------------- /Python/Easy/1160. Find Words That Can Be Formed by Characters.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def countCharacters(self, words: List[str], chars: str) -> int: 4 | 5 | c2=Counter(chars) 6 | ans=0 7 | 8 | for i in words: 9 | ci=Counter(i) 10 | flag=0 11 | 12 | for j in ci: 13 | if ci[j] <= c2.get(j,0): 14 | flag +=1 15 | 16 | if flag == len(ci): 17 | ans += len(i) 18 | 19 | return ans 20 | 21 | #return sum(not cnt(w) - cnt(chars) and len(w) for w in words) -------------------------------------------------------------------------------- /Python/Easy/118. Pascal's Triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generate(self, numRows: int) -> List[List[int]]: 3 | result = [] 4 | for i in range(1,numRows+1): 5 | cur = [1] * i 6 | for j in range(1, i-1): 7 | cur[j] = result[-1][j-1] + result[-1][j] 8 | result.append(cur) 9 | 10 | return result 11 | 12 | -------------------------------------------------------------------------------- /Python/Easy/119. Pascal's Triangle II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getRow(self, rowIndex: int) -> List[int]: 3 | result = [1] * (rowIndex+1) 4 | for i in range(0, rowIndex+1): 5 | for j in range(i-1, 0, -1): 6 | result[j] = result[j] + result[j-1] 7 | 8 | return result 9 | -------------------------------------------------------------------------------- /Python/Easy/121. Best Time to Buy and Sell Stock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | min_p, max_p = inf, 0 4 | for p in prices: 5 | min_p=min(p, min_p) 6 | max_p=max(max_p, p-min_p) 7 | 8 | return max_p 9 | 10 | -------------------------------------------------------------------------------- /Python/Easy/122. Best Time to Buy and Sell Stock II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | result = 0 4 | buy = float('inf') 5 | for i in range(len(prices)-1): 6 | if prices[i] < buy: 7 | buy = prices[i] 8 | if prices[i] > buy and prices[i+1] < prices[i]: 9 | result = result + prices[i] - buy 10 | buy = float('inf') 11 | 12 | if prices[-1] > buy: 13 | result = result + prices[-1] - buy 14 | 15 | return result 16 | 17 | #Basically, if tomorrow's price is higher than today's, we buy it today and sell tomorrow. Otherwise, we don't. Here is the code: 18 | 19 | class Solution(object): 20 | def maxProfit(self, prices): 21 | return sum(max(prices[i + 1] - prices[i], 0) for i in range(len(prices) - 1)) -------------------------------------------------------------------------------- /Python/Easy/1221. Split a String in Balanced Strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def balancedStringSplit(self, s: str) -> int: 3 | cnt=0 4 | flag=0 5 | 6 | for i in s: 7 | if i == 'R': 8 | flag += 1 9 | else: 10 | flag -= 1 11 | if flag == 0: 12 | cnt +=1 13 | 14 | return cnt 15 | 16 | 17 | # simpler version 18 | from itertools import accumulate as acc 19 | class Solution: 20 | def balancedStringSplit(self, s: str) -> int: 21 | return list(acc(1 if c == 'L' else -1 for c in s)).count(0) -------------------------------------------------------------------------------- /Python/Easy/125. Valid Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param s: A string 4 | @return: Whether the string is a valid palindrome 5 | """ 6 | def isPalindrome(self, s): 7 | # write your code here 8 | 9 | 10 | 11 | left, right = 0, len(s) - 1 12 | while left < right and right >=0 and left < len(s) : 13 | while left < len(s) and not s[left].isalnum(): 14 | left += 1 15 | while right >= 0 and not s[right].isalnum(): 16 | right -= 1 17 | 18 | if left < right and s[left].lower() != s[right].lower(): 19 | return False 20 | 21 | left += 1 22 | right -= 1 23 | 24 | return True 25 | -------------------------------------------------------------------------------- /Python/Easy/1281. Subtract the Product and Sum of Digits of an Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subtractProductAndSum(self, n: int) -> int: 3 | str_n=str(n) 4 | 5 | sum_n=0 6 | mul_n=1 7 | 8 | for i in str_n: 9 | sum_n += int(i) 10 | mul_n *= int(i) 11 | 12 | return mul_n - sum_n 13 | 14 | -------------------------------------------------------------------------------- /Python/Easy/13. Roman to Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def romanToInt(self, s: str) -> int: 3 | d = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1} 4 | num=0 5 | for i in range(0,len(s)-1): 6 | if d[s[i]] < d[s[i+1]]: 7 | num-=d[s[i]] 8 | else: 9 | num+=d[s[i]] 10 | num += d[s[-1]] 11 | return num -------------------------------------------------------------------------------- /Python/Easy/136. Single Number.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def singleNumber(self, nums: List[int]) -> int: 4 | c=Counter(nums) 5 | for i in c: 6 | if c[i]==1: 7 | return i 8 | 9 | #return (sum(list(dict.fromkeys(nums)))*2-sum(nums)) -------------------------------------------------------------------------------- /Python/Easy/14. Longest Common Prefix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonPrefix(self, strs: List[str]) -> str: 3 | if not strs: 4 | return "" 5 | 6 | shortest = min(strs, key=len) 7 | 8 | for i, char in enumerate(shortest): 9 | for other in strs: 10 | if other[i] != char: 11 | return shortest[:i] 12 | 13 | return shortest 14 | 15 | 16 | -------------------------------------------------------------------------------- /Python/Easy/141. Linked List Cycle.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def hasCycle(self, head: ListNode) -> bool: 9 | slow=fast=head 10 | while fast and fast.next: 11 | slow=slow.next 12 | fast=fast.next.next 13 | if slow==fast: 14 | return True 15 | return False -------------------------------------------------------------------------------- /Python/Easy/155. Min Stack.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | 3 | def __init__(self): 4 | """ 5 | initialize your data structure here. 6 | """ 7 | self.q=[] 8 | 9 | def push(self, x: int) -> None: 10 | self.q.append((x,min(self.getMin(),x))) 11 | 12 | def pop(self) -> None: 13 | self.q.pop() 14 | 15 | def top(self) -> int: 16 | if not self.q: 17 | return None 18 | else: 19 | return self.q[-1][0] 20 | 21 | def getMin(self) -> int: 22 | if self.q: 23 | return self.q[-1][1] 24 | return inf 25 | 26 | 27 | # Your MinStack object will be instantiated and called as such: 28 | # obj = MinStack() 29 | # obj.push(x) 30 | # obj.pop() 31 | # param_3 = obj.top() 32 | # param_4 = obj.getMin() -------------------------------------------------------------------------------- /Python/Easy/163. Missing Ranges.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]: 3 | if not nums: 4 | if lower == upper: 5 | return [str(lower)] 6 | else: 7 | return [str(lower) + "->" + str(upper)] 8 | 9 | 10 | nums.append(upper + 1) 11 | pre = lower - 1 12 | 13 | result = [] 14 | for i in range(len(nums)): 15 | if nums[i] == pre + 2: 16 | result.append(str(pre + 1)) 17 | elif nums[i] > pre + 2: 18 | result.append(str(pre + 1) + "->" + str(nums[i] - 1)) 19 | 20 | pre = nums[i] 21 | 22 | return result 23 | 24 | -------------------------------------------------------------------------------- /Python/Easy/167. Two Sum II - Input array is sorted.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, numbers: List[int], target: int) -> List[int]: 3 | left, right = 0, len(numbers) - 1 4 | 5 | while left < right: 6 | if numbers[left] + numbers[right] == target: 7 | return (left + 1, right + 1) 8 | elif numbers[left] + numbers[right] < target: 9 | left += 1 10 | else: 11 | right -= 1 12 | -------------------------------------------------------------------------------- /Python/Easy/168. Excel Sheet Column Title.py: -------------------------------------------------------------------------------- 1 | import string 2 | 3 | class Solution: 4 | def convertToTitle(self, n: int) -> str: 5 | dct = dict(zip(list(range(26)), string.ascii_uppercase)) 6 | 7 | ans = "" 8 | while n > 0: 9 | num = (n - 1) % 26 10 | ans = dct[num] + ans 11 | n = (n - 1) // 26 12 | 13 | return ans 14 | 15 | -------------------------------------------------------------------------------- /Python/Easy/169. Majority Element.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def majorityElement(self, nums: List[int]) -> int: 4 | c=Counter(nums) 5 | 6 | for i in c: 7 | if c[i] > len(nums)//2: 8 | return i -------------------------------------------------------------------------------- /Python/Easy/171. Excel Sheet Column Number.py: -------------------------------------------------------------------------------- 1 | import string 2 | class Solution: 3 | def titleToNumber(self, s: str) -> int: 4 | dct = dict(zip(string.ascii_uppercase, list(range(1,27)))) 5 | 6 | result = 0 7 | for i in s: 8 | result = result * 26 + dct[i] 9 | return result 10 | -------------------------------------------------------------------------------- /Python/Easy/172. Factorial Trailing Zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trailingZeroes(self, n: int) -> int: 3 | if n == 0: 4 | return 0 5 | 6 | return n //5 + self.trailingZeroes(n // 5) -------------------------------------------------------------------------------- /Python/Easy/190. Reverse Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseBits(self, n: int) -> int: 3 | ans = 0 4 | for i in range(32): 5 | ans = (ans << 1) ^ (n & 1) 6 | n >>= 1 7 | return ans -------------------------------------------------------------------------------- /Python/Easy/191. Number of 1 Bits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def hammingWeight(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | ans = 0 8 | while n: 9 | if n & 1 == 1: 10 | ans += 1 11 | n >>= 1 12 | 13 | return ans -------------------------------------------------------------------------------- /Python/Easy/198. House Robber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | if not nums: 4 | return 0 5 | 6 | if len(nums)<3: 7 | return max(nums) 8 | 9 | money = [nums[0], nums[1]] 10 | 11 | for i in range(2,len(nums)): 12 | money=[max(money[0],money[1]),money[0]+nums[i]] 13 | 14 | return max(money) 15 | 16 | # simpler version 17 | last, now = 0, 0 18 | for i in nums: 19 | last, now = now, max(last + i, now) 20 | return now 21 | 22 | #another version lol 23 | if not nums: 24 | return 0 25 | if len(nums)<2: 26 | return nums[0] 27 | 28 | dp=[0]*len(nums)#define dp 29 | dp[0]=nums[0] 30 | dp[1]=max(nums[0],nums[1]) 31 | for i in range(2,len(nums)): 32 | dp[i]=max(nums[i]+dp[i-2],dp[i-1]) 33 | print(dp) 34 | return dp[-1] -------------------------------------------------------------------------------- /Python/Easy/20. Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s: str) -> bool: 3 | stack=[] 4 | if not s: 5 | return True 6 | 7 | for i in s: 8 | if i in ['(', '{', '[']: 9 | stack.extend(i) 10 | if i == ')': 11 | if not stack or stack.pop() != '(': 12 | return False 13 | if i == '}' : 14 | if not stack or stack.pop() != '{': 15 | return False 16 | if i == ']' : 17 | if not stack or stack.pop() != '[': 18 | return False 19 | 20 | return True and not stack 21 | -------------------------------------------------------------------------------- /Python/Easy/202. Happy Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isHappy(self, n: int) -> bool: 3 | seen = set() 4 | 5 | while n != 1: 6 | seen.add(n) 7 | tmp = 0 8 | while n: 9 | tmp += (n%10)**2 10 | n = n//10 11 | 12 | if tmp in seen: 13 | return False 14 | 15 | n = tmp 16 | 17 | return True 18 | -------------------------------------------------------------------------------- /Python/Easy/203. Remove Linked List Elements.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def removeElements(self, head: ListNode, val: int) -> ListNode: 8 | dummy = ListNode(0) 9 | dummy.next = head 10 | cur = dummy 11 | 12 | while cur and cur.next: 13 | while cur.next and cur.next.val == val: 14 | cur.next = cur.next.next 15 | if cur: 16 | cur = cur.next 17 | 18 | return dummy.next -------------------------------------------------------------------------------- /Python/Easy/204. Count Primes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPrimes(self, n: int) -> int: 3 | 4 | count = 0 5 | prime = [True] * (n+1) 6 | 7 | for i in range(2, n): 8 | if prime[i]: 9 | count += 1 10 | 11 | j = 1 12 | while j * i <= n: 13 | prime[i * j] = False 14 | j += 1 15 | 16 | return count 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Python/Easy/21. Merge Two Sorted Lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 9 | dummy = cur = ListNode(0) 10 | 11 | while l1 and l2: 12 | if l1.val <= l2.val: 13 | cur.next = l1 14 | l1 = l1.next 15 | else: 16 | cur.next = l2 17 | l2 = l2.next 18 | cur = cur.next 19 | cur.next = l1 or l2 20 | return dummy.next 21 | -------------------------------------------------------------------------------- /Python/Easy/217. Contains Duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | i=0 4 | if len(nums)<=1: 5 | return False 6 | nums.sort() 7 | for i in range(0,len(nums)-1): 8 | if nums[i]==nums[i+1]: 9 | return True 10 | break 11 | return False 12 | -------------------------------------------------------------------------------- /Python/Easy/219. Contains Duplicate II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 3 | dct = {} 4 | for i, v in enumerate(nums): 5 | if v in dct and i <= dct[v]: 6 | return True 7 | dct[v] = i + k 8 | return False 9 | -------------------------------------------------------------------------------- /Python/Easy/226. Invert Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def invertTree(self, root: TreeNode) -> TreeNode: 10 | if not root: 11 | return None 12 | t=root.left 13 | root.left=root.right 14 | root.right=t 15 | root.left=self.invertTree(root.left) 16 | root.right=self.invertTree(root.right) 17 | 18 | return root 19 | -------------------------------------------------------------------------------- /Python/Easy/228. Summary Ranges.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def summaryRanges(self, nums: List[int]) -> List[str]: 3 | if not nums: 4 | return [] 5 | 6 | lower, pre = nums[0], nums[0] 7 | result = [] 8 | nums.append(nums[-1] + 2) 9 | 10 | for i in range(1, len(nums)): 11 | if nums[i] != pre + 1: 12 | if lower == pre: 13 | result.append(str(pre)) 14 | else: 15 | result.append(str(lower) + "->" + str(pre)) 16 | lower, pre = nums[i], nums[i] 17 | else: 18 | pre += 1 19 | 20 | 21 | return result 22 | 23 | -------------------------------------------------------------------------------- /Python/Easy/231. Power of Two.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfTwo(self, n: int) -> bool: 3 | if n == 0: 4 | return 0 5 | while n % 2 == 0: 6 | n = n // 2 7 | return n == 1 8 | 9 | if n <= 0: 10 | return False 11 | return !n&(n-1) 12 | -------------------------------------------------------------------------------- /Python/Easy/235. Lowest Common Ancestor of a Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | 10 | def lowestCommonAncestor(self, root, p, q): 11 | if p.val <= root.val <= q.val or q.val <= root.val <= p.val: 12 | return root 13 | 14 | if p.val > root.val and q.val > root.val: 15 | return self.lowestCommonAncestor(root.right, p, q) 16 | 17 | if p.val < root.val and q.val < root.val: 18 | return self.lowestCommonAncestor(root.left, p, q) 19 | -------------------------------------------------------------------------------- /Python/Easy/243. Shortest Word Distance.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shortestDistance(self, words: List[str], word1: str, word2: str) -> int: 3 | index1 = [i for i in range(len(words)) if words[i] == word1] 4 | index2 = [i for i in range(len(words)) if words[i] == word2] 5 | 6 | ans = float('inf') 7 | for i1 in index1: 8 | for i2 in index2: 9 | ans = min(ans, abs(i1 - i2)) 10 | 11 | return ans 12 | 13 | 14 | def shortestDistance(self, words, word1, word2): 15 | ans = len(words) 16 | current_word, current_index = None, 0 17 | for index, word in enumerate(words): 18 | if word != word1 and word != word2: 19 | continue 20 | if current_word and word != current_word: 21 | ans = min(ans, index - current_index) 22 | current_word, current_index = word, index 23 | return ans -------------------------------------------------------------------------------- /Python/Easy/246. Strobogrammatic Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isStrobogrammatic(self, num: str) -> bool: 3 | dct = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'} 4 | 5 | left, right = 0, len(num) - 1 6 | while left <= right: 7 | if num[left] not in dct or dct[num[left]] != num[right]: 8 | return False 9 | 10 | left += 1 11 | right -= 1 12 | 13 | return True -------------------------------------------------------------------------------- /Python/Easy/252. Meeting Rooms.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canAttendMeetings(self, intervals: List[List[int]]) -> bool: 3 | intervals.sort(key = lambda x : x[0]) 4 | for i in range(1, len(intervals)): 5 | if intervals[i][0] < intervals[i - 1][1]: 6 | return False 7 | return True -------------------------------------------------------------------------------- /Python/Easy/256. Paint House.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCost(self, costs: List[List[int]]) -> int: 3 | 4 | for i in range(1,len(costs)): 5 | costs[i][0] += min(costs[i-1][1],costs[i-1][2]) 6 | costs[i][1] += min(costs[i-1][0],costs[i-1][2]) 7 | costs[i][2] += min(costs[i-1][0],costs[i-1][1]) 8 | 9 | n=len(costs)-1 10 | return min(costs[n][0], costs[n][1], costs[n][2]) 11 | 12 | red, blue, green = 0, 0, 0 13 | for cr, cb, cg in costs: 14 | red, blue, green = min(blue, green) + cr, min(red, green) + cb, min(red, blue) + cg 15 | return min(red, blue, green) -------------------------------------------------------------------------------- /Python/Easy/257. Binary Tree Paths.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def binaryTreePaths(self, root: TreeNode) -> List[str]: 9 | if not root: 10 | return [] 11 | result = [] 12 | self.recursive(root, result, [str(root.val)]) 13 | return result 14 | 15 | 16 | def recursive(self, root, result, cur): 17 | if not root.left and not root.right: 18 | result.append("->".join(cur)) 19 | 20 | if root.left: 21 | cur.append(str(root.left.val)) 22 | self.recursive(root.left, result, cur) 23 | cur.pop() 24 | 25 | if root.right: 26 | cur.append(str(root.right.val)) 27 | self.recursive(root.right, result, cur) 28 | cur.pop() 29 | -------------------------------------------------------------------------------- /Python/Easy/258. Add Digits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addDigits(self, num: int) -> int: 3 | while num // 10 > 0: 4 | tmp = 0 5 | while num > 0: 6 | tmp += num % 10 7 | num //= 10 8 | num = tmp 9 | 10 | return num 11 | -------------------------------------------------------------------------------- /Python/Easy/26. Remove Duplicates from Sorted Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums: List[int]) -> int: 3 | if not nums: 4 | return 0 5 | 6 | j = 0 7 | for i in range(1,len(nums)): 8 | if nums[i] != nums[j]: 9 | j += 1 10 | nums [j] = nums[i] 11 | 12 | return j+1 -------------------------------------------------------------------------------- /Python/Easy/263. Ugly Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isUgly(self, num: int) -> bool: 3 | if not num: 4 | return False 5 | 6 | tmp = num 7 | 8 | while num % 2 == 0: 9 | num = num // 2 10 | 11 | while num % 3 == 0: 12 | num = num // 3 13 | 14 | while num % 5 == 0: 15 | num = num // 5 16 | 17 | return num == 1 18 | -------------------------------------------------------------------------------- /Python/Easy/266. Palindrome Permutation.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def canPermutePalindrome(self, s: str) -> bool: 5 | dct = Counter(s) 6 | 7 | count = 0 8 | for value in dct.values(): 9 | if count > 1: 10 | return False 11 | if value % 2 == 1: 12 | count += 1 13 | 14 | 15 | return count <= 1 -------------------------------------------------------------------------------- /Python/Easy/268. Missing Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingNumber(self, nums: List[int]) -> int: 3 | return sum(range(len(nums)+1)) - sum(nums) 4 | -------------------------------------------------------------------------------- /Python/Easy/27. Remove Element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeElement(self, nums: List[int], val: int) -> int: 3 | i = 0 4 | for j in range(len(nums)): 5 | if nums[j] != val: 6 | nums[i] = nums[j] 7 | i += 1 8 | return i -------------------------------------------------------------------------------- /Python/Easy/270. Closest Binary Search Tree Value.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def closestValue(self, root: TreeNode, target: float) -> int: 9 | upper = root 10 | lower = root 11 | 12 | while root: 13 | if root.val > target: 14 | upper = root 15 | root = root.left 16 | elif root.val < target: 17 | lower = root 18 | root = root.right 19 | else: 20 | return root.val 21 | 22 | if abs(upper.val - target) > abs(lower.val - target): 23 | return lower.val 24 | return upper.val -------------------------------------------------------------------------------- /Python/Easy/276. Paint Fence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numWays(self, n: int, k: int) -> int: 3 | if n == 0: 4 | return 0 5 | 6 | if n == 1: 7 | return k 8 | 9 | same, diff = k, k * (k - 1) 10 | for i in range(3, n+1): 11 | same, diff = diff, (same + diff) * (k - 1) 12 | 13 | return same + diff -------------------------------------------------------------------------------- /Python/Easy/278. First Bad Version.py: -------------------------------------------------------------------------------- 1 | # The isBadVersion API is already defined for you. 2 | # @param version, an integer 3 | # @return an integer 4 | # def isBadVersion(version): 5 | 6 | class Solution: 7 | def firstBadVersion(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | 13 | left, right = 1, n 14 | while left + 1 < right: 15 | mid = left + (right - left) // 2 16 | 17 | if not isBadVersion(mid): 18 | left = mid + 1 19 | else: 20 | right = mid 21 | 22 | if isBadVersion(left): 23 | return left 24 | return right 25 | -------------------------------------------------------------------------------- /Python/Easy/28. Implement strStr().py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def strStr(self, haystack: str, needle: str) -> int: 3 | # if len(needle)==0: 4 | # return 0 5 | # return haystack.find(needle) 6 | 7 | if len(needle) > len(haystack) : 8 | return -1 9 | if not needle: 10 | return 0 11 | 12 | 13 | for i in range(len(haystack)-len(needle)+1): 14 | if haystack[i] == needle[0]: 15 | if haystack[i:i+len(needle)] == needle: 16 | return i 17 | return -1 18 | -------------------------------------------------------------------------------- /Python/Easy/283. Move Zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def moveZeroes(self, nums: List[int]) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | if len(nums) <=1: 7 | return nums 8 | 9 | i, j = 0, 0 10 | 11 | while j < len(nums): 12 | if nums[j] != 0: 13 | nums[i]=nums[j] 14 | i += 1 15 | j +=1 16 | 17 | while i < len(nums): 18 | nums[i]=0 19 | i += 1 20 | 21 | return nums 22 | 23 | -------------------------------------------------------------------------------- /Python/Easy/290. Word Pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordPattern(self, pattern: str, s: str) -> bool: 3 | d1, d2 = {}, {} 4 | 5 | for i, val in enumerate(pattern): 6 | d1[val] = d1.get(val, []) + [i] 7 | for i, val in enumerate(s.split()): 8 | d2[val] = d2.get(val, []) + [i] 9 | 10 | return sorted(d1.values()) == sorted(d2.values()) 11 | -------------------------------------------------------------------------------- /Python/Easy/292. Nim Game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canWinNim(self, n: int) -> bool: 3 | return not n%4 == 0 -------------------------------------------------------------------------------- /Python/Easy/293. Flip Game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generatePossibleNextMoves(self, s: str) -> List[str]: 3 | result = [] 4 | for i in range(len(s) - 1): 5 | if s[i:i+2] == "++": 6 | result.append(s[:i] + "--" + s[i+2:]) 7 | return result -------------------------------------------------------------------------------- /Python/Easy/344. Reverse String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseString(self, s: List[str]) -> None: 3 | """ 4 | Do not return anything, modify s in-place instead. 5 | """ 6 | 7 | i,j=0,len(s)-1 8 | while i int: 3 | if target <= nums[0]: 4 | return 0 5 | elif target > nums[-1]: 6 | return len(nums) 7 | else: 8 | l, r = 0, len(nums)-1 9 | while l <= r: 10 | mid = (l + r) //2 11 | if nums[mid] == target: 12 | return mid 13 | if nums[mid] < target: 14 | l = mid+1 15 | else: 16 | r = mid-1 17 | 18 | return l 19 | 20 | 21 | #one-line solution 22 | class Solution(object): 23 | def searchInsert(self, nums, target): 24 | """ 25 | :type nums: List[int] 26 | :type target: int 27 | :rtype: int 28 | """ 29 | return len([x for x in nums if x bool: 11 | """ 12 | Returns true if the message should be printed in the given timestamp, otherwise returns false. 13 | If this method returns false, the message will not be printed. 14 | The timestamp is in seconds granularity. 15 | """ 16 | if timestamp < self.dicts.get(message,0): 17 | return False 18 | 19 | self.dicts[message]=timestamp + 10 20 | return True 21 | 22 | 23 | # Your Logger object will be instantiated and called as such: 24 | # obj = Logger() 25 | # param_1 = obj.shouldPrintMessage(timestamp,message) -------------------------------------------------------------------------------- /Python/Easy/38. Count and Say.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countAndSay(self, n: int) -> str: 3 | if n==0: 4 | return "" 5 | s = "1" 6 | for i in range(1,n): 7 | count, temp = 1, "" 8 | for j in range(1,len(s)): 9 | if s[j] == s[j-1]: 10 | count += 1 11 | else: 12 | temp += str(count) 13 | temp += s[j-1] 14 | count = 1 15 | temp += str(count) 16 | temp += s[-1] 17 | s = temp 18 | return s 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Python/Easy/404. Sum of Left Leaves.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def sumOfLeftLeaves(self, root: TreeNode) -> int: 9 | return self.dfs(root, 0) if root else 0 10 | 11 | def dfs(self, root, count): 12 | if not root: 13 | return 14 | if root.left and not root.left.left and not root.left.right: 15 | count += root.left.val 16 | 17 | if root.left: 18 | count = self.dfs(root.left, count) 19 | if root.right: 20 | count = self.dfs(root.right, count) 21 | 22 | return count 23 | -------------------------------------------------------------------------------- /Python/Easy/408. Valid Word Abbreviation.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validWordAbbreviation(self, word: str, abbr: str) -> bool: 3 | i, j = 0, 0 4 | while i < len(word) and j < len(abbr): 5 | if word[i] == abbr[j]: 6 | i += 1 7 | j += 1 8 | elif abbr[j] == '0': 9 | return False 10 | elif abbr[j].isdigit(): 11 | k = j 12 | while k < len(abbr) and abbr[k].isdigit(): 13 | k += 1 14 | i += int(abbr[j:k]) 15 | j = k 16 | else: 17 | return False 18 | 19 | return i == len(word) and j == len(abbr) -------------------------------------------------------------------------------- /Python/Easy/448. Find All Numbers Disappeared in an Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 3 | nums=[0] + nums 4 | for num in nums: 5 | if nums[abs(num)]>0: 6 | nums[abs(num)]=-nums[abs(num)] 7 | 8 | return [i for i in range(1,len(nums)) if nums[i]>0] 9 | 10 | 11 | #return set(range(1,len(nums)+1))-set(nums) 12 | 13 | -------------------------------------------------------------------------------- /Python/Easy/453. Minimum Moves to Equal Array Elements.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minMoves(self, nums: List[int]) -> int: 3 | return sum(nums) - len(nums) * min(nums) -------------------------------------------------------------------------------- /Python/Easy/459. Repeated Substring Pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def repeatedSubstringPattern(self, s: str) -> bool: 3 | n = len(s) 4 | for i in range(1, n // 2 + 1): 5 | if n % i == 0 and s[:i] * (n // i) == s: 6 | return True 7 | return False -------------------------------------------------------------------------------- /Python/Easy/463. Island Perimeter.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def islandPerimeter(self, grid: List[List[int]]) -> int: 3 | ans = 0 4 | n = len(grid) 5 | m = len(grid[0]) 6 | for i in range(n): 7 | for j in range(m): 8 | if grid[i][j]==1: 9 | ans += 4 10 | if i in range(n) and j-1 in range(m) and grid[i][j-1] == 1: 11 | ans -= 1 12 | if i in range(n) and j+1 in range(m) and grid[i][j+1] == 1: 13 | ans -= 1 14 | if j in range(m) and i-1 in range(n) and grid[i-1][j] == 1: 15 | ans -= 1 16 | if j in range(m) and i+1 in range(n) and grid[i+1][j] == 1: 17 | ans -= 1 18 | 19 | return ans 20 | 21 | def islandPerimeter(self, grid): 22 | return sum(sum(map(operator.ne, [0] + row, row + [0])) 23 | for row in grid + map(list, zip(*grid))) -------------------------------------------------------------------------------- /Python/Easy/496. Next Greater Element I.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 | ans=[] 4 | for i in nums1: 5 | j=nums2.index(i) 6 | 7 | flag=True 8 | for k in nums2[j:]: 9 | if k > i: 10 | ans.append(k) 11 | flag=False 12 | break 13 | if flag: 14 | ans.append(-1) 15 | 16 | return ans 17 | 18 | #simpler version 19 | return [next((y for y in nums[nums.index(x):] if y > x), -1) for x in findNums] 20 | 21 | #using stack 22 | def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: 23 | d = {} 24 | s = [] 25 | ans = [] 26 | 27 | for i in nums2: 28 | while s and s[-1] < i: 29 | d[s.pop()]=i 30 | s.append(i) 31 | 32 | return [d.get(i,-1) for i in nums1] 33 | -------------------------------------------------------------------------------- /Python/Easy/509. Fibonacci Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fib(self, N: int) -> int: 3 | n=[0, 1] 4 | if N<=1: 5 | return n[N] 6 | 7 | for i in range(2,N+1): 8 | n.append(n[i-1]+n[i-2]) 9 | 10 | return n[N] 11 | 12 | #using recurssive 13 | if N < 2: 14 | return N 15 | return self.fib(N-1) + self.fib(N-2) -------------------------------------------------------------------------------- /Python/Easy/516. Longest Palindromic Subsequence.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def longestPalindrome(self, s: str) -> int: 5 | if not s: 6 | return 0 7 | 8 | vocab = Counter(s) 9 | 10 | length = 0 11 | count_one = 1 12 | for char in vocab: 13 | if vocab[char] % 2 == 0: 14 | length += vocab[char] 15 | elif vocab[char] % 2 == 1 and count_one > 0: 16 | length += vocab[char] 17 | count_one = 0 18 | else: 19 | length += vocab[char] - 1 20 | 21 | 22 | return length 23 | 24 | 25 | -------------------------------------------------------------------------------- /Python/Easy/53. Maximum Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | cur_sum, max_sum = -inf, -inf 4 | for num in nums: 5 | cur_sum=max(cur_sum+num,num) 6 | max_sum=max(max_sum,cur_sum) 7 | return max_sum -------------------------------------------------------------------------------- /Python/Easy/543. Diameter of Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def diameterOfBinaryTree(self, root: TreeNode) -> int: 10 | 11 | self.ans=0 12 | 13 | def depth(n): 14 | if not n: 15 | return 0 16 | left=depth(n.left) 17 | right=depth(n.right) 18 | self.ans=max(self.ans,left+right) 19 | return 1+max(left,right) 20 | 21 | depth(root) 22 | 23 | return self.ans 24 | -------------------------------------------------------------------------------- /Python/Easy/557. Reverse Words in a String III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | return " ".join(i[::-1] for i in s.split(' ')) -------------------------------------------------------------------------------- /Python/Easy/561. Array Partition I.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrayPairSum(self, nums: List[int]) -> int: 3 | nums.sort() 4 | return sum([nums[i] for i in range(len(nums)) if i%2 ==0 ]) 5 | 6 | #simpler version 7 | return sum(sorted(nums)[::2]) -------------------------------------------------------------------------------- /Python/Easy/58. Length of Last Word.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | if not s: 4 | return 0 5 | result = s.strip().split() 6 | if not result: 7 | return 0 8 | return len(result[-1]) 9 | -------------------------------------------------------------------------------- /Python/Easy/617. Merge Two Binary Trees.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: 10 | if t1 and t2: 11 | merge=TreeNode(t1.val+t2.val) 12 | merge.left=self.mergeTrees(t1.left,t2.left) 13 | merge.right=self.mergeTrees(t1.right,t2.right) 14 | return merge 15 | else: 16 | return t1 or t2 17 | -------------------------------------------------------------------------------- /Python/Easy/669. Trim a Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode: 10 | 11 | if not root: 12 | return None 13 | if root.val < L: 14 | return self.trimBST(root.right, L, R) 15 | elif root.val > R: 16 | return self.trimBST(root.left, L, R) 17 | 18 | root.left = self.trimBST(root.left, L, R) 19 | root.right = self.trimBST(root.right, L, R) 20 | 21 | return root 22 | 23 | -------------------------------------------------------------------------------- /Python/Easy/67. Add Binary.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addBinary(self, a: str, b: str) -> str: 3 | index_a, index_b = len(a)-1, len(b)-1 4 | 5 | num = 0 6 | result = '' 7 | 8 | while num > 0 or index_a >= 0 or index_b >=0: 9 | if index_a >=0: 10 | num += int(a[index_a]) 11 | index_a -=1 12 | 13 | if index_b >=0: 14 | num += int(b[index_b]) 15 | index_b -=1 16 | 17 | result = str(num%2) + result 18 | 19 | num //= 2 20 | 21 | 22 | return result -------------------------------------------------------------------------------- /Python/Easy/69. Sqrt(x).py: -------------------------------------------------------------------------------- 1 | #https://blog.csdn.net/u014485485/article/details/77599953?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param 2 | # #Newton iteration 3 | 4 | 5 | class Solution: 6 | def mySqrt(self, x: int) -> int: 7 | 8 | # r = x 9 | # while r*r > x: 10 | # r = (r + x/r) // 2 11 | # return int(r) 12 | 13 | l, r = 0, x 14 | while l + 1 < r: 15 | m = l + (r - l)//2 16 | 17 | if m * m > x: 18 | r = m 19 | elif m * m < x: 20 | l = m 21 | else: 22 | return m 23 | 24 | if r * r <= x: 25 | return r 26 | return l 27 | 28 | -------------------------------------------------------------------------------- /Python/Easy/7. Reverse Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x: int, flag = 0) -> int: 3 | y=0 4 | while x >0: 5 | y=y*10+x%10 6 | x=x//10 7 | 8 | if x <0: 9 | x=-x 10 | while x >0: 11 | y=y*10+x%10 12 | x=x//10 13 | y=-y 14 | if y < -2**31 or x < -2**31 or y > 2**31-1 or x > 2**31-1: 15 | return 0 16 | return y 17 | 18 | 19 | -------------------------------------------------------------------------------- /Python/Easy/70. Climbing Stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | 4 | if n<3: 5 | return n 6 | 7 | ways = [1,2] 8 | 9 | for i in range(3,n+1): 10 | ways=[ways[1],ways[0]+ways[1]] 11 | 12 | return ways[1] -------------------------------------------------------------------------------- /Python/Easy/700. Search in a Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def searchBST(self, root: TreeNode, val: int) -> TreeNode: 9 | node = root 10 | while node: 11 | if node.val > val: 12 | node = node.left 13 | elif node.val < val: 14 | node = node.right 15 | else: 16 | return node 17 | return None -------------------------------------------------------------------------------- /Python/Easy/709. To Lower Case.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def toLowerCase(self, str: str) -> str: 3 | return "".join(chr(ord(c) + 32) if "A" <= c <= "Z" else c for c in str) -------------------------------------------------------------------------------- /Python/Easy/771. Jewels and Stones.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numJewelsInStones(self, J: str, S: str) -> int: 3 | cnt=0 4 | for i in S: 5 | if i in J: 6 | cnt +=1 7 | return cnt 8 | 9 | # simpler version 10 | def numJewelsInStones(self, J, S): 11 | return sum(map(J.count, S)) -------------------------------------------------------------------------------- /Python/Easy/821. Shortest Distance to a Character.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shortestToChar(self, S: str, C: str) -> List[int]: 3 | ans = [] 4 | loc = [] 5 | 6 | for i, c in enumerate(S): 7 | if c==C: 8 | loc.append(i) 9 | 10 | 11 | for i in range(len(S)): 12 | ans.append(min([abs(i-j) for j in loc])) 13 | 14 | return ans 15 | -------------------------------------------------------------------------------- /Python/Easy/83. Remove Duplicates from Sorted List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def deleteDuplicates(self, head: ListNode) -> ListNode: 8 | dummy = ListNode(0) 9 | dummy.next = head 10 | while head and head.next: 11 | if head.val == head.next.val: 12 | head.next = head.next.next 13 | else: 14 | head = head.next 15 | 16 | return dummy.next 17 | -------------------------------------------------------------------------------- /Python/Easy/852. Peak Index in a Mountain Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def peakIndexInMountainArray(self, A: List[int]) -> int: 3 | return A.index(max(A)) 4 | 5 | #O(logN) 6 | def peakIndexInMountainArray(self, A): 7 | l, r = 0, len(A) - 1 8 | while l < r: 9 | m = (l + r) // 2 10 | if A[m] < A[m + 1]: 11 | l = m + 1 12 | else: 13 | r = m 14 | return l -------------------------------------------------------------------------------- /Python/Easy/876. Middle of the Linked List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def middleNode(self, head: ListNode) -> ListNode: 9 | cnt = 0 10 | node = head 11 | while node: 12 | node = node.next 13 | cnt += 1 14 | cnt = cnt //2 + 1 15 | 16 | node=head 17 | for i in range(cnt-1): 18 | node=node.next 19 | 20 | return node 21 | 22 | # slow and fast pointers 23 | def middleNode(self, head): 24 | slow = fast = head 25 | while fast and fast.next: 26 | slow = slow.next 27 | fast = fast.next.next 28 | return slow -------------------------------------------------------------------------------- /Python/Easy/88. Merge Sorted Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: 3 | """ 4 | Do not return anything, modify nums1 in-place instead. 5 | """ 6 | 7 | index = len(nums1)-1 8 | 9 | l1, l2 = m-1, n-1 10 | 11 | while l1 >= 0 and l2>=0 : 12 | if nums1[l1] <= nums2[l2]: 13 | nums1[index] = nums2[l2] 14 | l2 -= 1 15 | index -= 1 16 | 17 | else: 18 | nums1[index] = nums1[l1] 19 | l1 -= 1 20 | index -= 1 21 | 22 | 23 | if l2 >= 0: 24 | nums1[:l2+1] = nums2[:l2+1] -------------------------------------------------------------------------------- /Python/Easy/9. Palindrome Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, x: int) -> bool: 3 | input_x = x 4 | if x < 0: 5 | return False 6 | remain = 0 7 | count = 0 8 | while x >0: 9 | remain = (x%10)+(remain*10) 10 | count += 1 11 | x //= 10 12 | if remain == input_x: 13 | return True 14 | return False 15 | -------------------------------------------------------------------------------- /Python/Easy/905. Sort Array By Parity.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortArrayByParity(self, A: List[int]) -> List[int]: 3 | odd=[] 4 | even=[] 5 | 6 | for i in A: 7 | if i%2==0: 8 | even.append(i) 9 | else: 10 | odd.append(i) 11 | 12 | return even+odd 13 | 14 | # simpler version 15 | return([i for i in A if i%2==0]+[i for i in A if i%2!=0]) 16 | 17 | return sorted(A, key=lambda x: x % 2) -------------------------------------------------------------------------------- /Python/Easy/938. Range Sum of BST.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: 10 | if not root: 11 | return 0 12 | if root.val < L: 13 | return self.rangeSumBST(root.right, L, R) 14 | elif root.val > R: 15 | return self.rangeSumBST(root.left, L, R) 16 | return root.val+self.rangeSumBST(root.right, L, R)+self.rangeSumBST(root.left, L, R) -------------------------------------------------------------------------------- /Python/Easy/977. Squares of a Sorted Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortedSquares(self, A: List[int]) -> List[int]: 3 | i, j = 0, len(A)-1 4 | k = len(A) - 1 5 | ans = [0] * len(A) 6 | 7 | while i <= j: 8 | if (-A[i]) > A[j]: 9 | ans[k] = A[i] ** 2 10 | k -=1 11 | i +=1 12 | else: 13 | ans[k] = A[j] ** 2 14 | k -=1 15 | j -=1 16 | 17 | return ans 18 | 19 | #return sorted([i**2 for i in A]) -------------------------------------------------------------------------------- /Python/Hard/124. Binary Tree Maximum Path Sum.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def maxPathSum(self, root: TreeNode) -> int: 9 | 10 | def recursive(root): 11 | if not root: 12 | return (0, -float('inf')) 13 | 14 | left, left_max = recursive(root.left) 15 | right, right_max = recursive(root.right) 16 | 17 | max_val = max(left_max, right_max, left + right + root.val, root.val + left, root.val + right, root.val) 18 | 19 | return (max(root.val, root.val + left, root.val + right), max_val) 20 | 21 | return recursive(root)[1] 22 | -------------------------------------------------------------------------------- /Python/Hard/154. Find Minimum in Rotated Sorted Array II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMin(self, nums: List[int]) -> int: 3 | start, end = 0, len(nums) - 1 4 | 5 | while start + 1 < end: 6 | mid = start + (end - start) // 2 7 | if nums[mid] > nums[end]: 8 | start = mid 9 | elif nums[mid] < nums[end]: 10 | end = mid 11 | else: 12 | end -= 1 13 | 14 | return min(nums[start], nums[end]) -------------------------------------------------------------------------------- /Python/Hard/23. Merge k Sorted Lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | 7 | 8 | from heapq import * 9 | class Solution: 10 | def mergeKLists(self, lists: List[ListNode]) -> ListNode: 11 | if not lists: 12 | return None 13 | 14 | heap = [] 15 | count = 0 16 | for i in lists: 17 | if i: 18 | count += 1 19 | heappush(heap, (i.val, count, i)) 20 | 21 | head, cur = None, None 22 | while heap: 23 | _, _, val = heappop(heap) 24 | if head is None: 25 | head, cur = val, val 26 | else: 27 | cur.next = val 28 | cur = cur.next 29 | if val.next: 30 | count += 1 31 | heappush(heap, (val.next.val, count, val.next)) 32 | 33 | return head 34 | 35 | 36 | -------------------------------------------------------------------------------- /Python/Hard/239. Sliding Window Maximum.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | class Solution: 3 | def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: 4 | 5 | queue = deque([]) 6 | result = [] 7 | 8 | for i in range(k): 9 | while queue: 10 | if nums[i] > nums[queue[-1]]: 11 | queue.pop() 12 | else: 13 | break 14 | queue.append(i) 15 | 16 | for i in range(k, len(nums)): 17 | result.append(nums[queue[0]]) 18 | 19 | if i - k + 1 > queue[0]: 20 | queue.popleft() 21 | 22 | while queue: 23 | if nums[i] > nums[queue[-1]]: 24 | queue.pop() 25 | else: 26 | break 27 | queue.append(i) 28 | 29 | 30 | result.append(nums[queue[0]]) 31 | 32 | return result 33 | -------------------------------------------------------------------------------- /Python/Hard/30. Substring with Concatenation of All Words.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def findSubstring(self, s: str, words: List[str]) -> List[int]: 4 | n_words, word_len = len(words), len(words[0]) 5 | result = [] 6 | 7 | for i in range(len(s) - n_words * word_len + 1): 8 | count = n_words 9 | 10 | counter = Counter(words) 11 | for j in range(n_words): 12 | word = s[i + j * word_len : i + (j+1) * word_len] 13 | if word not in counter: 14 | break 15 | counter[word] -= 1 16 | if counter[word] >= 0: 17 | count -= 1 18 | 19 | if count == 0: 20 | result.append(i) 21 | 22 | 23 | return result 24 | 25 | 26 | -------------------------------------------------------------------------------- /Python/Hard/41. First Missing Positive.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstMissingPositive(self, nums: List[int]) -> int: 3 | if not nums: 4 | return 1 5 | 6 | n = len(nums) 7 | result = n * [-1] 8 | 9 | for num in nums: 10 | if 0 < num <= n: 11 | result[num - 1] = 1 12 | 13 | for i in range(n): 14 | if result[i] == -1: 15 | return i + 1 16 | 17 | return n + 1 18 | 19 | -------------------------------------------------------------------------------- /Python/Hard/42. Trapping Rain Water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trap(self, height: List[int]) -> int: 3 | if not height: 4 | return 0 5 | 6 | left, right = 0, len(height) - 1 7 | max_left, max_right = height[left], height[right] 8 | 9 | ans = 0 10 | while left < right: 11 | max_left, max_right = max(height[left], max_left), max(height[right], max_right) 12 | if max_left <= max_right: 13 | ans += max_left - height[left] 14 | left += 1 15 | else: 16 | ans += max_right - height[right] 17 | right -= 1 18 | 19 | return ans -------------------------------------------------------------------------------- /Python/Hard/57. Insert Interval.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: 3 | intervals.sort() 4 | result = [] 5 | 6 | i = 0 7 | while i= newInterval[0] and intervals[i][0] <= newInterval[1]: 12 | newInterval[0] = min(intervals[i][0], newInterval[0]) 13 | newInterval[1] = max(intervals[i][1], newInterval[1]) 14 | i += 1 15 | 16 | result.append(newInterval) 17 | 18 | while i newInterval[1]: 19 | result.append(intervals[i]) 20 | i += 1 21 | 22 | return result 23 | -------------------------------------------------------------------------------- /Python/Hard/65. Valid Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isNumber(self, s: str) -> bool: 3 | has_number, has_dot, has_e = False, False, False 4 | for i, c in enumerate(s): 5 | if c in "+-": 6 | if i > 0 and s[i - 1] not in 'eE': 7 | return False 8 | elif c == '.': 9 | if has_dot or has_e: 10 | return False 11 | has_dot = True 12 | elif c in 'eE': 13 | if has_e or not has_number: 14 | return False 15 | has_e, has_number = True, False 16 | elif c.isdigit(): 17 | has_number = True 18 | else: 19 | return False 20 | return has_number -------------------------------------------------------------------------------- /Python/Hard/685. Redundant Connection II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]: 3 | 4 | 5 | parent = list(range(len(edges))) 6 | 7 | def find(x): 8 | if x != parent[x]: 9 | parent[x] = find(parent[x]) 10 | return parent[x] 11 | 12 | def union(x, y): 13 | x, y = find(x), find(y) 14 | if x == y: 15 | return False 16 | parent[y] = x 17 | return True 18 | 19 | can1, can2, to_node = None, None, {} 20 | for (x, y) in edges: 21 | if y in to_node: 22 | can1, can2 = to_node[y], (x,y) 23 | break 24 | to_node[y] = [x, y] 25 | 26 | for (x,y) in edges: 27 | if (x,y) == can2: 28 | continue 29 | if not union(x - 1, y - 1): 30 | if can1: 31 | return can1 32 | return (x, y) 33 | 34 | return can2 35 | -------------------------------------------------------------------------------- /Python/Hard/759. Employee Free Time.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for an Interval. 3 | class Interval: 4 | def __init__(self, start: int = None, end: int = None): 5 | self.start = start 6 | self.end = end 7 | """ 8 | 9 | class Solution: 10 | def employeeFreeTime(self, schedule: '[[Interval]]') -> '[Interval]': 11 | schedule = sorted([i for s in schedule for i in s], key = lambda x: x.start) 12 | result, pre = [], schedule[0] 13 | for i in schedule[1:]: 14 | if i.start > pre.end: 15 | result.append(Interval(pre.end, i.start)) 16 | pre.end = i.end 17 | else: 18 | pre.end = max(i.end, pre.end) 19 | return result 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Python/Hard/76. Minimum Window Substring.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def minWindow(self, s: str, t: str) -> str: 4 | left, count = 0, 0 5 | freq = Counter(t) 6 | ans = "" 7 | for right in range(len(s)): 8 | if s[right] in freq: 9 | freq[s[right]] -= 1 10 | if freq[s[right]] >= 0: 11 | count += 1 12 | 13 | while count == len(t): 14 | if not ans or right - left + 1 < len(ans): 15 | ans = s[left : right + 1] 16 | 17 | if s[left] in freq: 18 | freq[s[left]] += 1 19 | if freq[s[left]] > 0: 20 | count -= 1 21 | 22 | left += 1 23 | 24 | return ans -------------------------------------------------------------------------------- /Python/Hard/84. Largest Rectangle in Histogram.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestRectangleArea(self, heights: List[int]) -> int: 3 | stack = [-1] 4 | heights.append(0) 5 | result = 0 6 | for i in range(len(heights)): 7 | while stack and heights[i] < heights[stack[-1]]: 8 | left = stack.pop() 9 | h = heights[left] 10 | w = i - stack[-1] - 1 11 | result = max(result, w * h) 12 | stack.append(i) 13 | heights.pop() 14 | return result -------------------------------------------------------------------------------- /Python/Medium/105. Construct Binary Tree from Preorder and Inorder Traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: 9 | if not preorder or not inorder: 10 | return None 11 | root = TreeNode(preorder[0]) 12 | index = inorder.index(preorder[0]) 13 | root.left = self.buildTree(preorder[1:1+index],inorder[:index]) 14 | root.right = self.buildTree(preorder[index+1:], inorder[index+1:]) 15 | return root 16 | 17 | -------------------------------------------------------------------------------- /Python/Medium/106. Construct Binary Tree from Inorder and Postorder Traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: 9 | if not inorder or not postorder: 10 | return None 11 | root = TreeNode(postorder[-1]) 12 | index = inorder.index(postorder[-1]) 13 | root.left = self.buildTree(inorder[:index], postorder[:index]) 14 | root.right = self.buildTree(inorder[index+1:], postorder[index:-1]) 15 | return root 16 | -------------------------------------------------------------------------------- /Python/Medium/11. Container With Most Water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, height: List[int]) -> int: 3 | result = 0 4 | left = 0 5 | right = len(height) - 1 6 | while left < right: 7 | result = max(result, min(height[left], height[right])*(right - left)) 8 | if height[left] < height[right]: 9 | left += 1 10 | else: 11 | right -= 1 12 | return result -------------------------------------------------------------------------------- /Python/Medium/113. Path Sum II.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: 9 | if not root: 10 | return [] 11 | res = [] 12 | self.find(root, sum, [], res) 13 | return res 14 | 15 | def find(self, root, sum, cur, result): 16 | if not root: 17 | return 18 | if root.val == sum and not root.left and not root.right: 19 | result.append(cur+[root.val]) 20 | 21 | self.find(root.left, sum - root.val, cur+[root.val], result) or self.find(root.right, sum - root.val, cur+[root.val], result) -------------------------------------------------------------------------------- /Python/Medium/114. Flatten Binary Tree to Linked List.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def flatten(self, root: TreeNode) -> None: 9 | """ 10 | Do not return anything, modify root in-place instead. 11 | """ 12 | self.flatten_and_find_last(root) 13 | 14 | def flatten_and_find_last(self, root): 15 | if root is None: 16 | return None 17 | 18 | left_last = self.flatten_and_find_last(root.left) 19 | right_last = self.flatten_and_find_last(root.right) 20 | 21 | if left_last: 22 | left_last.right = root.right 23 | root.right = root.left 24 | root.left = None 25 | 26 | return right_last or left_last or root -------------------------------------------------------------------------------- /Python/Medium/116. Populating Next Right Pointers in Each Node.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | self.next = next 9 | """ 10 | 11 | class Solution: 12 | def connect(self, root: 'Node') -> 'Node': 13 | if not root: 14 | return None 15 | 16 | root.next = None 17 | tmp = root 18 | while tmp and tmp.left: 19 | node = tmp 20 | while node: 21 | node.left.next = node.right 22 | if node.next: 23 | node.right.next = node.next.left 24 | else: 25 | node.right.next = None 26 | node = node.next 27 | 28 | tmp = tmp.left 29 | 30 | return root 31 | 32 | 33 | -------------------------------------------------------------------------------- /Python/Medium/117. Populating Next Right Pointers in Each Node II.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | self.next = next 9 | """ 10 | 11 | class Solution: 12 | def connect(self, root: 'Node') -> 'Node': 13 | if not root: 14 | return None 15 | 16 | cur = dummy = Node(0) 17 | node = root 18 | while node: 19 | cur.next = node.left 20 | if cur.next: 21 | cur = cur.next 22 | cur.next = node.right 23 | if cur.next: 24 | cur = cur.next 25 | node = node.next 26 | 27 | if not node: 28 | node = dummy.next 29 | cur = dummy 30 | 31 | return root 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Python/Medium/120. Triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumTotal(self, triangle: List[List[int]]) -> int: 3 | 4 | for i in range(1,len(triangle)): 5 | if i == 1: 6 | triangle[i] = [j + triangle[0][0] for j in triangle[i]] 7 | continue 8 | 9 | 10 | for j in range(len(triangle[i])): 11 | if j == 0: 12 | triangle[i][j] = triangle[i][j]+triangle[i-1][j] 13 | elif j == i: 14 | triangle[i][j] = triangle[i][j]+triangle[i-1][j-1] 15 | else: 16 | triangle[i][j] = min(triangle[i][j]+triangle[i-1][j-1], triangle[i][j]+triangle[i-1][j]) 17 | 18 | return min(triangle[-1]) 19 | 20 | -------------------------------------------------------------------------------- /Python/Medium/127. Word Ladder.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | class Solution: 3 | def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: 4 | if endWord not in wordList: 5 | return 0 6 | 7 | wordList = set(wordList) 8 | chars = list(set([i for word in wordList for i in word ])) 9 | queue = deque([(beginWord, 1)]) 10 | 11 | while queue: 12 | beginWord, level = queue.popleft() 13 | if beginWord == endWord: 14 | return level 15 | 16 | for i in range(len(beginWord)): 17 | for j in chars: 18 | cur = beginWord[:i] + j + beginWord[i+1:] 19 | if cur in wordList: 20 | wordList.remove(cur) 21 | queue.append((cur, level+1)) 22 | 23 | return 0 24 | 25 | -------------------------------------------------------------------------------- /Python/Medium/129. Sum Root to Leaf Numbers.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def sumNumbers(self, root: TreeNode) -> int: 9 | if not root: 10 | return 0 11 | result = [] 12 | self.find(root, result, 0) 13 | return sum(result) 14 | 15 | 16 | def find(self, root, res, cur): 17 | if not root.left and not root.right: 18 | res.append(cur*10+root.val) 19 | return 20 | 21 | if root.left and root.right: 22 | self.find(root.left, res, cur*10 + root.val) or self.find(root.right, res, cur*10 + root.val) 23 | if root.left and not root.right: 24 | self.find(root.left, res, cur*10 + root.val) 25 | if not root.left and root.right: 26 | self.find(root.right, res, cur*10 + root.val) 27 | -------------------------------------------------------------------------------- /Python/Medium/131. Palindrome Partitioning.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def partition(self, s: str) -> List[List[str]]: 3 | results = [] 4 | self.findPalindrome(s, [], results) 5 | return results 6 | 7 | def findPalindrome(self, s, palindromes, results): 8 | if not s: 9 | results.append(list(palindromes)) 10 | 11 | for i in range(len(s)): 12 | if not self.isPalindrome(s[:i+1]): 13 | continue 14 | palindromes.append(s[:i+1]) 15 | self.findPalindrome(s[i+1:], palindromes, results) 16 | palindromes.pop() 17 | 18 | 19 | def isPalindrome(self, s): 20 | l, r = 0, len(s)-1 21 | while l <= r: 22 | if s[l] != s[r]: 23 | return False 24 | l += 1 25 | r -= 1 26 | 27 | return True -------------------------------------------------------------------------------- /Python/Medium/134. Gas Station.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 3 | if sum(gas) < sum(cost): 4 | return -1 5 | 6 | diff = 0 7 | pos = 0 8 | for i in range(len(gas)): 9 | diff += (gas[i] - cost[i]) 10 | if diff < 0: 11 | pos = i + 1 12 | diff = 0 13 | 14 | return pos 15 | -------------------------------------------------------------------------------- /Python/Medium/1353. Maximum Number of Events That Can Be Attended.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxEvents(self, A): 3 | A.sort(reverse=1) 4 | print(A) 5 | h = [] 6 | res = d = 0 7 | while A or h: 8 | if not h: d = A[-1][0] 9 | while A and A[-1][0] <= d: 10 | heapq.heappush(h, A.pop()[1]) 11 | heapq.heappop(h) 12 | res += 1 13 | d += 1 14 | while h and h[0] < d: 15 | heapq.heappop(h) 16 | return res -------------------------------------------------------------------------------- /Python/Medium/137. Single Number II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: List[int]) -> int: 3 | return (3 * sum(set(nums)) - sum(nums)) // 2 -------------------------------------------------------------------------------- /Python/Medium/138. Copy List with Random Pointer.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): 5 | self.val = int(x) 6 | self.next = next 7 | self.random = random 8 | """ 9 | 10 | class Solution: 11 | def copyRandomList(self, head: 'Node') -> 'Node': 12 | dummy = Node(0) 13 | cur_new = dummy 14 | cur = head 15 | dct = {} 16 | dct[None] = None 17 | 18 | while cur: 19 | cur_new.next = Node(cur.val) 20 | cur_new = cur_new.next 21 | dct[cur] = cur_new 22 | cur = cur.next 23 | cur_new.next = None 24 | 25 | cur_new = dummy.next 26 | cur = head 27 | while cur: 28 | cur_new.random = dct[cur.random] 29 | cur = cur.next 30 | cur_new = cur_new.next 31 | 32 | return dummy.next 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Python/Medium/139. Word Break.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordBreak(self, s: str, wordDict: List[str]) -> bool: 3 | if not s: 4 | return True 5 | 6 | dp = [False] * (len(s) + 1) 7 | dp[0] = True 8 | 9 | max_len = max([len(word) for word in wordDict]) if wordDict else 0 10 | for i in range(1, len(s) + 1): 11 | for l in range(1, max_len + 1): 12 | 13 | if i < l: 14 | break 15 | 16 | if not dp[i - l]: 17 | continue 18 | 19 | if s[i - l: i] in wordDict: 20 | dp[i] = True 21 | break 22 | 23 | return dp[-1] -------------------------------------------------------------------------------- /Python/Medium/144. Binary Tree Preorder Traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def preorderTraversal(self, root: TreeNode) -> List[int]: 9 | result = [] 10 | self.preorder(root, result) 11 | return result 12 | 13 | def preorder(self, root, result): 14 | if not root: 15 | return 16 | 17 | result.append(root.val) 18 | self.preorder(root.left, result) 19 | self.preorder(root.right, result) 20 | -------------------------------------------------------------------------------- /Python/Medium/145. Binary Tree Postorder Traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def postorderTraversal(self, root: TreeNode) -> List[int]: 9 | result = [] 10 | self.postorder(root, result) 11 | return result 12 | 13 | def postorder(self, root, result): 14 | if not root: 15 | return 16 | 17 | self.postorder(root.left, result) 18 | self.postorder(root.right, result) 19 | result.append(root.val) 20 | -------------------------------------------------------------------------------- /Python/Medium/147. Insertion Sort List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def insertionSortList(self, head: ListNode) -> ListNode: 8 | dummy = ListNode(0) 9 | dummy.next = head 10 | 11 | while head and head.next: 12 | if head.val < head.next.val: 13 | head = head.next 14 | else: 15 | pre = dummy 16 | insert = head.next 17 | while pre.next.val < insert.val: 18 | pre = pre.next 19 | 20 | insert_next= insert.next 21 | pre_next = pre.next 22 | 23 | pre.next = insert 24 | insert.next = pre_next 25 | head.next = insert_next 26 | 27 | return dummy.next 28 | 29 | -------------------------------------------------------------------------------- /Python/Medium/150. Evaluate Reverse Polish Notation.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def evalRPN(self, tokens: List[str]) -> int: 3 | stack = [] 4 | for t in tokens: 5 | if t not in '+-/*': 6 | stack.append(int(t)) 7 | else: 8 | r, l = stack.pop(), stack.pop() 9 | if t == '+': 10 | stack.append( l+r) 11 | elif t == '-': 12 | stack.append( l - r) 13 | elif t == '*': 14 | stack.append( l * r) 15 | else: 16 | stack.append( int(float(l)/r)) 17 | 18 | return stack.pop() -------------------------------------------------------------------------------- /Python/Medium/152. Maximum Product Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, nums: List[int]) -> int: 3 | ans, max_prod, min_prod = nums[0], nums[0], nums[0] 4 | 5 | for num in nums[1:]: 6 | x = max(num, max_prod * num, min_prod * num) 7 | y = min(num, max_prod * num, min_prod * num) 8 | max_prod, min_prod = x, y 9 | ans = max(ans, max_prod) 10 | 11 | return ans 12 | -------------------------------------------------------------------------------- /Python/Medium/153. Find Minimum in Rotated Sorted Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMin(self, nums: List[int]) -> int: 3 | if not nums: 4 | return -1 5 | 6 | start, end = 0, len(nums) - 1 7 | while start + 1 < end: 8 | 9 | mid = start + (end - start) // 2 10 | if nums[mid] <= nums[end]: 11 | end = mid 12 | else: 13 | start = mid 14 | 15 | return min(nums[start], nums[end]) -------------------------------------------------------------------------------- /Python/Medium/156. Binary Tree Upside Down.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def upsideDownBinaryTree(self, root: TreeNode) -> TreeNode: 9 | if not root or not root.left: 10 | return root 11 | 12 | queue = [] 13 | node = root 14 | while node and node.left: 15 | queue.append(node) 16 | node = node.left 17 | 18 | new_root = node 19 | while queue: 20 | new_right = queue.pop() 21 | new_left = new_right.right 22 | new_right.right = None 23 | new_right.left = None 24 | node.left = new_left 25 | node.right = new_right 26 | node = new_right 27 | 28 | return new_root 29 | 30 | -------------------------------------------------------------------------------- /Python/Medium/159. Longest Substring with At Most Two Distinct Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int: 3 | begin, ans = 0, 0 4 | dct = {} 5 | 6 | for i in range(len(s)): 7 | if s[i] not in dct: 8 | dct[s[i]] = 1 9 | else: 10 | dct[s[i]] += 1 11 | 12 | 13 | while len(dct) > 2: 14 | if dct[s[begin]] > 1: 15 | dct[s[begin]] -= 1 16 | else: 17 | del dct[s[begin]] 18 | begin += 1 19 | 20 | if len(dct) <= 2: 21 | ans = max(ans, sum(dct.values())) 22 | 23 | return ans 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Python/Medium/16. 3Sum Closest.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSumClosest(self, num: List[int], target: int) -> int: 3 | num.sort() 4 | result = num[0] + num[1] + num[2] 5 | for i in range(len(num) - 2): 6 | j, k = i+1, len(num) - 1 7 | while j < k: 8 | sum = num[i] + num[j] + num[k] 9 | if sum == target: 10 | return sum 11 | 12 | if abs(sum - target) < abs(result - target): 13 | result = sum 14 | 15 | if sum < target: 16 | j += 1 17 | elif sum > target: 18 | k -= 1 19 | 20 | return result -------------------------------------------------------------------------------- /Python/Medium/161. One Edit Distance.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def isOneEditDistance(self, s: str, t: str) -> bool: 4 | if s == t or abs(len(s) - len(t)) > 1: 5 | return False 6 | 7 | index_s, index_t = 0, 0 8 | 9 | diff = 0 10 | while index_s < len(s) and index_t < len(t): 11 | if diff > 1: 12 | return False 13 | if s[index_s] == t[index_t]: 14 | index_s += 1 15 | index_t += 1 16 | else: 17 | diff += 1 18 | if len(s) > len(t): 19 | index_s += 1 20 | elif len(s) < len(t): 21 | index_t += 1 22 | else: 23 | index_s += 1 24 | index_t += 1 25 | 26 | return diff <= 1 27 | -------------------------------------------------------------------------------- /Python/Medium/162. Find Peak Element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findPeakElement(self, nums: List[int]) -> int: 3 | if not nums: 4 | return None 5 | 6 | left, right = 0, len(nums) - 1 7 | while left + 1 < right: 8 | mid = left + (right - left) // 2 9 | 10 | if nums[mid - 1] > nums[mid]: 11 | right = mid 12 | elif nums[mid] < nums[mid + 1]: 13 | left = mid 14 | else: 15 | return mid 16 | 17 | 18 | if nums[left] > nums[right]: 19 | return left 20 | else: 21 | return right -------------------------------------------------------------------------------- /Python/Medium/179. Largest Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestNumber(self, nums: List[int]) -> str: 3 | for i in range(len(nums) - 1, 0, -1): 4 | for j in range(len(nums) - 2, len(nums) - i - 2, -1): 5 | if str(nums[j]) + str(nums[j + 1]) < str(nums[j + 1]) + str(nums[j]): 6 | nums[j], nums[j + 1] = nums[j + 1], nums[j] 7 | 8 | return str(int("".join(map(str, nums)))) 9 | 10 | 11 | 12 | # bubble sort 13 | def largestNumber2(self, nums): 14 | for i in xrange(len(nums), 0, -1): 15 | for j in xrange(i-1): 16 | if not self.compare(nums[j], nums[j+1]): 17 | nums[j], nums[j+1] = nums[j+1], nums[j] 18 | return str(int("".join(map(str, nums)))) 19 | 20 | def compare(self, n1, n2): 21 | return str(n1) + str(n2) > str(n2) + str(n1) -------------------------------------------------------------------------------- /Python/Medium/187. Repeated DNA Sequences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findRepeatedDnaSequences(self, s: str) -> List[str]: 3 | word_set = set() 4 | result = set() 5 | for i in range(len(s) - 9): 6 | if s[i:i + 10] not in word_set: 7 | word_set.add(s[i:i + 10]) 8 | else: 9 | result.add(s[i:i + 10]) 10 | 11 | return list(result) 12 | -------------------------------------------------------------------------------- /Python/Medium/19. Remove Nth Node From End of List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 9 | dummy = ListNode(0) 10 | dummy.next = head 11 | fast = slow = dummy 12 | for _ in range(n): 13 | fast = fast.next 14 | while fast and fast.next: 15 | fast = fast.next 16 | slow = slow.next 17 | if slow.next is not None: 18 | slow.next = slow.next.next 19 | return dummy.next -------------------------------------------------------------------------------- /Python/Medium/198. House Robber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | if not nums: 4 | return 0 5 | 6 | if len(nums) <= 2: 7 | return max(nums) 8 | 9 | front, back = nums[0], nums[1] 10 | result = max(front, back) 11 | 12 | for i in range(2, len(nums)): 13 | tmp = max(front + nums[i], back) 14 | result = max(result, tmp) 15 | front = max(front, back) 16 | back = max(back, tmp) 17 | 18 | return result 19 | 20 | 21 | class Solution: 22 | 23 | def rob(self, nums): 24 | 25 | last, now = 0, 0 26 | 27 | for i in nums: 28 | last, now = now, max(last + i, now) 29 | 30 | return now -------------------------------------------------------------------------------- /Python/Medium/199. Binary Tree Right Side View.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | from collections import deque 8 | class Solution: 9 | def rightSideView(self, root: TreeNode) -> List[int]: 10 | if not root: 11 | return [] 12 | 13 | result = [] 14 | queue = deque([root]) 15 | while queue: 16 | result.append(queue[-1].val) 17 | for _ in range(len(queue)): 18 | node = queue.popleft() 19 | if node.left: 20 | queue.append(node.left) 21 | if node.right: 22 | queue.append(node.right) 23 | 24 | return result 25 | -------------------------------------------------------------------------------- /Python/Medium/201. Bitwise AND of Numbers Range.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rangeBitwiseAnd(self, m: int, n: int) -> int: 3 | # Time Limit Exceeded 4 | # result = m 5 | # for i in range(m+1, n+1): 6 | # result &= i 7 | # return result 8 | 9 | shift = 0 10 | while m < n: 11 | m = m >> 1 12 | n = n >> 1 13 | shift += 1 14 | 15 | return m << shift 16 | -------------------------------------------------------------------------------- /Python/Medium/209. Minimum Size Subarray Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSubArrayLen(self, s: int, nums: List[int]) -> int: 3 | slow = 0 4 | sumation = 0 5 | length = len(nums) + 1 6 | for i in range(len(nums)): 7 | sumation += nums[i] 8 | 9 | while sumation >= s: 10 | length = min(i - slow + 1, length) 11 | sumation -= nums[slow] 12 | slow += 1 13 | 14 | return length if length < len(nums) + 1 else 0 -------------------------------------------------------------------------------- /Python/Medium/213. House Robber II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | if not nums: 4 | return 0 5 | elif len(nums) == 1: 6 | return nums[0] 7 | return max(self.no_cycle(nums, 0, len(nums)-1), self.no_cycle(nums, 1, len(nums))) 8 | 9 | def no_cycle(self, nums, begin, end): 10 | last, now = 0, 0 11 | for i in nums[begin:end]: 12 | last, now = max(last, now), max(now, last + i) 13 | return now 14 | -------------------------------------------------------------------------------- /Python/Medium/216. Combination Sum III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum3(self, k: int, n: int) -> List[List[int]]: 3 | if n < k: 4 | return [] 5 | result = [] 6 | self.backtrack(list(range(1, min(n, 9) + 1)), 0, k, n, [], result) 7 | return result 8 | 9 | def backtrack(self, nums, index, k, target, cur, result): 10 | if len(cur) == k and target == 0: 11 | result.append(list(cur)) 12 | 13 | if target <= 0: 14 | return 15 | 16 | for i in range(index, len(nums)): 17 | cur.append(nums[i]) 18 | self.backtrack(nums, i+1, k, target - nums[i], cur, result) 19 | cur.pop() -------------------------------------------------------------------------------- /Python/Medium/220. Contains Duplicate III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: 3 | if t < 0: 4 | return False 5 | 6 | n = len(nums) 7 | d = {} 8 | w = t + 1 9 | 10 | for i in range(n): 11 | m = nums[i] // w 12 | if m in d: 13 | return True 14 | if m - 1 in d and abs(d[m - 1] - nums[i]) <= t: 15 | return True 16 | if m + 1 in d and abs(d[m + 1] - nums[i]) <= t: 17 | return True 18 | 19 | d[m] = nums[i] 20 | 21 | if i >= k: 22 | del d[nums[i - k] // w] 23 | 24 | return False 25 | 26 | -------------------------------------------------------------------------------- /Python/Medium/221. Maximal Square.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximalSquare(self, matrix: List[List[str]]) -> int: 3 | if not matrix: 4 | return 0 5 | 6 | max_size = 0 7 | m, n = len(matrix), len(matrix[0]) 8 | dp = [[0] * (n + 1) for _ in range(m + 1)] 9 | 10 | for i in range(m): 11 | for j in range(n): 12 | if matrix[i][j] == "1": 13 | dp[i + 1][j + 1] = min(dp[i][j], dp[i + 1][j], dp[i][j + 1]) + 1 14 | max_size = max(dp[i + 1][j + 1], max_size) 15 | 16 | return max_size ** 2 17 | -------------------------------------------------------------------------------- /Python/Medium/223. Rectangle Area.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int: 3 | if E >= C or A >= G or B >= H or F >= D: 4 | area = 0 5 | else: 6 | area = (min(C, G) - max(A, E)) * (min(D, H) - max(B, F)) 7 | 8 | return (D - B) * (C - A) + (G - E) * (H - F) - area -------------------------------------------------------------------------------- /Python/Medium/227. Basic Calculator II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def calculate(self, s: str) -> int: 3 | if not s: 4 | return 0 5 | 6 | stack, num, sign = [], 0, "+" 7 | 8 | for i in range(len(s)): 9 | if s[i].isdigit(): 10 | num = num * 10 + int(s[i]) 11 | if (not s[i].isdigit() and s[i] != " " ) or i == len(s) - 1: 12 | if sign == '+': 13 | stack.append(num) 14 | if sign == "-": 15 | stack.append(-num) 16 | if sign == '*': 17 | num = stack.pop() * num 18 | stack.append(num) 19 | if sign == '/': 20 | tmp = stack.pop() 21 | if tmp < 0 and tmp % num != 0: 22 | stack.append(tmp // num + 1) 23 | else: 24 | stack.append(tmp // num) 25 | 26 | sign = s[i] 27 | num = 0 28 | 29 | return sum(stack) 30 | -------------------------------------------------------------------------------- /Python/Medium/229. Majority Element II.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def majorityElement(self, nums: List[int]) -> List[int]: 4 | # counter = Counter(nums) 5 | # result = [] 6 | 7 | # for key, value in counter.items(): 8 | # if value > len(nums) // 3: 9 | # result.append(key) 10 | 11 | # return result 12 | 13 | if not nums: 14 | return [] 15 | 16 | count1, count2, num1, num2 = 0, 0, 0, 1 17 | for num in nums: 18 | if num == num1: 19 | count1 += 1 20 | elif num == num2: 21 | count2 += 1 22 | elif count1 == 0: 23 | num1 = num 24 | count1 = 1 25 | elif count2 == 0: 26 | num2 = num 27 | count2 = 1 28 | else: 29 | count1 -= 1 30 | count2 -= 1 31 | 32 | return [i for i in (num1, num2) if nums.count(i) > len(nums) // 3] 33 | -------------------------------------------------------------------------------- /Python/Medium/230. Kth Smallest Element in a BST.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def kthSmallest(self, root: TreeNode, k: int) -> int: 9 | count = k 10 | stack = [] 11 | node = root 12 | while node or stack: 13 | while node: 14 | stack.append(node) 15 | node = node.left 16 | node = stack.pop() 17 | count -= 1 18 | if count == 0: 19 | return node.val 20 | node = node.right 21 | 22 | -------------------------------------------------------------------------------- /Python/Medium/238. Product of Array Except Self.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def productExceptSelf(self, nums: List[int]) -> List[int]: 3 | ans = [0] * len(nums) 4 | 5 | ans[0] = 1 6 | for i in range(1, len(nums)): 7 | ans[i] = ans[i - 1] * nums[i - 1] 8 | 9 | 10 | right = 1 11 | for i in range(len(nums) - 1, -1, -1): 12 | ans[i] = ans[i] * right 13 | right *= nums[i] 14 | 15 | return ans -------------------------------------------------------------------------------- /Python/Medium/241. Different Ways to Add Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def diffWaysToCompute(self, input: str) -> List[int]: 3 | result = [] 4 | 5 | if "+" not in input and "-" not in input and "*" not in input: 6 | return [int(input)] 7 | 8 | for i, v in enumerate(input): 9 | if v == "+" or v == "-" or v == "*": 10 | left = self.diffWaysToCompute(input[:i]) 11 | right = self.diffWaysToCompute(input[i+1:]) 12 | 13 | for l in left: 14 | for r in right: 15 | if v == "+": 16 | result.append(l + r) 17 | if v == "-": 18 | result.append(l - r) 19 | if v == "*": 20 | result.append(l * r) 21 | 22 | return result 23 | -------------------------------------------------------------------------------- /Python/Medium/244. Shortest Word Distance II.py: -------------------------------------------------------------------------------- 1 | class WordDistance: 2 | 3 | def __init__(self, words: List[str]): 4 | self.dct, self.length = {}, len(words) 5 | for i, word in enumerate(words): 6 | self.dct[word] = self.dct.get(word, []) + [i] 7 | 8 | def shortest(self, word1: str, word2: str) -> int: 9 | list1 = self.dct[word1] 10 | list2 = self.dct[word2] 11 | 12 | ans = self.length 13 | l1 = l2 = 0 14 | while l1 < len(list1) and l2 < len(list2): 15 | ans = min(ans, abs(list1[l1] - list2[l2])) 16 | if list1[l1] < list2[l2]: 17 | l1 += 1 18 | else: 19 | l2 += 1 20 | 21 | return ans 22 | 23 | 24 | 25 | 26 | 27 | # Your WordDistance object will be instantiated and called as such: 28 | # obj = WordDistance(words) 29 | # param_1 = obj.shortest(word1,word2) -------------------------------------------------------------------------------- /Python/Medium/245. Shortest Word Distance III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shortestWordDistance(self, words: List[str], word1: str, word2: str) -> int: 3 | current_word, current_index = None, 0 4 | result = len(words) 5 | for i, word in enumerate(words): 6 | if word != word1 and word != word2: 7 | continue 8 | if current_word and word != current_word: 9 | result = min(result, i - current_index) 10 | elif current_word and word1 == word2: 11 | result = min(result, i - current_index) 12 | current_word, current_index = word, i 13 | 14 | return result 15 | 16 | -------------------------------------------------------------------------------- /Python/Medium/249. Group Shifted Strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupStrings(self, strings: List[str]) -> List[List[str]]: 3 | dct = {} 4 | for s in strings: 5 | key = () 6 | for i in range(len(s) - 1): 7 | diff = 26 + ord(s[i]) - ord(s[i - 1]) 8 | key += (diff % 26,) 9 | dct[key] = dct.get(key, []) + [s] 10 | 11 | return list(dct.values()) 12 | -------------------------------------------------------------------------------- /Python/Medium/250. Count Univalue Subtrees.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def countUnivalSubtrees(self, root: TreeNode) -> int: 9 | self.count = 0 10 | self.recursive(root) 11 | return self.count 12 | 13 | 14 | def recursive(self, root): 15 | if not root: 16 | return True 17 | 18 | left = self.recursive(root.left) 19 | right = self.recursive(root.right) 20 | 21 | if left and right and (not root.left or root.left.val == root.val) and (not root.right or root.right.val == root.val): 22 | self.count += 1 23 | return True 24 | 25 | return False 26 | -------------------------------------------------------------------------------- /Python/Medium/253. Meeting Rooms II.py: -------------------------------------------------------------------------------- 1 | from heapq import * 2 | 3 | class Solution: 4 | def minMeetingRooms(self, intervals: List[List[int]]) -> int: 5 | intervals.sort(key = lambda x: x[0]) 6 | heap = [] 7 | ans = 0 8 | for i in intervals: 9 | if heap and i[0] >= heap[0]: 10 | heapreplace(heap, i[1]) 11 | else: 12 | heappush(heap, i[1]) 13 | ans = max(ans, len(heap)) 14 | 15 | return ans 16 | -------------------------------------------------------------------------------- /Python/Medium/254. Factor Combinations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getFactors(self, n: int) -> List[List[int]]: 3 | result = [] 4 | self.backtrack([], n, result, 2) 5 | return result 6 | 7 | 8 | def backtrack(self, cur, n, result, start): 9 | if n == 1 and len(cur) > 1: 10 | result.append(list(cur)) 11 | 12 | for i in range(start, n + 1): 13 | if n % i == 0 and i != 1: 14 | cur.append(i) 15 | self.backtrack(cur, n//i, result, i) 16 | cur.pop() -------------------------------------------------------------------------------- /Python/Medium/255. Verify Preorder Sequence in Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def verifyPreorder(self, preorder: List[int]) -> bool: 3 | if not preorder: 4 | return True 5 | 6 | stack = [] 7 | lower = -float('inf') 8 | for x in preorder: 9 | if x < lower: 10 | return False 11 | 12 | while stack and x > stack[-1]: 13 | lower = stack.pop() 14 | 15 | stack.append(x) 16 | 17 | return True 18 | 19 | -------------------------------------------------------------------------------- /Python/Medium/256. Paint House.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCost(self, costs: List[List[int]]) -> int: 3 | if not costs: 4 | return 0 5 | 6 | for i in range(1,len(costs)): 7 | costs[i][0] += min(costs[i-1][1],costs[i-1][2]) 8 | costs[i][1] += min(costs[i-1][0],costs[i-1][2]) 9 | costs[i][2] += min(costs[i-1][0],costs[i-1][1]) 10 | 11 | n=len(costs)-1 12 | return min(costs[n][0], costs[n][1], costs[n][2]) 13 | 14 | # red, blue, green = 0, 0, 0 15 | # for cr, cb, cg in costs: 16 | # red, blue, green = min(blue, green) + cr, min(red, green) + cb, min(red, blue) + cg 17 | # return min(red, blue, green) -------------------------------------------------------------------------------- /Python/Medium/259. 3Sum Smaller.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSumSmaller(self, nums: List[int], target: int) -> int: 3 | 4 | nums.sort() 5 | result = 0 6 | for i in range(len(nums) - 2): 7 | left = i + 1 8 | right = len(nums) - 1 9 | 10 | while left < right: 11 | if nums[left] + nums[right] < target - nums[i]: 12 | result += (right - left) 13 | left += 1 14 | else: 15 | right -= 1 16 | 17 | return result -------------------------------------------------------------------------------- /Python/Medium/260. Single Number III.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def singleNumber(self, nums: List[int]) -> List[int]: 4 | counter = Counter(nums) 5 | result = [] 6 | for v, freq in counter.items(): 7 | if freq == 1: 8 | result.append(v) 9 | 10 | return result 11 | -------------------------------------------------------------------------------- /Python/Medium/264. Ugly Number II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nthUglyNumber(self, n: int) -> int: 3 | i2, i3, i5 = 0, 0, 0 4 | ugly = [1] 5 | while len(ugly) < n: 6 | while ugly[i2] * 2 <= ugly[-1]: 7 | i2 += 1 8 | while ugly[i3] * 3 <= ugly[-1]: 9 | i3 += 1 10 | while ugly[i5] * 5 <= ugly[-1]: 11 | i5 += 1 12 | ugly.append(min(ugly[i2] * 2, ugly[i3] * 3, ugly[i5] * 5)) 13 | 14 | return ugly[-1] 15 | -------------------------------------------------------------------------------- /Python/Medium/274. H-Index.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hIndex(self, citations: List[int]) -> int: 3 | tmp = [0] * (len(citations) + 1) 4 | for i in range(len(citations)): 5 | if citations[i] >= len(citations): 6 | tmp[len(citations)] += 1 7 | else: 8 | tmp[citations[i]] += 1 9 | 10 | count = 0 11 | for i in range(len(citations), -1, -1): 12 | count += tmp[i] 13 | if count >= i: 14 | return i 15 | 16 | return 0 -------------------------------------------------------------------------------- /Python/Medium/275. H-Index II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hIndex(self, citations: List[int]) -> int: 3 | if not citations: 4 | return 0 5 | 6 | low, high = 0, len(citations) - 1 7 | while low + 1 < high: 8 | mid = low + (high - low) // 2 9 | h = len(citations) - mid 10 | if citations[mid] >= h: 11 | if mid - 1 >= 0 and citations[mid - 1] >= h + 1: 12 | high = mid 13 | else: 14 | return h 15 | else: 16 | low = mid 17 | 18 | if citations[low] >= len(citations) - low: 19 | return len(citations) - low 20 | if citations[high] >= len(citations) - high: 21 | return len(citations) - high 22 | 23 | return 0 24 | -------------------------------------------------------------------------------- /Python/Medium/277. Find the Celebrity.py: -------------------------------------------------------------------------------- 1 | # The knows API is already defined for you. 2 | # return a bool, whether a knows b 3 | # def knows(a: int, b: int) -> bool: 4 | 5 | class Solution: 6 | def findCelebrity(self, n: int) -> int: 7 | for i in range(0, n): 8 | flag = True 9 | for j in range(0, n): 10 | if j == i: 11 | continue 12 | flag = flag and not knows(i, j) and knows(j, i) 13 | if flag: 14 | return i 15 | 16 | return -1 17 | 18 | 19 | x = 0 20 | for i in range(n): 21 | if knows(x, i): 22 | x = i 23 | 24 | for i in range(x): 25 | if knows(x, i): 26 | return -1 27 | 28 | for i in range(n): 29 | if not knows(i, x): 30 | return -1 31 | -------------------------------------------------------------------------------- /Python/Medium/279. Perfect Squares.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def numSquares(self, n): 4 | dp = [0] + [float('inf')]*n 5 | for i in range(1, n+1): 6 | dp[i] = min(dp[i-j*j] for j in range(1, int(i**0.5)+1)) + 1 7 | return dp[n] -------------------------------------------------------------------------------- /Python/Medium/285. Inorder Successor in BST.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': 10 | succ = None 11 | node = root 12 | while node: 13 | if p.val < node.val: 14 | succ = node 15 | node = node.left 16 | else: 17 | node = node.right 18 | 19 | return succ -------------------------------------------------------------------------------- /Python/Medium/286. Walls and Gates.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | class Solution: 3 | def wallsAndGates(self, rooms: List[List[int]]) -> None: 4 | """ 5 | Do not return anything, modify rooms in-place instead. 6 | """ 7 | def bfs(i, j): 8 | queue = deque([(i,j)]) 9 | while queue: 10 | x, y = queue.popleft() 11 | for (i,j) in [(-1, 0), (1, 0), (0, -1), (0, 1)]: 12 | new_x, new_y = x + i, y + j 13 | if 0 <= new_x < len(rooms) and 0 <= new_y < len(rooms[0]) and rooms[new_x][new_y] != -1 and rooms[x][y] + 1 < rooms[new_x][new_y]: 14 | rooms[new_x][new_y] = rooms[x][y] + 1 15 | queue.append((new_x,new_y)) 16 | 17 | for i in range(len(rooms)): 18 | for j in range(len(rooms[0])): 19 | if rooms[i][j] == -1 or rooms[i][j] == 2147483647: 20 | continue 21 | bfs(i, j) 22 | 23 | 24 | -------------------------------------------------------------------------------- /Python/Medium/287. Find the Duplicate Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicate(self, nums: List[int]) -> int: 3 | for i in range(len(nums)): 4 | if nums[i] < 0: 5 | if nums[-nums[i] - 1] < 0: 6 | return -nums[i] 7 | else: 8 | nums[-nums[i] - 1] = - nums[-nums[i] - 1] 9 | else: 10 | if nums[nums[i] - 1] < 0: 11 | return nums[i] 12 | else: 13 | nums[nums[i] - 1] = - nums[nums[i] - 1] 14 | 15 | 16 | 17 | def findDuplicate(self, nums): 18 | slow = fast = finder = 0 19 | while True: 20 | slow = nums[slow] 21 | fast = nums[nums[fast]] 22 | if slow == fast: 23 | while finder != slow: 24 | finder = nums[finder] 25 | slow = nums[slow] 26 | return finder -------------------------------------------------------------------------------- /Python/Medium/288. Unique Word Abbreviation.py: -------------------------------------------------------------------------------- 1 | class ValidWordAbbr: 2 | 3 | def __init__(self, dictionary: List[str]): 4 | self.abb_count = {} 5 | for word in dictionary: 6 | if len(word) == 1: 7 | abb = word 8 | else: 9 | abb = word[0] + str(len(word[1:-1])) + word[-1] 10 | self.abb_count[abb] = self.abb_count.setdefault(abb, []) 11 | if word not in self.abb_count[abb]: 12 | self.abb_count[abb].append(word) 13 | 14 | def isUnique(self, word: str) -> bool: 15 | if len(word) <= 2: 16 | abb = word 17 | else: 18 | abb = word[0] + str(len(word[1:-1])) + word[-1] 19 | 20 | if abb not in self.abb_count or self.abb_count[abb] == [word]: 21 | return True 22 | return False 23 | 24 | 25 | 26 | # Your ValidWordAbbr object will be instantiated and called as such: 27 | # obj = ValidWordAbbr(dictionary) 28 | # param_1 = obj.isUnique(word) -------------------------------------------------------------------------------- /Python/Medium/29. Divide Two Integers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def divide(self, dividend: int, divisor: int) -> int: 3 | return int(dividend / divisor) if int(dividend / divisor) <= 2**31 -1 else 2**31 -1 4 | 5 | class Solution: 6 | # @return an integer 7 | def divide(self, dividend, divisor): 8 | positive = (dividend < 0) is (divisor < 0) 9 | dividend, divisor = abs(dividend), abs(divisor) 10 | res = 0 11 | while dividend >= divisor: 12 | temp, i = divisor, 1 13 | while dividend >= temp: 14 | dividend -= temp 15 | res += i 16 | i <<= 1 17 | temp <<= 1 18 | if not positive: 19 | res = -res 20 | return min(max(-2147483648, res), 2147483647) -------------------------------------------------------------------------------- /Python/Medium/294. Flip Game II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canWin(self, s: str) -> bool: 3 | flag = False 4 | return self.backtrack(s, flag) 5 | 6 | 7 | def backtrack(self, s, flag): 8 | if not "++" in s: 9 | return False 10 | 11 | for i in range(len(s) - 1): 12 | if s[i:i + 2] == "++": 13 | flag = flag or not self.backtrack(s[:i] + "--" + s[i + 2:], flag) 14 | if flag: 15 | return True 16 | return False 17 | -------------------------------------------------------------------------------- /Python/Medium/298. Binary Tree Longest Consecutive Sequence.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def longestConsecutive(self, root: TreeNode) -> int: 9 | return self.backtrack(root)[-1] 10 | 11 | def backtrack(self, root): 12 | if not root: 13 | return (0, None, 0) 14 | 15 | max_len, root_len = 1, 1 16 | left_len, left_val, max_left = self.backtrack(root.left) 17 | right_len, right_val, max_right = self.backtrack(root.right) 18 | 19 | 20 | if left_val != None and root.val + 1 == left_val: 21 | root_len = max(root_len, left_len + 1) 22 | if right_val != None and root.val + 1 == right_val: 23 | root_len = max(root_len, right_len + 1) 24 | 25 | max_len = max(root_len, max_left, max_right) 26 | 27 | return (root_len, root.val, max_len) 28 | -------------------------------------------------------------------------------- /Python/Medium/3. Longest Substring Without Repeating Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | start = 0 4 | result = 0 5 | mapping = {} 6 | for i in range(len(s)): 7 | if s[i] not in mapping: 8 | mapping[s[i]] = i 9 | else: 10 | if start <= mapping[s[i]]: 11 | start = mapping[s[i]] + 1 12 | mapping[s[i]] = i 13 | 14 | result = max(result, i - start + 1) 15 | 16 | return result 17 | 18 | 19 | -------------------------------------------------------------------------------- /Python/Medium/322. Coin Change.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def coinChange(self, coins: List[int], amount: int) -> int: 3 | 4 | dp = [float('inf')] * (amount + 1) 5 | dp[0] = 0 6 | 7 | for coin in coins: 8 | for j in range(coin, amount + 1): 9 | if dp[j - coin] != float('inf'): 10 | dp[j] = min(dp[j], dp[j - coin] + 1) 11 | 12 | return -1 if dp[amount] == float('inf') else dp[amount] 13 | 14 | -------------------------------------------------------------------------------- /Python/Medium/33. Search in Rotated Sorted Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: an integer rotated sorted array 4 | @param target: an integer to be searched 5 | @return: an integer 6 | """ 7 | def search(self, nums, target): 8 | # write your code here 9 | if not nums: 10 | return -1 11 | 12 | 13 | start, end = 0, len(nums) - 1 14 | while start + 1 < end: 15 | mid = start + (end - start) // 2 16 | 17 | if nums[mid] >= nums[start]: 18 | if nums[start] <= target <= nums[mid]: 19 | end = mid 20 | else: 21 | start = mid 22 | else: 23 | if nums[mid] <= target <= nums[end]: 24 | start = mid 25 | else: 26 | end = mid 27 | 28 | 29 | if nums[start] == target: 30 | return start 31 | if nums[end] == target: 32 | return end 33 | 34 | return -1 35 | -------------------------------------------------------------------------------- /Python/Medium/337. House Robber III.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | from collections import deque 8 | class Solution: 9 | def rob(self, root: TreeNode) -> int: 10 | return max(self.backtrack(root)) 11 | 12 | def backtrack(self, root): 13 | if not root: 14 | return (0, 0) 15 | 16 | now, later = 0, 0 17 | 18 | left = self.backtrack(root.left) 19 | right = self.backtrack(root.right) 20 | 21 | now = root.val + left[1] + right[1] 22 | later = max(left) + max(right) 23 | 24 | return (now, later) 25 | 26 | 27 | -------------------------------------------------------------------------------- /Python/Medium/338. Counting Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countBits(self, num: int) -> List[int]: 3 | if num == 0: 4 | return [0] 5 | 6 | if num == 1: 7 | return [0, 1] 8 | 9 | res = [0, 1] 10 | for i in range(2, num + 1): 11 | now = i & 1 12 | prev = i >> 1 13 | res.append(now + res[prev]) 14 | 15 | return res -------------------------------------------------------------------------------- /Python/Medium/34. Find First and Last Position of Element in Sorted Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchRange(self, nums: List[int], target: int) -> List[int]: 3 | if not nums: 4 | return [-1, -1] 5 | 6 | start, end = 0, len(nums) - 1 7 | end_index = -1 8 | while start + 1 < end: 9 | mid = start + (end - start) // 2 10 | if nums[mid] == target: 11 | start = mid 12 | elif nums[mid] < target: 13 | start = mid 14 | else: 15 | end = mid 16 | 17 | if nums[end] == target: 18 | end_index = end 19 | elif nums[start] == target: 20 | end_index = start 21 | 22 | if end_index == -1: 23 | return [-1, -1] 24 | 25 | start = end_index 26 | while start >= 0 and nums[start] == nums[end_index]: 27 | start -= 1 28 | 29 | return [start + 1, end_index] 30 | 31 | -------------------------------------------------------------------------------- /Python/Medium/340. Longest Substring with At Most K Distinct Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int: 3 | slow, ans = 0, 0 4 | dct = {} 5 | 6 | for i in range(len(s)): 7 | if s[i] not in dct: 8 | dct[s[i]] = 1 9 | else: 10 | dct[s[i]] += 1 11 | 12 | while len(dct) > k: 13 | if dct[s[slow]] == 1: 14 | del dct[s[slow]] 15 | else: 16 | dct[s[slow]] -= 1 17 | slow += 1 18 | 19 | if len(dct) <= k: 20 | ans = max(ans, i - slow + 1) 21 | 22 | return ans -------------------------------------------------------------------------------- /Python/Medium/347. Top K Frequent Elements.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from heapq import * 3 | 4 | class Solution: 5 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 6 | counter = Counter(nums) 7 | 8 | heap = [] 9 | for num, freq in counter.items(): 10 | heappush(heap, (-freq, num)) 11 | 12 | result = [] 13 | while k > 0 and heap: 14 | freq, num = heappop(heap) 15 | result.append(num) 16 | k -= 1 17 | 18 | return result -------------------------------------------------------------------------------- /Python/Medium/36. Valid Sudoku.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValidSudoku(self, board: List[List[str]]) -> bool: 3 | repeat = [] 4 | for i in range(0,9): 5 | for j in range(0,9): 6 | if board[i][j]!='.': 7 | cur = board[i][j] 8 | if (i,cur) in repeat or (cur,j) in repeat or (i//3,j//3,cur) in repeat: 9 | return False 10 | repeat.append((i,cur)) 11 | repeat.append((cur,j)) 12 | repeat.append((i//3,j//3,cur)) 13 | return True 14 | 15 | -------------------------------------------------------------------------------- /Python/Medium/378. Kth Smallest Element in a Sorted Matri.py: -------------------------------------------------------------------------------- 1 | from heapq import * 2 | class Solution: 3 | def kthSmallest(self, matrix: List[List[int]], k: int) -> int: 4 | heap = [] 5 | m,n = len(matrix), len(matrix[0]) 6 | heappush(heap, (matrix[0][0], 0, 0)) 7 | while k > 0: 8 | val, i, j = heappop(heap) 9 | k -= 1 10 | 11 | if i + 1 < m and (matrix[i + 1][j], i + 1, j) not in heap: 12 | heappush(heap, (matrix[i + 1][j], i + 1, j)) 13 | if j + 1 < n and (matrix[i][j + 1], i, j + 1) not in heap: 14 | heappush(heap, (matrix[i][j + 1], i, j + 1)) 15 | 16 | return val 17 | -------------------------------------------------------------------------------- /Python/Medium/39. Combination Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 3 | results = [] 4 | self.find(sorted(list(set(candidates))), 0, target, [], results) 5 | return results 6 | 7 | def find(self, candidates, index, target, combination, results): 8 | if target == 0: 9 | results.append(list(combination)) 10 | if target < 0: 11 | return 12 | 13 | for i in range(index, len(candidates)): 14 | combination.append(candidates[i]) 15 | self.find(candidates, i, target - candidates[i], combination, results) 16 | combination.pop() 17 | -------------------------------------------------------------------------------- /Python/Medium/394. Decode String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def decodeString(self, s: str) -> str: 3 | 4 | num, stack, string = 0, [], "" 5 | 6 | for c in s: 7 | if c.isdigit(): 8 | num = num * 10 + int(c) 9 | 10 | elif c == "[": 11 | stack.append(string) 12 | stack.append(num) 13 | num, string = 0, "" 14 | 15 | 16 | elif c == "]": 17 | n = stack.pop() 18 | prev_string = stack.pop() 19 | 20 | string = prev_string + n * string 21 | 22 | else: 23 | string += c 24 | 25 | return string 26 | 27 | 28 | -------------------------------------------------------------------------------- /Python/Medium/40. Combination Sum II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: 3 | results = [] 4 | self.find(sorted(candidates), 0, target, [], results) 5 | return results 6 | 7 | def find(self, candidates, index, target, combination, results): 8 | if target == 0: 9 | results.append(list(combination)) 10 | if target < 0: 11 | return 12 | 13 | for i in range(index, len(candidates)): 14 | if i > index and candidates[i] == candidates[i-1]: 15 | continue 16 | combination.append(candidates[i]) 17 | self.find(candidates, i+1, target - candidates[i], combination, results) 18 | combination.pop() 19 | -------------------------------------------------------------------------------- /Python/Medium/400. Nth Digit.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findNthDigit(self, n: int) -> int: 3 | if n <= 9: 4 | return n 5 | i, p = 1, 9 6 | while True: 7 | n += p 8 | p = p * 10 + 9 9 | i += 1 10 | if n <= i * p: 11 | return int(str(int((n + i - 1) // i))[(n + i - 1) % i]) 12 | -------------------------------------------------------------------------------- /Python/Medium/402. Remove K Digits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeKdigits(self, num: str, k: int) -> str: 3 | stack = [] 4 | 5 | for i in num: 6 | while stack and k > 0 and i < stack[-1]: 7 | stack.pop() 8 | k -= 1 9 | stack.append(i) 10 | 11 | while k > 0: 12 | stack.pop() 13 | k -= 1 14 | 15 | return "".join(stack).lstrip("0") or "0" -------------------------------------------------------------------------------- /Python/Medium/416. Partition Equal Subset Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canPartition(self, nums: List[int]) -> bool: 3 | if sum(nums) % 2 == 1: 4 | return False 5 | 6 | target = sum(nums) // 2 7 | 8 | dp = [[False] * (target + 1) for _ in range(len(nums) + 1)] 9 | 10 | dp[0][0] = True 11 | 12 | for i in range(1, len(nums) + 1): 13 | for j in range(1, target + 1): 14 | if nums[i - 1] <= j: 15 | dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i - 1]] 16 | else: 17 | dp[i][j] = dp[i - 1][j] 18 | 19 | return dp[-1][-1] -------------------------------------------------------------------------------- /Python/Medium/43. Multiply Strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def multiply(self, num1: str, num2: str) -> str: 3 | mapping = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9} 4 | 5 | 6 | int1 = [] 7 | int2 = [] 8 | 9 | for i in num1: 10 | int1.append(mapping[i]) 11 | for i in num2: 12 | int2.append(mapping[i]) 13 | 14 | return str(self.convertInteger(int1)*self.convertInteger(int2)) 15 | 16 | 17 | def convertInteger(self, num): 18 | return sum( v*10**i for i, v in enumerate(num[::-1])) 19 | -------------------------------------------------------------------------------- /Python/Medium/435. Non-overlapping Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: 3 | if not intervals: 4 | return 0 5 | 6 | intervals.sort(key = lambda x : (x[0], x[1])) 7 | count, prev = 0, intervals[0] 8 | 9 | for i in intervals[1:]: 10 | if i[0] < prev[1]: 11 | count += 1 12 | if i[1] < prev[1]: 13 | prev[1] = i[1] 14 | else: 15 | prev[1] = i[1] 16 | 17 | 18 | 19 | return count -------------------------------------------------------------------------------- /Python/Medium/436. Find Right Interval.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findRightInterval(self, intervals: List[List[int]]) -> List[int]: 3 | result = [] 4 | data = sorted((inter[0], i) for i,inter in enumerate(intervals)) 5 | for i in intervals: 6 | index = bisect.bisect_left(data, (i[1],)) 7 | if index >= len(intervals): 8 | result.append(-1) 9 | else: 10 | result.append(data[index][1]) 11 | return result 12 | -------------------------------------------------------------------------------- /Python/Medium/437. Path Sum III.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def pathSum(self, root: TreeNode, sum: int) -> int: 10 | memo = {0: 1} 11 | 12 | 13 | def find(root, target, cur_sum): 14 | if not root: 15 | return 0 16 | 17 | cur_sum = cur_sum + root.val 18 | cur_res = memo.get(cur_sum - target, 0) 19 | memo[cur_sum] = memo.get(cur_sum, 0) + 1 20 | res = cur_res + find(root.left, target, cur_sum) + find(root.right, target, cur_sum) 21 | memo[cur_sum] -= 1 22 | return res 23 | 24 | return find(root, sum, 0) 25 | -------------------------------------------------------------------------------- /Python/Medium/438. Find All Anagrams in a String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findAnagrams(self, s: str, p: str) -> List[int]: 3 | counter_p = dict(Counter(p)) 4 | 5 | dct, result = {}, [] 6 | k = len(p) 7 | for i in range(len(s)): 8 | dct[s[i]] = dct.get(s[i], 0) + 1 9 | 10 | if i >= k: 11 | if dct[s[i - k]] > 1: 12 | dct[s[i - k]] -= 1 13 | else: 14 | del dct[s[i - k]] 15 | 16 | if dct == counter_p: 17 | result.append(i - k + 1) 18 | 19 | return result 20 | 21 | 22 | -------------------------------------------------------------------------------- /Python/Medium/442. Find All Duplicates in an Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicates(self, nums: List[int]) -> List[int]: 3 | result = [] 4 | for i, num in enumerate(nums): 5 | if num < 0: 6 | idx = -num - 1 7 | if nums[idx] > 0: 8 | nums[idx] = -nums[idx] 9 | else: 10 | result.append(-num) 11 | else: 12 | if nums[num - 1] > 0: 13 | nums[num - 1] = -nums[num - 1] 14 | else: 15 | result.append(num) 16 | return result 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Python/Medium/451. Sort Characters By Frequency.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def frequencySort(self, s: str) -> str: 4 | freq = Counter(s) 5 | freq_list = list(zip(freq.keys(), freq.values())) 6 | return "".join([i[0]*i[1] for i in sorted(freq_list, key = lambda x: x[1], reverse = True)]) -------------------------------------------------------------------------------- /Python/Medium/452. Minimum Number of Arrows to Burst Balloons.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMinArrowShots(self, points: List[List[int]]) -> int: 3 | if not points: 4 | return 0 5 | points.sort(key = lambda x: x[0]) 6 | count = 1 7 | prev = points[0] 8 | for point in points[1:]: 9 | if point[0] > prev[1]: 10 | count += 1 11 | prev = point 12 | else: 13 | prev[0] = max(point[0], prev[0]) 14 | prev[1] = min(point[1], prev[1]) 15 | 16 | return count 17 | -------------------------------------------------------------------------------- /Python/Medium/454. 4Sum II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int: 3 | counter = {} 4 | count = 0 5 | for a in A: 6 | for b in B: 7 | counter[a+b] = counter.get(a+b, 0) + 1 8 | 9 | for c in C: 10 | for d in D: 11 | if -(c+d) in counter: 12 | count += counter[-(c+d)] 13 | 14 | return count -------------------------------------------------------------------------------- /Python/Medium/46. Permutations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def permute(self, nums: List[int]) -> List[List[int]]: 3 | visited = set() 4 | ans = [] 5 | self.backtrack(nums, [], ans, visited) 6 | return ans 7 | 8 | def backtrack(self, nums, permutation, ans, visited): 9 | if len(permutation) == len(nums): 10 | ans.append(list(permutation)) 11 | 12 | for i in nums: 13 | if i in visited: 14 | continue 15 | visited.add(i) 16 | permutation.append(i) 17 | self.backtrack(nums, permutation, ans, visited) 18 | visited.remove(i) 19 | permutation.pop() 20 | 21 | -------------------------------------------------------------------------------- /Python/Medium/462. Minimum Moves to Equal Array Elements II.py: -------------------------------------------------------------------------------- 1 | import math 2 | class Solution: 3 | def minMoves2(self, nums: List[int]) -> int: 4 | n = len(nums) 5 | median = sorted(nums)[n//2] 6 | 7 | result = 0 8 | for num in nums: 9 | result += abs(num - median) 10 | return result -------------------------------------------------------------------------------- /Python/Medium/47. Permutations II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def permuteUnique(self, nums: List[int]) -> List[List[int]]: 3 | nums.sort() 4 | visited = [False] * len(nums) 5 | result = [] 6 | self.backtrack(nums, [], result, visited) 7 | return result 8 | 9 | def backtrack(self, nums, permutation, result, visited): 10 | 11 | if len(permutation) == len(nums): 12 | result.append(list(permutation)) 13 | 14 | for i in range(len(nums)): 15 | if visited[i] == True or (i>0 and nums[i] == nums[i-1] and visited[i-1] == False): 16 | continue 17 | 18 | visited[i] = True 19 | permutation.append(nums[i]) 20 | self.backtrack(nums, permutation, result, visited) 21 | visited[i] = False 22 | permutation.pop() 23 | -------------------------------------------------------------------------------- /Python/Medium/48. Rotate Image.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, matrix: List[List[int]]) -> None: 3 | """ 4 | Do not return anything, modify matrix in-place instead. 5 | """ 6 | 7 | for i in range(len(matrix)-1): 8 | for j in range(i,len(matrix)): 9 | matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] 10 | 11 | for i in range(len(matrix)): 12 | left, right = 0, len(matrix[i])-1 13 | while left <= right: 14 | matrix[i][left], matrix[i][right] = matrix[i][right], matrix[i][left] 15 | left += 1 16 | right -= 1 17 | 18 | -------------------------------------------------------------------------------- /Python/Medium/494. Target Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTargetSumWays(self, nums: List[int], S: int) -> int: 3 | 4 | memo = {} 5 | 6 | def recursive(index, cur_sum): 7 | 8 | if (index, cur_sum) in memo: 9 | return memo[(index, cur_sum)] 10 | 11 | if index == len(nums) and cur_sum == S: 12 | return 1 13 | elif index == len(nums): 14 | return 0 15 | 16 | positive = recursive(index + 1, cur_sum + nums[index]) 17 | negative = recursive(index + 1, cur_sum - nums[index]) 18 | 19 | memo[(index, cur_sum)] = positive + negative 20 | 21 | return memo[(index, cur_sum)] 22 | 23 | return recursive(0, 0) 24 | -------------------------------------------------------------------------------- /Python/Medium/498. Diagonal Traverse.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]: 3 | if not matrix: 4 | return [] 5 | 6 | d = {} 7 | m, n = len(matrix), len(matrix[0]) 8 | for i in range(m): 9 | for j in range(n): 10 | d[i+j] = d.get(i+j, []) + [matrix[i][j]] 11 | 12 | result = [] 13 | for i in sorted(d.keys()): 14 | if i % 2 == 0: 15 | result += d[i][::-1] 16 | else: 17 | result += d[i] 18 | 19 | return result -------------------------------------------------------------------------------- /Python/Medium/50. Pow(x, n).py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x: float, n: int) -> float: 3 | if n <0: 4 | x = 1/x 5 | n = -n 6 | return self.fastPow(x, n) 7 | 8 | 9 | def fastPow(self, x, n): 10 | if n == 0: 11 | return 1 12 | 13 | half = self.fastPow(x, n//2) 14 | if n % 2 == 0: 15 | return half * half 16 | else: 17 | return half * half * x 18 | 19 | 20 | 21 | class Solution(object): 22 | def __init__(self): 23 | self.cache = {} 24 | 25 | def myPow(self, x, n): 26 | if n == 0: 27 | return 1 28 | if n < 0: 29 | return 1.0/self.helper(x, -n) 30 | return self.helper(x, n) 31 | 32 | def helper(self, x, n): 33 | if n in self.cache: 34 | return self.cache[n] 35 | if n == 1: 36 | return x 37 | left = n/2 38 | right = n-left 39 | temp = self.helper(x, left) * self.helper(x, right) 40 | self.cache[n] = temp 41 | return temp -------------------------------------------------------------------------------- /Python/Medium/503. Next Greater Element II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextGreaterElements(self, nums: List[int]) -> List[int]: 3 | stack, result = [], [-1] * len(nums) 4 | for i, num in enumerate(nums + nums): 5 | while stack and stack[-1][1] < num: 6 | idx, val = stack.pop() 7 | if idx < len(nums): 8 | result[idx] = num 9 | stack.append((i, num)) 10 | 11 | 12 | return result -------------------------------------------------------------------------------- /Python/Medium/516. Longest Palindromic Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestPalindromeSubseq(self, s: str) -> int: 3 | if not s: 4 | return 0 5 | 6 | n = len(s) 7 | is_Palindrome = [[0] * n for _ in range(n)] 8 | 9 | for i in range(n): 10 | is_Palindrome[i][i] = 1 11 | 12 | for length in range(2, n + 1): 13 | for i in range(0, n - length + 1): 14 | j = i + length -1 15 | if s[i] == s[j]: 16 | is_Palindrome[i][j] = 2 + is_Palindrome[i+1][j-1] 17 | else: 18 | is_Palindrome[i][j] = max(is_Palindrome[i+1][j], is_Palindrome[i][j-1]) 19 | 20 | return is_Palindrome[0][n-1] -------------------------------------------------------------------------------- /Python/Medium/54. Spiral Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 3 | if not matrix: 4 | return [] 5 | 6 | result = [] 7 | nr, nc = len(matrix), len(matrix[0]) 8 | seen = [[False] * nc for _ in matrix] 9 | 10 | dr = [0, 1, 0, -1] 11 | dc = [1, 0, -1, 0] 12 | 13 | r = c = i = 0 14 | 15 | for _ in range(nr*nc): 16 | result.append(matrix[r][c]) 17 | seen[r][c] = True 18 | 19 | r_next = r + dr[i] 20 | c_next = c + dc[i] 21 | 22 | if 0 <= r_next < nr and 0 <= c_next < nc and not seen[r_next][c_next]: 23 | r, c = r_next, c_next 24 | else: 25 | i = (i+1)%4 26 | r, c = r + dr[i], c + dc[i] 27 | 28 | return result 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Python/Medium/55. Jump Game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | index = len(nums)-1 4 | for i in range(len(nums)-1, -1,-1): 5 | if i+nums[i] >= index: 6 | index=i 7 | 8 | return index == 0 -------------------------------------------------------------------------------- /Python/Medium/556. Next Greater Element III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextGreaterElement(self, n: int) -> int: 3 | nums = str(n) 4 | for i in range(len(nums) - 1, 0, -1): 5 | if nums[i] > nums[i-1]: 6 | idx, start = i, i 7 | while idx < len(nums) and nums[idx] > nums[i-1]: 8 | if nums[idx] < nums[start]: 9 | start = idx 10 | idx += 1 11 | prefix = nums[:i-1] + nums[start] 12 | res = int(prefix + "".join(sorted(list(nums[i-1:start] + nums[start+1:])))) 13 | return res if res < 2**31 else -1 14 | return -1 -------------------------------------------------------------------------------- /Python/Medium/56. Merge Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 3 | 4 | if not intervals: 5 | return [] 6 | 7 | intervals.sort() 8 | result = [intervals[0]] 9 | 10 | for i in range(1,len(intervals)): 11 | temp = result.pop() 12 | 13 | if temp[1] < intervals[i][0]: 14 | result.append(temp) 15 | result.append(intervals[i]) 16 | elif temp[1] >= intervals[i][0] and temp[1] < intervals[i][1]: 17 | result.append([temp[0], intervals[i][1]]) 18 | elif temp[1] >= intervals[i][1]: 19 | result.append(temp) 20 | 21 | 22 | return result -------------------------------------------------------------------------------- /Python/Medium/560. Subarray Sum Equals K.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subarraySum(self, nums: List[int], k: int) -> int: 3 | dct = {0:1} 4 | 5 | cur, ans = 0, 0 6 | for i in nums: 7 | cur += i 8 | ans += dct.get(cur - k, 0) 9 | dct[cur] = dct.get(cur, 0) + 1 10 | 11 | return ans -------------------------------------------------------------------------------- /Python/Medium/581. Shortest Unsorted Continuous Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findUnsortedSubarray(self, nums: List[int]) -> int: 3 | start_val, end_val = float('inf'), -float('inf') 4 | last = len(nums) 5 | 6 | 7 | res = 0 8 | for i in range(1, len(nums)): 9 | if nums[i] < nums[i - 1]: 10 | start_val = min(start_val, nums[i]) 11 | end_val = max(end_val, nums[i - 1]) 12 | if nums[i - 1] == end_val: 13 | last = i 14 | 15 | start, end = len(nums), len(nums) 16 | for i in range(len(nums)): 17 | if nums[i] > start_val: 18 | start = min(start, i) 19 | if nums[i] >= end_val and i != start and i > last: 20 | end = min(end, i) 21 | 22 | 23 | 24 | if start_val != float('inf'): 25 | res = end - start 26 | 27 | return res -------------------------------------------------------------------------------- /Python/Medium/59. Spiral Matrix II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateMatrix(self, n: int) -> List[List[int]]: 3 | result = [[0]*n for i in range(n)] 4 | 5 | seen = [[False]*n for i in range(n)] 6 | 7 | dr = [0,1,0,-1] 8 | dc = [1,0,-1,0] 9 | 10 | c=r=di=0 11 | 12 | for i in range(n*n): 13 | result[r][c] = i+1 14 | seen[r][c] = True 15 | 16 | r_next = r + dr[di] 17 | c_next = c + dc[di] 18 | 19 | if 0 <= c_next < n and 0 <= r_next < n and not seen[r_next][c_next]: 20 | r = r_next 21 | c = c_next 22 | else: 23 | di = (di+1)%4 24 | r = r + dr[di] 25 | c = c + dc[di] 26 | 27 | return result -------------------------------------------------------------------------------- /Python/Medium/60. Permutation Sequence.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def getPermutation(self, n: int, k: int) -> str: 4 | nums = list(range(1, n+1)) 5 | fact = [1] * n 6 | for i in range(1, n): 7 | fact[i] = i * fact[i-1] 8 | 9 | result = "" 10 | for i in range(n-1, -1, -1): 11 | n = (k-1) // fact[i] 12 | result += str(nums[n]) 13 | nums.pop(n) 14 | k = k%fact[i] 15 | 16 | 17 | return result 18 | 19 | 20 | -------------------------------------------------------------------------------- /Python/Medium/61. Rotate List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def rotateRight(self, head: ListNode, k: int) -> ListNode: 8 | if not head: 9 | return None 10 | start = head 11 | length = 0 12 | while start: 13 | start = start.next 14 | length += 1 15 | 16 | k = k%length 17 | 18 | if k == 0: 19 | return head 20 | end = head 21 | 22 | for i in range(length-k-1): 23 | end = end.next 24 | 25 | start = end.next 26 | end.next = None 27 | connect = start 28 | 29 | while connect.next: 30 | connect = connect.next 31 | 32 | connect.next = head 33 | return start 34 | 35 | -------------------------------------------------------------------------------- /Python/Medium/611. Valid Triangle Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def triangleNumber(self, nums: List[int]) -> int: 3 | if not nums: 4 | return 0 5 | 6 | nums. sort() 7 | count = 0 8 | for i in range(2, len(nums)): 9 | left, right = 0, i-1 10 | while left < right: 11 | if nums[left] + nums[right] > nums[i]: 12 | count += right - left 13 | right -= 1 14 | else: 15 | left += 1 16 | 17 | return count 18 | 19 | -------------------------------------------------------------------------------- /Python/Medium/62. Unique Paths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m: int, n: int) -> int: 3 | result = 1 4 | 5 | for i in range(m+n-2,m-1,-1): 6 | result *= i 7 | 8 | for i in range(1,n): 9 | result /= i 10 | 11 | return int(result) -------------------------------------------------------------------------------- /Python/Medium/621. Task Scheduler.py: -------------------------------------------------------------------------------- 1 | from heapq import * 2 | from collections import Counter 3 | 4 | class Solution: 5 | def leastInterval(self, tasks: List[str], n: int) -> int: 6 | counter = Counter(tasks) 7 | 8 | heap = [] 9 | for c, freq in counter.items(): 10 | heappush(heap, (-freq, c)) 11 | 12 | k, res = n + 1, 0 13 | waitlist = [] 14 | while heap: 15 | while k > 0 and heap: 16 | freq, c = heappop(heap) 17 | freq += 1 18 | res += 1 19 | k -= 1 20 | if freq < 0: 21 | waitlist.append((freq, c)) 22 | 23 | if waitlist: 24 | res += k 25 | while waitlist: 26 | (freq, c) = waitlist.pop() 27 | heappush(heap, (freq, c)) 28 | k = n + 1 29 | 30 | return res 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Python/Medium/63. Unique Paths II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: 3 | result = [[0] * len(obstacleGrid[0]) for i in range(len(obstacleGrid))] 4 | 5 | for i in range(len(obstacleGrid)): 6 | for j in range(len(obstacleGrid[0])): 7 | if obstacleGrid[i][j] == 1: 8 | result[i][j] = 0 9 | else: 10 | if i==0 and j==0: 11 | result[i][j] = 1 12 | elif i==0: 13 | result[i][j] = result[i][j-1] 14 | elif j==0: 15 | result[i][j] = result[i-1][j] 16 | else: 17 | result[i][j] = result[i-1][j] + result[i][j-1] 18 | 19 | return result[-1][-1] -------------------------------------------------------------------------------- /Python/Medium/647. Palindromic Substrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSubstrings(self, s: str) -> int: 3 | n = len(s) 4 | dp = [[0] * n for i in range(n, 0, -1)] 5 | 6 | for i in range(n): 7 | dp[i][i] = 1 8 | 9 | 10 | 11 | for i in range(1, n): 12 | for j in range(i): 13 | if s[i] == s[j] and (dp[j + 1][i - 1] == 1 or j == i - 1): 14 | dp[j][i] = 1 15 | 16 | 17 | res = 0 18 | for i in range(n): 19 | res += sum(dp[i]) 20 | 21 | return res 22 | 23 | def countSubstrings(self, s: str) -> int: 24 | n = len(s) 25 | dp = [[0] * n for _ in range(n)] 26 | 27 | res = 0 28 | for i in range(n-1, -1, -1): 29 | for j in range(i, n): 30 | dp[i][j] = s[i] == s[j] and ((j-i+1) < 3 or dp[i+1][j-1]) 31 | res += dp[i][j] 32 | return res 33 | -------------------------------------------------------------------------------- /Python/Medium/680. Valid Palindrome II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validPalindrome(self, s: str) -> bool: 3 | if not s: 4 | return False 5 | 6 | left, right = self.find_diff(0, len(s) - 1, s) 7 | if left >= right: 8 | return True 9 | 10 | return self.is_Palindrome(left + 1, right, s) or self.is_Palindrome(left, right - 1, s) 11 | 12 | 13 | def is_Palindrome(self, left, right, s): 14 | left, right = self.find_diff(left, right, s) 15 | if left >= right: 16 | return True 17 | else: 18 | return False 19 | 20 | 21 | def find_diff(self, left, right, s): 22 | while left < right and s[left] == s[right]: 23 | left += 1 24 | right -= 1 25 | return left, right -------------------------------------------------------------------------------- /Python/Medium/684. Redundant Connection.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: 3 | 4 | parent = list(range(len(edges))) 5 | 6 | def find(x): 7 | if x != parent[x]: 8 | parent[x] = find(parent[x]) 9 | return parent[x] 10 | 11 | def union(x, y): 12 | x, y = find(x), find(y) 13 | if x == y: 14 | return False 15 | parent[x] = y 16 | return True 17 | 18 | for (x,y) in edges: 19 | if not union(x - 1, y - 1): 20 | return [x, y] 21 | -------------------------------------------------------------------------------- /Python/Medium/71. Simplify Path.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def simplifyPath(self, path: str) -> str: 3 | direction_list = [i for i in path.split("/") if i != "" and i != "."] 4 | 5 | stack = [] 6 | 7 | for i in direction_list: 8 | if i != "..": 9 | stack.append(i) 10 | else: 11 | if stack != []: 12 | stack.pop() 13 | 14 | return "/"+"/".join(stack) -------------------------------------------------------------------------------- /Python/Medium/721. Accounts Merge.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]: 3 | 4 | def find(x): 5 | if x != parent[x]: 6 | parent[x] = find(parent[x]) 7 | return parent[x] 8 | 9 | d = {} #email:index 10 | parent = list(range(len(accounts))) 11 | 12 | for i, account in enumerate(accounts): 13 | for email in account[1:]: 14 | if email not in d: 15 | d[email] = i 16 | else: 17 | x, y = find(i), find(d[email]) 18 | parent[x] = y 19 | 20 | tmp = collections.defaultdict(set) #index:email 21 | for i in range(len(accounts)): 22 | tmp[find(i)] = tmp[find(i)].union(set(accounts[i][1:])) 23 | 24 | result = [] 25 | for key, value in tmp.items(): 26 | result.append([accounts[key][0]] +sorted(list(value))) 27 | 28 | return result 29 | 30 | -------------------------------------------------------------------------------- /Python/Medium/737. Sentence Similarity II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def areSentencesSimilarTwo(self, words1: List[str], words2: List[str], pairs: List[List[str]]) -> bool: 3 | l1, l2 = len(words1), len(words2) 4 | if l1 != l2: 5 | return False 6 | 7 | parent = {} 8 | def find(a): 9 | if a not in parent: 10 | parent[a] = a 11 | if a != parent[a]: 12 | parent[a] = find(parent[a]) 13 | return parent[a] 14 | 15 | for a, b in pairs: 16 | x, y = find(a), find(b) 17 | parent[x] = y 18 | 19 | for i in range(l1): 20 | a, b = find(words1[i]), find(words2[i]) 21 | if a != b: 22 | return False 23 | 24 | return True 25 | 26 | -------------------------------------------------------------------------------- /Python/Medium/739. Daily Temperatures.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dailyTemperatures(self, T: List[int]) -> List[int]: 3 | stack = [] 4 | res = [0] * len(T) 5 | 6 | for i, temp in enumerate(T): 7 | while stack and temp > stack[-1][0]: 8 | prev_i = stack.pop()[1] 9 | res[prev_i] = i - prev_i 10 | stack.append([temp, i]) 11 | 12 | return res 13 | -------------------------------------------------------------------------------- /Python/Medium/75. Sort Colors.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortColors(self, nums: List[int]) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | 7 | for i in range(1, len(nums)): 8 | for j in range(0,len(nums)-i): 9 | if nums[j] > nums[j+1]: 10 | nums[j], nums[j+1] = nums[j+1], nums[j] 11 | 12 | 13 | # two pointers solution 14 | red, white, blue = 0, 0, len(nums)-1 15 | 16 | while white <= blue: 17 | if nums[white] == 0: 18 | nums[red], nums[white] = nums[white], nums[red] 19 | white += 1 20 | red += 1 21 | elif nums[white] == 1: 22 | white += 1 23 | else: 24 | nums[blue], nums[white] = nums[white], nums[blue] 25 | blue -= 1 -------------------------------------------------------------------------------- /Python/Medium/77. Combinations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combine(self, n: int, k: int) -> List[List[int]]: 3 | nums = list(range(1, n+1)) 4 | result = [] 5 | self.get_result(nums, 0, [], result, k) 6 | return result 7 | 8 | def get_result(self, nums, index, cur, result, k): 9 | if len(cur) == k: 10 | result.append(list(cur)) 11 | 12 | for i in range(index, len(nums)): 13 | cur.append(nums[i]) 14 | self.get_result(nums, i + 1, cur, result, k) 15 | cur.pop() 16 | 17 | -------------------------------------------------------------------------------- /Python/Medium/78. Subsets.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsets(self, nums: List[int]) -> List[List[int]]: 3 | 4 | result = [] 5 | self.search(nums, 0, [], result) 6 | return result 7 | 8 | 9 | def search(self, nums, index, current, result): 10 | result.append(list(current)) 11 | 12 | for i in range(index, len(nums)): 13 | current.append(nums[i]) 14 | self.search(nums, i + 1, current, result) 15 | current.pop() 16 | -------------------------------------------------------------------------------- /Python/Medium/79. Word Search.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def exist(self, board: List[List[str]], word: str) -> bool: 3 | 4 | def find(i, j, cur, board, word, index): 5 | if index == len(word) : 6 | return True 7 | 8 | if index >= len(word) or i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[index]: 9 | return False 10 | 11 | tmp = board[i][j] 12 | board[i][j] = '#' 13 | 14 | res = find(i+1, j, cur+ board[i][j], board, word, index+1) or find(i-1, j, cur+ board[i][j], board, word, index+1) or find(i, j+1, cur+ board[i][j], board, word, index+1) or find(i, j-1, cur+ board[i][j], board, word, index+1) 15 | 16 | board[i][j] = tmp 17 | 18 | return res 19 | 20 | for i in range(len(board)): 21 | for j in range(len(board[0])): 22 | if find(i,j, "", board, word, 0): 23 | return True 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Python/Medium/8. String to Integer (atoi).py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myAtoi(self, str: str) -> int: 3 | 4 | 5 | ls=list(str.strip()) 6 | if len(ls)==0: 7 | return 0 8 | 9 | if ls[0]=='-': 10 | sign= -1 11 | else: 12 | sign=1 13 | 14 | if ls[0] in ['+','-']: 15 | del ls[0] 16 | num,i=0,0 17 | while i < len(ls) and ls[i].isdigit(): 18 | num=num*10+ord(ls[i]) - ord('0') 19 | i=i+1 20 | return min(2**31-1,max(sign*num,-2**31)) -------------------------------------------------------------------------------- /Python/Medium/80. Remove Duplicates from Sorted Array II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums: List[int]) -> int: 3 | if not nums: 4 | return 0 5 | 6 | if len(nums) <=2 : 7 | return len(nums) 8 | 9 | former, latter = 1, 1 10 | count = 1 11 | 12 | while latter < len(nums): 13 | if nums[latter] == nums[latter-1]: 14 | count += 1 15 | else: 16 | count = 1 17 | 18 | nums[former] = nums[latter] 19 | 20 | if count <= 2: 21 | former += 1 22 | latter += 1 23 | else: 24 | latter += 1 25 | 26 | return former 27 | 28 | 29 | -------------------------------------------------------------------------------- /Python/Medium/81. Search in Rotated Sorted Array II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> bool: 3 | if not nums: 4 | return False 5 | 6 | start, end = 0, len(nums) - 1 7 | while start + 1 < end: 8 | mid = start + (end - start) // 2 9 | if nums[mid] > nums[end]: 10 | if nums[start] <= target <= nums[mid]: 11 | end = mid 12 | else: 13 | start = mid 14 | elif nums[mid] < nums[end]: 15 | 16 | if nums[mid] <= target <= nums[end]: 17 | start = mid 18 | else: 19 | end = mid 20 | else: 21 | end -= 1 22 | 23 | if nums[start] == target: 24 | return True 25 | if nums[end] == target: 26 | return True 27 | 28 | return False -------------------------------------------------------------------------------- /Python/Medium/82. Remove Duplicates from Sorted List II.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def deleteDuplicates(self, head: ListNode) -> ListNode: 8 | l1 = h1 = ListNode(0) 9 | l1.next = head 10 | while head and head.next: 11 | if head.val == head.next.val: 12 | while head and head.next and head.val == head.next.val: 13 | head = head.next 14 | 15 | head = head.next 16 | l1.next = head 17 | else: 18 | head = head.next 19 | l1 = l1.next 20 | 21 | return h1.next 22 | 23 | -------------------------------------------------------------------------------- /Python/Medium/86. Partition List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def partition(self, head: ListNode, x: int) -> ListNode: 8 | l1 = h1 = ListNode(0) 9 | l2 = h2 = ListNode(0) 10 | 11 | while head: 12 | if head.val < x: 13 | l1.next = head 14 | l1 = l1.next 15 | else: 16 | l2.next = head 17 | l2 = l2.next 18 | head = head.next 19 | 20 | l2.next = None 21 | l1.next = h2.next 22 | 23 | return h1.next -------------------------------------------------------------------------------- /Python/Medium/89. Gray Code.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def grayCode(self, n: int) -> List[int]: 3 | results = [0] 4 | 5 | for i in range(n): 6 | results += [v + 2**i for v in results[::-1]] 7 | 8 | return results -------------------------------------------------------------------------------- /Python/Medium/90. Subsets II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: 3 | nums.sort() 4 | result = [] 5 | self.search([], nums, 0, result) 6 | return result 7 | 8 | def search(self, cur, nums, index, result): 9 | result.append(list(cur)) 10 | 11 | for i in range(index, len(nums)): 12 | if i > index and nums[i] == nums[i-1]: 13 | continue 14 | cur.append(nums[i]) 15 | self.search(cur, nums, i+1, result) 16 | cur.pop() 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Python/Medium/91. Decode Ways.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numDecodings(self, s: str) -> int: 3 | # alphabet = [str(i) for i in range(1,27)] 4 | 5 | # def search(cur, s, result): 6 | # #print(s) 7 | # if s == "": 8 | # result.append(cur) 9 | 10 | # for i in range(1,len(s)+1): 11 | # if s[:i] in alphabet: 12 | # search(cur + s[:i], s[i:], result) 13 | 14 | # result = [] 15 | # search("", s, result) 16 | 17 | # return len(result) 18 | result = [0] * (len(s) + 1 ) 19 | result[0] = 1 20 | if s[0] == '0': 21 | result[1] = 0 22 | else: 23 | result[1] = 1 24 | 25 | for i in range(2,len(s)+1): 26 | if 0 < int(s[i-1:i]) < 10: 27 | result[i] += result[i-1] 28 | 29 | if 10 <= int(s[i-2:i]) < 27: 30 | result[i] += result[i-2] 31 | 32 | return result[-1] 33 | -------------------------------------------------------------------------------- /Python/Medium/93. Restore IP Addresses.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def restoreIpAddresses(self, s): 3 | def findIP(cur, s, index, result): 4 | 5 | if s == "" and index == 4: 6 | result.append(cur[:-1]) 7 | elif index >4: 8 | return 9 | 10 | for i in range(1,len(s)+1): 11 | if i > 3: 12 | break 13 | if s[:i] == '0' or (s[0] != '0' and 0 < int(s[:i]) < 256): 14 | findIP(cur + s[:i] + '.', s[i:], index+1, result) 15 | 16 | result = [] 17 | findIP("", s, 0, result) 18 | 19 | return result -------------------------------------------------------------------------------- /Python/Medium/95. Unique Binary Search Trees II.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | 9 | def generateTrees(self, n: int) -> List[TreeNode]: 10 | if n == 0: 11 | return [] 12 | else: 13 | return self.find(1,n) 14 | 15 | def find(self, left, right): 16 | if left > right: 17 | return [None] 18 | 19 | result = [] 20 | 21 | for i in range(left, right+1): 22 | left_nodes = self.find(left, i-1) 23 | right_nodes = self.find(i+1, right) 24 | for l in left_nodes: 25 | for r in right_nodes: 26 | root = TreeNode(i) 27 | root.left = l 28 | root.right = r 29 | result.append(root) 30 | 31 | return result 32 | -------------------------------------------------------------------------------- /Python/Medium/96. Unique Binary Search Trees.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.dp = {} 4 | 5 | def numTrees(self, n: int) -> int: 6 | if n in self.dp: 7 | return self.dp[n] 8 | if n == 0 or n == 1: 9 | return 1 10 | count = 0 11 | for i in range(1, n+1): 12 | count += self.numTrees(i-1) * self.numTrees(n-i) 13 | 14 | self.dp[n] = count 15 | return count -------------------------------------------------------------------------------- /Python/Medium/98. Validate Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def isValidBST(self, root: TreeNode, max_val = float('inf'), min_val = float('-inf')) -> bool: 9 | 10 | if not root: 11 | return True 12 | 13 | if root.val >= max_val or root.val <= min_val: 14 | return False 15 | 16 | return self.isValidBST(root.left, min(max_val, root.val), min_val) and self.isValidBST(root.right, max_val, max(min_val, root.val)) -------------------------------------------------------------------------------- /Python/Medium/986. Interval List Intersections.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: 3 | idx1, idx2 = 0, 0 4 | result = [] 5 | 6 | while idx1 < len(firstList) and idx2 < len(secondList): 7 | start1, end1, start2, end2 = firstList[idx1][0], firstList[idx1][1], secondList[idx2][0], secondList[idx2][1] 8 | 9 | if max(start1, start2) <= min(end1, end2): 10 | result.append([max(start1, start2), min(end1, end2)]) 11 | 12 | if end1 < end2: 13 | idx1 += 1 14 | else: 15 | idx2 += 1 16 | 17 | return result -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Leetcode 2 | 3 | Source code for Leetcode problems 4 | -------------------------------------------------------------------------------- /SQL/Easy/1068. Product Sales Analysis I.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT product_name, 3 | year, 4 | price 5 | FROM sales s 6 | JOIN product p 7 | ON s.product_id = p.product_id 8 | ORDER BY year -------------------------------------------------------------------------------- /SQL/Easy/1142. User Activity for the Past 30 Days II.sql: -------------------------------------------------------------------------------- 1 | -- -- /* Write your T-SQL query statement below */ 2 | SELECT Cast(Avg(sessions) AS DECIMAL(8, 2)) AS average_sessions_per_user 3 | FROM (SELECT user_id, 4 | Count(session_id) AS sessions 5 | FROM activity 6 | WHERE activity_type = 'open_session' 7 | AND Datediff(day, activity_date, '2019-07-27') < 30 8 | GROUP BY user_id) tmp 9 | 10 | 11 | -- seems sql server would only round avg() to integer 12 | -- if we want to use sql server 13 | 14 | -- -- /* Write your T-SQL query statement below */ 15 | SELECT Isnull(Round(Sum(sessions) * 1.00 / Count(user_id), 2), 0.00) AS 16 | average_sessions_per_user 17 | FROM (SELECT user_id, 18 | Count(DISTINCT session_id) AS sessions 19 | FROM activity 20 | WHERE Datediff(day, activity_date, '2019-07-27') < 30 21 | GROUP BY user_id) tmp -------------------------------------------------------------------------------- /SQL/Easy/1251. Average Selling Price.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT u.product_id AS product_id, 3 | Round(Sum(price * units) / Sum(units), 2) AS average_price 4 | FROM unitssold u 5 | JOIN prices p 6 | ON p.product_id = u.product_id 7 | AND p.start_date <= u.purchase_date 8 | AND p.end_date >= u.purchase_date 9 | GROUP BY u.product_id -------------------------------------------------------------------------------- /SQL/Easy/1350. Students With Invalid Departments.sql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT id, 3 | NAME 4 | FROM students 5 | WHERE department_id NOT IN (SELECT id 6 | FROM departments); -------------------------------------------------------------------------------- /SQL/Easy/176. Second Highest Salary.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | -- except for the highest salary, find the next highest salary 3 | -- (the other way is to use dense_rank()) 4 | SELECT Max(salary) AS SecondHighestSalary 5 | FROM employee 6 | WHERE salary NOT IN (SELECT Max(salary) 7 | FROM employee) -------------------------------------------------------------------------------- /SQL/Easy/182. Duplicate Emails.sql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT email 3 | FROM person 4 | GROUP BY email 5 | HAVING Count(email) > 1; -------------------------------------------------------------------------------- /SQL/Easy/196. Delete Duplicate Emails.sql: -------------------------------------------------------------------------------- 1 | -- Write your MySQL query statement below 2 | DELETE FROM Person WHERE 3 | id in (select id 4 | from ( 5 | select id, ROW_NUMBER() OVER (partition by email order by id asc) as ranking 6 | from person 7 | ) t where t.ranking > 1 8 | ); 9 | 10 | -- simpler version 11 | With cte as 12 | ( 13 | Select pp.id as id 14 | from person p 15 | join person pp 16 | on p.email = pp.email and p.id d.salary THEN 'lower' 6 | WHEN c.salary < d.salary THEN 'higher' 7 | ELSE 'same' 8 | end AS comparison 9 | FROM (SELECT Avg(amount) AS salary, 10 | Date_format(pay_date, '%Y-%m') AS month 11 | FROM salary s 12 | GROUP BY Date_format(pay_date, '%Y-%m')) c 13 | JOIN (SELECT Avg(amount) AS salary, 14 | Date_format(pay_date, '%Y-%m') AS month, 15 | department_id 16 | FROM salary s 17 | JOIN employee e 18 | ON s.employee_id = e.employee_id 19 | GROUP BY Date_format(pay_date, '%Y-%m'), 20 | department_id) d 21 | ON c.month = d.month -------------------------------------------------------------------------------- /SQL/Hard/618. Students Report By Geography.sql: -------------------------------------------------------------------------------- 1 | SELECT Min(america) AS America, 2 | Min(asia) AS Asia, 3 | Min(europe) AS Europe 4 | FROM (SELECT Row_number () 5 | OVER ( 6 | partition BY continent 7 | ORDER BY NAME ASC) AS row_num, 8 | CASE 9 | WHEN continent = 'America' THEN NAME 10 | END AS America, 11 | CASE 12 | WHEN continent = 'Europe' THEN NAME 13 | END AS Europe, 14 | CASE 15 | WHEN continent = 'Asia' THEN NAME 16 | END AS Asia 17 | FROM student) tmp 18 | GROUP BY row_num -------------------------------------------------------------------------------- /SQL/Medium/1045. Customers Who Bought All Products.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT customer_id 3 | FROM customer 4 | GROUP BY customer_id 5 | HAVING Count(DISTINCT product_key) = (SELECT Count(*) 6 | FROM product) -------------------------------------------------------------------------------- /SQL/Medium/1077. Project Employees III.sql: -------------------------------------------------------------------------------- 1 | # write your mysql query statement below 2 | SELECT project_id, 3 | employee_id 4 | FROM ( 5 | SELECT p.employee_id AS employee_id, 6 | NAME, 7 | project_id, 8 | Rank() OVER (partition BY project_id ORDER BY experience_years DESC) AS ranking 9 | FROM project p 10 | JOIN employee e 11 | ON p.employee_id = e.employee_id) tmp 12 | WHERE ranking = 1 13 | ORDER BY project_id, 14 | employee_id -------------------------------------------------------------------------------- /SQL/Medium/1098. Unpopular Books.sql: -------------------------------------------------------------------------------- 1 | SELECT book_id, 2 | NAME 3 | FROM (SELECT b.book_id AS book_id, 4 | b.NAME AS NAME, 5 | ISNULL(Sum (IIF (dispatch_date BETWEEN 6 | '2018-06-23' AND '2019-06-23', 7 | quantity, 8 | 0)), 0) AS sales 9 | FROM books b 10 | LEFT JOIN orders o 11 | ON b.book_id = o.book_id 12 | WHERE available_from < '2019-05-23' 13 | GROUP BY b.book_id, 14 | b.NAME) tmp 15 | WHERE sales < 10 16 | ORDER BY book_id ASC; -------------------------------------------------------------------------------- /SQL/Medium/1112. Highest Grade For Each Student.sql: -------------------------------------------------------------------------------- 1 | # write your mysql query statement below 2 | SELECT student_id, 3 | course_id, 4 | grade 5 | FROM ( 6 | SELECT student_id, 7 | course_id, 8 | grade, 9 | Rank() OVER (partition BY student_id ORDER BY grade DESC, course_id ASC) AS ranking 10 | FROM enrollments) tmp 11 | WHERE ranking = 1 -------------------------------------------------------------------------------- /SQL/Medium/1158. Market Analysis I.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT user_id AS buyer_id, 3 | join_date, 4 | Count(order_id) AS orders_in_2019 5 | FROM users u 6 | LEFT JOIN (SELECT order_id, 7 | buyer_id 8 | FROM orders 9 | WHERE Year(order_date) = 2019) o 10 | ON u.user_id = o.buyer_id 11 | GROUP BY user_id, 12 | join_date -------------------------------------------------------------------------------- /SQL/Medium/1193. Monthly Transactions I.sql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT Date_format(trans_date, '%Y-%m') AS month, 3 | country, 4 | Count(*) AS trans_count, 5 | SUM(IF(state = 'approved', 1, 0)) AS approved_count, 6 | SUM(amount) AS trans_total_amount, 7 | SUM(IF(state = 'approved', amount, 0)) AS approved_total_amount 8 | FROM transactions 9 | GROUP BY Date_format(trans_date, '%Y-%m'), 10 | country -------------------------------------------------------------------------------- /SQL/Medium/1270. All People Report to the Given Manager.sql: -------------------------------------------------------------------------------- 1 | -- write your mysql query statement below 2 | WITH recursive cte AS 3 | ( 4 | SELECT 0 AS n , 5 | 1 AS employee_id 6 | FROM employees 7 | UNION ALL 8 | SELECT cte.n+1, 9 | e.employee_id 10 | FROM employees e 11 | JOIN cte 12 | ON e.manager_id = cte.employee_id 13 | WHERE n < 3 ) 14 | 15 | SELECT DISTINCT employee_id 16 | FROM cte 17 | WHERE employee_id != 1 ; -------------------------------------------------------------------------------- /SQL/Medium/1321. Restaurant Growth.sql: -------------------------------------------------------------------------------- 1 | # write your mysql query statement below 2 | SELECT visited_on, 3 | sum(amount) OVER (ORDER BY visited_on ASC rows BETWEEN 6 PRECEDING AND CURRENT row ) AS amount, 4 | round(avg(amount) OVER (ORDER BY visited_on ASC rows BETWEEN 6 PRECEDING AND CURRENT row),2) AS average_amount 5 | FROM ( 6 | SELECT visited_on, 7 | sum(amount) AS amount 8 | FROM customer 9 | GROUP BY visited_on ) tmp limit 6, 10 | 100 -------------------------------------------------------------------------------- /SQL/Medium/1341. Movie Rating.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | (SELECT name AS results 3 | FROM movie_rating r 4 | JOIN users u 5 | ON r.user_id = u.user_id 6 | GROUP BY r.user_id 7 | ORDER BY Count(*) DESC, 8 | name ASC 9 | LIMIT 1) 10 | UNION 11 | (SELECT title AS results 12 | FROM movie_rating r 13 | JOIN movies m 14 | ON r.movie_id = m.movie_id 15 | WHERE Month(created_at) = 2 16 | GROUP BY r.movie_id 17 | ORDER BY Avg(rating) DESC, 18 | title ASC 19 | LIMIT 1) -------------------------------------------------------------------------------- /SQL/Medium/1355. Activity Participants.sql: -------------------------------------------------------------------------------- 1 | # # write your mysql query statement below 2 | 3 | WITH cte1 AS 4 | ( 5 | SELECT activity, 6 | count(activity) AS counts 7 | FROM friends 8 | GROUP BY activity ), cte2 AS 9 | ( 10 | SELECT max(counts) 11 | FROM cte1 12 | UNION ALL 13 | SELECT min(counts) 14 | FROM cte1 )SELECT activity 15 | FROM cte1 16 | WHERE counts NOT IN 17 | ( 18 | SELECT * 19 | FROM cte2) -------------------------------------------------------------------------------- /SQL/Medium/1369. Get the Second Most Recent Activity.sql: -------------------------------------------------------------------------------- 1 | # write your mysql query statement below 2 | SELECT username, 3 | activity, 4 | startdate, 5 | enddate 6 | FROM ( 7 | SELECT username, 8 | activity, 9 | startdate, 10 | enddate, 11 | Row_number() OVER (partition BY username ORDER BY startdate DESC) AS ranking, 12 | Count(*) OVER (partition BY username) AS total_counts 13 | FROM useractivity ) tmp 14 | WHERE ranking = 2 15 | OR total_counts = 1 -------------------------------------------------------------------------------- /SQL/Medium/1393. Capital Gain Loss.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT stock_name, 3 | Sum(CASE 4 | WHEN operation = 'Sell' THEN price 5 | ELSE -price 6 | end) AS capital_gain_loss 7 | FROM stocks 8 | GROUP BY stock_name -------------------------------------------------------------------------------- /SQL/Medium/1421. NPV Queries.sql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT q.id, 3 | q.year, 4 | COALESCE(npv, 0) AS NPV 5 | FROM queries q 6 | LEFT JOIN npv n 7 | ON q.id = n.id 8 | AND q.year = n.year -------------------------------------------------------------------------------- /SQL/Medium/1445. Apples & Oranges.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT sale_date, 3 | Sum(CASE 4 | WHEN fruit = 'apples' THEN sale_amount 5 | ELSE -sale_amount 6 | end) AS diff 7 | FROM (SELECT sale_date, 8 | fruit, 9 | Sum(sold_num) AS sale_amount 10 | FROM sales 11 | GROUP BY sale_date, 12 | fruit) tmp 13 | GROUP BY sale_date -------------------------------------------------------------------------------- /SQL/Medium/1454. Active Users.sql: -------------------------------------------------------------------------------- 1 | # write your mysql query statement belowSELECT DISTINCT l.id, 2 | NAME 3 | FROM ( 4 | SELECT id, 5 | login_date, 6 | Lag(login_date,4) OVER (partition BY id ORDER BY login_date) AS prev5 7 | FROM ( 8 | SELECT DISTINCT id, 9 | login_date 10 | FROM logins ) distinct_logins) l 11 | JOIN accounts a 12 | ON l.id = a.id 13 | WHERE Datediff(login_date, prev5) = 4 14 | ORDER BY id -------------------------------------------------------------------------------- /SQL/Medium/1501. Countries You Can Safely Invest In.sql: -------------------------------------------------------------------------------- 1 | # write your mysql query statement below 2 | 3 | WITH cte AS 4 | ( 5 | SELECT c.NAME AS country, 6 | duration 7 | FROM person p 8 | JOIN country c 9 | ON LEFT(p.phone_number,3) = c.country_code 10 | JOIN calls 11 | ON calls.caller_id = p.id 12 | OR calls.callee_id = p.id )SELECT country 13 | FROM cte 14 | GROUP BY country 15 | HAVING Avg(duration) > 16 | ( 17 | SELECT Avg(duration) 18 | FROM cte) -------------------------------------------------------------------------------- /SQL/Medium/1532. The Most Recent Three Orders.sql: -------------------------------------------------------------------------------- 1 | # write your mysql query statement below 2 | 3 | SELECT NAME AS customer_name, 4 | c.customer_id, 5 | order_id, 6 | order_date 7 | FROM customers c 8 | JOIN 9 | ( 10 | SELECT order_id, 11 | order_date, 12 | customer_id, 13 | Row_number() OVER (partition BY customer_id ORDER BY order_date DESC) AS ranking 14 | FROM orders ) o 15 | ON c.customer_id = o.customer_id 16 | WHERE ranking <=3 17 | ORDER BY customer_name, 18 | customer_id, 19 | order_date DESC -------------------------------------------------------------------------------- /SQL/Medium/1549. The Most Recent Orders for Each Product.sql: -------------------------------------------------------------------------------- 1 | # write your mysql query statement below 2 | 3 | SELECT product_name, 4 | o.product_id, 5 | order_id, 6 | order_date 7 | FROM ( 8 | SELECT order_id, 9 | order_date, 10 | product_id, 11 | Rank() OVER (partition BY product_id ORDER BY order_date DESC) AS ranking 12 | FROM orders ) o 13 | JOIN products p 14 | ON o.product_id = p.product_id 15 | WHERE ranking = 1 16 | ORDER BY product_name, 17 | o.product_id, 18 | order_id -------------------------------------------------------------------------------- /SQL/Medium/180. Consecutive Numbers.sql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | 3 | SELECT DISTINCT l3.num AS ConsecutiveNums 4 | FROM ( logs l1 5 | JOIN logs l2 6 | ON l2.id - 1 = l1.id 7 | JOIN logs l3 8 | ON l3.id - 1 = l2.id 9 | AND l3.id - 2 = l1.id ) 10 | WHERE l1.num = l2.num 11 | AND l2.num = l3.num 12 | AND l3.num = l1.num 13 | 14 | 15 | -- using lead and lag 16 | SELECT DISTINCT( a.num ) AS ConsecutiveNums 17 | FROM (SELECT num, 18 | Lag(num) 19 | OVER () AS above, 20 | Lead(num) 21 | OVER () AS below 22 | FROM logs) a 23 | WHERE num = above 24 | AND num = below -------------------------------------------------------------------------------- /SQL/Medium/534. Game Play Analysis III.sql: -------------------------------------------------------------------------------- 1 | # write your mysql query statement below 2 | SELECT player_id, 3 | event_date, 4 | sum(games_played) OVER (partition BY player_id ORDER BY event_date ASC rows BETWEEN UNBOUNDED PRECEDING AND CURRENT row) AS games_played_so_far 5 | FROM activity 6 | ORDER BY player_id, 7 | event_date -------------------------------------------------------------------------------- /SQL/Medium/550. Game Play Analysis IV.sql: -------------------------------------------------------------------------------- 1 | # write your mysql query statement below 2 | SELECT round(sum(IF(Datediff(later_date, event_date)=1, 1, 0))/count(*),2) AS fraction 3 | FROM ( 4 | SELECT player_id, 5 | event_date, 6 | lead(event_date,1) OVER (partition BY player_id ORDER BY event_date ) AS later_date, 7 | row_number() OVER (partition BY player_id ORDER BY event_date ) AS ranking 8 | FROM activity ) tmp 9 | WHERE ranking = 1 -------------------------------------------------------------------------------- /SQL/Medium/570. Managers with at Least 5 Direct Reports.sql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT DISTINCT e1.NAME 3 | FROM (SELECT NAME, 4 | id 5 | FROM employee) e1 6 | LEFT JOIN (SELECT managerid, 7 | Count(*) AS freq 8 | FROM employee 9 | GROUP BY managerid) e2 10 | ON e1.id = e2.managerid 11 | WHERE e2.freq >= 5; 12 | 13 | 14 | SELECT NAME 15 | FROM employee 16 | WHERE id IN (SELECT managerid 17 | FROM employee 18 | GROUP BY managerid 19 | HAVING Count(*) >= 5) -------------------------------------------------------------------------------- /SQL/Medium/574. Winning Candidate.sql: -------------------------------------------------------------------------------- 1 | # write your mysql query statement below 2 | 3 | WITH cte AS 4 | ( 5 | SELECT candidateid, 6 | count(*) AS counting 7 | FROM vote 8 | GROUP BY candidateid )SELECT NAME 9 | FROM ( 10 | SELECT candidateid 11 | FROM cte 12 | WHERE counting = 13 | ( 14 | SELECT Max(counting) 15 | FROM cte)) v 16 | JOIN candidate c 17 | ON v.candidateid = c.id 18 | 19 | 20 | select name 21 | from candidate c join vote v on c.id = v.candidateid 22 | group by name 23 | order by count(*) desc 24 | limit 1 -------------------------------------------------------------------------------- /SQL/Medium/602. Friend Requests II -- Who Has the Most Friends.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT col_1 AS id, 3 | Count(*) AS num 4 | FROM ((SELECT requester_id AS col_1, 5 | accepter_id AS col_2 6 | FROM request_accepted) 7 | UNION 8 | (SELECT accepter_id AS col_1, 9 | requester_id AS col_2 10 | FROM request_accepted))tmp 11 | GROUP BY col_1 12 | ORDER BY Count(*) DESC 13 | LIMIT 1 -------------------------------------------------------------------------------- /SQL/Medium/608. Tree Node.sql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT id, 3 | ( CASE 4 | WHEN p_id IS NULL THEN 'Root' 5 | WHEN id IN (SELECT DISTINCT p_id 6 | FROM tree) THEN 'Inner' 7 | ELSE 'Leaf' 8 | END ) AS type 9 | FROM tree; -------------------------------------------------------------------------------- /SQL/Medium/612. Shortest Distance in a Plane.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT 3 | Round(Min(Sqrt(( a.x - b.x ) * ( a.x - b.x ) + ( a.y - b.y ) * ( a.y - b.y ))), 2) AS shortest 4 | FROM point_2d a 5 | JOIN point_2d b 6 | ON ( a.x != b.x 7 | OR a.y != b.y ) -------------------------------------------------------------------------------- /SQL/Medium/614. Second Degree Follower.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT f1.follower AS follower, 3 | Count(DISTINCT f2.follower) AS num 4 | FROM follow f1 5 | JOIN follow f2 6 | ON f1.follower = f2.followee 7 | GROUP BY f1.follower -------------------------------------------------------------------------------- /SQL/Medium/626. Exchange Seats.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | id, 3 | COALESCE ( 4 | CASE WHEN id % 2 = 1 THEN Lead(student, 1) OVER( 5 | ORDER BY 6 | id 7 | ) ELSE Lag(student, 1) OVER( 8 | ORDER BY 9 | id 10 | ) END, 11 | student 12 | ) AS student 13 | FROM 14 | seat; 15 | --------------------------------------------------------------------------------