Sports Programming 筆記
Sports Programming,又稱 Competitive Programming
(演算法競賽、競技プログラミング)
Sports Programming 心得
確實確認問題的條件
與 Interviewee 的互動
復述問題予 Interviewee
- 增加交流
- 確認問題
向 Interviewee 仔細確認未於文字中詳細說明的部分
把問題數學化
冷靜並透徹地看待問題全貌
不要因為慌亂,或為了急著表現/開口填補空隙,而急就章地開始
冷靜地不慌不忙了解問題,適當地向 interviewee 確認有疑義的地方
去了解這個問題的全貌,才能最快接近好的方法
草擬幾個例子推演自己的構想
以草擬的方式,無須工整,演示並測試自己初步的構想
考慮極端特例
考慮 Corner Cases
範例:LeetCode #43. Multiply Strings
給定字串num1, num2,求兩者乘積(in str) ーー 考慮num1, num2有一者為零時 ⇒ 直接回傳零
範例:LeetCode 58. Length of Last Word
Given a string s consisting of words and spaces,
return the length of the last word in the string.
可能的特例:
- s 結束於空格
- s 只有 1 個 word 且不始於空格
(即 last word 前無空格)
class Solution: def lengthOfLastWord(self, s: str) -> int: i = len(s) - 1 first_non_space = -1 for i in range(len(s) - 1, -1, -1): if first_non_space == -1 and s[i] != " ": first_non_space = i if first_non_space != -1 and s[i] == " ": return first_non_space - i return first_non_space + 1
範例:LeetCode 1232. Check If It Is a Straight Line
You are given an array coordinates,
coordinates[i] = [x, y],
where [x, y] represents the coordinate of a point.
Check if these points make a straight line in the XY plane.
Constraints:
2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates
contains no duplicate point.
如果使用斜截式 y = m * x + b
應考慮豎直線的情況導致斜率 m 無法計算(分母 xi – xj 為 0)
(此題 input 的 coordinates 不包含一樣的樣本,
可以忽略有重複樣本的可能性)
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: #if () x1, y1 = coordinates[0] x2, y2 = coordinates[1] if x1 == x2: return all(x == x1 for x, y in coordinates[2:]) m = (y2 - y1) / (x2 - x1) b = coordinates[0][1] - m * coordinates[0][0] for x, y in coordinates[2:]: if y != m * x + b: return False return True
考慮 Boundary Cases (Edge Cases)
確認 constraints
範例:LeetCode #1178. Number of Valid Words for Each Puzzle
Constraints:
- puzzles[i].length == 7
- Each puzzles[i] does not contain repeated characters.
這意味著len(set(words[i]))不可超過7
Coding 過程應注意事項
Coding 過程中切勿沉默不語,敘述你的想法給 Interviewee
適當地定義新變數去縮短名稱或使得其更容易理解
範例:top, left, right, button = rectangle
推導出最佳解之前
不要一開始就想著最佳解
不要自作聰明
束手無策時,適時地請求 Interviewee 的幫助
考慮最適合的 data structure
Submission Accepted 後試著計算 Time/Space Complexity,再嘗試思考是否有更好的解
關於 return
以「易懂」的立場,將回傳值變數命名為 result
result
ans, res
ult, return
注意題目要求 return 的是什麼,避免做多餘的運算
例:
Run 之前
先在腦中 Debug
注意過程中是否有 index out of range
注意變數被使用及改變的時間點
範例:Leetcode # 152. Maximum Product Subarray
要 print() 出來 debug 的內容一定要設置為變數而不是運算式
以免運算式內容被修改了,但是 print() 裡沒有同步更新
先徵求 Interviewee的許可
array / str
如果覺得複雜時,可以嘗試逆著做回來
slicing 用的指標命名:start, stop
相關網站
LeetCode
小訣竅
LeetCode 的 Python3 內建 math
, collections
module
例題筆記
- Leetcode # 1. Two Sum
- Leetcode # 2. Add Two Numbers
- Leetcode # 3. Longest Substring Without Repeating Characters
- Leetcode # 5. Longest Palindromic Substring (Manacher’s Algorithm)
- Leetcode # 8. String to Integer (atoi)
- LeetCode # 11. Container With Most Water
- Leetcode # 13. Roman to Integer
- Leetcode # 15. 3Sum
- Leetcode # 17. Letter Combinations of a Phone Number
- Leetcode # 20. Valid Parentheses
- Leetcode # 21. Merge Two Sorted Lists
- Leetcode # 26. Remove Duplicates from Sorted Array
- Leetcode # 28. Find the Index of the First Occurrence in a String
- Leetcode # 31. Next Permutation
- Leetcode # 35. Search Insert Position
- Leetcode # 42. Trapping Rain Water
- Leetcode # 43. Multiply Strings
- Leetcode # 45. Jump Game II
- Leetcode # 46. Permutations
- Leetcode # 48. Rotate Image
- Leetcode # 50. Pow(x, n)
- Leetcode # 53. Maximum Subarray (Kadane’s Algorithm)
- Leetcode # 54. Spiral Matrix
- Leetcode # 56. ⭐️ Merge Intervals
- Leetcode # 62. Unique Paths
- Leetcode # 65. Valid Number
- Leetcode # 67. Add Binary
- Leetcode # 68. Text Justification
- Leetcode # 74. Search a 2D Matrix
- Leetcode # 77. Combinations
- Leetcode # 79. Perfect Squares
- Leetcode # 80. Remove Duplicates from Sorted Array II
- Leetcode # 81. Search in Rotated Sorted Array II
- Leetcode # 86. Partition List
- Leetcode # 88. Merge Sorted Array
- Leetcode # 92. Reverse Linked List II
- Leetcode # 97. Interleaving String
- Leetcode # 98. Validate Binary Search Tree
- Leetcode # 101. Symmetric Tree
- Leetcode # 102. Binary Tree Level Order Traversal
- Leetcode # 103. Binary Tree Zigzag Level Order Traversal
- Leetcode # 111. Minimum Depth of Binary Tree
- Leetcode # 112. Path Sum
- Leetcode # 116. Populating Next Right Pointers in Each Node
- Leetcode # 118. Pascal’s Triangle
- Leetcode # 121. Best Time to Buy and Sell Stock
- Leetcode # 122. Best Time to Buy and Sell Stock II
- Leetcode # 124. Binary Tree Maximum Path Sum
- Leetcode # 128. Longest Consecutive Sequence
- Leetcode # 136. Single Number
- Leetcode # 139. Word Break
- Leetcode # 141. Linked List Cycle
- Leetcode # 142. Linked List Cycle II (Floyd’s Tortoise🐢 and Hare🐇)
- Leetcode # 143. Reorder List
- Leetcode # 146. LRU Cache
- Leetcode # 152. Maximum Product Subarray
- Leetcode # 167. Two Sum II – Input Array Is Sorted
- Leetcode # 168. Excel Sheet Column Title
- Leetcode # 200. Number of Islands
- Leetcode # 203. Remove Linked List Elements
- Leetcode # 204. Count Primes
- Leetcode # 205. Isomorphic Strings
- Leetcode # 206. Reverse Linked List
- Leetcode # 209. Minimum Size Subarray Sum
- Leetcode # 210. Course Schedule II
- Leetcode # 213. House Robber II
- Leetcode # 215. Kth Largest Element in an Array
- Leetcode # 217. Contains Duplicate
- Leetcode # 221. Maximal Square
- Leetcode # 226. Invert Binary Tree
- Leetcode # 235. Lowest Common Ancestor of a Binary Search Tree
- Leetcode # 239. ⭐️ Sliding Window Maximum
- Leetcode # 242. Valid Anagram
- Leetcode # 249. Group Shifted Strings
- Leetcode # 270. Closest Binary Search Tree Value
- Leetcode # 271. Encode and Decode Strings
- Leetcode # 278. First Bad Version
- Leetcode # 283. Move Zeroes
- Leetcode # 299. Bulls and Cows
- Leetcode # 305. Number of Islands II
- Leetcode # 323. Number of Connected Components in an Undirected Graph
- Leetcode # 328. Odd Even Linked List
- Leetcode # 344. Reverse String
- Leetcode # 350. Intersection of Two Arrays II
- Leetcode # 394. Decode String
- Leetcode # 409. Longest Palindrome
- Leetcode # 418. Sentence Screen Fitting
- Leetcode # 424. Longest Repeating Character Replacement
- Leetcode # 435. Non-overlapping Intervals
- Leetcode # 438. Find All Anagrams in a String
- Leetcode # 439. Ternary Expression Parser
- Leetcode # 445. Add Two Numbers II
- Leetcode # 451. Sort Characters By Frequency
- Leetcode # 459. Repeated Substring Pattern
- Leetcode # 485. Max Consecutive Ones
- Leetcode # 486. Predict the Winner
- Leetcode # 487. Max Consecutive Ones II
- Leetcode # 490. The Maze
- Leetcode # 494. Target Sum
- Leetcode # 515. Find Largest Value in Each Tree Row
- Leetcode # 518. Coin Change II
- Leetcode # 523. Continuous Subarray Sum
- Leetcode # 542. 01 Matrix
- Leetcode # 543. Diameter of Binary Tree
- Leetcode # 566. Reshape the Matrix
- Leetcode # 567. Permutation in String
- Leetcode # 589. N-ary Tree Preorder Traversal
- Leetcode # 632. Smallest Range Covering Elements from K Lists
- Leetcode # 643. Maximum Average Subarray I
- Leetcode # 664. Strange Printer
- Leetcode # 688. Knight Probability in Chessboard
- Leetcode # 701. Insert into a Binary Search Tree
- Leetcode # 706. Design HashMap
- Leetcode # 712. Minimum ASCII Delete Sum for Two Strings
- Leetcode # 723. Candy Crush
- Leetcode # 735. Asteroid Collision
- Leetcode # 740. Delete and Earn
- Leetcode # 746. Min Cost Climbing Stairs
- Leetcode # 767. Reorganize String
- Leetcode # 769. ⭐ Max Chunks To Make Sorted
- Leetcode # 784. Letter Case Permutation
- Leetcode # 792. Number of Matching Subsequences
- Leetcode # 808. Soup Servings
- Leetcode # 844. Backspace String Compare
- Leetcode # 852. Peak Index in a Mountain Array
- Leetcode # 859. Buddy Strings
- Leetcode # 876. Middle of the Linked List
- Leetcode # 894. All Possible Full Binary Trees
- Leetcode # 902. Numbers At Most N Given Digit Set
- Leetcode # 918. Maximum Sum Circular Subarray
- Leetcode # 918. Maximum Sum Circular Subarray
- Leetcode # 938. Range Sum of BST
- Leetcode # 974. ⭐️ Subarray Sums Divisible by K
- Leetcode # 977. Squares of a Sorted Array
- Leetcode # 1004. Max Consecutive Ones III
- Leetcode # 1009. Complement of Base 10 Integer
- Leetcode # 1014. Best Sightseeing Pair
- Leetcode # 1026. Maximum Difference Between Node and Ancestor
- Leetcode # 1051. Height Checker
- Leetcode # 1056. Confusing Number
- Leetcode # 1060. Missing Element in Sorted Array
- Leetcode # 1095. Find in Mountain Array
- Leetcode # 1110. Delete Nodes And Return Forest
- Leetcode # 1122. Relative Sort Array
- Leetcode # 1137. N-th Tribonacci Number
- Leetcode # 1143. Longest Common Subsequence
- Leetcode # 1145. Binary Tree Coloring Game
- Leetcode # 1183. Maximum Number of Ones
- Leetcode # 1275. Find Winner on a Tic Tac Toe Game
- Leetcode # 1302. Deepest Leaves Sum
- Leetcode # 1335. Minimum Difficulty of a Job Schedule
- Leetcode # 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
- Leetcode # 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree
- Leetcode # 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
- Leetcode # 1475. Final Prices With a Special Discount in a Shop
- Leetcode # 1483. ⭐️ Kth Ancestor of a Tree Node
- Leetcode # 1493. Longest Subarray of 1’s After Deleting One Element
- Leetcode # 1502. Can Make Arithmetic Progression From Sequence
- Leetcode # 1567. Maximum Length of Subarray With Positive Product
- Leetcode # 1615. Maximal Network Rank
- Leetcode # 1644. Lowest Common Ancestor of a Binary Tree II
- Leetcode # 1657. Determine if Two Strings Are Close
- Leetcode # 1704. Determine if String Halves Are Alike
- Leetcode # 1770. Maximum Score from Performing Multiplication Operations
- Leetcode # 1792. Maximum Average Pass Ratio
- Leetcode # 1909. Remove One Element to Make the Array Strictly Increasing
- Leetcode # 1940. Longest Common Subsequence Between Sorted Arrays
- Leetcode # 2024. Maximize the Confusion of an Exam
- Leetcode # 2037. Minimum Number of Moves to Seat Everyone
- Leetcode # 2054. Two Best Non-Overlapping Events
- Leetcode # 2083. Substrings That Begin and End With the Same Letter
- Leetcode # 2109. Adding Spaces to a String
- Leetcode # 2182. Construct String With Repeat Limit
- Leetcode # 2337. Move Pieces to Obtain a String
- Leetcode # 2361. Minimum Costs Using the Train Line
- Leetcode # 2369. Check if There is a Valid Partition For The Array
- Leetcode # 2415. Reverse Odd Levels of Binary Tree
- Leetcode # 2444. Count Subarrays With Fixed Bounds
- Leetcode # 2483. Minimum Penalty for a Shop
- Leetcode # 2554. Maximum Number of Integers to Choose From a Range I
- Leetcode # 2558. Take Gifts From the Richest Pile
- Leetcode # 2593. Find Score of an Array After Marking All Elements
- Leetcode # 2616. Minimize the Maximum Difference of Pairs
- Leetcode # 2779. ⭐️ Maximum Beauty of an Array After Applying Operation
- Leetcode # 2786. Visit Array Positions to Maximize Score
- Leetcode # 2798. Number of Employees Who Met the Target
- Leetcode # 2799. Count Complete Subarrays in an Array
- Leetcode # 2800. Shortest String That Contains Three Strings
- Leetcode # 2808. Minimum Seconds to Equalize a Circular Array
- Leetcode # 2812. Find the Safest Path in a Grid
- Leetcode # 2818. Apply Operations to Maximize Score
- Leetcode # 2825. Make String a Subsequence Using Cyclic Increments
- Leetcode # 2843. Count Symmetric Integers
- Leetcode # 2844. Minimum Operations to Make a Special Number
- Leetcode # 2845. Count of Interesting Subarrays
- Leetcode # 2846. Minimum Edge Weight Equilibrium Queries in a Tree
- Leetcode # 2848. Points That Intersect With Cars
- Leetcode # 2850. Minimum Moves to Spread Stones Over Grid
- Leetcode # 2856. Minimum Array Length After Pair Removals
- Leetcode # 2859. Sum of Values at Indices With K Set Bits
- Leetcode # 2860. Happy Students
- Leetcode # 2861. Maximum Number of Alloys
- Leetcode # 2862. Maximum Element-Sum of a Complete Subset of Indices
- Leetcode # 2867. Count Valid Paths in a Tree
- Leetcode # 2869. Minimum Operations to Collect Elements
- Leetcode # 2870. Minimum Number of Operations to Make Array Empty
- Leetcode # 2873. Maximum Value of an Ordered Triplet I
- Leetcode # 2874. ⭐️ Maximum Value of an Ordered Triplet II
- Leetcode # 2875. Minimum Size Subarray in Infinite Array
- Leetcode # 2876. Count Visited Nodes in a Directed Graph
- Leetcode # 2940. Find Building Where Alice and Bob Can Meet
- Leetcode # 2981. Find Longest Special Substring That Occurs Thrice I
- Leetcode # 3110. Score of a String
- Leetcode # 3264. Final Array State After K Multiplication Operations I
Pramp
例題筆記
- Pramp – Array of Array Products
- Pramp – BST Successor Search
- Pramp – Getting a Different Number
- Pramp – Number of Paths
- Pramp – Root of Number
- Pramp – Smallest Substring of All Characters
相關心得
Algorithm 演算法
Complexity 複雜度
Recursion 遞迴
Brute-Force 暴力法/窮舉法|Backtracking 回溯法
Sorting 排序
Binary Method 二分法
BFS and DFS
⭐️ Dynamic Programming
Disjoint Set Union (DSU)
Data Structure 資料結構
Stack
Monotonic Stack
Linked List
Graph
Heap 堆積
Tree
- Ancestor Nodes:
The parent’s parent, a node reachable by repeated proceeding from child to parent. - Descendant:
A node reachable by repeated proceeding from parent to child. Also known as subchild. - Sibling Nodes: Child nodes with the same parent.
- Neighbor: Parent or child.
- Internal Node / Inner Node / Inode (for short) / Branch Node:
Any node of a tree that has child nodes. - External Node / Outer Node / Leaf Node / Terminal node:
Any node of a tree that does not have child nodes. - Breadth: The number of leaves.
- Degree:
For a given node, its number of children. A leaf, by definition, has degree zero. - Degree of Tree:
The degree of a tree is the maximum degree of a node in the tree.
- Size of a Tree:
Number of nodes in the tree. - Distance:
The number of edges along the shortest path between two nodes. - Diameter:
The length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
- Height: The length of the longest downward path to a leaf from that node.
(The height of the root is the height of the tree.) - Depth / Level: The length of the path to its root (i.e., its root path).
- Width: The number of nodes in a level.
Binary Tree 二元樹
Lowest Common Ancestor
Priority Queue 優先權佇列
常見題型
Prefix Sum
Subarray Sums Divisible by K
- Leetcode # 523. Continuous Subarray Sum
- Leetcode # 974. ⭐️ Subarray Sums Divisible by K
- Leetcode # 2845. Count of Interesting Subarrays
⭐️ Parsing
Merge Intervals
列出所有排列/組合 List All Permutations/Combinations
請參考 Backtracking 回溯法
Permutations
Combinations
- Leetcode # 17. Letter Combinations of a Phone Number
- Leetcode # 77. Combinations
- Leetcode # 894. All Possible Full Binary Trees
Two pointers | Sliding Window
String-Searching Algorithm
Rabin-Karp Algorithm|Knuth-Morris-Pratt (KMP) Algorithm
Hash a String
class HashString: def __init__(self, init_str, method = 0): self.MOD = [ 10 ** 9 + 33, 2 ** 31 ][method] self.RADIX = [52, 53][method] self.BIAS = [0, 1][method] self.MAX_WEIGHT, self.value = 1, 0 for i, c in enumerate(init_str): self.value = (self.value * self.RADIX + self.ord(c)) % self.MOD if i > 0: self.MAX_WEIGHT = (self.MAX_WEIGHT * self.RADIX) % self.MOD self.cur_str = init_str def __str__(self): return self.cur_str def get_value(self): return self.value def ord(self, c): ascii = ord(c) if ascii >= 65 and ascii <= 90: return ascii - 65 + self.BIAS elif ascii >= 97 and ascii <= 122: return ascii - 71 + self.BIAS def popleft_append(self, c): self.value = (self.value \ - (self.ord(self.cur_str[0]) * self.MAX_WEIGHT) % self.MOD ) % self.MOD self.value = ((self.value * self.RADIX) % self.MOD \ + self.ord(c)) % self.MOD self.cur_str = self.cur_str[1:] + c return self.value
Find Subtring(s) in String s
def find_substr(s, target, only_first=True): if len(s) < len(target): return -1 if only_first else [] result = [] target_v = [HashString(target, m).get_value() for m in range(2)] hashed_str = [HashString(s[:len(target)], m) for m in range(2)] for i in range(len(s) - len(target) + 1): if all(hashed_str[m].get_value() == target_v[m] for m in range(2)): if only_first: return i result.append(i) if i == len(s) - len(target): break for m in range(2): hashed_str[m].popleft_append(s[i + len(target)]) return -1 if only_first else result
關於 2D 座標
我的常用自訂函式
Python
Last Updated on 2024/12/18 by A1go