├── String ├── Leetcode 290. Word Pattern.py ├── Leetcode 171. Excel Sheet Column Number.py ├── Leetcode 293. Flip Game.py ├── Leetcode 294. Flip Game II.py ├── Leetcode 214. Shortest Palindrome.py ├── Leetcode 28. Implement strStr().py ├── Leetcode 3. Longest Substring Without Repeating Characters.py ├── Leetcode 205. Isomorphic Strings.py ├── Leetcode 12. Integer to Roman.py ├── Leetcode 242. Valid Anagram.py ├── Leetcode 249. Group Shifted Strings.py ├── Leetcode 680. Valid Palindrome II.py ├── Leetcode 316. Remove Duplicate Letters.py ├── Leetcode 13. Roman to Integer.py ├── Leetcode 763. Partition Labels.py ├── Leetcode 125. Valid Palindrome.py ├── Leetcode 161. One Edit Distance.py ├── Leetcode 20. Valid Parentheses.py ├── Leetcode 38. Count and Say.py ├── Leetcode 22. Generate Parentheses.py ├── Leetcode 32. Longest Valid Parentheses.py ├── Leetcode 844. Backspace String Compare.py ├── Leetcode 1249. Minimum Remove to Make Valid Parentheses.py ├── Leetcode 97. Interleaving String.py ├── Leetcode 157. Read N Characters Given Read4.py ├── Leetcode 168. Excel Sheet Column Title.py ├── Leetcode 186. Reverse Words in a String II.py ├── Leetcode 1246. Palindrome Removal.py ├── Leetcode 516. Longest Palindromic Subsequence.py ├── Leetcode 271. Encode and Decode Strings.py ├── Leetcode 340. Longest Substring with At Most K Distinct Characters.py ├── Leetcode 158. Read N Characters Given Read4 II - Call multiple times.py ├── Leetcode 616. Add Bold Tag in String.py ├── Leetcode 241. Different Ways to Add Parentheses.py ├── Leetcode 5. Longest Palindromic Substring.py ├── Leetcode 115. Distinct Subsequences.py ├── Leetcode 438. Find All Anagrams in a String.py ├── Leetcode 68. Text Justification.py ├── Leetcode 767. Reorganize String.py ├── Leetcode 1156. Swap For Longest Repeated Character Substring.py ├── Leetcode 336. Palindrome Pairs.py └── Leetcode 76. Minimum Window Substring.py ├── Algorithm ├── Two Pointer.md ├── Dynamic Programming.md └── Strong connected components.md ├── LinkedList ├── Leetcode 24. Swap Nodes in Pairs.py ├── Leetcode 206. Reverse Linked List.py ├── Leetcode 237. Delete Node in a Linked List.py ├── Leetcode 141. Linked List Cycle.py ├── Leetcode 203. Remove Linked List Elements.py ├── Leetcode 234. Palindrome Linked List.py ├── Leetcode 328. Odd Even Linked List.py ├── Leetcode 142. Linked List Cycle II.py ├── Leetcode 19. Remove Nth Node From End of List.py ├── Leetcode 83. Remove Duplicates from Sorted List.py ├── Leetcode 92. Reverse Linked List II.py ├── Leetcode 21. Merge Two Sorted Lists.py ├── Leetcode 369. Plus One Linked List.py ├── Leetcode 82. Remove Duplicates from Sorted List II.py ├── Leetcode 147. Insertion Sort List.py ├── Leetcode 143. Reorder List.py ├── Leetcode 2. Add Two Numbers.py ├── Leetcode 86. Partition List.py ├── Leetcode 25. Reverse Nodes in k-Group.py ├── Leetcode 160. Intersection of Two Linked Lists.py └── Leetcode 148. Sort List.py ├── Stack Queue ├── Leetcode 739. Daily Temperatures.py ├── Leetcode 71. Simplify Path.py ├── Leetcode 341. Flatten Nested List Iterator.py ├── Leetcode 347. Top K Frequent Elements.py ├── Leetcode 378. Kth Smallest Element in a Sorted Matrix.py ├── Leetcode 155. Min Stack.py ├── Leetcode 394. Decode String.py ├── Leetcode 973. K Closest Points to Origin.py ├── Leetcode 150. Evaluate Reverse Polish Notation.py ├── Leetcode 385. Mini Parser.py ├── Leetcode 621. Task Scheduler.py ├── Leetcode 373. Find K Pairs with Smallest Sums.py ├── Leetcode 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows.py └── Leetcode 227. Basic Calculator II.py ├── .DS_Store ├── leetcode.png ├── Bit Manipulation ├── Leetcode 136. Single Number.py └── Leetcode 318. Maximum Product of Word Lengths.py ├── Array ├── Leetcode 27. Remove Element.py ├── Leetcode 122. Best Time to Buy and Sell Stock II.py ├── Leetcode 189. Rotate Array.py ├── Leetcode 53. Maximum Subarray.py ├── Leetcode 217. Contains Duplicate.py ├── Leetcode 219. Contains Duplicate II.py ├── Leetcode 283. Move Zeroes.py ├── Leetcode 55. Jump Game.py ├── Leetcode 324. Wiggle Sort II.py ├── Leetcode 376. Wiggle Subsequence.py ├── Leetcode 220. Contains Duplicate III.py ├── Leetcode 277. Find the Celebrity.py ├── Leetcode 121. Best Time to Buy and Sell Stock.py ├── Leetcode 135. Candy.py ├── Leetcode 209. Minimum Size Subarray Sum.py ├── Leetcode 26. Remove Duplicates from Sorted Array.py ├── Leetcode 252. Meeting Rooms.py ├── Leetcode 280. Wiggle Sort.py ├── Leetcode 152. Maximum Product Subarray.py ├── Leetcode 334. Increasing Triplet Subsequence.py ├── Leetcode 560. Subarray Sum Equals K.py ├── Leetcode 977. Squares of a Sorted Array.py ├── Leetcode 239. Sliding Window Maximum.py ├── Leetcode 245. Shortest Word Distance III.py ├── Leetcode 503. Next Greater Element II.py ├── Leetcode 128. Longest Consecutive Sequence.py ├── Leetcode 238. Product of Array Except Self.py ├── Leetcode 80. Remove Duplicates from Sorted Array II.py ├── Leetcode 11. Container With Most Water.py ├── Leetcode 244. Shortest Word Distance II.py ├── Leetcode 253. Meeting Rooms II.py ├── Leetcode 228. Summary Ranges.py ├── Leetcode 134. Gas Station.py ├── Leetcode 41. First Missing Positive.py ├── Leetcode 275. H-Index II.py ├── Leetcode 274. H-Index.py ├── Leetcode 75. Sort Colors.py ├── Leetcode 88. Merge Sorted Array.py ├── Leetcode 986. Interval List Intersections.py ├── Python 287. Find the Duplicate Number.py ├── Leetcode 42. Trapping Rain Water.py ├── Leetcode 496. Next Greater Element I.py ├── Leetcode 163. Missing Ranges.py ├── Leetcode 403. Frog Jump.py ├── Leetcode 581. Shortest Unsorted Continuous Subarray.py ├── Leetcode 56. Merge Intervals.py ├── Leetcode 325. Maximum Size Subarray Sum Equals k.py ├── Leetcode 299. Bulls and Cows.py ├── Leetcode 957. Prison Cells After N Days.py ├── Leetcode 309. Best Time to Buy and Sell Stock with Cooldown.py ├── Leetcode 57. Insert Interval.py ├── Leetcode 1239. Maximum Length of a Concatenated String with Unique Characters.py ├── Leetcode 123. Best Time to Buy and Sell Stock III.py ├── Leetcode 4. Median of Two Sorted Arrays.py ├── Leetcode 352. Data Stream as Disjoint Intervals.py └── Leetcode 45. Jump Game II.py ├── Hackerrank ├── LinkedList │ ├── Reverse a Doubly Linked List.py │ ├── Insert a node at a specific position in a linked list.py │ └── Inserting a Node Into a Sorted Doubly Linked List.py ├── Array │ ├── Max Min Array.py │ ├── Count Matching Pairs of Numbers.py │ ├── Searching for Difference Pairs.py │ ├── Counting Valleys on Hike.py │ ├── Jumping on the Clouds.py │ ├── 2D Array - Maximum Hourglass.py │ └── Minimum Swaps to Sort Array.py ├── Trees │ └── Height of a Binary Tree.py ├── String │ ├── Alternating Characters.py │ ├── Cout the a's in an infinitely Repeating String.py │ ├── Recursive Digit Sum.py │ ├── Making Anagrams.py │ └── Character Frequencies.py ├── HashTable │ ├── Count Triplets.py │ └── Sherlock and Anagrams or Count Substring Anagrams.py ├── Stack │ └── Min Max Riddle.py ├── Graphs │ ├── Find the nearest clone.py │ └── Connected Cell in a Grid.py ├── Search │ └── Minimum Time Required.py └── Queue │ └── Castle on the Grid.py ├── Tree ├── Leetcode 96. Unique Binary Search Trees.py ├── Leetcode 108. Convert Sorted Array to Binary Search Tree.py ├── Leetcode 230. Kth Smallest Element in a BST.py ├── Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal.py ├── Leetcode 101. Symmetric Tree.py ├── Leetcode 98. Validate Binary Search Tree.py ├── Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal.py ├── Leetcode 1008. Construct Binary Search Tree from Preorder Traversal.py ├── Leetcode 938. Range Sum of BST.py ├── Leetcode 543. Diameter of Binary Tree.py ├── Leetcode 285. Inorder Successor in BST.py ├── Leetcode 889. Construct Binary Tree from Preorder and Postorder Traversal.py ├── Leetcode 270. Closest Binary Search Tree Value.py ├── Leetcode 110. Balanced Binary Tree.py ├── Leetcode 124. Binary Tree Maximum Path Sum.py ├── Leetcode 199. Binary Tree Right Side View.py ├── Leetcode 366. Find Leaves of Binary Tree.py ├── Leetcode 1339. Maximum Product of Splitted Binary Tree.py ├── Leetcode 129. Sum Root to Leaf Numbers.py ├── Leetcode 117. Populating Next Right Pointers in Each Node II.py ├── Leetcode 109. Convert Sorted List to Binary Search Tree.py ├── Leetcode 111. Minimum Depth of Binary Tree.py ├── Leetcode 426. Convert Binary Search Tree to Sorted Doubly Linked List.py ├── Leetcode 314. Binary Tree Vertical Order Traversal.py ├── Leetcode 226. Invert Binary Tree.py ├── Leetcode 100. Same Tree.py ├── Leetcode 337. House Robber III.py ├── Leetcode 104. Maximum Depth of Binary Tree.py ├── Leetcode 987. Vertical Order Traversal of a Binary Tree.py ├── Leetcode 103. Binary Tree Zigzag Level Order Traversal.py ├── Leetcode 235. Lowest Common Ancestor of a Binary Search Tree.py ├── Leetcode 549. Binary Tree Longest Consecutive Sequence II.py └── Leetcode 173. Binary Search Tree Iterator.py ├── Math ├── Leetcode 231. Power of Two.py ├── Leetcode 1. Two Sum.py ├── Leetcode 204. Count Primes.py ├── Leetcode 69. Sqrt(x).py ├── Leetcode 202. Happy Number.py ├── Leetcode 66. Plus One.py ├── Leetcode 7. Reverse Integer.py ├── Leetcode 263. Ugly Number.py ├── Leetcode 223. Rectangle Area.py ├── Leetcode 264. Ugly Number II.py ├── Leetcode 367. Valid Perfect Square.py ├── Leetcode 670. Maximum Swap.py ├── Leetcode 67. Add Binary.py ├── Leetcode 8. String to Integer (atoi).py ├── Leetcode 445. Add Two Numbers II.py ├── Leetcode 43. Multiply Strings.py ├── Leetcode 50. Pow(x, n).py ├── Leetcode 29. Divide Two Integers.py └── Leetcode 15. 3Sum.py ├── DP ├── Leetcode 198. House Robber.py ├── Leetcode 70. Climbing Stairs.py ├── Leetcode 276. Paint Fence.py ├── Leetcode 322. Coin Change.py ├── Leetcode 91. Decode Ways.py ├── Leetcode 279. Perfect Squares.py ├── Leetcode 62. Unique Paths.py ├── Leetcode 256. Paint House.py ├── Leetcode 983. Minimum Cost For Tickets.py ├── Leetcode 312. Burst Balloons.py ├── Leetcode 44. Wildcard Matching.py ├── Leetcode 213. House Robber II.py ├── Leetcode 265. Paint House II.py ├── Leetcode 72. Edit Distance.py ├── Leetcode 221. Maximal Square.py ├── Leetcode 1143. Longest Common Subsequence.py ├── Leetcode 472. Concatenated Words.py ├── Leetcode 368. Largest Divisible Subset.py └── Leetcode 10. Regular Expression Matching.py ├── Design ├── Leetcode 346. Moving Average from Data Stream.py ├── Leetcode 303. Range Sum Query - Immutable.py ├── Leetcode 284. Peeking Iterator.py ├── Leetcode 359. Logger Rate Limiter.py ├── Leetcode 895. Maximum Frequency Stack.py ├── Leetcode 362. Design Hit Counter.py ├── Leetcode 251. Flatten 2D Vector.py ├── Leetcode 281. Zigzag Iterator.py └── Leetcode 170. Two Sum III - Data structure design.py ├── Backtracking ├── Leetcode 78. Subsets.py ├── Leetcode 77. Combinations.py ├── Leetcode 90. Subsets II.py ├── Leetcode 216. Combination Sum III.py ├── Leetcode 46. Permutations.py ├── Leetcode 254. Factor Combinations.py ├── Leetcode 39. Combination Sum.py ├── Leetcode 17. Letter Combinations of a Phone Number.py ├── Leetcode 60. Permutation Sequence.py ├── Leetcode 93. Restore IP Addresses.py ├── Leetcode 47. Permutations II.py ├── Leetcode 40. Combination Sum II.py ├── Leetcode 51. N-Queens.py ├── Leetcode 351. Android Unlock Patterns.py ├── Leetcode 52. N-Queens II.py └── Leetcode 31. Next Permutation.py ├── Non-Leetcode ├── Kth Largest Element in a BST.py ├── Stock Span.py ├── Print Nodes in Left View of Binary Tree.py ├── Number of Subsets I.py ├── Pythagorean Triplet in an array.py ├── Print Nodes in Bottom View of Binary Tree.py ├── Print Nodes in Right View of Binary Tree.py ├── Print Nodes in Top View of Binary Tree.py ├── Integer to Chinese.py └── K Decimal Addition.py ├── Binary Search ├── Leetcode 374. Guess Number Higher or Lower.py ├── Leetcode 658. Find K Closest Elements.py ├── Leetcode 278. First Bad Version.py ├── Leetcode 153. Find Minimum in Rotated Sorted Array.py ├── Leetcode 162. Find Peak Element.py ├── Leetcode 35. Search Insert Position.py ├── Leetcode 154. Find Minimum in Rotated Sorted Array II.py ├── Leetcode 33. Search in Rotated Sorted Array.py └── Leetcode 81. Search in Rotated Sorted Array II.py ├── Random ├── Leetcode 398. Random Pick Index.py ├── Leetcode 384. Shuffle an Array.py ├── Leetcode 382. Linked List Random Node.py ├── Leetcode 381. Insert Delete GetRandom O(1) - Duplicates allowed.py └── Leetcode 380. Insert Delete GetRandom O(1).py ├── Matrix ├── Leetcode 240. Search a 2D Matrix II.py ├── Leetcode 311. Sparse Matrix Multiplication.py ├── Leetcode 36. Valid Sudoku.py ├── Leetcode 48. Rotate Image.py ├── Leetcode 1102. Path With Maximum Minimum Value.py ├── Leetcode 1219. Path with Maximum Gold.py └── Leetcode 59. Spiral Matrix II.py ├── DFS BFS ├── Leetcode 1436. Destination City.py ├── Leetcode 332. Reconstruct Itinerary.py ├── Leetcode 339. Nested List Weight Sum.py ├── Leetcode 1236. Web Crawler.py ├── Leetcode 494. Target Sum.py ├── Leetcode 743. Network Delay Time.py ├── Leetcode 364. Nested List Weight Sum II.py ├── Leetcode 490. The Maze.py ├── Leetcode 1269. Number of Ways to Stay in the Same Place After Some Steps.py ├── Leetcode 127. Word Ladder.py ├── Leetcode 638. Shopping Offers.py ├── Leetcode 695. Max Area of Island.py └── Leetcode 329. Longest Increasing Path in a Matrix.py ├── Graph ├── Leetcode 133. Clone Graph.py ├── Leetcode 138. Copy List with Random Pointer.py ├── Leetcode 1152. Analyze User Website Visit Pattern.py ├── Leetcode 310. Minimum Height Trees.py └── Leetcode 399. Evaluate Division.py ├── Toplogical Sort ├── Leetcode 210. Course Schedule II.py └── Leetcode 207. Course Schedule.py └── Trie └── Leetcode 208. Implement Trie (Prefix Tree).py /String/Leetcode 290. Word Pattern.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Algorithm/Two Pointer.md: -------------------------------------------------------------------------------- 1 | # Two Pointer 2 | -------------------------------------------------------------------------------- /LinkedList/Leetcode 24. Swap Nodes in Pairs.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Stack Queue/Leetcode 739. Daily Temperatures.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Algorithm/Dynamic Programming.md: -------------------------------------------------------------------------------- 1 | # Dynamic Programming 2 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zengtian006/LeetCode/HEAD/.DS_Store -------------------------------------------------------------------------------- /leetcode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zengtian006/LeetCode/HEAD/leetcode.png -------------------------------------------------------------------------------- /Algorithm/Strong connected components.md: -------------------------------------------------------------------------------- 1 | # Strong connected components 2 | 3 | - 练习 4 | 5 | [Leetcode 1192](https://leetcode.com/problems/critical-connections-in-a-network/) 6 | -------------------------------------------------------------------------------- /Bit Manipulation/Leetcode 136. Single Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: List[int]) -> int: 3 | res = 0 4 | for num in nums: 5 | res = num^res 6 | return res -------------------------------------------------------------------------------- /String/Leetcode 171. Excel Sheet Column Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def titleToNumber(self, s: str) -> int: 3 | res = 0 4 | for char in s: 5 | n = ord(char) - ord('A') +1 6 | res = res*26 +n 7 | return res -------------------------------------------------------------------------------- /Array/Leetcode 27. Remove Element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeElement(self, nums: List[int], val: int) -> int: 3 | idx = 0 4 | for num in nums: 5 | if num != val: 6 | nums[idx] = num 7 | idx +=1 8 | return idx -------------------------------------------------------------------------------- /Hackerrank/LinkedList/Reverse a Doubly Linked List.py: -------------------------------------------------------------------------------- 1 | def reverse(head): 2 | cur = head 3 | pre = None 4 | while cur: 5 | nxt = cur.next 6 | cur.next = pre 7 | cur.pre = nxt 8 | 9 | pre = cur 10 | cur = nxt 11 | return pre -------------------------------------------------------------------------------- /Hackerrank/Array/Max Min Array.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/angry-children/problem 2 | 3 | def maxMin(k, arr): 4 | arr.sort() 5 | res = float('inf') 6 | for i in range(len(arr)-k+1): 7 | j = i+k-1 8 | res = min(res, arr[j]-arr[i]) 9 | return res -------------------------------------------------------------------------------- /Array/Leetcode 122. Best Time to Buy and Sell Stock II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | profit = 0 4 | for i in range(1, len(prices)): 5 | s = prices[i] - prices[i-1] 6 | profit += s if s >0 else 0 7 | return profit -------------------------------------------------------------------------------- /Array/Leetcode 189. Rotate Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, nums: List[int], k: int) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | k = k%len(nums) 7 | nums[:] = nums[-k:]+nums[:-k] 8 | 9 | # 减少重复计算,k%length -------------------------------------------------------------------------------- /Hackerrank/Trees/Height of a Binary Tree.py: -------------------------------------------------------------------------------- 1 | def getHeight(root): 2 | if not root: 3 | return 0 4 | left = getHeight(root.left) 5 | right = getHeight(root.right) 6 | return 1+max(left, right) 7 | 8 | def height(root): 9 | height = getHeight(root) 10 | return height-1 -------------------------------------------------------------------------------- /Tree/Leetcode 96. Unique Binary Search Trees.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numTrees(self, n: int) -> int: 3 | dp = [0]*(n+1) 4 | dp[0] = dp[1] = 1 5 | for i in range(2,n+1): 6 | for j in range(0,i): 7 | dp[i] += dp[j]*dp[i-j-1] 8 | return dp[-1] -------------------------------------------------------------------------------- /Math/Leetcode 231. Power of Two.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfTwo(self, n: int) -> bool: 3 | if -0 ListNode: 3 | pre, cur = None, head 4 | while cur: 5 | nxt = cur.next 6 | cur.next = pre 7 | pre = cur 8 | cur = nxt 9 | return pre -------------------------------------------------------------------------------- /String/Leetcode 293. Flip Game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generatePossibleNextMoves(self, s: str) -> List[str]: 3 | if not s: return [] 4 | res = [] 5 | for i in range(len(s)-1): 6 | if s[i:i+2] == '++': 7 | res.append(s[:i]+'--'+s[i+2:]) 8 | return res -------------------------------------------------------------------------------- /Hackerrank/Array/Count Matching Pairs of Numbers.py: -------------------------------------------------------------------------------- 1 | def numberPairs(n, ar): 2 | 3 | # Write your code here 4 | dic = {} 5 | count = 0 6 | for a in ar: 7 | if a in dic: 8 | count += 1 9 | del dic[a] 10 | else: 11 | dic[a] = 1 12 | return count -------------------------------------------------------------------------------- /LinkedList/Leetcode 237. Delete Node in a Linked List.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def deleteNode(self, node): 3 | """ 4 | :type node: ListNode 5 | :rtype: void Do not return anything, modify node in-place instead. 6 | """ 7 | node.val = node.next.val 8 | node.next = node.next.next -------------------------------------------------------------------------------- /Math/Leetcode 1. Two Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | dic = {} 4 | for i in range(len(nums)): 5 | if target - nums[i] in dic: 6 | return [dic[target - nums[i]],i] 7 | else: 8 | dic[nums[i]] = i -------------------------------------------------------------------------------- /String/Leetcode 294. Flip Game II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canWin(self, s: str) -> bool: 3 | for i in range(len(s)-1): 4 | if s[i:i+2] == '++': 5 | temp = s[:i]+'--'+s[i+2:] 6 | if not self.canWin(temp): 7 | return True 8 | return False 9 | -------------------------------------------------------------------------------- /Array/Leetcode 53. Maximum Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | dp = [float('-inf')] * len(nums) 4 | dp[0] = nums[0] 5 | for i in range(1,len(nums)): 6 | dp[i] = max(nums[i], dp[i-1]+nums[i]) 7 | return max(dp) 8 | 9 | 10 | # 求极值,考虑DP -------------------------------------------------------------------------------- /DP/Leetcode 198. House Robber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | if not nums: 4 | return 0 5 | dp = [0]*len(nums) 6 | dp[0] = nums[0] 7 | for i in range(1, len(nums)): 8 | dp[i] = max(dp[i-1], nums[i]+(dp[i-2] if i>1 else 0)) 9 | return dp[-1] -------------------------------------------------------------------------------- /LinkedList/Leetcode 141. Linked List Cycle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hasCycle(self, head: ListNode) -> bool: 3 | slow = fast = head 4 | while fast and fast.next: 5 | slow = slow.next 6 | fast =fast.next.next 7 | if slow == fast: 8 | return True 9 | return False -------------------------------------------------------------------------------- /Array/Leetcode 217. Contains Duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | dic = {} 4 | for num in nums: 5 | if num in dic: 6 | return True 7 | dic[num] = dic.get(num,0)+1 8 | return False 9 | 10 | # O(1) 读写 考虑hashtable, set -------------------------------------------------------------------------------- /DP/Leetcode 70. Climbing Stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | if n <=1: 4 | return 1 5 | dp = [0]*(n+1) 6 | dp[0] = 1 7 | dp[1] = 1 8 | dp[2] = 2 9 | for i in range(3, n+1): 10 | dp[i] = dp[i-2]+dp[i-1] 11 | return dp[-1] -------------------------------------------------------------------------------- /Hackerrank/String/Alternating Characters.py: -------------------------------------------------------------------------------- 1 | def alternatingCharacters(s): 2 | i = 0 3 | j = 1 4 | count = 0 5 | while j str: 3 | t = s[::-1] 4 | for i in range(len(s),-1,-1): 5 | if s[:i] == t[len(s)-i:]: 6 | break 7 | return t[:len(s)-i]+s 8 | 9 | # s = babcd 10 | # t = dcbab -------------------------------------------------------------------------------- /Array/Leetcode 219. Contains Duplicate II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 3 | dic = {} 4 | for i, v in enumerate(nums): 5 | if v in dic: 6 | if i - dic[v]<=k: 7 | return True 8 | dic[v] = i 9 | return False -------------------------------------------------------------------------------- /DP/Leetcode 276. Paint Fence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numWays(self, n: int, k: int) -> int: 3 | if n == 0: return 0 4 | if n == 1: return k 5 | dp = [0]*n 6 | dp[0] = k 7 | dp[1] = k*k 8 | for i in range(2,n): 9 | dp[i] = dp[i-1]*(k-1) + dp[i-2]*(k-1) 10 | return dp[-1] -------------------------------------------------------------------------------- /Hackerrank/Array/Searching for Difference Pairs.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/pairs/problem 2 | def pairs(k, arr): 3 | dic = {} 4 | count = 0 5 | for i,a in enumerate(arr): 6 | if a-k in dic: 7 | count +=1 8 | if a+k in dic: 9 | count += 1 10 | dic[a] = i 11 | return count -------------------------------------------------------------------------------- /String/Leetcode 28. Implement strStr().py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def strStr(self, haystack: str, needle: str) -> int: 3 | if not needle: return 0 4 | m, n = len(haystack), len(needle) 5 | for i in range(m-n+1): 6 | j = n +i 7 | if haystack[i:j] == needle: 8 | return i 9 | return -1 -------------------------------------------------------------------------------- /Hackerrank/String/Cout the a's in an infinitely Repeating String.py: -------------------------------------------------------------------------------- 1 | def repeatedString(s, n): 2 | count = 0 3 | for c in s: 4 | if c == 'a': 5 | count += 1 6 | k = n//len(s) 7 | res = count*k 8 | rest = n%len(s) 9 | 10 | for i in range(rest): 11 | if s[i] == 'a': 12 | res += 1 13 | return res -------------------------------------------------------------------------------- /Math/Leetcode 204. Count Primes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPrimes(self, n: int) -> int: 3 | p = [1]*n 4 | res = 0 5 | for i in range(2,n): 6 | if p[i] == 1: 7 | res +=1 8 | j = 2 9 | while i*j int: 3 | if x <= 1:return x 4 | left, right = 1, x 5 | while left<=right: 6 | mid = left + (right-left)//2 7 | if mid*mid>x: 8 | right = mid-1 9 | else: 10 | left = mid+1 11 | return left-1 -------------------------------------------------------------------------------- /Array/Leetcode 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 | i = 0 7 | for j in range(len(nums)): 8 | if nums[j]!=0: 9 | nums[i],nums[j] = nums[j],nums[i] 10 | i+=1 -------------------------------------------------------------------------------- /Math/Leetcode 202. Happy Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isHappy(self, n: int) -> bool: 3 | s = set() 4 | while n not in s and n > 1: 5 | s.add(n) 6 | k = n 7 | res = 0 8 | while k > 0: 9 | res += (k%10)**2 10 | k //=10 11 | n = res 12 | return n == 1 -------------------------------------------------------------------------------- /Hackerrank/HashTable/Count Triplets.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/count-triplets-1/problem 2 | 3 | def countTriplets(arr, r): 4 | v2 = {} 5 | v3 = {} 6 | count = 0 7 | for a in arr: 8 | count += v3.get(a,0) 9 | if a in v2: 10 | v3[a*r] = v3.get(a*r,0)+v2[a] 11 | v2[a*r] = v2.get(a*r, 0) +1 12 | return count -------------------------------------------------------------------------------- /Hackerrank/Array/Counting Valleys on Hike.py: -------------------------------------------------------------------------------- 1 | def countingValleys(n, s): 2 | height = 0 3 | pre_height = 0 4 | count = 0 5 | for c in s: 6 | if c == 'U': 7 | height += 1 8 | else: 9 | height -= 1 10 | if height == 0 and pre_height < 0: 11 | count += 1 12 | pre_height = height 13 | return count -------------------------------------------------------------------------------- /Design/Leetcode 346. Moving Average from Data Stream.py: -------------------------------------------------------------------------------- 1 | class MovingAverage: 2 | 3 | def __init__(self, size: int): 4 | self.q = collections.deque() 5 | self.size = size 6 | 7 | def next(self, val: int) -> float: 8 | if len(self.q) == self.size: 9 | self.q.popleft() 10 | self.q.append(val) 11 | return sum(self.q)/len(self.q) -------------------------------------------------------------------------------- /Math/Leetcode 66. Plus One.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def plusOne(self, digits: List[int]) -> List[int]: 3 | carry = 1 4 | res = [] 5 | for i in range(len(digits)-1,-1,-1): 6 | s = digits[i] + carry 7 | s, carry = s%10, s//10 8 | res.append(s) 9 | if carry: 10 | res.append(carry) 11 | return res[::-1] -------------------------------------------------------------------------------- /Math/Leetcode 7. Reverse Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x: int) -> int: 3 | sign = -1 if x<0 else 1 4 | x = abs(x) 5 | res = 0 6 | while x>0: 7 | n = x%10 8 | res = res*10 + n 9 | if res>2**31 -1 or res <-2**31 : 10 | return 0 11 | x //= 10 12 | return res*sign -------------------------------------------------------------------------------- /Tree/Leetcode 108. Convert Sorted Array to Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortedArrayToBST(self, nums: List[int]) -> TreeNode: 3 | if not nums:return None 4 | mid = len(nums) // 2 5 | root = TreeNode(nums[mid]) 6 | root.left = self.sortedArrayToBST(nums[:mid]) 7 | root.right = self.sortedArrayToBST(nums[mid+1:]) 8 | return root -------------------------------------------------------------------------------- /DP/Leetcode 322. Coin Change.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def coinChange(self, coins: List[int], amount: int) -> int: 3 | dp = [float('inf')]*(amount+1) 4 | dp[0] = 0 5 | for i in range(1, amount+1): 6 | for coin in coins: 7 | if i>=coin: 8 | dp[i] = min(dp[i],dp[i-coin]+1) 9 | return dp[-1] if dp[-1] bool: 3 | farthest = nums[0] 4 | for i in range(1,len(nums)): 5 | if farthest>=i: 6 | farthest = max(farthest, nums[i]+i) 7 | return farthest>=len(nums)-1 8 | 9 | # 局部最优推导出全局最优 考虑Greedy 10 | # 从第一个数开始,计算farthest范围内的farthest。最后如果farthest超过数组,则return True -------------------------------------------------------------------------------- /Math/Leetcode 263. Ugly Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isUgly(self, num: int) -> bool: 3 | while num > 1: 4 | if num % 2 == 0: 5 | num //= 2 6 | elif num % 3 == 0: 7 | num //= 3 8 | elif num % 5 == 0: 9 | num //= 5 10 | else: 11 | return False 12 | return num == 1 -------------------------------------------------------------------------------- /Array/Leetcode 324. Wiggle Sort II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wiggleSort(self, nums: List[int]) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | copy = sorted(nums) 7 | for i in range(1,len(nums), 2): 8 | nums[i] = copy.pop() 9 | for i in range(0,len(nums), 2): 10 | nums[i] = copy.pop() -------------------------------------------------------------------------------- /Array/Leetcode 376. Wiggle Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wiggleMaxLength(self, nums: List[int]) -> int: 3 | if len(nums)<2:return len(nums) 4 | up, down = 1, 1 5 | for i in range(1, len(nums)): 6 | if nums[i]>nums[i-1]: 7 | up = down+1 8 | elif nums[i] List[List[int]]: 3 | nums.sort() 4 | res = [] 5 | self.bt(nums, 0, [], res) 6 | return res 7 | def bt(self, nums, idx, tempList, res): 8 | res.append(tempList) 9 | for i in range(idx, len(nums)): 10 | self.bt(nums, i+1, tempList+[nums[i]], res) -------------------------------------------------------------------------------- /Design/Leetcode 303. Range Sum Query - Immutable.py: -------------------------------------------------------------------------------- 1 | class NumArray: 2 | 3 | def __init__(self, nums: List[int]): 4 | self.sums = [0]*(len(nums)+1) 5 | self.sums[0] = 0 6 | for i in range(1,len(nums)+1): 7 | self.sums[i] = self.sums[i-1] + nums[i-1] 8 | 9 | 10 | def sumRange(self, i: int, j: int) -> int: 11 | return self.sums[j+1] - self.sums[i] -------------------------------------------------------------------------------- /String/Leetcode 3. Longest Substring Without Repeating Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | res = 0 4 | i = 0 5 | dic = {} 6 | for j in range(len(s)): 7 | if s[j] in dic: 8 | i = max(dic[s[j]]+1, i) 9 | dic[s[j]] = j 10 | res = max(res, j-i+1) 11 | return res -------------------------------------------------------------------------------- /DP/Leetcode 91. Decode Ways.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numDecodings(self, s: str) -> int: 3 | dp = [0]*(len(s)+1) 4 | dp[0] = 1 5 | dp[1] = 1 if 1<=int(s[0])<=9 else 0 6 | for i in range(2,len(s)+1): 7 | if 10<=int(s[i-2:i])<=26: 8 | dp[i] += dp[i-2] 9 | if 0 str: 3 | strs = path.split('/') 4 | res = [] 5 | for s in strs: 6 | if s == '..': 7 | if res: 8 | res.pop() 9 | elif s.isalpha() or (s and s!='.'): # "/..." 10 | res.append(s) 11 | return '/' + '/'.join(res) -------------------------------------------------------------------------------- /DP/Leetcode 279. Perfect Squares.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numSquares(self, n: int) -> int: 3 | ps_nums = [i**2 for i in range(1, int(n**0.5)+1)] 4 | dp = [float('inf')]*(n+1) 5 | dp[0] = 0 6 | dp[1] = 1 7 | for i in range(2,n+1): 8 | for num in ps_nums: 9 | if i>=num: 10 | dp[i] = min(dp[i], dp[i-num]+1) 11 | return dp[n] -------------------------------------------------------------------------------- /DP/Leetcode 62. Unique Paths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m: int, n: int) -> int: 3 | dp = [[0]*n for _ in range(m)] 4 | for i in range(m): 5 | dp[i][0] = 1 6 | for j in range(n): 7 | dp[0][j] = 1 8 | for i in range(1,m): 9 | for j in range(1,n): 10 | dp[i][j] = dp[i-1][j] + dp[i][j-1] 11 | return dp[-1][-1] -------------------------------------------------------------------------------- /Hackerrank/String/Recursive Digit Sum.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/recursive-digit-sum/problem 2 | 3 | def superDigit(n, k): 4 | sums = 0 5 | for i in range(len(n)): 6 | sums += int(n[i]) 7 | 8 | sums *= k 9 | while sums > 9: 10 | s = 0 11 | while sums > 0: 12 | s += sums % 10 13 | sums //= 10 14 | sums = s 15 | return sums -------------------------------------------------------------------------------- /String/Leetcode 205. Isomorphic Strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isIsomorphic(self, s: str, t: str) -> bool: 3 | dic1 = {} 4 | dic2 = {} 5 | for x,y in zip(s,t): 6 | if x not in dic1: 7 | dic1[x] = y 8 | if y not in dic2: 9 | dic2[y] = x 10 | if dic1[x]!=y or dic2[y]!=x: 11 | return False 12 | return True -------------------------------------------------------------------------------- /Array/Leetcode 220. Contains Duplicate III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: 3 | if t == 0 and len(set(nums)) == len(nums): 4 | return False 5 | for i in range(len(nums)): 6 | for j in range(i+1,min(i+k+1,len(nums))): 7 | if abs(nums[j] - nums[i]) <=t: 8 | return True 9 | return False -------------------------------------------------------------------------------- /Array/Leetcode 277. Find the Celebrity.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findCelebrity(self, n: int) -> int: 3 | celebrity = 0 4 | for i in range(1,n): 5 | if not knows(i,celebrity): 6 | celebrity = i 7 | 8 | for i in range(n): 9 | if celebrity !=i and (knows(celebrity,i) or not knows(i, celebrity)): 10 | return -1 11 | return celebrity -------------------------------------------------------------------------------- /Non-Leetcode/Kth Largest Element in a BST.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthSmallest(self, root: TreeNode, k: int) -> int: 3 | stack = [] 4 | while root or stack: 5 | while root: 6 | stack.append(root) 7 | root = root.right 8 | node = stack.pop() 9 | k-=1 10 | if k == 0: 11 | return node.val 12 | root = node.left -------------------------------------------------------------------------------- /String/Leetcode 12. Integer to Roman.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intToRoman(self, num: int) -> str: 3 | v = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] 4 | s = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'] 5 | res="" 6 | for i in range(len(v)): 7 | while num>=v[i]: 8 | num -= v[i] 9 | res += s[i] 10 | return res -------------------------------------------------------------------------------- /Tree/Leetcode 230. Kth Smallest Element in a BST.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthSmallest(self, root: TreeNode, k: int) -> int: 3 | stack = [] 4 | while root or stack: 5 | while root: 6 | stack.append(root) 7 | root = root.left 8 | node = stack.pop() 9 | k-=1 10 | if k == 0: 11 | return node.val 12 | root = node.right -------------------------------------------------------------------------------- /Array/Leetcode 121. Best Time to Buy and Sell Stock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | if not prices: return 0 4 | min_buy = float('inf') 5 | max_profit = 0 6 | for p in prices: 7 | min_buy = min(min_buy,p) 8 | max_profit = max(max_profit, p-min_buy) 9 | return max_profit 10 | 11 | # 求极值,考虑DP 12 | # 计算前面最小的buy price,再用当前数字减去最小的buy price -------------------------------------------------------------------------------- /Backtracking/Leetcode 77. Combinations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combine(self, n: int, k: int) -> List[List[int]]: 3 | res = [] 4 | self.bt(n, 1, [], k, res) 5 | return res 6 | 7 | def bt(self, n, idx, tempList, k, res): 8 | if len(tempList) == k: 9 | res.append(tempList) 10 | return 11 | for i in range(idx, n+1): 12 | self.bt(n, i+1, tempList + [i], k, res) -------------------------------------------------------------------------------- /Binary Search/Leetcode 374. Guess Number Higher or Lower.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def guessNumber(self, n: int) -> int: 3 | left, right = 0, n 4 | while left <= right: 5 | mid = left + (right-left)//2 6 | if guess(mid) == 0: 7 | return mid 8 | elif guess(mid) == 1: 9 | left = mid + 1 10 | elif guess(mid) == -1: 11 | right = mid - 1 -------------------------------------------------------------------------------- /Binary Search/Leetcode 658. Find K Closest Elements.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: 3 | left, right = 0, len(arr)-k-1 4 | while left <= right: 5 | mid = left + (right-left)//2 6 | if x - arr[mid] > arr[mid+k] - x: 7 | left = mid + 1 8 | else: 9 | right = mid - 1 10 | return arr[left:left+k] -------------------------------------------------------------------------------- /LinkedList/Leetcode 203. Remove Linked List Elements.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeElements(self, head: ListNode, val: int) -> ListNode: 3 | dummy = ListNode(0) 4 | dummy.next = head 5 | pre = dummy 6 | while pre and pre.next: 7 | if pre.next and pre.next.val == val: 8 | pre.next = pre.next.next 9 | else: 10 | pre = pre.next 11 | return dummy.next -------------------------------------------------------------------------------- /Math/Leetcode 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 | w1 = max(A,E) 4 | w2 = min(C,G) 5 | width =max(0, w2-w1) 6 | 7 | h1 = max(B,F) 8 | h2 = min(D,H) 9 | height = max(0, h2-h1) 10 | 11 | a1 = (C-A)*(D-B) 12 | a2 = (G-E)*(H-F) 13 | return a1+a2-width*height -------------------------------------------------------------------------------- /Array/Leetcode 135. Candy.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def candy(self, ratings: List[int]) -> int: 3 | n = len(ratings) 4 | candies = [1]*n 5 | for i in range(1,n): 6 | if ratings[i]>ratings[i-1]: 7 | candies[i] = candies[i-1]+1 8 | for i in range(n-2,-1,-1): 9 | if ratings[i]>ratings[i+1]: 10 | candies[i] = max(candies[i] ,candies[i+1]+1) 11 | return sum(candies) -------------------------------------------------------------------------------- /Array/Leetcode 209. Minimum Size Subarray Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSubArrayLen(self, s: int, nums: List[int]) -> int: 3 | i = 0 4 | res = len(nums)+1 5 | sums = 0 6 | for j in range(len(nums)): 7 | sums += nums[j] 8 | while sums >=s: 9 | res = min(res, j-i+1) 10 | sums -= nums[i] 11 | i+=1 12 | return res if res bool: 3 | if not head: return True 4 | cur = head 5 | stack = [] 6 | while cur: 7 | stack.append(cur.val) 8 | cur = cur.next 9 | while head: 10 | if stack.pop()!=head.val: 11 | return False 12 | head = head.next 13 | return True -------------------------------------------------------------------------------- /Random/Leetcode 398. Random Pick Index.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def __init__(self, nums: List[int]): 4 | self.nums = nums 5 | 6 | def pick(self, target: int) -> int: 7 | count = 0 8 | res = -1 9 | for i in range(len(self.nums)): 10 | if self.nums[i] == target: 11 | count += 1 12 | if random.randint(1, count) == 1: 13 | res = i 14 | return res -------------------------------------------------------------------------------- /Hackerrank/Stack/Min Max Riddle.py: -------------------------------------------------------------------------------- 1 | # https://www.geeksforgeeks.org/find-the-maximum-of-minimums-for-every-window-size-in-a-given-array/ 2 | def riddle(arr): 3 | # complete this function 4 | res = [] 5 | for k in range(1, len(arr)+1): 6 | local_max = float('-inf') 7 | for i in range(len(arr)-k+1): 8 | j = i+k 9 | local_max = max(local_max, min(arr[i:j])) 10 | res.append(local_max) 11 | return res -------------------------------------------------------------------------------- /Array/Leetcode 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 | i = 0 6 | for j in range(1,len(nums)): 7 | if nums[j]!=nums[i]: 8 | i += 1 9 | nums[i] = nums[j] 10 | return i+1 11 | 12 | # 双指针适用in-place modification 13 | # 一个指针(快)遍历,另一个指针(慢)指向下一个要交换的位置,快指针遍历到符合要求的就与慢指针的值交换 -------------------------------------------------------------------------------- /Binary Search/Leetcode 278. First Bad Version.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstBadVersion(self, n): 3 | left, right = 0, n 4 | while left<=right: 5 | mid = left + (right-left)//2 6 | if isBadVersion(mid): 7 | if mid == 0 or not isBadVersion(mid-1): 8 | return mid 9 | else: 10 | right = mid - 1 11 | else: 12 | left = mid + 1 -------------------------------------------------------------------------------- /Tree/Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal.py: -------------------------------------------------------------------------------- 1 | def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: 2 | if not preorder or not inorder: 3 | return None 4 | root = TreeNode(preorder[0]) 5 | i = inorder.index(preorder[0]) 6 | root.left = self.buildTree(preorder[1:1+i], inorder[:i]) 7 | root.right = self.buildTree(preorder[1+i:], inorder[i+1:]) 8 | return root -------------------------------------------------------------------------------- /Array/Leetcode 252. Meeting Rooms.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canAttendMeetings(self, intervals: List[List[int]]) -> bool: 3 | if not intervals: return True 4 | intervals.sort() 5 | pre = intervals[0] 6 | for i in range(1, len(intervals)): 7 | interval = intervals[i] 8 | if pre[1]<=interval[0]: 9 | pre = interval 10 | else: 11 | return False 12 | return True -------------------------------------------------------------------------------- /Array/Leetcode 280. Wiggle Sort.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wiggleSort(self, nums: List[int]) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | for i in range(1,len(nums)): 7 | if i%2 == 1 and nums[i] < nums[i-1]: 8 | nums[i], nums[i-1] = nums[i-1], nums[i] 9 | elif i%2 == 0 and nums[i] > nums[i-1]: 10 | nums[i], nums[i-1] = nums[i-1], nums[i] -------------------------------------------------------------------------------- /LinkedList/Leetcode 328. Odd Even Linked List.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def oddEvenList(self, head: ListNode) -> ListNode: 3 | if not head: return None 4 | odd = head 5 | even = head.next 6 | evenHead = even 7 | while even and even.next: 8 | odd.next = even.next 9 | odd = odd.next 10 | even.next = odd.next 11 | even = even.next 12 | odd.next = evenHead 13 | return head -------------------------------------------------------------------------------- /Matrix/Leetcode 240. Search a 2D Matrix II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchMatrix(self, matrix, target): 3 | if not matrix or not matrix[0]: return False 4 | row = 0 5 | col = len(matrix[0])-1 6 | while col>=0 and row matrix[row][col]: 10 | row+=1 11 | else: col-=1 12 | return False -------------------------------------------------------------------------------- /LinkedList/Leetcode 142. Linked List Cycle II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def detectCycle(self, head: ListNode) -> ListNode: 3 | dic = {} 4 | dummy = ListNode(0) 5 | dummy.next = head 6 | slow = dummy 7 | fast = dummy.next 8 | pos = 1 9 | while fast and fast not in dic: 10 | slow = slow.next 11 | fast = fast.next 12 | dic[slow] = pos 13 | pos += 1 14 | 15 | return fast -------------------------------------------------------------------------------- /LinkedList/Leetcode 19. Remove Nth Node From End of List.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 3 | dummy = ListNode(0) 4 | dummy.next = head 5 | slow = fast = dummy 6 | for _ in range(n): 7 | fast = fast.next 8 | while fast.next: 9 | slow = slow.next 10 | fast = fast.next 11 | slow.next = slow.next.next 12 | return dummy.next 13 | 14 | -------------------------------------------------------------------------------- /String/Leetcode 242. Valid Anagram.py: -------------------------------------------------------------------------------- 1 | class Solution1: 2 | def isAnagram(self, s: str, t: str) -> bool: 3 | return sorted(s) == sorted(t) 4 | 5 | class Solution2: 6 | def isAnagram(self, s: str, t: str) -> bool: 7 | dic1, dic2 = {},{} 8 | for item in s: 9 | dic1[item] = dic1.get(item,0) + 1 10 | 11 | for item in t: 12 | dic2[item] = dic2.get(item,0) +1 13 | 14 | return dic1 == dic2 -------------------------------------------------------------------------------- /Array/Leetcode 152. Maximum Product Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, nums: List[int]) -> int: 3 | # Because there is negaive digits, so we should store the minimum value for now -> cur_min 4 | res = cur_max = cur_min = nums[0] 5 | for i in range(1, len(nums)): 6 | cur_max, cur_min = max(nums[i],nums[i]*cur_max, cur_min*nums[i]), min(nums[i],nums[i]*cur_max, cur_min*nums[i]) 7 | res = max(res, cur_max) 8 | return res -------------------------------------------------------------------------------- /DFS BFS/Leetcode 1436. Destination City.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def destCity(self, paths: List[List[str]]) -> str: 3 | dic = collections.defaultdict(list) 4 | for [x,y] in paths: 5 | dic[x].append(y) 6 | 7 | res = set() 8 | stack = [] 9 | stack.append(paths[0][0]) 10 | while stack: 11 | while dic[stack[-1]]: 12 | stack.append(dic[stack[-1]].pop()) 13 | return stack[-1] -------------------------------------------------------------------------------- /LinkedList/Leetcode 83. Remove Duplicates from Sorted List.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def deleteDuplicates(self, head: ListNode) -> ListNode: 3 | cur = head 4 | while cur: 5 | if cur.next and cur.val == cur.next.val : 6 | start = cur 7 | while start.next and start.val == start.next.val : 8 | start = start.next 9 | cur.next = start.next 10 | cur = cur.next 11 | return head -------------------------------------------------------------------------------- /Tree/Leetcode 101. Symmetric Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSymmetric(self, root: TreeNode) -> bool: 3 | if not root: return True 4 | return self.isSame(root.left, root.right) 5 | 6 | def isSame(self, p, q): 7 | if not p and not q:return True 8 | if not p or not q: return False 9 | if p.val != q.val: 10 | return False 11 | return p.val == q.val and self.isSame(p.left, q.right) and self.isSame(p.right, q.left) -------------------------------------------------------------------------------- /Tree/Leetcode 98. Validate Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValidBST(self, root: TreeNode) -> bool: 3 | stack = [] 4 | pre = None 5 | while root or stack: 6 | while root: 7 | stack.append(root) 8 | root = root.left 9 | node = stack.pop() 10 | if pre and node.val <= pre.val: 11 | return False 12 | root,pre = node.right,node 13 | return True -------------------------------------------------------------------------------- /Array/Leetcode 334. Increasing Triplet Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def increasingTriplet(self, nums: List[int]) -> bool: 3 | firstSmall = secondSmall = float('inf') 4 | for num in nums: 5 | if num <= firstSmall: 6 | firstSmall = num 7 | elif num <= secondSmall: 8 | secondSmall = num 9 | else: 10 | return True 11 | return False 12 | 13 | # 找到前两个最小数字,如果后面的数字比这两个数字大,则True -------------------------------------------------------------------------------- /Tree/Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: 3 | if not inorder or not postorder: 4 | return None 5 | root = TreeNode(postorder[-1]) 6 | i = inorder.index(postorder[-1]) 7 | root.left = self.buildTree(inorder[:i], postorder[:i]) 8 | root.right = self.buildTree(inorder[i+1:], postorder[i:-1]) 9 | return root -------------------------------------------------------------------------------- /String/Leetcode 249. Group Shifted Strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupStrings(self, strings: List[str]) -> List[List[str]]: 3 | dic= collections.defaultdict(list) 4 | for strr in strings: 5 | s = '' 6 | f = ord(strr[0]) 7 | for c in strr: 8 | s += str((ord(c) - f)%26)+" " 9 | dic[s].append(strr) 10 | res = [] 11 | for v in dic.values(): 12 | res.append(v) 13 | return res -------------------------------------------------------------------------------- /String/Leetcode 680. Valid Palindrome II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validPalindrome(self, s: str) -> bool: 3 | left = 0 4 | right = len(s)-1 5 | while left < right: 6 | if s[left]!=s[right]: 7 | return self.isValid(s,left+1,right) or self.isValid(s, left, right -1) 8 | left += 1 9 | right -=1 10 | return True 11 | 12 | def isValid(self, s, i, j): 13 | return s[i:j+1] == s[i:j+1][::-1] -------------------------------------------------------------------------------- /Array/Leetcode 560. Subarray Sum Equals K.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subarraySum(self, nums: List[int], k: int) -> int: 3 | preSum = [0]*(len(nums)+1) 4 | for i in range(len(nums)): 5 | preSum[i+1] = preSum[i]+nums[i] 6 | dic = {} 7 | res = 0 8 | for i in range(len(preSum)): 9 | if preSum[i] - k in dic: 10 | res += dic[preSum[i] - k ] 11 | dic[preSum[i]] = dic.get(preSum[i],0)+1 12 | return res -------------------------------------------------------------------------------- /Backtracking/Leetcode 90. Subsets II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: 3 | nums.sort() 4 | res = [] 5 | self.bt(nums, 0, [], res) 6 | return res 7 | 8 | def bt(self, nums, idx, tempList, res): 9 | res.append(tempList) 10 | for i in range(idx,len(nums)): 11 | if i> idx and nums[i] == nums[i-1]: 12 | continue 13 | self.bt(nums, i+1, tempList+[nums[i]], res) -------------------------------------------------------------------------------- /LinkedList/Leetcode 92. Reverse Linked List II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: 3 | pre = dummy = ListNode(0) 4 | dummy.next = head 5 | for _ in range(m-1): 6 | pre = pre.next 7 | cur = pre.next 8 | for _ in range(m,n): 9 | nxt = cur.next 10 | cur.next = nxt.next 11 | nxt.next = pre.next 12 | pre.next = nxt 13 | return dummy.next -------------------------------------------------------------------------------- /Math/Leetcode 264. Ugly Number II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nthUglyNumber(self, n: int) -> int: 3 | dp = [1] 4 | i2 = i3 = i5 =0 5 | while n > 1: 6 | mn = min(dp[i2]*2,dp[i3]*3,dp[i5]*5) 7 | if mn == dp[i2]*2: 8 | i2 += 1 9 | if mn == dp[i3]*3: 10 | i3 += 1 11 | if mn == dp[i5]*5: 12 | i5 += 1 13 | dp.append(mn) 14 | n -= 1 15 | return dp[-1] -------------------------------------------------------------------------------- /String/Leetcode 316. Remove Duplicate Letters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicateLetters(self, s: str) -> str: 3 | dic = {} 4 | for char in s: 5 | dic[char] = dic.get(char,0)+1 6 | res = [] 7 | for char in s: 8 | dic[char] -= 1 9 | if char not in res: 10 | while res and char0: 11 | res.pop() 12 | res.append(char) 13 | return ''.join(res) -------------------------------------------------------------------------------- /Tree/Leetcode 1008. Construct Binary Search Tree from Preorder Traversal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bstFromPreorder(self, preorder: List[int]) -> TreeNode: 3 | if not preorder: 4 | return None 5 | root = TreeNode(preorder[0]) 6 | i = 1 7 | while i List[str]: 3 | dic = collections.defaultdict(list) 4 | for s, d in sorted(tickets, reverse=True): 5 | dic[s].append(d) 6 | res = [] 7 | stack = ['JFK'] 8 | while stack: 9 | while dic[stack[-1]]: 10 | stack.append(dic[stack[-1]].pop()) 11 | res.append(stack.pop()) 12 | return res[::-1] -------------------------------------------------------------------------------- /Math/Leetcode 367. Valid Perfect Square.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPerfectSquare(self, num: int) -> bool: 3 | if num < 2: 4 | return True 5 | left, right = 1, num//2 6 | while left <= right: 7 | mid = left + (right-left)//2 8 | if mid*mid == num: 9 | return mid 10 | if mid*mid > num: 11 | right = mid-1 12 | if mid*mid < num: 13 | left = mid +1 14 | return False -------------------------------------------------------------------------------- /Tree/Leetcode 938. Range Sum of BST.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: 3 | res = 0 4 | stack = [] 5 | while root or stack: 6 | while root: 7 | stack.append(root) 8 | root = root.left 9 | node = stack.pop() 10 | if L<=node.val<=R: 11 | res += node.val 12 | if node.right: 13 | root = node.right 14 | 15 | return res -------------------------------------------------------------------------------- /Array/Leetcode 977. Squares of a Sorted Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortedSquares(self, A: List[int]) -> List[int]: 3 | res = [0]*len(A) 4 | idx= len(A)-1 5 | left, right = 0, len(A)-1 6 | while left<=right: 7 | if abs(A[left]) > abs(A[right]): 8 | res[idx] = A[left]**2 9 | left += 1 10 | else: 11 | res[idx] = A[right]**2 12 | right -=1 13 | idx -=1 14 | return res -------------------------------------------------------------------------------- /Matrix/Leetcode 311. Sparse Matrix Multiplication.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def multiply(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]: 3 | m_a, n_a = len(A), len(A[0]) 4 | m_b, n_b = len(B), len(B[0]) 5 | res = [[0]*n_b for _ in range(m_a)] 6 | for i in range(m_a): 7 | for j in range(n_a): 8 | if A[i][j] != 0: 9 | for c in range(n_b): 10 | res[i][c] += A[i][j]*B[j][c] 11 | return res -------------------------------------------------------------------------------- /String/Leetcode 13. Roman to Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def romanToInt(self, s: str) -> int: 3 | ss = ["I","V","X","L","C","D","M"] 4 | vv = [1,5,10,50,100,500,1000] 5 | dic = {} 6 | for k,v in zip(ss,vv): 7 | dic[k]=v 8 | res = dic[s[0]] 9 | for i in range(1,len(s)): 10 | if dic[s[i]]>dic[s[i-1]]: 11 | res += dic[s[i]]-dic[s[i-1]]*2 12 | else: 13 | res += dic[s[i]] 14 | return res -------------------------------------------------------------------------------- /Tree/Leetcode 543. Diameter of Binary Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def diameterOfBinaryTree(self, root: TreeNode) -> int: 3 | if not root: 4 | return 0 5 | self.res = 0 6 | self.dfs(root) 7 | return self.res-1 8 | 9 | def dfs(self, root): 10 | if not root: 11 | return 0 12 | left = self.dfs(root.left) 13 | right = self.dfs(root.right) 14 | self.res = max(self.res, left+right+1) 15 | return max(left, right) +1 -------------------------------------------------------------------------------- /Array/Leetcode 239. Sliding Window Maximum.py: -------------------------------------------------------------------------------- 1 | import collections 2 | class Solution: 3 | def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: 4 | q = collections.deque() 5 | res = [] 6 | for i in range(len(nums)): 7 | while q and nums[i] > nums[q[-1]]: 8 | q.pop() 9 | q.append(i) 10 | if i - q[0] == k: 11 | q.popleft() 12 | if i>=k-1: 13 | res.append(nums[q[0]]) 14 | return res -------------------------------------------------------------------------------- /Array/Leetcode 245. Shortest Word Distance III.py: -------------------------------------------------------------------------------- 1 | import collections 2 | class Solution: 3 | def shortestWordDistance(self, words: List[str], word1: str, word2: str) -> int: 4 | dic = collections.defaultdict(set) 5 | for i in range(len(words)): 6 | dic[words[i]].add(i) 7 | 8 | res = float('inf') 9 | for i in dic[word1]: 10 | for j in dic[word2]: 11 | if i!=j: 12 | res = min(res, abs(i-j)) 13 | return res -------------------------------------------------------------------------------- /Array/Leetcode 503. Next Greater Element II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextGreaterElements(self, nums: List[int]) -> List[int]: 3 | stack = [] 4 | stack.append(0) 5 | res = [-1]*len(nums) 6 | for i in range(1,len(nums)*2): 7 | i %= len(nums) 8 | while stack and nums[i]>nums[stack[-1]]: 9 | idx = stack.pop() 10 | res[idx] = nums[i] 11 | stack.append(i) 12 | return res 13 | 14 | -------------------------------------------------------------------------------- /Backtracking/Leetcode 216. Combination Sum III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum3(self, k: int, n: int) -> List[List[int]]: 3 | res = [] 4 | self.bt(1, [], k, n, res) 5 | return res 6 | 7 | def bt(self, idx, tempList, k, n, res): 8 | if n < 0 or k < 0: 9 | return 10 | if n == 0 and k == 0: 11 | res.append(tempList) 12 | return 13 | for i in range(idx,10): 14 | self.bt(i+1, tempList+[i], k-1, n-i,res) -------------------------------------------------------------------------------- /Backtracking/Leetcode 46. Permutations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def permute(self, nums: List[int]) -> List[List[int]]: 3 | res = [] 4 | self.bt(nums, [], res) 5 | return res 6 | 7 | def bt(self, nums, tempList, res): 8 | if len(tempList) == len(nums): 9 | res.append(tempList) 10 | return 11 | for i in range(len(nums)): 12 | if nums[i] in tempList: 13 | continue 14 | self.bt(nums, tempList+[nums[i]], res) -------------------------------------------------------------------------------- /Binary Search/Leetcode 153. Find Minimum in Rotated Sorted Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMin(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | left, right = 0, n-1 5 | while left <= right: 6 | mid = left + (right-left)//2 7 | if nums[mid] nums[right]: 10 | left = mid + 1 11 | else: 12 | right = mid - 1 13 | return nums[left] -------------------------------------------------------------------------------- /String/Leetcode 763. Partition Labels.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def partitionLabels(self, S: str) -> List[int]: 3 | last = {} 4 | for i, c in enumerate(S): 5 | last[c] = i 6 | 7 | cur_end = cur_start = 0 8 | res = [] 9 | for i, c in enumerate(S): 10 | j = last[c] 11 | cur_end = max(cur_end, j) 12 | if i == cur_end: 13 | res.append(i-cur_start+1) 14 | cur_start = i+1 15 | return res -------------------------------------------------------------------------------- /Array/Leetcode 128. Longest Consecutive Sequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestConsecutive(self, nums: List[int]) -> int: 3 | s = set(nums) 4 | res = 0 5 | for num in s: 6 | if num - 1 not in s: 7 | cur_num = num 8 | count = 1 9 | while cur_num + 1 in s: 10 | cur_num += 1 11 | count += 1 12 | res = max(res, count) 13 | return res 14 | 15 | # 只往后面找连续数字,比如3 只找4,5,6 不找2,1 -------------------------------------------------------------------------------- /Array/Leetcode 238. Product of Array Except Self.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def productExceptSelf(self, nums: List[int]) -> List[int]: 3 | n = len(nums) 4 | fwd, bwd = [0]*n, [0]*n 5 | res = [0]*n 6 | fwd[0] = 1 7 | for i in range(1,n): 8 | fwd[i] = fwd[i-1] * nums[i-1] 9 | bwd[-1] = 1 10 | for i in range(n-2,-1,-1): 11 | bwd[i] = bwd[i+1] * nums[i+1] 12 | for i in range(n): 13 | res[i] = fwd[i]*bwd[i] 14 | return res -------------------------------------------------------------------------------- /Array/Leetcode 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 | i = 0 7 | count = 1 8 | for j in range(1, len(nums)): 9 | if nums[j] == nums[i]: 10 | count += 1 11 | else: 12 | count = 1 13 | if count <=2: 14 | i += 1 15 | nums[i] = nums[j] 16 | return i+1 -------------------------------------------------------------------------------- /Array/Leetcode 11. Container With Most Water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, height: List[int]) -> int: 3 | res = 0 4 | left = 0 5 | right = len(height)-1 6 | while left List[List[int]]: 3 | if n <=1: 4 | return[] 5 | res = [] 6 | self.bt(n, 2, [], res) 7 | return res 8 | 9 | def bt(self, n, idx, tempList, res): 10 | if len(tempList)>1 and n == 1: 11 | res.append(tempList) 12 | return 13 | for i in range(idx,n+1): 14 | if n%i ==0: 15 | self.bt(n//i, i, tempList+[i], res) -------------------------------------------------------------------------------- /Design/Leetcode 284. Peeking Iterator.py: -------------------------------------------------------------------------------- 1 | class PeekingIterator: 2 | def __init__(self, iterator): 3 | self.iter = iterator 4 | self.nxt = self.iter.next() if self.iter.hasNext() else None 5 | 6 | 7 | def peek(self): 8 | return self.nxt 9 | 10 | 11 | def next(self): 12 | res = self.nxt 13 | self.nxt = self.iter.next() if self.iter.hasNext() else None 14 | return res 15 | 16 | 17 | def hasNext(self): 18 | return self.nxt != None -------------------------------------------------------------------------------- /Hackerrank/HashTable/Sherlock and Anagrams or Count Substring Anagrams.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem 2 | def anagramPairs(s): 3 | # Write your code here 4 | dic = {} 5 | res = 0 6 | for k in range(1, len(s)): 7 | for i in range(len(s)-k+1): 8 | j = i+k 9 | strr = "".join(sorted(s[i:j])) 10 | dic[strr] = dic.get(strr,0)+1 11 | for v in dic.values(): 12 | if v>1: 13 | res += (v*(v-1))//2 14 | return res -------------------------------------------------------------------------------- /LinkedList/Leetcode 21. Merge Two Sorted Lists.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 3 | dummy = ListNode(0) 4 | cur = dummy 5 | while l1 and l2: 6 | if l1.val <= l2.val: 7 | cur.next=ListNode(l1.val) 8 | l1=l1.next 9 | else: 10 | cur.next=ListNode(l2.val) 11 | l2=l2.next 12 | cur = cur.next 13 | cur.next = l1 or l2 14 | return dummy.next -------------------------------------------------------------------------------- /Tree/Leetcode 285. Inorder Successor in BST.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': 3 | stack = [] 4 | found = False 5 | while stack or root: 6 | while root: 7 | stack.append(root) 8 | root = root.left 9 | node = stack.pop() 10 | if found: 11 | return node 12 | if node.val == p.val: 13 | found = True 14 | root = node.right -------------------------------------------------------------------------------- /Array/Leetcode 244. Shortest Word Distance II.py: -------------------------------------------------------------------------------- 1 | import collections 2 | class WordDistance: 3 | 4 | def __init__(self, words: List[str]): 5 | self.dic = collections.defaultdict(set) 6 | for i in range(len(words)): 7 | self.dic[words[i]].add(i) 8 | 9 | def shortest(self, word1: str, word2: str) -> int: 10 | res = float('inf') 11 | for i in self.dic[word1]: 12 | for j in self.dic[word2]: 13 | res = min(res, abs(i-j)) 14 | return res 15 | # 优化读,用hashtable -------------------------------------------------------------------------------- /Non-Leetcode/Stock Span.py: -------------------------------------------------------------------------------- 1 | # https://www.geeksforgeeks.org/the-stock-span-problem/amp/ 2 | 3 | # input {100, 80, 60, 70, 60, 75, 85} 4 | # output {1, 1, 1, 2, 1, 4, 6} 5 | 6 | def calculateSpan(prices): 7 | res = [0]*len(prices) 8 | 9 | res[0] = 1 10 | stack = [] 11 | stack.append(0) 12 | for i in range(1, len(prices)): 13 | while stack and prices[i] >= prices[stack[-1]]: 14 | stack.pop() 15 | res[i] = i-stack[-1] 16 | stack.append(i) 17 | 18 | print(res) 19 | 20 | calculateSpan([100, 80, 60, 70, 60, 75, 85]) -------------------------------------------------------------------------------- /Tree/Leetcode 889. Construct Binary Tree from Preorder and Postorder Traversal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode: 3 | if not pre or not post: 4 | return None 5 | root = TreeNode(pre[0]) 6 | if len(pre) == 1: 7 | return root 8 | i = post.index(pre[1])+1 9 | root.left = self.constructFromPrePost(pre[1:i+1], post[:i]) 10 | root.right = self.constructFromPrePost(pre[i+1:], post[i:-1]) 11 | return root -------------------------------------------------------------------------------- /Array/Leetcode 253. Meeting Rooms II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minMeetingRooms(self, intervals: List[List[int]]) -> int: 3 | if not intervals: 4 | return 0 5 | rooms = [] 6 | intervals.sort() 7 | heapq.heappush(rooms, intervals[0][1]) 8 | for i in range(1, len(intervals)): 9 | interval = intervals[i] 10 | if interval[0]>=rooms[0]: 11 | heapq.heappop(rooms) 12 | 13 | heappush(rooms, interval[1]) 14 | return len(rooms) -------------------------------------------------------------------------------- /LinkedList/Leetcode 369. Plus One Linked List.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def plusOne(self, head: ListNode) -> ListNode: 3 | carry = self.dfs(head) 4 | if carry == 1: 5 | root = ListNode(1) 6 | root.next = head 7 | return root 8 | else: 9 | return head 10 | 11 | def dfs(self, node): 12 | if not node: 13 | return 1 14 | carry = self.dfs(node.next) 15 | sums = node.val + carry 16 | node.val = sums%10 17 | return sums//10 -------------------------------------------------------------------------------- /Math/Leetcode 670. Maximum Swap.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumSwap(self, num: int) -> int: 3 | i = 1 4 | num = list(str(num)) 5 | dic = {} 6 | for i in range(len(num)): 7 | dic[int(num[i])] = i 8 | 9 | for i in range(len(num)): 10 | for j in range(9, int(num[i]), -1): 11 | if j in dic and dic[j]>i: 12 | num[i], num[dic[j]] = num[dic[j]], num[i] 13 | return int("".join(num)) 14 | return int("".join(num)) -------------------------------------------------------------------------------- /String/Leetcode 125. Valid Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, s: str) -> bool: 3 | left, right = 0, len(s)-1 4 | while left < right: 5 | while not s[left].isalnum() and leftleft: 8 | right-=1 9 | if s[left].lower() == s[right].lower(): 10 | left += 1 11 | right -= 1 12 | else: 13 | return False 14 | return True -------------------------------------------------------------------------------- /String/Leetcode 161. One Edit Distance.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isOneEditDistance(self, s: str, t: str) -> bool: 3 | m, n = len(s), len(t) 4 | if abs(m-n)>1: 5 | return False 6 | for i in range(min(m,n)): 7 | if s[i]!=t[i]: 8 | if m == n: 9 | return s[i+1:] == t[i+1:] 10 | if m > n: 11 | return s[i+1:] == t[i:] 12 | if m < n: 13 | return s[i:] == t[i+1:] 14 | return abs(m-n) == 1 -------------------------------------------------------------------------------- /String/Leetcode 20. Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s: str) -> bool: 3 | stack = [] 4 | for c in s: 5 | if c == '(': 6 | stack.append(')') 7 | elif c == '{': 8 | stack.append('}') 9 | elif c == '[': 10 | stack.append(']') 11 | else: 12 | if stack and c==stack[-1]: 13 | stack.pop() 14 | else: 15 | return False 16 | return not stack -------------------------------------------------------------------------------- /Array/Leetcode 228. Summary Ranges.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def summaryRanges(self, nums: List[int]) -> List[str]: 3 | i = 0 4 | res = [] 5 | while i < len(nums): 6 | if i"+str(nums[i])) 11 | else: 12 | res.append(str(nums[i])) 13 | i+=1 14 | return res -------------------------------------------------------------------------------- /Binary Search/Leetcode 162. Find Peak Element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findPeakElement(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | left, right = 0, n-1 5 | while left <= right: 6 | mid = left + (right - left)//2 7 | if mid == n-1 or nums[mid]>nums[mid+1]: 8 | if nums[mid]>nums[mid-1]: 9 | return mid 10 | else: 11 | right = mid - 1 12 | else: 13 | left = mid + 1 14 | return right + 1 -------------------------------------------------------------------------------- /String/Leetcode 38. Count and Say.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countAndSay(self, n: int) -> str: 3 | i,res = 1, '1' 4 | while i int: 3 | total = cur_gas = 0 4 | start = 0 5 | for i in range(len(gas)): 6 | total += gas[i] - cost[i] 7 | cur_gas += gas[i] - cost[i] 8 | if cur_gas < 0: 9 | start = i + 1 10 | cur_gas = 0 11 | return start if total >= 0 else -1 12 | 13 | #从第一个加油站开始,total是看从任意一点能不能回到原点,cur_gas是开从start出发,车上有多少汽油,如果cur_gar<0表示汽油不够,则start和汽油要重新计算 -------------------------------------------------------------------------------- /Binary Search/Leetcode 35. Search Insert Position.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchInsert(self, nums: List[int], target: int) -> int: 3 | n = len(nums) 4 | left, right = 0, n-1 5 | while left <= right: 6 | mid = left + (right-left) // 2 7 | if nums[mid]>=target: 8 | if mid == 0 or nums[mid-1] int: 4 | dic = collections.defaultdict(set) 5 | for i in range(len(words)): 6 | for ch in words[i]: 7 | dic[i].add(ch) 8 | 9 | res = 0 10 | for i in range(1,len(words)): 11 | for j in range(i): 12 | if not (dic[i] & dic[j]): 13 | res = max(res, len(words[i])*len(words[j])) 14 | return res -------------------------------------------------------------------------------- /String/Leetcode 22. Generate Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateParenthesis(self, n: int) -> List[str]: 3 | res = [] 4 | self.helper(res, '', n, n) 5 | return res 6 | 7 | def helper(self, res, tempList, left, right): 8 | if left > right: 9 | return 10 | if left == 0 and right == 0: 11 | res.append(tempList) 12 | if left>0: 13 | self.helper(res,tempList+'(', left-1,right) 14 | if right>0: 15 | self.helper(res, tempList+')', left, right-1) -------------------------------------------------------------------------------- /Array/Leetcode 41. First Missing Positive.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstMissingPositive(self, nums: List[int]) -> int: 3 | for i in range(len(nums)): 4 | while 0 int: 3 | stack = [] 4 | mn = float('inf') 5 | 6 | while stack or root: 7 | while root: 8 | stack.append(root) 9 | root = root.left 10 | node = stack.pop() 11 | if abs(node.val-target) < mn: 12 | mn = abs(node.val-target) 13 | res = node.val 14 | root = node.right 15 | return res 16 | -------------------------------------------------------------------------------- /LinkedList/Leetcode 82. Remove Duplicates from Sorted List II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def deleteDuplicates(self, head: ListNode) -> ListNode: 3 | dummy = ListNode(0) 4 | dummy.next = head 5 | cur = dummy 6 | while cur and cur.next: 7 | nxt = cur.next.next 8 | if nxt and cur.next.val == nxt.val: 9 | while nxt and cur.next.val == nxt.val: 10 | nxt = nxt.next 11 | cur.next = nxt 12 | else: 13 | cur = cur.next 14 | return dummy.next -------------------------------------------------------------------------------- /Hackerrank/String/Making Anagrams.py: -------------------------------------------------------------------------------- 1 | def makeAnagram(a, b): 2 | dic1 = {} 3 | dic2 = {} 4 | chars = set() 5 | for c in a: 6 | dic1[c] = dic1.get(c, 0)+1 7 | chars.add(c) 8 | for c in b: 9 | dic2[c] = dic2.get(c, 0)+1 10 | chars.add(c) 11 | 12 | res = 0 13 | for c in chars: 14 | if (c in dic1 and c not in dic2) or (c in dic2 and c not in dic1): 15 | res += dic1[c] if c in dic1 else dic2[c] 16 | elif c in dic1 and c in dic2: 17 | res += abs(dic1[c]-dic2[c]) 18 | return res -------------------------------------------------------------------------------- /String/Leetcode 32. Longest Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestValidParentheses(self, s: str) -> int: 3 | if not s: return 0 4 | dp = [0] * len(s) 5 | for i in range(len(s)): 6 | if s[i] == ')': 7 | if i>0 and s[i-1] == '(': 8 | dp[i] = dp[i-2] + 2 9 | if i>0 and s[i-1] == ')': #(()) 10 | if i-dp[i-1] > 0 and s[i-dp[i-1]-1] == '(': 11 | dp[i] = dp[i-1] + dp[i-dp[i-1]-2] + 2 12 | return max(dp) 13 | 14 | # 求极值 考虑DP -------------------------------------------------------------------------------- /Array/ Leetcode 275. H-Index II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hIndex(self, citations: List[int]) -> int: 3 | low,hight, n = 0, len(citations)-1, len(citations) 4 | while low<=hight: 5 | middle = low+(hight-low)//2 6 | if (n - middle) == citations[middle]: 7 | return citations[middle] 8 | if (n - middle) < citations[middle]: 9 | hight = middle -1 10 | if (n - middle) > citations[middle]: 11 | low = middle +1 12 | return n-low 13 | 14 | # 看到Sorted首先想到Binary Search -------------------------------------------------------------------------------- /Tree/Leetcode 110. Balanced Binary Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isBalanced(self, root: TreeNode) -> bool: 3 | if not root: 4 | return True 5 | left = self.getHeight(root.left) 6 | right = self.getHeight(root.right) 7 | return abs(left-right)<2 and self.isBalanced(root.left) and self.isBalanced(root.right) 8 | 9 | def getHeight(self, node): 10 | if not node: 11 | return 0 12 | left =self.getHeight(node.left) 13 | right = self.getHeight(node.right) 14 | return max(left, right) + 1 -------------------------------------------------------------------------------- /Array/Leetcode 274. H-Index.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hIndex(self, citations: List[int]) -> int: 3 | dic = {} 4 | for i in range(len(citations)): 5 | if citations[i] > len(citations): 6 | dic[len(citations)] = dic.get(len(citations),0)+1 7 | else: 8 | dic[citations[i]] = dic.get(citations[i],0)+1 9 | 10 | count = 0 11 | for i in range(len(citations),-1,-1): 12 | count += dic.get(i,0) 13 | if count>=i: 14 | return i 15 | return 0 -------------------------------------------------------------------------------- /Math/Leetcode 67. Add Binary.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addBinary(self, a: str, b: str) -> str: 3 | carry = 0 4 | m,n = len(a)-1,len(b)-1 5 | res = '' 6 | while m>=0 or n>=0: 7 | s = 0 8 | if m >=0: 9 | s += int(a[m]) 10 | m-=1 11 | if n >=0: 12 | s+=int(b[n]) 13 | n-=1 14 | s += carry 15 | s, carry = s%2, s//2 16 | res = str(s) + res 17 | if carry: 18 | res = str(carry) + res 19 | return res -------------------------------------------------------------------------------- /Array/Leetcode 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 | i, j = 0, len(nums)-1 7 | k = 0 8 | while k<=j: 9 | if nums[k] == 0: 10 | nums[i], nums[k] = nums[k],nums[i] 11 | i+=1 12 | k+=1 13 | elif nums[k] == 2: 14 | nums[j], nums[k] = nums[k],nums[j] 15 | j-=1 16 | elif nums[k] == 1: 17 | k+=1 -------------------------------------------------------------------------------- /String/Leetcode 844. Backspace String Compare.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def backspaceCompare(self, S: str, T: str) -> bool: 3 | i = 0 4 | for s in S: 5 | if s != '#': 6 | S = S[:i]+s+S[i+1:] 7 | i+=1 8 | else: 9 | if i>0: 10 | i-=1 11 | j = 0 12 | for t in T: 13 | if t != '#': 14 | T = T[:j]+t+T[j+1:] 15 | j+=1 16 | else: 17 | if j>0: 18 | j-=1 19 | return S[:i] == T[:j] -------------------------------------------------------------------------------- /Tree/Leetcode 124. Binary Tree Maximum Path Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxPathSum(self, root: TreeNode) -> int: 3 | self.res = float('-inf') 4 | self.helper(root) 5 | return self.res 6 | 7 | def helper(self, node): 8 | if not node: 9 | return 0 10 | # 计算左边分支最大值,左边分支如果为负数还不如不选择 11 | left = max(self.helper(node.left), 0) 12 | # 计算右边分支最大值,右边分支如果为负数还不如不选择 13 | right = max(self.helper(node.right), 0) 14 | self.res = max(self.res, node.val + left + right) 15 | return max(left, right)+node.val -------------------------------------------------------------------------------- /Tree/Leetcode 199. Binary Tree Right Side View.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rightSideView(self, root: TreeNode) -> List[int]: 3 | if not root: return [] 4 | q = collections.deque() 5 | q.append(root) 6 | res = [] 7 | while q: 8 | size = len(q) 9 | for _ in range(size): 10 | node = q.popleft() 11 | if node.left: 12 | q.append(node.left) 13 | if node.right: 14 | q.append(node.right) 15 | res.append(node.val) 16 | return res -------------------------------------------------------------------------------- /Array/Leetcode 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 | i,j = m-1, n-1 7 | k = m+n-1 8 | while i>=0 and j>=0: 9 | if nums1[i]>nums2[j]: 10 | nums1[k] = nums1[i] 11 | i-=1 12 | else: 13 | nums1[k] = nums2[j] 14 | j-=1 15 | k-=1 16 | if j>=0: 17 | nums1[:j+1] = nums2[:j+1] -------------------------------------------------------------------------------- /Array/Leetcode 986. Interval List Intersections.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]: 3 | i, j = 0, 0 4 | res = [] 5 | while iA[i][1]: 13 | i+=1 14 | else: 15 | j+=1 16 | return res -------------------------------------------------------------------------------- /Array/Python 287. Find the Duplicate Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicate(self, nums: List[int]) -> int: 3 | left, right = 1, len(nums)-1 4 | while left < right: 5 | mid = left + (right-left)//2 6 | count = 0 7 | for num in nums: 8 | if num<=mid: 9 | count+=1 10 | if count>mid: 11 | right = mid 12 | else: 13 | left = mid + 1 14 | return right 15 | 16 | 17 | # 从1.。n枚举, 如果mid是3, 再遍历nums,如果小于等于3的数大于3个,则重复数子一定在3以前(包括3),反之则在3之后(不包括3) -------------------------------------------------------------------------------- /Backtracking/Leetcode 39. Combination Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 3 | res = [] 4 | self.bt(candidates, 0, [], target, res) 5 | return res 6 | 7 | def bt(self, candidates, idx, tempList, target, res): 8 | if target < 0: 9 | return 10 | if target == 0: 11 | res.append(tempList) 12 | return 13 | for i in range(idx, len(candidates)): 14 | self.bt(candidates, i, tempList+[candidates[i]], target-candidates[i], res) -------------------------------------------------------------------------------- /Tree/Leetcode 366. Find Leaves of Binary Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findLeaves(self, root: TreeNode) -> List[List[int]]: 3 | d = collections.defaultdict(list) 4 | self.dfs(d, root) 5 | res = [] 6 | for v in d.values(): 7 | res.append(v) 8 | return res 9 | 10 | def dfs(self, d, node): 11 | if not node: 12 | return 0 13 | left = self.dfs(d, node.left) 14 | right = self.dfs(d, node.right) 15 | depth = max(left, right) + 1 16 | d[depth].append(node.val) 17 | return depth -------------------------------------------------------------------------------- /DP/Leetcode 256. Paint House.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCost(self, costs: List[List[int]]) -> int: 3 | if not costs: 4 | return 0 5 | m = len(costs) 6 | dp = [[0]*3 for _ in range(m)] 7 | dp[0][0] = costs[0][0] 8 | dp[0][1] = costs[0][1] 9 | dp[0][2] = costs[0][2] 10 | for i in range(1, m): 11 | dp[i][0] = min(dp[i-1][1],dp[i-1][2]) + costs[i][0] 12 | dp[i][1] = min(dp[i-1][0],dp[i-1][2]) + costs[i][1] 13 | dp[i][2] = min(dp[i-1][0],dp[i-1][1]) + costs[i][2] 14 | return min(dp[-1]) -------------------------------------------------------------------------------- /DP/Leetcode 983. Minimum Cost For Tickets.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mincostTickets(self, days: List[int], costs: List[int]) -> int: 3 | dp = [float('inf')]*(days[-1]+1) 4 | for d in days: 5 | dp[d] = 0 6 | dp[0] = 0 7 | for i in range(1,days[-1]+1): 8 | if dp[i] == float('inf'): 9 | dp[i] = dp[i-1] 10 | else: 11 | dp[i] = dp[i-1]+costs[0] 12 | dp[i] = min(dp[i], dp[max(0,i-7)]+costs[1]) 13 | dp[i] = min(dp[i], dp[max(0,i-30)]+costs[2]) 14 | 15 | return dp[-1] -------------------------------------------------------------------------------- /Hackerrank/Array/Jumping on the Clouds.py: -------------------------------------------------------------------------------- 1 | def jumpingOnClouds(c): 2 | pre_max = cur_max = 0 3 | steps = 0 4 | for i in range(len(c)): 5 | if pre_max >= len(c)-1: 6 | return steps 7 | if c[i] == 1: 8 | continue 9 | local_max = 0 10 | if c[i] == 0: 11 | if i+1 < len(c) and c[i+1]!=1: 12 | local_max = i+1 13 | if i+2 < len(c) and c[i+2]!=1: 14 | local_max = i+2 15 | cur_max = max(cur_max, local_max) 16 | if i == pre_max: 17 | pre_max = cur_max 18 | steps += 1 -------------------------------------------------------------------------------- /String/Leetcode 1249. Minimum Remove to Make Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minRemoveToMakeValid(self, s: str) -> str: 3 | remove = [] 4 | stack = [] 5 | for i in range(len(s)): 6 | if s[i] == '(': 7 | stack.append(i) 8 | elif s[i] == ')': 9 | if not stack: 10 | remove.append(i) 11 | else: 12 | stack.pop() 13 | remove.extend(stack) 14 | remove.sort(reverse = True) 15 | for i in remove: 16 | s = s[:i]+s[i+1:] 17 | return s -------------------------------------------------------------------------------- /Binary Search/Leetcode 154. Find Minimum in Rotated Sorted Array II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMin(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | left, right = 0, n-1 5 | while left <= right: 6 | mid = left + (right-left)//2 7 | if nums[mid] nums[right]: 10 | left = mid + 1 11 | elif nums[mid] < nums[right]: 12 | right = mid - 1 13 | elif nums[mid] == nums[right]: 14 | right -= 1 15 | return nums[left] -------------------------------------------------------------------------------- /Graph/Leetcode 133. Clone Graph.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def cloneGraph(self, node: 'Node') -> 'Node': 3 | if not node: 4 | return node 5 | dic = {} 6 | q = collections.deque() 7 | q.append(node) 8 | dic[node] = Node(node.val, []) 9 | while q: 10 | n = q.popleft() 11 | for neighbor in n.neighbors: 12 | if neighbor not in dic: 13 | dic[neighbor] = Node(neighbor.val, []) 14 | q.append(neighbor) 15 | dic[n].neighbors.append(dic[neighbor]) 16 | return dic[node] -------------------------------------------------------------------------------- /Array/Leetcode 42. Trapping Rain Water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trap(self, height: List[int]) -> int: 3 | leftmost, rightmost = 0, 0 4 | left, right = 0, len(height)-1 5 | res = 0 6 | while left int: 3 | self.subsums = [] 4 | totalsums = self.helper(root) 5 | res = 0 6 | for s in self.subsums: 7 | res = max(res, s*(totalsums-s)) 8 | return res % (10**9 + 7) 9 | 10 | def helper(self, root): 11 | if not root: 12 | return 0 13 | left = self.helper(root.left) 14 | right = self.helper(root.right) 15 | sums = left+right+root.val 16 | self.subsums.append(sums) 17 | return sums -------------------------------------------------------------------------------- /DP/Leetcode 312. Burst Balloons.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxCoins(self, nums: List[int]) -> int: 3 | newnums = [] 4 | # for n in nums: 5 | # if n!=0: 6 | # newnums.append(n) 7 | newnums = [1]+nums+[1] 8 | n = len(newnums) 9 | dp = [[0]*n for _ in range(n)] 10 | for left in range(n-3,-1,-1): 11 | for right in range(left+2, n): 12 | for i in range(left+1, right): 13 | dp[left][right] = max(dp[left][right],dp[left][i]+newnums[i]*newnums[left]*newnums[right] + dp[i][right] ) 14 | return dp[0][n-1] -------------------------------------------------------------------------------- /DP/Leetcode 44. Wildcard Matching.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isMatch(self, s: str, p: str) -> bool: 3 | m, n = len(s), len(p) 4 | dp = [[0]*(n+1) for _ in range(m+1)] 5 | dp[0][0] = 1 6 | for j in range(1, n+1): 7 | if p[j-1] == '*': 8 | dp[0][j] = dp[0][j-1] 9 | for i in range(1, m+1): 10 | for j in range(1, n+1): 11 | if s[i-1] == p[j-1] or p[j-1] == '?': 12 | dp[i][j] = dp[i-1][j-1] 13 | elif p[j-1] == '*': 14 | dp[i][j] = dp[i][j-1] or dp[i-1][j] 15 | return dp[m][n] -------------------------------------------------------------------------------- /Tree/Leetcode 129. Sum Root to Leaf Numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumNumbers(self, root: TreeNode) -> int: 3 | if not root: 4 | return 0 5 | res = 0 6 | stack = [] 7 | stack.append((root,str(root.val))) 8 | while stack: 9 | node, strr = stack.pop() 10 | if not node.left and not node.right: 11 | res+=int(strr) 12 | if node.left: 13 | stack.append((node.left, strr+str(node.left.val))) 14 | if node.right: 15 | stack.append((node.right, strr+str(node.right.val))) 16 | return res -------------------------------------------------------------------------------- /Array/Leetcode 496. Next Greater Element I.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 | stack = [] 4 | stack.append(0) 5 | dic = {} 6 | for i in range(1, len(nums2)): 7 | while stack and nums2[i]>nums2[stack[-1]]: 8 | idx = stack.pop() 9 | dic[nums2[idx]] = nums2[i] 10 | stack.append(i) 11 | res = [] 12 | for num in nums1: 13 | if num in dic: 14 | res.append(dic[num]) 15 | else: 16 | res.append(-1) 17 | return res -------------------------------------------------------------------------------- /DFS BFS/Leetcode 339. Nested List Weight Sum.py: -------------------------------------------------------------------------------- 1 | # BFS 2 | class Solution: 3 | def depthSum(self, nestedList: List[NestedInteger]) -> int: 4 | level = 0 5 | q = collections.deque() 6 | q.append(nestedList) 7 | sums = 0 8 | while q: 9 | level += 1 10 | size = len(q) 11 | for _ in range(size): 12 | nl = q.popleft() 13 | for n in nl: 14 | if n.isInteger(): 15 | sums += n.getInteger()*level 16 | else: 17 | q.append(n.getList()) 18 | return sums -------------------------------------------------------------------------------- /LinkedList/Leetcode 147. Insertion Sort List.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def insertionSortList(self, head: ListNode) -> ListNode: 3 | dummy = ListNode(0) 4 | cur = dummy.next = head 5 | while cur and cur.next: 6 | if cur.next.val > cur.val: 7 | cur = cur.next 8 | else: 9 | nxt = cur.next 10 | cur.next = nxt.next 11 | pre = dummy 12 | while pre.next and pre.next.val int: 3 | str = str.strip() 4 | if not str: 5 | return 0 6 | sign = 1 7 | if str[0] in '+-': 8 | sign = 1 if str[0] =='+' else -1 9 | str = str[1:] 10 | res = 0 11 | for s in str: 12 | if not s.isdigit(): 13 | break 14 | res = res * 10 + int(s) 15 | 16 | res = sign * res 17 | if res > 2**31 -1: 18 | return 2**31-1 19 | if res < -2**31: 20 | return -2**31 21 | return res -------------------------------------------------------------------------------- /String/Leetcode 97. Interleaving String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isInterleave(self, s1: str, s2: str, s3: str) -> bool: 3 | l1, l2 = len(s1),len(s2) 4 | if l1+l2!= len(s3): 5 | return False 6 | dp = [[0]*(l2+1) for _ in range(l1+1)] 7 | dp[0][0] = 1 8 | 9 | for i in range(l1+1): 10 | for j in range(l2+1): 11 | k = i+j-1 12 | if i>0 and dp[i-1][j] and s3[k] == s1[i-1]: 13 | dp[i][j] = 1 14 | elif j>0 and dp[i][j-1] and s3[k] == s2[j-1]: 15 | dp[i][j] = 1 16 | return dp[-1][-1] -------------------------------------------------------------------------------- /Array/Leetcode 163. Missing Ranges.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]: 3 | res = [] 4 | left = lower 5 | for i in range(len(nums)): 6 | if nums[i]>left: 7 | if nums[i] == left+1: 8 | res.append(str(left)) 9 | else: 10 | res.append(str(left)+"->"+str(nums[i]-1)) 11 | left = nums[i]+1 12 | if upper == left: 13 | res.append(str(upper)) 14 | elif upper > left: 15 | res.append(str(left)+"->"+str(upper)) 16 | return res -------------------------------------------------------------------------------- /DP/Leetcode 213. House Robber II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | if not nums: 4 | return 0 5 | if len(nums) == 1: 6 | return nums[0] 7 | wo_first = nums[1:] 8 | wo_last = nums[:-1] 9 | n = len(nums)-1 10 | dp1 = [0]*n 11 | dp2 = [0]*n 12 | dp1[0] = wo_first[0] 13 | dp2[0] = wo_last[0] 14 | for i in range(1,n): 15 | dp1[i] = max(dp1[i-1], wo_first[i] + (dp1[i-2] if i>1 else 0) ) 16 | dp2[i] = max(dp2[i-1], wo_last[i] + (dp2[i-2] if i>1 else 0) ) 17 | return max(dp1[-1], dp2[-1]) -------------------------------------------------------------------------------- /DP/Leetcode 265. Paint House II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCostII(self, costs: List[List[int]]) -> int: 3 | if not costs: 4 | return 0 5 | m, k = len(costs), len(costs[0]) 6 | dp = [[0]*k for _ in range(m)] 7 | for i in range(k): 8 | dp[0][i] = costs[0][i] 9 | for i in range(1,m): 10 | for j in range(k): 11 | min_pre = float('inf') 12 | for h in range(k): 13 | if h != j: 14 | min_pre = min(min_pre, dp[i-1][h]) 15 | dp[i][j] = min_pre+costs[i][j] 16 | return min(dp[-1]) -------------------------------------------------------------------------------- /DP/Leetcode 72. Edit Distance.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minDistance(self, word1: str, word2: str) -> int: 3 | m, n = len(word1), len(word2) 4 | dp = [[0]*(n+1) for _ in range(m+1)] 5 | for i in range(m+1): 6 | dp[i][0] = i 7 | for j in range(n+1): 8 | dp[0][j] = j 9 | 10 | for i in range(1, m+1): 11 | for j in range(1, n+1): 12 | if word1[i-1] == word2[j-1]: 13 | dp[i][j] = dp[i-1][j-1] 14 | else: 15 | dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])+1 16 | return dp[-1][-1] -------------------------------------------------------------------------------- /Design/Leetcode 359. Logger Rate Limiter.py: -------------------------------------------------------------------------------- 1 | class Logger: 2 | 3 | def __init__(self): 4 | self.times = [0]*10 5 | self.dic = collections.defaultdict(set) 6 | 7 | def shouldPrintMessage(self, timestamp: int, message: str) -> bool: 8 | t = timestamp % 10 9 | if self.times[t] != timestamp: 10 | self.times[t] = timestamp # reset 11 | self.dic[t] = set() #reset 12 | for i in range(10): 13 | if timestamp - self.times[i] < 10: 14 | if message in self.dic[i]: 15 | return False 16 | self.dic[t].add(message) 17 | return True -------------------------------------------------------------------------------- /Design/Leetcode 895. Maximum Frequency Stack.py: -------------------------------------------------------------------------------- 1 | class FreqStack: 2 | 3 | def __init__(self): 4 | self.dic = collections.defaultdict(int) 5 | self.freq = collections.defaultdict(list) 6 | self.max_freq = 0 7 | 8 | def push(self, x: int) -> None: 9 | f =self.dic[x]+1 10 | self.freq[f].append(x) 11 | self.dic[x] = f 12 | self.max_freq = max(self.max_freq, f) 13 | 14 | def pop(self) -> int: 15 | x = self.freq[self.max_freq].pop() 16 | self.dic[x] -= 1 17 | if len(self.freq[self.max_freq]) == 0: 18 | self.max_freq -= 1 19 | return x -------------------------------------------------------------------------------- /Hackerrank/Array/2D Array - Maximum Hourglass.py: -------------------------------------------------------------------------------- 1 | def getRegion(arr, x, y): 2 | region = 0 3 | for i in range(3): 4 | for j in range(3): 5 | if i == 1 and (j ==0 or j ==2): 6 | continue 7 | region+=arr[x+i][y+j] 8 | return region 9 | 10 | 11 | def hourglassSum(arr): 12 | if not arr: 13 | return -1 14 | m, n = len(arr), len(arr[0]) 15 | if m<3 or n<3: 16 | return -1 17 | res = float('-inf') 18 | for i in range(m-2): 19 | for j in range(n-2): 20 | region = getRegion(arr, i, j) 21 | res = max(res, region) 22 | return res -------------------------------------------------------------------------------- /String/Leetcode 157. Read N Characters Given Read4.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def read(self, buf, n): 3 | """ 4 | :type buf: Destination buffer (List[str]) 5 | :type n: Number of characters to read (int) 6 | :rtype: The number of actual characters read (int) 7 | """ 8 | idx = 0 9 | buf4 = [None]*4 10 | res = [] 11 | while n > 0: 12 | k = read4(buf4) 13 | if not k: 14 | return idx 15 | for i in range(min(k,n)): 16 | buf[idx] = buf4[i] 17 | idx += 1 18 | n -= 1 19 | return idx -------------------------------------------------------------------------------- /String/Leetcode 168. Excel Sheet Column Title.py: -------------------------------------------------------------------------------- 1 | class Solution1: 2 | def convertToTitle(self, n: int) -> str: 3 | res = '' 4 | while n>26: 5 | n,m = divmod(n, 26) 6 | if m ==0: 7 | m = 26 8 | n -= 1 9 | res = chr(m-1 + ord('A')) + res 10 | res = chr(n-1+ord('A')) + res 11 | return res 12 | 13 | 14 | class Solution2: 15 | def convertToTitle(self, n: int) -> str: 16 | if n<=26: 17 | return chr(ord('A')+ n-1) 18 | else: 19 | return self.convertToTitle((n-1)//26)+chr((n-1)%26+ord('A')) -------------------------------------------------------------------------------- /Tree/Leetcode 117. Populating Next Right Pointers in Each Node II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def connect(self, root: 'Node') -> 'Node': 3 | if not root: 4 | return root 5 | q = collections.deque() 6 | q.append(root) 7 | while q: 8 | size = len(q) 9 | nxt = None 10 | for _ in range(size): 11 | node = q.popleft() 12 | node.next = nxt 13 | nxt = node 14 | if node.right: 15 | q.append(node.right) 16 | if node.left: 17 | q.append(node.left) 18 | return root -------------------------------------------------------------------------------- /Graph/Leetcode 138. Copy List with Random Pointer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def copyRandomList(self, head: 'Node') -> 'Node': 3 | dummy = Node(0) 4 | new_head = dummy 5 | dic = {} 6 | while head: 7 | if head not in dic: 8 | dic[head] = Node(head.val) 9 | new_head.next = dic[head] 10 | if head.random: 11 | if head.random not in dic: 12 | dic[head.random] = Node(head.random.val) 13 | new_head.next.random = dic[head.random] 14 | new_head = new_head.next 15 | head = head.next 16 | return dummy.next -------------------------------------------------------------------------------- /String/Leetcode 186. Reverse Words in a String II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: List[str]) -> None: 3 | """ 4 | Do not return anything, modify s in-place instead. 5 | """ 6 | self.reverse(s,0,len(s)-1) 7 | i = j = 0 8 | while j < len(s): 9 | if s[j] == ' ': 10 | self.reverse(s,i,j-1) 11 | i = j+1 12 | j+=1 13 | self.reverse(s,i,j-1) 14 | 15 | def reverse(self, s, left, right): 16 | while left TreeNode: 3 | if not head: 4 | return 5 | pre = None 6 | slow = fast = head 7 | while fast and fast.next: 8 | pre = slow 9 | slow = slow.next 10 | fast = fast.next.next 11 | if pre: 12 | pre.next = None 13 | root = TreeNode(slow.val) 14 | if slow == head: 15 | return root 16 | root.left = self.sortedListToBST(head) 17 | root.right = self.sortedListToBST(slow.next) 18 | return root -------------------------------------------------------------------------------- /Tree/Leetcode 111. Minimum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 1 | import collections 2 | class Solution: 3 | def minDepth(self, root: TreeNode) -> int: 4 | if not root: 5 | return 0 6 | q = collections.deque() 7 | q.append((root, 1)) 8 | while q: 9 | size = len(q) 10 | for _ in range(size): 11 | node, depth = q.popleft() 12 | if not node.left and not node.right: 13 | return depth 14 | if node.left: 15 | q.append((node.left, depth+1)) 16 | if node.right: 17 | q.append((node.right, depth+1)) -------------------------------------------------------------------------------- /Array/Leetcode 403. Frog Jump.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCross(self, stones: List[int]) -> bool: 3 | fail = set() 4 | stone_set = set(stones) 5 | stack = [] 6 | stack.append((0,0)) 7 | while stack: 8 | cur_pos, jump = stack.pop() 9 | for j in (jump-1, jump, jump+1): 10 | pos = cur_pos+j 11 | if pos > 0 and pos in stone_set and (pos, j) not in fail: 12 | if pos == stones[-1]: 13 | return True 14 | stack.append((pos, j)) 15 | 16 | fail.add((cur_pos, jump)) 17 | return False -------------------------------------------------------------------------------- /Array/Leetcode 581. Shortest Unsorted Continuous Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findUnsortedSubarray(self, nums: List[int]) -> int: 3 | stack = [] 4 | left = len(nums) 5 | right = 0 6 | for i in range(len(nums)): 7 | while stack and nums[i]nums[stack[-1]]: 13 | right = max(right, stack.pop()) 14 | stack.append(i) 15 | return right-left+1 if right>left else 0 16 | -------------------------------------------------------------------------------- /Array/Leetcode 56. Merge Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 3 | if not intervals: return [] 4 | res = [] 5 | intervals.sort() 6 | pre = intervals[0] 7 | for i in range(1,len(intervals)): 8 | interval = intervals[i] 9 | if interval[0] > pre[1]: 10 | res.append(pre) 11 | pre = interval 12 | elif interval[1] < pre[0]: 13 | res.append(interval) 14 | else: 15 | pre = [min(interval[0],pre[0]),max(interval[1],pre[1])] 16 | res.append(pre) 17 | return res -------------------------------------------------------------------------------- /DP/Leetcode 221. Maximal Square.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximalSquare(self, matrix: List[List[str]]) -> int: 3 | if not matrix: return 0 4 | m, n = len(matrix), len(matrix[0]) 5 | dp = [[0]*n for _ in range(m)] 6 | res = 0 7 | for i in range(m): 8 | dp[i][0] = int(matrix[i][0]) 9 | for j in range(n): 10 | dp[0][j] = int(matrix[0][j]) 11 | for i in range(1, m): 12 | for j in range(1, n): 13 | if matrix[i][j] == '1': 14 | dp[i][j] = min(dp[i-1][j],dp[i-1][j-1],dp[i][j-1])+1 15 | res = max(res, dp[i][j]) 16 | return res**2 -------------------------------------------------------------------------------- /Hackerrank/Array/Minimum Swaps to Sort Array.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/minimum-swaps-2/problem 2 | # Explaination :https://www.youtube.com/watch?v=J9ikRMK8Yhs 3 | 4 | def minimumSwaps(arr): 5 | dic = {} 6 | for i in range(len(arr)): 7 | dic[i+1] =arr[i] 8 | visited = [0]*(len(arr)+1) 9 | visited[0] = 1 10 | res = 0 11 | for i in range(1,len(arr)+1): 12 | if visited[i] or dic[i] == i: 13 | continue 14 | j = i 15 | circle = 0 16 | while not visited[j]: 17 | visited[j] = 1 18 | j = dic[j] 19 | circle+=1 20 | res += circle -1 21 | return res -------------------------------------------------------------------------------- /String/Leetcode 1246. Palindrome Removal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumMoves(self, A): 3 | dp = [[len(A) for i in A] for j in A] 4 | for i in range(len(A)): 5 | dp[i][i] = 1 6 | for i in range(len(A)-1): 7 | dp[i][i+1] = 1 if A[i] == A[i+1] else 2 8 | 9 | for size in range(3,len(A)+1): 10 | for l in range(len(A)-size+1): 11 | r = l+size-1 12 | if A[l] == A[r]: 13 | dp[l][r] = dp[l+1][r-1] 14 | for mid in range(l, r): 15 | dp[l][r] = min( dp[l][r], dp[l][mid]+dp[mid+1][r]) 16 | return dp[0][len(A)-1] -------------------------------------------------------------------------------- /String/Leetcode 516. Longest Palindromic Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | # down-top 4 | def longestPalindromeSubseq(self, s: str) -> int: 5 | n = len(s) 6 | 7 | dp = [[0]*n for _ in range(n)] 8 | 9 | for i in range(n): 10 | dp[i][i] = 1 11 | 12 | 13 | for left in range(n-1,-1,-1): 14 | for right in range(left+1,n): 15 | if s[left]==s[right]: 16 | dp[left][right] = 2+dp[left+1][right-1] 17 | else: 18 | dp[left][right] = max(dp[left+1][right],dp[left][right-1]) 19 | return dp[0][-1] -------------------------------------------------------------------------------- /Array/Leetcode 325. Maximum Size Subarray Sum Equals k.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArrayLen(self, nums: List[int], k: int) -> int: 3 | preSum = [0]*(len(nums)+1) 4 | preSum[0] = 0 5 | for i in range(1, len(nums)+1): 6 | preSum[i] = preSum[i-1] + nums[i-1] 7 | 8 | 9 | dic = {} 10 | res = 0 11 | for i in range(len(preSum)): 12 | if preSum[i] not in dic: 13 | dic[preSum[i]] = i 14 | if preSum[i]-k in dic: 15 | res = max(res, i-dic[preSum[i]-k]) 16 | return res 17 | 18 | 19 | # 求数组某部分连续的合,考虑创建一个PreSum数组: 数组i 到 j的和 = presum[j+1] - presum[i]的合 -------------------------------------------------------------------------------- /Design/Leetcode 362. Design Hit Counter.py: -------------------------------------------------------------------------------- 1 | class HitCounter: 2 | 3 | def __init__(self): 4 | self.times = [0]*300 5 | self.counts = [0]*300 6 | 7 | 8 | def hit(self, timestamp: int) -> None: 9 | t = timestamp % 300 10 | if self.times[t] != timestamp: 11 | self.times[t] = timestamp 12 | self.counts[t] = 1 13 | else: 14 | self.counts[t] += 1 15 | 16 | 17 | def getHits(self, timestamp: int) -> int: 18 | count = 0 19 | for i in range(300): 20 | if timestamp - self.times[i] < 300: 21 | count += self.counts[i] 22 | return count -------------------------------------------------------------------------------- /Non-Leetcode/Number of Subsets I.py: -------------------------------------------------------------------------------- 1 | # For a given list of integers and integer K, find the number of non-empty subsets S such that min(S) + max(S) = K. 2 | 3 | # Example 1: 4 | 5 | # nums = [1, 2, 3, 4] 6 | # k = 5 7 | # Output: 5 8 | # Explanation: [1,4],[1,2,4][1,2,3,4][1,3,4][2,3] 9 | 10 | def countSubsets(nums,k): 11 | nums.sort() 12 | count = 0 13 | for i in range(len(nums)): 14 | for j in range(i,len(nums)): 15 | if nums[i]+nums[j]>k: 16 | break 17 | if nums[i]+nums[j]==k: 18 | count += 2**((j-i-1) if j-i>1 else 0) 19 | print(count) 20 | return count 21 | 22 | countSubsets([1,2,3,4,5], 5) -------------------------------------------------------------------------------- /Non-Leetcode/Pythagorean Triplet in an array.py: -------------------------------------------------------------------------------- 1 | # Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a^2 + b^2 = c^2. 2 | 3 | def isTriplet(ar): 4 | n = len(ar) 5 | for i in range(n): 6 | ar[i] = ar[i] * ar[i] 7 | ar.sort() 8 | 9 | for i in range(n-1, 1, -1): 10 | j = 0 11 | k = i - 1 12 | while (j < k): 13 | if (ar[j] + ar[k] == ar[i]): 14 | return True 15 | else: 16 | if (ar[j] + ar[k] < ar[i]): 17 | j = j + 1 18 | else: 19 | k = k - 1 20 | return False 21 | isTriplet([3, 1, 4, 6, 2]) -------------------------------------------------------------------------------- /Random/Leetcode 384. Shuffle an Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def __init__(self, nums: List[int]): 4 | self.nums = nums 5 | 6 | def reset(self) -> List[int]: 7 | """ 8 | Resets the array to its original configuration and return it. 9 | """ 10 | return self.nums 11 | 12 | 13 | def shuffle(self) -> List[int]: 14 | """ 15 | Returns a random shuffling of the array. 16 | """ 17 | nums_copy = self.nums[::] 18 | for i in range(len(nums_copy)): 19 | j = random.randint(0,i) 20 | nums_copy[i], nums_copy[j] = nums_copy[j], nums_copy[i] 21 | return nums_copy -------------------------------------------------------------------------------- /Stack Queue/Leetcode 341. Flatten Nested List Iterator.py: -------------------------------------------------------------------------------- 1 | import collections 2 | class NestedIterator: 3 | def __init__(self, nestedList: [NestedInteger]): 4 | self.q = collections.deque() 5 | self.flatten(nestedList) 6 | def flatten(self, nestedList): 7 | if not nestedList: return 8 | for ni in nestedList: 9 | if ni.isInteger(): 10 | self.q.append(ni.getInteger()) 11 | else: 12 | self.flatten(ni.getList()) 13 | 14 | def next(self) -> int: 15 | if self.q: 16 | return self.q.popleft() 17 | 18 | def hasNext(self) -> bool: 19 | return len(self.q)>0 -------------------------------------------------------------------------------- /DP/Leetcode 1143. Longest Common Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 3 | m, n = len(text1), len(text2) 4 | dp = [[0]*(n+1) for _ in range(m+1)] 5 | res = 0 6 | for i in range(1,m+1): 7 | for j in range(1,n+1): 8 | if text1[i-1] == text2[j-1]: 9 | dp[i][j] = dp[i-1][j-1]+1 10 | else: 11 | # dp[i-1][j]: remove text1[i-1] 12 | # dp[i][j-1]: remove text2[j-1] 13 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]) 14 | res = max(res, dp[i][j]) 15 | return res -------------------------------------------------------------------------------- /Tree/Leetcode 426. Convert Binary Search Tree to Sorted Doubly Linked List.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def treeToDoublyList(self, root: 'Node') -> 'Node': 3 | if not root: 4 | return None 5 | dummy = Node(-1) 6 | pre = dummy 7 | stack = [] 8 | while stack or root: 9 | while root: 10 | stack.append(root) 11 | root = root.left 12 | cur = stack.pop() 13 | pre.right = cur 14 | cur.left = pre 15 | pre = cur 16 | root = cur.right 17 | head = dummy.right 18 | head.left = pre 19 | pre.right = head 20 | return head -------------------------------------------------------------------------------- /Array/Leetcode 299. Bulls and Cows.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getHint(self, secret: str, guess: str) -> str: 3 | bulls = cows = 0 4 | dic = {} 5 | for i in range(len(guess)): 6 | if guess[i] == secret[i]: 7 | bulls += 1 8 | else: 9 | dic[secret[i]] = dic.get(secret[i], 0)+1 10 | 11 | for i in range(len(guess)): 12 | if guess[i] != secret[i] and dic.get(guess[i], 0) != 0: 13 | cows += 1 14 | dic[guess[i]] -= 1 15 | return str(bulls)+"A"+str(cows)+"B" 16 | 17 | 18 | # 第一轮遍历后,bulls统计完,把剩余没比较的secret放入dic,再统计cows。避免这个case s='1100' g = '0011' 0A4B -------------------------------------------------------------------------------- /String/Leetcode 271. Encode and Decode Strings.py: -------------------------------------------------------------------------------- 1 | class Codec: 2 | def encode(self, strs: [str]) -> str: 3 | """Encodes a list of strings to a single string. 4 | """ 5 | res='' 6 | for strr in strs: 7 | res += str(len(strr))+'$'+strr 8 | print(res) 9 | return res 10 | 11 | def decode(self, s: str) -> [str]: 12 | """Decodes a single string to a list of strings. 13 | """ 14 | res = [] 15 | i = 0 16 | while i List[str]: 3 | if not digits: return [] 4 | dic = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} 5 | res = [] 6 | self.bt(0, '', digits, dic, res) 7 | return res 8 | 9 | def bt(self, idx, strr, digits, dic ,res): 10 | if len(strr) == len(digits): 11 | res.append(strr) 12 | return 13 | for i in range(idx, len(digits)): 14 | for char in dic[digits[i]]: 15 | self.bt(i+1, strr+char, digits, dic, res) -------------------------------------------------------------------------------- /DFS BFS/Leetcode 1236. Web Crawler.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def crawl(self, startUrl: str, htmlParser: 'HtmlParser') -> List[str]: 3 | hostname = startUrl[:startUrl.find('/', startUrl.find('//')+2)] 4 | q = collections.deque() 5 | q.append(startUrl) 6 | res = [startUrl] 7 | visited = set() 8 | visited.add(startUrl) 9 | while q: 10 | url = q.popleft() 11 | urls = htmlParser.getUrls(url) 12 | for u in urls: 13 | if u.find(hostname)>=0 and u not in visited: 14 | visited.add(u) 15 | res.append(u) 16 | q.append(u) 17 | return res -------------------------------------------------------------------------------- /LinkedList/Leetcode 143. Reorder List.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reorderList(self, head: ListNode) -> None: 3 | """ 4 | Do not return anything, modify head in-place instead. 5 | """ 6 | if not head: 7 | return 8 | stack = [] 9 | cur = head 10 | while cur: 11 | stack.append(cur) 12 | cur = cur.next 13 | count = (len(stack)-1)//2 14 | cur = head 15 | while count>0: 16 | node = stack.pop() 17 | nxt = cur.next 18 | cur.next = node 19 | node.next = nxt 20 | cur = nxt 21 | count-=1 22 | stack[-1].next = None -------------------------------------------------------------------------------- /LinkedList/Leetcode 2. Add Two Numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 3 | dummy = ListNode(0) 4 | cur = dummy 5 | carry = 0 6 | while l1 or l2: 7 | sums = 0 8 | if l1: 9 | sums += l1.val 10 | l1 = l1.next 11 | if l2: 12 | sums += l2.val 13 | l2 = l2.next 14 | sums += carry 15 | cur.next = ListNode(sums%10) 16 | cur = cur.next 17 | carry = sums//10 18 | if carry: 19 | cur.next = ListNode(carry) 20 | 21 | return dummy.next -------------------------------------------------------------------------------- /Backtracking/Leetcode 60. Permutation Sequence.py: -------------------------------------------------------------------------------- 1 | # TLE 2 | class Solution: 3 | def getPermutation(self, n: int, k: int) -> str: 4 | self.res = '' 5 | self.k = k 6 | self.bt(n, '', set()) 7 | return self.res 8 | 9 | def bt(self, n, strr, visited): 10 | if len(strr) == n: 11 | self.k -= 1 12 | if self.k == 0: 13 | self.res = strr 14 | return 15 | for i in range(1,n+1): 16 | if self.res: 17 | break 18 | if i not in visited: 19 | visited.add(i) 20 | self.bt(n, strr+str(i), visited) 21 | visited.remove(i) -------------------------------------------------------------------------------- /Backtracking/Leetcode 93. Restore IP Addresses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def restoreIpAddresses(self, s: str) -> List[str]: 3 | if len(s)>12: 4 | return [] 5 | res = [] 6 | self.helper(s, [], res) 7 | return res 8 | 9 | 10 | def helper(self, s, tempList, res): 11 | if len(tempList) == 4 and not s: 12 | res.append(".".join(tempList)) 13 | return 14 | if len(tempList)>4: 15 | return 16 | 17 | for i in range(1,min(4,len(s)+1)): 18 | if i>1 and s[0]=='0': 19 | break 20 | if 0<=int(s[:i])<=255: 21 | self.helper(s[i:], tempList+[s[:i]], res) -------------------------------------------------------------------------------- /Design/Leetcode 251. Flatten 2D Vector.py: -------------------------------------------------------------------------------- 1 | class Vector2D: 2 | 3 | def __init__(self, v: List[List[int]]): 4 | self. v = v 5 | self.inner = 0 6 | self.outer = 0 7 | 8 | def next(self) -> int: 9 | while self.outer < len(self.v) and self.inner == len(self.v[self.outer]) : 10 | self.inner = 0 11 | self.outer +=1 12 | res = self.v[self.outer][self.inner] 13 | self.inner += 1 14 | return res 15 | 16 | def hasNext(self) -> bool: 17 | while self.outer < len(self.v) and self.inner == len(self.v[self.outer]) : 18 | self.inner = 0 19 | self.outer +=1 20 | return self.outer < len(self.v) -------------------------------------------------------------------------------- /LinkedList/Leetcode 86. Partition List.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def partition(self, head: ListNode, x: int) -> ListNode: 3 | dummy = ListNode(0) 4 | pre = dummy 5 | dummy.next = head 6 | # find the last node Y which is smaller than x 7 | while pre.next and pre.next.val= x: 12 | cur = cur.next 13 | else: 14 | nxt = cur.next 15 | cur.next = nxt.next 16 | nxt.next = pre.next 17 | pre.next = nxt 18 | pre = pre.next 19 | return dummy.next -------------------------------------------------------------------------------- /Random/Leetcode 382. Linked List Random Node.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def __init__(self, head: ListNode): 4 | """ 5 | @param head The linked list's head. 6 | Note that the head is guaranteed to be not null, so it contains at least one node. 7 | """ 8 | self.head = head 9 | 10 | 11 | def getRandom(self) -> int: 12 | """ 13 | Returns a random node's value. 14 | """ 15 | cur = self.head 16 | count = 0 17 | res = -1 18 | while cur: 19 | count += 1 20 | if random.randint(1, count) == 1: 21 | res = cur.val 22 | cur = cur.next 23 | return res -------------------------------------------------------------------------------- /Backtracking/Leetcode 47. Permutations II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def permuteUnique(self, nums: List[int]) -> List[List[int]]: 3 | nums.sort() 4 | res = [] 5 | self.bt(nums, [], set(), res) 6 | return res 7 | 8 | def bt(self, nums, tempList, used, res): 9 | if len(nums) == len(tempList): 10 | res.append(tempList) 11 | return 12 | for i in range(len(nums)): 13 | if i in used: 14 | continue 15 | if i > 0 and nums[i] == nums[i-1] and i-1 in used: 16 | continue 17 | used.add(i) 18 | self.bt(nums, tempList+[nums[i]], used, res) 19 | used.remove(i) -------------------------------------------------------------------------------- /Array/Leetcode 957. Prison Cells After N Days.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]: 3 | cur = [0]*8 4 | firstDay = [] 5 | count = 0 6 | while N>0: 7 | for i in range(1,7): 8 | if cells[i-1] == cells[i+1]: 9 | cur[i] = 1 10 | else: 11 | cur[i] = 0 12 | if count==0: 13 | firstDay = cur[:] 14 | elif cur == firstDay: 15 | N %= count 16 | if N == 0: 17 | N = count 18 | count +=1 19 | N-=1 20 | cells = cur[:] 21 | return cur -------------------------------------------------------------------------------- /Backtracking/Leetcode 40. Combination Sum II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: 3 | candidates.sort() 4 | res = [] 5 | self.bt(candidates,0,[],target, res) 6 | return res 7 | 8 | def bt(self, candidates, idx, tempList, target, res): 9 | if target < 0: 10 | return 11 | if target == 0: 12 | res.append(tempList) 13 | return 14 | for i in range(idx, len(candidates)): 15 | if i>idx and candidates[i] == candidates[i-1]: 16 | continue 17 | self.bt(candidates, i+1, tempList+[candidates[i]], target-candidates[i], res) -------------------------------------------------------------------------------- /DFS BFS/Leetcode 494. Target Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTargetSumWays(self, nums: List[int], S: int) -> int: 3 | self.res = 0 4 | dic = collections.defaultdict(dict) 5 | return self.helper(nums, 0, S, dic) 6 | return (self.res) 7 | 8 | def helper(self, nums, idx, S, dic): 9 | if idx == len(nums): 10 | if S == 0: 11 | return 1 12 | else: 13 | return 0 14 | if S in dic[idx]: 15 | return dic[idx][S] 16 | x = self.helper(nums, idx+1, S-nums[idx], dic) 17 | y = self.helper(nums, idx+1, S+nums[idx], dic) 18 | dic[idx][S] = x+y 19 | return dic[idx][S] 20 | -------------------------------------------------------------------------------- /Design/Leetcode 281. Zigzag Iterator.py: -------------------------------------------------------------------------------- 1 | class ZigzagIterator: 2 | def __init__(self, v1: List[int], v2: List[int]): 3 | i = j = 0 4 | self.v = [] 5 | while i< len(v1) and j < len(v2): 6 | self.v.append(v1[i]) 7 | self.v.append(v2[j]) 8 | i+=1 9 | j+=1 10 | if i < len(v1): 11 | self.v.extend(v1[i:]) 12 | if j < len(v2): 13 | self.v.extend(v2[j:]) 14 | self.p = 0 15 | def next(self) -> int: 16 | val = self.v[self.p] 17 | self.p+=1 18 | return val 19 | def hasNext(self) -> bool: 20 | if self.p >= len(self.v): 21 | return False 22 | return True -------------------------------------------------------------------------------- /Stack Queue/Leetcode 347. Top K Frequent Elements.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 3 | dic = {} 4 | bucket = [0]*(len(nums)+1) 5 | for num in nums: 6 | dic[num] = dic.get(num, 0) +1 7 | 8 | for key, count in dic.items(): 9 | if bucket[count] == 0: 10 | bucket[count] = [] 11 | bucket[count].append(key) 12 | 13 | res = [] 14 | for i in range(len(bucket)-1,-1,-1): 15 | if bucket[i] != 0: 16 | res.extend(bucket[i]) 17 | k -= len(bucket[i]) 18 | if k<=0: 19 | return res -------------------------------------------------------------------------------- /DP/Leetcode 472. Concatenated Words.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]: 3 | if len(words)<=2:return [] 4 | 5 | dic = set(words) 6 | res = [] 7 | for word in words: 8 | if word: 9 | dic.remove(word) 10 | dp = [0]*(len(word)+1) 11 | dp[0] = 1 12 | for j in range(len(word)+1): 13 | for i in range(j): 14 | if dp[i] and word[i:j] in dic: 15 | dp[j] = 1 16 | break 17 | if dp[-1]: res.append(word) 18 | dic.add(word) 19 | return res -------------------------------------------------------------------------------- /DFS BFS/Leetcode 743. Network Delay Time.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int: 3 | graph = collections.defaultdict(dict) 4 | for s,d,w in times: 5 | graph[s][d] = w 6 | 7 | q = [(0,K)] 8 | dist = [float('inf')]*(N+1) 9 | dist[K] = 0 10 | while q: 11 | cost, node = heapq.heappop(q) 12 | for nxt in graph[node]: 13 | newCost = cost + graph[node][nxt] 14 | if dist[nxt] > newCost: 15 | dist[nxt] = newCost 16 | heapq.heappush(q, (newCost, nxt)) 17 | return -1 if max(dist[1:]) == float('inf') else max(dist[1:]) -------------------------------------------------------------------------------- /String/Leetcode 340. Longest Substring with At Most K Distinct Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int: 3 | dic = {} 4 | i = 0 5 | res = 0 6 | for j in range(len(s)): 7 | if s[j] not in dic: 8 | k -= 1 9 | dic[s[j]] = dic.get(s[j], 0) + 1 10 | 11 | if k > -1: 12 | res = max(res, j-i+1) 13 | while k == -1: 14 | if s[i] in dic: 15 | dic[s[i]] -= 1 16 | if dic[s[i]] == 0: 17 | k +=1 18 | del dic[s[i]] 19 | i += 1 20 | return res -------------------------------------------------------------------------------- /Hackerrank/LinkedList/Inserting a Node Into a Sorted Doubly Linked List.py: -------------------------------------------------------------------------------- 1 | def sortedInsert(head, data): 2 | cur = head 3 | pre = None 4 | while cur and cur.data<=data: 5 | pre = cur 6 | cur = cur.next 7 | node = DoublyLinkedListNode(data) 8 | if cur == head: 9 | node.next = cur 10 | cur.prev = node 11 | return node 12 | elif not cur: 13 | pre.next= node 14 | node.prev = pre 15 | return head 16 | else: 17 | node.prev = cur.prev 18 | node.next = cur 19 | cur.prev.next= node 20 | cur.prev = node 21 | return head 22 | 23 | # https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/problem -------------------------------------------------------------------------------- /Non-Leetcode/Print Nodes in Bottom View of Binary Tree.py: -------------------------------------------------------------------------------- 1 | def bottomView(root): 2 | ''' 3 | :param root: root of the binary tree 4 | :return: None, newline is provided by driver code 5 | ''' 6 | # code here 7 | if not root: 8 | return '' 9 | dic = {} 10 | q = collections.deque() 11 | q.append((root,0)) 12 | res = [] 13 | while q: 14 | node, c = q.popleft() 15 | dic[c] = node.data 16 | if node.left: 17 | q.append((node.left, c-1)) 18 | if node.right: 19 | q.append((node.right, c+1)) 20 | for k in sorted(dic.keys()): 21 | res.append(dic[k]) 22 | return res 23 | 24 | # https://www.geeksforgeeks.org/bottom-view-binary-tree/ -------------------------------------------------------------------------------- /Non-Leetcode/Print Nodes in Right View of Binary Tree.py: -------------------------------------------------------------------------------- 1 | def rightView(root): 2 | ''' 3 | :param root: root of given tree. 4 | :return: print the right view of tree, dont print new line 5 | ''' 6 | if not root: 7 | return 8 | res = [] 9 | q = collections.deque() 10 | q.append(root) 11 | while q: 12 | size = len(q) 13 | for i in range(size): 14 | node = q.popleft() 15 | if i == size-1: 16 | res.append(node.data) 17 | 18 | if node.left: 19 | q.append(node.left) 20 | if node.right: 21 | q.append(node.right) 22 | for c in res: 23 | print(c, end=' ') 24 | return res -------------------------------------------------------------------------------- /Stack Queue/Leetcode 378. Kth Smallest Element in a Sorted Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthSmallest(self, matrix: List[List[int]], k: int) -> int: 3 | visited = set() 4 | n = len(matrix) 5 | h = [] 6 | heapq.heappush(h, (matrix[0][0], 0, 0)) 7 | visited.add((0,0)) 8 | while k>0: 9 | res, x, y = heapq.heappop(h) 10 | if x+1 < n and (x+1, y) not in visited: 11 | heapq.heappush(h, (matrix[x+1][y], x+1, y)) 12 | visited.add((x+1, y)) 13 | if y+1 < n and (x, y+1) not in visited: 14 | heapq.heappush(h, (matrix[x][y+1], x, y+1)) 15 | visited.add((x, y+1)) 16 | k -= 1 17 | return res -------------------------------------------------------------------------------- /LinkedList/Leetcode 25. Reverse Nodes in k-Group.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseKGroup(self, head: ListNode, k: int) -> ListNode: 3 | count, cur=0, head 4 | while cur: 5 | count+=1 6 | cur=cur.next 7 | if k<=1 or count2->3->4->5 k= 3 20 | # 1 <- 2 <- 3 | 4 -> 5 21 | # head pre cur 22 | # head.next = cur 23 | #. 5<-4<-1<-2<-3 24 | # reutrn pre -------------------------------------------------------------------------------- /Math/Leetcode 445. Add Two Numbers II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 3 | s1,s2 = [], [] 4 | while l1: 5 | s1.append(l1.val) 6 | l1 = l1.next 7 | while l2: 8 | s2.append(l2.val) 9 | l2 = l2.next 10 | 11 | res = ListNode(0) 12 | sums =0 13 | while s1 or s2: 14 | if s1: 15 | sums += s1.pop() 16 | if s2: 17 | sums += s2.pop() 18 | res.val = sums%10 19 | head = ListNode(sums//10) 20 | head.next = res 21 | res = head 22 | sums //= 10 23 | return res if res.val else res.next -------------------------------------------------------------------------------- /Array/Leetcode 309. Best Time to Buy and Sell Stock with Cooldown.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | if not prices: return 0 4 | n = len(prices) 5 | dp = [[0]*2 for _ in range(n)] 6 | dp[0][0] = 0 7 | dp[0][1] = -prices[0] 8 | for i in range(1,n): 9 | dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]) 10 | dp[i][1] = max(dp[i-1][1], (dp[i-2][0] if i>=2 else 0) - prices[i]) 11 | return dp[-1][0] 12 | 13 | # dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]) 第i天手上沒有股票, 有兩種可能,1,前一天就没股票,2, 第i天把股票卖了 14 | # dp[i][1] = max(dp[i-1][1], (dp[i-2][0] if i>=2 else 0) - prices[i]), 第i天手上有股票,有3种可能,1,前一天就有股票,2,前两天没有股票,第i天买了第一支股票 3,前一天什么也没做,第i天买了第一支股票 -------------------------------------------------------------------------------- /DP/Leetcode 368. Largest Divisible Subset.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestDivisibleSubset(self, nums: List[int]) -> List[int]: 3 | if not nums: 4 | return [] 5 | nums.sort() 6 | dic = collections.defaultdict(list) 7 | dp = [[num] for num in nums] 8 | maxLen = 1 9 | idx = 0 10 | for i in range(len(nums)): 11 | for j in range(i): 12 | if nums[i]%nums[j] == 0 and len(dp[j])+1 > len(dp[i]): 13 | dp[i] = dp[j]+[nums[i]] 14 | if len(dp[i])>maxLen: 15 | maxLen = len(dp[i]) 16 | idx = i 17 | return dp[idx] 18 | 19 | 20 | 21 | # https://www.youtube.com/watch?v=6WRuJzsw1TE -------------------------------------------------------------------------------- /Matrix/Leetcode 36. Valid Sudoku.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValidSudoku(self, board: List[List[str]]) -> bool: 3 | rows = [set() for _ in range(9)] 4 | cols = [set() for _ in range(9)] 5 | boxes = [set() for _ in range(9)] 6 | for i in range(9): 7 | for j in range(9): 8 | if board[i][j] == '.': 9 | continue 10 | num = int(board[i][j]) 11 | boxIdx = (i//3)*3+ j//3 12 | 13 | if num in rows[i] or num in cols[j] or num in boxes[boxIdx]: 14 | return False 15 | rows[i].add(num) 16 | cols[j].add(num) 17 | boxes[boxIdx].add(num) 18 | return True -------------------------------------------------------------------------------- /Matrix/Leetcode 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 | top = left = 0 7 | right = bottom = len(matrix) - 1 8 | while top < bottom: 9 | for i in range(bottom - top): 10 | temp = matrix[top][left+i] 11 | matrix[top][left+i] = matrix[bottom-i][left] 12 | matrix[bottom-i][left] = matrix[bottom][right-i] 13 | matrix[bottom][right-i] = matrix[top+i][right] 14 | matrix[top+i][right] = temp 15 | top += 1 16 | bottom -= 1 17 | left += 1 18 | right -= 1 -------------------------------------------------------------------------------- /Array/Leetcode 57. Insert Interval.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: 3 | res = [] 4 | for interval in intervals: 5 | if interval[1]newInterval[1]: 8 | res.append(newInterval) 9 | newInterval = interval 10 | else: 11 | newInterval = [min(newInterval[0],interval[0]),max(newInterval[1],interval[1])] 12 | res.append(newInterval) 13 | return res 14 | 15 | 16 | # interval 问题判断两个条件,一个是能不能插在当前数的后面,另一个是能不鞥插在当前数的前面, 插入在前面的话要记得更新newinteval 17 | # 其他情况就是merge interval 18 | # 最后把newInterval合并到末尾 -------------------------------------------------------------------------------- /Binary Search/Leetcode 33. Search in Rotated Sorted Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | n = len(nums) 4 | left, right = 0, n-1 5 | while left <= right: 6 | mid = left + (right-left)//2 7 | if nums[mid] == target: 8 | return mid 9 | if nums[mid] > nums[right]: 10 | if nums[left]<=target int: 7 | idx = 0 8 | while len(self.q) and n>0: 9 | buf[idx] = self.q.popleft() 10 | n -= 1 11 | idx += 1 12 | 13 | while n > 0: 14 | buf4 = [None]*4 15 | k = read4(buf4) 16 | if not k: 17 | return idx 18 | if k>n: 19 | self.q.extend(buf4[n:k]) 20 | for i in range(min(k,n)): 21 | buf[idx] = buf4[i] 22 | idx+=1 23 | n-=1 24 | return idx -------------------------------------------------------------------------------- /Tree/Leetcode 314. Binary Tree Vertical Order Traversal.py: -------------------------------------------------------------------------------- 1 | collections 2 | class Solution: 3 | def verticalOrder(self, root: TreeNode) -> List[List[int]]: 4 | if not root : 5 | return 6 | q = collections.deque() 7 | dic = collections.defaultdict(list) 8 | q. append((root, 0)) 9 | while q: 10 | size = len(q) 11 | for _ in range(size): 12 | node, v = q.popleft() 13 | dic[v].append(node.val) 14 | if node.left: 15 | q.append((node.left, v-1)) 16 | if node.right: 17 | q.append((node.right, v+1)) 18 | res = [] 19 | for k in sorted(dic.keys()): 20 | res.append(dic[k]) 21 | return res -------------------------------------------------------------------------------- /Stack Queue/Leetcode 155. Min Stack.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | 3 | def __init__(self): 4 | """ 5 | initialize your data structure here. 6 | """ 7 | self.stack = [] 8 | self.min_stack = [] 9 | 10 | def push(self, x: int) -> None: 11 | self.stack.append(x) 12 | if self.min_stack and x > self.min_stack[-1]: 13 | return 14 | self.min_stack.append(x) 15 | 16 | def pop(self) -> None: 17 | x = self.stack.pop() 18 | if x == self.min_stack[-1]: 19 | self.min_stack.pop() 20 | 21 | def top(self) -> int: 22 | return self.stack[-1] 23 | 24 | def getMin(self) -> int: 25 | if self.min_stack: 26 | return self.min_stack[-1] 27 | return None -------------------------------------------------------------------------------- /DP/Leetcode 10. Regular Expression Matching.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isMatch(self, s: str, p: str) -> bool: 3 | m, n = len(s), len(p) 4 | dp = [[0]*(n+1) for _ in range(m+1)] 5 | dp[0][0] = 1 6 | for j in range(1, n+1): 7 | if p[j-1] == '*': 8 | dp[0][j] = dp[0][j-2] 9 | for i in range(1, m+1): 10 | for j in range(1, n+1): 11 | if s[i-1] == p[j-1] or p[j-1] == '.': 12 | dp[i][j] = dp[i-1][j-1] 13 | elif p[j-1] == '*': 14 | if s[i-1] == p[j-2] or p[j-2] == '.': 15 | dp[i][j] = dp[i][j-2] or dp[i][j-1] or dp[i-1][j] 16 | else: 17 | dp[i][j] = dp[i][j-2] 18 | return dp[m][n] -------------------------------------------------------------------------------- /DFS BFS/Leetcode 364. Nested List Weight Sum II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def depthSumInverse(self, nestedList: List[NestedInteger]) -> int: 3 | dic = {} 4 | level = 0 5 | q = collections.deque() 6 | q.append(nestedList) 7 | res = 0 8 | while q: 9 | size = len(q) 10 | level += 1 11 | sums = 0 12 | for _ in range(size): 13 | nl = q.popleft() 14 | for n in nl: 15 | if n.isInteger(): 16 | sums += n.getInteger() 17 | else: 18 | q.append(n.getList()) 19 | dic[level] = sums 20 | 21 | for k, v in dic.items(): 22 | res += (level+1-k)*v 23 | return res -------------------------------------------------------------------------------- /Stack Queue/Leetcode 394. Decode String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def decodeString(self, s: str) -> str: 3 | stack_mul = [] 4 | stack_char = [] 5 | mul = 0 6 | strr = '' 7 | for char in s: 8 | if char.isdigit(): 9 | mul = 10*mul + int(char) 10 | elif char.isalpha(): 11 | strr += char 12 | elif char == '[': 13 | stack_mul.append(mul) 14 | stack_char.append(strr) 15 | mul = 0 16 | strr = '' 17 | elif char == ']': 18 | m = stack_mul.pop() 19 | strr = stack_char.pop() + strr * m 20 | return strr 21 | 22 | # 遇到'[' 记录之前的strr 和 muli_num 23 | # 遇到']' 将目前的strr 与 之前的mul_num相乘 在加上之前的strr -------------------------------------------------------------------------------- /Tree/Leetcode 226. Invert Binary Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def invertTree(self, root: TreeNode) -> TreeNode: 3 | if not root: return root 4 | root.left, root.right = root.right, root.left 5 | self.invertTree(root.left) 6 | self.invertTree(root.right) 7 | return root 8 | 9 | class Solution: 10 | def invertTree(self, root: TreeNode) -> TreeNode: 11 | if not root: 12 | return None 13 | q = collections.deque() 14 | q.append(root) 15 | while q: 16 | node = q.popleft() 17 | node.left, node.right =node.right, node.left 18 | 19 | if node.left: 20 | q.append(node.left) 21 | if node.right: 22 | q.append(node.right) 23 | return root -------------------------------------------------------------------------------- /String/Leetcode 616. Add Bold Tag in String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addBoldTag(self, s: str, dict: List[str]) -> str: 3 | n = len(s) 4 | bold = [False]*n 5 | end = 0 6 | res = "" 7 | for i in range(n): 8 | for word in dict: 9 | l = len(word) 10 | if i+l<=n and s[i:i+l] == word: 11 | end = max(end, i+l) 12 | bold[i] = end>i 13 | 14 | i = 0 15 | while i < n: 16 | if bold[i] == False: 17 | res += s[i] 18 | i += 1 19 | elif bold[i] == True: 20 | start = i 21 | while i' 24 | return res -------------------------------------------------------------------------------- /Tree/Leetcode 100. Same Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: 3 | if not p and not q:return True 4 | if not p or not q: return False 5 | if p.val == q.val: 6 | return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 7 | return False 8 | 9 | 10 | class Solution: 11 | def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: 12 | 13 | q = collections.deque([(p, q)]) 14 | while q: 15 | n1,n2 = q.popleft() 16 | if not n1 and not n2: continue 17 | if not n1 or not n2: return False 18 | if n1.val != n2.val: return False 19 | q.append((n1.left, n2.left)) 20 | q.append((n1.right, n2.right)) 21 | return True -------------------------------------------------------------------------------- /String/Leetcode 241. Different Ways to Add Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def diffWaysToCompute(self, input: str) -> List[int]: 3 | res = [] 4 | for i in range(len(input)): 5 | if input[i] in '+-*': 6 | left = self.diffWaysToCompute(input[:i]) 7 | right = self.diffWaysToCompute(input[i+1:]) 8 | for l in left: 9 | for r in right: 10 | if input[i] == "+": 11 | res.append(l+r) 12 | elif input[i] == "-": 13 | res.append(l-r) 14 | elif input[i] == "*": 15 | res.append(l*r) 16 | 17 | if not res: 18 | return [int(input)] 19 | return res -------------------------------------------------------------------------------- /Tree/Leetcode 337. House Robber III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, root: TreeNode) -> int: 3 | if not root: 4 | return 0 5 | self.res = 0 6 | dic = {} 7 | self.dfs(root, dic) 8 | return self.res 9 | def dfs(self, node, dic): 10 | if not node: 11 | return 0 12 | if node in dic: 13 | return dic[node] 14 | left = self.dfs(node.left, dic) 15 | right = self.dfs(node.right, dic) 16 | v = node.val 17 | if node.left: 18 | v += self.dfs(node.left.left, dic) + self.dfs(node.left.right, dic) 19 | if node.right: 20 | v += self.dfs(node.right.left, dic) + self.dfs(node.right.right, dic) 21 | dic[node] = self.res = max(v, left+right) 22 | return dic[node] -------------------------------------------------------------------------------- /Math/Leetcode 43. Multiply Strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def multiply(self, num1: str, num2: str) -> str: 3 | m, n = len(num1),len(num2) 4 | offset = 0 5 | res = [0]*(m+n) 6 | for i in range(n-1,-1,-1): 7 | self.mul(int(num2[i]), num1, offset, res) 8 | offset += 1 9 | result = 0 10 | for i in range(len(res)): 11 | result = result*10 + res[i] 12 | return str(result) 13 | 14 | def mul(self, mul, nums, offset, res): 15 | carry = 0 16 | j = len(res)-1 17 | for i in range(len(nums)-1,-1,-1): 18 | s = mul * int(nums[i]) + carry + res[j-offset] 19 | s, carry = s%10, s//10 20 | res[j-offset] = s 21 | j -= 1 22 | if carry>0: 23 | res[j-offset] = carry -------------------------------------------------------------------------------- /Design/Leetcode 170. Two Sum III - Data structure design.py: -------------------------------------------------------------------------------- 1 | class TwoSum: 2 | 3 | def __init__(self): 4 | """ 5 | Initialize your data structure here. 6 | """ 7 | self.dic = {} 8 | self.nums = [] 9 | 10 | def add(self, number: int) -> None: 11 | """ 12 | Add the number to an internal data structure.. 13 | """ 14 | self.dic[number] = len(self.nums) 15 | self.nums.append(number) 16 | 17 | def find(self, value: int) -> bool: 18 | """ 19 | Find if there exists any pair of numbers which sum is equal to the value. 20 | """ 21 | for i in range(len(self.nums)): 22 | diff = value - self.nums[i] 23 | if diff in self.dic and self.dic[diff] != i: 24 | return True 25 | return False -------------------------------------------------------------------------------- /Stack Queue/Leetcode 973. K Closest Points to Origin.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | class Solution: 3 | def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]: 4 | dis = [] 5 | p_arr = [] 6 | for i in range(len(points)): 7 | point = points[i] 8 | d=(point[0]**2 + point[1]**2)**0.5 9 | p_arr.append((d,i)) 10 | 11 | h = [] 12 | for i in range(len(p_arr)): 13 | if ih[0][0]: 17 | heapq.heappop(h) 18 | heapq.heappush(h, (-p_arr[i][0],p_arr[i][1])) 19 | res = [] 20 | while h: 21 | res.append(points[heapq.heappop(h)[1]]) 22 | return res -------------------------------------------------------------------------------- /Matrix/Leetcode 1102. Path With Maximum Minimum Value.py: -------------------------------------------------------------------------------- 1 | from heapq import * 2 | class Solution: 3 | def maximumMinimumPath(self, A: List[List[int]]) -> int: 4 | m, n = len(A),len(A[0]) 5 | visited = [[0]*n for _ in range(m)] 6 | q=[] 7 | heappush(q,(-A[0][0],0,0)) 8 | visited[0][0] = 1 9 | dirs = [(0, 1), (0, -1), (-1, 0), (1, 0)] 10 | res = float('inf') 11 | while q: 12 | v,x,y = heappop(q) 13 | res = min(res,-v) 14 | if x == m-1 and y == n-1: 15 | return res 16 | for xd,yd in dirs: 17 | nx = x + xd 18 | ny = y + yd 19 | if 0<=nx int: 3 | stack = [] 4 | for token in tokens: 5 | if token in '+-*/': 6 | right = int(stack.pop()) 7 | left = int(stack.pop()) 8 | s = 0 9 | if token == '+': 10 | s = right + left 11 | if token == '-': 12 | s = left - right 13 | if token == '*': 14 | s = right * left 15 | if token == '/': 16 | s = math.trunc(left / right) 17 | # s = int(left / right) 18 | stack.append(str(s)) 19 | else: 20 | stack.append(token) 21 | return int(stack[-1]) -------------------------------------------------------------------------------- /String/Leetcode 5. Longest Palindromic Substring.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestPalindrome(self, s: str) -> str: 3 | n = len(s) 4 | dp = [[0]* n for _ in range(n)] 5 | max_len = 0 6 | res = '' 7 | for i in range(len(s)): 8 | dp[i][i] = 1 9 | max_len = 1 10 | res = s[i] 11 | for i in range(len(s)-1): 12 | if s[i] == s[i+1]: 13 | dp[i][i+1] = 1 14 | max_len = 2 15 | res = s[i:i+2] 16 | for j in range(len(s)): 17 | for i in range(j): 18 | if s[i] == s[j] and dp[i+1][j-1]: 19 | dp[i][j] = 1 20 | if j-i+1 > max_len: 21 | max_len = j-i+1 22 | res = s[i:j+1] 23 | return res -------------------------------------------------------------------------------- /String/Leetcode 115. Distinct Subsequences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numDistinct(self, s: str, t: str) -> int: 3 | m, n = len(s), len(t) 4 | dp = [[0]*(n+1) for _ in range(m+1)] #dp[m+1][n+1] means s[:m+2] t[:n+2] 5 | for i in range(m+1): 6 | dp[i][0] = 1 7 | for i in range(1,m+1): 8 | for j in range(1,n+1): 9 | if s[i-1] == t[j-1]: 10 | dp[i][j] = dp[i-1][j] + dp[i-1][j-1] 11 | else: 12 | dp[i][j] = dp[i-1][j] #drop s[i] 13 | return dp[-1][-1] 14 | 15 | 16 | # 0 r a b b i t 17 | # 0 1 0 0 0 0 0 0 18 | # r 1 1 0 0 0 0 0 19 | # a 1 1 1 0 0 0 0 20 | # b 1 1 1 1 0 0 0 21 | # b 1 1 1 2 1 0 0 22 | # b 1 1 1 3 3 0 0 23 | # i 1 1 1 3 3 3 0 24 | # t 1 1 1 3 3 3 3 -------------------------------------------------------------------------------- /Array/Leetcode 1239. Maximum Length of a Concatenated String with Unique Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxLength(self, arr: List[str]) -> int: 3 | word_sets = [] 4 | for i in range(len(arr)): 5 | if len(arr[i])>len(set(arr[i])): 6 | continue 7 | s = set() 8 | for char in arr[i]: 9 | s.add(char) 10 | word_sets.append(s) 11 | 12 | self.res = 0 13 | self.helper(word_sets, 0, []) 14 | return self.res 15 | 16 | def helper(self, word_sets, idx, tempList): 17 | if tempList: 18 | self.res = max(self.res, len(tempList)) 19 | for i in range(idx, len(word_sets)): 20 | if not set(tempList) & word_sets[i]: 21 | self.helper(word_sets, i+1, tempList+list(word_sets[i])) -------------------------------------------------------------------------------- /Math/Leetcode 50. Pow(x, n).py: -------------------------------------------------------------------------------- 1 | class Solution1: 2 | def myPow(self, x: float, n: int) -> float: 3 | if n<0: 4 | x = 1/x 5 | n = abs(n) 6 | res = 1 7 | while n >0: 8 | if n%2 == 1: 9 | res *= x 10 | x *=x 11 | n //= 2 12 | return res 13 | 14 | 15 | # 2^8 = 4^4 16 | # 2^9 = 2*4^4 17 | 18 | #Recursive 19 | class Solution2: 20 | def myPow(self, x: float, n: int) -> float: 21 | if n<0: 22 | return self.helper(1/x,-n) 23 | return self.helper(x,n) 24 | 25 | def helper(self, x,n): 26 | if n == 0: 27 | return 1 28 | half = self.helper(x, n//2) 29 | if n % 2 == 1: 30 | return x * half * half 31 | else: 32 | return half * half -------------------------------------------------------------------------------- /Non-Leetcode/Integer to Chinese.py: -------------------------------------------------------------------------------- 1 | lessThan10 = ['零', '一', '贰', '叁', '肆', '伍', '六', '七', '八' ,'九'] 2 | lessThan1000 = ['','拾','佰','千'] 3 | thousands = ["", "万", "亿", "兆"] 4 | def numberToWords(num: int) -> str: 5 | 6 | if num == 0 : 7 | return "零" 8 | res = '' 9 | i = 0 10 | while num>0: 11 | if num%10000 != 0: 12 | res = helper(num%10000) + thousands[i] + res 13 | num //= 10000 14 | i += 1 15 | print(res) 16 | return res.strip() 17 | 18 | def helper(num): 19 | res = [] 20 | i = 0 21 | while num > 0: 22 | if num % 10 != 0: 23 | res.append(lessThan10[num%10]+lessThan1000[i]) 24 | else: 25 | if i != 0 and res[-1] != "零": 26 | res.append('零') 27 | num //=10 28 | i+=1 29 | return "".join(res[::-1]) 30 | 31 | numberToWords(10051002) -------------------------------------------------------------------------------- /Backtracking/Leetcode 51. N-Queens.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def solveNQueens(self, n: int) -> List[List[str]]: 3 | res = [] 4 | self.bt(n, 0, [], res) 5 | return res 6 | 7 | def bt(self, n, row, tempList, res): 8 | if row == n: 9 | s = '' 10 | r = [] 11 | for x in tempList: 12 | s = "."*x + 'Q' + "."*(n-x-1) 13 | r.append(s) 14 | res.append(r) 15 | return 16 | for j in range(n): 17 | if self.check(row,j,tempList): 18 | self.bt(n, row+1, tempList+[j], res) 19 | 20 | def check(self, row, col, tempList): 21 | for i in range(len(tempList)): 22 | if abs(i-row) == abs(tempList[i] - col) or col == tempList[i]: 23 | return False 24 | return True -------------------------------------------------------------------------------- /Binary Search/Leetcode 81. Search in Rotated Sorted Array II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | n = len(nums) 4 | left, right = 0, n-1 5 | while left <= right: 6 | mid = left + (right-left)//2 7 | if nums[mid] == target: 8 | return True 9 | if nums[mid] > nums[right]: 10 | if nums[left]<=target int: 3 | if dividend == -2**31: 4 | if divisor == -1: 5 | return 2**31-1 6 | if divisor == 1: 7 | return dividend 8 | if dividend == 2**31-1 and divisor == 1: 9 | return dividend 10 | 11 | sign = 1 12 | if dividend < 0: 13 | sign = -sign 14 | dividend = -dividend 15 | if divisor < 0: 16 | sign = -sign 17 | divisor = -divisor 18 | res = 0 19 | while dividend - divisor>=0: 20 | shift = 0 21 | while dividend>=(divisor< List[int]: 3 | res = [] 4 | dic_p = {} 5 | for char in p: 6 | dic_p[char] = dic_p.get(char,0)+1 7 | 8 | dic_s = {} 9 | i = 0 10 | for j in range(len(s)): 11 | dic_s[s[j]] = dic_s.get(s[j],0)+1 12 | 13 | if j>=len(p): 14 | dic_s[s[i]] -= 1 15 | i+=1 16 | if self.equal(dic_s, dic_p): 17 | res.append(i) 18 | return res 19 | 20 | def equal(self, a,b): 21 | for k in a.keys(): 22 | if a.get(k,0)!=b.get(k,0): 23 | return False 24 | for k in b.keys(): 25 | if a.get(k,0)!=b.get(k,0): 26 | return False 27 | return True -------------------------------------------------------------------------------- /Tree/Leetcode 104. Maximum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxDepth(self, root: TreeNode) -> int: 3 | if not root: 4 | return 0 5 | res = 1 6 | stack = [] 7 | stack.append((root, 1)) 8 | while stack: 9 | node, depth = stack.pop() 10 | if not node.left and not node.right: 11 | res = max(res, depth) 12 | if node.left: 13 | stack.append((node.left, depth+1)) 14 | if node.right: 15 | stack.append((node.right, depth+1)) 16 | return res 17 | 18 | class Solution: 19 | def maxDepth(self, root: TreeNode) -> int: 20 | 21 | if not root: 22 | return 0 23 | left = self.maxDepth(root.left) 24 | right = self.maxDepth(root.right) 25 | return max(left,right)+1 26 | -------------------------------------------------------------------------------- /Backtracking/Leetcode 351. Android Unlock Patterns.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfPatterns(self, m: int, n: int) -> int: 3 | self.m, self.n = m, n 4 | res = [] 5 | self.bt(1, [], res) 6 | return len(res) 7 | 8 | def bt(self, start, tempList, res): 9 | checkPairs = [(1,3),(3,1),(1,7),(7,1),(1,9),(9,1),(2,8),(8,2),(3,7),(7,3),(3,9),(9,3),(4,6),(6,4),(7,9),(9,7)] 10 | if self.m<=len(tempList)<=self.n: 11 | res.append(tempList) 12 | for i in range(1, 10): 13 | if i in tempList: 14 | continue 15 | if len(tempList)==self.n: 16 | break 17 | if len(tempList)>=1: 18 | if (i,tempList[-1]) in checkPairs and (i + tempList[-1]) // 2 not in tempList: 19 | continue 20 | self.bt(i+1, tempList+[i],res) 21 | -------------------------------------------------------------------------------- /Non-Leetcode/K Decimal Addition.py: -------------------------------------------------------------------------------- 1 | # Example1 2 | 3 | # Input: k = 3, a = "12", b = "1" 4 | # Output: 20 5 | # Explanation: 6 | # 12 + 1 = 20 in 3 bases. 7 | # Example2 8 | 9 | # Input: k = 10, a = "12", b = "1" 10 | # Output: 13 11 | # Explanation: 12 | # 12 + 1 = 13 in 10 bases. 13 | 14 | 15 | # 先转成10进制,再转回k进制 16 | class Solution: 17 | def addition(self, k, a, b): 18 | # Write your code here 19 | a = self.to_ten(a,k) 20 | b = self.to_ten(b,k) 21 | sums = a+b 22 | res = '' 23 | while sums > 0: 24 | sums, n = divmod(sums, k) 25 | res = str(n)+res 26 | return res 27 | 28 | 29 | def to_ten(self, a, k): 30 | r = 0 31 | total = 0 32 | for i in range(len(a)-1,-1,-1): 33 | total += int(a[i])*(k**r) 34 | r+=1 35 | return total -------------------------------------------------------------------------------- /Random/Leetcode 381. Insert Delete GetRandom O(1) - Duplicates allowed.py: -------------------------------------------------------------------------------- 1 | class RandomizedCollection: 2 | 3 | def __init__(self): 4 | self.dic = collections.defaultdict(set) 5 | self.nums = [] 6 | 7 | def insert(self, val: int) -> bool: 8 | self.nums.append(val) 9 | self.dic[val].add(len(self.nums)-1) 10 | return len(self.dic[val]) == 1 11 | 12 | 13 | def remove(self, val: int) -> bool: 14 | if not self.dic[val]: 15 | return False 16 | idx_to_remove = self.dic[val].pop() 17 | last = self.nums[-1] 18 | self.nums[idx_to_remove] = last 19 | self.dic[last].add(idx_to_remove) 20 | self.dic[last].remove(len(self.nums)-1) 21 | self.nums.pop() 22 | return True 23 | 24 | 25 | def getRandom(self) -> int: 26 | return random.choice(self.nums) -------------------------------------------------------------------------------- /Stack Queue/Leetcode 385. Mini Parser.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def deserialize(self, s: str) -> NestedInteger: 3 | if not s : return NestedInteger() 4 | if s[0] != '[' : return NestedInteger(int(s)) 5 | stack = [] 6 | start = 0 7 | for i in range(len(s)): 8 | if s[i] == '[': 9 | stack.append(NestedInteger()) 10 | start = i+1 11 | elif s[i] in ',]': 12 | if s[start:i].lstrip('-').isdigit(): #judge if it's negative number 13 | num = int(s[start:i]) 14 | stack[-1].add(NestedInteger(num)) 15 | if s[i] == ']': 16 | ni = stack.pop() 17 | if stack: 18 | stack[-1].add(ni) 19 | else: 20 | return ni 21 | start = i+1 -------------------------------------------------------------------------------- /Hackerrank/String/Character Frequencies.py: -------------------------------------------------------------------------------- 1 | #有没有可能删除一个字符,使所有字符出现的次数一样 2 | 3 | # aabbcd -> NO 4 | # aabbccddeefghi -> NO 5 | # aabbc -> YES 删除c 6 | # abcdd -> YES 删除d 7 | 8 | import collections 9 | # Complete the isValid function below. 10 | def isValid(s): 11 | if not s: 12 | return "YES" 13 | dic = {} 14 | for c in s: 15 | dic[c] = dic.get(c,0)+1 16 | 17 | freq = collections.defaultdict(list) 18 | for k,v in dic.items(): 19 | freq[v].append(k) 20 | print(freq) 21 | if len(freq.keys())>2: 22 | return "NO" 23 | if len(freq.keys()) == 1: 24 | return "YES" 25 | 26 | keys = list(freq.keys()) 27 | if (abs(keys[0] - keys[1]) == 1 and (len(freq[keys[0]])==1 or len(freq[keys[1]]) == 1)) or (keys[0] == 1 and len(freq[keys[0]])==1) or (keys[1] == 1 and len(freq[keys[1]])==1): 28 | return "YES" 29 | return 'NO' -------------------------------------------------------------------------------- /Stack Queue/Leetcode 621. Task Scheduler.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def leastInterval(self, tasks: List[str], n: int) -> int: 3 | dic = {} 4 | for t in tasks: 5 | dic[t] = dic.get(t, 0) +1 6 | heap = [] 7 | for count in dic.values(): 8 | heapq.heappush(heap, -count) 9 | res = 0 10 | 11 | while heap: 12 | temp = [] 13 | i =0 14 | while i<=n: 15 | res += 1 16 | if heap: 17 | cnt = heapq.heappop(heap) 18 | if cnt != -1: 19 | temp.append(cnt+1) 20 | if not heap and not temp: 21 | break # finish all tasks 22 | else: 23 | i+=1 24 | for t in temp: 25 | heapq.heappush(heap, t) 26 | return res -------------------------------------------------------------------------------- /Tree/Leetcode 987. Vertical Order Traversal of a Binary Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def verticalTraversal(self, root: TreeNode) -> List[List[int]]: 3 | q = collections.deque() 4 | dic = collections.defaultdict(list) 5 | q.append((root,0)) 6 | while q: 7 | size = len(q) 8 | temp = collections.defaultdict(list) 9 | for _ in range(size): 10 | node, idx = q.popleft() 11 | temp[idx].append(node.val) 12 | if node.left: 13 | q.append((node.left, idx-1)) 14 | if node.right: 15 | q.append((node.right, idx+1)) 16 | for key in temp: 17 | dic[key].extend(sorted(temp[key])) 18 | 19 | res = [] 20 | for k in sorted(dic.keys()): 21 | res.append(dic[k]) 22 | return res -------------------------------------------------------------------------------- /Array/Leetcode 123. Best Time to Buy and Sell Stock III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | n = len(prices) 4 | if n <=1: return 0 5 | min_buy = prices[0] 6 | dp_left, dp_right = [0]*n, [0]*n 7 | for i in range(1,n): 8 | min_buy = min(min_buy, prices[i]) 9 | dp_left[i] = max(dp_left[i-1], prices[i] - min_buy) 10 | 11 | max_sell = prices[-1] 12 | for i in range(n-2, -1, -1): 13 | max_sell = max(max_sell, prices[i]) 14 | dp_right[i] = max(max_sell - prices[i], dp_right[i-1]) 15 | 16 | res = 0 17 | for x, y in zip(dp_left,dp_right): 18 | res = max(res, x+y) 19 | return res 20 | 21 | # 求极值,考虑DP 22 | # 分别从左(1,n-1) 右(n-2,0)计算最大profit 23 | # 比如 [a,b,c,d,e,f,g,h,i], 以e为分割点,e之前最大profit看dp_left。 e之后最大profit看dp_right. -------------------------------------------------------------------------------- /LinkedList/Leetcode 160. Intersection of Two Linked Lists.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: 3 | curA, curB = headA, headB 4 | countA, countB = 0, 0 5 | while curA: 6 | curA = curA.next 7 | countA+=1 8 | while curB: 9 | curB = curB.next 10 | countB+=1 11 | 12 | curA, curB = headA, headB 13 | diff = abs(countA-countB) 14 | if countA > countB: 15 | for _ in range(diff): 16 | curA = curA.next 17 | else: 18 | for _ in range(diff): 19 | curB = curB.next 20 | while curA and curB: 21 | if curA == curB: 22 | return curA 23 | else: 24 | curA = curA.next 25 | curB = curB.next 26 | return None -------------------------------------------------------------------------------- /String/Leetcode 68. Text Justification.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fullJustify(self, words: List[str], maxWidth: int) -> List[str]: 3 | count, cur_words = 0, [] 4 | res = [] 5 | for word in words: 6 | if count+ len(word) + len(cur_words) > maxWidth: 7 | spaces = maxWidth - count 8 | if len(cur_words) == 1: 9 | cur_words[0] += ' '*spaces 10 | else: 11 | for i in range(spaces): 12 | cur_words[i % (len(cur_words)-1)] += ' ' 13 | res.append("".join(cur_words)) 14 | count, cur_words = 0, [] 15 | count+=len(word) 16 | cur_words.append(word) 17 | 18 | #last row 19 | spaces = maxWidth - count - (len(cur_words)-1) 20 | res.append(" ".join(cur_words)+" "*spaces) 21 | return res -------------------------------------------------------------------------------- /String/Leetcode 767. Reorganize String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reorganizeString(self, S: str) -> str: 3 | dic = {} 4 | for s in S: 5 | dic[s] = dic.get(s,0)+1 6 | 7 | h = [] 8 | for k,v in dic.items(): 9 | if v>(len(S)+1)//2: 10 | return '' 11 | heapq.heappush(h, (-v, k)) 12 | res = "" 13 | while len(h)>1: 14 | count, char = heapq.heappop(h) 15 | if res and char == res[-1]: 16 | c, ch = count, char 17 | count, char = heapq.heappop(h) 18 | heapq.heappush(h, (c, ch)) 19 | res += char 20 | if count != -1: 21 | count += 1 22 | heapq.heappush(h, (count, char)) 23 | while h: 24 | count, char = heapq.heappop(h) 25 | res += char 26 | return res -------------------------------------------------------------------------------- /Tree/Leetcode 103. Binary Tree Zigzag Level Order Traversal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: 3 | if not root: 4 | return [] 5 | res = [] 6 | q = collections.deque() 7 | q.append(root) 8 | reverse = False 9 | while q: 10 | temp = [] 11 | size = len(q) 12 | for _ in range(size): 13 | node = q.popleft() 14 | if node: 15 | temp.append(node.val) 16 | if node.left: 17 | q.append(node.left) 18 | if node.right: 19 | q.append(node.right) 20 | if reverse: 21 | res.append(temp[::-1]) 22 | else: 23 | res.append(temp) 24 | reverse = not reverse 25 | return res 26 | -------------------------------------------------------------------------------- /Random/Leetcode 380. Insert Delete GetRandom O(1).py: -------------------------------------------------------------------------------- 1 | class RandomizedSet: 2 | 3 | def __init__(self): 4 | self.dic = {} 5 | self.nums = [] 6 | 7 | 8 | def insert(self, val: int) -> bool: 9 | if val not in self.nums: 10 | self.dic[val] = len(self.nums) 11 | self.nums.append(val) 12 | return True 13 | return False 14 | 15 | 16 | def remove(self, val: int) -> bool: 17 | if val in self.nums: 18 | last_num, del_idx =self.nums[-1], self.dic[val] 19 | self.nums[del_idx], self.nums[-1] = self.nums[-1], self.nums[del_idx] 20 | self.nums.pop() 21 | self.dic[last_num] = del_idx 22 | del self.dic[val] 23 | return True 24 | return False 25 | 26 | 27 | def getRandom(self) -> int: 28 | return random.sample(self.nums,1)[0] -------------------------------------------------------------------------------- /Math/Leetcode 15. 3Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSum(self, nums: List[int]) -> List[List[int]]: 3 | nums.sort() 4 | res = [] 5 | for k in range(len(nums)-2): 6 | if nums[k] > 0: break 7 | if k>0 and nums[k] == nums[k-1]: continue 8 | target = -nums[k] 9 | i,j = k+1, len(nums)-1 10 | while itarget: 14 | j-=1 15 | elif nums[i]+nums[j] == target: 16 | res.append([nums[k],nums[i],nums[j]]) 17 | while i int: 3 | m, n = len(grid), len(grid[0]) 4 | res = 0 5 | visited = set() 6 | for i in range(m): 7 | for j in range(n): 8 | if grid[i][j]!=0: 9 | x = self.helper(grid, i, j, visited) 10 | res = max(res, x) 11 | return res 12 | 13 | 14 | def helper(self, grid, x, y, visited): 15 | m, n = len(grid), len(grid[0]) 16 | res = 0 17 | if 0<=x int: 3 | group = [] 4 | dic = {} 5 | i = 0 6 | while i < len(text): 7 | char = text[i] 8 | count = 0 9 | while i< len(text) and text[i] == char: 10 | count += 1 11 | i+=1 12 | group.append((char,count)) 13 | dic[char] = dic.get(char, 0)+count 14 | 15 | res = 0 16 | for i in range(len(group)): 17 | (k, count) = group[i] 18 | res = max(res, min(count+1, dic[k])) 19 | for i in range(1, len(group)-1): 20 | if group[i-1][0] == group[i+1][0] and group[i][1] == 1: 21 | count = min(group[i-1][1] + group[i+1][1] +1, dic[group[i-1][0]]) 22 | res = max(res, count) 23 | return res -------------------------------------------------------------------------------- /Toplogical Sort/Leetcode 210. Course Schedule II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: 3 | child = collections.defaultdict(set) 4 | parent = collections.defaultdict(int) 5 | for c, p in prerequisites: 6 | child[p].add(c) 7 | parent[c] +=1 8 | 9 | q = collections.deque() 10 | for i in range(numCourses): 11 | if parent[i] == 0: 12 | q.append(i) 13 | del parent[i] 14 | 15 | res = [] 16 | while q: 17 | course = q.popleft() 18 | res.append(course) 19 | for ch in child[course]: 20 | parent[ch] -= 1 21 | if parent[ch] == 0: 22 | q.append(ch) 23 | del parent[ch] 24 | return res if len(res) == numCourses else [] -------------------------------------------------------------------------------- /Graph/Leetcode 1152. Analyze User Website Visit Pattern.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | class Solution: 3 | def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]: 4 | data = [[username[i], timestamp[i], website[i]] for i in range(len(username))] 5 | data.sort() 6 | dic = defaultdict(list) 7 | for u, t, w in data: 8 | dic[u].append(w) 9 | seq = defaultdict(set) 10 | for u, w in dic.items(): 11 | if len(w)>=3: 12 | for i in range(len(w)-2): 13 | for j in range(i+1,len(w)-1): 14 | for k in range(j+1,len(w)): 15 | webs = (w[i],w[j],w[k]) 16 | seq[webs].add(u) 17 | 18 | return sorted(seq.items(),key=lambda x:(-len(x[1]),x[0]))[0][0] 19 | 20 | -------------------------------------------------------------------------------- /Stack Queue/Leetcode 373. Find K Pairs with Smallest Sums.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: 3 | if not nums1 or not nums2: 4 | return [] 5 | heap = [] 6 | heapq.heappush(heap, (nums1[0]+nums2[0], 0, 0)) 7 | res = [] 8 | visited = set() 9 | visited.add((0,0)) 10 | while k>0 and heap: 11 | v, x, y = heapq.heappop(heap) 12 | res.append((nums1[x],nums2[y])) 13 | k-= 1 14 | 15 | if x+1 bool: 3 | m, n = len(maze), len(maze[0]) 4 | visited = set() 5 | stack = [] 6 | stack.append(start) 7 | visited.add((start[0], start[1])) 8 | dirs = [(0,1),(0,-1),(-1,0),(1,0)] 9 | while stack: 10 | x, y = stack.pop() 11 | for dx, dy in dirs: 12 | nx, ny = x, y 13 | while 0<=nx float: 4 | l1,l2 = len(nums1),len(nums2) 5 | 6 | l = l1+l2 7 | n = l//2 8 | heap = [] 9 | i = j = 0 10 | if nums1: 11 | heapq.heappush(heap, nums1[i]) 12 | if nums2: 13 | heapq.heappush(heap, nums2[j]) 14 | while n>0: 15 | x1 = heapq.heappop(heap) 16 | if nums1 and x1 == nums1[i] and i int: 3 | res = set() 4 | self.bt(n, 0, [], res) 5 | return len(res) 6 | 7 | def bt(self, n, row, tempList, res): 8 | if row>n: 9 | return 10 | if row==n: 11 | strr = '' 12 | for col in tempList: 13 | strr+=str(col) 14 | res.add(strr) 15 | for col in range(n): 16 | if self.check(col, row, tempList): 17 | self.bt(n, row+1, tempList+[col],res) 18 | 19 | def check(self, col, row, tempList): 20 | for r in range(row): 21 | if tempList[r] == col or row-r == abs(tempList[r]-col): 22 | return False 23 | return True 24 | 25 | # Ex., 26 | # [".Q..", 27 | # "...Q", 28 | # "Q...", 29 | # "..Q."], 30 | 31 | # strr = "1403" -------------------------------------------------------------------------------- /Tree/Leetcode 235. Lowest Common Ancestor of a Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 3 | if not root: return None 4 | if root.val > max(p.val, q.val): 5 | return self.lowestCommonAncestor(root.left, p, q) 6 | if root.val < min(p.val, q.val): 7 | return self.lowestCommonAncestor(root.right, p, q) 8 | return root 9 | 10 | 11 | class Solution: 12 | def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 13 | if not root: 14 | return None 15 | 16 | node = root 17 | while node: 18 | if max(p.val, q.val) node.val: 21 | node = node.right 22 | else: 23 | return node -------------------------------------------------------------------------------- /Tree/Leetcode 549. Binary Tree Longest Consecutive Sequence II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestConsecutive(self, root: TreeNode) -> int: 3 | if not root: 4 | return 0 5 | 6 | p1 = self.helper(root.left, root.val, -1)+self.helper(root.right, root.val, 1) + 1 7 | p2 = self.helper(root.left, root.val, 1)+self.helper(root.right, root.val, -1) + 1 8 | 9 | throughRoot = max(p1,p2) 10 | notThroughToor = max(self.longestConsecutive(root.left), self.longestConsecutive(root.right)) 11 | return max(throughRoot, notThroughToor) 12 | 13 | def helper(self, root, pre, diff): 14 | if not root: 15 | return 0 16 | if root.val == pre+diff: 17 | left = self.helper(root.left, root.val, diff) 18 | right = self.helper(root.right, root.val, diff) 19 | return max(left,right)+1 20 | else: 21 | return 0 -------------------------------------------------------------------------------- /Graph/Leetcode 310. Minimum Height Trees.py: -------------------------------------------------------------------------------- 1 | import collections 2 | class Solution: 3 | def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: 4 | if n == 1: 5 | return [0] 6 | dic = collections.defaultdict(set) 7 | for x,y in edges: 8 | dic[x].add(y) 9 | dic[y].add(x) 10 | 11 | q = collections.deque() 12 | res = [] 13 | for i in range(n): 14 | if len(dic[i]) == 1: #leaf node 15 | q.append(i) 16 | while n > 2: 17 | l = len(q) 18 | n -= l 19 | for i in range(l): 20 | node = q.popleft() 21 | for nxt in dic[node]: 22 | dic[nxt].remove(node) 23 | if len(dic[nxt]) == 1: 24 | q.append(nxt) 25 | while q: 26 | res.append(q.popleft()) 27 | return res -------------------------------------------------------------------------------- /Matrix/Leetcode 59. Spiral Matrix II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateMatrix(self, n: int) -> List[List[int]]: 3 | res = [[0]*n for _ in range(n)] 4 | top = left = 0 5 | bottom = right = n-1 6 | x = 1 7 | while top int: 4 | m = len(mat) 5 | res = self.helper(mat, k) 6 | return res[k-1] 7 | 8 | def helper(self, mat, k): 9 | if len(mat) == 1: 10 | return mat[0] 11 | mid = len(mat)//2 12 | l1 = self.helper(mat[:mid], k) 13 | l2 = self.helper(mat[mid:], k) 14 | return self.merge(l1, l2, k) 15 | 16 | def merge(self, l1, l2, k): 17 | res = [] 18 | if not l1 or not l2 or not k: 19 | return res 20 | heap = [] 21 | for i in l1: 22 | for j in l2: 23 | heapq.heappush(heap, i+j) 24 | while heap and k>0: 25 | res += [heapq.heappop(heap)] 26 | k-=1 27 | return res 28 | 29 | # Divide and Conquer -------------------------------------------------------------------------------- /String/Leetcode 336. Palindrome Pairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def palindromePairs(self, words: List[str]) -> List[List[int]]: 3 | words = {word: i for i, word in enumerate(words)} 4 | res = [] 5 | for word, idx in words.items(): 6 | for i in range(len(word)+1): 7 | pre = word[:i] 8 | suf = word[i:] 9 | if self.isPali(pre): 10 | if suf[::-1] in words: 11 | if idx != words[suf[::-1]]: 12 | res.append([words[suf[::-1]], idx]) 13 | if i !=len(word): 14 | if self.isPali(suf): 15 | if pre[::-1] in words: 16 | if idx != words[pre[::-1]]: 17 | res.append([idx, words[pre[::-1]]]) 18 | 19 | return res 20 | 21 | def isPali(self, strr): 22 | return strr[::-1] == strr -------------------------------------------------------------------------------- /Array/Leetcode 352. Data Stream as Disjoint Intervals.py: -------------------------------------------------------------------------------- 1 | class SummaryRanges: 2 | 3 | def __init__(self): 4 | """ 5 | Initialize your data structure here. 6 | """ 7 | self.intervals = [] 8 | 9 | def addNum(self, val: int) -> None: 10 | res = [] 11 | newInterval = [val, val] 12 | for i in range(len(self.intervals)): 13 | interval = self.intervals[i] 14 | if newInterval[1] < interval[0]-1: 15 | res.append(newInterval) 16 | newInterval = interval 17 | elif newInterval[0] > interval[1]+1: 18 | res.append(interval) 19 | else: 20 | newInterval = [min(newInterval[0], interval[0]),max(newInterval[1],interval[1])] 21 | res.append(newInterval) 22 | self.intervals = res 23 | 24 | def getIntervals(self) -> List[List[int]]: 25 | return self.intervals 26 | 27 | # 与Leetcode57 基本一样 -------------------------------------------------------------------------------- /Toplogical Sort/Leetcode 207. Course Schedule.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: 3 | child = collections.defaultdict(set) 4 | parent = collections.defaultdict(int) 5 | for c, p in prerequisites: 6 | child[p].add(c) 7 | parent[c] = parent.get(c,0)+1 8 | 9 | q = collections.deque() 10 | for i in range(numCourses): 11 | if parent[i] == 0: 12 | q.append(i) 13 | del parent[i] 14 | if not q: 15 | return False 16 | 17 | res = [] 18 | while q: 19 | course = q.popleft() 20 | res.append(course) 21 | for ch in child[course]: 22 | parent[ch] -=1 23 | if parent[ch] == 0: 24 | q.append(ch) 25 | del parent[ch] 26 | return len(res) == numCourses -------------------------------------------------------------------------------- /LinkedList/Leetcode 148. Sort List.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortList(self, head: ListNode) -> ListNode: 3 | if not head or not head.next: return head 4 | pre = slow = fast = head 5 | while fast and fast.next: 6 | pre = slow 7 | slow = slow.next 8 | fast = fast.next.next 9 | pre.next = None 10 | firstHalf = self.sortList(head) 11 | secondHalf = self.sortList(slow) 12 | return self.sort(firstHalf,secondHalf) 13 | 14 | def sort(self, left, right): 15 | dummy = ListNode(0) 16 | cur = dummy 17 | while left and right: 18 | if left.val <= right.val: 19 | cur.next = left 20 | left = left.next 21 | elif left.val > right.val: 22 | cur.next = right 23 | right = right.next 24 | cur = cur.next 25 | cur.next = left or right 26 | return dummy.next -------------------------------------------------------------------------------- /Graph/Leetcode 399. Evaluate Division.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: 3 | dic = collections.defaultdict(dict) 4 | for (x,y),r in zip(equations,values): 5 | dic[x][y] = r 6 | dic[y][x] = 1/r 7 | 8 | res = [] 9 | for m, n in queries: 10 | if m not in dic: 11 | res.append(-1) 12 | else: 13 | res.append(self.dfs(m, n, dic, set())) 14 | return res 15 | 16 | def dfs(self, m, n, dic, visited): 17 | if m not in dic: 18 | return -1 19 | if m == n: 20 | return 1 21 | visited.add(m) 22 | for nxt in dic[m]: 23 | if nxt not in visited: 24 | r = self.dfs(nxt, n, dic, visited) 25 | if r != -1: 26 | return dic[m][nxt]*r 27 | return -1 -------------------------------------------------------------------------------- /Tree/Leetcode 173. Binary Search Tree Iterator.py: -------------------------------------------------------------------------------- 1 | class BSTIterator: 2 | 3 | def __init__(self, root: TreeNode): 4 | self.stack = [] 5 | self.inOrder(root) 6 | 7 | def inOrder(self, node): 8 | s = [] 9 | while s or node: 10 | while node: 11 | s.append(node) 12 | node = node.right 13 | node = s.pop() 14 | self.stack.append(node.val) 15 | node = node.left 16 | 17 | # if not node: 18 | # return 19 | # self.inOrder(node.left) 20 | # self.stack.append(node.val) 21 | # self.inOrder(node.right) 22 | 23 | def next(self) -> int: 24 | """ 25 | @return the next smallest number 26 | """ 27 | return self.stack.pop() 28 | 29 | def hasNext(self) -> bool: 30 | """ 31 | @return whether we have a next smallest number 32 | """ 33 | return len(self.stack) > 0 -------------------------------------------------------------------------------- /DFS BFS/Leetcode 1269. Number of Ways to Stay in the Same Place After Some Steps.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numWays(self, steps: int, arrLen: int) -> int: 3 | if steps == 0 or arrLen == 1: 4 | return 1 5 | 6 | visited = {} 7 | return self.helper(0, steps, arrLen, visited) % (10 ** 9 + 7) 8 | 9 | def helper(self, pos, steps, n, visited): 10 | if (pos, steps) in visited: 11 | return visited[(pos, steps)] 12 | if steps == 0: 13 | if pos == 0: 14 | return 1 15 | else: 16 | return 0 17 | if pos > steps: 18 | return 0 19 | res = self.helper(pos, steps-1, n, visited) 20 | if 0<=pos+1 int: 4 | dic = set(wordList) 5 | if endWord not in dic: 6 | return 0 7 | 8 | step = 1 9 | q = collections.deque() 10 | q.append(beginWord) 11 | while q: 12 | size = len(q) 13 | for _ in range(size): 14 | word = q.popleft() 15 | for i in range(len(word)): 16 | for char in range(ord('a'), ord('z')+1): 17 | char = chr(char) 18 | new_word = word[:i] +char +word[i+1:] 19 | if new_word == endWord: 20 | return step+1 21 | if new_word in dic: 22 | q.append(new_word) 23 | dic.remove(new_word) 24 | step+=1 25 | return 0 -------------------------------------------------------------------------------- /String/Leetcode 76. Minimum Window Substring.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minWindow(self, s: str, t: str) -> str: 3 | l_s, l_t = len(s), len(t) 4 | if not s or l_t>l_s: 5 | return '' 6 | 7 | dic = {} 8 | count = 0 9 | for char in t: 10 | dic[char] = dic.get(char,0)+1 11 | 12 | l = r = 0 13 | min_l = l_s + 1 14 | res = "" 15 | while r 0: 18 | count += 1 19 | dic[s[r]] -=1 20 | 21 | while count == l_t: 22 | if r-l+1 < min_l: 23 | min_l = r-l+1 24 | res = s[l:r+1] 25 | if s[l] in dic: 26 | dic[s[l]] += 1 27 | if dic[s[l]] > 0: 28 | count -= 1 29 | l += 1 30 | r += 1 31 | return res -------------------------------------------------------------------------------- /Hackerrank/Graphs/Connected Cell in a Grid.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/connected-cell-in-a-grid/problem 2 | 3 | # Complete the maxRegion function below. 4 | def getRegion(grid, x, y, visited): 5 | m, n = len(grid), len(grid[0]) 6 | dirs = [(1,0),(-1,0),(0,1),(0,-1),(-1,-1),(-1,1),(1,-1),(1,1)] 7 | res = 1 8 | for dx, dy in dirs: 9 | nx = dx + x 10 | ny = dy + y 11 | if 0<=nx None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | idx = len(nums)-2 7 | while idx>=0: 8 | if nums[idx]nums[idx]: 17 | nextIdx+=1 18 | 19 | #swap idx and nextIdx 20 | nums[idx], nums[nextIdx-1] = nums[nextIdx-1], nums[idx] 21 | nums[idx+1:] = nums[idx+1:][::-1] 22 | 23 | 24 | # 1  2  7  4  3  1 find 2 -> first element which is smaller that next element 25 | # 1  2  7  4  3  1 find 3 -> smallest emlement which is larget that 2 26 | # 1  3  7  4  2  1 swap 2 and 3 27 | # 1  3  [1  2  4  7] sort nums after 3 -------------------------------------------------------------------------------- /DFS BFS/Leetcode 638. Shopping Offers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int: 3 | return self.helper(price, special, needs, {}) 4 | 5 | def helper(self,price, special, needs, visited): 6 | if tuple(needs) in visited: 7 | return visited[tuple(needs)] 8 | sums = 0 9 | for i in range(len(needs)): 10 | sums += needs[i]*price[i] 11 | res = sums 12 | for spec in special: 13 | needs_copy = needs[::] 14 | isValid = True 15 | for i in range(len(needs)): 16 | if needs_copy[i] < spec[i]: 17 | isValid = False 18 | break 19 | needs_copy[i] -= spec[i] 20 | 21 | if isValid: 22 | res = min(res, spec[-1] + self.helper(price, special, needs_copy,visited)) 23 | visited[tuple(needs)] = res 24 | return res 25 | -------------------------------------------------------------------------------- /Hackerrank/Search/Minimum Time Required.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/minimum-time-required/problem 2 | 3 | def calItems(machines, goal, days): 4 | items = 0 5 | for m in machines: 6 | items += days//m 7 | if items >=goal: 8 | break 9 | return items 10 | 11 | def minTime(machines, goal): 12 | left, right = 0, max(machines)*goal 13 | while left<=right: 14 | mid = left + (right-left)//2 15 | items = calItems(machines,goal, mid) 16 | if items>=goal: 17 | right = mid - 1 18 | else: 19 | left = mid + 1 20 | return right+1 21 | 22 | 23 | 24 | 25 | 26 | # another solution 27 | def minTime(machines, goal): 28 | h = [] 29 | for i in range(len(machines)): 30 | heapq.heappush(h, (machines[i], i)) 31 | days = 0 32 | while goal>0: 33 | goal -= 1 34 | d, i = heapq.heappop(h) 35 | days += d-days 36 | heapq.heappush(h, (d+machines[i], i)) 37 | return days -------------------------------------------------------------------------------- /Array/Leetcode 45. Jump Game II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, nums: List[int]) -> int: 3 | curMax = preMax = 0 4 | res = 0 5 | for i in range(len(nums)-1): 6 | curMax = max(curMax, nums[i]+i) 7 | if i == preMax: 8 | res += 1 9 | preMax = curMax 10 | return res 11 | 12 | 13 | class Solution: 14 | def jump(self, nums: List[int]) -> int: 15 | cur_reach = pre_reach = 0 16 | step = 0 17 | for i in range(len(nums)): 18 | if pre_reach >= len(nums)-1: 19 | return step 20 | if i<=pre_reach: 21 | cur_reach = max(cur_reach, nums[i]+i) 22 | if i == pre_reach: 23 | step+=1 24 | pre_reach = cur_reach 25 | return step 26 | #求机值,除了考虑Dynamic programming,还要考虑Greedy,局部最优推导出全局最优 27 | #preMax 指的是上一步走的最大距离,一旦走到preMax,step+1,并且更新preMax为curMax(curMax是preMax范围内的最大距离),因为题目假设一定可以到达最终,所以也可不需要在preMax范围内求curMax,只需一直计算curMax即可 -------------------------------------------------------------------------------- /DFS BFS/Leetcode 695. Max Area of Island.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxAreaOfIsland(self, grid: List[List[int]]) -> int: 3 | res = 0 4 | m, n = len(grid), len(grid[0]) 5 | dirs = [(1,0),(-1,0),(0,1),(0,-1)] 6 | for i in range(m): 7 | for j in range(n): 8 | if grid[i][j] == 1: 9 | stack = [] 10 | stack.append((i,j)) 11 | grid[i][j] = '#' 12 | cur_area = 1 13 | while stack: 14 | x, y = stack.pop() 15 | for dx, dy in dirs: 16 | nx = dx + x 17 | ny = dy + y 18 | if 0<=nx int: 3 | if not matrix or not matrix[0]: 4 | return 0 5 | m, n = len(matrix), len(matrix[0]) 6 | visited = {} 7 | res = 0 8 | for i in range(m): 9 | for j in range(n): 10 | path = self.dfs(matrix, i, j, visited) 11 | res = max(res, path) 12 | return res 13 | 14 | def dfs(self, matrix, x, y, visited): 15 | m, n = len(matrix), len(matrix[0]) 16 | if (x,y) in visited: 17 | return visited[(x,y)] 18 | dirs = [(0,1),(0,-1),(1,0),(-1,0)] 19 | res = 1 20 | for dx, dy in dirs: 21 | nx = dx + x 22 | ny = dy + y 23 | if 0<=nxmatrix[x][y]: 24 | res = max(res, 1 + self.dfs(matrix, nx, ny, visited)) 25 | visited[(x,y)] = res 26 | return res -------------------------------------------------------------------------------- /Trie/Leetcode 208. Implement Trie (Prefix Tree).py: -------------------------------------------------------------------------------- 1 | class TrieNode: 2 | def __init__(self): 3 | self.child = collections.defaultdict(TrieNode) 4 | self.isWord = False 5 | 6 | class Trie: 7 | 8 | def __init__(self): 9 | self.root = TrieNode() 10 | 11 | 12 | def insert(self, word: str) -> None: 13 | cur =self.root 14 | for w in word: 15 | cur = cur.child[w] 16 | cur.isWord = True 17 | 18 | 19 | def search(self, word: str) -> bool: 20 | cur = self.root 21 | for w in word: 22 | if w in cur.child: 23 | cur = cur.child[w] 24 | else: 25 | return False 26 | return cur.isWord 27 | 28 | 29 | def startsWith(self, prefix: str) -> bool: 30 | cur = self.root 31 | for w in prefix: 32 | if w in cur.child: 33 | cur = cur.child[w] 34 | else: 35 | return False 36 | return True -------------------------------------------------------------------------------- /Hackerrank/Queue/Castle on the Grid.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/castle-on-the-grid/problem 2 | import collections 3 | def minimumMoves(grid, startX, startY, goalX, goalY): 4 | m, n = len(grid), len(grid[0]) 5 | q = collections.deque() 6 | q.append((startX, startY)) 7 | visited = set() 8 | visited.add((startX, startY)) 9 | step = 0 10 | dirs = [(0,1),(1,0),(-1,0), (0,-1)] 11 | while q: 12 | size = len(q) 13 | for _ in range(size): 14 | x, y = q.popleft() 15 | for dx, dy in dirs: 16 | nx = x 17 | ny = y 18 | while 0<=nx int: 3 | s += '+' 4 | stack = [] 5 | i,sign,num = 0, '+', 0 6 | while i < len(s): 7 | if s[i].isdigit(): 8 | while s[i].isdigit() and i