diff --git a/README.md b/README.md index c34ae3b..9368fac 100644 --- a/README.md +++ b/README.md @@ -10,244 +10,244 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal [Python](https://github.com/qiyuangong/leetcode/tree/master/python) and [Java](https://github.com/qiyuangong/leetcode/tree/master/java) full list. ♥ means you need a subscription. -| # | Title | Solution | Basic idea (One line) | -|---| ----- | -------- | --------------------- | -| 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/001_Two_Sum.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/001_Two_Sum.java) | 1. Hash O(n) and O(n) space.
2. Sort and search with two points O(n) and O(1) space. | -| 2 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/002_Add_Two_Numbers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/002_Add_Two_Numbers.java) | Take care of the carry from lower digit. | -| 3 | [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/003_Longest_Substring_Without_Repeating_Characters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/003_Longest_Substring_Without_Repeating_Characters.java) |1. Check every possible substring O(n^2)
2. Remember the character index and current check pos, if character index >= current pos, then there is duplicate | -| 4 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/004_Median_of_Two_Sorted_Arrays.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/004_Median_of_Two_Sorted_Arrays.java) | 1. Merge two sorted lists and compute median, O(m + n) and O(m + n)
2. An extension of median of two sorted arrays of equal size problem| -| 5 | [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/005_Longest_Palindromic_Substring.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/005_Longest_Palindromic_Substring.java) | [Background knowledge](http://en.wikipedia.org/wiki/Longest_palindromic_substring)
1. DP if s[i]==s[j] and P[i+1, j-1] then P[i,j]
2. A palindrome can be expanded from its center
3. Manacher algorithm| -| 7 | [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/007_Reverse_Integer.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/007_Reverse_Integer.java) | Overflow when the result is greater than 2147483647 or less than -2147483648. -| 8 | [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/008_String_to_Integer(atoi).py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/008_String_to_Integer(atoi).java) | Overflow, Space, and negative number | -| 9 | [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/009_Palindrome_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/009_Palindrome_Number.java) | Get the len and check left and right with 10^len, 10 | -| 11 | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/011_Container_With_Most_Water.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/011_Container_With_Most_Water.java) | 1. Brute Force, O(n^2) and O(1)
2. Two points, O(n) and O(1) | -| 12 | [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/012_Integer_to_Roman.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/012_Integer_to_Roman.java) | [Background knowledge](http://www.rapidtables.com/convert/number/how-number-to-roman-numerals.htm) Just like 10-digit number, divide and minus | -| 13 | [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/013_Roman_to_Integer.py) | Add all curr, if curr > prev, then need to subtract 2 * prev | -| 15 | [3Sum](https://leetcode.com/problems/3sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/015_3Sum.py) | 1. Sort and O(n^2) search with three points
2. Multiple Two Sum (Problem 1) | -| 16 | [3Sum Closest](https://leetcode.com/problems/3sum-closest/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/016_3Sum_Closest.py) | Sort and Multiple Two Sum check abs| -| 18 | [4Sum](https://leetcode.com/problems/4sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/018_4Sum.py) | The same as 3Sum, but we can merge pairs with the same sum | -| 19 | [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/019_Remove_Nth_Node_From_End_of_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/019_Remove_Nth_Node_From_End_of_List.java) | 1. Go through list and get length, then remove length-n, O(n) and O(n)
2. Two pointers, first pointer goes to n position, then move both pointers until reach tail, O(n) and O(n) | -| 20 | [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/020_Valid_Parentheses.py) | 1. Stack
2. Replace all parentheses with '', if empty then True | -| 21 | [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/021_Merge_Two_Sorted_Lists.py) | Add a dummy head, then merge two sorted list in O(m+n) | -| 23 | [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/023_Merge_k_Sorted_Lists.py) | 1. Priority queue O(nk log k)
2. Binary merge O(nk log k)| | -| 24 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/024_Swap_Nodes_in_Pairs.py) | Add a dummy and store the prev | -| 28 | [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/028_Implement_strStr().py) | 1. O(nm) comparison
2. KMP | -| 35 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/035_Search_Insert_Position.py) | Binary Search | -| 46 | [Permutations](https://leetcode.com/problems/permutations/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/046_Permutations.py) | 1. Python itertools.permutations
2. DFS with swapping, O(n^2) and O(n^2)
3. iteratively generate n-permutations with (n-1)-permutations, O(n^3) and O(n^2) | -| 47 | [Permutations II](https://leetcode.com/problems/permutations-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/047_Permutations_II.py) | 1. DFS with swapping, check duplicate, O(n^2) and O(n^2)
2. iteratively generate n-permutations with (n-1)-permutations, O(n^3) and O(n^2) | -| 53 | [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/053_Maximum_Subarray.py) | 1. Recursion, O(nlgn), O(lgn)
2. Bottom-up DP, O(n) and O(n)
3. Bottom-up DP, f(x) = max(f(x-1)+A[x], A[x]), f(x) = max(f(x-1)+A[x], A[x]),O(n) and O(1) | -| 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/054_Spiral_Matrix.py) | O(nm) 1. Turn in the corner and loop
2. (0, 1) -> (1, 0) -> (0, -1) -> (-1, 0) | -| 62 | [Unique Paths](https://leetcode.com/problems/unique-paths/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/062_Unique_Paths.py) | 1. Bottom-up DP, dp[i][j] = dmap[i-1][j] + dmap[i][j-1], O(mn) and O(mn)
2. Combination (m+n-2, m-1) | -| 63 | [Unique Paths II](https://leetcode.com/problems/unique-paths-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/063_Unique_Paths_II.py) | Bottom-up DP, dp[i][j] = dmap[i-1][j] + dmap[i][j-1] (if block, then 0), O(mn) and O(mn) | -| 65 | [Valid Number](https://leetcode.com/problems/valid-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/065_Valid_Number.py) | 1. strip leading and tailing space, then check float using exception, check e using split
2. check is number split by . or e, note that number after e may be negative | -| 66 | [Plus One](https://leetcode.com/problems/plus-one/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/066_Plus_One.py) | Check if current digit == 9. | -| 70 | [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/070_Climbing_Stairs.py) | Bottom-up DP, dp[i] = dp[i - 2] + dp[i- 1]
1. O(n) and O(n)
2. Only two variables are needed, O(n) and O(1) | -| 72 | [Edit Distance](https://leetcode.com/problems/edit-distance/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/072_Edit_Distance.py) | [Background](https://en.wikipedia.org/wiki/Edit_distance)
1. DP O(n^2) space
2. DP O(n) space | -| 78 | [Subsets](https://leetcode.com/problems/subsets/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/078_Subsets.py) | 1. DFS Recursion, O(2^n) and O(2^n)
2. Recursion on a binary number, O(2^n) and O(2^n)
3. Sort and iteratively generate n subset with n-1 subset, O(n^2) and O(2^n)| -| 90 | [Subsets II](https://leetcode.com/problems/subsets-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/090_Subsets_II.py) | 1. DFS Recursion with duplicate check, O(2^n) and O(2^n)
2. Recursion on a binary number, O(2^n) and O(2^n)
3. Sort and iteratively generate n subset with n-1 subset, note that if nums[index] == nums[index - 1] then generate from last end to curr end, O(n^2) and O(2^n) | -| 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/094_Binary_Tree_Inorder_Traversal.py) | 1. Recursion, O(n) and O(1)
2. Stack and check isinstance(curr, TreeNode), O(n) and O(n)
3. Stack and check left and right, O(n) and O(n) | -| 98 | [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/098_Validate_Binary_Search_Tree.py) | 1. Stack O(n) and O(n)
2. Recursion O(n) and O(n) | -| 104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/104_Maximum_Depth_of_Binary_Tree.py)| Recursion max(left, right) + 1 | -| 108 | [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/108_Convert_Sorted_Array_to_Binary_Search_Tree.py)| Recursion O(n) and O(nlgn)| -| 109 | [Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/109_Convert_Sorted_List_to_Binary_Search_Tree.py) | 1. Two points fast (next next) and slow (next) O(nlgn) and O(n)
2. Bottom-up recursion O(n) and O(lgn) | -| 110 | [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/110_Balanced_Binary_Tree.py) | Recursion 1. Top-down O(n^2) and O(n), Bottom-up recursion with sentinel -1 O(n) and O(n) | -| 111 | [Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/111_Minimum_Depth_of_Binary_Tree.py) | 1. Recursion, note that when size of left (ld) or right (rd) is 0, then min = 1 + ld + rd
2. BFS check by level (right most), which is much faster than recursion | -| 124 | [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/124_Binary_Tree_Maximum_Path_Sum.py) | Recursion O(n) and O(n), max (left + node, right + node, left + node + right) | -| 125 | [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/125_Valid_Palindrome.py)| Exclude non-alphanumeric characters and compare O(n) | -| 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/128_Longest_Consecutive_Sequence.py) | Set or hash, pop adjacency, O(n) and O(n) | -| 133 | [Clone Graph](https://leetcode.com/problems/clone-graph/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/133_Clone_Graph.py) | Hash and DFS or BFS | -| 136 | [Single Number](https://leetcode.com/problems/single-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/136_Single_Number.py) | 1. Hash or set, O(n) and O(n)
2. xor O(n) and O(1) | -| 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/137_Single_Number_II.py) | 1. ctypes 32 % 3 and &, O(n) and O(1)
2. ones, twos, threes as bitmask (e.g. ones represents ith bit had appeared once), O(n) and O(1) | -| 138 | [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/138_Copy_List_with_Random_Pointer.py) | 1. Hash O(n) and O(n)
2. Modify original structure: Original->Copy->Original, then node.next.random = node.random.next, O(n) and O(1) | -| 141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/141_Linked_List_Cycle.py) | 1. Hash or set
2. Two points (fast and slow)
3. Add a max and check if reach the max | -| 142 | [Linked List Cycle II](https://discuss.leetcode.com/topic/2975/o-n-solution-by-using-two-pointers-without-change-anything) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/142_Linked_List_Cycle_II.py) | Two points, a+b=nr | -| 143 | [Reorder List](https://leetcode.com/problems/reorder-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/143_Reorder_List.py) | 1. List as index to rebuild relation, O(n) and O(n)
2. Two points, O(n) and O(1) | -| 144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/144_Binary_Tree_Preorder_Traversal.py) | 1. Recursion, O(n) and O(n)
2. Stack, O(n) and O(n) | -| 145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/145_Binary_Tree_Postorder_Traversal.py) | 1. Recursion, O(n) and O(n)
2. Stack and queue (insert 0), O(n) and O(n)
3. Stack and isinstance(curr, TreeNode), O(n) and O(n) | -| 146 | [LRU Cache](https://leetcode.com/problems/lru-cache/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/146_LRU_Cache.py) | 1. Queue and dict
2. OrderedDict | -| 150 | [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/150_Evaluate_Reverse_Polish_Notation.py) | Stack | -| 151 | [Reverse Words in a String](https://discuss.leetcode.com/category/159/reverse-words-in-a-string) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/151_Reverse_Words_in_a_String.py)| 1. Python split by space
2. Reverse all and reverse words | -| 152 | [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/152_Maximum_Product_Subarray.py) | DP, f(k) = max(f(k-1) * A[k], A[k], g(k-1) * A[k]), g(k) = min(g(k-1) * A[k], A[k], f(k-1) * A[k]), O(n) and O(1) | -| 153 | [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/153_Find_Minimum_in_Rotated_Sorted_Array.py) | Binary search with conditions, A[l] > A[r] | -| 154 | [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/154_Find_Minimum_in_Rotated_Sorted_Array_II.py) | Binary search with conditions, A[l] > A[r], A[l]=A[mid]=A[r] | -| 155 | [Min Stack](https://leetcode.com/problems/min-stack/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/155_Min_Stack.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/155_Min_Stack.java) | Add another stack for min stack, maintance this stack when the main stack pop or push: 1. Only push min, such that len(minStack)<=len(Stack) 2. Push min again when current top is min, such that len(minStack)=len(Stack) | -| 156 | [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/156_Binary_Tree_Upside_Down.py) | p.left = parent.right, parent.right = p.right, p.right = parent, parent = p.left, p = left | -| 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/157_Read_N_Characters_Given_Read4.py) | Handle the edge case (the end) | -| 158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/158_Read_N_Characters_Given_Read4_II_Call_multiple_times.py) | Store the pos and offset that is read by last read4 | -| 159 | [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/159_Longest_Substring_with_At_Most_Two_Distinct_Characters.py) | Maintain a sliding window that always satisfies such condition | -| 161 | [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) ♥| [Python](https://github.com/qiyuangong/leetcode/blob/master/python/161_One_Edit_Distance.py) | 1. Check the different position and conditions
2. [Edit distance](https://leetcode.com/problems/edit-distance/)| -| 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/163_Missing_Ranges.py) | Add -1 to lower for special case, then check if curr - prev >= 2| -| 166 | [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/166_Fraction_to_Recurring_Decimal.py) | % and Hash to find duplicate | -| 167 | [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/167_Two_Sum_II_Input_array_is_sorted.py) | Two points O(n) and O(1) | -| 170 | [Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/170_Two_Sum_III-Data_structure_design.py) | 1. Hash, O(1) for add, O(n) for find, O(n) space
2. sorted list, O(logn) for add, O(n) for find, O(n) space
3. Sort before find, O(1) for add, O(nlogn) for find, O(n) space| -| 179 | [Largest Number](https://leetcode.com/problems/largest-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/179_Largest_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/179_Largest_Number.java) | Define a comparator with str(x) + str(y) > str(y) + str(x), O(nlgn) and O(n) | -| 186 | [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) ♥| [Python](https://github.com/qiyuangong/leetcode/blob/master/python/186_Reverse_Words_in_a_String_II.py) | Reverse all and reverse each words | -| 198 | [House Robber](https://leetcode.com/problems/house-robber/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/198_House_Robber.py) | f(k) = max(f(k – 2) + num[k], f(k – 1)), O(n) and O(1) | -| 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/200_Number_of_Islands.py) | 1. Quick union find, O(nlogn) and O(n^2)
2. BFS with marks, O(n^2) and O(1) | -| 204 | [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/204_Count_Primes.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/204_Count_Primes.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/204_Count_Primes.cpp) | [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity), O(nloglogn) and O(n) | -| 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/206_Reverse_Linked_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/206_Reverse_Linked_List.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/206_Reverse_Linked_List.cpp) | 1. Stack, O(n) and O(n)
2. Traverse on prev and curr, then curr.next = prev, O(n) and O(1)
3. Recursion, O(n) and O(1) | -| 207 | [Course Schedule](https://leetcode.com/problems/course-schedule/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/207_Course_Schedule.py) | Cycle detection problem | -| 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/213_House_Robber_II.py) | f(k) = max(f(k – 2) + num[k], max(dp[0~ls-2],dp[1~ls-1], O(n) and O(1)| -| 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/215_Kth_Largest_Element_in_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/215_Kth_Largest_Element_in_an_Array.java) | 1. Sort, O(n) and O(n)
2. Heap, O(nlgk) and O(n)
3. Quick selection, O(klgn) and O(n)| -| 216 | [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/216_Combination_Sum_III.py) | Generate all combinations of length k and keep those that sum to n| -| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/217_Contains_Duplicate.py) | 1. Set and compare length
2. Sort and check i,i +1| -| 219 | [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/219_Contains_Duplicate_II.py) | 1. Brute force
2. Maintenance a set that contains previous k numbers, and check if curr in set | -| 220 | [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/220_Contains_Duplicate_III.py) | 1. Sort and binary Search
2. Bucket sort | -| 221 | [Maximal Square](https://leetcode.com/problems/maximal-square/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/221_Maximal_Square.py) | 1. Brute force
2. dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1, O(mn) and O(mn)
3. dp[j] = min([j], dp[j-1], prev) + 1, O(mn) and O(n)| -| 223 | [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/223_Rectangle_Area.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/223_Rectangle_Area.java) | Rectangle A + B - common area, O(1) and O(1) | -| 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/228_Summary_Ranges.py) | Detect start and jump, O(n) and O(1) | -| 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/236_Lowest_Common_Ancestor_of_a_Binary_Tree.java) | 1. Recursive check left, val and right, LCA is the split paths in tree, O(n) and O(n)
2. Store parents during traversing tree, reverse check their lowest common parent, O(n) and O(n) | -| 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/238_Product_of_Array_Except_Self.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/238_Product_of_Array_Except_Self.java) | The ans is [0,i -1] * [i+1, len- 1]. We can twice for left and right (reverse), O(n) and O(n) | -| 243 | [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/243_Shortest_Word_Distance.py) | Update index1 and index2, and check distance, O(n) and O(1) | -| 246 | [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/246_Strobogrammatic_Number.py) | Hash table and reverse string, O(n) and O(n) | -| 249 | [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/249_Group_Shifted_Strings.py) | Hash and generate hash code for each string, O(n) and O(n) | -| 252 | [Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/252_Meeting_Rooms.py) | 1. Sort and compare intervals[i].end with intervals[i+1], O(nlogn) and O(1)
2. Sort and check intervals when count >= 2, O(nlogn) and O(n) | -| 253 | [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/253_Meeting_Rooms_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/253_Meeting_Rooms_II.java) | 1. Priority queue and sort, O(nlogn) and O(n)
2. Go through timeline. If it's a start then meeting + 1, else meeting - 1. The ans is the max(meeting) in timeline. O(nlogn) and O(n) | -| 259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/259_3Sum_Smaller.py) | 1. Reduce to two sum smaller, then binary search, O(n^2lgn) and O(1)
2. Reduce to two sum smaller, then two points, O(n^2) and O(1)| -| 266 | [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/266_Palindrome_Permutation.py) | Compute frequency, check number of odd occurrences <= 1 then palindrome, O(n) and O(n)| -| 267 | [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/267_Palindrome_Permutation_II.py) | Check palindrome then generate half with [Permutations II](https://leetcode.com/problems/permutations-ii/), O(n^2) and O(n^2) | -| 268 | [Missing Number](https://leetcode.com/problems/missing-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/268_Missing_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/268_Missing_Number.java) | 1. Find missing by n * (n - 1)/2 - sum(nums)
2. XOR with index
3. Sort and binary search | -| 270 | [Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/270_Closest_Binary_Search_Tree_Value.py) | 1. Recursively brute force, O(n) and O(n)
2. Recursively compare root result with current kid's result (left or right), O(logn) and O(logn)
3. Iteratively compare root result with current kid's result (left or right), O(logn) and O(logn) | -| 273 | [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/273_Integer_to_English_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/python/273_Integer_to_English_Words.java) | Careful about corner cases, such 1-20 and 21-Hundred, O(lgn) and O(1) | -| 274 | [H-Index](https://leetcode.com/problems/h-index/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/274_H-Index.py) | [Background](https://en.wikipedia.org/wiki/H-index)
1. Sort and check number of papers greater than h, O(nlogn) and O(1)
2. Counting sort, O(n) and O(n) | -| 276 | [Paint Fence](https://leetcode.com/problems/paint-fence/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/276_Paint_Fence.py) | ways[i>2] = (ways[i-1] + ways[i-2]) * (k - 1), O(n) and O(1) | -| 280 | [Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/280_Wiggle_Sort.py) | 1. Sort and insert (n - 1) / 2 from tail to correct position, O(nlogn) and O(1)
2. Sort and swap(i, i + 1) from 1 to n - 1, O(nlogn)
3. Iteratively check order and reverse order, if not satisfied, then swap i with i + 1, O(n) | -| 286 | [Walls and Gates](https://leetcode.com/problems/walls-and-gates/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/286_Walls_and_Gates.py) | BFS with queue, O(mn) and O(mn) | -| 288 | [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/288_Unique_Word_Abbreviation.py) | hash | -| 293 | [Flip Game](https://leetcode.com/problems/flip-game/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/293_Flip_Game.py) | Python string slicing | -| 294 | [Flip Game II](https://leetcode.com/problems/flip-game-ii/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/294_Flip_Game_II.py) | 1. Backtracking to ensure that next step is False, O(n!!) and O(n!!)
2. Backtracking with memo, O(n!!) and O(n!)
3. DP based on [Sprague-Grundy Function](https://discuss.leetcode.com/topic/27282/theory-matters-from-backtracking-128ms-to-dp-0ms) | -| 296 | [Best Meeting Point](https://leetcode.com/problems/best-meeting-point/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/296_Best_Meeting_Point.py) | Think hard about Manhattan Distance in 1D case. Sort and find mean, O(mnlogmn) and O(1) | -| 298 | [Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/298_Binary_Tree_Longest_Consecutive_Sequence.py) | Bottom-up or top-down recursion, O(n) and O(n) | -| 305 | [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/305_Number_of_Islands_II.py) | Quick union find with weights, O(nlogn) and O(n) | -| 322 | [Coin Change](https://leetcode.com/problems/coin-change/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/322_Coin_Change.py) | Bottom-up or top-down DP, dp[n] = min(dp[n], dp[n - v_i]), where v_i is the coin, O(amount * n) and O(amount) | -| 336 | [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/336_Palindrome_Pairs.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/336_Palindrome_Pairs.java) | 1. Create a reverse word to index map, then for each word, check prefix and posfix, O(nk^2) and O(n)
2. Tire tree, O(nk^2) and O(n) | -| 337 | [House Robber III](https://leetcode.com/problems/house-robber-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/337_House_Robber_III.py) | 1. Recursion with hash map, O(n) and O(n)
2. Recursion on two steps, O(n) and O(1) | -| 339 | [Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/339_Nested_List_Weight_Sum.py) | Depth-first recursion | -| 340 | [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/340_Longest_Substring_with_At_Most_K_Distinct_Characters.py) | Maintain a sliding window with at most k distinct characters and a count for this window. Note that the start position need a loop to update.| -| 346 | [Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/346_Moving_Average_from_Data_Stream.py) | fix-sized queue or dequeue, O(1) and O(n) | -| 347 | [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/347_Top_K_Frequent_Elements.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/347_Top_K_Frequent_Elements.java) | 1. Sort by frequency, O(nlogn) and O(n).
2. we can build a min heaq (based on frequency), then pop min until there are k element, O(klgn) and O(n) | -| 351 | [Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/351_Android_Unlock_Patterns.py) | Backtracking, O(n!) and O(n) | -| 359 | [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/359_Logger_Rate_Limiter.py) | 1. hash which stores the latest timestamp, O(1) and O(n)
2. Using Priority queue to remove older logs, O(n) and O(n) | -| 366 | [Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/366_Find_Leaves_of_Binary_Tree.py) | 1. Set or hash to check leaft, O(n^2) and O(n)
2. Recursively check level and return them, O(n) and O(n)| -| 367 | [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/367_Valid_Perfect_Square.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/367_Valid_Perfect_Square.java) | [Integer square root](https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division)
1. 1+3+…+(2n-1) = n^2
2. Binary search
3. Newton's method | -| 368 | [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/368_Largest_Divisible_Subset.py) | Sort and generate x subset with previous results, O(n^2) and O(n^2) | -| 369 | [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/369_Plus_One_Linked_List.py) | 1. Stack or list that store the list, O(n) and O(n)
2. Two points, the first to the tail, the second to the latest place that is not 9, O(n) and O(1) | -| 370 | [Range Addition](https://leetcode.com/problems/range-addition/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/370_Range_Addition.py) | Interval problem with cumulative sums, O(n + k) and O(n) | -| 380 | [Insert, Delete, Get Random](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/380_Insert_Delete_GetRandom.py)| Uses both a list of nums and a list of their locations | -| 383 | [Ransom Note](https://leetcode.com/problems/ransom-note/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/383_Ransom_Note.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/383_Ransom_Note.java) | Get letter frequency (table or hash map) of magazine, then check randomNote frequency | -| 384 | [Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/384_Shuffle_an_Array.py) | [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle), O(n) and O(n) | -| 387 | [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/387_First_Unique_Character_in_a_String.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/387_First_Unique_Character_in_a_String.java) | Get frequency of each letter, return first letter with frequency 1, O(n) and O(1) | -| 388 | [Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/388_Longest_Absolute_File_Path.py) | Store last length and rindex, O(n) and O(n) | -| 389 | [Find the Difference](https://leetcode.com/problems/find-the-difference/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/389_Find_the_Difference.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/389_Find_the_Difference.java) | 1. Imaging letter a as 0, then the sum(t)-sum(s) is the result
2. Based on solution 1, bit manipulate | -| 400 | [Nth Digit](https://leetcode.com/problems/nth-digit/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/400_Nth_Digit.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/400_Nth_Digit.java) | islands * 4 - overlaps * 2 | -| 401 | [Binary Watch](https://leetcode.com/problems/binary-watch/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/401_Binary_Watch.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/401_Binary_Watch.java) | Note that 12 * 60 is much less than 2^n or n^2. | -| 404 | [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/404_Sum_of_Left_Leaves.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/404_Sum_of_Left_Leaves.java) | 1. Recursively DFS with root.left.left and root.left.right check
2. The same DFS based on stack | -| 405 | [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/405_Convert_a_Number_to_Hexadecimal.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/405_Convert_a_Number_to_Hexadecimal.java) | [Two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) 1. Bit manipulate, each time handle 4 digits
2. Python (hex) and Java API (toHexString & Integer.toHexString) | -| 408 | [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/408_Valid_Word_Abbreviation.py) | Go over abbr and word, O(n) and O(1) | -| 409 | [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/409_Longest_Palindrome.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/409_Longest_Palindrome.java) | Length of Palindrome is always 2n or 2n + 1. So, get all possible 2*n, and choose a single one as 1 if it exists. | -| 412 | [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/412_Fizz_Buzz.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/412_Fizz_Buzz.java) [Cpp](https://github.com/qiyuangong/leetcode/blob/master/cpp/412_Fizz_Buzz.cpp) | 1. From 1 to n, condition check
2. Condition check and string connect | -| 414 | [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/414_Third_Maximum_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/414_Third_Maximum_Number.java) | 1. Keep max 1-3 then compare, O(n) and O(1)
2. PriorityQueue, O(n) and O(1) | -| 415 | [Add Strings](https://leetcode.com/problems/add-strings/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/415_Add_Strings.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/415_Add_Strings.java) | Two points, careful abour carry, O(n) and O(n) | -| 416 | [Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/416_Partition_Equal_Subset_Sum.py) | DP, Check if sum of some elements can be half of total sum, O(total_sum / 2 * n) and O(total_sum / 2) | -| 421 | [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/421_Maximum_XOR_of_Two_Numbers_in_an_Array.py) | Check 0~32 prefix, check if there is x y in prefixes, where x ^ y = answer ^ 1, O(32n) and O(n) | -| 422 | [Valid Word Square](https://leetcode.com/problems/valid-word-square/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/422_Valid_Word_Square.py) | Compare row with column, O(n^2) | -| 434 | [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/434_Number_of_Segments_in_a_String.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/434_Number_of_Segments_in_a_String.java) | 1. trim &split
2. Find segment in place | -| 437 | [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/437_Path_Sum_III.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/437_Path_Sum_III.java) | 1. Recursively travese the whole tree, O(n^2)
2. Cache sum in Hash based on solution 1. Note that if sum(A->B)=target, then sum(root->a)-sum(root-b)=target.| -| 438 | [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/438_Find_All_Anagrams_in_a_String.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/438_Find_All_Anagrams_in_a_String.java) | Build a char count list with 26-256 length. Note that this list can be update when going through the string. O(n) and O(1) | -| 441 | [Arranging Coins](https://leetcode.com/problems/arranging-coins/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/441_Arranging_Coins.py) | O(n) time. | -| 443 | [String Compression](https://leetcode.com/problems/string-compression/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/443_String_Compression.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/443_String_Compression.java) | Maintain curr, read, write and anchor (start of this char). | -| 448 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/448_Find_All_Numbers_Disappeared_in_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/448_Find_All_Numbers_Disappeared_in_an_Array.java) | Value (1, n) and index (0, n-1). Mark every value postion as negative. Then, the remain index with positive values are result. O(n)| -| 453 | [Number of Segments in a String](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/453_Minimum_Moves_to_Equal_Array_Elements.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/453_Minimum_Moves_to_Equal_Array_Elements.java) | Each move is equal to minus one element in array, so the answer is the sum of all elements after minus min. | -| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/458_Poor_Pigs.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/458_Poor_Pigs.java) | [2 pigs for 5 * 5 metric](https://leetcode.com/problems/poor-pigs/discuss/94266/Another-explanation-and-solution) | -| 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/461_Hamming_Distance.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/461_Hamming_Distance.java) | Hamming Distance is related to XOR for numbers. So, XOR then count 1. O(n) | -| 463 | [Island Perimeter](https://leetcode.com/problems/island-perimeter/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/463_Island_Perimeter.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/463_Island_Perimeter.java) | math, find the area, actual number, then find the digit | -| 475 | [Heaters](https://leetcode.com/problems/heaters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/475_Heaters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/475_Heaters.java) | 1. Binary search hourse in heater array, O(nlogn) and O(1)
2. Two points, O(nlogn) and O(1) | -| 479 | [Largest Palindrome Product](https://leetcode.com/problems/largest-palindrome-product/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/479_Largest_Palindrome_Product.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/479_Largest_Palindrome_Product.java) | 1. Product max palindrome than check, O(n^2) and O(1)
2. [Math](https://leetcode.com/problems/largest-palindrome-product/discuss/96305/Python-Solution-Using-Math-In-48ms) | -| 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/482_License_Key_Formatting.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/482_License_Key_Formatting.java) | String processing, lower and len % K, O(n) and O(n) | -| 485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/485_Max_Consecutive_Ones.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/485_Max_Consecutive_Ones.java) | Add one when encounter 1, set to 0 when encounter 0, O(n) and O(1) | -| 509 | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/509_Fibonacci_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/509_Fibonacci_Number.java) | 1. Recursive, O(n)
2. DP with memo, O(n). Note that N<=30, which means that we can keep a memo from 0 to 30. | -| 523 | [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/523_Continuous_Subarray_Sum.py) | O(n) solution using dict() | -| 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | -| 541 | [Reverse String II](https://leetcode.com/problems/reverse-string-ii/solution/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/541_Reverse_String_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/541_Reverse_String_II.java) | Handle each 2k until reaching end, On(n) and O(n) | -| 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | -| 547 | [Friend Circles](https://leetcode.com/problems/friend-circles/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/547_Friend_Circles.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/547_Friend_Circles.java) | 1. DFS, O(n^2) and O(1)
2. BFS, O(n^2) and O(1)
3. Union-find, O(n^2) and O(n)| -| 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/557_Reverse_Words_in_a_String_III.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/557_Reverse_Words_in_a_String_III.java) | String handle: Split with space than reverse word, O(n) and O(n). Better solution is that reverse can be O(1) space in array. | -| 560 | [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/560_Subarray_Sum_Equals_K.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/560_Subarray_Sum_Equals_K.java) | Note that there are n^2 possible pairs, so the key point is accelerate computation for sum and reduce unnecessary pair. 1. Cummulative sum, O(n^2) and O(1)/O(n)
2. Add sum into hash, check if sum - k is in hash, O(n) and O(n) | -| 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/572_Subtree_of_Another_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/572_Subtree_of_Another_Tree.java) | 1. Tree traverse and compare
2. Tree to string and compare | -| 581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/581_Shortest_Unsorted_Continuous_Subarray.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/581_Shortest_Unsorted_Continuous_Subarray.java) | 1. Sort and find the difference (min and max), O(nlgn)
2. Using stack to find boundaries (push when correct order, pop when not correct), O(n) and O(n)
3. Find min and max of unordered array, O(n) and O(1)| -| 605 | [Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/605_Can_Place_Flowers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/605_Can_Place_Flowers.java) | One time scan, check [i-1] [i] and [i+1], O(n) and O(1) | -| 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/617_Merge_Two_Binary_Trees.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/617_Merge_Two_Binary_Trees.java) | Traverse both trees Recursion & Iterative (stack) | -| 628 | [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/628_Maximum_Product_of_Three_Numbers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/628_Maximum_Product_of_Three_Numbers.java) | Actually, we should only care about min1, min2 and max1-max3, to find these five elements, we can use 1. Brute force, O(n^3) and O(1)
2. Sort, O(nlogn) and O(1)
3. Single scan with 5 elements keep, O(n) and O(1) | -| 654 | [Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/654_Maximum_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/654_Maximum_Binary_Tree.java) | 1. Divide and conquer, recursive, O(n^2)
2. Monotonic stack, O(n) | -| 665 | [Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/665_Non-decreasing_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/665_Non-decreasing_Array.java) | 1. Find the broken index, then check this point, O(n) and O(1)
2. Replace broken point with correct value, then check if there are more than 1 broken point, O(n) and O(1) | -| 668 | [Kth Smallest Number in Multiplication Table](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/668_Kth_Smallest_Number_in_Multiplication_Table.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/668_Kth_Smallest_Number_in_Multiplication_Table.java) [Cpp](https://github.com/qiyuangong/leetcode/blob/master/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp) | Binary search, O(mlog(mn) and O(1) | -| 671 | [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/671_Second_Minimum_Node_In_a_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/671_Second_Minimum_Node_In_a_Binary_Tree.java) | Note that min value is root: 1. Get all values then find result, O(n) and O(n)
2. BFS or DFS traverse the tree, then find the reslut, O(n) and O(n)| -| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/674_Longest_Continuous_Increasing_Subsequence.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/674_Longest_Continuous_Increasing_Subsequence.java) | Scan nums once, check nums[i] < nums[i+1], if not reset count, O(n) and O(1) | -| 680 | [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/680_Valid_Palindrome_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/680_Valid_Palindrome_II.java) | Recursively check s[left == end, when not equal delete left or right. | -| 692 | [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/692_Top_K_Frequent_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/692_Top_K_Frequent_Words.java) | 1. Sort based on frequency and alphabetical order, O(nlgn) and O(n)
2. Find top k with Heap, O(nlogk) and O(n) | -| 695 | [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/695_Max_Area_of_Island.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/695_Max_Area_of_Island.java) | 1. DFS, O(n^2) and O(n)
2. BFS, O(n^2) and O(n)| -| 697 | [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/697_Degree_of_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/697_Degree_of_an_Array.java) | 1. Find degree and value, then find smallest subarray (start and end with this value), O(n) and O(n)
2. Go through nums, remember left most pos and right most for each value, O(n) and O(n) | -| 700 | [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/700_Search_in_a_Binary_Search_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/700_Search_in_a_Binary_Search_Tree.java) | Recursive or iteration, O(logn) | -| 703 | [Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/703_Kth_Largest_Element_in_a_Stream.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/703_Kth_Largest_Element_in_a_Stream.java) | 1. Sort and insert into right place, O(nlgn) and O(n)
2. k largest heap, O(nlogk) and O(n) | -| 706 | [Design HashMap](https://leetcode.com/problems/design-hashmap/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/706_Design_HashMap.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/706_Design_HashMap.java) | Hash implementation, mod is fine. Be careful about key conflict and key remove. | -| 709 | [To Lower Case](https://leetcode.com/problems/to-lower-case/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/709_To_Lower_Case.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/709_To_Lower_Case.java) | String processing:
1. str.lower() or str.toLowerCase()
2. ASCII processing. O(n) and O(1) | -| 716 | [Max Stack](https://leetcode.com/problems/max-stack/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/716_Max_Stack.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/716_Max_Stack.java) | 1. Two stacks
2. Double linked list and Hash | -| 717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/717_1-bit_and_2-bit_Characters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/717_1-bit_and_2-bit_Characters.java) | 1. Go through bits, 1 skip next, O(n) and O(1)
2. Find second last zero reversely, O(n) and O(1) | -| 720 | [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/720_Longest_Word_in_Dictionary.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/720_Longest_Word_in_Dictionary.java) | 1. Brute Force, O(sum(w^2)) and O(w)
2. Tire Tree, O(sum(w) and O(w))
3. Sort and word without last char, O(nlogn + sum(w)) and O(w) | -| 724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/724_Find_Pivot_Index.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/724_Find_Pivot_Index.java) | Seach the array to find a place where left sum is equal to right sum, O(n) and O(1) | -| 728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/solution/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/728_Self_Dividing_Numbers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/728_Self_Dividing_Numbers.java) | Brute Force check every digit, O(nlogD) and O(1) | -| 733 | [Flood Fill](https://leetcode.com/problems/flood-fill/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/733_Flood_Fill.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/733_Flood_Fill.java) | 1. DFS with stack or recursive, O(n) and O(n)
2. BFS with queue, O(n) and O(n) | -| 743 | [Network Delay Time](https://leetcode.com/problems/network-delay-time/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/743_Network_Delay_Time.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/743_Network_Delay_Time.java) | Let V == N, then: 1. DFS, O(V^V+ElgE), O(V+E)
2. Dijkstra, O(V^2+E), O(V+E)| -| 751 | [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/751_IP_to_CIDR.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/751_IP_to_CIDR.java) | Bit manipulations, incrementail is 1 << (32 - mask) | -| 760 | [Find Anagram Mappings](https://leetcode.com/problems/find-anagram-mappings/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/760_Find_Anagram_Mappings.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/760_Find_Anagram_Mappings.java) | Hash table with A's (val, index), O(n) and O(n) | -| 766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/766_Toeplitz_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/766_Toeplitz_Matrix.java) | Check from top left to bottom right, i,j == i + 1, j + 1. | -| 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/771_Jewels_and_Stones.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/771_Jewels_and_Stones.java) | Count given char in string. Hash or table. [Oneline](https://leetcode.com/problems/jewels-and-stones/discuss/113574/1-liners-PythonJavaRuby) | -| 784 | [Letter Case Permutation](https://leetcode.com/problems/letter-case-permutation/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/784_Letter_Case_Permutation.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/784_Letter_Case_Permutation.java) | Note that this is a 2^n problem. 1. Recursively generate result with previous result
2. Bin Mask, number of zeor equal to number of alpha
3. Python build in product. | -| 804 | [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/804_Unique_Morse_Code_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/804_Unique_Morse_Code_Words.java) | String, Hash and Set. Set is recommended. | -| 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/811_Subdomain_Visit_Count.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/811_Subdomain_Visit_Count.java) | String split and HashMap, O(n) and O(n) | -| 819 | [Most Common Word](https://leetcode.com/problems/most-common-word/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/819_Most_Common_Word.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/819_Most_Common_Word.java) | String processing, be careful about 'b,b,b'. regex is recommended. | -| 832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/832_Flipping_an_Image.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/832_Flipping_an_Image.java) | Invert and swap can be done at the same time, and careful about (n + 1)/2, O(n^2) and O(1) | -| 836 | [Rectangle Overlap](https://leetcode.com/problems/rectangle-overlap/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/836_Rectangle_Overlap.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/836_Rectangle_Overlap.java) | 1. Check position, O(1) and O(1)
2. Check area, O(1) and O(1) | -| 844 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/844_Backspace_String_Compare.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/844_Backspace_String_Compare.java) | 1. Stack pop when encounters #, O(n) and O(n)
2. Compare string from end to start, O(n) and O(1) | -| 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/852_Peak_Index_in_a_Mountain_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/852_Peak_Index_in_a_Mountain_Array.java) | 1. Scan the array until encountering decline, O(n) and O(1)
2. Binary seach with additional check for [i + 1], O(logn) and O(1) | -| 867 | [Transpose Matrix](https://leetcode.com/problems/transpose-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/867_Transpose_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/867_Transpose_Matrix.java) | Res[i][j] = A[j][i] | -| 868 | [Binary Gap](https://leetcode.com/problems/binary-gap/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/868_Binary_Gap.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/868_Binary_Gap.java) | 1. Store index and check, O(logn) and O(logn)
2. One pass and store max, O(logn) and O(1) | -| 872 | [Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/872_Leaf-Similar_Trees.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/872_Leaf-Similar_Trees.java) | DFS (stack or recursion) get leaf value sequence and compare, O(n) and O(n) | -| 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/876_Middle_of_the_Linked_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/876_Middle_of_the_Linked_List.java) | 1. Copy to array, O(n) and O(n)
2. Fast and slow point, where fast point is 2 times faster than slow point, O(n) and O(1) | -| 904 | [Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/904_Fruit_Into_Baskets.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/904_Fruit_Into_Baskets.java) | 1. Scan through blocks of tree, O(n) and O(n)
2. Mainten a sliding window with start and curr point, O(n) and O(n). | -| 905 | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/905_Sort_Array_By_Parity.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/905_Sort_Array_By_Parity.java) | 1. Sort with condition, O(nlogn) and O(1)
2. Scan all and split odd and even number into different array, O(n) and O(n)
3. In place swap similar to quick sort, O(n) and O(1) | -| 922 | [Sort Array By Parity II](https://leetcode.com/problems/sort-array-by-parity-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/922_Sort_Array_By_Parity_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/922_Sort_Array_By_Parity_II.java) | 1. Place odd and even number in odd and even place, not sort is needed. O(n) and O(1)
2. Two points with quick sort swap idea, O(n) and O(1). | -| 929 | [Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/929_Unique_Email_Addresses.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/929_Unique_Email_Addresses.java) | String handle and hash (or set) | -| 933 | [Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/933_Number_of_Recent_Calls.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/933_Number_of_Recent_Calls.java) | Queue, remove val in head when val < t - 3000, O(n) and O(n) | -| 937 | [Reorder Log Files](https://leetcode.com/problems/reorder-log-files/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/937_Reorder_Log_Files.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/937_Reorder_Log_Files.java) | 1. Comstom Sort, O(nlogn) and O(1)
2. Separete letter logs and digit logs, then sort letter logs and merge with digit logs, O(nlogn) and O(n) | -| 945 | [Minimum Increment to Make Array Unique](https://leetcode.com/problems/minimum-increment-to-make-array-unique/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/945_Minimum_Increment_to_Make_Array_Unique.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/945_Minimum_Increment_to_Make_Array_Unique.java) | Sort, then list duplicate and missing value in sorted list. O(nlgn) and O(n) | -| 946 | [Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/946_Validate_Stack_Sequences.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/946_Validate_Stack_Sequences.java) | Add a stack named inStack to help going through pushed and popped. O(n) and O(n) | -| 953 | [Verifying an Alien Dictionary](https://leetcode.com/contest/weekly-contest-114/problems/verifying-an-alien-dictionary/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/953_Verifying_an_Alien_Dictionary.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/953_Verifying_an_Alien_Dictionary.java) | Use hashmap to store index of each value, then create a comparator based on this index, O(n) and O(n) | -| 954 | [Array of Doubled Pairs](https://leetcode.com/contest/weekly-contest-114/problems/array-of-doubled-pairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/954_Array_of_Doubled_Pairs.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/954_Array_of_Doubled_Pairs.java) | Sort, then use hashmap to store the frequency of each value. Then, check n, 2 * n in hashmap, O(nlogn) and O(n) | -| 961 | [N-Repeated Element in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/961_N-Repeated_Element_in_Size_2N_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/961_N-Repeated_Element_in_Size_2N_Array.java) | Hash and count number, O(n) and O(n) | -| 962 | [Maximum Width Ramp](https://leetcode.com/problems/maximum-width-ramp/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/962_Maximum_Width_Ramp.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/962_Maximum_Width_Ramp.java) | 1. Sort index by value, then transfer problem into finding max gap between index, O(nlogn) and O(1)
2. Binary Search for candicates, O(nlogn) and O(n) | -| 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/977_Squares_of_a_Sorted_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/977_Squares_of_a_Sorted_Array.java) | 1. Sort, O(nlogn) and O(n)
2. Two point, O(n) and O(n) | -| 973 | [K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/973_K_Closest_Points_to_Origin.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/973_K_Closest_Points_to_Origin.java) | 1. Sort and get 0-K, O(nlogn) and O(1)
2. Min Heap, O(nlogk) and O(k) | -| 981 | [Time Based Key-Value Store](https://leetcode.com/problems/time-based-key-value-store/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/981_Time_Based_Store.py) | Get: O(log(n)) time
Set: O(1) time | -| 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1064_Fixed_Point.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1064_Fixed_Point.java) | 1. Go through index and value, until find solution encounter index < value, O(n) and O(1)
2. Binary search, O(logn) and O(1) | -| 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1089_Duplicate_Zeros.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1089_Duplicate_Zeros.java) | 2 Pass, store last position and final move steps, O(n) and O(1) | -| 1108 | [Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1108_Defanging_an_IP_Address.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1108_Defanging_an_IP_Address.java) | String manipulate (split, replace and join), O(n) and O(n) | -| 1189 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1189_Maximum_Number_of_Balloons.java) | Count letters in `balon`, then find min, O(n) and O(1) | -| 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | -| 1290 | [Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py) | Take 2 to the power digit position from right (starting from 0) and multiply it with the digit | -| 1304 | [Find N Unique Integers Sum up to Zero](https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java) | [1,n-1] and its negative sum | -| 1310 | [XOR Queries of a Subarray](https://leetcode.com/problems/xor-queries-of-a-subarray) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1310_XOR_Queries_of_a_Subarray.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1310_XOR_Queries_of_a_Subarray.java) [Cpp](https://github.com/qiyuangong/leetcode/blob/master/cpp/1310_XOR_Queries_of_a_Subarray.cpp) | Compute accumulated xor from head, qeury result equals to xor[0, l] xor x[0, r], O(n) and O(n) | -| 1323 | [Maximum 69 Number](https://leetcode.com/problems/maximum-69-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1323_Maximum_69_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1323_Maximum_69_Number.java) | 9 is greater than 6, so change first 6 to 9 from left if exist, O(n) and O(1) | -| 1337 | [The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1337_The_K_Weakest_Rows_in_a_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1337_The_K_Weakest_Rows_in_a_Matrix.java) | Check by row, from left to right, until encount first zero, O(mn) and O(1) | -| 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py) | If number is divisible by 2, divide the number by 2, else subtract 1 from the number, and output the number of steps, O(logn) and O(1) | -| 1365 | [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java) | 1. Sort and get position in sorted nums, O(nlogn) and O(n)
2. Fill count into 0-100, O(n) and O(1) | -| 1480 | [Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1480_Running_Sum_of_1d_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1480_Running_Sum_of_1d_Array.java) | 1. Go through the array, O(n) and O(1)
2. Accumulate API | -| 1539 | [Kth Missing Positive Number](https://leetcode.com/problems/kth-missing-positive-number/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1539_Kth_Missing_Positive_Number.java) | Binary search, num of missing = arr[i]-i-1 | -| 1909 | [Remove One Element to Make the Array Strictly Increasing](https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py )| Use brute-force. O( (nums.length)2) | -| 1981 | [Minimize the Difference Between Target and Chosen Elements](https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java) | DP memo[row][sum] to avoid recomputing | -| 2409 | [Count Days Spent Together](https://leetcode.com/problems/count-days-spent-together/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2409_Count_Days_Spent_Together.py)| Use month as a day | -| 2413 | [Smallest Even Multiple](https://leetcode.com/problems/smallest-even-multiple/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2413_Smallest_Even_Multiple.py)| Check the n is multiply by 2 | -| 2429 | [Minimize XOR](https://leetcode.com/problems/minimize-xor/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2429_Minimize_XOR.py.py) | check the num1, num2 with length and replace "0" compare with num1. | +| # | Title | Solution | Basic idea (One line) | +|------|----------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/001_Two_Sum.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/001_Two_Sum.java) | 1. Hash O(n) and O(n) space.
2. Sort and search with two points O(n) and O(1) space. | +| 2 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/002_Add_Two_Numbers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/002_Add_Two_Numbers.java) | Take care of the carry from lower digit. | +| 3 | [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/003_Longest_Substring_Without_Repeating_Characters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/003_Longest_Substring_Without_Repeating_Characters.java) | 1. Check every possible substring O(n^2)
2. Remember the character index and current check pos, if character index >= current pos, then there is duplicate | +| 4 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/004_Median_of_Two_Sorted_Arrays.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/004_Median_of_Two_Sorted_Arrays.java) | 1. Merge two sorted lists and compute median, O(m + n) and O(m + n)
2. An extension of median of two sorted arrays of equal size problem | +| 5 | [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/005_Longest_Palindromic_Substring.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/005_Longest_Palindromic_Substring.java) | [Background knowledge](http://en.wikipedia.org/wiki/Longest_palindromic_substring)
1. DP if s[i]==s[j] and P[i+1, j-1] then P[i,j]
2. A palindrome can be expanded from its center
3. Manacher algorithm | +| 7 | [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/007_Reverse_Integer.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/007_Reverse_Integer.java) | Overflow when the result is greater than 2147483647 or less than -2147483648. | +| 8 | [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/008_String_to_Integer(atoi).py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/008_String_to_Integer(atoi).java) | Overflow, Space, and negative number | +| 9 | [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/009_Palindrome_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/009_Palindrome_Number.java) | Get the len and check left and right with 10^len, 10 | +| 11 | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/011_Container_With_Most_Water.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/011_Container_With_Most_Water.java) | 1. Brute Force, O(n^2) and O(1)
2. Two points, O(n) and O(1) | +| 12 | [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/012_Integer_to_Roman.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/012_Integer_to_Roman.java) | [Background knowledge](http://www.rapidtables.com/convert/number/how-number-to-roman-numerals.htm) Just like 10-digit number, divide and minus | +| 13 | [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/013_Roman_to_Integer.py) | Add all curr, if curr > prev, then need to subtract 2 * prev | +| 15 | [3Sum](https://leetcode.com/problems/3sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/015_3Sum.py) | 1. Sort and O(n^2) search with three points
2. Multiple Two Sum (Problem 1) | +| 16 | [3Sum Closest](https://leetcode.com/problems/3sum-closest/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/016_3Sum_Closest.py) | Sort and Multiple Two Sum check abs | +| 18 | [4Sum](https://leetcode.com/problems/4sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/018_4Sum.py) | The same as 3Sum, but we can merge pairs with the same sum | +| 19 | [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/019_Remove_Nth_Node_From_End_of_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/019_Remove_Nth_Node_From_End_of_List.java) | 1. Go through list and get length, then remove length-n, O(n) and O(n)
2. Two pointers, first pointer goes to n position, then move both pointers until reach tail, O(n) and O(n) | +| 20 | [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/020_Valid_Parentheses.py) | 1. Stack
2. Replace all parentheses with '', if empty then True | +| 21 | [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/021_Merge_Two_Sorted_Lists.py) | Add a dummy head, then merge two sorted list in O(m+n) | +| 23 | [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/023_Merge_k_Sorted_Lists.py) | 1. Priority queue O(nk log k)
2. Binary merge O(nk log k) | | +| 24 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/024_Swap_Nodes_in_Pairs.py) | Add a dummy and store the prev | +| 28 | [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/028_Implement_strStr().py) | 1. O(nm) comparison
2. KMP | +| 35 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/035_Search_Insert_Position.py) | Binary Search | +| 46 | [Permutations](https://leetcode.com/problems/permutations/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/046_Permutations.py) | 1. Python itertools.permutations
2. DFS with swapping, O(n^2) and O(n^2)
3. iteratively generate n-permutations with (n-1)-permutations, O(n^3) and O(n^2) | +| 47 | [Permutations II](https://leetcode.com/problems/permutations-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/047_Permutations_II.py) | 1. DFS with swapping, check duplicate, O(n^2) and O(n^2)
2. iteratively generate n-permutations with (n-1)-permutations, O(n^3) and O(n^2) | +| 53 | [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/053_Maximum_Subarray.py) | 1. Recursion, O(nlgn), O(lgn)
2. Bottom-up DP, O(n) and O(n)
3. Bottom-up DP, f(x) = max(f(x-1)+A[x], A[x]), f(x) = max(f(x-1)+A[x], A[x]),O(n) and O(1) | +| 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/054_Spiral_Matrix.py) | O(nm) 1. Turn in the corner and loop
2. (0, 1) -> (1, 0) -> (0, -1) -> (-1, 0) | +| 62 | [Unique Paths](https://leetcode.com/problems/unique-paths/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/062_Unique_Paths.py) | 1. Bottom-up DP, dp[i][j] = dmap[i-1][j] + dmap[i][j-1], O(mn) and O(mn)
2. Combination (m+n-2, m-1) | +| 63 | [Unique Paths II](https://leetcode.com/problems/unique-paths-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/063_Unique_Paths_II.py) | Bottom-up DP, dp[i][j] = dmap[i-1][j] + dmap[i][j-1] (if block, then 0), O(mn) and O(mn) | +| 65 | [Valid Number](https://leetcode.com/problems/valid-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/065_Valid_Number.py) | 1. strip leading and tailing space, then check float using exception, check e using split
2. check is number split by . or e, note that number after e may be negative | +| 66 | [Plus One](https://leetcode.com/problems/plus-one/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/066_Plus_One.py) | Check if current digit == 9. | +| 70 | [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/070_Climbing_Stairs.py) | Bottom-up DP, dp[i] = dp[i - 2] + dp[i- 1]
1. O(n) and O(n)
2. Only two variables are needed, O(n) and O(1) | +| 72 | [Edit Distance](https://leetcode.com/problems/edit-distance/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/072_Edit_Distance.py) | [Background](https://en.wikipedia.org/wiki/Edit_distance)
1. DP O(n^2) space
2. DP O(n) space | +| 78 | [Subsets](https://leetcode.com/problems/subsets/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/078_Subsets.py) | 1. DFS Recursion, O(2^n) and O(2^n)
2. Recursion on a binary number, O(2^n) and O(2^n)
3. Sort and iteratively generate n subset with n-1 subset, O(n^2) and O(2^n) | +| 90 | [Subsets II](https://leetcode.com/problems/subsets-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/090_Subsets_II.py) | 1. DFS Recursion with duplicate check, O(2^n) and O(2^n)
2. Recursion on a binary number, O(2^n) and O(2^n)
3. Sort and iteratively generate n subset with n-1 subset, note that if nums[index] == nums[index - 1] then generate from last end to curr end, O(n^2) and O(2^n) | +| 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/094_Binary_Tree_Inorder_Traversal.py) | 1. Recursion, O(n) and O(1)
2. Stack and check isinstance(curr, TreeNode), O(n) and O(n)
3. Stack and check left and right, O(n) and O(n) | +| 98 | [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/098_Validate_Binary_Search_Tree.py) | 1. Stack O(n) and O(n)
2. Recursion O(n) and O(n) | +| 104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/104_Maximum_Depth_of_Binary_Tree.py) | Recursion max(left, right) + 1 | +| 108 | [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/108_Convert_Sorted_Array_to_Binary_Search_Tree.py) | Recursion O(n) and O(nlgn) | +| 109 | [Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/109_Convert_Sorted_List_to_Binary_Search_Tree.py) | 1. Two points fast (next next) and slow (next) O(nlgn) and O(n)
2. Bottom-up recursion O(n) and O(lgn) | +| 110 | [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/110_Balanced_Binary_Tree.py) | Recursion 1. Top-down O(n^2) and O(n), Bottom-up recursion with sentinel -1 O(n) and O(n) | +| 111 | [Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/111_Minimum_Depth_of_Binary_Tree.py) | 1. Recursion, note that when size of left (ld) or right (rd) is 0, then min = 1 + ld + rd
2. BFS check by level (right most), which is much faster than recursion | +| 124 | [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/124_Binary_Tree_Maximum_Path_Sum.py) | Recursion O(n) and O(n), max (left + node, right + node, left + node + right) | +| 125 | [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/125_Valid_Palindrome.py) | Exclude non-alphanumeric characters and compare O(n) | +| 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/128_Longest_Consecutive_Sequence.py) | Set or hash, pop adjacency, O(n) and O(n) | +| 133 | [Clone Graph](https://leetcode.com/problems/clone-graph/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/133_Clone_Graph.py) | Hash and DFS or BFS | +| 136 | [Single Number](https://leetcode.com/problems/single-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/136_Single_Number.py) | 1. Hash or set, O(n) and O(n)
2. xor O(n) and O(1) | +| 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/137_Single_Number_II.py) | 1. ctypes 32 % 3 and &, O(n) and O(1)
2. ones, twos, threes as bitmask (e.g. ones represents ith bit had appeared once), O(n) and O(1) | +| 138 | [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/138_Copy_List_with_Random_Pointer.py) | 1. Hash O(n) and O(n)
2. Modify original structure: Original->Copy->Original, then node.next.random = node.random.next, O(n) and O(1) | +| 141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/141_Linked_List_Cycle.py) | 1. Hash or set
2. Two points (fast and slow)
3. Add a max and check if reach the max | +| 142 | [Linked List Cycle II](https://discuss.leetcode.com/topic/2975/o-n-solution-by-using-two-pointers-without-change-anything) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/142_Linked_List_Cycle_II.py) | Two points, a+b=nr | +| 143 | [Reorder List](https://leetcode.com/problems/reorder-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/143_Reorder_List.py) | 1. List as index to rebuild relation, O(n) and O(n)
2. Two points, O(n) and O(1) | +| 144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/144_Binary_Tree_Preorder_Traversal.py) | 1. Recursion, O(n) and O(n)
2. Stack, O(n) and O(n) | +| 145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/145_Binary_Tree_Postorder_Traversal.py) | 1. Recursion, O(n) and O(n)
2. Stack and queue (insert 0), O(n) and O(n)
3. Stack and isinstance(curr, TreeNode), O(n) and O(n) | +| 146 | [LRU Cache](https://leetcode.com/problems/lru-cache/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/146_LRU_Cache.py) | 1. Queue and dict
2. OrderedDict | +| 150 | [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/150_Evaluate_Reverse_Polish_Notation.py) | Stack | +| 151 | [Reverse Words in a String](https://discuss.leetcode.com/category/159/reverse-words-in-a-string) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/151_Reverse_Words_in_a_String.py) | 1. Python split by space
2. Reverse all and reverse words | +| 152 | [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/152_Maximum_Product_Subarray.py) | DP, f(k) = max(f(k-1) * A[k], A[k], g(k-1) * A[k]), g(k) = min(g(k-1) * A[k], A[k], f(k-1) * A[k]), O(n) and O(1) | +| 153 | [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/153_Find_Minimum_in_Rotated_Sorted_Array.py) | Binary search with conditions, A[l] > A[r] | +| 154 | [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/154_Find_Minimum_in_Rotated_Sorted_Array_II.py) | Binary search with conditions, A[l] > A[r], A[l]=A[mid]=A[r] | +| 155 | [Min Stack](https://leetcode.com/problems/min-stack/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/155_Min_Stack.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/155_Min_Stack.java) | Add another stack for min stack, maintance this stack when the main stack pop or push: 1. Only push min, such that len(minStack)<=len(Stack) 2. Push min again when current top is min, such that len(minStack)=len(Stack) | +| 156 | [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/156_Binary_Tree_Upside_Down.py) | p.left = parent.right, parent.right = p.right, p.right = parent, parent = p.left, p = left | +| 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/157_Read_N_Characters_Given_Read4.py) | Handle the edge case (the end) | +| 158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/158_Read_N_Characters_Given_Read4_II_Call_multiple_times.py) | Store the pos and offset that is read by last read4 | +| 159 | [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/159_Longest_Substring_with_At_Most_Two_Distinct_Characters.py) | Maintain a sliding window that always satisfies such condition | +| 161 | [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/161_One_Edit_Distance.py) | 1. Check the different position and conditions
2. [Edit distance](https://leetcode.com/problems/edit-distance/) | +| 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/163_Missing_Ranges.py) | Add -1 to lower for special case, then check if curr - prev >= 2 | +| 166 | [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/166_Fraction_to_Recurring_Decimal.py) | % and Hash to find duplicate | +| 167 | [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/167_Two_Sum_II_Input_array_is_sorted.py) | Two points O(n) and O(1) | +| 170 | [Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/170_Two_Sum_III-Data_structure_design.py) | 1. Hash, O(1) for add, O(n) for find, O(n) space
2. sorted list, O(logn) for add, O(n) for find, O(n) space
3. Sort before find, O(1) for add, O(nlogn) for find, O(n) space | +| 179 | [Largest Number](https://leetcode.com/problems/largest-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/179_Largest_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/179_Largest_Number.java) | Define a comparator with str(x) + str(y) > str(y) + str(x), O(nlgn) and O(n) | +| 186 | [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/186_Reverse_Words_in_a_String_II.py) | Reverse all and reverse each words | +| 198 | [House Robber](https://leetcode.com/problems/house-robber/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/198_House_Robber.py) | f(k) = max(f(k – 2) + num[k], f(k – 1)), O(n) and O(1) | +| 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/200_Number_of_Islands.py) | 1. Quick union find, O(nlogn) and O(n^2)
2. BFS with marks, O(n^2) and O(1) | +| 204 | [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/204_Count_Primes.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/204_Count_Primes.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/204_Count_Primes.cpp) | [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity), O(nloglogn) and O(n) | +| 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/206_Reverse_Linked_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/206_Reverse_Linked_List.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/206_Reverse_Linked_List.cpp) | 1. Stack, O(n) and O(n)
2. Traverse on prev and curr, then curr.next = prev, O(n) and O(1)
3. Recursion, O(n) and O(1) | +| 207 | [Course Schedule](https://leetcode.com/problems/course-schedule/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/207_Course_Schedule.py) | Cycle detection problem | +| 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/213_House_Robber_II.py) | f(k) = max(f(k – 2) + num[k], max(dp[0~ls-2],dp[1~ls-1], O(n) and O(1) | +| 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/215_Kth_Largest_Element_in_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/215_Kth_Largest_Element_in_an_Array.java) | 1. Sort, O(n) and O(n)
2. Heap, O(nlgk) and O(n)
3. Quick selection, O(klgn) and O(n) | +| 216 | [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/216_Combination_Sum_III.py) | Generate all combinations of length k and keep those that sum to n | +| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/217_Contains_Duplicate.py) | 1. Set and compare length
2. Sort and check i,i +1 | +| 219 | [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/219_Contains_Duplicate_II.py) | 1. Brute force
2. Maintenance a set that contains previous k numbers, and check if curr in set | +| 220 | [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/220_Contains_Duplicate_III.py) | 1. Sort and binary Search
2. Bucket sort | +| 221 | [Maximal Square](https://leetcode.com/problems/maximal-square/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/221_Maximal_Square.py) | 1. Brute force
2. dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1, O(mn) and O(mn)
3. dp[j] = min([j], dp[j-1], prev) + 1, O(mn) and O(n) | +| 223 | [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/223_Rectangle_Area.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/223_Rectangle_Area.java) | Rectangle A + B - common area, O(1) and O(1) | +| 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/228_Summary_Ranges.py) | Detect start and jump, O(n) and O(1) | +| 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/236_Lowest_Common_Ancestor_of_a_Binary_Tree.java) | 1. Recursive check left, val and right, LCA is the split paths in tree, O(n) and O(n)
2. Store parents during traversing tree, reverse check their lowest common parent, O(n) and O(n) | +| 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/238_Product_of_Array_Except_Self.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/238_Product_of_Array_Except_Self.java) | The ans is [0,i -1] * [i+1, len- 1]. We can twice for left and right (reverse), O(n) and O(n) | +| 243 | [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/243_Shortest_Word_Distance.py) | Update index1 and index2, and check distance, O(n) and O(1) | +| 246 | [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/246_Strobogrammatic_Number.py) | Hash table and reverse string, O(n) and O(n) | +| 249 | [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/249_Group_Shifted_Strings.py) | Hash and generate hash code for each string, O(n) and O(n) | +| 252 | [Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/252_Meeting_Rooms.py) | 1. Sort and compare intervals[i].end with intervals[i+1], O(nlogn) and O(1)
2. Sort and check intervals when count >= 2, O(nlogn) and O(n) | +| 253 | [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/253_Meeting_Rooms_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/253_Meeting_Rooms_II.java) | 1. Priority queue and sort, O(nlogn) and O(n)
2. Go through timeline. If it's a start then meeting + 1, else meeting - 1. The ans is the max(meeting) in timeline. O(nlogn) and O(n) | +| 259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/259_3Sum_Smaller.py) | 1. Reduce to two sum smaller, then binary search, O(n^2lgn) and O(1)
2. Reduce to two sum smaller, then two points, O(n^2) and O(1) | +| 266 | [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/266_Palindrome_Permutation.py) | Compute frequency, check number of odd occurrences <= 1 then palindrome, O(n) and O(n) | +| 267 | [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/267_Palindrome_Permutation_II.py) | Check palindrome then generate half with [Permutations II](https://leetcode.com/problems/permutations-ii/), O(n^2) and O(n^2) | +| 268 | [Missing Number](https://leetcode.com/problems/missing-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/268_Missing_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/268_Missing_Number.java) | 1. Find missing by n * (n - 1)/2 - sum(nums)
2. XOR with index
3. Sort and binary search | +| 270 | [Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/270_Closest_Binary_Search_Tree_Value.py) | 1. Recursively brute force, O(n) and O(n)
2. Recursively compare root result with current kid's result (left or right), O(logn) and O(logn)
3. Iteratively compare root result with current kid's result (left or right), O(logn) and O(logn) | +| 273 | [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/273_Integer_to_English_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/python/273_Integer_to_English_Words.java) | Careful about corner cases, such 1-20 and 21-Hundred, O(lgn) and O(1) | +| 274 | [H-Index](https://leetcode.com/problems/h-index/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/274_H-Index.py) | [Background](https://en.wikipedia.org/wiki/H-index)
1. Sort and check number of papers greater than h, O(nlogn) and O(1)
2. Counting sort, O(n) and O(n) | +| 276 | [Paint Fence](https://leetcode.com/problems/paint-fence/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/276_Paint_Fence.py) | ways[i>2] = (ways[i-1] + ways[i-2]) * (k - 1), O(n) and O(1) | +| 280 | [Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/280_Wiggle_Sort.py) | 1. Sort and insert (n - 1) / 2 from tail to correct position, O(nlogn) and O(1)
2. Sort and swap(i, i + 1) from 1 to n - 1, O(nlogn)
3. Iteratively check order and reverse order, if not satisfied, then swap i with i + 1, O(n) | +| 286 | [Walls and Gates](https://leetcode.com/problems/walls-and-gates/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/286_Walls_and_Gates.py) | BFS with queue, O(mn) and O(mn) | +| 288 | [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/288_Unique_Word_Abbreviation.py) | hash | +| 293 | [Flip Game](https://leetcode.com/problems/flip-game/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/293_Flip_Game.py) | Python string slicing | +| 294 | [Flip Game II](https://leetcode.com/problems/flip-game-ii/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/294_Flip_Game_II.py) | 1. Backtracking to ensure that next step is False, O(n!!) and O(n!!)
2. Backtracking with memo, O(n!!) and O(n!)
3. DP based on [Sprague-Grundy Function](https://discuss.leetcode.com/topic/27282/theory-matters-from-backtracking-128ms-to-dp-0ms) | +| 296 | [Best Meeting Point](https://leetcode.com/problems/best-meeting-point/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/296_Best_Meeting_Point.py) | Think hard about Manhattan Distance in 1D case. Sort and find mean, O(mnlogmn) and O(1) | +| 298 | [Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/298_Binary_Tree_Longest_Consecutive_Sequence.py) | Bottom-up or top-down recursion, O(n) and O(n) | +| 305 | [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/305_Number_of_Islands_II.py) | Quick union find with weights, O(nlogn) and O(n) | +| 322 | [Coin Change](https://leetcode.com/problems/coin-change/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/322_Coin_Change.py) | Bottom-up or top-down DP, dp[n] = min(dp[n], dp[n - v_i]), where v_i is the coin, O(amount * n) and O(amount) | +| 336 | [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/336_Palindrome_Pairs.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/336_Palindrome_Pairs.java) | 1. Create a reverse word to index map, then for each word, check prefix and posfix, O(nk^2) and O(n)
2. Tire tree, O(nk^2) and O(n) | +| 337 | [House Robber III](https://leetcode.com/problems/house-robber-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/337_House_Robber_III.py) | 1. Recursion with hash map, O(n) and O(n)
2. Recursion on two steps, O(n) and O(1) | +| 339 | [Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/339_Nested_List_Weight_Sum.py) | Depth-first recursion | +| 340 | [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/340_Longest_Substring_with_At_Most_K_Distinct_Characters.py) | Maintain a sliding window with at most k distinct characters and a count for this window. Note that the start position need a loop to update. | +| 346 | [Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/346_Moving_Average_from_Data_Stream.py) | fix-sized queue or dequeue, O(1) and O(n) | +| 347 | [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/347_Top_K_Frequent_Elements.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/347_Top_K_Frequent_Elements.java) | 1. Sort by frequency, O(nlogn) and O(n).
2. we can build a min heaq (based on frequency), then pop min until there are k element, O(klgn) and O(n) | +| 351 | [Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/351_Android_Unlock_Patterns.py) | Backtracking, O(n!) and O(n) | +| 359 | [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/359_Logger_Rate_Limiter.py) | 1. hash which stores the latest timestamp, O(1) and O(n)
2. Using Priority queue to remove older logs, O(n) and O(n) | +| 366 | [Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/366_Find_Leaves_of_Binary_Tree.py) | 1. Set or hash to check leaft, O(n^2) and O(n)
2. Recursively check level and return them, O(n) and O(n) | +| 367 | [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/367_Valid_Perfect_Square.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/367_Valid_Perfect_Square.java) | [Integer square root](https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division)
1. 1+3+…+(2n-1) = n^2
2. Binary search
3. Newton's method | +| 368 | [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/368_Largest_Divisible_Subset.py) | Sort and generate x subset with previous results, O(n^2) and O(n^2) | +| 369 | [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/369_Plus_One_Linked_List.py) | 1. Stack or list that store the list, O(n) and O(n)
2. Two points, the first to the tail, the second to the latest place that is not 9, O(n) and O(1) | +| 370 | [Range Addition](https://leetcode.com/problems/range-addition/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/370_Range_Addition.py) | Interval problem with cumulative sums, O(n + k) and O(n) | +| 380 | [Insert, Delete, Get Random](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/380_Insert_Delete_GetRandom.py) | Uses both a list of nums and a list of their locations | +| 383 | [Ransom Note](https://leetcode.com/problems/ransom-note/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/383_Ransom_Note.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/383_Ransom_Note.java) | Get letter frequency (table or hash map) of magazine, then check randomNote frequency | +| 384 | [Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/384_Shuffle_an_Array.py) | [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle), O(n) and O(n) | +| 387 | [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/387_First_Unique_Character_in_a_String.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/387_First_Unique_Character_in_a_String.java) | Get frequency of each letter, return first letter with frequency 1, O(n) and O(1) | +| 388 | [Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/388_Longest_Absolute_File_Path.py) | Store last length and rindex, O(n) and O(n) | +| 389 | [Find the Difference](https://leetcode.com/problems/find-the-difference/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/389_Find_the_Difference.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/389_Find_the_Difference.java) | 1. Imaging letter a as 0, then the sum(t)-sum(s) is the result
2. Based on solution 1, bit manipulate | +| 400 | [Nth Digit](https://leetcode.com/problems/nth-digit/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/400_Nth_Digit.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/400_Nth_Digit.java) | islands * 4 - overlaps * 2 | +| 401 | [Binary Watch](https://leetcode.com/problems/binary-watch/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/401_Binary_Watch.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/401_Binary_Watch.java) | Note that 12 * 60 is much less than 2^n or n^2. | +| 404 | [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/404_Sum_of_Left_Leaves.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/404_Sum_of_Left_Leaves.java) | 1. Recursively DFS with root.left.left and root.left.right check
2. The same DFS based on stack | +| 405 | [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/405_Convert_a_Number_to_Hexadecimal.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/405_Convert_a_Number_to_Hexadecimal.java) | [Two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) 1. Bit manipulate, each time handle 4 digits
2. Python (hex) and Java API (toHexString & Integer.toHexString) | +| 408 | [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/408_Valid_Word_Abbreviation.py) | Go over abbr and word, O(n) and O(1) | +| 409 | [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/409_Longest_Palindrome.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/409_Longest_Palindrome.java) | Length of Palindrome is always 2n or 2n + 1. So, get all possible 2*n, and choose a single one as 1 if it exists. | +| 412 | [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/412_Fizz_Buzz.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/412_Fizz_Buzz.java) [Cpp](https://github.com/qiyuangong/leetcode/blob/master/cpp/412_Fizz_Buzz.cpp) | 1. From 1 to n, condition check
2. Condition check and string connect | +| 414 | [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/414_Third_Maximum_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/414_Third_Maximum_Number.java) | 1. Keep max 1-3 then compare, O(n) and O(1)
2. PriorityQueue, O(n) and O(1) | +| 415 | [Add Strings](https://leetcode.com/problems/add-strings/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/415_Add_Strings.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/415_Add_Strings.java) | Two points, careful abour carry, O(n) and O(n) | +| 416 | [Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/416_Partition_Equal_Subset_Sum.py) | DP, Check if sum of some elements can be half of total sum, O(total_sum / 2 * n) and O(total_sum / 2) | +| 421 | [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/421_Maximum_XOR_of_Two_Numbers_in_an_Array.py) | Check 0~32 prefix, check if there is x y in prefixes, where x ^ y = answer ^ 1, O(32n) and O(n) | +| 422 | [Valid Word Square](https://leetcode.com/problems/valid-word-square/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/422_Valid_Word_Square.py) | Compare row with column, O(n^2) | +| 434 | [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/434_Number_of_Segments_in_a_String.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/434_Number_of_Segments_in_a_String.java) | 1. trim &split
2. Find segment in place | +| 437 | [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/437_Path_Sum_III.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/437_Path_Sum_III.java) | 1. Recursively travese the whole tree, O(n^2)
2. Cache sum in Hash based on solution 1. Note that if sum(A->B)=target, then sum(root->a)-sum(root-b)=target. | +| 438 | [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/438_Find_All_Anagrams_in_a_String.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/438_Find_All_Anagrams_in_a_String.java) | Build a char count list with 26-256 length. Note that this list can be update when going through the string. O(n) and O(1) | +| 441 | [Arranging Coins](https://leetcode.com/problems/arranging-coins/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/441_Arranging_Coins.py) | O(n) time. | +| 443 | [String Compression](https://leetcode.com/problems/string-compression/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/443_String_Compression.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/443_String_Compression.java) | Maintain curr, read, write and anchor (start of this char). | +| 448 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/448_Find_All_Numbers_Disappeared_in_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/448_Find_All_Numbers_Disappeared_in_an_Array.java) | Value (1, n) and index (0, n-1). Mark every value postion as negative. Then, the remain index with positive values are result. O(n) | +| 453 | [Number of Segments in a String](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/453_Minimum_Moves_to_Equal_Array_Elements.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/453_Minimum_Moves_to_Equal_Array_Elements.java) | Each move is equal to minus one element in array, so the answer is the sum of all elements after minus min. | +| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/458_Poor_Pigs.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/458_Poor_Pigs.java) | [2 pigs for 5 * 5 metric](https://leetcode.com/problems/poor-pigs/discuss/94266/Another-explanation-and-solution) | +| 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/461_Hamming_Distance.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/461_Hamming_Distance.java) | Hamming Distance is related to XOR for numbers. So, XOR then count 1. O(n) | +| 463 | [Island Perimeter](https://leetcode.com/problems/island-perimeter/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/463_Island_Perimeter.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/463_Island_Perimeter.java) | math, find the area, actual number, then find the digit | +| 475 | [Heaters](https://leetcode.com/problems/heaters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/475_Heaters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/475_Heaters.java) | 1. Binary search hourse in heater array, O(nlogn) and O(1)
2. Two points, O(nlogn) and O(1) | +| 479 | [Largest Palindrome Product](https://leetcode.com/problems/largest-palindrome-product/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/479_Largest_Palindrome_Product.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/479_Largest_Palindrome_Product.java) | 1. Product max palindrome than check, O(n^2) and O(1)
2. [Math](https://leetcode.com/problems/largest-palindrome-product/discuss/96305/Python-Solution-Using-Math-In-48ms) | +| 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/482_License_Key_Formatting.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/482_License_Key_Formatting.java) | String processing, lower and len % K, O(n) and O(n) | +| 485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/485_Max_Consecutive_Ones.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/485_Max_Consecutive_Ones.java) | Add one when encounter 1, set to 0 when encounter 0, O(n) and O(1) | +| 509 | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/509_Fibonacci_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/509_Fibonacci_Number.java) | 1. Recursive, O(n)
2. DP with memo, O(n). Note that N<=30, which means that we can keep a memo from 0 to 30. | +| 523 | [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/523_Continuous_Subarray_Sum.py) | O(n) solution using dict() | +| 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/538_Convert_BST_to_Greater_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/538_Convert_BST_to_Greater_Tree.java) | Right first DFS with a variable recording sum of node.val and right.val. 1. Recursive.
2. Stack 3. Reverse Morris In-order Traversal | +| 541 | [Reverse String II](https://leetcode.com/problems/reverse-string-ii/solution/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/541_Reverse_String_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/541_Reverse_String_II.java) | Handle each 2k until reaching end, On(n) and O(n) | +| 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/543_Diameter_of_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/543_Diameter_of_Binary_Tree.java) | DFS with O(1) for max answer | +| 547 | [Friend Circles](https://leetcode.com/problems/friend-circles/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/547_Friend_Circles.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/547_Friend_Circles.java) | 1. DFS, O(n^2) and O(1)
2. BFS, O(n^2) and O(1)
3. Union-find, O(n^2) and O(n) | +| 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/557_Reverse_Words_in_a_String_III.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/557_Reverse_Words_in_a_String_III.java) | String handle: Split with space than reverse word, O(n) and O(n). Better solution is that reverse can be O(1) space in array. | +| 560 | [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/560_Subarray_Sum_Equals_K.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/560_Subarray_Sum_Equals_K.java) | Note that there are n^2 possible pairs, so the key point is accelerate computation for sum and reduce unnecessary pair. 1. Cummulative sum, O(n^2) and O(1)/O(n)
2. Add sum into hash, check if sum - k is in hash, O(n) and O(n) | +| 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/572_Subtree_of_Another_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/572_Subtree_of_Another_Tree.java) | 1. Tree traverse and compare
2. Tree to string and compare | +| 581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/subtree-of-another-tree/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/581_Shortest_Unsorted_Continuous_Subarray.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/581_Shortest_Unsorted_Continuous_Subarray.java) | 1. Sort and find the difference (min and max), O(nlgn)
2. Using stack to find boundaries (push when correct order, pop when not correct), O(n) and O(n)
3. Find min and max of unordered array, O(n) and O(1) | +| 605 | [Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/605_Can_Place_Flowers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/605_Can_Place_Flowers.java) | One time scan, check [i-1] [i] and [i+1], O(n) and O(1) | +| 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/617_Merge_Two_Binary_Trees.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/617_Merge_Two_Binary_Trees.java) | Traverse both trees Recursion & Iterative (stack) | +| 628 | [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/628_Maximum_Product_of_Three_Numbers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/628_Maximum_Product_of_Three_Numbers.java) | Actually, we should only care about min1, min2 and max1-max3, to find these five elements, we can use 1. Brute force, O(n^3) and O(1)
2. Sort, O(nlogn) and O(1)
3. Single scan with 5 elements keep, O(n) and O(1) | +| 654 | [Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/654_Maximum_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/654_Maximum_Binary_Tree.java) | 1. Divide and conquer, recursive, O(n^2)
2. Monotonic stack, O(n) | +| 665 | [Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/665_Non-decreasing_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/665_Non-decreasing_Array.java) | 1. Find the broken index, then check this point, O(n) and O(1)
2. Replace broken point with correct value, then check if there are more than 1 broken point, O(n) and O(1) | +| 668 | [Kth Smallest Number in Multiplication Table](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/668_Kth_Smallest_Number_in_Multiplication_Table.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/668_Kth_Smallest_Number_in_Multiplication_Table.java) [Cpp](https://github.com/qiyuangong/leetcode/blob/master/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp) | Binary search, O(mlog(mn) and O(1) | +| 671 | [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/671_Second_Minimum_Node_In_a_Binary_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/671_Second_Minimum_Node_In_a_Binary_Tree.java) | Note that min value is root: 1. Get all values then find result, O(n) and O(n)
2. BFS or DFS traverse the tree, then find the reslut, O(n) and O(n) | +| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/674_Longest_Continuous_Increasing_Subsequence.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/674_Longest_Continuous_Increasing_Subsequence.java) | Scan nums once, check nums[i] < nums[i+1], if not reset count, O(n) and O(1) | +| 680 | [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/680_Valid_Palindrome_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/680_Valid_Palindrome_II.java) | Recursively check s[left == end, when not equal delete left or right. | +| 692 | [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/692_Top_K_Frequent_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/692_Top_K_Frequent_Words.java) | 1. Sort based on frequency and alphabetical order, O(nlgn) and O(n)
2. Find top k with Heap, O(nlogk) and O(n) | +| 695 | [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/695_Max_Area_of_Island.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/695_Max_Area_of_Island.java) | 1. DFS, O(n^2) and O(n)
2. BFS, O(n^2) and O(n) | +| 697 | [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/697_Degree_of_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/697_Degree_of_an_Array.java) | 1. Find degree and value, then find smallest subarray (start and end with this value), O(n) and O(n)
2. Go through nums, remember left most pos and right most for each value, O(n) and O(n) | +| 700 | [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/700_Search_in_a_Binary_Search_Tree.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/700_Search_in_a_Binary_Search_Tree.java) | Recursive or iteration, O(logn) | +| 703 | [Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/703_Kth_Largest_Element_in_a_Stream.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/703_Kth_Largest_Element_in_a_Stream.java) | 1. Sort and insert into right place, O(nlgn) and O(n)
2. k largest heap, O(nlogk) and O(n) | +| 706 | [Design HashMap](https://leetcode.com/problems/design-hashmap/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/706_Design_HashMap.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/706_Design_HashMap.java) | Hash implementation, mod is fine. Be careful about key conflict and key remove. | +| 709 | [To Lower Case](https://leetcode.com/problems/to-lower-case/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/709_To_Lower_Case.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/709_To_Lower_Case.java) | String processing:
1. str.lower() or str.toLowerCase()
2. ASCII processing. O(n) and O(1) | +| 716 | [Max Stack](https://leetcode.com/problems/max-stack/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/716_Max_Stack.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/716_Max_Stack.java) | 1. Two stacks
2. Double linked list and Hash | +| 717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/717_1-bit_and_2-bit_Characters.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/717_1-bit_and_2-bit_Characters.java) | 1. Go through bits, 1 skip next, O(n) and O(1)
2. Find second last zero reversely, O(n) and O(1) | +| 720 | [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/720_Longest_Word_in_Dictionary.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/720_Longest_Word_in_Dictionary.java) | 1. Brute Force, O(sum(w^2)) and O(w)
2. Tire Tree, O(sum(w) and O(w))
3. Sort and word without last char, O(nlogn + sum(w)) and O(w) | +| 724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/724_Find_Pivot_Index.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/724_Find_Pivot_Index.java) | Seach the array to find a place where left sum is equal to right sum, O(n) and O(1) | +| 728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/solution/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/728_Self_Dividing_Numbers.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/728_Self_Dividing_Numbers.java) | Brute Force check every digit, O(nlogD) and O(1) | +| 733 | [Flood Fill](https://leetcode.com/problems/flood-fill/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/733_Flood_Fill.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/733_Flood_Fill.java) | 1. DFS with stack or recursive, O(n) and O(n)
2. BFS with queue, O(n) and O(n) | +| 743 | [Network Delay Time](https://leetcode.com/problems/network-delay-time/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/743_Network_Delay_Time.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/743_Network_Delay_Time.java) | Let V == N, then: 1. DFS, O(V^V+ElgE), O(V+E)
2. Dijkstra, O(V^2+E), O(V+E) | +| 751 | [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/751_IP_to_CIDR.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/751_IP_to_CIDR.java) | Bit manipulations, incrementail is 1 << (32 - mask) | +| 760 | [Find Anagram Mappings](https://leetcode.com/problems/find-anagram-mappings/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/760_Find_Anagram_Mappings.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/760_Find_Anagram_Mappings.java) | Hash table with A's (val, index), O(n) and O(n) | +| 766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/766_Toeplitz_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/766_Toeplitz_Matrix.java) | Check from top left to bottom right, i,j == i + 1, j + 1. | +| 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/771_Jewels_and_Stones.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/771_Jewels_and_Stones.java) | Count given char in string. Hash or table. [Oneline](https://leetcode.com/problems/jewels-and-stones/discuss/113574/1-liners-PythonJavaRuby) | +| 784 | [Letter Case Permutation](https://leetcode.com/problems/letter-case-permutation/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/784_Letter_Case_Permutation.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/784_Letter_Case_Permutation.java) | Note that this is a 2^n problem. 1. Recursively generate result with previous result
2. Bin Mask, number of zeor equal to number of alpha
3. Python build in product. | +| 804 | [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/804_Unique_Morse_Code_Words.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/804_Unique_Morse_Code_Words.java) | String, Hash and Set. Set is recommended. | +| 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/811_Subdomain_Visit_Count.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/811_Subdomain_Visit_Count.java) | String split and HashMap, O(n) and O(n) | +| 819 | [Most Common Word](https://leetcode.com/problems/most-common-word/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/819_Most_Common_Word.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/819_Most_Common_Word.java) | String processing, be careful about 'b,b,b'. regex is recommended. | +| 832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/832_Flipping_an_Image.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/832_Flipping_an_Image.java) | Invert and swap can be done at the same time, and careful about (n + 1)/2, O(n^2) and O(1) | +| 836 | [Rectangle Overlap](https://leetcode.com/problems/rectangle-overlap/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/836_Rectangle_Overlap.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/836_Rectangle_Overlap.java) | 1. Check position, O(1) and O(1)
2. Check area, O(1) and O(1) | +| 844 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/844_Backspace_String_Compare.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/844_Backspace_String_Compare.java) | 1. Stack pop when encounters #, O(n) and O(n)
2. Compare string from end to start, O(n) and O(1) | +| 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/852_Peak_Index_in_a_Mountain_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/852_Peak_Index_in_a_Mountain_Array.java) | 1. Scan the array until encountering decline, O(n) and O(1)
2. Binary seach with additional check for [i + 1], O(logn) and O(1) | +| 867 | [Transpose Matrix](https://leetcode.com/problems/transpose-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/867_Transpose_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/867_Transpose_Matrix.java) | Res[i][j] = A[j][i] | +| 868 | [Binary Gap](https://leetcode.com/problems/binary-gap/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/868_Binary_Gap.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/868_Binary_Gap.java) | 1. Store index and check, O(logn) and O(logn)
2. One pass and store max, O(logn) and O(1) | +| 872 | [Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/872_Leaf-Similar_Trees.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/872_Leaf-Similar_Trees.java) | DFS (stack or recursion) get leaf value sequence and compare, O(n) and O(n) | +| 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/876_Middle_of_the_Linked_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/876_Middle_of_the_Linked_List.java) | 1. Copy to array, O(n) and O(n)
2. Fast and slow point, where fast point is 2 times faster than slow point, O(n) and O(1) | +| 904 | [Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/904_Fruit_Into_Baskets.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/904_Fruit_Into_Baskets.java) | 1. Scan through blocks of tree, O(n) and O(n)
2. Mainten a sliding window with start and curr point, O(n) and O(n). | +| 905 | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/905_Sort_Array_By_Parity.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/905_Sort_Array_By_Parity.java) | 1. Sort with condition, O(nlogn) and O(1)
2. Scan all and split odd and even number into different array, O(n) and O(n)
3. In place swap similar to quick sort, O(n) and O(1) | +| 922 | [Sort Array By Parity II](https://leetcode.com/problems/sort-array-by-parity-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/922_Sort_Array_By_Parity_II.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/922_Sort_Array_By_Parity_II.java) | 1. Place odd and even number in odd and even place, not sort is needed. O(n) and O(1)
2. Two points with quick sort swap idea, O(n) and O(1). | +| 929 | [Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/929_Unique_Email_Addresses.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/929_Unique_Email_Addresses.java) | String handle and hash (or set) | +| 933 | [Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/933_Number_of_Recent_Calls.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/933_Number_of_Recent_Calls.java) | Queue, remove val in head when val < t - 3000, O(n) and O(n) | +| 937 | [Reorder Log Files](https://leetcode.com/problems/reorder-log-files/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/937_Reorder_Log_Files.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/937_Reorder_Log_Files.java) | 1. Comstom Sort, O(nlogn) and O(1)
2. Separete letter logs and digit logs, then sort letter logs and merge with digit logs, O(nlogn) and O(n) | +| 945 | [Minimum Increment to Make Array Unique](https://leetcode.com/problems/minimum-increment-to-make-array-unique/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/945_Minimum_Increment_to_Make_Array_Unique.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/945_Minimum_Increment_to_Make_Array_Unique.java) | Sort, then list duplicate and missing value in sorted list. O(nlgn) and O(n) | +| 946 | [Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/946_Validate_Stack_Sequences.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/946_Validate_Stack_Sequences.java) | Add a stack named inStack to help going through pushed and popped. O(n) and O(n) | +| 953 | [Verifying an Alien Dictionary](https://leetcode.com/contest/weekly-contest-114/problems/verifying-an-alien-dictionary/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/953_Verifying_an_Alien_Dictionary.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/953_Verifying_an_Alien_Dictionary.java) | Use hashmap to store index of each value, then create a comparator based on this index, O(n) and O(n) | +| 954 | [Array of Doubled Pairs](https://leetcode.com/contest/weekly-contest-114/problems/array-of-doubled-pairs/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/954_Array_of_Doubled_Pairs.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/954_Array_of_Doubled_Pairs.java) | Sort, then use hashmap to store the frequency of each value. Then, check n, 2 * n in hashmap, O(nlogn) and O(n) | +| 961 | [N-Repeated Element in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/961_N-Repeated_Element_in_Size_2N_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/961_N-Repeated_Element_in_Size_2N_Array.java) | Hash and count number, O(n) and O(n) | +| 962 | [Maximum Width Ramp](https://leetcode.com/problems/maximum-width-ramp/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/962_Maximum_Width_Ramp.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/962_Maximum_Width_Ramp.java) | 1. Sort index by value, then transfer problem into finding max gap between index, O(nlogn) and O(1)
2. Binary Search for candicates, O(nlogn) and O(n) | +| 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/977_Squares_of_a_Sorted_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/977_Squares_of_a_Sorted_Array.java) | 1. Sort, O(nlogn) and O(n)
2. Two point, O(n) and O(n) | +| 973 | [K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/973_K_Closest_Points_to_Origin.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/973_K_Closest_Points_to_Origin.java) | 1. Sort and get 0-K, O(nlogn) and O(1)
2. Min Heap, O(nlogk) and O(k) | +| 981 | [Time Based Key-Value Store](https://leetcode.com/problems/time-based-key-value-store/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/981_Time_Based_Store.py) | Get: O(log(n)) time
Set: O(1) time | +| 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1064_Fixed_Point.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1064_Fixed_Point.java) | 1. Go through index and value, until find solution encounter index < value, O(n) and O(1)
2. Binary search, O(logn) and O(1) | +| 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1089_Duplicate_Zeros.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1089_Duplicate_Zeros.java) | 2 Pass, store last position and final move steps, O(n) and O(1) | +| 1108 | [Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1108_Defanging_an_IP_Address.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1108_Defanging_an_IP_Address.java) | String manipulate (split, replace and join), O(n) and O(n) | +| 1189 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1189_Maximum_Number_of_Balloons.java) | Count letters in `balon`, then find min, O(n) and O(1) | +| 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1260_Shift_2D_Grid.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1260_Shift_2D_Grid.java) | Final position of each element can be computed according to k, m and n, e.g., k == mn, then don't move, O(mn) and O(mn) | +| 1290 | [Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py) | Take 2 to the power digit position from right (starting from 0) and multiply it with the digit | +| 1304 | [Find N Unique Integers Sum up to Zero](https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java) | [1,n-1] and its negative sum | +| 1310 | [XOR Queries of a Subarray](https://leetcode.com/problems/xor-queries-of-a-subarray) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1310_XOR_Queries_of_a_Subarray.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1310_XOR_Queries_of_a_Subarray.java) [Cpp](https://github.com/qiyuangong/leetcode/blob/master/cpp/1310_XOR_Queries_of_a_Subarray.cpp) | Compute accumulated xor from head, qeury result equals to xor[0, l] xor x[0, r], O(n) and O(n) | +| 1323 | [Maximum 69 Number](https://leetcode.com/problems/maximum-69-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1323_Maximum_69_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1323_Maximum_69_Number.java) | 9 is greater than 6, so change first 6 to 9 from left if exist, O(n) and O(1) | +| 1337 | [The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1337_The_K_Weakest_Rows_in_a_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1337_The_K_Weakest_Rows_in_a_Matrix.java) | Check by row, from left to right, until encount first zero, O(mn) and O(1) | +| 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py) | If number is divisible by 2, divide the number by 2, else subtract 1 from the number, and output the number of steps, O(logn) and O(1) | +| 1365 | [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java) | 1. Sort and get position in sorted nums, O(nlogn) and O(n)
2. Fill count into 0-100, O(n) and O(1) | +| 1480 | [Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1480_Running_Sum_of_1d_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1480_Running_Sum_of_1d_Array.java) | 1. Go through the array, O(n) and O(1)
2. Accumulate API | +| 1539 | [Kth Missing Positive Number](https://leetcode.com/problems/kth-missing-positive-number/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1539_Kth_Missing_Positive_Number.java) | Binary search, num of missing = arr[i]-i-1 | +| 1909 | [Remove One Element to Make the Array Strictly Increasing](https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py ) | Use brute-force. O( (nums.length)2) | +| 1981 | [Minimize the Difference Between Target and Chosen Elements](https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java) | DP memo[row][sum] to avoid recomputing | +| 2409 | [Count Days Spent Together](https://leetcode.com/problems/count-days-spent-together/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2409_Count_Days_Spent_Together.py) | Use month as a day | +| 2413 | [Smallest Even Multiple](https://leetcode.com/problems/smallest-even-multiple/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2413_Smallest_Even_Multiple.py) | Check the n is multiply by 2 | +| 2429 | [Minimize XOR](https://leetcode.com/problems/minimize-xor/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2429_Minimize_XOR.py.py) | check the num1, num2 with length and replace "0" compare with num1. | | # | To Understand | |---| ----- | diff --git a/machinelearning/cv2_single_channel_int_testing.py b/machinelearning/cv2_single_channel_int_testing.py new file mode 100644 index 0000000..12d2d21 --- /dev/null +++ b/machinelearning/cv2_single_channel_int_testing.py @@ -0,0 +1,5 @@ +import cv2 +import numpy as np + +mimicing_semseg = np.random.randint(0, high=40, size=(480, 640)) +print('pasie') diff --git a/machinelearning/kmeans.py b/machinelearning/kmeans.py new file mode 100644 index 0000000..1999197 --- /dev/null +++ b/machinelearning/kmeans.py @@ -0,0 +1,103 @@ +from scipy.cluster.vq import kmeans # just for code jump and look up the implementation wrapped inside +import collections + +def kmeans(k: int, pts): # pts 2d arr, [n, 2] + centroids = [] + + def cal_dist(point, centroid): + dx = point[0] - centroid[0] + dy = point[1] - centroid[1] + return dx**2+dy**2 + + # init centroid + for i in range(k): + centroids.append(pts[i]) + # centroids.append([random.randint(0, 300), random.randint(0, 300)]) + + # init each pts label + pts_label = [0 for i in range(len(pts))] # [n, 1] + label_cluster = collections.defaultdict(list) # each key-val store the pts with the same label, built-in func that can easily implement a hash-map + collections.OrderedDict + for t in range(100): # do 100 iterations + # find each pt label + for pidx in range(len(pts)): + pt_min_dist_across_centroids = float('inf') + closet_label = -1 # important to set it as none label, otherwise + for label, ctd in enumerate(centroids): + new_dist = cal_dist(pts[pidx], ctd) + if pt_min_dist_across_centroids > new_dist: + pt_min_dist_across_centroids = new_dist + closet_label = label + label_cluster[closet_label].append(pidx) # to do append with the null dict, this dict needs to be instantiated as `defaultdict` with the default_factory as List + pts_label[pidx] = closet_label + + # update each centroid position + for label in label_cluster: + new_centroid_x = sum([pts[p][0] for p in label_cluster[label]]) / len(label_cluster[label]) + new_centroid_y = sum([pts[p][1] for p in label_cluster[label]]) / len(label_cluster[label]) + centroids[label] = [new_centroid_x, new_centroid_y] + + return pts_label + +# for vis: https://blog.csdn.net/weixin_45690272/article/details/105748829 + +def kmeans_chinese(k, positions): + def getDistance(pos1, pos2): + # x1,y1,x2,y2二维数组——就是平方距离即可,也不必开根号了 + return (pos1[0] - pos2[0]) ** 2 + (pos1[1] - pos2[1]) ** 2 + + def getNewCenter(posList): + centerX, centerY = 0, 0 + for pos in posList: # 取这个中心所有点的距离平均值!!作为最后更新的质心,绝了 + centerX += pos[0] + centerY += pos[1] + + return (centerX / len(posList), centerY / len(posList)) + + + class_center = positions[:k] # 初始化默认自己就是自己中心 + sample_class = [None for i in range(len(positions))] # 聚类结果 + iteration = 0 + + while iteration < 100: # 迭代T次 + # 记录k个类别的簇,编号呗 + class_cluster = collections.defaultdict(list) # 字典,收集key-value,value就是类别key的归类类别 + for i in range(len(positions)): # N个点 + cur = positions[i] # 取出这个点xy + min_distance = float('inf') # max + trulabel = -1 # 目前默认没有类别 + for label in range(k): # k个簇 + # 计算cur跟所有k个簇质心的距离——把前面k个点,作为标准的聚类中心 + center = class_center[label] + distance = getDistance(cur, center) # 计算cur跟原类别质心的距离 + if distance < min_distance: + min_distance = distance + trulabel = label # 新来的一个距离不错,就将其归类到这里 + # 最后一个OK的结果,放for外面哦 + class_cluster[trulabel].append(cur) # 每个簇类别记录了cur属于自己——记录的就是一个一个点的xy坐标 + sample_class[i] = trulabel # 这一轮迭代的结果——取最小这个簇囊括i这个点 + + # 更新几个簇的质心 + for label in class_cluster: # 每个类别里面都放了哪些下标 + new_center = getNewCenter(class_cluster[label]) + class_center[label] = new_center # 换中心了 + iteration += 1 + + return sample_class # 最后一次的结果,就是最终的聚类结果 + + +if __name__ == '__main__': + arr = [ + [1.5, 2.1], + [0.8, 2.1], + [1.3, 2.1], + [110.5, 260.6], + [21.7, 32.8], + [130.9, 150.8], + [32.6, 40.7], + [41.5, 24.7] + ] + k = 3 + # expects: [1, 1, 1, 0, 2, 0, 2, 2] + print(kmeans(k, arr)) + # print(kmeans_chinese(k, arr)) diff --git a/machinelearning/losses.py b/machinelearning/losses.py new file mode 100644 index 0000000..6b61b0f --- /dev/null +++ b/machinelearning/losses.py @@ -0,0 +1,56 @@ +import torch +import torch.nn.functional as F + +input = torch.randn(3, 2, requires_grad=False) # N C +# target_class = torch.randint(2, (3,), requires_grad=False) # N, required by the cross entropy function +target = torch.randn(3, 2).softmax(1) # class prob +target_class = target.max(1)[1] + +# sinput = torch.sigmoid(input) +# loss = F.binary_cross_entropy(sinput, target) + +# input = torch.randn(3, 5, requires_grad=True) +# target = torch.randn(3, 5).softmax(dim=1) + +loss = F.cross_entropy(input, target_class, reduction='none') # with reduction just takes mean +print('with reduction, torch loss is {}, which is {}'.format(F.cross_entropy(input, target_class), loss)) + + +# target = torch.randint(5, (3,), dtype=torch.int64) + +def CE_Loss(target, act): + """Input is softmax-ed, thus CE is doing softmax+log+NLLLoss for the input logit""" + # out = torch.sum((-target * torch.log(act) - (1 - target) * torch.log(1 - act))) + loss = torch.zeros(target.shape) + for dim_label in range(target.shape[0]): + cls = target[dim_label] + loss[dim_label] = - 1 * torch.log(act[dim_label][cls]) # the gt cls index the log(pred) in the cross entropy + return loss + + +input_soft = F.softmax(input) +my_loss = CE_Loss(target_class, input_soft) +print('[my func: target as class label] loss is {} from {}'.format(my_loss, torch.mean(my_loss))) + +""" Or the target can be passed in as each class prob instead of class label""" + + +def CE_loss_takes_targetprob(target, soft_input): + loss = - target * torch.log(soft_input) + loss_sum = loss.sum(1) + loss = loss_sum.mean() + return loss, loss_sum + + +my_prob_loss, loss_sum = CE_loss_takes_targetprob(target, input_soft) +print('[my func: target as class prob] loss is {} from {}'.format(my_prob_loss, torch.mean(loss_sum))) +# will be the same as following +print('directly with target prob in ce loss: {}'.format(F.cross_entropy(input, target_class))) + +""" Output: +with reduction, torch loss is 1.286257028579712, which is tensor([1.2287, 1.3038, 1.3262]) +[my func: target as class label] loss is tensor([1.2287, 1.3038, 1.3262]) from 1.2862569093704224 +[my func: target as class prob] loss is 1.0002144575119019 from 1.0002144575119019 +directly with target prob in ce loss: 1.286257028579712 +""" + diff --git a/machinelearning/zhihu_loss.py b/machinelearning/zhihu_loss.py new file mode 100644 index 0000000..7335420 --- /dev/null +++ b/machinelearning/zhihu_loss.py @@ -0,0 +1,46 @@ +import torch +import torch.nn.functional as F + +N = 1 +C = 3 # n_classses +H = 2 +W = 2 +dev = torch.device('cpu') +# one weight per class +weights = torch.ones(C, device=dev) + +pred = torch.randn(N, C, H, W, device=dev).uniform_(0, 1) +print("input pred: \n", pred) + +# label must stay in [0, C-1] +label = torch.zeros(N, H, W, device=dev).long() +label[0][0][0] = 0 +label[0][0][1] = 1 +label[0][1][0] = 1 +label[0][1][1] = 2 +print("target label: \n", label) +loss = F.cross_entropy(input=pred, target=label, weight=weights, reduction="none") +print("round-0: cross_entropy: \n", loss) + +softmax = torch.nn.LogSoftmax(dim=1) +nllloss = torch.nn.NLLLoss(weight=weights, reduction="none") +pred_softmax = softmax(pred) +# print("pred_LogSoftmax: \n", pred_softmax) +loss = nllloss(pred_softmax, label) +print("round-1: cross_entropy: \n", loss) + + +"""implementing softmax`""" +pred_exp = torch.exp(pred) +pred_sum = torch.sum(pred_exp, dim=(1), keepdim=False) +pred_div = torch.div(pred_exp, pred_sum) +pred_log = torch.log(pred_div) +# print("pred_log: \n", pred_log) + +loss = torch.zeros(N, H, W, device=dev) +for dim0 in range(N): + for dim1 in range(H): + for dim2 in range(W): + cls = label[dim0][dim1][dim2] + loss[dim0][dim1][dim2] = -1 * weights[cls] * pred_log[dim0][cls][dim1][dim2] +print("round-2: cross_entropy: \n", loss) diff --git a/python/006_ZigZag_Conversion.py b/python/006_ZigZag_Conversion.py index ae3c418..5cd89f8 100644 --- a/python/006_ZigZag_Conversion.py +++ b/python/006_ZigZag_Conversion.py @@ -37,7 +37,7 @@ def convert(self, s, numRows): # calculate period p = 2 * (numRows - 1) result = [""] * numRows - for i in xrange(len(s)): + for i in range(len(s)): floor = i % p if floor >= p//2: floor = p - floor @@ -48,6 +48,6 @@ def convert(self, s, numRows): if __name__ == '__main__': # begin s = Solution() - print s.convert("PAYPALISHIRING", 3) + print(s.convert("PAYPALISHIRING", 3)) diff --git a/python/008_String_to_Integer(atoi).py b/python/008_String_to_Integer(atoi).py index ac167ad..f190d32 100644 --- a/python/008_String_to_Integer(atoi).py +++ b/python/008_String_to_Integer(atoi).py @@ -40,4 +40,4 @@ def myAtoi(self, str): if __name__ == '__main__': # begin s = Solution() - print s.myAtoi("+-2") \ No newline at end of file + print(s.myAtoi("+-2")) \ No newline at end of file diff --git a/python/015_3Sum.py b/python/015_3Sum.py index 0d9914a..e5f8693 100644 --- a/python/015_3Sum.py +++ b/python/015_3Sum.py @@ -1,3 +1,10 @@ +""" +for hash table questions, there are two types: +1. use {}/defaultdict (the latter gives non-key-existent val as 0) to record those whose key are text str; +2. use set() or array [] to encode those of the same type, such as uncounted integers (as keys). +""" +from typing import List + class Solution(object): # def threeSum(self, nums): @@ -74,3 +81,58 @@ def threeSum(self, nums): else: k -= 1 return res + + def threeSum_db_ptr(self, nums: List[int]) -> List[List[int]]: + """we maintain the three num in the list as [x, left, right] after sorting, such that the condition satisfies.""" + results = [] + nums.sort() # sorting is primarily under o(n^2), while the algo 3sum here is o(n^2) as well thus no influence if we do the sorting here + for i in range(len(nums)): + if nums[i] > 0: + return results # now with ptr mv, sum is already larger than 0, return what in results + + if i > 0 and nums[i] == nums[ + i - 1]: # will form an exact same pair with the prev, coz only i update here neither left nor right updated + continue + + # init + left = i + 1 + right = len(nums) - 1 # the last one ptr + + while left < right: + _sum = nums[i] + nums[left] + nums[right] + if _sum < 0: + left += 1 + elif _sum > 0: + right -= 1 + else: + results.append([nums[i], nums[left], nums[right]]) + while right > left and nums[right] == nums[right - 1]: + right -= 1 + while right > left and nums[left] == nums[left + 1]: + left += 1 + # at least one time even not equal to keep moving + right -= 1 + left += 1 + + return results + + def threeSum_dict(self, nums): + res = [] + nums.sort() + for i in range(len(nums)): + if nums[i] > 0: + return res # now with ptr mv, sum is already larger than 0, return what in results + if i > 0 and nums[i-1] == nums[i]: + continue + dict_for_c = {} + for j in range(i + 1, len(nums)): + dict_for_c + + + + +if __name__ == '__main__': + nums = [0, 0, 0] + s = Solution() + out = s.threeSum_db_ptr(nums) + print(out) diff --git a/python/018_4Sum.py b/python/018_4Sum.py index adbd653..4d46055 100644 --- a/python/018_4Sum.py +++ b/python/018_4Sum.py @@ -55,7 +55,8 @@ def fourSum(self, nums, target): # index_pairs[sum] = [(i,j)] # return combos.keys() + if __name__ == '__main__': # begin s = Solution() - print s.fourSum([0, 0, 0, 0], 0) \ No newline at end of file + print(s.fourSum([0, 0, 0, 0], 0)) diff --git a/python/020_Valid_Parentheses.py b/python/020_Valid_Parentheses.py index a9e65bf..3c05c4f 100644 --- a/python/020_Valid_Parentheses.py +++ b/python/020_Valid_Parentheses.py @@ -1,6 +1,6 @@ # class Solution(object): # def isValid(self, s): - + # class Solution: def isValid(self, s): @@ -38,8 +38,38 @@ def isValid(self, s): if len(stack) == 0: return True else: + return + + def fred_test_two(self, head): + # determine whether this linked list as a circle in it + if head is None: return False + slow = head + fast = head + while fast is not None and fast.next is not None: + slow = slow.next + fast = fast.next.next + if slow == fast: + return True + return False + def isValid_stack(self, s): + stack = [] + for i in s: + if i in ['(', '{', '[']: + stack.append(i) + else: + if len(stack) == 0: + return False + out_stack = stack.pop() + if not ((out_stack == '(' and i == ')') or \ + (out_stack == '[' and i == ']') or \ + (out_stack == '{' and i == '}')): + return False + if len(stack) != 0: # make sure it is not single side column + return False + else: + return True # def isValid(self, s): # # python replace @@ -57,3 +87,11 @@ def isValid(self, s): # return True # else: # return False + + +if __name__ == '__main__': + sinput = "()[]{}" + gt = True + s = Solution() + out = s.isValid_stack(sinput) + print(out) diff --git a/python/027_Remove_Element.py b/python/027_Remove_Element.py index 3266ad3..27903a2 100644 --- a/python/027_Remove_Element.py +++ b/python/027_Remove_Element.py @@ -5,6 +5,51 @@ # :type val: int # :rtype: int # """ + +"""fred: below try the double ptr method""" + + +class SolutionFred(object): + def removeElement_index_count_unordered(self, nums, val): + ls = len(nums) + if ls == 0: + return ls + count = 0 + index = 0 + while index < ls - count: # fast ptr index: if not reaching the end, then in loop + if nums[index] == val: + # changing the order of ele by assigning the last ele to the current index. And the index is not added up until num[index] != val, to make sure that every time bring back the last index iis not val + nums[index] = nums[ls - 1 - count] + count += 1 + else: + index += 1 + return ls - count + + # def removeElement_db_ptr(self, nums, val): + # ls = len(nums) + # if ls == 0: + # return ls + # fast, slow = 0, 0 + # while fast < ls: + # if nums[fast] != val: + # nums[slow] = nums[fast] + # slow += 1 + # fast += 1 + # return slow + + def removeElement_db_ptr(self, nums, val): + ls = len(nums) + if ls == 0: + return ls + fast, slow = 0, 0 + while fast < ls: # out of loop when fast == ls, reach idx range + if nums[fast] != val: + nums[slow] = nums[fast] + slow += 1 + fast += 1 + return slow + + class Solution(object): # def removeElement(self, nums, val): # ls = len(nums) @@ -34,8 +79,14 @@ def removeElement(self, nums, val): index += 1 return ls - count + if __name__ == '__main__': # begin - s = Solution() - print s.removeElement([1], 1) + # s = Solution() + # print(s.removeElement([1], 1)) + s2 = SolutionFred() + nums = [3, 2, 2, 3] + # k = s2.removeElement_index_count_unordered(nums, 3) + k = s2.removeElement_db_ptr(nums, 3) + print(f"k is {k}, nums is {nums}") diff --git a/python/028_Implement_strStr().py b/python/028_Implement_strStr().py index eece835..f997cd9 100644 --- a/python/028_Implement_strStr().py +++ b/python/028_Implement_strStr().py @@ -68,3 +68,108 @@ def makeNext(self, needle): j = next[j] return next + def strstr(self, haystack, needle): + lsh, lsn = len(haystack), len(needle) + if lsn == 0: + return 0 + for i in range(lsh - lsn + 1): + if haystack[i:i + lsn] == needle: + return i + return -1 + + def strstr_kmp(self, haystack, needle): + lsh, lsn = len(haystack), len(needle) + if lsn == 0: + return 0 + next = self.makeNext(needle) + i = j = 0 + while i < lsh: + if j == -1 or haystack[i] == needle[j]: + i += 1 + j += 1 + if j == lsn: + return i - lsn + if i < lsh and haystack[i] != needle[j]: + j = next[j] + return -1 + + def detect_cycle_linked_list(self, head): + if head is None: + return False + slow = head + fast = head + while fast is not None and fast.next is not None: + slow = slow.next + fast = fast.next.next + if slow == fast: + return True + return False + + def fizzBuzz(self, n): + """ + :type n: int + :rtype: List[str] + """ + out = [] + for i in range(1, n + 1): + if i % 3 == 0 and i % 5 == 0: + out.append('FizzBuzz') + elif i % 3 == 0: + out.append('Fizz') + elif i % 5 == 0: + out.append('Buzz') + else: + out.append(str(i)) + return out + + def drawingEdge(self, n): + """ + :type n: int + :rtype: List[str] + """ + out = [] + for i in range(1, n + 1): + if i == 1 or i == n: + out.append('*' * n) + else: + out.append('*' + ' ' * (n - 2) + '*') + return out + + def getMinOperations(self, n): + """ + :type n: int + :rtype: int + """ + if n == 1: + return 0 + if n % 2 == 0: + return 1 + self.getMinOperations(n // 2) + else: + return 1 + min(self.getMinOperations(n - 1), self.getMinOperations(n + 1)) + + def getMinOperations_dp(self, n): + """ + :type n: int + :rtype: int + """ + dp = [0] * (n + 1) + for i in range(2, n + 1): + dp[i] = 1 + dp[i - 1] + if i % 2 == 0: + dp[i] = min(dp[i], 1 + dp[i // 2]) + return dp[n] + + def getMinOperations_dp2(self, n): + """ + :type n: int + :rtype: int + """ + dp = [0] * (n + 1) + for i in range(2, n + 1): + dp[i] = 1 + dp[i - 1] + if i % 2 == 0: + dp[i] = min(dp[i], 1 + dp[i // 2]) + if i % 3 == 0: + dp[i] = min(dp[i], 1 + dp[i // 3]) + return dp[n] + diff --git a/python/032_Longest_Valid_Parentheses.py b/python/032_Longest_Valid_Parentheses.py index 0a23760..438f6ce 100644 --- a/python/032_Longest_Valid_Parentheses.py +++ b/python/032_Longest_Valid_Parentheses.py @@ -1,4 +1,6 @@ import pdb + + class Solution(object): # def longestValidParentheses(self, s): # """ @@ -41,7 +43,60 @@ def longestValidParentheses(self, s): tep = 0 return max(tep, res) + # on leetcode oj will over time + def fred_brute_force(self, s): + """tc: O(n^3)""" + def is_valid(x): + """A sub func to determine the current substr is valid for parenthesis construction or not, + in outer descending iterations of substrings """ + stack = [] + for i in range(len(x)): + if x[i] == '(': + stack.append('(') + elif stack != [] and stack[-1] == '(': # when x[i] == ')' and last ele is '(', it matches parenthesis + stack.pop() + else: # if stack[-1] == ')' + return False # coz it's gonna be a parenthesis with a lonely ')' here + return stack == [] # if there is remaining symbol in stacks meaning that current string contains invalid + # ( or ), thus False. Only empty list true + + if len(s) < 2: return 0 + n = len(s) + for i in range(n if n % 2 == 0 else n - 1, 0, -1): # start, stop, step: the window length + for j in range(n - i + 1): # on the left-hand side idx, from the leftest + if is_valid(s[j:j + i]): + return i # found the max valid substring + return 0 # if fail to find valid, return 0 + + def fred_dp(self, s): + """ tc: O(n) + dp1. it records the longest num of the str. init as n size + dp2. state transferring: + 1. get in the loop + IF str[i] == ')', and IF str[i-dp[i-1]-1] == '(', + then it's a full parenthesis thus dp[i]=2; + 2. consider str[i-dp[i-1]-1:i] and aggregate (only IF this idx>=0). Now dp[i]=2 + dp[i-1]; + 3. for str[0:i-dp[i-1]-1]. Now dp[i] = 2 + dp[i-1] + dp[i-dp[i-1]-2] + """ + n = len(s) + if n == 0: return 0 + dp = [0] * n + for i in range(len(s)): + if s[i] == ')' and s[i - dp[i - 1] - 1] == '(' and i - dp[i - 1] - 1 >= 0: + dp[i] = 2 + dp[i - 1] + dp[i - dp[i - 1] - 2] # even if i - dp[i - 1] - 1 ==0, i - dp[i - 1] - 2==-1 will not affects dp, as dp arr is init as 0 + return max(dp) + + def fred_stack_list(self): + current_len = 0 + max_len = 0 + stack = [] # storing the current idx that is not forming parenthesis + pass + + if __name__ == '__main__': s = Solution() # print s.longestValidParentheses(")(((((()())()()))()(()))(") - print s.longestValidParentheses(')()())') + # print(s.longestValidParentheses(')()())')) + # print(s.fred_brute_force(')()())')) + print(s.fred_dp("(()")) + # print(s.fred_dp(')()())')) diff --git a/python/044_Wildcard_Matching.py b/python/044_Wildcard_Matching.py index 1ba2eb5..4d24051 100644 --- a/python/044_Wildcard_Matching.py +++ b/python/044_Wildcard_Matching.py @@ -71,9 +71,9 @@ def isMatch(self, s, p): return p_index == p_len - if __name__ == '__main__': # begin s = Solution() - print s.isMatch("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*")) diff --git a/python/051_N-Queens.py b/python/051_N-Queens.py index 9a64e31..c0763ce 100644 --- a/python/051_N-Queens.py +++ b/python/051_N-Queens.py @@ -39,4 +39,4 @@ def do_solveNQueens(self, res, board, num): if __name__ == '__main__': # begin s = Solution() - print s.solveNQueens(4) \ No newline at end of file + print(s.solveNQueens(4)) \ No newline at end of file diff --git a/python/053_Maximum_Subarray.py b/python/053_Maximum_Subarray.py index 6a8977e..21c724c 100644 --- a/python/053_Maximum_Subarray.py +++ b/python/053_Maximum_Subarray.py @@ -1,3 +1,6 @@ +"""This question is supposed to be a greedy problem. But it can be done with dp for sure.""" + + class Solution(object): # def maxSubArray(self, nums): # return self.maxSubArrayHelper(nums, 0, len(nums) - 1) @@ -45,4 +48,23 @@ def maxSubArray(self, nums): for i in range(1, len(nums)): maxEndingHere = max(maxEndingHere + nums[i], nums[i]) maxSofFar = max(maxEndingHere, maxSofFar) - return maxSofFar \ No newline at end of file + return maxSofFar + + def max_sub_dp(self, nums): + """ + dp1: dp arr stores the max sum of its subarray + dp2: dp[i]=max(dp[i]-1 + num[i], num[i]). But the result is not the final dp arr, but the max(dp). + dp3: dp[0]=num[0], needs to init len(nums) space for dp arr + dp4: for loop starts with dp[1], and increasing + dp5: when nums = [5,4,-1,7,8], the elements sum are all positive therefore can be all + """ + dp = [0] * len(nums) + for i in range(1, len(nums)): + dp[i] = max(dp[i - 1] + nums[i], nums[i]) + return max(dp) + + +nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] +s = Solution() +out = s.max_sub_dp(nums) +print(out) diff --git a/python/062_Unique_Paths.py b/python/062_Unique_Paths.py index acf44b2..6bd2a12 100644 --- a/python/062_Unique_Paths.py +++ b/python/062_Unique_Paths.py @@ -19,3 +19,27 @@ def uniquePaths(self, m, n): l = dmap[i][j-1] dmap[i][j] = l + u return dmap[m-1][n-1] + + def fred(self, m, n): + """dp week 2#1. + dp1. dp arr is 2d, dp[i][j] means the i row and j col's #unique_path in this ele. + dp2. dp[i][j] = dp[i-1][j] + dp[i][j-1] + dp3. init at the beginning and dp[1][0], dp[0][1] = 1, 1. Not only that, the whole first row and first column needs to be init a 1. + dp4. the for loop increasing i,j. Don't modify the very first one again so not range(m) but range(1, m) + dp5. dp[1][1] = 2 using the transfer equation, makes sense. + """ + dp = [[0] * n for _ in range(m)] # list whose len==m, the row. Each ele is a row with n ele + for i in range(m): + dp[i][0] = 1 + for j in range(n): + dp[0][j] = 1 + for i in range(1, m): + for j in range(1, n): + dp[i][j] = dp[i-1][j] + dp[i][j-1] + return dp[-1][-1] + +s = Solution() +m, n = 3, 2 +out = s.fred(m, n) +# out = s.uniquePaths(m, n) +print(out) diff --git a/python/070_Climbing_Stairs.py b/python/070_Climbing_Stairs.py index fe7ae69..fb58c58 100644 --- a/python/070_Climbing_Stairs.py +++ b/python/070_Climbing_Stairs.py @@ -1,3 +1,6 @@ +"""DP session in the programming carl. #2.""" + + class Solution(object): # def climbStairs(self, n): # """ @@ -19,6 +22,18 @@ def climbStairs(self, n): dp[1], dp[0] = dp[1] + dp[0], dp[1] return dp[1] + def climb_stairs(self, n): + """ + DP1. dp arr is the current idx's #different_methods + DP2. state transferring: dp[i] = dp[i-1] + dp[i-2] + DP3. init at the beginning is ok + DP4. in each for loop, assign dp[i], with increasing i + DP5. dp == [1, 1, 2, 3] or if just two ele dp == [1,2] when i==1 + """ + dp = [1] * 2 # for fibonacci just needs to maintain two ele in dp arr, this two init as 1 and 1 representing 0 and 1st step + for i in range(n-1): + dp[1], dp[0] = dp[0] + dp[1], dp[1] + return dp[1] # C = {1: 1, 2: 2} @@ -35,3 +50,9 @@ def climbStairs(self, n): # Solution.C[n] = result # return result +if __name__ == '__main__': + s = Solution() + input = 2 + out = s.climb_stairs(input) + print(out) + diff --git a/python/078_Subsets.py b/python/078_Subsets.py index 9e3dfc0..e809c80 100644 --- a/python/078_Subsets.py +++ b/python/078_Subsets.py @@ -1,5 +1,9 @@ +"""backtracking/recursion""" + + class Solution(object): - # def subsets(self, nums): + # backtracking + # def subsets_bt(self, nums): # """ # :type nums: List[int] # :rtype: List[List[int]] @@ -7,11 +11,14 @@ class Solution(object): # nums.sort() # res = [[]] # res.append(list(nums)) + # self.counter_fred = 0 # for ls in range(1, len(nums)): # self.get_subsets(res, nums, [], ls, 0) + # print(f'counter out: {self.counter_fred}') # return res # # def get_subsets(self, res, nums, curr_set, ls, index): + # self.counter_fred += 1 # # recursive # if ls == 0: # res.append(list(curr_set)) @@ -21,6 +28,24 @@ class Solution(object): # curr_set.pop() # self.get_subsets(res, nums, curr_set, ls, index + 1) + def subsets_bt(self, nums): + result = [] + path = [] + self.counter = 0 + self.backtracking(nums, 0, path, result) + print(self.counter) + return result + + def backtracking(self, nums, startIndex, current_set, result): + self.counter += 1 + result.append(current_set[:]) # 收集子集,要放在终止添加的上面,否则会漏掉自己 + # if startIndex >= len(nums): # 终止条件可以不加 + # return + for i in range(startIndex, len(nums)): + current_set.append(nums[i]) + self.backtracking(nums, i + 1, current_set, result) + current_set.pop() # backtracking, go on to explore other combination to form subset under current hierachy in the tree + # def subsets(self, nums): # # https://leetcode.com/discuss/89343/c-8-lines-bit-operation # # doesn't work when len(nums) > 32 @@ -51,8 +76,6 @@ def subsets(self, nums): return res - - if __name__ == "__main__": s = Solution() - print s.subsets([1,2,3]) + print(s.subsets_bt([1, 2, 3])) diff --git a/python/089_Gray_Code.py b/python/089_Gray_Code.py index 09cff79..b588037 100644 --- a/python/089_Gray_Code.py +++ b/python/089_Gray_Code.py @@ -21,5 +21,5 @@ def grayCode(self, n): if __name__ == "__main__": s = Solution() - print s.grayCode(2) + print(s.grayCode(2)) diff --git a/python/102_Binary_Tree_Level_Order_Traversal.py b/python/102_Binary_Tree_Level_Order_Traversal.py index 95573ea..38e4c0c 100644 --- a/python/102_Binary_Tree_Level_Order_Traversal.py +++ b/python/102_Binary_Tree_Level_Order_Traversal.py @@ -1,9 +1,14 @@ # Definition for a binary tree node. -# class TreeNode(object): -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None +from typing import List, Optional +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None + + +import collections + class Solution(object): # def levelOrder(self, root): @@ -42,3 +47,58 @@ def levelOrder(self, root): q.append(record) return [[x.val for x in level] for level in q] + def levelOrderToTest(self, root: Optional[TreeNode]) -> List[List[int]]: + if not root: + return [] + queue = collections.deque([root]) + result = [] + while queue: + level = [] + for _ in range(len(queue)): + cur = queue.popleft() + level.append(cur.val) + if cur.left: + queue.append(cur.left) + if cur.right: + queue.append(cur.right) + result.append(level) + return result + + def levelOrderFredRe(self, root): + if not root: + return [] + queue = collections.deque([root]) # store current level of tree's nodes + result = [] + while queue: + level_of_tree = [] + for i in range(len(queue)): + node_to_proc = queue.popleft() + level_of_tree.append(node_to_proc.val) + if node_to_proc.left: + queue.append(node_to_proc.left) # push from the right + if node_to_proc.right: + queue.append(node_to_proc.right) + result.append(level_of_tree) + return result + + +if __name__ == '__main__': + root = TreeNode(3) + root.left = TreeNode(9) + root.right = TreeNode(20) + root.right.left = TreeNode(15) + root.right.right = TreeNode(7) + print(Solution().levelOrder(root)) + print(Solution().levelOrderToTest(root)) + print(Solution().levelOrderFredRe(root)) + # should expecting this + # Input: root = [3, 9, 20, null, null, 15, 7] + # Output: [[3], [9, 20], [15, 7]] + + # root = TreeNode(1) + # root.left = TreeNode(2) + # root.right = TreeNode(3) + # root.left.left = TreeNode(4) + # root.left.right = TreeNode(5) + # print(Solution().levelOrder(root)) + # print(Solution().levelOrderToTest(root)) diff --git a/python/104_Maximum_Depth_of_Binary_Tree.py b/python/104_Maximum_Depth_of_Binary_Tree.py index 6dd5183..439b84b 100644 --- a/python/104_Maximum_Depth_of_Binary_Tree.py +++ b/python/104_Maximum_Depth_of_Binary_Tree.py @@ -1,18 +1,111 @@ # Definition for a binary tree node -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None +import unittest + +# # recursive DFS, t: O(n), s: O(n), where n is the number of nodes in the tree +# # big O upper bound, t is O(n) for the unbalanced tree +# class Solution: +# def maxDepth(self, root): +# """ +# :type root: TreeNode +# :rtype: int +# """ +# if root is None: +# return 0 +# ld = self.maxDepth(root.left) +# rd = self.maxDepth(root.right) +# return 1 + max(ld, rd) + +# # iterative DFS, emulate the stack, same big O +# class Solution: +# def maxDepth(self, root): +# """ +# :type root: TreeNode +# :rtype: int +# """ +# stack = [] +# depth = 0 +# if root is not None: +# stack.append((1, root)) +# while stack != []: +# cur_depth, root = stack.pop() # pop out each branch as it is just pushed in, thus DFS +# if root is not None: +# depth = max(depth, cur_depth) # update depth val in the as the max +# stack.append((cur_depth + 1, root.left)) # push the updated-depth-node pair into the stack +# stack.append((cur_depth + 1, root.right)) +# return depth + +from collections import deque + +# iterative BFS, need a FIFO to do the breadth, thus queue +# can also do a deque version as in https://github.com/neetcode-gh/leetcode/blob/ec5ef95c2d42eca117a854d070fa122649f2647a/python/0104-maximum-depth-of-binary-tree.py#L27 class Solution: + # def maxDepth(self, root): + # queue = [] + # depth = 0 + # if root is not None: + # queue.append((1, root)) + # while queue != []: + # cur_depth, root = queue.pop(0) + # if root is not None: # if root is None, meaning that there is no children node, thus depth should not be updated with the below line + # depth = max(depth, cur_depth) + # queue.append((cur_depth +1, root.left)) + # queue.append((cur_depth +1, root.right)) + # return depth + def maxDepth(self, root): - """ - :type root: TreeNode - :rtype: int - """ - if root is None: - return 0 - ld = self.maxDepth(root.left) - rd = self.maxDepth(root.right) - return 1 + max(ld, rd) + queue = deque() + depth = 0 + if root: + queue.append(root) + while queue: + for i in range(len(queue)): # need to pop out all the nodes in current level of the queue, before adding depth + node = queue.popleft() + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + depth += 1 + return depth + +def create_binary_tree(arr): + """ + :type arr: list + :rtype: TreeNode + """ + if arr == []: + return None + root = TreeNode(arr[0]) + queue = [root] + i = 1 + while i < len(arr): + node = queue.pop(0) + if arr[i] is not None: + node.left = TreeNode(arr[i]) + queue.append(node.left) + i += 1 + if i < len(arr) and arr[i] is not None: + node.right = TreeNode(arr[i]) + queue.append(node.right) + i += 1 + return root + + +class Test(unittest.TestCase): + null = None + input_list = [3,9,20,null,null,15,7] + output_list = 3 + + def test_example(self): + root = create_binary_tree(self.input_list) + output = Solution().maxDepth(root) + self.assertEqual(output, self.output_list) + + +if __name__ == '__main__': + unittest.main() diff --git a/python/110_Balanced_Binary_Tree.py b/python/110_Balanced_Binary_Tree.py index a6fce6e..8540679 100644 --- a/python/110_Balanced_Binary_Tree.py +++ b/python/110_Balanced_Binary_Tree.py @@ -48,5 +48,14 @@ def getDepth(self, node): # return max(self.depth(root.left), self.depth(root.right)) + 1 - +class mySolution: + def isBalanced(self, root): + return self.getDepth(root)[0] + + def getDepth(self, root): + if not root: # if reach leaf node, return, otherwise keeps on recursion + return (True, 0) # less overhead for tuple, if no need to modify in the future + left, right = self.getDepth(root.left), self.getDepth(root.right) + balanced = left[0] and right[0] and abs(left[1] - right[1]) <= 1 # needs to make sure the children nodes are all balanced, otherwise will have tricky tree that messed up with the ultimate judgement + return (balanced, 1 + max(left[1], right[1])) diff --git a/python/125_Valid_Palindrome.py b/python/125_Valid_Palindrome.py index 4d198f0..aba41b0 100644 --- a/python/125_Valid_Palindrome.py +++ b/python/125_Valid_Palindrome.py @@ -1,15 +1,55 @@ -class Solution(object): +import unittest + +class Solution: def isPalindrome(self, s): """ :type s: str :rtype: bool """ - alnum_s = [t.lower() for t in s if t.isalnum()] + alnum_s = [t.lower() for t in s if t.isalnum()] # make all lower case ls = len(alnum_s) if ls <= 1: return True mid = ls / 2 - for i in range(mid): - if alnum_s[i] != alnum_s[ls - 1 - i]: + for i in range(int(mid)): + if alnum_s[i] != alnum_s[ls - 1 - i]: # check if palindrome return False - return True \ No newline at end of file + return True + +# # same +# def isPalindrome(self, s: str) -> bool: +# alnum_s = [t.lower() for t in s if t.isalnum()] # get rid of non alnum, then make lower case +# if len(alnum_s) == 0: +# return True +# for i in range(len(alnum_s) // 2): +# if alnum_s[i] != alnum_s[-i-1]: +# return False +# return True + + +class Test(unittest.TestCase): + """dd """ + test_cases = [ + "A man, a plan, a canal: Panama", + "race a car", + "" + ] + test_results = [ + True, + False, + True + ] + def test_example(self): + func = Solution().isPalindrome + for i, input in enumerate(self.test_cases): + # actual = test_example(arr, func) + # self.assertEqual(actual, expected) + # input = self.test_cases[i] + output = self.test_results[i] + out = func(input) + print(out) + assert out == output, f"Wrong: {out} != {output}" + + +if __name__ == "__main__": + unittest.main() diff --git a/python/141_Linked_List_Cycle.py b/python/141_Linked_List_Cycle.py index 509535d..4a38c2a 100644 --- a/python/141_Linked_List_Cycle.py +++ b/python/141_Linked_List_Cycle.py @@ -1,8 +1,9 @@ # Definition for singly-linked list. -# class ListNode(object): -# def __init__(self, x): -# self.val = x -# self.next = None +class ListNode(object): + def __init__(self, x): + self.val = x + self.next = None + class Solution(object): # def hasCycle(self, head): @@ -45,7 +46,38 @@ def hasCycle(self, head): while fast != slow: fast = fast.next.next slow = slow.next - return True - except: - return False \ No newline at end of file + except: # means fast hits the end + return False + + def hasCycle_dptr(self, head): + if not head or not head.next: + return False # for null node or null next node, we can safely determine not cycled + + # Two points + fast = head.next # don't do too much linked, coz input may have only one node + slow = head + + while fast != slow: + if not fast or not fast.next: # when fast reaches the end, and they're still not meeting, return False + return False + fast = fast.next.next + slow = slow.next + # out of loop means fast == slow + return True + + +# indata = [3, 2, 0, -4] +# pos = 1 +indata = [1] +pos = -1 +outdata = 1 +sol = Solution() +nodes = [] +for i in range(len(indata)): + nodes.append(ListNode(indata[i])) +for i in range(len(nodes) - 1): + nodes[i].next = nodes[i + 1] +# nodes[-1].next = nodes[pos] # make the cycle +out = sol.hasCycle(nodes[0]) +print(out) diff --git a/python/144_Binary_Tree_Preorder_Traversal.py b/python/144_Binary_Tree_Preorder_Traversal.py index de97b29..be42c5c 100644 --- a/python/144_Binary_Tree_Preorder_Traversal.py +++ b/python/144_Binary_Tree_Preorder_Traversal.py @@ -1,9 +1,10 @@ # Definition for a binary tree node. -# class TreeNode(object): -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None + class Solution(object): # def __init__(self): @@ -26,7 +27,7 @@ class Solution(object): # self.preorderTraversalHelper(node.left) # self.preorderTraversalHelper(node.right) - def preorderTraversal(self, root): + def preorderTraversal_prev(self, root: [TreeNode]): # stack if root is None: return [] @@ -41,3 +42,31 @@ def preorderTraversal(self, root): stack.append(curr.left) return res + def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + stack = [] + self.fred_preorder_traversal_func(root) + + def fred_preorder_traversal_func(self, node, stack): + """ + binary tree (bt) traversal steps: + bt1: determine the traverse param: which is the current handling node and the global preorder node list + bt2: determine end condition: when it reaches null ptr, ends for this traverse iteration (here formally speaking is using recursion) + bt3: since it is preorder, takes middle-left-right + """ + if node == null: return + stack.append(node.val) # middle + self.fred_preorder_traversal_func(node.left, stack) # left + self.fred_preorder_traversal_func(node.right.stack) + + +input = [1, null, 2, 3] + + +# for linked list or binary tree questions, if input is a list, then it needs to be adapted first before passed into the solution function +def create_linked_list(arr): + dummy = TreeNode(0) + ptr = dummy + for num in arr: + ptr.next = TreeNode(num) # create linked node for each coming .next + ptr = ptr.next + return dummy.next diff --git a/python/169_majority_element.py b/python/169_majority_element.py new file mode 100644 index 0000000..8af1071 --- /dev/null +++ b/python/169_majority_element.py @@ -0,0 +1,22 @@ +# time com: O(n) +# space com: O(1) + +class Solution: + def findMajority(self, input): + count = 0 + candidate = None # by doing one buffer only, the space complexity is O(1) + for num in input: + if count == 0: + candidate = num + if num == candidate: # find a same number as the one stored in the buffer + count += 1 + else: + count -= 1 # if new number come decrease coz chances are the candidate will not be more than a half + return candidate + + +if __name__ == '__main__': + theMajority = Solution() + print(theMajority.findMajority([1, 2, 1, 1, 3, 4, 0])) # should be None coz no majority + print(theMajority.findMajority([2, 2, 1, 1, 1, 2, 2])) # should be 2 + print(theMajority.findMajority([1, 2, 1, 1, 1, 2, 2])) # should be 1 diff --git a/python/174_Dungeon_Game.py b/python/174_Dungeon_Game.py new file mode 100644 index 0000000..7b3a954 --- /dev/null +++ b/python/174_Dungeon_Game.py @@ -0,0 +1,45 @@ +import unittest + + +class Solution(object): + def calculateMinimumHP(self, dungeon): + """ + :type dungeon: List[List[int]] + :rtype: int + + 1. DP + 2. DFS + """ + # check + if dungeon is None or len(dungeon) == 0: + return 0 + + # init + rows, cols = len(dungeon), len(dungeon[0]) + # # allocate mem to dp + # dp = [[0] * cols for _ in range(rows)] + # or simply + dp = [0] * cols * rows + # handle the lower right corner cases + dp[-1][-1] = max(1, 1 - dungeon[-1][-1]) + # handle the last row, and the last col + for j in range(cols - 2, -1, -1): + dp[-1][j] = max(1, dp[-1][j+1] - dungeon[-1][j]) + for i in range(rows - 2, -1, -1): + dp[i][-1] = max(1, dp[i+1][-1] - dungeon[i][-1]) + + for i in range(rows - 2, -1, -1): # the for loop already handle in dp fashion + for j in range(cols - 2, -1, -1): + dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]), max(1, dp[i][j+1] - dungeon[i][j])) + print('dp00 is {}'.format(dp[0][0])) + return dp[0][0] + + +class Test(unittest.TestCase): + def test1(self): + dungeon = [[-2, -3, 3], + [-5, -10, 1], + [10, 30, -5]] + expected = 7 + sol = Solution() + self.assertEqual(sol.calculateMinimumHP(dungeon), expected) diff --git a/python/200_Number_of_Islands.py b/python/200_Number_of_Islands.py index 1ee164c..2d3a671 100644 --- a/python/200_Number_of_Islands.py +++ b/python/200_Number_of_Islands.py @@ -1,3 +1,16 @@ +import unittest + +""" The tree for this island problem is shown below: + r0c0 + r1c0 r1c1 r1c2 +r2c0 r2c1 r2c2 r2c3 + + +Therefore, for all the recursive way that exploring the neighbors, it is actually BFS; +For all the recursive way that exploring the row or the column first, it is actually DFS. +""" + + class Solution(object): def numIslands(self, grid): """ @@ -9,19 +22,72 @@ def numIslands(self, grid): return 0 islands = 0 for i in range(len(grid)): - for j in range(len(grid[i])): + for j in range(len(grid[i])): # explore each row, each col if grid[i][j] == '1': self.explore(grid, i, j) islands += 1 return islands def explore(self, grid, i, j): - grid[i][j] = 'X' - if i - 1 >= 0 and grid[i - 1][j] == '1': + grid[i][j] = 'X' # make explored as 'X', then won't be explore by '1' again + print('exploring [{},{}]'.format(i, j)) + # recursively explore all the neighbors, searching directions is its neighbors, thus BFS + if i - 1 >= 0 and grid[i - 1][j] == '1': # make sure inside bound and is land self.explore(grid, i - 1, j) if j - 1 >= 0 and grid[i][j - 1] == '1': self.explore(grid, i, j - 1) if i + 1 < len(grid) and grid[i + 1][j] == '1': self.explore(grid, i + 1, j) if j + 1 < len(grid[i]) and grid[i][j + 1] == '1': - self.explore(grid, i, j + 1) \ No newline at end of file + self.explore(grid, i, j + 1) + + +class SolutionDFS(object): + def numIslandsDFS(self, grid): + """ + :type grid: List[List[str]] + :rtype: int + """ + # DFS with marks + if grid is None or len(grid) == 0: + return 0 + islands = 0 + self.visited = set() + self.rows, self.cols = len(grid), len(grid[0]) + for r in range(self.rows): + for c in range(self.cols): + if grid[r][c] == "1" and (r, c) not in self.visited: + self.explore(r, c, grid) + islands += 1 + return islands + + def explore(self, r, c, grid): + if r not in range(self.rows) or c not in range(self.cols) or grid[r][c] == "0" or (r, c) in self.visited: + return + self.visited.add((r, c)) + print('exploring [{},{}]'.format(r, c)) + directions = [(0, 1), (0, -1), (1, 0), (-1, + 0)] # this direction means that you traverse the row first, by keeping the row and change the col, thus this is a depth first search wrt the row + for dr, dc in directions: # explore all the neighbors + self.explore(r + dr, c + dc, grid) + + +class Test(unittest.TestCase): + grid = [["1", "1", "0", "0", "0"], + ["1", "1", "0", "0", "0"], + ["0", "0", "1", "0", "0"], + ["0", "0", "0", "1", "1"]] + expected = 3 + test_funcs1 = [Solution().numIslands] + test_funcs2 = [SolutionDFS().numIslandsDFS] + test_funcs = test_funcs1 + test_funcs2 + + def testNum(self): + for test_func in self.test_funcs: + print('doing {}'.format(test_func.__name__)) + self.assertEqual(test_func(self.grid), self.expected) + # restore input + self.grid = [["1", "1", "0", "0", "0"], + ["1", "1", "0", "0", "0"], + ["0", "0", "1", "0", "0"], + ["0", "0", "0", "1", "1"]] diff --git a/python/202_Happy_Number.py b/python/202_Happy_Number.py index 8436d37..71da474 100644 --- a/python/202_Happy_Number.py +++ b/python/202_Happy_Number.py @@ -1,4 +1,8 @@ +from collections import defaultdict + + class Solution(object): + """log(n), base of 10 maybe""" def isHappy(self, n): """ :type n: int @@ -9,4 +13,20 @@ def isHappy(self, n): while n > 1 and n not in seen_numbers: seen_numbers.add(n) n = sum(map(lambda x: int(x) * int(x), list(str(n)))) - return n == 1 \ No newline at end of file + return n == 1 + + def isHappy_dict(self, n): + def squ(x: str): + return int(x) ** 2 + + seen = defaultdict(int) + # seen = {} + while n > 1 and n not in seen.keys(): + seen[n] += 1 + n = sum(map(squ, list(str(n)))) + return n == 1 # if n != 1, means that it's a looped and out of seen + + +sol = Solution() +out = sol.isHappy_dict(19) +print(out) diff --git a/python/203_Remove_Linked_List_Elements.py b/python/203_Remove_Linked_List_Elements.py index 5f21fbf..cdf49b9 100644 --- a/python/203_Remove_Linked_List_Elements.py +++ b/python/203_Remove_Linked_List_Elements.py @@ -1,25 +1,79 @@ # Definition for singly-linked list. -# class ListNode(object): -# def __init__(self, x): -# self.val = x -# self.next = None +class ListNode(object): + def __init__(self, x): + self.val = x + self.next = None + class Solution(object): - def removeElements(self, head, val): + def remove_elements_iterative(self, head, val): """ :type head: ListNode :type val: int :rtype: ListNode """ # add a extra head for removing head - prehead = ListNode(-1) + prehead = ListNode(-1) # dummy before this head otherwise cannot analyze the first one prehead.next = head - last, pos = prehead, head - while pos is not None: - if pos.val == val: - last.next = pos.next + raw_prehead = prehead + while head is not None: + if head.val == val: + prehead.next = head.next # remove the ele that is in condition + else: + prehead = head + head = head.next + return raw_prehead.next # the head of + + def rmi(self, head, val): + calculating_node = ListNode(-1) # initialized it as a prehead, such that the head of the ListNode can be considerred + calculating_node.next = head + prehead = calculating_node + while calculating_node.next is not None: + if calculating_node.next.val == val: + calculating_node.next = calculating_node.next.next # remove else: - last = pos - pos = pos.next + calculating_node = calculating_node.next return prehead.next + def remove_elements_recursive(self, head, val): + if head is None: + return head + head.next = self.remove_elements_recursive(head.next, val) + if head.val == val: + return head.next # return the ListNode for the linkage to the previous ListNode + else: + return head # is not val, current head will be linked to the prev node + + +# below two funcs are all for feeding test data correctly and arange the output in list correctly, from `q328 odd even linked list` +def create_linked_list(arr): + dummy = ListNode(-1) + ptr = dummy + for num in arr: + ptr.next = ListNode(num) # create linked node for each coming .next + ptr = ptr.next + return dummy.next + + +def linked_list_to_list(head): + arr = [] + while head: + arr.append(head.val) + head = head.next + return arr + + + +input_arr = [1, 2, 6, 3, 4, 5, 6] +val = 6 +linked_list_head = create_linked_list(input_arr) +sol = Solution() + +# new_head = sol.remove_elements_iterative(linked_list_head, val) +# new_head = sol.rmi(linked_list_head, val) +new_head = sol.remove_elements_recursive(linked_list_head, val) + +result = linked_list_to_list(new_head) +print(result) +# solution = Solution().removeElements_iterative(head, val) +# print(solution) diff --git a/python/206_Reverse_Linked_List.py b/python/206_Reverse_Linked_List.py index 97d10ee..2e3b9ae 100644 --- a/python/206_Reverse_Linked_List.py +++ b/python/206_Reverse_Linked_List.py @@ -1,8 +1,8 @@ # Definition for singly-linked list. -# class ListNode(object): -# def __init__(self, x): -# self.val = x -# self.next = None +class ListNode(object): + def __init__(self, x, next=None): + self.val = x + self.next = next class Solution(object): @@ -56,16 +56,56 @@ class Solution(object): # while curr is not None: # next_temp = curr.next # curr.next = prev + # # # below two lines can also been used in a recursion like below commented + # # def reverse(prev, curr): # moving the ptrs once curr.next re-assigned + # # return reverse(curr, temp) # prev = curr # curr = next_temp # return prev def reverseList(self, head): + """ steps of doing recursion + 1. define end state and return + 2. determine where to recurse it in the function + 3. determine what is the return value for the recursion line + 4. determine the real func here that helps the recursion works + """ # recursion # simple recursively without extra space if head is None or head.next is None: return head - p = self.reverseList(head.next) - head.next.next = head - head.next = None - return p + new_head = self.reverseList(head.next) + head.next.next = head # the original next node (head.next) now has a new next, which is the prev one, thus reverse the linked list + head.next = None # delete the original direction of link + return new_head # return the new head of the Linked List + + def reverse_list_with_double_ptr(self, head): + # iterative double ptr + left_ptr, right_ptr = None, head + while right_ptr: + temp = right_ptr.next + right_ptr.next = left_ptr # change the link direction, from left to right to right to left + # update the ptr position + left_ptr = right_ptr + right_ptr = temp + + return left_ptr # right ptr already None when reaches here, left ptr is the new head + + + +if __name__ == '__main__': + from python.design_linked_list_707 import MyLinkedList + input_head = [1, 2, 3, 4, 5] + output_head = [5, 4, 3, 2, 1] + test_node = ListNode(input_head[0]) + test_node.next = ListNode(input_head[1]) + input_linked_list = MyLinkedList() + for i in range(len(input_head)): + input_linked_list.addAtIndex(i, input_head[i]) + solution = Solution() + # out = solution.reverseList(input_linked_list.dummy_head) + out = solution.reverse_list_with_double_ptr(input_linked_list.dummy_head) + for i in range(len(input_head)): + val = out.val + out = out.next + print(val) diff --git a/python/225_Implement_Stack_using_Queues.py b/python/225_Implement_Stack_using_Queues.py index 0c9ca3e..4cc347e 100644 --- a/python/225_Implement_Stack_using_Queues.py +++ b/python/225_Implement_Stack_using_Queues.py @@ -85,3 +85,56 @@ def empty(self): """ return len(self.queue1) == 0 + +# todo notice that another method in python is to use deque +class MyStack: + + def __init__(self): + self.queue = [] + self.current_top = 0 + + def push(self, x: int) -> None: + self.queue.append(x) + self.current_top = x + + def pop(self, *a) -> int: + if len(self.queue) == 0: + return None + qsize = len(self.queue) + while qsize > 1: + self.queue.append(self.queue[0]) + self.queue.pop(0) + qsize -= 1 + result = self.queue.pop(0) + if self.empty(): + self.current_top = 0 + else: + self.current_top = self.queue[-1] + return result + + def top(self, *a) -> int: + if self.empty() is False: + return self.current_top + + def empty(self, *a) -> bool: + return len(self.queue) == 0 + + +# Your MyStack object will be instantiated and called as such: +obj = MyStack() +# obj.push(1) +# obj.push(2) +# param_2 = obj.pop() +# # param_3 = obj.top() +# param_4 = obj.empty() +# print(param_4) + +# Input = ["push", "push", "pop", "top"] +# Input2 = [[1], [2], [], []] +Input = ["push", "push", "push", "top", "pop", "top", "pop", "top", "empty", "pop", "empty"] +Input2 = [[1], [2], [3], [], [], [], [], [], [], [], []] + +for func, var in zip(Input, Input2): + fun = getattr(obj, func) + p = fun(var) + print(p) diff --git a/python/226_Invert_Binary_Tree.py b/python/226_Invert_Binary_Tree.py index 8e06b9f..0264efb 100644 --- a/python/226_Invert_Binary_Tree.py +++ b/python/226_Invert_Binary_Tree.py @@ -6,30 +6,30 @@ # self.right = None class Solution(object): - # def invertTree(self, root): - # """ - # :type root: TreeNode - # :rtype: TreeNode - # """ - # # recursively - # if root is None: - # return None - # right = self.invertTree(root.right) - # left = self.invertTree(root.left) - # root.left = right - # root.right = left - # return root - def invertTree(self, root): - # iteratively + """ + :type root: TreeNode + :rtype: TreeNode + """ + # recursively if root is None: return None - queue = [root] - while len(queue): - curr = queue.pop(0) - curr.left, curr.right = curr.right, curr.left - if curr.left is not None: - queue.append(curr.left) - if curr.right is not None: - queue.append(curr.right) - return root \ No newline at end of file + root.left, root.right = root.right, root.left + + self.invertTree(root.right) + self.invertTree(root.left) + return root + + # def invertTree(self, root): + # # iteratively + # if root is None: + # return None + # queue = [root] + # while len(queue): + # curr = queue.pop(0) + # curr.left, curr.right = curr.right, curr.left + # if curr.left is not None: + # queue.append(curr.left) + # if curr.right is not None: + # queue.append(curr.right) + # return root \ No newline at end of file diff --git a/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py b/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py index 13859c9..8008d80 100644 --- a/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py +++ b/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py @@ -28,7 +28,7 @@ class Solution(object): # return self.ans def lowestCommonAncestor(self, root, p, q): - """ + """ using linked list? or just list? :type root: TreeNode :type p: TreeNode :type q: TreeNode diff --git a/python/239_sliding_window_maximum.py b/python/239_sliding_window_maximum.py new file mode 100644 index 0000000..e69de29 diff --git a/python/242_Valid_Anagram.py b/python/242_Valid_Anagram.py index aa5e814..8886094 100644 --- a/python/242_Valid_Anagram.py +++ b/python/242_Valid_Anagram.py @@ -1,3 +1,5 @@ +from collections import defaultdict + class Solution(object): # def isAnagram(self, s, t): # """ @@ -18,11 +20,32 @@ def isAnagram(self, s, t): # https://leetcode.com/articles/valid-anagram/ if len(s) != len(t): return False - counter = [0] * 26 + counter = [0] * 26 # an arr counter for char for i in range(len(s)): counter[ord(s[i]) - ord('a')] += 1 counter[ord(t[i]) - ord('a')] -= 1 for num in counter: if num != 0: return False - return True \ No newline at end of file + return True + + def isAnagram_defaultdict(self, s, t): + if len(s) != len(t): + return False + counter = defaultdict(int) # needs to make the default val of the dict as int 0, using dict seems not able to meet this + # counter = {} + for char in s: + counter[char] += 1 + for char in t: + counter[char] -= 1 + for k, v in counter.items(): + if v != 0: + return False + return True + + +sol = Solution() +s = "anagram" +t = "nagaram" +out = sol.isAnagram_defaultdict(s, t) +print(out) diff --git a/python/2571_Minimum_Operations_Reduce_Int_ 0.py b/python/2571_Minimum_Operations_Reduce_Int_ 0.py new file mode 100644 index 0000000..27c4dd0 --- /dev/null +++ b/python/2571_Minimum_Operations_Reduce_Int_ 0.py @@ -0,0 +1,33 @@ +# not dp, but using binary as the question is all about binary operations. +class Solution: + def minOperations(self, n): + if n == 0: + return 0 + if n == 1: + return 0 + if n < 0: + return 0 + + # do comparison with either makes up with 1 or not + ret = 0 + # pos int n means it is single precision + for i in range(32): + if self.count_1(n + (1 << i)) + 1 <= self.count_1(n): # in fact, it considers the case of subtraction, coz if it is 0b'10000000001, apparently it won't get into the loop, and the result will just ret + self.count_1(n), which is done by doing substation + n += 1 << i + ret += 1 + return ret + self.count_1(n) + + def count_1(self, n): + binary_n = bin(n) + return binary_n.count('1') + + +# indata = [3, 2, 0, -4] +# pos = 1 +# indata = 39 +# output = 3 +indata = 54 +output = 3 +sol = Solution() +out = sol.minOperations(indata) +print(out) diff --git a/python/300_longest-increasing-subsequence.py b/python/300_longest-increasing-subsequence.py new file mode 100644 index 0000000..b28998b --- /dev/null +++ b/python/300_longest-increasing-subsequence.py @@ -0,0 +1,97 @@ +"""Dynamic programming (DP), is good for problems that have multiple sub problems. + +The core value is to come up with a dp table that records multiple states. That's how it's different from greedy algorithm. Because greedy algorithm only has the optimal solution directly without states changing. + +5 steps of DP: + 1. Define dp array and its content + 2. Define state transferring function + 3. Initialize dp array + 4. Determine the sequence of state transferring + 5. Sub in example to verify the dp array holding correct elements + +For instance, when dealing with the Fibonacci problem. With Step 5 using dp[10] as an example, we find that dp[0:10] == [0 1 1 2 3 5 8 13 21 34 55]. And for our code it needs to be matched. +""" + + +class Solution: + def fib_solution_bigo_n(self, data_list, n): + """tc: o(n), sc: o(n)""" + if n == 0: # get avoid with corner case + return 0 + dp_arr = [0] * n + dp_arr[0], dp_arr[1] = 0, 1 + output_model_list = [] + for i in data_list: + dp_arr[i] = dp_arr[i - 1] + dp_arr[i - 2] + output_model_list.append(dp_arr[i]) + print(output_model_list) + + def fib_solution_bigo_1(self, data_list): + """tc: o(n), sc: o(1), coz neglecting input and output, here dp_arr is only with two elements""" + dp_arr = [0] * 2 + dp_arr[0], dp_arr[1] = 0, 1 + output_model_list = [] + for i in data_list: + temp = dp_arr[0] + dp_arr[0] = dp_arr[1] + dp_arr[1] = dp_arr[0] + temp + output_model_list.append(dp_arr[1]) + print(output_model_list) + + def findLengthOfLCIS(self, nums) -> int: + """ For longest continuous increasing subsequence: Leetcode Q674 + dp_arr ele is the length of the longest inc subseq of the current idx ele in input, which is ended with this current ele (important, otherwise cannot do comparison with the prev ele to update dp_arr intuitively). + + BigO: TC: O(n); SC: O(n). + + If using greedy algo. with two int vars count and result only, then TC==O(n), SC==O(1). + """ + # dp arr init + dp_arr = [1] * len(nums) + result = 1 + for i in range(len(nums) - 1): # no need to do one more layer of for loop since it's LCIS rather than LIS + if nums[i + 1] > nums[i]: + dp_arr[i + 1] = dp_arr[i] + 1 + result = max(result, dp_arr[i + 1]) # with a minimum 1, to avoid some negative number as the input to mess up + return result + + def findLengthOfLIS(self, nums) -> int: + """For longest increasing subsequence: Leetcode Q300 + + BigO: TC: O(n^2); SC: O(n) + """ + dp_arr = [1] * len(nums) # dp arr init, the length of current idx's LIS + result = 1 + for i in range(len(nums)): # start handling from the nums[1] + for j in range(i): + if nums[i] > nums[j]: + dp_arr[i] = max(dp_arr[i], dp_arr[j] + 1) + result = max(result, dp_arr[i]) + return result + + +if __name__ == '__main__': + s = Solution() + + # # for fib seq testing, a simple example for the dp problems + # input_list = [2, 3, 4] + # output_gt_list = [1, 2, 3] + # # s.fib_solution_bigo_n(input_list, 10) + # s.fib_solution_bigo_1(input_list) + + # # for lcis + # # nums = [10, 9, 2, 5, 3, 7, 101, 18] + # # output_gt = 4 + # nums = [1, 3, 5, 4, 7] + # # nums = [1,3,5,4,7] + # # nums = [2,1] + # # output_gt = 3 + # out = s.findLengthOfLCIS(nums) + # print(out) + + # for lis problem, if brute-force tc will be o(n^2) + # nums = [10, 9, 2, 5, 3, 7, 101, 18] + nums = [0, 1, 0, 3, 2, 3] + out = s.findLengthOfLIS(nums) + print(out) + diff --git a/python/307_Range_Sum_Query_Mutable.py b/python/307_Range_Sum_Query_Mutable.py index 4a7eca4..83dc946 100644 --- a/python/307_Range_Sum_Query_Mutable.py +++ b/python/307_Range_Sum_Query_Mutable.py @@ -1,5 +1,83 @@ -# import math -# +import math +import unittest + + +# Time Limit Exceeded for the naive solution +class NumArray: + + def __init__(self, nums): + self.num_list = nums + + def update(self, index: int, val: int) -> None: + self.num_list[index] = val + + def sumRange(self, left: int, right: int) -> int: + sum = 0 + for i in range(left, right + 1): + sum += self.num_list[i] + + return sum + + +# with segment tree +class Node(object): + def __init__(self, start, end, sum): + self.start = start + self.end = end + self.sum = sum + self.left = None + self.right = None + + +class myNumArr(object): + def __init__(self, nums): + self.nums = [] + self.ls = len(nums) + self.b = [] + + def createTree(nums, start, end): + if start > end: + return None + if start == end: + node = Node(start, end, nums[start]) + return node + mid = (start + end) // 2 + node = Node(start, end, 0) + node.left = createTree(nums, start, mid) + node.right = createTree(nums, mid + 1, end) + node.sum = node.left.sum + node.right.sum + return node + + self.root = createTree(nums, 0, self.ls - 1) + + def update(self, i, val): + def updateVal(root, i, val): + if root.start == root.end: + root.sum = val + return val + mid = (root.start + root.end) // 2 + if i <= mid: + updateVal(root.left, i, val) + else: + updateVal(root.right, i, val) + root.sum = root.left.sum + root.right.sum + return root.sum + return updateVal(self.root, i, val) + + def sumRange(self, i, j): + def rangeSum(root, i, j): + if root.start == i and root.end == j: + return root.sum + mid = (root.start + root.end) // 2 + if j <= mid: + return rangeSum(root.left, i, j) + elif i > mid: + return rangeSum(root.right, i, j) + else: + return rangeSum(root.left, i, mid) + rangeSum(root.right, mid + 1, j) + + return rangeSum(self.root, i, j) + # class NumArray(object): # def __init__(self, nums): # """ @@ -42,68 +120,75 @@ # return res -class NumArray(object): - def __init__(self, nums): - """ - initialize your data structure here. - :type nums: List[int] - """ - self.ls = len(nums) - self.tree = [0] * (self.ls * 2) - self.buildTree(nums) - - def buildTree(self, nums): - i, j = self.ls, 0 - while i < 2 * self.ls: - self.tree[i] = nums[j] - i += 1 - j += 1 - for i in reversed(range(1, self.ls)): - self.tree[i] = self.tree[i * 2] + self.tree[i * 2 + 1] - +# class NumArray(object): +# def __init__(self, nums): +# """ +# initialize your data structure here. +# :type nums: List[int] +# """ +# self.ls = len(nums) +# self.tree = [0] * (self.ls * 2) +# self.buildTree(nums) +# +# def buildTree(self, nums): +# i, j = self.ls, 0 +# while i < 2 * self.ls: +# self.tree[i] = nums[j] +# i += 1 +# j += 1 +# for i in reversed(range(1, self.ls)): +# self.tree[i] = self.tree[i * 2] + self.tree[i * 2 + 1] +# +# def update(self, i, val): +# """ +# :type i: int +# :type val: int +# :rtype: int +# """ +# i += self.ls +# self.tree[i] = val +# while i > 0: +# left = right = i +# if i % 2 == 0: +# right = i + 1 +# else: +# left = i - 1 +# self.tree[i / 2] = self.tree[left] + self.tree[right] +# i /= 2 +# +# def sumRange(self, i, j): +# """ +# sum of elements nums[i..j], inclusive. +# :type i: int +# :type j: int +# :rtype: int +# """ +# res = 0 +# i += self.ls +# j += self.ls +# +# while i <= j: +# if i % 2 == 1: +# res += self.tree[i] +# i += 1 +# if j % 2 == 0: +# res += self.tree[j] +# j -= 1 +# i /= 2 +# j /= 2 +# return res +# +# # Your NumArray object will be instantiated and called as such: +# # numArray = NumArray(nums) +# # numArray.sumRange(0, 1) +# # numArray.update(1, 10) +# # numArray.sumRange(1, 2) - def update(self, i, val): - """ - :type i: int - :type val: int - :rtype: int - """ - i += self.ls - self.tree[i] = val - while i > 0: - left = right = i - if i % 2 == 0: - right = i + 1 - else: - left = i -1 - self.tree[i / 2] = self.tree[left] + self.tree[right] - i /= 2 - def sumRange(self, i, j): - """ - sum of elements nums[i..j], inclusive. - :type i: int - :type j: int - :rtype: int - """ - res = 0 - i += self.ls - j += self.ls - - while i <= j: - if i % 2 == 1: - res += self.tree[i] - i += 1 - if j % 2 == 0: - res += self.tree[j] - j -= 1 - i /= 2 - j /= 2 - return res - - - # Your NumArray object will be instantiated and called as such: - # numArray = NumArray(nums) - # numArray.sumRange(0, 1) - # numArray.update(1, 10) - # numArray.sumRange(1, 2) \ No newline at end of file +class TestSolution(unittest.TestCase): + def test_update(self): + numArray = myNumArr([1, 3, 5]) + numArray.update(1, 2) + self.assertEqual(numArray.sumRange(0, 2), 8) + numArray.update(0, 3) + self.assertEqual(numArray.sumRange(0, 2), 10) diff --git a/python/328_Odd_Even_Linked_List.py b/python/328_Odd_Even_Linked_List.py index 38ed95a..a903765 100644 --- a/python/328_Odd_Even_Linked_List.py +++ b/python/328_Odd_Even_Linked_List.py @@ -1,13 +1,27 @@ +import unittest + + # Definition for singly-linked list. -# class ListNode(object): -# def __init__(self, x): -# self.val = x -# self.next = None +class ListNode(object): + """ + dd + """ + + def __init__(self, x): + self.val = x + self.next = None # for unknown next ptr, set it to None + +# using LinkedList space complexity is O(1), fixed +# if using two list to hold odd and even, space complexity is O(n) class Solution(object): + """ + dd + """ + def oddEvenList(self, head): - """ - :type head: ListNode + """ Process the head of the target linked list + :type head: ListNode, pointing to the head of the processed linked list :rtype: ListNode """ odd = head @@ -17,11 +31,11 @@ def oddEvenList(self, head): return head even_head = even = head.next while odd.next is not None and even.next is not None: - odd.next = even.next - odd = odd.next - even.next = odd.next - even = even.next - odd.next = even_head + odd.next = even.next # the new come even.next is a odd, so can be the odd next for the odd to be + odd = odd.next # update odd to be + even.next = odd.next # the new come odd.next is a even + even = even.next # update even + odd.next = even_head # end of the odd, link to the even head return head # def oddEvenList(self, head): @@ -34,4 +48,64 @@ def oddEvenList(self, head): # x.append(head.val) # head = head.next # x.append(head.val) - # return x[0::2] + x[1::2] \ No newline at end of file + # return x[0::2] + x[1::2] + + +# below two funcs are all for feeding test data correctly and arange the output in list correctly +def create_linked_list(arr): + dummy = ListNode(0) + ptr = dummy + for num in arr: + ptr.next = ListNode(num) # create linked node for each coming .next + ptr = ptr.next + return dummy.next + + +def linked_list_to_list(head): + arr = [] + while head: + arr.append(head.val) + head = head.next + return arr + + +def test_example(arr, func): + head = create_linked_list(arr) + result = linked_list_to_list(func(head=head)) + return result + + +class Test(unittest.TestCase): + """ + """ + test_cases = [ + ([2, 1, 3, 5, 6, 4, 7], [2, 3, 6, 7, 1, 5, 4]) + ] + test_listnode_cases = [] + test_functions = [Solution().oddEvenList] + + # def prepare_linked_list(self, items: list) -> ListNode | None: + # if not items: + # return None + # root = None + # last_node = None + # for ind, val in enumerate(items): + # if ind == 0: + # root = ListNode(val) # root node + # last_node = root + # else: + # last_node.next = ListNode(val) + # last_node = last_node.next + # return root + + # in unittest, all func starts with "test" will be run by unittest.main(). Thus carefully choosing the name + def test_oddeven_link(self): + for (test_in, test_out) in self.test_cases: + for func in self.test_functions: + out = test_example(arr=test_in, func=func) + print(f'out is {out}') + assert (out == test_out), f"{func.__name__} fialed for val: {test_in}, as {out}" + + +if __name__ == "__main__": + unittest.main() diff --git a/python/349_Intersection_of_Two_Arrays.py b/python/349_Intersection_of_Two_Arrays.py index 25bc471..d462a8c 100644 --- a/python/349_Intersection_of_Two_Arrays.py +++ b/python/349_Intersection_of_Two_Arrays.py @@ -1,3 +1,5 @@ +from collections import defaultdict + class Solution(object): def intersection(self, nums1, nums2): """ @@ -6,4 +8,52 @@ def intersection(self, nums1, nums2): :rtype: List[int] """ # set - return list(set(nums1) & set(nums2)) \ No newline at end of file + return list(set(nums1) & set(nums2)) + + + + def intersection_withdict(self, nums1, nums2): + theset = defaultdict(int) + res = [] + for i in nums1: + if not theset.get(i): + theset[i] = 1 + for i in nums2: + if theset.get(i): + res.append(i) + theset[i] = 0 # rm as the problem requests + return res + + +def getPlusSignCount(N, Len, Dir): + x, y = 0, 0 # 初始位置 + up, down, left, right = set(), set(), set(), set() + plus_signs = 0 + + for L, D in zip(Len, Dir): + if D == 'U': + y_new = y + L + for i in range(y, y_new): + up.add(i) + y = y_new + elif D == 'D': + y_new = y - L + for i in range(y, y_new, -1): + down.add(i) + y = y_new + elif D == 'L': + x_new = x - L + for i in range(x, x_new, -1): + left.add(i) + x = x_new + elif D == 'R': + x_new = x + L + for i in range(x, x_new): + right.add(i) + x = x_new + + # 检查当前位置是否形成加号 + if x in left and x in right and y in up and y in down: + plus_signs += 1 + + return plus_signs \ No newline at end of file diff --git a/python/429_n-ary-tree-level-order-traversal.py b/python/429_n-ary-tree-level-order-traversal.py new file mode 100644 index 0000000..e38f7cb --- /dev/null +++ b/python/429_n-ary-tree-level-order-traversal.py @@ -0,0 +1,87 @@ +from typing import List, Optional + + +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None + + +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children + + +import collections + + +class Solution(object): + def levelOrder(self, root: 'Node') -> List[List[int]]: + if not root: + return [] + queue = collections.deque([root]) + result = [] + while queue: # new level for each iter + level = [] + for i in range(len(queue)): + node_proc = queue.popleft() + level.append(node_proc.val) + if node_proc.children: + for j in range(len(node_proc.children)): + queue.append(node_proc.children[j]) + result.append(level) + return result + + +if __name__ == '__main__': + root = Node(1) + root.children = [Node(3), Node(2), Node(4)] + root.children[0].children = [Node(5), Node(6)] + print(Solution().levelOrder(root)) + # should expecting this + # Input: root = [1, 3, 2, 4, 5, 6] + # Output: [[1], [3, 2, 4], [5, 6]] + # Explanation: The above tree is represented in the level order. + # (1) -> 1 + # (2) -> 3, 2, 4 + # (3) -> 5, 6 + # return its level order traversal as: + # [ + # [1], + # [3, 2, 4], + # [5, 6] + # ] + # + # Input: root = [1, null, 2, 3, 4, 5, null, null, 6, 7, null, 8, null, 9, 10] + # Output: [[1], [2, 3, 4, 5], [6, 7, 8, 9, 10]] + # Explanation: The above tree is represented in the level order. + # (1) -> 1 + # (2) -> 2 + # (3) -> 3, 4, 5 + # (4) -> 6, 7 + # (5) -> 8 + # (6) -> 9 + # (7) -> 10 + # return its level order traversal as: + # [ + # [1], + # [2], + # [3, 4, 5], + # [6, 7], + # [8], + # [9], + # [10] + # ] + # + # Input: root = [] + # Output: [] + # Explanation: The tree has no nodes. + # return []. + # + # Input: root = [1] + # Output: [[1]] + # Explanation: The tree has only one node. + # return [[1]]. + # diff --git a/python/704_Binary_Search.py b/python/704_Binary_Search.py new file mode 100644 index 0000000..b3b170b --- /dev/null +++ b/python/704_Binary_Search.py @@ -0,0 +1,96 @@ +import unittest + + +class Solution(object): + """ + xx + """ + + # def binarySearch(self, nums, start, target): + # left, right = start, len(nums) - 1 + # while left < right: + # mid = (left + right + 1) / 2 + # if nums[mid] < target: + # # left should always less than target + # left = mid + # else: + # right = mid - 1 + # return left + + # dichotomy + def search(self, nums, target): + """ + xx + """ + if nums == []: + return -1 + idx = 0 + # # take this out, avoid inf loop + # if len(nums) == 1: + # return idx + while len(nums) >= 1: + mid_idx = len(nums) // 2 + if mid_idx > 0: + mid = nums[mid_idx] + if mid == target: + return len(nums) // 2 + idx + elif mid > target: + nums = nums[:len(nums) // 2] + elif mid < target: + idx += len(nums) // 2 + nums = nums[len(nums) // 2:] + else: + raise ValueError("Unexpected case") + else: + if nums[0] == target: + return idx + else: + return -1 + # if go through the loop haven't return, then means no target found + return -1 + + # double ptr, tc: o(log_2^N) + def search2(self, nums, target): + l, r = 0, len(nums) - 1 + while l <= r: + mid_idx = l + ((r-l) // 2) # halve, thus o(log_2^N) + if nums[mid_idx] > target: + r = mid_idx - 1 + elif nums[mid_idx] < target: + l = mid_idx + 1 + else: + return mid_idx + return -1 + + +class Test(unittest.TestCase): + """ + unittest + """ + test_cases = [ + [2, 5], + 2, + [5], + 5, + [-1, 0, 3, 5, 9, 12], + 9, + [-1, 0, 3, 5, 9, 12], + 2 + ] + test_output = [0, 0, 4, -1] + test_functions = [Solution().search, Solution().search2] + + def test_search(self): + """ + binary search + """ + for i in range(int(len(self.test_cases) / 2)): + nums, target = self.test_cases[2 * i], self.test_cases[2 * i + 1] + for test_func in self.test_functions: + test_result = test_func(nums, target) + print(test_result) + self.assertEqual(test_result, self.test_output[i]) + + +if __name__ == '__main__': + unittest.main() diff --git a/python/746_min-cost-climbing-stairs.py b/python/746_min-cost-climbing-stairs.py new file mode 100644 index 0000000..734c262 --- /dev/null +++ b/python/746_min-cost-climbing-stairs.py @@ -0,0 +1,23 @@ +"""DP session in the programming carl. #3.""" + + +class Solution(object): + def minCostClimbingStairs(self, cost: [int]) -> int: + """ + dp1. dp arr is min cost of the current idx step + dp2. dp[i] == min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]), as the question requires getting on top of the whole steps. THEREFORE dp table needs to be len(cost) + 1 + dp5. make sure what the dp table first 5 elements, what are they. And then can test it cost = [10,15,20], dp[-1] == min(10+20, 15) == 15 + """ + dp_arr = [0] * (len(cost)+1) # init dp table + # dp_arr[1] = cost[0] + for i in range(2, len(cost)+1): # only do len(cost) - 1 times, and start with the dp_arr[1] + dp_arr[i] = min(dp_arr[i - 1] + cost[i - 1], dp_arr[i - 2] + cost[i - 2]) + return dp_arr[-1] + + +if __name__ == '__main__': + s = Solution() + # input = [10, 15, 20] + input = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] + out = s.minCostClimbingStairs(input) + print(out) diff --git a/python/977_sort.py b/python/977_sort.py new file mode 100644 index 0000000..c193c44 --- /dev/null +++ b/python/977_sort.py @@ -0,0 +1,28 @@ +class Solution: + def sorted_withlib(self, nums): + return sorted(x * x for x in nums) + + def sorted(self, nums): # double ptr here + l, r, o_ptr = 0, len(nums) - 1, len(nums) - 1 + out = [0] * len(nums) + while l <= r: + lq = nums[l] ** 2 + rq = nums[r] ** 2 + pre_max = max(lq, rq) + out[o_ptr] = pre_max + o_ptr -= 1 + if lq == pre_max: + l += 1 + else: + r -= 1 + return out + + +Input = [-4, -1, 0, 3, 10] +Outpu = [0, 1, 9, 16, 100] +s = Solution() +# otu = s.sorted_withlib(Input) +# print(otu) + +out = s.sorted(Input) +print(out) diff --git a/python/Count_of_distinct_graphs_N_vertices.py b/python/Count_of_distinct_graphs_N_vertices.py new file mode 100644 index 0000000..e52d19e --- /dev/null +++ b/python/Count_of_distinct_graphs_N_vertices.py @@ -0,0 +1,27 @@ +class Solution: + def count_of_distinct_graphs(self, N): + return 2 ** (N * (N - 1) // 2) + + def test(self, n): + MOD = int(1e9 + 7) + + # Function to return the count of distinct + # graphs possible with n vertices + def countGraphs(n): + # Maximum number of edges for a + # graph with n vertices + x = (n * (n - 1)) // 2 + + # Return 2 ^ x + return (pow(2, x, MOD)) + + # Driver code + n = 5 + print(countGraphs(n)) + +Input = 3 +Output = 8 +s = Solution() +s.test(4) +# Input = 4 +# Output = 64 diff --git a/python/design_linked_list_707.py b/python/design_linked_list_707.py new file mode 100644 index 0000000..ea69759 --- /dev/null +++ b/python/design_linked_list_707.py @@ -0,0 +1,92 @@ +"""Puting name like this is for other file importing purposes""" + +class ListNode(object): + def __init__(self, x, next=None): + self.val = x + self.next = next + + +class MyLinkedList: + + def __init__(self): + # self.the_list = [] + self.dummy_head = ListNode(0) + self.size = 0 + + def get(self, index: int) -> int: + """Note that list (array) is not implemented as a Linked List on the hw for python, they have different time + complexity for both insertion and query, + see https://programmercarl.com/%E9%93%BE%E8%A1%A8%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html. Thus, no List can + be used in this func here. """ + # if self.the_list[index] is not None: + # return self.the_list[index] + if index < 0 or index >= self.size: + return -1 + + ptr = -1 + current = self.dummy_head + while ptr < index: + current = current.next + ptr += 1 + return current.val + + def addAtHead(self, val: int) -> None: + new_head = ListNode(val) + new_head.next = self.dummy_head.next + self.dummy_head.next = new_head + self.size += 1 + + def addAtTail(self, val: int) -> None: + current = self.dummy_head # init current + while current.next: # is not none then in the while loop + current = current.next # only when the tail, out loop + current.next = ListNode(val) + self.size += 1 + + def addAtIndex(self, index: int, val: int) -> None: + if index < 0 or index > self.size: + return + current = self.dummy_head + # todo using for loop is clearer + for i in range(index): + current = current.next # sliding to the one that needs to add on + current.next = ListNode(val, current.next) # adding + self.size += 1 + + def deleteAtIndex(self, index: int) -> None: + if index < 0 or index >= self.size: # if index larger or equal to the size, cannot delete thus return + return None + current = self.dummy_head + for i in range(index): + current = current.next # slide + current.next = current.next.next + self.size -= 1 + + +if __name__ == '__main__': + input_func = ["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"] + input_value = [[], [1], [3], [1, 2], [1], [1], [1]] + null = None + gt = [null, null, null, null, 2, null, 3] + # for func, val in zip(input_func, input_value): + # func = globals()[func] + # out = func(val) + # print(out) + + # obj = MyLinkedList() + # obj.addAtHead(input_value[1][0]) + # obj.addAtTail(input_value[2][0]) + # obj.addAtIndex(input_value[3][0], input_value[3][1]) + # param_1 = obj.get(input_value[4][0]) + # print(param_1) + # obj.deleteAtIndex(input_value[5][0]) + # param_2 = obj.get(input_value[6][0]) + # print(param_2) + + a = MyLinkedList() + a.addAtIndex(0, 10) + a.addAtIndex(0, 20) + a.addAtIndex(1, 30) + out1 = a.get(0) + + print(out1) diff --git a/testdome/test1.py b/testdome/test1.py new file mode 100644 index 0000000..329c1c4 --- /dev/null +++ b/testdome/test1.py @@ -0,0 +1,68 @@ +from enum import Enum + + +class Side(Enum): + none = 0 + left = 1 + right = 2 + + +class ChainLink: + + def __init__(self): + self._left = None + self._right = None + + def append(self, link): + if self._right is not None: raise Exception('Link already connected!') + self._right = link + link._left = self + + # def longer_side(self, num_left=0, num_right=0): + # if self._left is not None: + # self.left_nodes = num_left + # self.left_nodes += 1 + # self._left.longer_side(self.left_nodes, self.right_nodes) + # if self._right is not None: + # self.right_nodes = num_right + # self.right_nodes += 1 + # self._right.longer_side(self.left_nodes, self.right_nodes) + # if self.left_nodes > self.right_nodes: + # return Side.left + # elif self.left_nodes < self.right_nodes: + # return Side.right + # else: + # return Side.none + + def longer_side(self): + left_count = self.count_links(self._left, 'left') + right_count = self.count_links(self._right, 'right') + + if left_count > right_count: + return Side.left + elif right_count > left_count: + return Side.right + else: + return Side.equal + + @staticmethod + def count_links(node, direction=None): + count = 0 + while node: + count += 1 + if direction == 'left': + node = node._left + elif direction == 'right': + node = node._right + else: + raise Exception('Direction not specified!') + return count + + +if __name__ == "__main__": + left = ChainLink() + middle = ChainLink() + right = ChainLink() + left.append(middle) + middle.append(right) + print(left.longer_side() == Side.right) diff --git a/testdome/test2.py b/testdome/test2.py new file mode 100644 index 0000000..8331253 --- /dev/null +++ b/testdome/test2.py @@ -0,0 +1,49 @@ +# class MovingTotal: +# def __init__(self): +# self.numbers = [] +# +# def append(self, new_numbers): +# self.numbers.extend(new_numbers) +# +# def contains(self, target): +# return any(target == sum(self.numbers[i:i+3]) for i in range(len(self.numbers) - 2)) + +class MovingTotal: + def __init__(self): + self.numbers = [] + self.sums = set() + + def append(self, new_numbers): + for num in new_numbers: + if len(self.numbers) >= 3: + # self.sums.remove(sum(self.numbers[:3])) + self.sums.add(sum(self.numbers)) + self.numbers.pop(0) + self.numbers.append(num) + + def contains(self, target): + return target in self.sums + + +if __name__ == "__main__": + movingtotal = MovingTotal() + + movingtotal.append([1, 2, 3, 4]) + print(movingtotal.contains(6)) + print(movingtotal.contains(9)) + print(movingtotal.contains(12)) + print(movingtotal.contains(7)) + + movingtotal.append([5]) + print(movingtotal.contains(6)) + print(movingtotal.contains(9)) + print(movingtotal.contains(12)) + print(movingtotal.contains(7)) + expected = [True, + True, + False, + False, + True, + True, + True, + False] diff --git a/testdome/test3.py b/testdome/test3.py new file mode 100644 index 0000000..d0cb9b0 --- /dev/null +++ b/testdome/test3.py @@ -0,0 +1,31 @@ +# class CategoryTree: +# +# def __init__(self): +# pass +# +# def add_category(self, category, parent): +# pass +# +# def get_children(self, parent): +# return [] + + +class CategoryTree: + def __init__(self): + self.categories = {} # hashmap + + def add_category(self, category, parent): + self.categories[category] = parent + if (parent not in self.categories.keys() and parent is not None) or category in self.categories.values(): + raise KeyError + + def get_children(self, category): + return [child for child, parent in self.categories.items() if parent == category] # list comprehension + + +if __name__ == "__main__": + c = CategoryTree() + c.add_category('A', None) + c.add_category('B', 'A') + c.add_category('C', 'A') + print(','.join(c.get_children('A') or [])) pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy