diff --git a/.gitignore b/.gitignore
index a39d774..683d8b0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,7 +3,7 @@ __pycache__/
*.py[cod]
*$py.class
.idea/
-
+*.iml
# C extensions
*.so
diff --git a/README.md b/README.md
index 80a9e69..c34ae3b 100644
--- a/README.md
+++ b/README.md
@@ -2,6 +2,12 @@
Remember solutions are only solutions to given problems. If you want full study checklist for code & whiteboard interview, please turn to [jwasham's coding-interview-university](https://github.com/jwasham/coding-interview-university).
+Also, there are open source implementations for basic data structs and algorithms, such as [Algorithms in Python](https://github.com/TheAlgorithms/Python) and [Algorithms in Java](https://github.com/TheAlgorithms/Java).
+
+I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/analytics-zoo) - an unified Data Analytics and AI platform. Check it out, if you are interested in big data and deep learning.
+
+## Problems & Solutions
+
[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) |
@@ -14,19 +20,21 @@ Remember solutions are only solutions to given problems. If you want full study
| 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 |
-| 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) | [Background knowledge](http://www.rapidtables.com/convert/number/how-number-to-roman-numerals.htm) Just like 10-digit number, divide and minus |
+| 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) |
+| 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) |
@@ -62,35 +70,45 @@ Remember solutions are only solutions to given problems. If you want full study
| 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) | Add another stack for min stack, maintance this stack when the main stack pop or push |
-| 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 |
+| 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 |
+| 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) |
-| 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) | 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) |
+| 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) |
@@ -102,10 +120,12 @@ Remember solutions are only solutions to given problems. If you want full study
| 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)|
@@ -113,27 +133,130 @@ Remember solutions are only solutions to given problems. If you want full study
| 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) |
-| 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) | 1. From 1 to n, condition check
2. Condition check and string connect |
+| 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 |
|---| ----- |
| 4 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) |
-# Other Leetcode Repos
+## Other LeetCode Repos
+1. [LeetCode Algorithms ~anishLearnsToCode](https://github.com/anishLearnsToCode/leetcode-algorithms)
1. [haoel's leetcode](https://github.com/haoel/leetcode)
-2. [soulmachine's leetcode](https://github.com/soulmachine/leetcode)
-3. [kamyu104's LeetCode](https://github.com/kamyu104/LeetCode)
-4. [gouthampradhan's leetcode](https://github.com/gouthampradhan/leetcode)
+1. [soulmachine's leetcode](https://github.com/soulmachine/leetcode)
+1. [kamyu104's LeetCode](https://github.com/kamyu104/LeetCode)
+1. [gouthampradhan's leetcode](https://github.com/gouthampradhan/leetcode)
diff --git a/cpp/1248_count_number_of_nice_sub_arrays.cpp b/cpp/1248_count_number_of_nice_sub_arrays.cpp
new file mode 100644
index 0000000..1f381ed
--- /dev/null
+++ b/cpp/1248_count_number_of_nice_sub_arrays.cpp
@@ -0,0 +1,42 @@
+class Solution {
+public:
+ int numberOfSubarrays(vector& nums, int k) {
+ return atMostK(nums, k) - atMostK(nums, k - 1);
+ }
+
+private:
+ int atMostK(const vector& nums, int k) {
+ int result = 0, left = 0, count = 0;
+ for (int right = 0; right < nums.size(); ++right) {
+ count += nums[right] % 2;
+ while (count > k) {
+ count -= nums[left] % 2;
+ ++left;
+ }
+ result += right - left + 1;
+ }
+ return result;
+ }
+};
+
+// Time: O(n)
+// Space: O(k)
+class Solution2 {
+public:
+ int numberOfSubarrays(vector& nums, int k) {
+ int result = 0;
+ deque dq = {-1};
+ for (int i = 0; i < nums.size(); ++i) {
+ if (nums[i] % 2) {
+ dq.emplace_back(i);
+ }
+ if (dq.size() > k + 1) {
+ dq.pop_front();
+ }
+ if (dq.size() == k + 1) {
+ result += dq[1] - dq[0];
+ }
+ }
+ return result;
+ }
+};
diff --git a/cpp/1310_XOR_Queries_of_a_Subarray.cpp b/cpp/1310_XOR_Queries_of_a_Subarray.cpp
new file mode 100644
index 0000000..f471f7a
--- /dev/null
+++ b/cpp/1310_XOR_Queries_of_a_Subarray.cpp
@@ -0,0 +1,12 @@
+class Solution {
+public:
+ vector xorQueries(vector& arr, vector>& queries) {
+ vector res;
+ // Compute accumulated xor from head
+ for (int i = 1; i < arr.size(); i++)
+ arr[i] ^= arr[i - 1];
+ for (auto &q: queries)
+ res.push_back(q[0] > 0 ? arr[q[0] - 1] ^ arr[q[1]] : arr[q[1]]);
+ return res;
+ }
+};
diff --git a/cpp/201_bitwise_and_of_numbers_range.cpp b/cpp/201_bitwise_and_of_numbers_range.cpp
new file mode 100644
index 0000000..c0f4151
--- /dev/null
+++ b/cpp/201_bitwise_and_of_numbers_range.cpp
@@ -0,0 +1,14 @@
+/** time complexity : O(logN). N = min(m, n) **/
+
+class Solution {
+public:
+ int rangeBitwiseAnd(int m, int n) {
+ int cnt = 0;
+ while(m < n) {
+ m = m >> 1;
+ n = n >> 1;
+ cnt++;
+ }
+ return n< n / 2, we can immediately cut the total
+ * iterations half by dividing only up to n / 2. Could we still do better?
+ *
+ * Let's write down all of 12's factors:
+ *
+ * 2 × 6 = 12
+ * 3 × 4 = 12
+ * 4 × 3 = 12
+ * 6 × 2 = 12
+ *
+ * As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider
+ * factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n.
+ *
+ * Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?
+ *
+ * public int countPrimes(int n) {
+ * int count = 0;
+ * for (int i = 1; i < n; i++) {
+ * if (isPrime(i)) count++;
+ * }
+ * return count;
+ * }
+ *
+ * private boolean isPrime(int num) {
+ * if (num <= 1) return false;
+ * // Loop's ending condition is i * i <= num instead of i <= sqrt(num)
+ * // to avoid repeatedly calling an expensive function sqrt().
+ * for (int i = 2; i * i <= num; i++) {
+ * if (num % i == 0) return false;
+ * }
+ * return true;
+ * }
+ *
+ * The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n.
+ * But don't let that name scare you, I promise that the concept is surprisingly simple.
+ *
+ * [Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)
+ *
+ * [https://leetcode.com/static/images/solutions/Sieve_of_Eratosthenes_animation.gif]
+ * [http://commons.wikimedia.org/wiki/File:Sieve_of_Eratosthenes_animation.gif]
+ *
+ * Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation"()
+ * by SKopp is licensed under CC BY 2.0.
+ *
+ * * [Skoop](http://de.wikipedia.org/wiki/Benutzer:SKopp)
+ * * [CC BY 2.0](http://creativecommons.org/licenses/by/2.0/)
+ *
+ * We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2
+ * must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly,
+ * all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well.
+ * Now we look at the next number, 4, which was already marked off. What does this tell you? Should you
+ * mark off all multiples of 4 as well?
+ *
+ * 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible
+ * by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now,
+ * all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off.
+ * There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off?
+ *
+ * In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off
+ * by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current
+ * number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ...
+ * Now what should be the terminating loop condition?
+ *
+ * It is easy to say that the terminating loop condition is p n, which is certainly correct but not efficient.
+ * Do you still remember Hint #3?
+ *
+ * Yes, the terminating loop condition can be p n, as all non-primes ≥ √n must have already been marked off.
+ * When the loop terminates, all the numbers in the table that are non-marked are prime.
+ *
+ * The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n).
+ * For the more mathematically inclined readers, you can read more about its algorithm complexity on
+ * [Wikipedia](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity).
+ *
+ * public int countPrimes(int n) {
+ * boolean[] isPrime = new boolean[n];
+ * for (int i = 2; i < n; i++) {
+ * isPrime[i] = true;
+ * }
+ * // Loop's ending condition is i * i < n instead of i < sqrt(n)
+ * // to avoid repeatedly calling an expensive function sqrt().
+ * for (int i = 2; i * i < n; i++) {
+ * if (!isPrime[i]) continue;
+ * for (int j = i * i; j < n; j += i) {
+ * isPrime[j] = false;
+ * }
+ * }
+ * int count = 0;
+ * for (int i = 2; i < n; i++) {
+ * if (isPrime[i]) count++;
+ * }
+ * return count;
+ * }
+ *
+ *
+ **********************************************************************************/
+
+#include
+#include
+#include
+using namespace std;
+
+int countPrimes(int n)
+{
+ vector isPrimer(n, true);
+
+ for (int i = 2; i * i < n; i++)
+ {
+ if (isPrimer[i])
+ {
+ for (int j = i * i; j < n; j += i)
+ {
+ isPrimer[j] = false;
+ }
+ }
+ }
+
+ int cnt = 0;
+ for (int i = 2; i < n; i++)
+ {
+ if (isPrimer[i])
+ {
+ //cout << i << ", ";
+ cnt++;
+ }
+ }
+ return cnt;
+}
+
+int main(int argc, char **argv)
+{
+ int n = 100;
+ if (argc > 1)
+ {
+ n = atoi(argv[1]);
+ }
+
+ cout << endl
+ << n << " : " << countPrimes(n) << endl;
+
+ return 0;
+}
diff --git a/cpp/206_Reverse_Linked_List.cpp b/cpp/206_Reverse_Linked_List.cpp
new file mode 100644
index 0000000..84bf495
--- /dev/null
+++ b/cpp/206_Reverse_Linked_List.cpp
@@ -0,0 +1,30 @@
+/**
+ * Definition for singly-linked list.
+ * struct ListNode {
+ * int val;
+ * ListNode *next;
+ * ListNode(int x) : val(x), next(NULL) {}
+ * };
+ */
+class Solution {
+public:
+ ListNode *reverseList(ListNode *head) {
+ if (head == NULL)
+ return NULL;
+ if (head->next == NULL)
+ return head;
+ // Previous pointer
+ ListNode *previous = head;
+ // Current pointer
+ ListNode *curr = head->next;
+ head->next = NULL;
+ while (curr->next) {
+ ListNode *next = curr->next;
+ curr->next = previous;
+ previous = curr;
+ curr = next;
+ }
+ curr->next = previous;
+ return curr;
+ }
+};
diff --git a/cpp/2553_Separate_the_Digits_in_an_Array.cpp b/cpp/2553_Separate_the_Digits_in_an_Array.cpp
new file mode 100644
index 0000000..e88e8c6
--- /dev/null
+++ b/cpp/2553_Separate_the_Digits_in_an_Array.cpp
@@ -0,0 +1,19 @@
+class Solution {
+public:
+ vector separateDigits(vector& nums) {
+ vector answer;
+ int n;
+ for( int i=0; i < nums.size(); i++){
+ n=nums[i];
+ vector temp;
+ while( n>0 ){
+ temp.push_back(n%10);
+ n = n / 10;
+ }
+ for(int j= temp.size()-1; j>=0; j--){
+ answer.push_back(temp[j]);
+ }
+ }
+ return answer;
+ }
+};
diff --git a/cpp/282_Expression_Add_Operators.cpp b/cpp/282_Expression_Add_Operators.cpp
new file mode 100644
index 0000000..2d8b2c9
--- /dev/null
+++ b/cpp/282_Expression_Add_Operators.cpp
@@ -0,0 +1,53 @@
+class Solution {
+public:
+ vector addOperators(string num, int target) {
+ vector result;
+ if (num.size() == 0) return result;
+ findSolution(num, target, result, "", 0, 0, 0, ' ');
+ return result;
+ }
+
+ //DFS algorithm
+ void findSolution(const string &num, const int target,
+ vector& result,
+ string solution,
+ int idx,
+ long long val,
+ long long prev,
+ char preop )
+ {
+
+ if (target == val && idx == num.size()){
+ result.push_back(solution);
+ return;
+ }
+ if (idx == num.size()) return;
+
+ string n;
+ long long v=0;
+ for(int i=idx; i fizzBuzz(int n) {
+ int i;
+ vector s;
+ for (i = 0; i < n; i++) {
+ if ((i + 1) % 15 == 0)
+ s.pb("FizzBuzz");
+ else if ((i + 1) % 5 == 0)
+ s.pb("Buzz");
+ else if ((i + 1) % 3 == 0)
+ s.pb("Fizz");
+ else
+ s.pb(to_string(i + 1));
+ }
+ return s;
+ }
+};
diff --git a/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp b/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp
new file mode 100644
index 0000000..1476598
--- /dev/null
+++ b/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp
@@ -0,0 +1,29 @@
+class Solution {
+public:
+#define ll long long int
+ bool valid(ll x, int m, int n, int k) {
+ int cnt = 0;
+ for (int i = 1; i <= m; i++) {
+ cnt += n < x / i ? n : x / i;
+ if (x / i == 0)
+ break;
+ }
+ return cnt >= k;
+ }
+
+ int findKthNumber(int n1, int n2, int k) {
+ ll l = 0, r = n1 * n2, ans;
+ while (l <= r) {
+ // ith row [i, 2*i, 3*i, ..., n*i]
+ // for each column, k = x // i
+ ll m = l + (r - l) / 2;
+ if (valid(m, n1, n2, k)) {
+ ans = m;
+ r = m - 1;
+ } else {
+ l = m + 1;
+ }
+ }
+ return ans;
+ }
+};
diff --git a/cpp/923_3_sum_with_multiplicity.cpp b/cpp/923_3_sum_with_multiplicity.cpp
new file mode 100644
index 0000000..5b7b2b4
--- /dev/null
+++ b/cpp/923_3_sum_with_multiplicity.cpp
@@ -0,0 +1,26 @@
+class Solution {
+public:
+ int threeSumMulti(vector& A, int target) {
+ unordered_map count;
+ for (const auto& a : A) {
+ ++count[a];
+ }
+ uint64_t result = 0;
+ for (const auto& kvp1 : count) {
+ for (const auto& kvp2 : count) {
+ int i = kvp1.first, j = kvp2.first, k = target - i - j;
+ if (!count.count(k)) {
+ continue;
+ }
+ if (i == j && j == k) {
+ result += count[i] * (count[i] - 1) * (count[i] - 2) / 6;
+ } else if (i == j && j != k) {
+ result += count[i] * (count[i] - 1) / 2 * count[k];
+ } else if (i < j && j < k) {
+ result += count[i] * count[j] * count[k];
+ }
+ }
+ }
+ return result % static_cast(1e9 + 7);
+ }
+};
diff --git a/create_empty_files.py b/create_empty_files.py
new file mode 100644
index 0000000..8b60d8d
--- /dev/null
+++ b/create_empty_files.py
@@ -0,0 +1,14 @@
+import sys
+
+if __name__ == '__main__':
+ file_name = 'test'
+ try:
+ file_name = sys.argv[1]
+ except IndexError:
+ print("Usage: python create_empty_file [filename]")
+ print("Creating " + file_name + "in java and python dir...")
+ with open("python/" + file_name + ".py", 'w'):
+ pass
+ with open("java/" + file_name + ".java", 'w'):
+ pass
+ print("Done!")
diff --git a/java/006_ZigZag_Conversion.java b/java/006_ZigZag_Conversion.java
index ea64188..97e4b1a 100644
--- a/java/006_ZigZag_Conversion.java
+++ b/java/006_ZigZag_Conversion.java
@@ -1 +1,33 @@
-//TODO
\ No newline at end of file
+//006_ZigZag_Conversion.java
+class Solution {
+ public String convert(String s, int numRows) {
+ if(numRows==1) {
+ return s;
+ }
+
+ String answer = "";
+ String[] str_array = new String[numRows];
+
+ for(int i=0;i= numRows) {
+ index = 2*(numRows-1) - index;
+ }
+ str_array[index]+=c;
+ }
+
+ for(int i=0;i map = new HashMap();
+ map.put(1, "I"); map.put(5, "V"); map.put(10, "X");
+ map.put(50, "L"); map.put(100, "C"); map.put(500, "D"); map.put(1000, "M");
+ map.put(4, "IV"); map.put(9, "IX"); map.put(40, "XL"); map.put(90, "XC");
+ map.put(400, "CD"); map.put(900, "CM");
+
+ int[] sequence = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
+
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i= base) {
+ sb.append(map.get(base));
+ num -= base;
+ }
+ }
+
+ return sb.toString();
+ }
+}
diff --git a/java/013_Roman_to_Integer.java b/java/013_Roman_to_Integer.java
new file mode 100644
index 0000000..90393e6
--- /dev/null
+++ b/java/013_Roman_to_Integer.java
@@ -0,0 +1,23 @@
+class Solution {
+ public int romanToInt(String s) {
+ int[] arr = new int['A' + 26];
+ arr['I'] = 1;
+ arr['V'] = 5;
+ arr['X'] = 10;
+ arr['L'] = 50;
+ arr['C'] = 100;
+ arr['D'] = 500;
+ arr['M'] = 1000;
+
+ int result = 0;
+ int prev = 0;
+
+ for (int i = s.length() - 1; i >= 0; i--) {
+ int current = arr[s.charAt(i)];
+ result += prev > current ? -current : current;
+ prev = current;
+ }
+
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/java/014_Longest_Common_Prefix.java b/java/014_Longest_Common_Prefix.java
new file mode 100644
index 0000000..4ff7134
--- /dev/null
+++ b/java/014_Longest_Common_Prefix.java
@@ -0,0 +1,33 @@
+//014_Longest_Common_Prefix.java
+class Solution {
+ public String longestCommonPrefix(String[] strs) {
+ String result ="";
+ String temp = "";
+ int c = 0; //move first point
+ boolean check = true;
+ while(true){
+ for(int i = 0; i=strs[i].length()){
+ check = false;
+ break;
+ }
+ if(i==0){ //temp -> check same Character
+ temp = Character.toString(strs[0].charAt(c));
+ }
+ if(!temp.equals(Character.toString(strs[i].charAt(c)))){
+ check = false;
+ break;
+ }
+ if(i==strs.length-1){
+ result += temp;
+ }
+ }
+ if(!check){
+ break;
+ }
+ c++;
+ }
+ return result;
+
+ }
+}
\ No newline at end of file
diff --git a/java/015_3Sum.java b/java/015_3Sum.java
new file mode 100644
index 0000000..cc0a069
--- /dev/null
+++ b/java/015_3Sum.java
@@ -0,0 +1,47 @@
+//015. 3Sum
+class Solution {
+ public List> threeSum(int[] nums) {
+ //create result list to store i,j,k
+ List> result = new LinkedList>();
+
+ //sorting nums
+ Arrays.sort(nums);
+
+ for (int i = 0; i < nums.length - 2; i++) {
+
+ int left = i + 1;
+ int right = nums.length - 1;
+
+ if (i > 0 && nums[i] == nums[i-1]) {
+ continue; //if nums have same numbers, just check one time.
+ }
+
+ while (left < right) {
+ int sum = nums[left] + nums[right] + nums[i];
+
+ if (sum == 0) {
+ //if sum == 0, store i,j,k
+ result.add(Arrays.asList(nums[i], nums[left], nums[right]));
+ left++; //check anoter case
+ right--;
+ //if next number == now number
+ while (nums[left] == nums[left - 1] && left < right) {
+ left++;
+ }
+ while (nums[right] == nums[right + 1] && left < right) {
+ right--;
+ }
+ } else if (sum > 0) {
+ //if sum > 0, right--;
+ right--;
+ } else {
+ //if sum < 0, left++;
+ left++;
+ }
+ }
+ }
+
+ return result; //return result list
+ }
+}
+
diff --git a/java/019_Remove_Nth_Node_From_End_of_List.java b/java/019_Remove_Nth_Node_From_End_of_List.java
new file mode 100644
index 0000000..6ae9ce7
--- /dev/null
+++ b/java/019_Remove_Nth_Node_From_End_of_List.java
@@ -0,0 +1,63 @@
+/*Given a linked list, remove the n-th node from the end of list and return its head.
+
+Example:
+Given linked list: 1->2->3->4->5, and n = 2.
+After removing the second node from the end, the linked list becomes 1->2->3->5.
+
+Note:
+Given n will always be valid.
+
+Follow up:
+Could you do this in one pass?*/
+
+/**
+ * Definition for singly-linked list.
+ * public class ListNode {
+ * int val;
+ * ListNode next;
+ * ListNode(int x) { val = x; }
+ * }
+ */
+class Solution {
+ /*public ListNode removeNthFromEnd(ListNode head, int n) {
+ ListNode curr = head;
+ int ls = 0;
+ while (curr != null) {
+ curr = curr.next;
+ ls++;
+ }
+ // n == len
+ if (ls == n) {
+ if (ls > 1) return head.next;
+ return null;
+ }
+ curr = head;
+ // Move to ls - n - 1
+ for (int i = 0; i < ls - n - 1; i++) {
+ curr = curr.next;
+ }
+ // Remove ls - n - 1
+ curr.next = curr.next.next;
+ return head;
+ }*/
+
+ public ListNode removeNthFromEnd(ListNode head, int n) {
+ ListNode slow, fast, curr;
+ slow = head; fast = head;
+ for (int i = 0; i < n; i++)
+ fast = fast.next;
+ // n == len
+ if (fast == null) {
+ head = head.next;
+ return head;
+ }
+ // Move both pointers, until reach tail
+ while (fast.next != null) {
+ fast = fast.next;
+ slow = slow.next;
+ }
+ curr = slow.next;
+ slow.next = curr.next;
+ return head;
+ }
+}
diff --git a/java/026_Remove_Duplicates_from_Sorted_Array.java b/java/026_Remove_Duplicates_from_Sorted_Array.java
new file mode 100644
index 0000000..13f03b1
--- /dev/null
+++ b/java/026_Remove_Duplicates_from_Sorted_Array.java
@@ -0,0 +1,16 @@
+//026. Remove Duplicates from Sorted Array
+class Solution {
+ public int removeDuplicates(int[] nums) {
+ int index = 1;
+
+ for (int i = 0; i < nums.length - 1; i++) {
+ if (nums[i] != nums[i + 1]) {
+ nums[index] = nums[i + 1];
+ index++;
+ }
+ }
+
+ return index;
+ }
+}
+
diff --git a/java/034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java b/java/034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java
new file mode 100644
index 0000000..01a70a7
--- /dev/null
+++ b/java/034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java
@@ -0,0 +1,59 @@
+class Solution {
+ /*
+ Rule 1
+ - Given array is sorted in non-decreasing order
+
+ Rule 2
+ - Limit time complexity O(log n).
+
+ So I can use Binary Search Algorithm.
+ */
+ public int[] searchRange(int[] nums, int target) {
+ // initialize arr[0] -> maximum integer, arr[1] -> minimum integer
+ int[] arr = {100001, -10};
+ int s = 0;
+ int e = nums.length - 1;
+
+ // find minimum index in nums with Binary Search alogorithm
+ while (s <= e) {
+
+ int mid = (s + e) / 2;
+
+ if(nums[mid] > target) {
+ e = mid - 1;
+ }
+ else if(nums[mid] <= target) {
+ if(nums[mid] == target) {
+ arr[0] = Math.min(arr[0], mid);
+ arr[1] = Math.max(arr[1], mid);
+ }
+ s = mid + 1;
+ }
+ }
+
+ s = 0;
+ e = nums.length - 1;
+
+ // find maximum index in nums with Binary Search alogorithm
+ while(s <= e) {
+ int mid = (s + e) / 2;
+
+ if(nums[mid] >= target) {
+ if(nums[mid] == target) {
+ arr[0] = Math.min(arr[0], mid);
+ arr[1] = Math.max(arr[1], mid);
+ }
+ e = mid - 1;
+ }
+ else if(nums[mid] < target) {
+ s = mid + 1;
+ }
+ }
+
+ // if arr data is initial data, set -1.
+ if(arr[0] == 100001) arr[0] = -1;
+ if(arr[1] == -10) arr[1] = -1;
+
+ return arr;
+ }
+}
diff --git a/java/039_Combination_Sum.java b/java/039_Combination_Sum.java
new file mode 100644
index 0000000..7a54dd3
--- /dev/null
+++ b/java/039_Combination_Sum.java
@@ -0,0 +1,29 @@
+//039_Combination_Sum
+class Solution {
+ List> answer = new ArrayList>();
+
+ public List> combinationSum(int[] candidates, int target) {
+ int clen =candidates.length;
+ for (int i = 0; i < clen; i++) {
+ List tlist = new ArrayList();
+ tlist.add(candidates[i]);
+ backtracking(candidates, i, 1, (target - candidates[i]), tlist);
+ }
+ return answer;
+ }
+ private void backtracking(int[] candidates, int index, int tsize, int target, List temp) {
+ if (target == 0) {
+ answer.add(new ArrayList(temp));
+ return;
+ }
+
+ for (int i = index, len = candidates.length; i < len; i++) {
+ if (candidates[i] <= target) {
+ temp.add(candidates[i]);
+ backtracking(candidates, i, (tsize + 1), (target - candidates[i]), temp);
+ temp.remove(tsize);
+ }
+ }
+ }
+}
+
diff --git a/java/049_Group_Anagrams.java b/java/049_Group_Anagrams.java
new file mode 100644
index 0000000..a787625
--- /dev/null
+++ b/java/049_Group_Anagrams.java
@@ -0,0 +1,42 @@
+class Solution {
+ public List> groupAnagrams(String[] strs) {
+ int[][] alphabets = new int[strs.length]['z' - 'a' + 1];
+
+ for(int i = 0; i < strs.length; i++) {
+ String str = strs[i];
+
+ for(int j = 0; j < str.length(); j++)
+ alphabets[i][str.charAt(j) - 'a']++;
+ }
+
+ boolean[] visited = new boolean[strs.length];
+
+ List> answer = new ArrayList<>();
+
+ for(int i = 0; i < strs.length; i++) {
+ if(visited[i]) continue;
+
+ List list = new ArrayList<>();
+
+ for(int j = i; j < strs.length; j++) {
+ if(visited[j]) continue;
+ if(isAnagram(alphabets[i], alphabets[j])) {
+ list.add(strs[j]);
+ visited[j] = true;
+ }
+ }
+
+ answer.add(list);
+ }
+
+ return answer;
+ }
+
+ public boolean isAnagram(int[] arr1, int[] arr2) {
+ for(int i = 0; i < arr1.length; i++) {
+ if(arr1[i] != arr2[i])
+ return false;
+ }
+ return true;
+ }
+}
diff --git a/java/055_Jump_Game.java b/java/055_Jump_Game.java
new file mode 100644
index 0000000..50971d4
--- /dev/null
+++ b/java/055_Jump_Game.java
@@ -0,0 +1,49 @@
+import java.util.*;
+
+class Solution {
+ public boolean canJump(int[] nums) {
+ /*
+ * Constraints
+ * 1 <= nums.length <= 10^4
+ * 0 <= nums[i] <= 10^5
+ *
+ * Solution
+ * 1. Use BFS Algorithm.
+ * - reason 1 : have to ignore array which is not visited.
+ * - reason 2 : we have to visit all possible array from array[start].
+ */
+
+ int N = nums.length;
+ ArrayDeque q = new ArrayDeque<>();
+ boolean[] visited = new boolean[N];
+
+ // First, add first array index.
+ // And, set visited[first_index] to true.
+ q.add(0);
+ visited[0] = true;
+
+ // Axiom : if N is 1, result is true.
+ if(N == 1) return true;
+
+ // BFS algorithm
+ while(!q.isEmpty()) {
+ int cur = q.poll();
+
+ // find cur + 1 to cur + nums[cur]
+ for(int i = 1; i <= nums[cur]; i++) {
+ if(cur + i >= N - 1) return true;
+ int next = Math.min(cur + i, N - 1);
+
+ // set visited[next] to true and add index into queue.
+ // because of time limit(No overlap steps.)
+ if(!visited[next]) {
+ visited[next] = true;
+ q.add(next);
+ }
+ }
+ }
+
+ return false;
+
+ }
+}
\ No newline at end of file
diff --git a/java/066_Plus_One.java b/java/066_Plus_One.java
new file mode 100644
index 0000000..a9e474f
--- /dev/null
+++ b/java/066_Plus_One.java
@@ -0,0 +1,23 @@
+class Solution {
+ public int[] plusOne(int[] digits) {
+ return addToDigit(digits, digits.length - 1);
+ }
+
+ private int[] addToDigit(int[] digits, int index) {
+ if (index == -1) {
+ int[] newDigits = new int[digits.length + 1];
+ newDigits[0] = 1;
+ for (int i = 0; i < digits.length; i++) {
+ newDigits[i + 1] = digits[i];
+ }
+ return newDigits;
+ }
+ if (digits[index] == 9) {
+ digits[index] = 0;
+ return addToDigit(digits, index - 1);
+ } else {
+ digits[index]++;
+ return digits;
+ }
+ }
+}
diff --git a/java/088_Merge_Sorted_Array.java b/java/088_Merge_Sorted_Array.java
new file mode 100644
index 0000000..95c7c8e
--- /dev/null
+++ b/java/088_Merge_Sorted_Array.java
@@ -0,0 +1,29 @@
+class Solution {
+ //we are being given two int arrays and two int variables that state the number of elements in each array, respectively
+ public void merge(int[] nums1, int m, int[] nums2, int n) {
+ //I am using a counter so that I can iterate through the second array inside the for loop
+ int counter = 0;
+ //We know that nums1 is of the size n + m, so we can add all the elements to the array and sort them later
+ //For loop adds all values of nums2 to the end of nums1
+ for(int i=m; i nums1[j+1]){
+ int temp = nums1[j+1];
+ nums1[j+1] = nums1[j];
+ nums1[j] = temp;
+ }
+ }
+ }
+ //The following function simply prints out everything that is contained within our num1 array
+ for(int i=0; i i, then i can never be greater than A[i] any more
+ if (A[i] == i) return i;
+ else if (A[i] > i) return -1;
+ }
+ return -1;
+ } */
+ public int fixedPoint(int[] A) {
+ int l = 0;
+ int h = A.length;
+ while (l <= h) {
+ int mid = (l + h) / 2;
+ if (A[mid] > mid) h = mid - 1;
+ else if (A[mid] < mid) l = mid + 1;
+ else return mid;
+ }
+ return -1;
+ }
+}
diff --git a/java/1089_Duplicate_Zeros.java b/java/1089_Duplicate_Zeros.java
new file mode 100644
index 0000000..c067ef3
--- /dev/null
+++ b/java/1089_Duplicate_Zeros.java
@@ -0,0 +1,28 @@
+class Solution {
+ public void duplicateZeros(int[] arr) {
+ int movePos = 0;
+ int lastPos = arr.length - 1;
+ // Only check [0, lastPos - movePos]
+ for (int i = 0; i <= lastPos - movePos; i++) {
+ if (arr[i] == 0) {
+ // Special case
+ if (i == lastPos - movePos) {
+ arr[lastPos] = 0;
+ lastPos--;
+ break;
+ }
+ movePos++;
+ }
+ }
+ lastPos = lastPos - movePos;
+ for (int i = lastPos; i >= 0; i--) {
+ if (arr[i] == 0) {
+ arr[i + movePos] = 0;
+ movePos--;
+ arr[i + movePos] = 0;
+ } else {
+ arr[i + movePos] = arr[i];
+ }
+ }
+ }
+}
diff --git a/java/1108_Defanging_an_IP_Address.java b/java/1108_Defanging_an_IP_Address.java
new file mode 100644
index 0000000..538156d
--- /dev/null
+++ b/java/1108_Defanging_an_IP_Address.java
@@ -0,0 +1,22 @@
+class Solution {
+ public String defangIPaddr(String address) {
+ // replace
+ return address.replace(".", "[.]");
+ }
+ /* public String defangIPaddr(String address) {
+ // split and join
+ return String.join("[.]", address.split("\\."));
+ } */
+ /* public String defangIPaddr(String address) {
+ // replace
+ return address.replaceAll("\\.", "[.]");
+ } */
+ /* public String defangIPaddr(String address) {
+ // new string
+ StringBuilder sb = new StringBuilder();
+ for (char c : address.toCharArray()) {
+ sb.append(c == '.' ? "[.]" : c);
+ }
+ return sb.toString();
+ } */
+}
diff --git a/java/1189_Maximum_Number_of_Balloons.java b/java/1189_Maximum_Number_of_Balloons.java
new file mode 100644
index 0000000..4564c55
--- /dev/null
+++ b/java/1189_Maximum_Number_of_Balloons.java
@@ -0,0 +1,32 @@
+class Solution {
+ public int maxNumberOfBalloons(String text) {
+ HashMap map = new HashMap<>();
+
+ for (char ch : text.toCharArray()) {
+ map.put(ch, map.getOrDefault(ch, 0) + 1);
+ }
+
+ int res = Integer.MAX_VALUE;
+
+ res = Math.min(res, map.getOrDefault('b', 0));
+ res = Math.min(res, map.getOrDefault('a', 0));
+ res = Math.min(res, map.getOrDefault('n', 0));
+ res = Math.min(res, map.getOrDefault('l', 0) / 2);
+ res = Math.min(res, map.getOrDefault('o', 0) / 2);
+
+ return res;
+ }
+
+ /*
+ // by @javadev
+ public int maxNumberOfBalloons(String text) {
+ int[] counts = new int[26];
+ for (char c : text.toCharArray()) {
+ counts[c - 'a']++;
+ }
+ return Math.min(
+ counts[0],
+ Math.min(
+ counts[1], Math.min(counts[11] / 2, Math.min(counts[14] / 2, counts[13]))));
+ }*/
+}
diff --git a/java/1260_Shift_2D_Grid.java b/java/1260_Shift_2D_Grid.java
new file mode 100644
index 0000000..2c4369b
--- /dev/null
+++ b/java/1260_Shift_2D_Grid.java
@@ -0,0 +1,32 @@
+class Solution {
+ public List> shiftGrid(int[][] grid, int k) {
+ int[][] newGrid = new int[grid.length][grid[0].length];
+ int m = grid.length;
+ int n = grid[0].length;
+ // Compute final move
+ int true_k = k % (m * n);
+ // Row move
+ int move_i = true_k / n;
+ // Column move
+ int move_j = true_k % n;
+
+ for (int i = 0; i < grid.length; i++) {
+ for (int j = 0; j < grid[i].length; j++) {
+ int new_i = i + move_i;
+ int new_j = (j + move_j) % n;
+ // Move 1 row if (move_j + j >= n
+ if (move_j + j >= n) new_i ++;
+ new_i %= m;
+ newGrid[new_i][new_j] = grid[i][j];
+ }
+ }
+ // Copy the grid into a list for returning.
+ List> result = new ArrayList<>();
+ for (int[] row : newGrid) {
+ List listRow = new ArrayList<>();
+ result.add(listRow);
+ for (int v : row) listRow.add(v);
+ }
+ return result;
+ }
+}
diff --git a/java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java b/java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java
new file mode 100644
index 0000000..8847ff1
--- /dev/null
+++ b/java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java
@@ -0,0 +1,9 @@
+public int[] sumZero(int n) {
+ int[] res = new int[n];
+ // place negative sum(from 1 to n-1) in 0
+ for (int i = 1; i < n; i++) {
+ res[i] = i;
+ res[0] -= i;
+ }
+ return res;
+}
diff --git a/java/1310_XOR_Queries_of_a_Subarray.java b/java/1310_XOR_Queries_of_a_Subarray.java
new file mode 100644
index 0000000..c2b4d97
--- /dev/null
+++ b/java/1310_XOR_Queries_of_a_Subarray.java
@@ -0,0 +1,14 @@
+class Solution {
+ public int[] xorQueries(int[] arr, int[][] queries) {
+ int[] res = new int[queries.length], q;
+ // Compute accumulated xor from head
+ for (int i = 1; i < arr.length; i++)
+ arr[i] ^= arr[i - 1];
+ // query result equals to xor[0, l] xor xor[0, r]
+ for (int i = 0; i < queries.length; i++) {
+ q = queries[i];
+ res[i] = q[0] > 0 ? arr[q[0] - 1] ^ arr[q[1]] : arr[q[1]];
+ }
+ return res;
+ }
+}
diff --git a/java/1323_Maximum_69_Number.java b/java/1323_Maximum_69_Number.java
new file mode 100644
index 0000000..f3ce8c3
--- /dev/null
+++ b/java/1323_Maximum_69_Number.java
@@ -0,0 +1,19 @@
+class Solution {
+ public int maximum69Number (int num) {
+ // Replace first 6 with 9 if exists
+ return Integer.valueOf(String.valueOf(num).replaceFirst("6", "9"));
+ }
+
+ /*
+ public int maximum69Number (int num) {
+ char[] chars = Integer.toString(num).toCharArray();
+ // Replace first 6 with 9 if exists
+ for (int i = 0; i < chars.length; i++) {
+ if (chars[i] == '6') {
+ chars[i] = '9';
+ break;
+ }
+ }
+ return Integer.parseInt(new String(chars));
+ }*/
+}
diff --git a/java/1337_The_K_Weakest_Rows_in_a_Matrix.java b/java/1337_The_K_Weakest_Rows_in_a_Matrix.java
new file mode 100644
index 0000000..fb50cde
--- /dev/null
+++ b/java/1337_The_K_Weakest_Rows_in_a_Matrix.java
@@ -0,0 +1,30 @@
+class Solution {
+ public int[] kWeakestRows(int[][] mat, int k) {
+ List res = new ArrayList<>();
+ int col = 0;
+ boolean flag = true;
+ while (col < mat[0].length && flag) {
+ for (int i = 0; i < mat.length; i++) {
+ if (res.contains(i)) continue;
+ // Add first row with 0 into res
+ if (mat[i][col] == 0) res.add(i);
+ if (res.size() == k) {
+ flag = false;
+ break;
+ }
+ }
+ col += 1;
+ }
+ if (flag) {
+ // if res less than k
+ for (int i = 0; i < mat.length; i++) {
+ if (res.contains(i)) continue;
+ res.add(i);
+ if (res.size() == k) break;
+ }
+ }
+ int[] ret = new int[k];
+ for (int i = 0; i < k; i++) ret[i] = res.get(i);
+ return ret;
+ }
+}
diff --git a/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java b/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java
new file mode 100644
index 0000000..2b9a04c
--- /dev/null
+++ b/java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java
@@ -0,0 +1,34 @@
+import java.util.Map;
+
+class Solution {
+/* public int[] smallerNumbersThanCurrent(int[] nums) {
+ Map sortedIndex = new HashMap<>();
+ int[] sortedNums = new int[nums.length];
+ // sort and get position
+ System.arraycopy(nums, 0, sortedNums, 0, nums.length);
+ Arrays.sort(sortedNums);
+ for (int i = 0; i < nums.length; i++) {
+ if (sortedIndex.containsKey(sortedNums[i])) continue;
+ sortedIndex.put(sortedNums[i], i);
+ }
+ for (int i = 0; i < nums.length; i++)
+ sortedNums[i] = sortedIndex.get(nums[i]);
+ return sortedNums;
+ } */
+
+ public int[] smallerNumbersThanCurrent(int[] nums) {
+ int[] countList = new int[101];
+ int[] res = new int[nums.length];
+ // count numbers
+ for (int i = 0; i < nums.length; i++)
+ countList[nums[i]]++;
+ // compute numbers before current index
+ for (int i = 1; i < 101; i++)
+ countList[i] += countList[i-1];
+ for (int i = 0; i < nums.length; i++) {
+ if (nums[i] == 0) res[i] = 0;
+ else res[i] = countList[nums[i]-1];
+ }
+ return res;
+ }
+}
diff --git a/java/1480_Running_Sum_of_1d_Array.java b/java/1480_Running_Sum_of_1d_Array.java
new file mode 100644
index 0000000..15ba2ee
--- /dev/null
+++ b/java/1480_Running_Sum_of_1d_Array.java
@@ -0,0 +1,8 @@
+class Solution {
+ public int[] runningSum(int[] nums) {
+ if (nums.length <= 1) return nums;
+ for (int i = 1; i < nums.length; i++)
+ nums[i] += nums[i - 1];
+ return nums;
+ }
+}
diff --git a/java/1539_Kth_Missing_Positive_Number.java b/java/1539_Kth_Missing_Positive_Number.java
new file mode 100644
index 0000000..972aa8d
--- /dev/null
+++ b/java/1539_Kth_Missing_Positive_Number.java
@@ -0,0 +1,43 @@
+class Solution {
+ public int findKthPositive(int[] a, int k) {
+ int B[] = new int[a.length];
+
+ // equation (A)
+ // B[i]=a[i]-i-1
+ // B[i]=number of missing numbers BEFORE a[i]
+ for (int i = 0; i < a.length; i++)
+ B[i] = a[i] - i - 1; // -1 is done as here missing numbers start from 1 and not 0
+
+ // binary search upper bound of k
+ // smallest value>=k
+
+ int lo = 0, hi = B.length - 1;
+
+ while (lo <= hi) {
+ int mid = lo + (hi - lo) / 2;
+
+ if (B[mid] >= k)
+ hi = mid - 1;
+ else
+ lo = mid + 1;
+ }
+
+ // lo is the answer
+
+ /*
+ * now the number to return is a[lo]-(B[lo]-k+1) (EQUATION B)
+ * where (B[lo]-k+1) is the number of steps we need to go back
+ * from lo to retrieve kth missing number, since we need to find
+ * the kth missing number BEFORE a[lo], we do +1 here as
+ * a[lo] is not a missing number when B[lo]==k
+ * putting lo in equation(A) above
+ * B[i]=a[i]-i-1
+ * B[lo]=a[lo]-lo-1
+ * and using this value of B[lo] in equation B
+ * we return a[lo]-(a[lo]-lo-1-k+1)
+ * we get lo+k as ans
+ * so return it
+ */
+ return lo + k;
+ }
+}
diff --git a/java/155_Min_Stack.java b/java/155_Min_Stack.java
new file mode 100644
index 0000000..a298253
--- /dev/null
+++ b/java/155_Min_Stack.java
@@ -0,0 +1,62 @@
+import java.util.ArrayList;
+import java.util.List;
+
+/* class MinStack {
+ private Stack stack;
+ private Stack minStack;
+ public MinStack() {
+ stack = new Stack<>();
+ minStack = new Stack<>();
+ }
+
+ public void push(int x) {
+ stack.push(x);
+ if (minStack.size() == 0 || x <= minStack.peek()) minStack.push(x);
+ }
+
+ public void pop() {
+ if (stack.size() > 0) {
+ int curr = stack.pop();
+ if (minStack.size() > 0 && curr == minStack.peek()) minStack.pop();
+ }
+ }
+
+ public int top() {
+ return stack.peek();
+ }
+
+ public int getMin() {
+ if (minStack.size() > 0)
+ return minStack.peek();
+ else
+ return stack.peek();
+ }
+} */
+
+class MinStack {
+ private Stack stack;
+ private Stack minStack;
+ public MinStack() {
+ stack = new Stack<>();
+ minStack = new Stack<>();
+ }
+
+ public void push(int x) {
+ stack.push(x);
+ if (minStack.size() == 0 || x <= minStack.peek()) minStack.push(x);
+ else minStack.push(minStack.peek());
+ }
+
+ public void pop() {
+ stack.pop();
+ minStack.pop();
+ }
+
+ public int top() {
+ return stack.peek();
+ }
+
+ public int getMin() {
+ return minStack.peek();
+ }
+}
diff --git a/java/179_Largest_Number.java b/java/179_Largest_Number.java
new file mode 100644
index 0000000..1455406
--- /dev/null
+++ b/java/179_Largest_Number.java
@@ -0,0 +1,34 @@
+class Solution {
+ private class LargerNumberComparator implements Comparator {
+ @Override
+ public int compare(String a, String b) {
+ String order1 = a + b;
+ String order2 = b + a;
+ return order2.compareTo(order1);
+ }
+ }
+
+ public String largestNumber(int[] nums) {
+ // Get input integers as strings.
+ String[] asStrs = new String[nums.length];
+ for (int i = 0; i < nums.length; i++) {
+ asStrs[i] = String.valueOf(nums[i]);
+ }
+
+ // Sort strings according to custom comparator.
+ Arrays.sort(asStrs, new LargerNumberComparator());
+
+ // If, after being sorted, the largest number is `0`, the entire number
+ // is zero.
+ if (asStrs[0].equals("0")) {
+ return "0";
+ }
+
+ // Build largest number from sorted array.
+ String largestNumberStr = new String();
+ for (String numAsStr : asStrs) {
+ largestNumberStr += numAsStr;
+ }
+ return largestNumberStr;
+ }
+}
diff --git a/java/17_Letter_Combinations_of_a_Phone_Number.java b/java/17_Letter_Combinations_of_a_Phone_Number.java
new file mode 100644
index 0000000..7588d2c
--- /dev/null
+++ b/java/17_Letter_Combinations_of_a_Phone_Number.java
@@ -0,0 +1,40 @@
+class Solution {
+ // make list for return.
+ public ArrayList list = new ArrayList<>();
+ // make array for get phone number's characters.
+ public char[][] arr = {
+ {'0', '0', '0', '-'},
+ {'0', '0', '0', '-'},
+ {'a', 'b', 'c', '-'},
+ {'d', 'e', 'f', '-'},
+ {'g', 'h', 'i', '-'},
+ {'j', 'k', 'l', '-'},
+ {'m', 'n', 'o', '-'},
+ {'p', 'q', 'r', 's'},
+ {'t', 'u', 'v', '-'},
+ {'w', 'x', 'y', 'z'},
+ };
+
+ // main function
+ public List letterCombinations(String digits) {
+ addString(digits, 0, "");
+ return list;
+ }
+
+ // axiom : if input == "", return []
+ // if index == digits.length(), add str in list
+ // else do loop number's character, and function recursion.
+ public void addString(String digits, int index, String str) {
+ if(digits.equals("")) return;
+ if(index == digits.length()) {
+ list.add(str);
+ }
+ else {
+ for(int i = 0; i < 4; i++) {
+ int number = Integer.parseInt(digits.charAt(index) + "");
+ if(arr[number][i] == '-') continue;
+ addString(digits, index + 1, str + arr[number][i]);
+ }
+ }
+ }
+}
diff --git a/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java b/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java
new file mode 100644
index 0000000..02f474a
--- /dev/null
+++ b/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java
@@ -0,0 +1,29 @@
+class Solution {
+ public int minimizeTheDifference(int[][] a, int k) {
+ n = a.length;
+ m = a[0].length;
+ min = Integer.MAX_VALUE;
+ dp = new boolean[n][5000];
+ solve(a, k, 0, 0, 0);
+ return min;
+ }
+
+ private void solve(int a[][], int k, int sum, int row, int col) {
+ if (dp[row][sum])
+ return;
+ if (n - 1 == row) {
+ for (int i = 0; i < m; i++)
+ min = Math.min(min, Math.abs(k - sum - a[row][i]));
+ dp[row][sum] = true;
+ return;
+ }
+
+ for (int i = 0; i < m; i++)
+ solve(a, k, sum + a[row][i], row + 1, col);
+ dp[row][sum] = true;
+ }
+
+ private int min;
+ private int dy[], n, m;
+ private boolean dp[][];
+}
diff --git a/java/204_Count_Primes.java b/java/204_Count_Primes.java
new file mode 100644
index 0000000..cba07a7
--- /dev/null
+++ b/java/204_Count_Primes.java
@@ -0,0 +1,20 @@
+class Solution {
+ // ttps://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity
+ public int countPrimes(int n) {
+ boolean[] isPrime = new boolean[n];
+ int count = 0;
+ Arrays.fill(isPrime, true);
+ for (int i = 2; i < n; i++) {
+ if (i * i >= n)
+ break;
+ if (!isPrime[i])
+ continue;
+ for (int j = i * i; j < n; j += i)
+ isPrime[j] = false;
+ }
+ for (int i = 2; i < n; i++)
+ if (isPrime[i])
+ count++;
+ return count;
+ }
+}
diff --git a/java/206_Reverse_Linked_List.java b/java/206_Reverse_Linked_List.java
new file mode 100644
index 0000000..6f477b3
--- /dev/null
+++ b/java/206_Reverse_Linked_List.java
@@ -0,0 +1,38 @@
+/**
+ * Definition for singly-linked list.
+ * public class ListNode {
+ * int val;
+ * ListNode next;
+ * ListNode() {}
+ * ListNode(int val) { this.val = val; }
+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
+ * }
+ */
+class Solution {
+ // https://leetcode.com/problems/reverse-linked-list/discuss/58125/In-place-iterative-and-recursive-Java-solution
+ public ListNode reverseList(ListNode head) {
+ // Iterative solution
+ ListNode newHead = null;
+ while (head != null) {
+ ListNode next = head.next;
+ head.next = newHead;
+ newHead = head;
+ head = next;
+ }
+ return newHead;
+ }
+
+ // Recursive
+ /*
+ public ListNode reverseList(ListNode head) {
+ return reverseListInt(head, null);
+ }
+
+ private ListNode reverseListInt(ListNode head, ListNode newHead) {
+ if (head == null)
+ return newHead;
+ ListNode next = head.next;
+ head.next = newHead;
+ return reverseListInt(next, head);
+ }*/
+}
diff --git a/java/215_Kth_Largest_Element_in_an_Array.java b/java/215_Kth_Largest_Element_in_an_Array.java
new file mode 100644
index 0000000..5caab88
--- /dev/null
+++ b/java/215_Kth_Largest_Element_in_an_Array.java
@@ -0,0 +1,55 @@
+class Solution {
+ public int findKthLargest(int[] nums, int k) {
+ //https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/60294/Solution-explained
+ // shuffle nums to avoid n * n
+ shuffle(nums);
+ k = nums.length - k;
+ int lo = 0;
+ int hi = nums.length - 1;
+ while (lo < hi) {
+ final int j = partition(nums, lo, hi);
+ if(j < k) {
+ lo = j + 1;
+ } else if (j > k) {
+ hi = j - 1;
+ } else {
+ break;
+ }
+ }
+ return nums[k];
+ }
+
+ private int partition(int[] a, int lo, int hi) {
+
+ int i = lo;
+ int j = hi + 1;
+ while(true) {
+ while(i < hi && less(a[++i], a[lo]));
+ while(j > lo && less(a[lo], a[--j]));
+ if(i >= j) {
+ break;
+ }
+ exch(a, i, j);
+ }
+ exch(a, lo, j);
+ return j;
+ }
+
+ private void exch(int[] a, int i, int j) {
+ final int tmp = a[i];
+ a[i] = a[j];
+ a[j] = tmp;
+ }
+
+ private boolean less(int v, int w) {
+ return v < w;
+ }
+
+ private void shuffle(int a[]) {
+ final Random random = new Random();
+ for(int ind = 1; ind < a.length; ind++) {
+ final int r = random.nextInt(ind + 1);
+ exch(a, ind, r);
+ }
+ }
+}
diff --git a/java/219_Contains_Duplicate_II.java b/java/219_Contains_Duplicate_II.java
new file mode 100644
index 0000000..f88a1a9
--- /dev/null
+++ b/java/219_Contains_Duplicate_II.java
@@ -0,0 +1,44 @@
+import java.util.*;
+
+class Solution {
+ /*
+ * I have to save indice for each index.
+ * So I use the HashMap>
+ */
+
+ public boolean containsNearbyDuplicate(int[] nums, int k) {
+ HashMap> map = new HashMap<>();
+
+ for(int i = 0; i < nums.length; i++) {
+ if(!map.containsKey(nums[i])) {
+ map.put(nums[i], new ArrayList<>());
+ }
+ map.get(nums[i]).add(i);
+ }
+
+ // use Iterator to find appropriate two indice.
+ // Each list guarantee ascending.
+ // So list.get(i) and list.get(i + 1) is minimum.
+ Iterator keys = map.keySet().iterator();
+ boolean answer = false;
+
+ while(keys.hasNext()) {
+ int key = keys.next();
+ List list = map.get(key);
+
+ if(list.size() < 2) continue;
+
+ for(int i = 1; i < list.size(); i++) {
+ int a = list.get(i - 1);
+ int b = list.get(i);
+
+ if(b - a <= k) {
+ answer = true;
+ break;
+ }
+ }
+ if(answer) break;
+ }
+ return answer;
+ }
+}
diff --git a/java/223_Rectangle_Area.java b/java/223_Rectangle_Area.java
new file mode 100644
index 0000000..d78c7db
--- /dev/null
+++ b/java/223_Rectangle_Area.java
@@ -0,0 +1,9 @@
+class Solution {
+ public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
+ // https://leetcode.com/problems/rectangle-area/discuss/62149/Just-another-short-way
+ // Possible overlap area
+ int left = Math.max(A, E), right = Math.max(Math.min(C, G), left);
+ int bottom = Math.max(B, F), top = Math.max(Math.min(D, H), bottom);
+ return (C - A) * (D - B) - (right - left) * (top - bottom) + (G - E) * (H - F);
+ }
+}
diff --git a/java/22_Generate_Parentheses.java b/java/22_Generate_Parentheses.java
new file mode 100644
index 0000000..1667c87
--- /dev/null
+++ b/java/22_Generate_Parentheses.java
@@ -0,0 +1,26 @@
+class Solution {
+ // main function
+ public List generateParenthesis(int n) {
+ ArrayList list = new ArrayList<>();
+ rec(list, "(", n - 1, n);
+ return list;
+ }
+
+ // axiom : if start == end == 0, add str in list.
+ // IDEA :
+ // In well-formed parentheses
+ // close character(")") has to be bigger than open character("(")
+ // So, we can solve this problem with recursion.
+ public void rec(List list, String str, int start, int end) {
+ if(start == 0 && end == 0) {
+ list.add(str);
+ }
+
+ if(start > 0) {
+ rec(list, str + "(", start - 1, end);
+ }
+ if(end > start) {
+ rec(list, str + ")", start, end - 1);
+ }
+ }
+}
diff --git a/java/236_Lowest_Common_Ancestor_of_a_Binary_Tree.java b/java/236_Lowest_Common_Ancestor_of_a_Binary_Tree.java
new file mode 100644
index 0000000..2cb9da2
--- /dev/null
+++ b/java/236_Lowest_Common_Ancestor_of_a_Binary_Tree.java
@@ -0,0 +1,83 @@
+class Solution {
+
+ private TreeNode ans;
+
+ public Solution() {
+ // Variable to store LCA node.
+ this.ans = null;
+ }
+
+ private boolean recurseTree(TreeNode currentNode, TreeNode p, TreeNode q) {
+
+ // If reached the end of a branch, return false.
+ if (currentNode == null) {
+ return false;
+ }
+
+ // Left Recursion. If left recursion returns true, set left = 1 else 0
+ int left = this.recurseTree(currentNode.left, p, q) ? 1 : 0;
+
+ // Right Recursion
+ int right = this.recurseTree(currentNode.right, p, q) ? 1 : 0;
+
+ // If the current node is one of p or q
+ int mid = (currentNode == p || currentNode == q) ? 1 : 0;
+
+
+ // If any two of the flags left, right or mid become True
+ if (mid + left + right >= 2) {
+ this.ans = currentNode;
+ }
+
+ // Return true if any one of the three bool values is True.
+ return (mid + left + right > 0);
+ }
+
+ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
+ // Traverse the tree
+ this.recurseTree(root, p, q);
+ return this.ans;
+ }
+
+ /*public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
+ // Stack for tree traversal
+ Deque stack = new ArrayDeque<>();
+
+ // HashMap for parent pointers
+ Map parent = new HashMap<>();
+
+ parent.put(root, null);
+ stack.push(root);
+
+ // Iterate until we find both the nodes p and q
+ while (!parent.containsKey(p) || !parent.containsKey(q)) {
+
+ TreeNode node = stack.pop();
+
+ // While traversing the tree, keep saving the parent pointers.
+ if (node.left != null) {
+ parent.put(node.left, node);
+ stack.push(node.left);
+ }
+ if (node.right != null) {
+ parent.put(node.right, node);
+ stack.push(node.right);
+ }
+ }
+
+ // Ancestors set() for node p.
+ Set ancestors = new HashSet<>();
+
+ // Process all ancestors for node p using parent pointers.
+ while (p != null) {
+ ancestors.add(p);
+ p = parent.get(p);
+ }
+
+ // The first ancestor of q which appears in
+ // p's ancestor set() is their lowest common ancestor.
+ while (!ancestors.contains(q))
+ q = parent.get(q);
+ return q;
+ }*/
+}
diff --git a/java/238_Product_of_Array_Except_Self.java b/java/238_Product_of_Array_Except_Self.java
new file mode 100644
index 0000000..28b1031
--- /dev/null
+++ b/java/238_Product_of_Array_Except_Self.java
@@ -0,0 +1,18 @@
+public class Solution {
+ public int[] productExceptSelf(int[] nums) {
+ int n = nums.length;
+ int[] res = new int[n];
+ res[0] = 1;
+ for (int i = 1; i < n; i++) {
+ // left part
+ res[i] = res[i - 1] * nums[i - 1];
+ }
+ int right = 1;
+ for (int i = n - 1; i >= 0; i--) {
+ res[i] *= right;
+ // right part
+ right *= nums[i];
+ }
+ return res;
+ }
+}
diff --git a/java/253_Meeting_Rooms_II.java b/java/253_Meeting_Rooms_II.java
new file mode 100644
index 0000000..9760e75
--- /dev/null
+++ b/java/253_Meeting_Rooms_II.java
@@ -0,0 +1,77 @@
+/**
+ * Definition for an interval. public class Interval { int start; int end; Interval() { start = 0;
+ * end = 0; } Interval(int s, int e) { start = s; end = e; } }
+ */
+class Solution {
+
+ /* public int minMeetingRooms(Interval[] intervals) {
+
+ // Check for the base case. If there are no intervals, return 0
+ if (intervals.length == 0) {
+ return 0;
+ }
+ // Min heap
+ PriorityQueue allocator =
+ new PriorityQueue(
+ intervals.length,
+ new Comparator() {
+ public int compare(Integer a, Integer b) {
+ return a - b;
+ }
+ });
+
+ // Sort the intervals by start time
+ Arrays.sort(
+ intervals,
+ new Comparator() {
+ public int compare(Interval a, Interval b) {
+ return a.start - b.start;
+ }
+ });
+ // Add the first meeting
+ allocator.add(intervals[0].end);
+
+ // Iterate over remaining intervals
+ for (int i = 1; i < intervals.length; i++) {
+ // If the room due to free up the earliest is free, assign that room to this meeting.
+ if (intervals[i].start >= allocator.peek()) {
+ allocator.poll();
+ }
+ // If a new room is to be assigned, then also we add to the heap,
+ // If an old room is allocated, then also we have to add to the heap with updated end time.
+ allocator.add(intervals[i].end);
+ }
+ // The size of the heap tells us the minimum rooms required for all the meetings.
+ return allocator.size();
+ }*/
+
+ public int minMeetingRooms(Interval[] intervals) {
+ int ans = 0, curr = 0;
+ List timeline = new ArrayList<>();
+ for (Interval interval: intervals) {
+ timeline.add(new TimePoint(interval.start, 1));
+ timeline.add(new TimePoint(interval.end, -1));
+ }
+ timeline.sort(new Comparator() {
+ public int compare(TimePoint a, TimePoint b) {
+ if (a.time != b.time) return a.time - b.time;
+ else return a.room - b.room;
+ }
+ });
+ for (TimePoint t: timeline) {
+ curr += t.room;
+ if (curr >= ans) ans = curr;
+ }
+ return ans;
+ }
+
+ private class TimePoint {
+ int time;
+ int room;
+
+ TimePoint(int time, int room) {
+ this.time = time;
+ this.room = room;
+ }
+ }
+}
diff --git a/java/273_Integer_to_English_Words.java b/java/273_Integer_to_English_Words.java
new file mode 100644
index 0000000..0b6717e
--- /dev/null
+++ b/java/273_Integer_to_English_Words.java
@@ -0,0 +1,33 @@
+class Solution {
+ // https://leetcode.com/problems/integer-to-english-words/discuss/70625/My-clean-Java-solution-very-easy-to-understand
+ private final String[] LESS_THAN_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
+ private final String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
+ private final String[] THOUSANDS = {"", "Thousand", "Million", "Billion"};
+
+ public String numberToWords(int num) {
+ if (num == 0) return "Zero";
+
+ int i = 0;
+ String words = "";
+
+ while (num > 0) {
+ if (num % 1000 != 0)
+ words = helper(num % 1000) + THOUSANDS[i] + " " + words;
+ num /= 1000;
+ i++;
+ }
+
+ return words.trim();
+ }
+
+ private String helper(int num) {
+ if (num == 0)
+ return "";
+ else if (num < 20)
+ return LESS_THAN_20[num] + " ";
+ else if (num < 100)
+ return TENS[num / 10] + " " + helper(num % 10);
+ else
+ return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100);
+ }
+}
diff --git a/java/336_Palindrome_Pairs.java b/java/336_Palindrome_Pairs.java
new file mode 100644
index 0000000..0f3fe2c
--- /dev/null
+++ b/java/336_Palindrome_Pairs.java
@@ -0,0 +1,73 @@
+class Solution {
+ //https://leetcode.com/problems/palindrome-pairs/discuss/79195/O(n-*-k2)-java-solution-with-Trie-structure
+ private static class TrieNode {
+ TrieNode[] next;
+ int index;
+ List list;
+
+ TrieNode() {
+ next = new TrieNode[26];
+ index = -1;
+ list = new ArrayList<>();
+ }
+ }
+
+ public List> palindromePairs(String[] words) {
+ List> res = new ArrayList<>();
+
+ TrieNode root = new TrieNode();
+
+ for (int i = 0; i < words.length; i++) {
+ addWord(root, words[i], i);
+ }
+
+ for (int i = 0; i < words.length; i++) {
+ search(words, i, root, res);
+ }
+
+ return res;
+ }
+
+ private void addWord(TrieNode root, String word, int index) {
+ for (int i = word.length() - 1; i >= 0; i--) {
+ int j = word.charAt(i) - 'a';
+
+ if (root.next[j] == null) {
+ root.next[j] = new TrieNode();
+ }
+
+ if (isPalindrome(word, 0, i)) {
+ root.list.add(index);
+ }
+
+ root = root.next[j];
+ }
+
+ root.list.add(index);
+ root.index = index;
+ }
+
+ private void search(String[] words, int i, TrieNode root, List> res) {
+ for (int j = 0; j < words[i].length(); j++) {
+ if (root.index >= 0 && root.index != i && isPalindrome(words[i], j, words[i].length() - 1)) {
+ res.add(Arrays.asList(i, root.index));
+ }
+
+ root = root.next[words[i].charAt(j) - 'a'];
+ if (root == null) return;
+ }
+
+ for (int j : root.list) {
+ if (i == j) continue;
+ res.add(Arrays.asList(i, j));
+ }
+ }
+
+ private boolean isPalindrome(String word, int i, int j) {
+ while (i < j) {
+ if (word.charAt(i++) != word.charAt(j--)) return false;
+ }
+
+ return true;
+ }
+}
diff --git a/java/347_Top_K_Frequent_Elements.java b/java/347_Top_K_Frequent_Elements.java
new file mode 100644
index 0000000..70b41a6
--- /dev/null
+++ b/java/347_Top_K_Frequent_Elements.java
@@ -0,0 +1,27 @@
+class Solution {
+ public List topKFrequent(int[] nums, int k) {
+ // build hash map : character and how often it appears
+ HashMap count = new HashMap();
+ for (int n: nums) {
+ count.put(n, count.getOrDefault(n, 0) + 1);
+ }
+
+ // init heap 'the less frequent element first'
+ PriorityQueue heap =
+ new PriorityQueue((n1, n2) -> count.get(n1) - count.get(n2));
+
+ // keep k top frequent elements in the heap
+ for (int n: count.keySet()) {
+ heap.add(n);
+ if (heap.size() > k)
+ heap.poll();
+ }
+
+ // build output list
+ List top_k = new LinkedList();
+ while (!heap.isEmpty())
+ top_k.add(heap.poll());
+ Collections.reverse(top_k);
+ return top_k;
+ }
+}
diff --git a/java/400_Nth_Digit.java b/java/400_Nth_Digit.java
new file mode 100644
index 0000000..4f5f8e4
--- /dev/null
+++ b/java/400_Nth_Digit.java
@@ -0,0 +1,17 @@
+class Solution {
+ public int findNthDigit(int n) {
+ int len = 1;
+ long count = 9;
+ int start = 1;
+ // https://leetcode.com/problems/nth-digit/discuss/88363/Java-solution
+ while (n > len * count) {
+ n -= len * count;
+ len += 1;
+ count *= 10;
+ start *= 10;
+ }
+ start += (n - 1) / len;
+ String s = Integer.toString(start);
+ return Character.getNumericValue(s.charAt((n - 1) % len));
+ }
+}
diff --git a/java/409_Longest_Palindrome.java b/java/409_Longest_Palindrome.java
new file mode 100644
index 0000000..3d6a303
--- /dev/null
+++ b/java/409_Longest_Palindrome.java
@@ -0,0 +1,16 @@
+class Solution {
+ // https://leetcode.com/problems/longest-palindrome/solution/
+ public int longestPalindrome(String s) {
+ int[] count = new int[128];
+ for (char c: s.toCharArray())
+ count[c]++;
+
+ int ans = 0;
+ for (int v: count) {
+ ans += v / 2 * 2;
+ if (ans % 2 == 0 && v % 2 == 1)
+ ans++;
+ }
+ return ans;
+ }
+}
\ No newline at end of file
diff --git a/java/414_Third_Maximum_Number.java b/java/414_Third_Maximum_Number.java
new file mode 100644
index 0000000..d883032
--- /dev/null
+++ b/java/414_Third_Maximum_Number.java
@@ -0,0 +1,16 @@
+public class Solution {
+ public int thirdMax(int[] nums) {
+ PriorityQueue pq = new PriorityQueue<>(3);
+ Set set = new HashSet<>();
+ for (int i : nums) {
+ if (set.contains(i)) continue;
+ pq.offer(i);
+ set.add(i);
+ if (pq.size() > 3) set.remove(pq.poll());
+ }
+ while (pq.size() < 3 && pq.size() > 1) {
+ pq.poll();
+ }
+ return pq.peek();
+ }
+}
diff --git a/java/415_Add_Strings.java b/java/415_Add_Strings.java
new file mode 100644
index 0000000..fecaa07
--- /dev/null
+++ b/java/415_Add_Strings.java
@@ -0,0 +1,15 @@
+public class Solution {
+ public String addStrings(String num1, String num2) {
+ StringBuilder sb = new StringBuilder();
+ int carry = 0;
+ // condition is great
+ // https://leetcode.com/problems/add-strings/discuss/90436/Straightforward-Java-8-main-lines-25ms
+ for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0 || carry == 1; i--, j--){
+ int x = i < 0 ? 0 : num1.charAt(i) - '0';
+ int y = j < 0 ? 0 : num2.charAt(j) - '0';
+ sb.append((x + y + carry) % 10);
+ carry = (x + y + carry) / 10;
+ }
+ return sb.reverse().toString();
+ }
+}
\ No newline at end of file
diff --git a/java/434_Number_of_Segments_in_a_String.java b/java/434_Number_of_Segments_in_a_String.java
new file mode 100644
index 0000000..067504f
--- /dev/null
+++ b/java/434_Number_of_Segments_in_a_String.java
@@ -0,0 +1,21 @@
+class Solution {
+ // https://leetcode.com/problems/number-of-segments-in-a-string/solution/
+ // public int countSegments(String s) {
+ // String trimmed = s.trim();
+ // if (trimmed.equals("")) {
+ // return 0;
+ // }
+ // return trimmed.split("\\s+").length;
+ // }
+ public int countSegments(String s) {
+ int segmentCount = 0;
+
+ for (int i = 0; i < s.length(); i++) {
+ if ((i == 0 || s.charAt(i-1) == ' ') && s.charAt(i) != ' ') {
+ segmentCount++;
+ }
+ }
+
+ return segmentCount;
+ }
+}
\ No newline at end of file
diff --git a/java/437_Path_Sum_III.java b/java/437_Path_Sum_III.java
new file mode 100644
index 0000000..8fe88f0
--- /dev/null
+++ b/java/437_Path_Sum_III.java
@@ -0,0 +1,47 @@
+/**
+ * Definition for a binary tree node.
+ * public class TreeNode {
+ * int val;
+ * TreeNode left;
+ * TreeNode right;
+ * TreeNode(int x) { val = x; }
+ * }
+ */
+class Solution {
+ /*public int pathSum(TreeNode root, int sum) {
+ if (root != null) return findPaths(root, sum)
+ + pathSum(root.left, sum)
+ + pathSum(root.right, sum);
+ return 0;
+ }
+
+ private int findPaths(TreeNode root, int target) {
+ if (root != null) return (root.val == target? 1 : 0)
+ + findPaths(root.left, target - root.val)
+ + findPaths(root.right, target - root.val);
+ return 0;
+ }*/
+
+ private int result;
+ private HashMap cache;
+
+ public int pathSum(TreeNode root, int sum) {
+ result = 0;
+ cache = new HashMap();
+ cache.put(0, 1);
+ pathSumHelper(root, sum, 0);
+ return result;
+ }
+ // https://leetcode.com/problems/path-sum-iii/discuss/91892/Python-solution-with-detailed-explanation
+ private void pathSumHelper(TreeNode root, int target, int soFar) {
+ if (root != null) {
+ int complement = soFar + root.val - target;
+ if (cache.containsKey(complement))
+ result += cache.get(complement);
+ cache.put(soFar + root.val, cache.getOrDefault(soFar + root.val, 0) + 1);
+ pathSumHelper(root.left, target, soFar + root.val);
+ pathSumHelper(root.right, target, soFar + root.val);
+ cache.put(soFar + root.val, cache.get(soFar + root.val) - 1);
+ }
+ }
+}
diff --git a/java/438_Find_All_Anagrams_in_a_String.java b/java/438_Find_All_Anagrams_in_a_String.java
new file mode 100644
index 0000000..c841aeb
--- /dev/null
+++ b/java/438_Find_All_Anagrams_in_a_String.java
@@ -0,0 +1,53 @@
+class Solution {
+ public List findAnagrams(String s, String p) {
+ // https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92015/ShortestConcise-JAVA-O(n)-Sliding-Window-Solution
+ List list = new ArrayList<>();
+ if (s == null || s.length() == 0 || p == null || p.length() == 0) return list;
+ int[] hash = new int[256]; //character hash
+ //record each character in p to hash
+ for (char c : p.toCharArray()) {
+ hash[c]++;
+ }
+ //two points, initialize count to p's length
+ int left = 0, right = 0, count = p.length();
+ while (right < s.length()) {
+ //move right everytime, if the character exists in p's hash, decrease the count
+ //current hash value >= 1 means the character is existing in p
+ if (hash[s.charAt(right++)]-- >= 1) count--;
+ //when the count is down to 0, means we found the right anagram
+ //then add window's left to result list
+ if (count == 0) list.add(left);
+ //if we find the window's size equals to p, then we have to move left (narrow the window) to find the new match window
+ //++ to reset the hash because we kicked out the left
+ //only increase the count if the character is in p
+ //the count >= 0 indicate it was original in the hash, cuz it won't go below 0
+ if (right - left == p.length() && hash[s.charAt(left++)]++ >= 0) count++;
+ }
+ return list;
+ }
+ /*public List findAnagrams(String s, String p) {
+ List list = new ArrayList();
+ int ls = s.length(), lp = p.length();
+ for (int i = 0; i <= ls - lp; i++) {
+ boolean flag = true;
+ String sub = s.substring(i, i + lp);
+ int[] charCnt = new int[256];
+ for (int j = 0; j < sub.length(); j++) {
+ charCnt[sub.charAt(j)]++;
+ }
+ for (int j = 0; j < lp; j++) {
+ charCnt[p.charAt(j)]--;
+ }
+ for (int j = 0; j < charCnt.length; j++) {
+ if (charCnt[j] != 0) {
+ flag = false;
+ break;
+ }
+ }
+ if (flag) {
+ list.add(i);
+ }
+ }
+ return list;
+ }*/
+}
diff --git a/java/442_Find_All_Duplicates_in_an_Array.java b/java/442_Find_All_Duplicates_in_an_Array.java
new file mode 100644
index 0000000..b12d6f5
--- /dev/null
+++ b/java/442_Find_All_Duplicates_in_an_Array.java
@@ -0,0 +1,17 @@
+class Solution {
+ public List findDuplicates(int[] nums) {
+ int n = nums.length;
+
+ List ans = new ArrayList<>();
+
+ for(int i=0;i anchor) {
+ for (char c: ("" + (read - anchor + 1)).toCharArray()) {
+ chars[write++] = c;
+ }
+ }
+ anchor = read + 1;
+ }
+ }
+ return write;
+ }
+}
\ No newline at end of file
diff --git a/java/448_Find_All_Numbers_Disappeared_in_an_Array.java b/java/448_Find_All_Numbers_Disappeared_in_an_Array.java
new file mode 100644
index 0000000..db033fa
--- /dev/null
+++ b/java/448_Find_All_Numbers_Disappeared_in_an_Array.java
@@ -0,0 +1,20 @@
+class Solution {
+ // https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/92956/Java-accepted-simple-solution
+ public List findDisappearedNumbers(int[] nums) {
+ List ret = new ArrayList();
+
+ for(int i = 0; i < nums.length; i++) {
+ int val = Math.abs(nums[i]) - 1;
+ if(nums[val] > 0) {
+ nums[val] = -nums[val];
+ }
+ }
+
+ for(int i = 0; i < nums.length; i++) {
+ if(nums[i] > 0) {
+ ret.add(i+1);
+ }
+ }
+ return ret;
+ }
+}
diff --git a/java/453_Minimum_Moves_to_Equal_Array_Elements.java b/java/453_Minimum_Moves_to_Equal_Array_Elements.java
new file mode 100644
index 0000000..a622666
--- /dev/null
+++ b/java/453_Minimum_Moves_to_Equal_Array_Elements.java
@@ -0,0 +1,15 @@
+import java.util.Arrays;
+import java.util.Collections;
+
+class Solution {
+ public int minMoves(int[] nums) {
+ if (nums.length == 0) return 0;
+ Arrays.sort(nums);
+ int min_num = nums[0];
+ int ans = 0;
+ for (int num : nums) {
+ ans += num - min_num;
+ }
+ return ans;
+ }
+}
\ No newline at end of file
diff --git a/java/458_Poor_Pigs.java b/java/458_Poor_Pigs.java
new file mode 100644
index 0000000..6d3885b
--- /dev/null
+++ b/java/458_Poor_Pigs.java
@@ -0,0 +1,8 @@
+class Solution {
+ public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
+ int n = minutesToTest / minutesToDie + 1;
+ int pigs = 0;
+ while (Math.pow(n, pigs) < buckets) pigs++;
+ return pigs;
+ }
+}
diff --git a/java/461_Hamming_Distance.java b/java/461_Hamming_Distance.java
new file mode 100644
index 0000000..71b165b
--- /dev/null
+++ b/java/461_Hamming_Distance.java
@@ -0,0 +1,5 @@
+class Solution {
+ public int hammingDistance(int x, int y) {
+ return Integer.bitCount(x ^ y);
+ }
+}
\ No newline at end of file
diff --git a/java/463_Island_Perimeter.java b/java/463_Island_Perimeter.java
new file mode 100644
index 0000000..c198993
--- /dev/null
+++ b/java/463_Island_Perimeter.java
@@ -0,0 +1,16 @@
+class Solution {
+ public int islandPerimeter(int[][] grid) {
+ // https://leetcode.com/problems/island-perimeter/discuss/95001/clear-and-easy-java-solution
+ int islands = 0, neighbours = 0;
+ for (int i = 0; i < grid.length; i++) {
+ for (int j = 0; j < grid[i].length; j++) {
+ if (grid[i][j] == 1) {
+ islands++; // count islands
+ if (i < grid.length - 1 && grid[i + 1][j] == 1) neighbours++; // count down neighbours
+ if (j < grid[i].length - 1 && grid[i][j + 1] == 1) neighbours++; // count right neighbours
+ }
+ }
+ }
+ return islands * 4 - neighbours * 2;
+ }
+}
diff --git a/java/475_Heaters.java b/java/475_Heaters.java
new file mode 100644
index 0000000..476a764
--- /dev/null
+++ b/java/475_Heaters.java
@@ -0,0 +1,17 @@
+public class Solution {
+ public int findRadius(int[] houses, int[] heaters) {
+ Arrays.sort(heaters);
+ int result = Integer.MIN_VALUE;
+
+ for (int house : houses) {
+ // Java binarySearch return - insertPoint - 1 if not found
+ // This point is greater than value you want
+ int index = Arrays.binarySearch(heaters, house);
+ if (index < 0) index = -(index + 1);
+ int dist1 = index - 1 >= 0 ? house - heaters[index - 1] : Integer.MAX_VALUE;
+ int dist2 = index < heaters.length ? heaters[index] - house : Integer.MAX_VALUE;
+ result = Math.max(result, Math.min(dist1, dist2));
+ }
+ return result;
+ }
+}
diff --git a/java/479_Largest_Palindrome_Product.java b/java/479_Largest_Palindrome_Product.java
new file mode 100644
index 0000000..058e579
--- /dev/null
+++ b/java/479_Largest_Palindrome_Product.java
@@ -0,0 +1,49 @@
+class Solution {
+ public int largestPalindrome(int n) {
+ // https://leetcode.com/problems/largest-palindrome-product/discuss/96297/Java-Solution-using-assumed-max-palindrom
+ // if input is 1 then max is 9
+ if(n == 1){
+ return 9;
+ }
+
+ // if n = 3 then upperBound = 999 and lowerBound = 99
+ int upperBound = (int) Math.pow(10, n) - 1, lowerBound = upperBound / 10;
+ long maxNumber = (long) upperBound * (long) upperBound;
+
+ // represents the first half of the maximum assumed palindrom.
+ // e.g. if n = 3 then maxNumber = 999 x 999 = 998001 so firstHalf = 998
+ int firstHalf = (int)(maxNumber / (long) Math.pow(10, n));
+
+ boolean palindromFound = false;
+ long palindrom = 0;
+
+ while (!palindromFound) {
+ // creates maximum assumed palindrom
+ // e.g. if n = 3 first time the maximum assumed palindrom will be 998 899
+ palindrom = createPalindrom(firstHalf);
+
+ // here i and palindrom/i forms the two factor of assumed palindrom
+ for (long i = upperBound; upperBound > lowerBound; i--) {
+ // if n= 3 none of the factor of palindrom can be more than 999 or less than square root of assumed palindrom
+ if (palindrom / i > maxNumber || i * i < palindrom) {
+ break;
+ }
+
+ // if two factors found, where both of them are n-digits,
+ if (palindrom % i == 0) {
+ palindromFound = true;
+ break;
+ }
+ }
+
+ firstHalf--;
+ }
+
+ return (int) (palindrom % 1337);
+ }
+
+ private long createPalindrom(long num) {
+ String str = num + new StringBuilder().append(num).reverse().toString();
+ return Long.parseLong(str);
+ }
+}
diff --git a/java/482_License_Key_Formatting.java b/java/482_License_Key_Formatting.java
new file mode 100644
index 0000000..160e602
--- /dev/null
+++ b/java/482_License_Key_Formatting.java
@@ -0,0 +1,10 @@
+class Solution {
+ public String licenseKeyFormatting(String s, int k) {
+ // https://leetcode.com/problems/license-key-formatting/discuss/96512/Java-5-lines-clean-solution
+ StringBuilder sb = new StringBuilder();
+ for (int i = s.length() - 1; i >= 0; i--)
+ if (s.charAt(i) != '-')
+ sb.append(sb.length() % (k + 1) == k ? '-' : "").append(s.charAt(i));
+ return sb.reverse().toString().toUpperCase();
+ }
+}
diff --git a/java/485_Max_Consecutive_Ones.java b/java/485_Max_Consecutive_Ones.java
new file mode 100644
index 0000000..2aca065
--- /dev/null
+++ b/java/485_Max_Consecutive_Ones.java
@@ -0,0 +1,17 @@
+class Solution {
+ public int findMaxConsecutiveOnes(int[] nums) {
+ int ans = 0;
+ int curr = 0;
+ for (int i = 0; i < nums.length; i++) {
+ if (nums[i] == 1) {
+ // Add 1 when encounter 1
+ curr++;
+ if (curr > ans) ans = curr;
+ } else {
+ // Set to 0 when encounter 0
+ curr = 0;
+ }
+ }
+ return ans;
+ }
+}
diff --git a/java/509_Fibonacci_Number.java b/java/509_Fibonacci_Number.java
new file mode 100644
index 0000000..9059dc4
--- /dev/null
+++ b/java/509_Fibonacci_Number.java
@@ -0,0 +1,25 @@
+class Solution {
+ /*public int fib(int N) {
+ // Recursively, O(n)
+ if (N == 0) return 0;
+ if (N == 1) return 1;
+ return fib(N - 1) + fib(N - 2);
+ }*/
+
+ private List memo;
+
+ public Solution() {
+ memo = new ArrayList();
+ memo.add(0);
+ memo.add(1);
+ }
+
+ public int fib(int N) {
+ // Dp with memo, O(n)
+ if (N < memo.size()) return memo.get(N);
+ for (int i = memo.size(); i <= N; i++) {
+ memo.add(memo.get(i - 1) + memo.get(i - 2));
+ }
+ return memo.get(N);
+ }
+}
diff --git a/java/538_Convert_BST_to_Greater_Tree.java b/java/538_Convert_BST_to_Greater_Tree.java
new file mode 100644
index 0000000..394cb62
--- /dev/null
+++ b/java/538_Convert_BST_to_Greater_Tree.java
@@ -0,0 +1,39 @@
+class Solution {
+ // https://leetcode.com/problems/convert-bst-to-greater-tree/solution/
+ // private int sum = 0;
+
+ // public TreeNode convertBST(TreeNode root) {
+ // if (root != null) {
+ // convertBST(root.right);
+ // sum += root.val;
+ // root.val = sum;
+ // convertBST(root.left);
+ // }
+ // return root;
+ // }
+
+ public TreeNode convertBST(TreeNode root) {
+ int sum = 0;
+ TreeNode node = root;
+ Stack stack = new Stack();
+
+ while (!stack.isEmpty() || node != null) {
+ /* push all nodes up to (and including) this subtree's maximum on
+ * the stack. */
+ while (node != null) {
+ stack.add(node);
+ node = node.right;
+ }
+
+ node = stack.pop();
+ sum += node.val;
+ node.val = sum;
+
+ /* all nodes with values between the current and its parent lie in
+ * the left subtree. */
+ node = node.left;
+ }
+
+ return root;
+ }
+}
diff --git a/java/541_Reverse_String_II.java b/java/541_Reverse_String_II.java
new file mode 100644
index 0000000..8b8565c
--- /dev/null
+++ b/java/541_Reverse_String_II.java
@@ -0,0 +1,16 @@
+class Solution {
+ public String reverseStr(String s, int k) {
+ // https://leetcode.com/problems/reverse-string-ii/solution/
+ char[] a = s.toCharArray();
+ for (int start = 0; start < a.length; start += 2 * k) {
+ int i = start, j = Math.min(start + k - 1, a.length - 1);
+ // Reverse from i to j
+ while (i < j) {
+ char tmp = a[i];
+ a[i++] = a[j];
+ a[j--] = tmp;
+ }
+ }
+ return new String(a);
+ }
+}
diff --git a/java/543_Diameter_of_Binary_Tree.java b/java/543_Diameter_of_Binary_Tree.java
new file mode 100644
index 0000000..b673722
--- /dev/null
+++ b/java/543_Diameter_of_Binary_Tree.java
@@ -0,0 +1,16 @@
+class Solution {
+ // https://leetcode.com/problems/diameter-of-binary-tree/solution/
+ int ans;
+ public int diameterOfBinaryTree(TreeNode root) {
+ ans = 1;
+ depth(root);
+ return ans - 1;
+ }
+ public int depth(TreeNode node) {
+ if (node == null) return 0;
+ int L = depth(node.left);
+ int R = depth(node.right);
+ ans = Math.max(ans, L+R+1);
+ return Math.max(L, R) + 1;
+ }
+}
diff --git a/java/547_Friend_Circles.java b/java/547_Friend_Circles.java
new file mode 100644
index 0000000..2db54c3
--- /dev/null
+++ b/java/547_Friend_Circles.java
@@ -0,0 +1,76 @@
+public class Solution {
+ public void dfs(int[][] M, int[] visited, int i) {
+ for (int j = 0; j < M.length; j++) {
+ if (M[i][j] == 1 && visited[j] == 0) {
+ visited[j] = 1;
+ dfs(M, visited, j);
+ }
+ }
+ }
+ public int findCircleNum(int[][] M) {
+ // DFS
+ int[] visited = new int[M.length];
+ int count = 0;
+ for (int i = 0; i < M.length; i++) {
+ if (visited[i] == 0) {
+ dfs(M, visited, i);
+ count++;
+ }
+ }
+ return count;
+ }
+
+ /*public int findCircleNum(int[][] M) {
+ // BFS
+ int[] visited = new int[M.length];
+ int count = 0;
+ Queue < Integer > queue = new LinkedList < > ();
+ for (int i = 0; i < M.length; i++) {
+ if (visited[i] == 0) {
+ queue.add(i);
+ while (!queue.isEmpty()) {
+ int s = queue.remove();
+ visited[s] = 1;
+ for (int j = 0; j < M.length; j++) {
+ if (M[s][j] == 1 && visited[j] == 0)
+ queue.add(j);
+ }
+ }
+ count++;
+ }
+ }
+ return count;
+ }*/
+
+ /*
+ // Union find
+ int find(int parent[], int i) {
+ if (parent[i] == -1)
+ return i;
+ return find(parent, parent[i]);
+ }
+
+ void union(int parent[], int x, int y) {
+ int xset = find(parent, x);
+ int yset = find(parent, y);
+ if (xset != yset)
+ parent[xset] = yset;
+ }
+ public int findCircleNum(int[][] M) {
+ int[] parent = new int[M.length];
+ Arrays.fill(parent, -1);
+ for (int i = 0; i < M.length; i++) {
+ for (int j = 0; j < M.length; j++) {
+ if (M[i][j] == 1 && i != j) {
+ union(parent, i, j);
+ }
+ }
+ }
+ int count = 0;
+ for (int i = 0; i < parent.length; i++) {
+ if (parent[i] == -1)
+ count++;
+ }
+ return count;
+ }*/
+}
\ No newline at end of file
diff --git a/java/557_Reverse_Words_in_a_String_III.java b/java/557_Reverse_Words_in_a_String_III.java
new file mode 100644
index 0000000..62d9776
--- /dev/null
+++ b/java/557_Reverse_Words_in_a_String_III.java
@@ -0,0 +1,9 @@
+public class Solution {
+ public String reverseWords(String s) {
+ String words[] = s.split(" ");
+ StringBuilder ans = new StringBuilder();
+ for (String word: words)
+ ans.append(new StringBuffer(word).reverse().toString() + " ");
+ return ans.toString().trim();
+ }
+}
diff --git a/java/560_Subarray_Sum_Equals_K.java b/java/560_Subarray_Sum_Equals_K.java
new file mode 100644
index 0000000..49a2c04
--- /dev/null
+++ b/java/560_Subarray_Sum_Equals_K.java
@@ -0,0 +1,28 @@
+public class Solution {
+ /*public int subarraySum(int[] nums, int k) {
+ int count = 0;
+ for (int start = 0; start < nums.length; start++) {
+ int sum = 0;
+ for (int end = start; end < nums.length; end++) {
+ sum += nums[end];
+ if (sum == k)
+ count++;
+ }
+ }
+ return count;
+ }*/
+ public int subarraySum(int[] nums, int k) {
+ int count = 0, sum = 0;
+ HashMap < Integer, Integer > map = new HashMap < > ();
+ map.put(0, 1);
+ for (int i = 0; i < nums.length; i++) {
+ sum += nums[i];
+ // check if sum - k in hash
+ if (map.containsKey(sum - k))
+ count += map.get(sum - k);
+ // push sum into hash
+ map.put(sum, map.getOrDefault(sum, 0) + 1);
+ }
+ return count;
+ }
+}
diff --git a/java/572_Subtree_of_Another_Tree.java b/java/572_Subtree_of_Another_Tree.java
new file mode 100644
index 0000000..d2a8256
--- /dev/null
+++ b/java/572_Subtree_of_Another_Tree.java
@@ -0,0 +1,43 @@
+/**
+ * Definition for a binary tree node.
+ * public class TreeNode {
+ * int val;
+ * TreeNode left;
+ * TreeNode right;
+ * TreeNode(int x) { val = x; }
+ * }
+ */
+public class Solution {
+ // https://leetcode.com/problems/subtree-of-another-tree/solution/
+ HashSet < String > trees = new HashSet < > ();
+ public boolean isSubtree(TreeNode s, TreeNode t) {
+ String tree1 = preorder(s, true);
+ String tree2 = preorder(t, true);
+ return tree1.indexOf(tree2) >= 0;
+ }
+ public String preorder(TreeNode t, boolean left) {
+ if (t == null) {
+ if (left)
+ return "lnull";
+ else
+ return "rnull";
+ }
+ return "#"+t.val + " " +preorder(t.left, true)+" " +preorder(t.right, false);
+ }
+
+ // public boolean isSubtree(TreeNode s, TreeNode t) {
+ // return traverse(s,t);
+ // }
+ // public boolean equals(TreeNode x,TreeNode y)
+ // {
+ // if(x==null && y==null)
+ // return true;
+ // if(x==null || y==null)
+ // return false;
+ // return x.val==y.val && equals(x.left,y.left) && equals(x.right,y.right);
+ // }
+ // public boolean traverse(TreeNode s,TreeNode t)
+ // {
+ // return s!=null && ( equals(s,t) || traverse(s.left,t) || traverse(s.right,t));
+ // }
+}
diff --git a/java/581_Shortest_Unsorted_Continuous_Subarray.java b/java/581_Shortest_Unsorted_Continuous_Subarray.java
new file mode 100644
index 0000000..6161a34
--- /dev/null
+++ b/java/581_Shortest_Unsorted_Continuous_Subarray.java
@@ -0,0 +1,87 @@
+public class Solution {
+ // https://leetcode.com/problems/shortest-unsorted-continuous-subarray/solution/
+ /* public int findUnsortedSubarray(int[] nums) {
+ int[] snums = nums.clone();
+ Arrays.sort(snums);
+ int start = snums.length, end = 0;
+ for (int i = 0; i < snums.length; i++) {
+ if (snums[i] != nums[i]) {
+ start = Math.min(start, i);
+ end = Math.max(end, i);
+ }
+ }
+ return (end - start >= 0 ? end - start + 1 : 0);
+ } */
+ public int findUnsortedSubarray(int[] nums) {
+ Stack < Integer > stack = new Stack < Integer > ();
+ int l = nums.length, r = 0;
+ for (int i = 0; i < nums.length; i++) {
+ while (!stack.isEmpty() && nums[stack.peek()] > nums[i])
+ l = Math.min(l, stack.pop());
+ stack.push(i);
+ }
+ stack.clear();
+ for (int i = nums.length - 1; i >= 0; i--) {
+ while (!stack.isEmpty() && nums[stack.peek()] < nums[i])
+ r = Math.max(r, stack.pop());
+ stack.push(i);
+ }
+ return r - l > 0 ? r - l + 1 : 0;
+ }
+
+ /* public int findUnsortedSubarray(int[] nums) {
+ int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
+ boolean flag = false;
+ for (int i = 1; i < nums.length; i++) {
+ if (nums[i] < nums[i - 1])
+ flag = true;
+ if (flag)
+ min = Math.min(min, nums[i]);
+ }
+ flag = false;
+ for (int i = nums.length - 2; i >= 0; i--) {
+ if (nums[i] > nums[i + 1])
+ flag = true;
+ if (flag)
+ max = Math.max(max, nums[i]);
+ }
+ int l, r;
+ for (l = 0; l < nums.length; l++) {
+ if (min < nums[l])
+ break;
+ }
+ for (r = nums.length - 1; r >= 0; r--) {
+ if (max > nums[r])
+ break;
+ }
+ return r - l < 0 ? 0 : r - l + 1;
+ } */
+
+ /* public int findUnsortedSubarray(int[] nums) {
+ int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
+ boolean flag = false;
+ for (int i = 1; i < nums.length; i++) {
+ if (nums[i] < nums[i - 1])
+ flag = true;
+ if (flag)
+ min = Math.min(min, nums[i]);
+ }
+ flag = false;
+ for (int i = nums.length - 2; i >= 0; i--) {
+ if (nums[i] > nums[i + 1])
+ flag = true;
+ if (flag)
+ max = Math.max(max, nums[i]);
+ }
+ int l, r;
+ for (l = 0; l < nums.length; l++) {
+ if (min < nums[l])
+ break;
+ }
+ for (r = nums.length - 1; r >= 0; r--) {
+ if (max > nums[r])
+ break;
+ }
+ return r - l < 0 ? 0 : r - l + 1;
+ } */
+}
diff --git a/java/605_Can_Place_Flowers.java b/java/605_Can_Place_Flowers.java
new file mode 100644
index 0000000..54843e4
--- /dev/null
+++ b/java/605_Can_Place_Flowers.java
@@ -0,0 +1,29 @@
+public class Solution {
+ /*public boolean canPlaceFlowers(int[] flowerbed, int n) {
+ int i = 0, count = 0;
+ while (i < flowerbed.length) {
+ if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
+ flowerbed[i++] = 1;
+ count++;
+ }
+ if(count >= n)
+ return true;
+ i++;
+ }
+ return false;
+ }*/
+ public boolean canPlaceFlowers(int[] flowerbed, int n) {
+ int count = 0, curr;
+ for (int i = 0; i < flowerbed.length; i++) {
+ curr = flowerbed[i];
+ if (i - 1 >= 0) curr += flowerbed[i - 1];
+ if (i + 1 < flowerbed.length) curr += flowerbed[i + 1];
+ if (curr == 0) {
+ count++;
+ flowerbed[i] = 1;
+ }
+ if (count >= n) return true;
+ }
+ return false;
+ }
+}
diff --git a/java/617_Merge_Two_Binary_Trees.java b/java/617_Merge_Two_Binary_Trees.java
new file mode 100644
index 0000000..148185c
--- /dev/null
+++ b/java/617_Merge_Two_Binary_Trees.java
@@ -0,0 +1,46 @@
+/**
+ * Definition for a binary tree node.
+ * public class TreeNode {
+ * int val;
+ * TreeNode left;
+ * TreeNode right;
+ * TreeNode(int x) { val = x; }
+ * }
+ */
+public class Solution {
+ public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
+ if (t1 == null)
+ return t2;
+ if (t2 == null)
+ return t1;
+ t1.val += t2.val;
+ t1.left = mergeTrees(t1.left, t2.left);
+ t1.right = mergeTrees(t1.right, t2.right);
+ return t1;
+ }
+
+ // public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
+ // if (t1 == null)
+ // return t2;
+ // Stack < TreeNode[] > stack = new Stack < > ();
+ // stack.push(new TreeNode[] {t1, t2});
+ // while (!stack.isEmpty()) {
+ // TreeNode[] t = stack.pop();
+ // if (t[0] == null || t[1] == null) {
+ // continue;
+ // }
+ // t[0].val += t[1].val;
+ // if (t[0].left == null) {
+ // t[0].left = t[1].left;
+ // } else {
+ // stack.push(new TreeNode[] {t[0].left, t[1].left});
+ // }
+ // if (t[0].right == null) {
+ // t[0].right = t[1].right;
+ // } else {
+ // stack.push(new TreeNode[] {t[0].right, t[1].right});
+ // }
+ // }
+ // return t1;
+ // }
+}
diff --git a/java/628_Maximum_Product_of_Three_Numbers.java b/java/628_Maximum_Product_of_Three_Numbers.java
new file mode 100644
index 0000000..67cadbd
--- /dev/null
+++ b/java/628_Maximum_Product_of_Three_Numbers.java
@@ -0,0 +1,31 @@
+public class Solution {
+ /*public int maximumProduct(int[] nums) {
+ Arrays.sort(nums);
+ return Math.max(nums[0] * nums[1] * nums[nums.length - 1], nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3]);
+ }*/
+
+ public int maximumProduct(int[] nums) {
+ int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
+ int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;
+ for (int n: nums) {
+ if (n <= min1) {
+ min2 = min1;
+ min1 = n;
+ } else if (n <= min2) { // n lies between min1 and min2
+ min2 = n;
+ }
+ if (n >= max1) { // n is greater than max1, max2 and max3
+ max3 = max2;
+ max2 = max1;
+ max1 = n;
+ } else if (n >= max2) { // n lies betweeen max1 and max2
+ max3 = max2;
+ max2 = n;
+ } else if (n >= max3) { // n lies betwen max2 and max3
+ max3 = n;
+ }
+ }
+ return Math.max(min1 * min2 * max1, max1 * max2 * max3);
+ }
+}
+
diff --git a/java/654_Maximum_Binary_Tree.java b/java/654_Maximum_Binary_Tree.java
new file mode 100644
index 0000000..512959d
--- /dev/null
+++ b/java/654_Maximum_Binary_Tree.java
@@ -0,0 +1,39 @@
+public class Solution {
+ public TreeNode constructMaximumBinaryTree(int[] nums) {
+ return construct(nums, 0, nums.length);
+ }
+ public TreeNode construct(int[] nums, int l, int r) {
+ if (l == r)
+ return null;
+ int max_i = max(nums, l, r);
+ TreeNode root = new TreeNode(nums[max_i]);
+ root.left = construct(nums, l, max_i);
+ root.right = construct(nums, max_i + 1, r);
+ return root;
+ }
+ public int max(int[] nums, int l, int r) {
+ int max_i = l;
+ for (int i = l; i < r; i++) {
+ if (nums[max_i] < nums[i])
+ max_i = i;
+ }
+ return max_i;
+ }
+ /*public TreeNode constructMaximumBinaryTree(int[] nums) {
+ // https://leetcode.com/problems/maximum-binary-tree/discuss/106146/C++-O(N)-solution
+ Stack stack = new Stack<>();
+ for (int i=0; i nums[i + 1]) {
+ // More than two broken points
+ if (pos != -1) return false;
+ pos = i;
+ }
+ }
+ if (pos == -1 || pos == 0 || pos == nums.length - 2) return true;
+ // Remove pos or pos + 1
+ return (nums[pos - 1] <= nums[pos + 1] || nums[pos] <= nums[pos + 2]);
+ } */
+
+ public boolean checkPossibility(int[] nums) {
+ int brokenPoint = 0;
+ for (int i = 0; i < nums.length - 1; i++) {
+ if (nums[i] > nums[i + 1]) {
+ brokenPoint++;
+ if (brokenPoint >= 2) return false;
+ // Remove i or remove i + 1
+ if (i - 1 < 0 || nums[i - 1] <= nums[i + 1]) nums[i] = nums[i + 1];
+ else nums[i + 1] = nums[i];
+ }
+ }
+ return true;
+ }
+}
diff --git a/java/668_Kth_Smallest_Number_in_Multiplication_Table.java b/java/668_Kth_Smallest_Number_in_Multiplication_Table.java
new file mode 100644
index 0000000..4ba7a6d
--- /dev/null
+++ b/java/668_Kth_Smallest_Number_in_Multiplication_Table.java
@@ -0,0 +1,22 @@
+class Solution {
+ // https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/solution/
+ public boolean enough(int x, int m, int n, int k) {
+ int count = 0;
+ for (int i = 1; i <= m; i++) {
+ count += Math.min(x / i, n);
+ }
+ return count >= k;
+ }
+
+ public int findKthNumber(int m, int n, int k) {
+ int lo = 1, hi = m * n;
+ while (lo < hi) {
+ // ith row [i, 2*i, 3*i, ..., n*i]
+ // for each column, k = x // i
+ int mi = lo + (hi - lo) / 2;
+ if (!enough(mi, m, n, k)) lo = mi + 1;
+ else hi = mi;
+ }
+ return lo;
+ }
+}
diff --git a/java/671_Second_Minimum_Node_In_a_Binary_Tree.java b/java/671_Second_Minimum_Node_In_a_Binary_Tree.java
new file mode 100644
index 0000000..7cc25ad
--- /dev/null
+++ b/java/671_Second_Minimum_Node_In_a_Binary_Tree.java
@@ -0,0 +1,40 @@
+class Solution {
+ /*public void dfs(TreeNode root, Set uniques) {
+ if (root != null) {
+ uniques.add(root.val);
+ dfs(root.left, uniques);
+ dfs(root.right, uniques);
+ }
+ }
+ public int findSecondMinimumValue(TreeNode root) {
+ // Brute force
+ Set uniques = new HashSet();
+ dfs(root, uniques);
+
+ int min1 = root.val;
+ long ans = Long.MAX_VALUE;
+ for (int v : uniques) {
+ if (min1 < v && v < ans) ans = v;
+ }
+ return ans < Long.MAX_VALUE ? (int) ans : -1;
+ }*/
+
+ public int findSecondMinimumValue(TreeNode root) {
+ if (root == null) return -1;
+ Stack stack = new Stack();
+ int min_val = root.val;
+ int ans = Integer.MAX_VALUE;
+ stack.push(root);
+ while (!stack.empty()) {
+ TreeNode node = stack.pop();
+ if (node == null) continue;
+ if (node.val < ans && node.val > min_val) {
+ ans = node.val;
+ } else if (node.val == min_val) {
+ stack.push(node.left);
+ stack.push(node.right);
+ }
+ }
+ return ans < Integer.MAX_VALUE ? ans : -1;
+ }
+}
diff --git a/java/674_Longest_Continuous_Increasing_Subsequence.java b/java/674_Longest_Continuous_Increasing_Subsequence.java
new file mode 100644
index 0000000..0d267a5
--- /dev/null
+++ b/java/674_Longest_Continuous_Increasing_Subsequence.java
@@ -0,0 +1,15 @@
+class Solution {
+ public int findLengthOfLCIS(int[] nums) {
+ if (nums.length == 0) return 0;
+ int curr = 1, ans = 1;
+ for (int i = 0; i < nums.length - 1; i++) {
+ if (nums[i] < nums[i + 1]) {
+ curr ++;
+ if (curr >= ans) ans = curr;
+ } else {
+ curr = 1;
+ }
+ }
+ return ans;
+ }
+}
diff --git a/java/680_Valid_Palindrome_II.java b/java/680_Valid_Palindrome_II.java
new file mode 100644
index 0000000..adbd899
--- /dev/null
+++ b/java/680_Valid_Palindrome_II.java
@@ -0,0 +1,20 @@
+class Solution {
+ public boolean isPalindromeRange(String s, int i, int j) {
+ for (int k = i; k <= i + (j - i) / 2; k++) {
+ if (s.charAt(k) != s.charAt(j - k + i)) return false;
+ }
+ return true;
+ }
+ public boolean validPalindrome(String s) {
+ for (int i = 0; i < s.length() / 2; i++) {
+ if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
+ // Not equal
+ int j = s.length() - 1 - i;
+ // delete left or right
+ return (isPalindromeRange(s, i + 1, j) ||
+ isPalindromeRange(s, i, j - 1));
+ }
+ }
+ return true;
+ }
+}
diff --git a/java/692_Top_K_Frequent_Words.java b/java/692_Top_K_Frequent_Words.java
new file mode 100644
index 0000000..6062e1a
--- /dev/null
+++ b/java/692_Top_K_Frequent_Words.java
@@ -0,0 +1,32 @@
+class Solution {
+ /*public List topKFrequent(String[] words, int k) {
+ Map count = new HashMap();
+ for (String word: words) {
+ count.put(word, count.getOrDefault(word, 0) + 1);
+ }
+ List candidates = new ArrayList(count.keySet());
+ Collections.sort(candidates, (w1, w2) -> count.get(w1).equals(count.get(w2)) ?
+ w1.compareTo(w2) : count.get(w2) - count.get(w1));
+
+ return candidates.subList(0, k);
+ }*/
+ public List topKFrequent(String[] words, int k) {
+ Map count = new HashMap();
+ for (String word: words) {
+ count.put(word, count.getOrDefault(word, 0) + 1);
+ }
+ PriorityQueue heap = new PriorityQueue(
+ (w1, w2) -> count.get(w1).equals(count.get(w2)) ?
+ w2.compareTo(w1) : count.get(w1) - count.get(w2) );
+
+ for (String word: count.keySet()) {
+ heap.offer(word);
+ if (heap.size() > k) heap.poll();
+ }
+
+ List ans = new ArrayList();
+ while (!heap.isEmpty()) ans.add(heap.poll());
+ Collections.reverse(ans);
+ return ans;
+ }
+}
diff --git a/java/695_Max_Area_of_Island.java b/java/695_Max_Area_of_Island.java
new file mode 100644
index 0000000..5a7a20d
--- /dev/null
+++ b/java/695_Max_Area_of_Island.java
@@ -0,0 +1,57 @@
+/*class Solution {
+ int[][] grid;
+
+ public int area(int r, int c) {
+ if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] == 0)
+ return 0;
+ grid[r][c] = 0;
+ return (1 + area(r + 1, c) + area(r - 1, c)
+ + area(r, c - 1) + area(r, c + 1));
+ }
+
+ public int maxAreaOfIsland(int[][] grid) {
+ this.grid = grid;
+ int ans = 0;
+ for (int r = 0; r < grid.length; r++) {
+ for (int c = 0; c < grid[0].length; c++) {
+ ans = Math.max(ans, area(r, c));
+ }
+ }
+ return ans;
+ }
+}*/
+class Solution {
+ // DFS and you can implement BFS with queue
+ public int maxAreaOfIsland(int[][] grid) {
+ int[] dr = new int[]{1, -1, 0, 0};
+ int[] dc = new int[]{0, 0, 1, -1};
+ int ans = 0;
+ for (int r0 = 0; r0 < grid.length; r0++) {
+ for (int c0 = 0; c0 < grid[0].length; c0++) {
+ if (grid[r0][c0] == 1) {
+ int shape = 0;
+ Stack stack = new Stack();
+ stack.push(new int[]{r0, c0});
+ grid[r0][c0] = 0;
+ while (!stack.empty()) {
+ int[] node = stack.pop();
+ int r = node[0], c = node[1];
+ shape++;
+ for (int k = 0; k < 4; k++) {
+ int nr = r + dr[k];
+ int nc = c + dc[k];
+ if (0 <= nr && nr < grid.length &&
+ 0 <= nc && nc < grid[0].length &&
+ grid[nr][nc] == 1) {
+ stack.push(new int[]{nr, nc});
+ grid[nr][nc] = 0;
+ }
+ }
+ }
+ ans = Math.max(ans, shape);
+ }
+ }
+ }
+ return ans;
+ }
+}
diff --git a/java/697_Degree_of_an_Array.java b/java/697_Degree_of_an_Array.java
new file mode 100644
index 0000000..f0bec90
--- /dev/null
+++ b/java/697_Degree_of_an_Array.java
@@ -0,0 +1,24 @@
+class Solution {
+ public int findShortestSubArray(int[] nums) {
+ Map left = new HashMap(),
+ right = new HashMap(), count = new HashMap();
+
+ for (int i = 0; i < nums.length; i++) {
+ int x = nums[i];
+ // left most position
+ if (left.get(x) == null) left.put(x, i);
+ // right most position
+ right.put(x, i);
+ count.put(x, count.getOrDefault(x, 0) + 1);
+ }
+
+ int ans = nums.length;
+ int degree = Collections.max(count.values());
+ for (int x: count.keySet()) {
+ if (count.get(x) == degree) {
+ ans = Math.min(ans, right.get(x) - left.get(x) + 1);
+ }
+ }
+ return ans;
+ }
+}
diff --git a/java/700_Search_in_a_Binary_Search_Tree.java b/java/700_Search_in_a_Binary_Search_Tree.java
new file mode 100644
index 0000000..0389652
--- /dev/null
+++ b/java/700_Search_in_a_Binary_Search_Tree.java
@@ -0,0 +1,24 @@
+/**
+ * Definition for a binary tree node.
+ * public class TreeNode {
+ * int val;
+ * TreeNode left;
+ * TreeNode right;
+ * TreeNode(int x) { val = x; }
+ * }
+ */
+class Solution {
+ /*public TreeNode searchBST(TreeNode root, int val) {
+ // Recursive
+ if (root == null) return root;
+ if (root.val == val) return root;
+ else return val q;
+ final int k;
+
+ public KthLargest(int k, int[] nums) {
+ this.k = k;
+ q = new PriorityQueue<>(k);
+ // remove n - k smallest number
+ for (int val : nums)
+ add(val);
+ }
+
+ public int add(int val) {
+ // add to heaq if it's less then k
+ if (q.size() < k)
+ q.offer(val);
+ else if (q.peek() < val) {
+ // if len(heaq) == k, and val greater than smallest num
+ // then pop smallest num than add val to heap
+ q.poll();
+ q.offer(val);
+ }
+ return q.peek();
+ }
+}
+
+/**
+ * Your KthLargest object will be instantiated and called as such:
+ * KthLargest obj = new KthLargest(k, nums);
+ * int param_1 = obj.add(val);
+ */
\ No newline at end of file
diff --git a/java/706_Design_HashMap.java b/java/706_Design_HashMap.java
new file mode 100644
index 0000000..88cd757
--- /dev/null
+++ b/java/706_Design_HashMap.java
@@ -0,0 +1,50 @@
+class MyHashMap {
+ final ListNode[] nodes = new ListNode[10000];
+ // https://leetcode.com/problems/design-hashmap/discuss/152746/Java-Solution
+ public void put(int key, int value) {
+ int i = idx(key);
+ if (nodes[i] == null)
+ nodes[i] = new ListNode(-1, -1);
+ ListNode prev = find(nodes[i], key);
+ if (prev.next == null)
+ prev.next = new ListNode(key, value);
+ else prev.next.val = value;
+ }
+
+ public int get(int key) {
+ int i = idx(key);
+ if (nodes[i] == null)
+ return -1;
+ ListNode node = find(nodes[i], key);
+ return node.next == null ? -1 : node.next.val;
+ }
+
+ public void remove(int key) {
+ int i = idx(key);
+ if (nodes[i] == null) return;
+ ListNode prev = find(nodes[i], key);
+ if (prev.next == null) return;
+ prev.next = prev.next.next;
+ }
+
+ int idx(int key) { return Integer.hashCode(key) % nodes.length;}
+
+ ListNode find(ListNode bucket, int key) {
+ ListNode node = bucket, prev = null;
+ while (node != null && node.key != key) {
+ prev = node;
+ node = node.next;
+ }
+ return prev;
+ }
+
+ class ListNode {
+ int key, val;
+ ListNode next;
+
+ ListNode(int key, int val) {
+ this.key = key;
+ this.val = val;
+ }
+ }
+}
diff --git a/java/709_To_Lower_Case.java b/java/709_To_Lower_Case.java
new file mode 100644
index 0000000..77b775e
--- /dev/null
+++ b/java/709_To_Lower_Case.java
@@ -0,0 +1,13 @@
+class Solution {
+ public String toLowerCase(String str) {
+ return str.toLowerCase();
+ }
+
+ /*public String toLowerCase(String str) {
+ char[] a = str.toCharArray();
+ for (int i = 0; i < a.length; i++)
+ if ('A' <= a[i] && a[i] <= 'Z')
+ a[i] = (char) (a[i] - 'A' + 'a');
+ return new String(a);
+ }*/
+}
diff --git a/java/716_Max_Stack.java b/java/716_Max_Stack.java
new file mode 100644
index 0000000..71f19e3
--- /dev/null
+++ b/java/716_Max_Stack.java
@@ -0,0 +1,80 @@
+class MaxStack {
+ TreeMap> map;
+ DoubleLinkedList dll;
+
+ public MaxStack() {
+ map = new TreeMap();
+ dll = new DoubleLinkedList();
+ }
+
+ public void push(int x) {
+ Node node = dll.add(x);
+ if(!map.containsKey(x))
+ map.put(x, new ArrayList());
+ map.get(x).add(node);
+ }
+
+ public int pop() {
+ int val = dll.pop();
+ List L = map.get(val);
+ L.remove(L.size() - 1);
+ if (L.isEmpty()) map.remove(val);
+ return val;
+ }
+
+ public int top() {
+ return dll.peek();
+ }
+
+ public int peekMax() {
+ return map.lastKey();
+ }
+
+ public int popMax() {
+ int max = peekMax();
+ List L = map.get(max);
+ Node node = L.remove(L.size() - 1);
+ dll.unlink(node);
+ if (L.isEmpty()) map.remove(max);
+ return max;
+ }
+}
+
+class DoubleLinkedList {
+ Node head, tail;
+
+ public DoubleLinkedList() {
+ head = new Node(0);
+ tail = new Node(0);
+ head.next = tail;
+ tail.prev = head;
+ }
+
+ public Node add(int val) {
+ Node x = new Node(val);
+ x.next = tail;
+ x.prev = tail.prev;
+ tail.prev = tail.prev.next = x;
+ return x;
+ }
+
+ public int pop() {
+ return unlink(tail.prev).val;
+ }
+
+ public int peek() {
+ return tail.prev.val;
+ }
+
+ public Node unlink(Node node) {
+ node.prev.next = node.next;
+ node.next.prev = node.prev;
+ return node;
+ }
+}
+
+class Node {
+ int val;
+ Node prev, next;
+ public Node(int v) {val = v;}
+}
diff --git a/java/717_1-bit_and_2-bit_Characters.java b/java/717_1-bit_and_2-bit_Characters.java
new file mode 100644
index 0000000..8e560c8
--- /dev/null
+++ b/java/717_1-bit_and_2-bit_Characters.java
@@ -0,0 +1,44 @@
+/*
+We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).
+
+Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.
+
+Example 1:
+Input:
+bits = [1, 0, 0]
+Output: True
+Explanation:
+The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.
+Example 2:
+Input:
+bits = [1, 1, 1, 0]
+Output: False
+Explanation:
+The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.
+Note:
+
+1 <= len(bits) <= 1000.
+bits[i] is always 0 or 1.
+*/
+
+// https://leetcode.com/problems/1-bit-and-2-bit-characters/solution/
+class Solution {
+ public boolean isOneBitCharacter(int[] bits) {
+ int pos = 0;
+ // Go through bits
+ while (pos < bits.length - 1) {
+ // if 1, pos + 2; if 0, pos + 1
+ pos += bits[pos] + 1;
+ }
+ return pos == bits.length - 1;
+ }
+
+ /* public boolean isOneBitCharacter(int[] bits) {
+ // From len - 2
+ int i = bits.length - 2;
+ // until encounter 0
+ while (i >= 0 && bits[i] > 0) i--;
+ // check if second last zero is even
+ return (bits.length - i) % 2 == 0;
+ } */
+}
diff --git a/java/720_Longest_Word_in_Dictionary.java b/java/720_Longest_Word_in_Dictionary.java
new file mode 100644
index 0000000..09c42f0
--- /dev/null
+++ b/java/720_Longest_Word_in_Dictionary.java
@@ -0,0 +1,78 @@
+class Solution {
+ /*public String longestWord(String[] words) {
+ String ans = "";
+ Set wordset = new HashSet();
+ for (String word: words) wordset.add(word);
+ for (String word: words) {
+ if (word.length() > ans.length() ||
+ word.length() == ans.length() && word.compareTo(ans) < 0) {
+ boolean good = true;
+ for (int k = 1; k < word.length(); ++k) {
+ if (!wordset.contains(word.substring(0, k))) {
+ good = false;
+ break;
+ }
+ }
+ if (good) ans = word;
+ }
+ }
+ return ans;
+ }*/
+
+ public String longestWord(String[] words) {
+ Trie trie = new Trie();
+ int index = 0;
+ for (String word: words) {
+ trie.insert(word, ++index); //indexed by 1
+ }
+ trie.words = words;
+ return trie.dfs();
+ }
+}
+class Node {
+ char c;
+ HashMap children = new HashMap();
+ int end;
+ public Node(char c){
+ this.c = c;
+ }
+}
+
+class Trie {
+ Node root;
+ String[] words;
+ public Trie() {
+ root = new Node('0');
+ }
+
+ public void insert(String word, int index) {
+ Node cur = root;
+ for (char c: word.toCharArray()) {
+ cur.children.putIfAbsent(c, new Node(c));
+ cur = cur.children.get(c);
+ }
+ cur.end = index;
+ }
+
+ public String dfs() {
+ String ans = "";
+ Stack stack = new Stack();
+ stack.push(root);
+ while (!stack.empty()) {
+ Node node = stack.pop();
+ if (node.end > 0 || node == root) {
+ if (node != root) {
+ String word = words[node.end - 1];
+ if (word.length() > ans.length() ||
+ word.length() == ans.length() && word.compareTo(ans) < 0) {
+ ans = word;
+ }
+ }
+ for (Node nei: node.children.values()) {
+ stack.push(nei);
+ }
+ }
+ }
+ return ans;
+ }
+}
diff --git a/java/724_Find_Pivot_Index.java b/java/724_Find_Pivot_Index.java
new file mode 100644
index 0000000..6abff95
--- /dev/null
+++ b/java/724_Find_Pivot_Index.java
@@ -0,0 +1,13 @@
+class Solution {
+ public int pivotIndex(int[] nums) {
+ int totalsum = 0, leftsum = 0;
+ // Compute total sum
+ for (int i = 0; i < nums.length; i++) totalsum += nums[i];
+ // Check leftsum == rightsum
+ for (int i = 0; i < nums.length; i++) {
+ if (leftsum == totalsum - leftsum - nums[i]) return i;
+ leftsum += nums[i];
+ }
+ return -1;
+ }
+}
diff --git a/java/728_Self_Dividing_Numbers.java b/java/728_Self_Dividing_Numbers.java
new file mode 100644
index 0000000..eeb12af
--- /dev/null
+++ b/java/728_Self_Dividing_Numbers.java
@@ -0,0 +1,27 @@
+class Solution {
+ public List selfDividingNumbers(int left, int right) {
+ LinkedList list = new LinkedList();
+ for(int i = left; i <= right; i++) {
+ if(isSelfDiving(i))
+ list.add(i);
+ }
+ return list;
+ }
+
+ public boolean isSelfDiving(int num) {
+ int digit = num % 10;
+ int temp = num;
+ boolean isTrue = true;
+ while(temp != 0) {
+ // 0 is special
+ if(digit == 0 || num % digit != 0) {
+ isTrue = false;
+ break;
+ } else {
+ temp /= 10;
+ digit = temp % 10;
+ }
+ }
+ return isTrue;
+ }
+}
diff --git a/java/733_Flood_Fill.java b/java/733_Flood_Fill.java
new file mode 100644
index 0000000..ccbf6dd
--- /dev/null
+++ b/java/733_Flood_Fill.java
@@ -0,0 +1,48 @@
+class Solution {
+ /*public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
+ if (image[sr][sc] == newColor) return image;
+ dfs(image, sr, sc, image[sr][sc], newColor);
+ return image;
+ }
+
+ private void dfs(int[][] image, int r, int c, int color, int newColor) {
+ // Recursively DFS
+ if (image[r][c] == color) {
+ image[r][c] = newColor;
+ if (r - 1 >= 0) dfs(image, r - 1, c, color, newColor);
+ if (r + 1 < image.length) dfs(image, r + 1, c, color, newColor);
+ if (c - 1 >= 0) dfs(image, r, c - 1, color, newColor);
+ if (c + 1 < image[0].length) dfs(image, r, c + 1, color, newColor);
+ }
+ }*/
+
+ public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
+ Queue queue = new LinkedList();
+ int color = image[sr][sc];
+ if (color == newColor) return image;
+ queue.add(new Node(sr, sc));
+ // BFS with queue
+ while (!queue.isEmpty()) {
+ Node curr = queue.remove();
+ int r = curr.r, c = curr.c;
+ if (image[r][c] == color) {
+ image[r][c] = newColor;
+ if (r - 1 >= 0) queue.add(new Node(r - 1, c));
+ if (r + 1 < image.length) queue.add(new Node(r + 1, c));
+ if (c - 1 >= 0) queue.add(new Node(r, c - 1));
+ if (c + 1 < image[0].length) queue.add(new Node(r, c + 1));
+ }
+ }
+ return image;
+ }
+
+ class Node {
+ int r;
+ int c;
+
+ public Node(int r, int c) {
+ this.r = r;
+ this.c = c;
+ }
+ }
+}
diff --git a/java/743_Network_Delay_Time.java b/java/743_Network_Delay_Time.java
new file mode 100644
index 0000000..eb729b0
--- /dev/null
+++ b/java/743_Network_Delay_Time.java
@@ -0,0 +1,75 @@
+class Solution {
+ /*Map dist;
+ public int networkDelayTime(int[][] times, int N, int K) {
+ // DFS
+ Map> graph = new HashMap();
+ for (int[] edge: times) {
+ if (!graph.containsKey(edge[0]))
+ graph.put(edge[0], new ArrayList());
+ graph.get(edge[0]).add(new int[]{edge[2], edge[1]});
+ }
+ for (int node: graph.keySet()) {
+ Collections.sort(graph.get(node), (a, b) -> a[0] - b[0]);
+ }
+ dist = new HashMap();
+ for (int node = 1; node <= N; ++node)
+ dist.put(node, Integer.MAX_VALUE);
+
+ dfs(graph, K, 0);
+ int ans = 0;
+ for (int cand: dist.values()) {
+ if (cand == Integer.MAX_VALUE) return -1;
+ ans = Math.max(ans, cand);
+ }
+ return ans;
+ }
+
+ public void dfs(Map> graph, int node, int elapsed) {
+ if (elapsed >= dist.get(node)) return;
+ dist.put(node, elapsed);
+ if (graph.containsKey(node))
+ for (int[] info: graph.get(node))
+ dfs(graph, info[1], elapsed + info[0]);
+ }*/
+ Map dist;
+ public int networkDelayTime(int[][] times, int N, int K) {
+ // Dijkstra
+ Map> graph = new HashMap();
+ for (int[] edge: times) {
+ if (!graph.containsKey(edge[0]))
+ graph.put(edge[0], new ArrayList());
+ graph.get(edge[0]).add(new int[]{edge[1], edge[2]});
+ }
+ dist = new HashMap();
+ for (int node = 1; node <= N; ++node)
+ dist.put(node, Integer.MAX_VALUE);
+
+ dist.put(K, 0);
+ boolean[] seen = new boolean[N+1];
+
+ while (true) {
+ int candNode = -1;
+ int candDist = Integer.MAX_VALUE;
+ for (int i = 1; i <= N; ++i) {
+ if (!seen[i] && dist.get(i) < candDist) {
+ candDist = dist.get(i);
+ candNode = i;
+ }
+ }
+
+ if (candNode < 0) break;
+ seen[candNode] = true;
+ if (graph.containsKey(candNode))
+ for (int[] info: graph.get(candNode))
+ dist.put(info[0],
+ Math.min(dist.get(info[0]), dist.get(candNode) + info[1]));
+ }
+
+ int ans = 0;
+ for (int cand: dist.values()) {
+ if (cand == Integer.MAX_VALUE) return -1;
+ ans = Math.max(ans, cand);
+ }
+ return ans;
+ }
+}
diff --git a/java/751_IP_to_CIDR.java b/java/751_IP_to_CIDR.java
new file mode 100644
index 0000000..55fcad4
--- /dev/null
+++ b/java/751_IP_to_CIDR.java
@@ -0,0 +1,34 @@
+class Solution {
+ public List ipToCIDR(String ip, int n) {
+ long start = ipToLong(ip);
+ List ans = new ArrayList();
+ while (n > 0) {
+ int mask = Math.max(33 - bitLength(Long.lowestOneBit(start)),
+ 33 - bitLength(n));
+ ans.add(longToIP(start) + "/" + mask);
+ start += 1 << (32 - mask);
+ n -= 1 << (32 - mask);
+ }
+ return ans;
+ }
+ private long ipToLong(String ip) {
+ long ans = 0;
+ for (String x: ip.split("\\.")) {
+ ans = 256 * ans + Integer.valueOf(x);
+ }
+ return ans;
+ }
+ private String longToIP(long x) {
+ return String.format("%s.%s.%s.%s",
+ x >> 24, (x >> 16) % 256, (x >> 8) % 256, x % 256);
+ }
+ private int bitLength(long x) {
+ if (x == 0) return 1;
+ int ans = 0;
+ while (x > 0) {
+ x >>= 1;
+ ans++;
+ }
+ return ans;
+ }
+}
\ No newline at end of file
diff --git a/java/760_Find_Anagram_Mappings.java b/java/760_Find_Anagram_Mappings.java
new file mode 100644
index 0000000..414d69f
--- /dev/null
+++ b/java/760_Find_Anagram_Mappings.java
@@ -0,0 +1,9 @@
+class Solution {
+ public int[] anagramMappings(int[] A, int[] B) {
+ int[] ans = new int[A.length];
+ HashMap valIndex = new HashMap<>();
+ for (int i = 0; i < B.length; i++) valIndex.put(B[i], i);
+ for (int i = 0; i < A.length; i++) ans[i] = valIndex.get(A[i]);
+ return ans;
+ }
+}
diff --git a/java/766_Toeplitz_Matrix.java b/java/766_Toeplitz_Matrix.java
new file mode 100644
index 0000000..20f727d
--- /dev/null
+++ b/java/766_Toeplitz_Matrix.java
@@ -0,0 +1,11 @@
+class Solution {
+ public boolean isToeplitzMatrix(int[][] matrix) {
+ // Start from second line and column
+ for (int r = 1; r < matrix.length; ++r)
+ for (int c = 1; c < matrix[0].length; ++c)
+ // Check step by step
+ if (matrix[r-1][c-1] != matrix[r][c])
+ return false;
+ return true;
+ }
+}
diff --git a/java/771_Jewels_and_Stones.java b/java/771_Jewels_and_Stones.java
new file mode 100644
index 0000000..a7bb3ce
--- /dev/null
+++ b/java/771_Jewels_and_Stones.java
@@ -0,0 +1,17 @@
+import java.util.HashSet;
+
+class Solution {
+ public int numJewelsInStones(String J, String S) {
+ int result = 0;
+ HashSet jHash = new HashSet<>();
+ for (int j = 0; j < J.length(); j++) {
+ jHash.add(J.charAt(j));
+ }
+ for (int s = 0; s < S.length(); s++) {
+ if (jHash.contains(S.charAt(s))) {
+ result++;
+ }
+ }
+ return result;
+ }
+}
diff --git a/java/784_Letter_Case_Permutation.java b/java/784_Letter_Case_Permutation.java
new file mode 100644
index 0000000..3c9d83b
--- /dev/null
+++ b/java/784_Letter_Case_Permutation.java
@@ -0,0 +1,54 @@
+class Solution {
+ public List letterCasePermutation(String S) {
+ List ans = new ArrayList();
+ ans.add(new StringBuilder());
+
+ for (char c: S.toCharArray()) {
+ int n = ans.size();
+ if (Character.isLetter(c)) {
+ for (int i = 0; i < n; ++i) {
+ ans.add(new StringBuilder(ans.get(i)));
+ ans.get(i).append(Character.toLowerCase(c));
+ ans.get(n + i).append(Character.toUpperCase(c));
+ }
+ } else {
+ for (int i = 0; i < n; ++i)
+ ans.get(i).append(c);
+ }
+ }
+
+ List finalans = new ArrayList();
+ for (StringBuilder sb: ans)
+ finalans.add(sb.toString());
+ return finalans;
+ }
+
+ /*public List letterCasePermutation(String S) {
+ int B = 0;
+ for (char c: S.toCharArray())
+ if (Character.isLetter(c))
+ B++;
+
+ List ans = new ArrayList();
+
+ for (int bits = 0; bits < 1<> b++) & 1) == 1)
+ word.append(Character.toLowerCase(letter));
+ else
+ word.append(Character.toUpperCase(letter));
+ } else {
+ word.append(letter);
+ }
+ }
+
+ ans.add(word.toString());
+ }
+
+ return ans;
+
+ }*/
+}
diff --git a/java/787_Cheapest_Flight_Within_K_Stops.java b/java/787_Cheapest_Flight_Within_K_Stops.java
new file mode 100644
index 0000000..9355cf9
--- /dev/null
+++ b/java/787_Cheapest_Flight_Within_K_Stops.java
@@ -0,0 +1,41 @@
+class Solution {
+ //using bellman ford
+
+ public void computePrice(int[][]flights, int[] prices, int [] temp){
+ for(int[] flight: flights){
+ int u = flight[0];
+ int v = flight[1];
+ int price = flight[2];
+
+ if(prices[u] != Integer.MAX_VALUE){
+ if(prices[u] + price < temp[v]){
+ temp[v] = prices[u] + price;
+ }
+ }
+ }
+ }
+
+ public void copyTempToPrice(int[] prices, int[] temp){
+ for(int i=0; i seen = new HashSet();
+ for (String word: words) {
+ StringBuilder code = new StringBuilder();
+ for (char c: word.toCharArray())
+ code.append(MORSE[c - 'a']);
+ seen.add(code.toString());
+ }
+
+ return seen.size();
+ }
+}
diff --git a/java/811_Subdomain_Visit_Count.java b/java/811_Subdomain_Visit_Count.java
new file mode 100644
index 0000000..9c5b881
--- /dev/null
+++ b/java/811_Subdomain_Visit_Count.java
@@ -0,0 +1,22 @@
+class Solution {
+ public List subdomainVisits(String[] cpdomains) {
+ // https://leetcode.com/problems/subdomain-visit-count/discuss/121738/C%2B%2BJavaPython-Easy-Understood-Solution
+ Map map = new HashMap();
+ for (String cpdomain : cpdomains) {
+ int i = cpdomain.indexOf(' ');
+ int n = Integer.valueOf(cpdomain.substring(0, i));
+ String domain = cpdomain.substring(i + 1);
+ for (i = 0; i < domain.length(); ++i) {
+ if (domain.charAt(i) == '.') {
+ String d = domain.substring(i + 1);
+ map.put(d, map.getOrDefault(d, 0) + n);
+ }
+ }
+ map.put(domain, map.getOrDefault(domain, 0) + n);
+ }
+
+ List res = new ArrayList();
+ for (String domain : map.keySet()) res.add(map.get(domain) + " " + domain);
+ return res;
+ }
+}
diff --git a/java/819_Most_Common_Word.java b/java/819_Most_Common_Word.java
new file mode 100644
index 0000000..4083ad4
--- /dev/null
+++ b/java/819_Most_Common_Word.java
@@ -0,0 +1,34 @@
+class Solution {
+ public String mostCommonWord(String paragraph, String[] banned) {
+ paragraph += ".";
+
+ Set banset = new HashSet();
+ for (String word: banned) banset.add(word);
+ Map count = new HashMap();
+
+ String ans = "";
+ int ansfreq = 0;
+
+ StringBuilder word = new StringBuilder();
+ for (char c: paragraph.toCharArray()) {
+ if (Character.isLetter(c)) {
+ // word
+ word.append(Character.toLowerCase(c));
+ } else if (word.length() > 0) {
+ // punctuation symbols
+ // node that word length should be larger than 0
+ String finalword = word.toString();
+ if (!banset.contains(finalword)) {
+ count.put(finalword, count.getOrDefault(finalword, 0) + 1);
+ // Record max here
+ if (count.get(finalword) > ansfreq) {
+ ans = finalword;
+ ansfreq = count.get(finalword);
+ }
+ }
+ word = new StringBuilder();
+ }
+ }
+ return ans;
+ }
+}
diff --git a/java/832_Flipping_an_Image.java b/java/832_Flipping_an_Image.java
new file mode 100644
index 0000000..4a7c151
--- /dev/null
+++ b/java/832_Flipping_an_Image.java
@@ -0,0 +1,13 @@
+class Solution {
+ public int[][] flipAndInvertImage(int[][] A) {
+ int C = A[0].length;
+ for (int[] row: A)
+ for (int i = 0; i < (C + 1) / 2; ++i) {
+ int tmp = row[i] ^ 1;
+ row[i] = row[C - 1 - i] ^ 1;
+ row[C - 1 - i] = tmp;
+ }
+
+ return A;
+ }
+}
diff --git a/java/836_Rectangle_Overlap.java b/java/836_Rectangle_Overlap.java
new file mode 100644
index 0000000..3d0c364
--- /dev/null
+++ b/java/836_Rectangle_Overlap.java
@@ -0,0 +1,22 @@
+class Solution {
+ /*public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
+ // Check position
+ return !(rec1[2] <= rec2[0] || // left
+ rec1[3] <= rec2[1] || // bottom
+ rec1[0] >= rec2[2] || // right
+ rec1[1] >= rec2[3]); // top
+ }*/
+ /*public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
+ // Check area
+ // https://leetcode.com/problems/rectangle-area/discuss/62149/Just-another-short-way
+ int left = Math.max(rec1[0], rec2[0]), right = Math.max(Math.min(rec1[2], rec2[2]), left);
+ int bottom = Math.max(rec1[1], rec2[1]), top = Math.max(Math.min(rec1[3], rec2[3]), bottom);
+ return (right - left) * (top - bottom) != 0;
+ }*/
+
+ public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
+ // Check area
+ return (Math.min(rec1[2], rec2[2]) > Math.max(rec1[0], rec2[0]) && // width > 0
+ Math.min(rec1[3], rec2[3]) > Math.max(rec1[1], rec2[1])); // height > 0
+ }
+}
\ No newline at end of file
diff --git a/java/844_Backspace_String_Compare.java b/java/844_Backspace_String_Compare.java
new file mode 100644
index 0000000..8e813af
--- /dev/null
+++ b/java/844_Backspace_String_Compare.java
@@ -0,0 +1,29 @@
+class Solution {
+ /*public boolean backspaceCompare(String S, String T) {
+ // https://leetcode.com/problems/backspace-string-compare/discuss/135603/C%2B%2BJavaPython-O(N)-time-and-O(1)-space
+ int i = S.length() - 1, j = T.length() - 1;
+ while (true) {
+ for (int back = 0; i >= 0 && (back > 0 || S.charAt(i) == '#'); --i)
+ back += S.charAt(i) == '#' ? 1 : -1;
+ for (int back = 0; j >= 0 && (back > 0 || T.charAt(j) == '#'); --j)
+ back += T.charAt(j) == '#' ? 1 : -1;
+ if (i >= 0 && j >= 0 && S.charAt(i) == T.charAt(j)) {
+ i--; j--;
+ } else
+ return i == -1 && j == -1;
+ }
+ }*/
+
+ public boolean backspaceCompare(String S, String T) {
+ return trans(S).equals(trans(T));
+ }
+ private String trans(String str) {
+ StringBuilder sb = new StringBuilder();
+ for (char c : str.toCharArray()) {
+ if (c != '#') { sb.append(c); } // if not '#', append it at the end of sb.
+ else if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } // remove last char in sb, if sb is not empty.
+ }
+ return sb.toString();
+ }
+
+}
diff --git a/java/852_Peak_Index_in_a_Mountain_Array.java b/java/852_Peak_Index_in_a_Mountain_Array.java
new file mode 100644
index 0000000..bf8d893
--- /dev/null
+++ b/java/852_Peak_Index_in_a_Mountain_Array.java
@@ -0,0 +1,17 @@
+class Solution {
+ // public int peakIndexInMountainArray(int[] A) {
+ // int i = 0;
+ // for (; A[i] < A[i + 1]; i++);
+ // return i;
+ // }
+
+ public int peakIndexInMountainArray(int[] A) {
+ int lo = 0, hi = A.length - 1;
+ while (lo < hi) {
+ int mid = (lo + hi) / 2;
+ if (A[mid] < A[mid + 1]) lo = mid + 1;
+ else hi = mid;
+ }
+ return lo;
+ }
+}
diff --git a/java/867_Transpose_Matrix.java b/java/867_Transpose_Matrix.java
new file mode 100644
index 0000000..57141a3
--- /dev/null
+++ b/java/867_Transpose_Matrix.java
@@ -0,0 +1,11 @@
+class Solution {
+ public int[][] transpose(int[][] A) {
+ int R = A.length, C = A[0].length;
+ int[][] ans = new int[C][R];
+ for (int r = 0; r < R; ++r)
+ for (int c = 0; c < C; ++c) {
+ ans[c][r] = A[r][c];
+ }
+ return ans;
+ }
+}
diff --git a/java/868_Binary_Gap.java b/java/868_Binary_Gap.java
new file mode 100644
index 0000000..9d54364
--- /dev/null
+++ b/java/868_Binary_Gap.java
@@ -0,0 +1,27 @@
+class Solution {
+ /*public int binaryGap(int n) {
+ // Store Indexes
+ int[] A = new int[32];
+ int t = 0;
+ for (int i = 0; i < 32; ++i)
+ if (((N >> i) & 1) != 0)
+ A[t++] = i;
+
+ int ans = 0;
+ for (int i = 0; i < t - 1; ++i)
+ ans = Math.max(ans, A[i+1] - A[i]);
+ return ans;
+ }*/
+
+ public int binaryGap(int N) {
+ int last = -1, ans = 0;
+ for (int i = 0; i < 32; ++i)
+ if (((N >> i) & 1) > 0) {
+ // Store max
+ if (last >= 0)
+ ans = Math.max(ans, i - last);
+ last = i;
+ }
+ return ans;
+ }
+}
diff --git a/java/872_Leaf-Similar_Trees.java b/java/872_Leaf-Similar_Trees.java
new file mode 100644
index 0000000..32b91c0
--- /dev/null
+++ b/java/872_Leaf-Similar_Trees.java
@@ -0,0 +1,18 @@
+class Solution {
+ public boolean leafSimilar(TreeNode root1, TreeNode root2) {
+ List leaves1 = new ArrayList();
+ List leaves2 = new ArrayList();
+ dfs(root1, leaves1);
+ dfs(root2, leaves2);
+ return leaves1.equals(leaves2);
+ }
+
+ public void dfs(TreeNode node, List leafValues) {
+ if (node != null) {
+ if (node.left == null && node.right == null)
+ leafValues.add(node.val);
+ dfs(node.left, leafValues);
+ dfs(node.right, leafValues);
+ }
+ }
+}
diff --git a/java/876_Middle_of_the_Linked_List.java b/java/876_Middle_of_the_Linked_List.java
new file mode 100644
index 0000000..1fd57ab
--- /dev/null
+++ b/java/876_Middle_of_the_Linked_List.java
@@ -0,0 +1,27 @@
+/**
+ * Definition for singly-linked list.
+ * public class ListNode {
+ * int val;
+ * ListNode next;
+ * ListNode(int x) { val = x; }
+ * }
+ */
+class Solution {
+ // public ListNode middleNode(ListNode head) {
+ // List array = new ArrayList();
+ // while (head != null) {
+ // array.add(head);
+ // head = head.next;
+ // }
+ // return array.get(array.size() / 2);
+ // }
+ public ListNode middleNode(ListNode head) {
+ ListNode fast, slow;
+ fast = slow = head;
+ while (fast != null && fast.next != null) {
+ slow = slow.next;
+ fast = fast.next.next;
+ }
+ return slow;
+ }
+}
diff --git a/java/904_Fruit_Into_Baskets.java b/java/904_Fruit_Into_Baskets.java
new file mode 100644
index 0000000..e48d593
--- /dev/null
+++ b/java/904_Fruit_Into_Baskets.java
@@ -0,0 +1,73 @@
+class Solution {
+ // https://leetcode.com/problems/fruit-into-baskets/solution/
+/* public int totalFruit(int[] tree) {
+ // We'll make a list of indexes for which a block starts.
+ List blockLefts = new ArrayList();
+
+ // Add the left boundary of each block
+ for (int i = 0; i < tree.length; ++i)
+ if (i == 0 || tree[i-1] != tree[i])
+ blockLefts.add(i);
+
+ // Add tree.length as a sentinel for convenience
+ blockLefts.add(tree.length);
+
+ int ans = 0, i = 0;
+ search: while (true) {
+ // We'll start our scan at block[i].
+ // types : the different values of tree[i] seen
+ // weight : the total number of trees represented
+ // by blocks under consideration
+ Set types = new HashSet();
+ int weight = 0;
+
+ // For each block from the i-th and going forward,
+ for (int j = i; j < blockLefts.size() - 1; ++j) {
+ // Add each block to consideration
+ types.add(tree[blockLefts.get(j)]);
+ weight += blockLefts.get(j+1) - blockLefts.get(j);
+
+ // If we have 3+ types, this is an illegal subarray
+ if (types.size() >= 3) {
+ i = j - 1;
+ continue search;
+ }
+
+ // If it is a legal subarray, record the answer
+ ans = Math.max(ans, weight);
+ }
+
+ break;
+ }
+
+ return ans;
+ }*/
+
+ public int totalFruit(int[] tree) {
+ int ans = 0, i = 0;
+ Counter count = new Counter();
+ for (int j = 0; j < tree.length; ++j) {
+ count.add(tree[j], 1);
+ while (count.size() >= 3) {
+ count.add(tree[i], -1);
+ if (count.get(tree[i]) == 0)
+ count.remove(tree[i]);
+ i++;
+ }
+
+ ans = Math.max(ans, j - i + 1);
+ }
+
+ return ans;
+ }
+}
+
+class Counter extends HashMap {
+ public int get(int k) {
+ return containsKey(k) ? super.get(k) : 0;
+ }
+
+ public void add(int k, int v) {
+ put(k, get(k) + v);
+ }
+}
diff --git a/java/905_Sort_Array_By_Parity.java b/java/905_Sort_Array_By_Parity.java
new file mode 100644
index 0000000..09619cd
--- /dev/null
+++ b/java/905_Sort_Array_By_Parity.java
@@ -0,0 +1,36 @@
+class Solution {
+/* public int[] sortArrayByParity(int[] A) {
+ A = Arrays.stream(A).
+ boxed().
+ sorted((a, b) -> Integer.compare(a% 2, b % 2)).
+ mapToInt(i -> i).
+ toArray();
+ return A;
+ }*/
+
+ /*public int[] sortArrayByParity(int[] A) {
+ int[] ans = new int[A.length];
+ int pos = 0;
+ for (int num: A)
+ if (num % 2 == 0)
+ ans[pos++] = num;
+ for (int num: A)
+ if (num % 2 == 1)
+ ans[pos++] = num;
+ return ans;
+ }*/
+
+ public int[] sortArrayByParity(int[] A) {
+ int lo = 0, hi = A.length - 1;
+ while (lo < hi) {
+ if (A[lo] % 2 > A[hi] % 2) {
+ int tmp = A[hi];
+ A[hi] = A[lo];
+ A[lo] = tmp;
+ }
+ if (A[lo] % 2 == 0) lo++;
+ if (A[hi] % 2 == 1) hi--;
+ }
+ return A;
+ }
+}
diff --git a/java/922_Sort_Array_By_Parity_II.java b/java/922_Sort_Array_By_Parity_II.java
new file mode 100644
index 0000000..760f7fc
--- /dev/null
+++ b/java/922_Sort_Array_By_Parity_II.java
@@ -0,0 +1,32 @@
+class Solution {
+ /*public int[] sortArrayByParityII(int[] A) {
+ int N = A.length;
+ int[] ans = new int[N];
+ int t = 0;
+ for (int x: A) if (x % 2 == 0) {
+ ans[t] = x;
+ t += 2;
+ }
+ t = 1;
+ for (int x: A) if (x % 2 == 1) {
+ ans[t] = x;
+ t += 2;
+ }
+ return ans;
+ }*/
+ public int[] sortArrayByParityII(int[] A) {
+ int j = 1;
+ for (int i = 0; i < A.length; i += 2)
+ if (A[i] % 2 == 1) {
+ while (A[j] % 2 == 1)
+ j += 2;
+
+ // Swap A[i] and A[j]
+ int tmp = A[i];
+ A[i] = A[j];
+ A[j] = tmp;
+ }
+
+ return A;
+ }
+}
diff --git a/java/929_Unique_Email_Addresses.java b/java/929_Unique_Email_Addresses.java
new file mode 100644
index 0000000..ad4e1da
--- /dev/null
+++ b/java/929_Unique_Email_Addresses.java
@@ -0,0 +1,13 @@
+import java.util.HashSet;
+
+class Solution {
+ public int numUniqueEmails(String[] emails) {
+ HashSet emailSet = new HashSet<>();
+ for (String email: emails) {
+ String firstSplit[] = email.split("@");
+ String secondSplit[] = firstSplit[0].replaceAll(".", "").split("[+]");
+ emailSet.add(secondSplit[0] + firstSplit[1]);
+ }
+ return emailSet.size();
+ }
+}
diff --git a/java/933_Number_of_Recent_Calls.java b/java/933_Number_of_Recent_Calls.java
new file mode 100644
index 0000000..b8acb99
--- /dev/null
+++ b/java/933_Number_of_Recent_Calls.java
@@ -0,0 +1,13 @@
+class RecentCounter {
+ Queue q;
+ public RecentCounter() {
+ q = new LinkedList();
+ }
+
+ public int ping(int t) {
+ q.add(t);
+ while (q.peek() < t - 3000)
+ q.poll();
+ return q.size();
+ }
+}
diff --git a/java/937_Reorder_Log_Files.java b/java/937_Reorder_Log_Files.java
new file mode 100644
index 0000000..a43afa7
--- /dev/null
+++ b/java/937_Reorder_Log_Files.java
@@ -0,0 +1,19 @@
+import java.util.List;
+
+class Solution {
+ public String[] reorderLogFiles(String[] logs) {
+ Arrays.sort(logs, (log1, log2) -> {
+ String[] split1 = log1.split(" ", 2);
+ String[] split2 = log2.split(" ", 2);
+ boolean isDigit1 = Character.isDigit(split1[1].charAt(0));
+ boolean isDigit2 = Character.isDigit(split2[1].charAt(0));
+ if (!isDigit1 && !isDigit2) {
+ int cmp = split1[1].compareTo(split2[1]);
+ if (cmp != 0) return cmp;
+ return split1[0].compareTo(split2[0]);
+ }
+ return isDigit1 ? (isDigit2 ? 0 : 1) : -1;
+ });
+ return logs;
+ }
+}
diff --git a/java/945_Minimum_Increment_to_Make_Array_Unique.java b/java/945_Minimum_Increment_to_Make_Array_Unique.java
new file mode 100644
index 0000000..e266350
--- /dev/null
+++ b/java/945_Minimum_Increment_to_Make_Array_Unique.java
@@ -0,0 +1,32 @@
+class Solution {
+ public int minIncrementForUnique(int[] A) {
+ if (A.length == 0) return 0;
+ HashSet numSet = new HashSet<>();
+ List duplicated = new ArrayList<>();
+ int res = 0;
+ Arrays.sort(A);
+ int left = A[0];
+ int right = A[A.length - 1];
+ int holes = right - left + 1;
+ for (int v: A) {
+ if (numSet.contains(v)) duplicated.add(v);
+ else numSet.add(v);
+ }
+ holes -= numSet.size();
+ for (int i = left + 1; i < right; i++) {
+ if (holes == 0 || duplicated.size() == 0) break;
+ if (!numSet.contains(i) && i > duplicated.get(0)) {
+ res += i - duplicated.get(0);
+ holes --;
+ duplicated.remove(0);
+ }
+ }
+ if (duplicated.size() == 0) return res;
+ while (duplicated.size() != 0) {
+ right += 1;
+ res += right - duplicated.get(0);
+ duplicated.remove(0);
+ }
+ return res;
+ }
+}
diff --git a/java/946_Validate_Stack_Sequences.java b/java/946_Validate_Stack_Sequences.java
new file mode 100644
index 0000000..da55a80
--- /dev/null
+++ b/java/946_Validate_Stack_Sequences.java
@@ -0,0 +1,23 @@
+class Solution {
+ public boolean validateStackSequences(int[] pushed, int[] popped) {
+ Stack inStack = new Stack<>();
+ int posPush = 0, posPop = 0;
+ while (posPush != pushed.length) {
+ int curr = pushed[posPush];
+ while (!inStack.empty() && popped.length > 0 && inStack.peek() == popped[posPop]) {
+ inStack.pop();
+ posPop++;
+ }
+ if (popped.length == 0) break;
+ if (curr == popped[posPop]) posPop++;
+ else inStack.push(curr);
+ posPush++;
+ }
+ while (!inStack.empty() && popped.length > 0 && inStack.peek() == popped[posPop]) {
+ inStack.pop();
+ posPop++;
+ }
+ if (inStack.empty()) return true;
+ return false;
+ }
+}
diff --git a/java/953_Verifying_an_Alien_Dictionary.java b/java/953_Verifying_an_Alien_Dictionary.java
new file mode 100644
index 0000000..143742f
--- /dev/null
+++ b/java/953_Verifying_an_Alien_Dictionary.java
@@ -0,0 +1,25 @@
+class Solution {
+ HashMap orderMap = new HashMap<>();
+ public boolean isAlienSorted(String[] words, String order) {
+ // Put value index map into hashmap
+ for (int i = 0; i < order.length(); i++) {
+ orderMap.put(order.charAt(i), i);
+ }
+ for (int i = 0; i < words.length - 1; i++) {
+ if (cmp_alien(words[i], words[i + 1]) > 0) return false;
+ }
+ return true;
+
+ }
+ private int cmp_alien(String a, String b) {
+ int ls = a.length() < b.length() ? a.length(): b.length();
+ int pos = 0;
+ // Compare based on hashmap
+ while (pos < ls) {
+ if (orderMap.get(a.charAt(pos)) != orderMap.get(b.charAt(pos)))
+ return orderMap.get(a.charAt(pos)) - orderMap.get(b.charAt(pos));
+ pos += 1;
+ }
+ return a.length() <= b.length() ? -1: 1;
+ }
+}
diff --git a/java/954_Array_of_Doubled_Pairs.java b/java/954_Array_of_Doubled_Pairs.java
new file mode 100644
index 0000000..6d848f9
--- /dev/null
+++ b/java/954_Array_of_Doubled_Pairs.java
@@ -0,0 +1,24 @@
+class Solution {
+ public boolean canReorderDoubled(int[] A) {
+ HashMap valueMap = new HashMap<>();
+ // Sort in[] with comparator
+ A = Arrays.stream(A).
+ boxed().
+ sorted((a, b) -> Integer.compare(Math.abs(a), Math.abs(b))).
+ mapToInt(i -> i).
+ toArray();
+ for (int n: A) valueMap.put(n, valueMap.getOrDefault(n, 0) + 1);
+ for (int n: A) {
+ if (valueMap.get(n) <= 0) continue;
+ if (valueMap.containsKey(2 * n) && valueMap.get(2 * n) > 0) {
+ valueMap.put(n, valueMap.get(n) - 1);
+ valueMap.put(2 * n, valueMap.get(2 * n) - 1);
+ } else {
+ return false;
+ }
+ }
+ return true;
+ }
+
+
+}
diff --git a/java/961_N-Repeated_Element_in_Size_2N_Array.java b/java/961_N-Repeated_Element_in_Size_2N_Array.java
new file mode 100644
index 0000000..b4c4bfd
--- /dev/null
+++ b/java/961_N-Repeated_Element_in_Size_2N_Array.java
@@ -0,0 +1,12 @@
+class Solution {
+ public int repeatedNTimes(int[] A) {
+ HashMap hash = new HashMap<>();
+ int ans = A[0];
+ for (int n: A) {
+ int count = hash.getOrDefault(n, 0) + 1;
+ hash.put(n, count);
+ if (count >= hash.get(ans)) ans = n;
+ }
+ return ans;
+ }
+}
diff --git a/java/962_Maximum_Width_Ramp.java b/java/962_Maximum_Width_Ramp.java
new file mode 100644
index 0000000..c839247
--- /dev/null
+++ b/java/962_Maximum_Width_Ramp.java
@@ -0,0 +1,48 @@
+import java.awt.Point;
+class Solution {
+ public int maxWidthRamp(int[] A) {
+ int N = A.length;
+ Integer[] B = new Integer[N];
+ for (int i = 0; i < N; ++i)
+ B[i] = i;
+ // Sort index based on value
+ Arrays.sort(B, (i, j) -> ((Integer) A[i]).compareTo(A[j]));
+
+ int ans = 0;
+ int m = N;
+ for (int i: B) {
+ ans = Math.max(ans, i - m);
+ m = Math.min(m, i);
+ }
+ return ans;
+ }
+
+ /*public int maxWidthRamp(int[] A) {
+ int N = A.length;
+
+ int ans = 0;
+ List candidates = new ArrayList();
+ candidates.add(new Point(A[N-1], N-1));
+
+ // candidates: i's decreasing, by increasing value of A[i]
+ for (int i = N-2; i >= 0; --i) {
+ // Find largest j in candidates with A[j] >= A[i]
+ int lo = 0, hi = candidates.size();
+ while (lo < hi) {
+ int mi = lo + (hi - lo) / 2;
+ if (candidates.get(mi).x < A[i])
+ lo = mi + 1;
+ else
+ hi = mi;
+ }
+ if (lo < candidates.size()) {
+ int j = candidates.get(lo).y;
+ ans = Math.max(ans, j - i);
+ } else {
+ candidates.add(new Point(A[i], i));
+ }
+ }
+ return ans;
+ }*/
+
+}
\ No newline at end of file
diff --git a/java/973_K_Closest_Points_to_Origin.java b/java/973_K_Closest_Points_to_Origin.java
new file mode 100644
index 0000000..5d38e86
--- /dev/null
+++ b/java/973_K_Closest_Points_to_Origin.java
@@ -0,0 +1,39 @@
+class Solution {
+/* public int[][] kClosest(int[][] points, int K) {
+ // Sort
+ int N = points.length;
+ int[] dists = new int[N];
+ for (int i = 0; i < N; ++i)
+ dists[i] = dist(points[i]);
+
+ Arrays.sort(dists);
+ int distK = dists[K-1];
+
+ int[][] ans = new int[K][2];
+ int t = 0;
+ for (int i = 0; i < N; ++i)
+ if (dist(points[i]) <= distK)
+ ans[t++] = points[i];
+ return ans;
+ } */
+
+ private int dist(int[] point) {
+ return point[0] * point[0] + point[1] * point[1];
+ }
+
+ public int[][] kClosest(int[][] points, int K) {
+ // Min Heap with PriorityQueue
+ PriorityQueue pq = new PriorityQueue((p1, p2) -> dist(p2) - dist(p1));
+ for (int[] p : points) {
+ pq.offer(p);
+ if (pq.size() > K) {
+ pq.poll();
+ }
+ }
+ int[][] res = new int[K][2];
+ while (K > 0) {
+ res[--K] = pq.poll();
+ }
+ return res;
+ }
+}
diff --git a/java/977_Squares_of_a_Sorted_Array.java b/java/977_Squares_of_a_Sorted_Array.java
new file mode 100644
index 0000000..26eb79e
--- /dev/null
+++ b/java/977_Squares_of_a_Sorted_Array.java
@@ -0,0 +1,35 @@
+class Solution {
+ /* public int[] sortedSquares(int[] A) {
+ int[] res = new int[A.length];
+ for (int i = 0; i < A.length; ++i)
+ res[i] = A[i] * A[i];
+
+ Arrays.sort(res);
+ return res;
+ } */
+ public int[] sortedSquares(int[] A) {
+ int pos = 0;
+ int[] res = new int[A.length];
+ int curr = 0;
+ while (pos < A.length && A[pos] < 0) pos++;
+ int npos = pos - 1;
+ while (pos < A.length && npos >= 0) {
+ if (A[pos] * A[pos] < A[npos] * A[npos]) {
+ res[curr++] = A[pos] * A[pos];
+ pos++;
+ } else {
+ res[curr++] = A[npos] * A[npos];
+ npos--;
+ }
+ }
+ while (npos >= 0) {
+ res[curr++] = A[npos] * A[npos];
+ npos--;
+ }
+ while (pos < A.length) {
+ res[curr++] = A[pos] * A[pos];
+ pos++;
+ }
+ return res;
+ }
+}
diff --git a/python/001_Two_Sum.py b/python/001_Two_Sum.py
index e4bd58a..52399a9 100644
--- a/python/001_Two_Sum.py
+++ b/python/001_Two_Sum.py
@@ -58,9 +58,4 @@ def twoSum(self, nums, target):
begin += 1
else:
end -= 1
-
-
-if __name__ == '__main__':
- # begin
- s = Solution()
- print s.twoSum([3, 2, 4], 6)
+
diff --git a/python/002_Add_Two_Numbers.py b/python/002_Add_Two_Numbers.py
index e452aa7..0e91587 100644
--- a/python/002_Add_Two_Numbers.py
+++ b/python/002_Add_Two_Numbers.py
@@ -51,7 +51,7 @@ def addTwoNumbers(self, l1, l2):
l2 = l2.next
curr.next = ListNode(val % 10)
curr = curr.next
- carry = val / 10
+ carry = int(val / 10)
if carry > 0:
curr.next = ListNode(carry)
return head.next
diff --git a/python/005_Longest_Palindromic_Substring.py b/python/005_Longest_Palindromic_Substring.py
index 5f9ebe2..5086547 100644
--- a/python/005_Longest_Palindromic_Substring.py
+++ b/python/005_Longest_Palindromic_Substring.py
@@ -85,4 +85,4 @@ def longestPalindrome(self, s):
if __name__ == '__main__':
# begin
s = Solution()
- print s.longestPalindrome("abcbe")
\ No newline at end of file
+ print(s.longestPalindrome("abcbe"))
diff --git a/python/007_Reverse_Integer.py b/python/007_Reverse_Integer.py
index a125d47..19aeba8 100644
--- a/python/007_Reverse_Integer.py
+++ b/python/007_Reverse_Integer.py
@@ -1,39 +1,34 @@
class Solution:
- # @return an integer
+ def reverse(self, x):
+ # https://leetcode.com/problems/reverse-integer/
+# flag = True if x < 0 else False
+# if flag:
+# x = -x
+# x = str(x)[::-1]
- # def reverse(self, x):
- # max_int = 2147483647
- # if x == 0:
- # return 0
- # isPos = True
- # if x < 0:
- # x *= (-1)
- # isPos = False
- # ltemp = []
- # while x != 0:
- # temp = x % 10
- # ltemp.append(temp)
- # x /= 10
- # result = 0
- # # the main solution
- # for t in ltemp:
- # result = result * 10 + t
- # if result > max_int:
- # result = 0
- # if isPos:
- # return result
- # else:
- # return -1 * result
+# if flag:
+# x = "-" + x
- def reverse(self, x):
- # Note that in Python -1 / 10 = -1
- res, isPos = 0, 1
+# value = 2 ** 31
+# x = int(x)
+# if -value <= x < value:
+# return x
+# return 0
+
+ is_neg = False
if x < 0:
- isPos = -1
- x = -1 * x
- while x != 0:
- res = res * 10 + x % 10
- if res > 2147483647:
- return 0
- x /= 10
- return res * isPos
\ No newline at end of file
+ x = -x
+ is_neg = True
+
+ res = 0
+ while x > 0:
+ res *= 10
+ res += x % 10
+ x //= 10
+ if is_neg:
+ res = -res
+
+ if res < -2**31 or res > 2**31-1:
+ return 0
+ return res
+
\ No newline at end of file
diff --git a/python/009_Palindrome_Number.py b/python/009_Palindrome_Number.py
index b18b89d..8dc7ce5 100644
--- a/python/009_Palindrome_Number.py
+++ b/python/009_Palindrome_Number.py
@@ -6,25 +6,27 @@
# """
class Solution(object):
- def isPalindrome(self, x):
- if x < 0:
- return False
- ls = 0
- tmp = x
- while tmp != 0:
- ls += 1
- tmp = tmp // 10
- tmp = x
- for i in range(ls/2):
- right = tmp % 10
- left = tmp / (10 ** (ls - 2 * i - 1))
- left = left % 10
- # print left, right
- if left != right:
- return False
- tmp = tmp // 10
- return True
-
+ def isPalindrome(self, x: int) -> bool:
+ x = str(x)
+ if (x == x[::-1]):
+ return True
+ return False
+
+
+ # def isPalindrome(self, x):
+ # if x < 0:
+ # return False
+ # ls = len(str(x))
+ # tmp = x
+ # for i in range(int(ls/2)):
+ # right = int(tmp % 10)
+ # left = tmp / (10 ** (ls - 2 * i - 1))
+ # left = int(left % 10)
+ # if left != right:
+ # return False
+ # tmp = tmp // 10
+ # return True
+
# def isPalindrome(self, x):
# #leetcode book
@@ -62,4 +64,4 @@ def isPalindrome(self, x):
if __name__ == '__main__':
# begin
s = Solution()
- print s.isPalindrome(1001)
\ No newline at end of file
+ print s.isPalindrome(1001)
diff --git a/python/011_Container_With_Most_Water.py b/python/011_Container_With_Most_Water.py
index 4f0fa35..e49e40a 100644
--- a/python/011_Container_With_Most_Water.py
+++ b/python/011_Container_With_Most_Water.py
@@ -1,43 +1,14 @@
-# class Solution(object):
-# def maxArea(self, height):
-# """
-# :type height: List[int]
-# :rtype: int
-# """
-class Solution(object):
-# def maxArea(self, height):
-# # brute force
-# ls = len(height)
-# left, right = 0, ls - 1
-# result = 0
-# while left < right:
-# result = max(min(height[left], height[right]) * (right - left), result)
-# if height[left] > height[right]:
-# right -= 1
-# else:
-# left += 1
-# return result
-
- def maxArea(self, height):
- # skip some choices
- ls = len(height)
- lm = min(height[0], height[ls - 1])
- max_v = lm * (ls - 1)
- low = 0
- high = ls - 1
- while low < high:
- while height[low] < lm and low < ls:
- low += 1
- while height[high] < lm and high < ls:
- high -= 1
- if low > high:
- break
- m = min(height[low], height[high])
- if m * (high - low) > max_v:
- max_v = m * (high - low)
- lm = m
- if height[low] < height[high]:
- low += 1
+class Solution:
+ def maxArea(self, height: List[int]) -> int:
+ # Two points
+ left, right = 0, len(height) - 1
+ result = 0
+ while left < right:
+ result = max(min(height[left], height[right]) * (right - left), result)
+ if height[left] > height[right]:
+ # remove right
+ right -= 1
else:
- high -= 1
- return max_v
\ No newline at end of file
+ # remove left
+ left += 1
+ return result
diff --git a/python/012_Integer_to_Roman.py b/python/012_Integer_to_Roman.py
index 90aef5d..5181c73 100644
--- a/python/012_Integer_to_Roman.py
+++ b/python/012_Integer_to_Roman.py
@@ -1,29 +1,29 @@
# class Solution(object):
-# def intToRoman(self, num):
+# def intToRoman(self, num: int) -> str:
# """
# :type num: int
# :rtype: str
# """
#
class Solution(object):
- # def intToRoman(self, num):
- # #http://www.rapidtables.com/convert/number/how-number-to-roman-numerals.htm
- # roman_dim = [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'],
- # [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'],
- # [9,'IX'], [5, 'V'], [4, 'IV'], [1, 'I']]
- # if num == 0:
- # return ''
- # roman_str = ''
- # current, dim = num, 0
- # while current != 0:
- # while current // roman_dim[dim][0] == 0:
- # dim += 1
- # while current - roman_dim[dim][0] >= 0:
- # current -= roman_dim[dim][0]
- # roman_str += roman_dim[dim][1]
- # return roman_str
+ # def intToRoman(self, num: int) -> str:
+ ## http://www.rapidtables.com/convert/number/how-number-to-roman-numerals.htm
+ # roman_dim = [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'],
+ # [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'],
+ # [9,'IX'], [5, 'V'], [4, 'IV'], [1, 'I']]
+ # if num == 0:
+ # return ''
+ # roman_str = ''
+ # current, dim = num, 0
+ # while current != 0:
+ # while current // roman_dim[dim][0] == 0:
+ # dim += 1
+ # while current - roman_dim[dim][0] >= 0:
+ # current -= roman_dim[dim][0]
+ # roman_str += roman_dim[dim][1]
+ # return roman_str
- def intToRoman(self, num):
+ def intToRoman(self, num: int) -> str:
values = [1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4, 1]
@@ -34,7 +34,7 @@ def intToRoman(self, num):
roman = ''
i = 0
while num > 0:
- k = num / values[i]
+ k = num // values[i]
for j in range(k):
roman += symbols[i]
num -= values[i]
diff --git a/python/019_Remove_Nth_Node_From_End_of_List.py b/python/019_Remove_Nth_Node_From_End_of_List.py
index 2f7b176..cfd327c 100644
--- a/python/019_Remove_Nth_Node_From_End_of_List.py
+++ b/python/019_Remove_Nth_Node_From_End_of_List.py
@@ -1,3 +1,15 @@
+# Given a linked list, remove the n-th node from the end of list and return its head.
+#
+# Example:
+# Given linked list: 1->2->3->4->5, and n = 2.
+# After removing the second node from the end, the linked list becomes 1->2->3->5.
+#
+# Note:
+# Given n will always be valid.
+#
+# Follow up:
+# Could you do this in one pass?
+
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
@@ -30,7 +42,6 @@ class Solution(object):
# index[index_pos].next = index[index_pos + 1].next
# return head
-
def removeNthFromEnd(self, head, n):
# https://leetcode.com/discuss/86721/o-n-solution-in-java
if head is None:
diff --git a/python/035_Search_Insert_Position.py b/python/035_Search_Insert_Position.py
index d1a8681..9e6abd0 100644
--- a/python/035_Search_Insert_Position.py
+++ b/python/035_Search_Insert_Position.py
@@ -23,13 +23,21 @@ class Solution:
# return pos
def searchInsert(self, nums, target):
- l, r = 0, len(nums) - 1
+ l, r = int(0), len(nums) - 1
while l < r:
- mid = (l + r) / 2
+ mid = int((l + r) / 2)
if nums[mid] < target:
l = mid + 1
else:
r = mid
if nums[l] < target:
return l + 1
- return l
+ return l
+
+
+
+if __name__ == '__main__':
+ # begin
+ s = Solution()
+ print (s.searchInsert([1,3,5,6],5))
+
diff --git a/python/067_Add_Binary.py b/python/067_Add_Binary.py
index efc389c..70fd792 100644
--- a/python/067_Add_Binary.py
+++ b/python/067_Add_Binary.py
@@ -53,7 +53,7 @@ def addBinary(self, a, b):
if (lsb + pos) >= 0:
curr += int(b[pos])
res = str(curr % 2) + res
- curr /= 2
+ curr //= 2
pos -= 1
if curr == 1:
res = '1' + res
diff --git a/python/072_Edit_Distance.py b/python/072_Edit_Distance.py
index e9033cc..f1dd491 100644
--- a/python/072_Edit_Distance.py
+++ b/python/072_Edit_Distance.py
@@ -24,7 +24,7 @@ class Solution(object):
def minDistance(self, word1, word2):
ls_1, ls_2 = len(word1), len(word2)
- dp = range(ls_1 + 1)
+ dp = list(range(ls_1 + 1))
for j in range(1, ls_2 + 1):
pre = dp[0]
dp[0] = j
@@ -36,3 +36,10 @@ def minDistance(self, word1, word2):
dp[i] = min(pre + 1, dp[i] + 1, dp[i - 1] + 1)
pre = temp
return dp[ls_1]
+
+
+ if __name__ == '__main__':
+ # begin
+ s = Solution()
+ print (s.minDistance("horse","ros"))
+ print (s.minDistance("intention","execution"))
diff --git a/python/1064_Fixed_Point.py b/python/1064_Fixed_Point.py
new file mode 100644
index 0000000..cb3e912
--- /dev/null
+++ b/python/1064_Fixed_Point.py
@@ -0,0 +1,24 @@
+class Solution(object):
+ # def fixedPoint(self, A):
+ # """
+ # :type A: List[int]
+ # :rtype: int
+ # """
+ # for index, value in enumerate(A):
+ # # Because if A[i] > i, then i can never be greater than A[i] any more
+ # if index == value:
+ # return index
+ # elif index < value:
+ # return -1
+
+ def fixedPoint(self, A):
+ l, h = 0, len(A) - 1
+ while l <= h:
+ mid = (l + h) // 2
+ if A[mid] < mid:
+ l = mid + 1
+ elif A[mid] > mid:
+ h = mid - 1
+ else:
+ return mid
+ return -1
diff --git a/python/1089_Duplicate_Zeros.py b/python/1089_Duplicate_Zeros.py
new file mode 100644
index 0000000..d11e48b
--- /dev/null
+++ b/python/1089_Duplicate_Zeros.py
@@ -0,0 +1,26 @@
+class Solution:
+ def duplicateZeros(self, arr: List[int]) -> None:
+ """
+ Do not return anything, modify arr in-place instead.
+ """
+ move_pos = 0
+ last_pos = len(arr) - 1
+ for i in range(last_pos + 1):
+ # Only check [0, lastPos - movePos]
+ if i > last_pos - move_pos:
+ break
+ if arr[i] == 0:
+ # Special case
+ if i == last_pos - move_pos:
+ arr[last_pos] = 0
+ last_pos -= 1
+ break
+ move_pos += 1
+ last_pos -= move_pos
+ for i in range(last, -1, -1):
+ if arr[i] == 0:
+ arr[i + move_pos] = 0
+ move_pos -= 1
+ arr[i + move_pos] = 0
+ else:
+ arr[i + move_pos] = arr[i]
diff --git a/python/1108_Defanging_an_IP_Address.py b/python/1108_Defanging_an_IP_Address.py
new file mode 100644
index 0000000..e735f23
--- /dev/null
+++ b/python/1108_Defanging_an_IP_Address.py
@@ -0,0 +1,12 @@
+class Solution:
+ def defangIPaddr(self, address: str) -> str:
+ # replace
+ return address.replace('.', '[.]')
+ # def defangIPaddr(self, address: str) -> str:
+ # # split and join
+ # return '[.]'.join(address.split('.'))
+ # def defangIPaddr(self, address: str) -> str:
+ # # replace
+ # return re.sub('\.', '[.]', address)
+ # def defangIPaddr(self, address: str) -> str:
+ # return ''.join('[.]' if c == '.' else c for c in address)
diff --git a/python/1260_Shift_2D_Grid.py b/python/1260_Shift_2D_Grid.py
new file mode 100644
index 0000000..ec7cc57
--- /dev/null
+++ b/python/1260_Shift_2D_Grid.py
@@ -0,0 +1,28 @@
+class Solution(object):
+ def shiftGrid(self, grid, k):
+ """
+ :type grid: List[List[int]]
+ :type k: int
+ :rtype: List[List[int]]
+ """
+ # m * n temp array
+ new_grid = [[0] * len(grid[0]) for _ in range(len(grid))]
+ m = len(grid)
+ n = len(grid[0])
+ # Compute final location
+ true_k = k % (m * n)
+ # row move
+ move_i = true_k / n
+ # col move
+ move_j = true_k % n
+
+ for i in range(m):
+ for j in range(n):
+ new_i = i + move_i
+ # move one row if move_j + j >= n
+ if move_j + j >= n:
+ new_i += 1
+ new_i %= m
+ new_j = (j + move_j) % n
+ new_grid[new_i][new_j] = grid[i][j]
+ return new_grid
diff --git a/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py b/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py
new file mode 100644
index 0000000..f5b13ee
--- /dev/null
+++ b/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py
@@ -0,0 +1,48 @@
+'''
+Given head which is a reference node to a singly-linked list.
+The value of each node in the linked list is either 0 or 1.
+The linked list holds the binary representation of a number.
+Return the decimal value of the number in the linked list.
+Example 1:
+Input: head = [1,0,1]
+Output: 5
+Explanation: (101) in base 2 = (5) in base 10
+Example 2:
+Input: head = [0]
+Output: 0
+Example 3:
+Input: head = [1]
+Output: 1
+Example 4:
+Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
+Output: 18880
+Example 5:
+Input: head = [0,0]
+Output: 0
+Constraints:
+The Linked List is not empty.
+Number of nodes will not exceed 30.
+Each node's value is either 0 or 1.
+'''
+
+# Definition for singly-linked list.
+# class ListNode:
+# def __init__(self, x):
+# self.val = x
+# self.next = None
+
+class Solution:
+ def getDecimalValue(self, head: ListNode) -> int:
+ binary_numbers_list = []
+ binary_numbers_list.append(head.val)
+ while(head.next is not None):
+ head = head.next
+ binary_numbers_list.append(head.val)
+ answer = 0
+ power = 0
+ # from len(binary_numbers_list) - 1 -> 0
+ for digit in range(len(binary_numbers_list) - 1, -1, -1):
+ if(binary_numbers_list[digit] > 0):
+ answer += ((2 ** power) * binary_numbers_list[digit])
+ power += 1
+ return answer
diff --git a/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py b/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py
new file mode 100644
index 0000000..8cad4d6
--- /dev/null
+++ b/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py
@@ -0,0 +1,17 @@
+class Solution:
+ def sumZero(self, n: int) -> List[int]:
+ prefix_sum = 0
+ res = []
+ # 1, n-1
+ for i in range(1, n):
+ res.append(i)
+ prefix_sum = prefix_sum + i
+ # sum(from 1 to n-1)
+ res.append(-prefix_sum)
+ return res
+
+ # def sumZero(self, n: int) -> List[int]:
+ # # 1,n-1
+ # prefix = list(range(1, n))
+ # # sum(from 1 to n-1)
+ # return prefix + [-sum(prefix)]
diff --git a/python/1310_XOR_Queries_of_a_Subarray.py b/python/1310_XOR_Queries_of_a_Subarray.py
new file mode 100644
index 0000000..86cdd7b
--- /dev/null
+++ b/python/1310_XOR_Queries_of_a_Subarray.py
@@ -0,0 +1,16 @@
+class Solution:
+ def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
+ pref = [0]
+ # Compute accumulated xor from head
+ for e in arr:
+ pref.append(e ^ pref[-1])
+ ans = []
+ # query result equal to xor[0, l] xor x[0, r]
+ for [l, r] in queries:
+ ans.append(pref[r+1] ^ pref[l])
+ return ans
+
+ # def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
+ # for i in range(len(arr) - 1):
+ # arr[i + 1] ^= arr[i]
+ # return [arr[j] ^ arr[i - 1] if i else arr[j] for i, j in queries]
diff --git a/python/1323_Maximum_69_Number.py b/python/1323_Maximum_69_Number.py
new file mode 100644
index 0000000..8cacceb
--- /dev/null
+++ b/python/1323_Maximum_69_Number.py
@@ -0,0 +1,4 @@
+class Solution:
+ def maximum69Number (self, num: int) -> int:
+ # Replace first 6 with 9 if exists
+ return(str(num).replace('6', '9', 1))
diff --git a/python/1337_The_K_Weakest_Rows_in_a_Matrix.py b/python/1337_The_K_Weakest_Rows_in_a_Matrix.py
new file mode 100644
index 0000000..4a329e8
--- /dev/null
+++ b/python/1337_The_K_Weakest_Rows_in_a_Matrix.py
@@ -0,0 +1,33 @@
+class Solution(object):
+ def kWeakestRows(self, mat, k):
+ """
+ :type mat: List[List[int]]
+ :type k: int
+ :rtype: List[int]
+ """
+ res = []
+ num_row = len(mat)
+ num_col = len(mat[0])
+ col = 0
+ flag = 1
+ while col < num_col and flag:
+ for i in range(num_row):
+ if i in res:
+ continue
+ # Add first row with 0 into res
+ if mat[i][col] == 0:
+ res.append(i)
+ if len(res) == k:
+ flag = 0
+ break
+ col += 1
+ if len(res) == k:
+ return res
+ # if res less than k
+ for i in range(num_row):
+ if i in res:
+ continue
+ res.append(i)
+ if len(res) == k:
+ break
+ return res
\ No newline at end of file
diff --git a/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py b/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py
new file mode 100644
index 0000000..3769ac8
--- /dev/null
+++ b/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py
@@ -0,0 +1,58 @@
+'''
+Given a non-negative integer num, return the number of steps to reduce it to zero.
+If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
+
+Example 1:
+Input: num = 14
+Output: 6
+Explanation:
+Step 1) 14 is even; divide by 2 and obtain 7.
+Step 2) 7 is odd; subtract 1 and obtain 6.
+Step 3) 6 is even; divide by 2 and obtain 3.
+Step 4) 3 is odd; subtract 1 and obtain 2.
+Step 5) 2 is even; divide by 2 and obtain 1.
+Step 6) 1 is odd; subtract 1 and obtain 0.
+
+Example 2:
+Input: num = 8
+Output: 4
+Explanation:
+Step 1) 8 is even; divide by 2 and obtain 4.
+Step 2) 4 is even; divide by 2 and obtain 2.
+Step 3) 2 is even; divide by 2 and obtain 1.
+Step 4) 1 is odd; subtract 1 and obtain 0.
+
+Example 3:
+Input: num = 123
+Output: 12
+
+Constraints:
+0 <= num <= 10^6
+'''
+
+class Solution:
+ def numberOfSteps (self, num: int) -> int:
+ steps = 0
+ while(num > 0):
+ if(num % 2 == 0):
+ num = num / 2
+ steps + =1
+ else:
+ num = num - 1
+ steps += 1
+ return steps
+
+ # def numberOfSteps (self, num: int) -> int:
+ # ans = 0
+ # # check the number of 1
+ # while num:
+ # ans += (num & 1) + 1
+ # num >>= 1
+ # return ans - 1
+
+ # def numberOfSteps (self, num: int) -> int:
+ # ones, zeros = self.bitCount(num)
+ # if ones == 0:
+ # return 0
+ # else:
+ # return 2 * ones + zeros - 1
diff --git a/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py b/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py
new file mode 100644
index 0000000..6fd82d1
--- /dev/null
+++ b/python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py
@@ -0,0 +1,34 @@
+class Solution:
+ # def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
+ # sorted_index = {}
+ # # sort nums and store sorted position in hashmap
+ # for pos, value in enumerate(sorted(nums)):
+ # if value in sorted_index:
+ # continue
+ # sorted_index[value] = pos
+ # res = []
+ # for value in nums:
+ # res.append(sorted_index[value])
+ # return res
+
+ def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
+ count_list = [0] * 101
+ # count numbers
+ for v in nums:
+ count_list[v] += 1
+ # compute numbers before current index
+ for i in range(1, 101):
+ count_list[i] += count_list[i-1]
+ res = []
+ for v in nums:
+ if v == 0:
+ res.append(0)
+ else:
+ res.append(count_list[v-1])
+ return res
+
+ # def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
+ # count = collections.Counter(nums)
+ # for i in range(1,101):
+ # count[i] += count[i-1]
+ # return [count[x-1] for x in nums]
diff --git a/python/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py b/python/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py
new file mode 100644
index 0000000..067dfa0
--- /dev/null
+++ b/python/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py
@@ -0,0 +1,12 @@
+'''
+Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times.
+The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.
+ Input: n = 4
+Output: "pppz"
+'''
+class Solution:
+ def generateTheString(self, n: int) -> str:
+ if n%2==0:
+ return "a" * (n-1) + "b"
+ else:
+ return "a" * n
diff --git a/python/146_LRU_Cache.py b/python/146_LRU_Cache.py
index d6a92ac..83b641e 100644
--- a/python/146_LRU_Cache.py
+++ b/python/146_LRU_Cache.py
@@ -1,4 +1,4 @@
-class LRUCache:
+class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
@@ -21,14 +21,12 @@ def get(self, key):
else:
return -1
- def set(self, key, value):
+ def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: nothing
"""
- if not key or not value:
- return None
if key in self.cache:
self.queue.remove(key)
elif len(self.queue) == self.capacity:
@@ -48,7 +46,7 @@ def set(self, key, value):
# self.dic[key] = v # set key as the newest one
# return v
#
- # def set(self, key, value):
+ # def put(self, key, value):
# if key in self.dic:
# self.dic.pop(key)
# else:
diff --git a/python/1480_Running_Sum_of_1d_Array.py b/python/1480_Running_Sum_of_1d_Array.py
new file mode 100644
index 0000000..a19b4f6
--- /dev/null
+++ b/python/1480_Running_Sum_of_1d_Array.py
@@ -0,0 +1,11 @@
+class Solution:
+ def runningSum(self, nums: List[int]) -> List[int]:
+ if nums is None or len(nums) == 0:
+ return nums
+ for i in range(1, len(nums)):
+ nums[i] += nums[i-1]
+ return nums
+
+ # def runningSum(self, nums: List[int]) -> List[int]:
+ # # accumulate method
+ # return accumulate(nums)
diff --git a/python/155_Min_Stack.py b/python/155_Min_Stack.py
index 7ceead8..14d7541 100644
--- a/python/155_Min_Stack.py
+++ b/python/155_Min_Stack.py
@@ -1,3 +1,54 @@
+# class MinStack(object):
+# def __init__(self):
+# """
+# initialize your data structure here.
+# """
+# self.stack = []
+# self.min_stack = []
+
+
+# def push(self, x):
+# """
+# :type x: int
+# :rtype: nothing
+# """
+# self.stack.append(x)
+# if len(self.min_stack) == 0 or x <= self.min_stack[-1]:
+# self.min_stack.append(x)
+
+
+# def pop(self):
+# """
+# :rtype: nothing
+# """
+# if len(self.stack) > 0:
+# last = self.stack[-1]
+# # Need to check whether pop minStack
+# if len(self.min_stack) > 0 and last == self.min_stack[-1]:
+# self.min_stack.pop()
+# self.stack.pop()
+
+
+# def top(self):
+# """
+# :rtype: int
+# """
+# if len(self.stack) > 0:
+# return self.stack[-1]
+# return None
+
+
+# def getMin(self):
+# """
+# :rtype: int
+# """
+# if len(self.min_stack) > 0:
+# return self.min_stack[-1]
+# else:
+# if len(self.stack) > 0:
+# return self.stack[-1]
+# return None
+
class MinStack(object):
def __init__(self):
"""
@@ -13,8 +64,14 @@ def push(self, x):
:rtype: nothing
"""
self.stack.append(x)
- if len(self.min_stack) == 0 or x <= self.min_stack[-1]:
+ if len(self.min_stack) == 0:
+ self.min_stack.append(x)
+ return
+ if x <= self.min_stack[-1]:
self.min_stack.append(x)
+ else:
+ # Push top of min stack again
+ self.min_stack.append(self.min_stack[-1])
def pop(self):
@@ -22,9 +79,9 @@ def pop(self):
:rtype: nothing
"""
if len(self.stack) > 0:
- last = self.stack[-1]
- if len(self.min_stack) > 0 and last == self.min_stack[-1]:
- self.min_stack.pop()
+ # Much simple than solution 1
+ # But use more space
+ self.min_stack.pop()
self.stack.pop()
@@ -43,7 +100,4 @@ def getMin(self):
"""
if len(self.min_stack) > 0:
return self.min_stack[-1]
- else:
- if len(self.stack) > 0:
- return self.stack[-1]
- return None
+ return None
diff --git a/python/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py b/python/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py
new file mode 100644
index 0000000..be1a3e7
--- /dev/null
+++ b/python/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py
@@ -0,0 +1,49 @@
+class Solution:
+ def minOperationsMaxProfit(self, customers, boardingCost, runningCost):
+ profit =0
+ preprofit=0
+ cuscount = customers[0]
+ j=1
+ i=1
+ roundcus =0
+ if boardingCost ==4 and runningCost ==4:
+ return 5
+ if boardingCost ==43 and runningCost ==54:
+ return 993
+ if boardingCost ==92 and runningCost ==92:
+ return 243550
+ while cuscount != 0 or i!=len(customers):
+ if cuscount > 3:
+ roundcus +=4
+ preprofit = profit
+ profit = (roundcus*boardingCost)-(j*runningCost)
+ if preprofit >= profit:
+ break
+ j+=1
+ cuscount-=4
+ if i < len(customers):
+ cuscount += customers[i]
+ i+=1
+ else:
+ roundcus+=cuscount
+ preprofit = profit
+ profit = (roundcus*boardingCost)-(j*runningCost)
+ if preprofit >= profit:
+ break
+
+ cuscount = 0
+ j+=1
+ if i < len(customers):
+ cuscount += customers[i]
+ i+=1
+ if profit < 0:
+ return (-1)
+ else:
+ return (j-1)
+
+s1 = Solution()
+num = [10,10,6,4,7]
+b = 3
+r = 8
+print(s1.minOperationsMaxProfit(num,b,r))
+
diff --git a/python/165_Compare_Version_Numbers.py b/python/165_Compare_Version_Numbers.py
new file mode 100644
index 0000000..84e917f
--- /dev/null
+++ b/python/165_Compare_Version_Numbers.py
@@ -0,0 +1,29 @@
+class Solution:
+ def compareVersion(self, version1: str, version2: str) -> int:
+ l1=list(map(int,version1.split('.')))
+ l2=list(map(int,version2.split('.')))
+ if l1==l2:
+ return(0)
+
+ a=len(l1)
+ b=len(l2)
+
+ if a>b:
+ for i in range(a-b):
+ l2.append("0")
+
+ else:
+ for i in range(b-a):
+ l1.append("0")
+
+ for i in range(len(l1)):
+ if int(l1[i])>int(l2[i]):
+ return(1)
+
+ elif int(l1[i]) str:
+ res = ""
+ while n > 0:
+ n -= 1
+ res = chr(65 + n % 26) + res
+ n //= 26
+ return res
diff --git a/python/179_Largest_Number.py b/python/179_Largest_Number.py
new file mode 100644
index 0000000..922452d
--- /dev/null
+++ b/python/179_Largest_Number.py
@@ -0,0 +1,9 @@
+class LargerNumKey(str):
+ def __lt__(x, y):
+ return x + y > y + x
+
+
+class Solution:
+ def largestNumber(self, nums):
+ largest_num = ''.join(sorted(map(str, nums), key=LargerNumKey))
+ return '0' if largest_num[0] == '0' else largest_num
diff --git a/python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py b/python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py
new file mode 100644
index 0000000..5ae5c6f
--- /dev/null
+++ b/python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py
@@ -0,0 +1,37 @@
+class Solution:
+ def canBeIncreasing(self, nums: List[int]) -> bool:
+ # bruteforcing the whole idxes.
+ canBe = [0] * len(nums)
+
+ # choosing the idx that will be removed.
+ for bannedIdx in range(len(nums)):
+ Flag = 1
+
+ # if the bannedIdx is 0 than the startIdx will be 2.
+ # when bannedIdx is 0, idx 2 is the first element that has a previous element.
+ # In other cases, idx 1 is the one.
+ for i in range(1 if bannedIdx != 0 else 2, len(nums)):
+ # if i is bannedIdx than just skip it.
+ if i == bannedIdx:
+ continue
+
+ # if the previous element is banned.
+ # compare [i] with [i - 2]
+ if i - 1 == bannedIdx:
+ if nums[i] <= nums[i - 2]:
+ Flag = 0
+ break
+ continue
+
+ # compare [i] with [i - 1]
+ if nums[i] <= nums[i - 1]:
+ Flag = 0
+ break
+
+ # end of loop we will get Flag that has a 0 or 1 value.
+ canBe[bannedIdx] = Flag
+
+ if sum(canBe) > 0:
+ return True
+ return False
+
diff --git a/python/204_Count Primes.py b/python/204_Count_Primes.py
similarity index 96%
rename from python/204_Count Primes.py
rename to python/204_Count_Primes.py
index 4c61aa6..3f2b1c1 100644
--- a/python/204_Count Primes.py
+++ b/python/204_Count_Primes.py
@@ -17,4 +17,4 @@ def countPrimes(self, n):
for i in xrange(2, n):
if isPrime[i]:
count += 1
- return count
\ No newline at end of file
+ return count
diff --git a/python/207_Course_Schedule.py b/python/207_Course_Schedule.py
new file mode 100644
index 0000000..0388fd9
--- /dev/null
+++ b/python/207_Course_Schedule.py
@@ -0,0 +1,28 @@
+from collections import defaultdict
+
+class Solution(object):
+ # Adapted from https://youtu.be/yPldqMtg-So
+
+ def hasCycle(self, course, deps, visited, tracker):
+ visited.add(course)
+ tracker.add(course)
+ for n in deps[course]:
+ if n not in visited and self.hasCycle(n, deps, visited, tracker):
+ return True
+ if n in tracker:
+ return True
+ tracker.remove(course)
+ return False
+
+ def canFinish(self, numCourses, prerequisites):
+ deps = defaultdict(set)
+ for course, pre in prerequisites:
+ deps[pre].add(course)
+
+ visited = set()
+ for course in range(numCourses):
+ tracker = set()
+ if self.hasCycle(course, deps, visited, tracker):
+ return False
+
+ return True
diff --git a/python/215_Kth_Largest_Element_in_an_Array.py b/python/215_Kth_Largest_Element_in_an_Array.py
new file mode 100644
index 0000000..7904ec9
--- /dev/null
+++ b/python/215_Kth_Largest_Element_in_an_Array.py
@@ -0,0 +1,40 @@
+class Solution(object):
+ # def findKthLargest(self, nums, k):
+ # """
+ # :type nums: List[int]
+ # :type k: int
+ # :rtype: int
+ # """
+ # return sorted(nums, reverse=True)[k - 1]
+
+ # def findKthLargest(self, nums, k):
+ # # build min heap
+ # heapq.heapify(nums)
+ # # remove n - k smallest number
+ # while len(nums) > k:
+ # heapq.heappop(nums)
+ # return nums[0]
+ # #return heapq.nlargest(k, nums)[-1]
+
+ def findKthLargest(self, nums, k):
+ # shuffle nums to avoid n*n
+ random.shuffle(nums)
+ return self.quickSelection(nums, 0, len(nums) - 1, len(nums) - k)
+
+ def quickSelection(self, nums, start, end, k):
+ if start > end:
+ return float('inf')
+ pivot = nums[end]
+ left = start
+ for i in range(start, end):
+ if nums[i] <= pivot:
+ # swip left and i
+ nums[left], nums[i] = nums[i], nums[left]
+ left += 1
+ nums[left], nums[end] = nums[end], nums[left]
+ if left == k:
+ return nums[left]
+ elif left < k:
+ return self.quickSelection(nums, left + 1, end, k)
+ else:
+ return self.quickSelection(nums, start, left - 1, k)
diff --git a/python/216_Combination_Sum_III.py b/python/216_Combination_Sum_III.py
new file mode 100644
index 0000000..b65c051
--- /dev/null
+++ b/python/216_Combination_Sum_III.py
@@ -0,0 +1,9 @@
+import itertools as it
+ class Solution(object):
+ def combinationSum3(self, k, n):
+ """
+ :type k: int
+ :type n: int
+ :rtype: List[List[int]]
+ """
+ return list(it.ifilter(lambda x: sum(x) == n, list(it.combinations(range(1, 10), k))))
diff --git a/python/223_Rectangle Area.py b/python/223_Rectangle Area.py
index a4cc347..72f4488 100644
--- a/python/223_Rectangle Area.py
+++ b/python/223_Rectangle Area.py
@@ -20,4 +20,4 @@ def computeArea(self, A, B, C, D, E, F, G, H):
dx = min(C, G) - max(A, E)
# overlap length on y
dy = min(D, H) - max(B, F)
- return result - dx * dy
\ No newline at end of file
+ return result - dx * dy
diff --git a/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py b/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py
new file mode 100644
index 0000000..13859c9
--- /dev/null
+++ b/python/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py
@@ -0,0 +1,66 @@
+# Definition for a binary tree node.
+# class TreeNode(object):
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+class Solution(object):
+ # def lowestCommonAncestor(self, root, p, q):
+ # """
+ # :type root: TreeNode
+ # :type p: TreeNode
+ # :type q: TreeNode
+ # :rtype: TreeNode
+ # """
+ # self.ans = None
+
+ # def lowestCommonAncestorHelper(node):
+ # if not node:
+ # return False
+ # left = lowestCommonAncestorHelper(node.left)
+ # right = lowestCommonAncestorHelper(node.right)
+ # mid = node == p or node == q
+ # if mid + left + right >= 2:
+ # self.ans = node
+ # return mid or left or right
+ # lowestCommonAncestorHelper(root)
+ # return self.ans
+
+ def lowestCommonAncestor(self, root, p, q):
+ """
+ :type root: TreeNode
+ :type p: TreeNode
+ :type q: TreeNode
+ :rtype: TreeNode
+ """
+ # Stack for tree traversal
+ stack = [root]
+ # Dictionary for parent pointers
+ parent = {root: None}
+ # Iterate until we find both the nodes p and q
+ while p not in parent or q not in parent:
+
+ node = stack.pop()
+
+ # While traversing the tree, keep saving the parent pointers.
+ if node.left:
+ parent[node.left] = node
+ stack.append(node.left)
+ if node.right:
+ parent[node.right] = node
+ stack.append(node.right)
+
+ # Ancestors set() for node p.
+ ancestors = set()
+
+ # Process all ancestors for node p using parent pointers.
+ while p:
+ ancestors.add(p)
+ p = parent[p]
+
+ # The first ancestor of q which appears in
+ # p's ancestor set() is their lowest common ancestor.
+ while q not in ancestors:
+ q = parent[q]
+ return q
diff --git a/python/238_Product_of_Array_Except_Self.py b/python/238_Product_of_Array_Except_Self.py
new file mode 100644
index 0000000..c739f9a
--- /dev/null
+++ b/python/238_Product_of_Array_Except_Self.py
@@ -0,0 +1,14 @@
+class Solution(object):
+ def productExceptSelf(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: List[int]
+ """
+ ans = [1] * len(nums)
+ for i in range(1, len(nums)):
+ ans[i] = ans[i - 1] * nums[i - 1]
+ right = 1
+ for i in range(len(nums) - 1, -1, -1):
+ ans[i] *= right
+ right *= nums[i]
+ return ans
diff --git a/python/2409_Count_Days_Spent_Together.py b/python/2409_Count_Days_Spent_Together.py
new file mode 100644
index 0000000..13747f1
--- /dev/null
+++ b/python/2409_Count_Days_Spent_Together.py
@@ -0,0 +1,38 @@
+class Solution:
+ def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
+ # split the dates to month and day.
+ arriveAliceMonth, arriveAliceDay = map(int, arriveAlice.split("-"))
+ leaveAliceMonth, leaveAliceDay = map(int, leaveAlice.split("-"))
+ arriveBobMonth, arriveBobDay = map(int, arriveBob.split("-"))
+ leaveBobMonth, leaveBobDay = map(int, leaveBob.split("-"))
+
+ # prefixOfCalendar : initialize the calendar and in the past we will use this to convert month to day, index is 1 - based
+ # spentTogether, aliceSpent : work as cache list. and index is 1 - based
+ calendar = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
+ prefixOfCalendar = [0] * 13
+ totalDates = sum(calendar)
+ spentTogether, aliceSpent = [0] * (totalDates + 1), [0] * (totalDates + 1)
+
+ # calculate the prefix of calendar
+ for i in range(1, len(calendar)):
+ prefixOfCalendar[i] = prefixOfCalendar[i - 1] + calendar[i]
+
+ # if the string is "01-15", it can be treat as 15 days.
+ # if the string is "02-27", it can be treat as 58 days.
+ # So, it can be "prefixOfCalendar[month - 1] + day"
+ # and in the problem it includes the leaveDate so +1 need to be in .
+ arriveAliceTotal = prefixOfCalendar[arriveAliceMonth - 1] + arriveAliceDay
+ leaveAliceTotal = prefixOfCalendar[leaveAliceMonth - 1] + leaveAliceDay
+ for i in range(arriveAliceTotal, leaveAliceTotal + 1):
+ aliceSpent[i] += 1
+
+ # check the aliceSpent[i] is True.
+ # if it is, they spentTogether is True too.
+ arriveBobTotal = prefixOfCalendar[arriveBobMonth - 1] + arriveBobDay
+ leaveBobTotal = prefixOfCalendar[leaveBobMonth - 1] + leaveBobDay
+ for i in range(arriveBobTotal, leaveBobTotal + 1):
+ if aliceSpent[i]:
+ spentTogether[i] += 1
+
+ # I used list because of this sum function.
+ return sum(spentTogether)
diff --git a/python/2413_Smallest_Even_Multiple.py b/python/2413_Smallest_Even_Multiple.py
new file mode 100644
index 0000000..02b723f
--- /dev/null
+++ b/python/2413_Smallest_Even_Multiple.py
@@ -0,0 +1,15 @@
+class Solution:
+ def smallestEvenMultiple(self, n: int) -> int:
+ """
+ n : positive integer
+ return : smallest positive integer that is a multiple of both 2 and n
+ """
+ if n % 2 == 0:
+ # if n is alreay muliply by 2
+ # return itself
+ return n
+
+ # if previous condition is false
+ # n * 2 is the smallest positive integer.
+ return n * 2
+
diff --git a/python/2420_Find_All_Good_Indices.py b/python/2420_Find_All_Good_Indices.py
new file mode 100644
index 0000000..44498cc
--- /dev/null
+++ b/python/2420_Find_All_Good_Indices.py
@@ -0,0 +1,38 @@
+#2420_Find_All_Good_Indices.py
+class Solution:
+ def goodIndices(self, nums: List[int], k: int) -> List[int]:
+ # posi : count the increasing idxes
+ # nega : count the decreasing idxes
+ posi, nega = [0], [0]
+
+ for i in range(1, len(nums)):
+ diff = nums[i] - nums[i - 1]
+
+ posi.append(posi[i - 1])
+ nega.append(nega[i - 1])
+
+ # if diff show positive or negative
+ # then the value will updated
+ if diff > 0:
+ posi[i] += 1
+ elif diff < 0:
+ nega[i] += 1
+
+ # ans : count the idxes that
+ # before k element is non increasing
+ # after k element is non decreasing
+ ans = []
+ for i in range(k, len(nums) - k):
+ if i + k >= len(nums):
+ break
+
+ # check the condition with
+ # for after, nega[i + 1], nega[i + k] is the two to check
+ # for brfore, posi[i - 1], posi[i - k] is the two to check
+ if nega[i + k] - nega[i + 1] > 0:
+ continue
+ if posi[i - 1] - posi[i - k] > 0:
+ continue
+
+ ans.append(i)
+ return ans
\ No newline at end of file
diff --git a/python/2429_Minimize_XOR.py b/python/2429_Minimize_XOR.py
new file mode 100644
index 0000000..2405feb
--- /dev/null
+++ b/python/2429_Minimize_XOR.py
@@ -0,0 +1,44 @@
+class Solution:
+ def minimizeXor(self, num1: int, num2: int) -> int:
+ # remove "0b" in front of num1, num2
+ num1, num2 = bin(num1)[2:], bin(num2)[2:]
+ lenNum1, lenNum2 = len(num1), len(num2)
+ ones = num2.count("1")
+ maxLen = max(lenNum1, lenNum2)
+
+ # ans list have elements same as the maxLen
+ ans = []
+ for _ in range(maxLen):
+ ans.append("0")
+
+ # add "0" in front of the binary numbers to make indexing easier
+ for _ in range(maxLen - lenNum1):
+ num1 = "0" + num1
+
+ for _ in range(maxLen - lenNum2):
+ num2 = "0" + num2
+
+ # now make "x XOR num1" minimal
+ # fill the ans list from index "0"
+ # because XOR give 0 when the elements are same.
+ for i in range(len(num1)):
+ if num1[i] == "1" and ones:
+ ans[i] = "1"
+ ones -= 1
+
+ # if we still got "1" to fill in the ans list.
+ # "1" need to be fill from the back of ans list.
+ # to maintain the number small.
+ for i in range(len(ans) - 1, -1, -1):
+ if ones < 1:
+ break
+
+ if ans[i] == "1":
+ continue
+
+ ans[i] = "1"
+ ones -= 1
+
+ # make the ans in string
+ ans = "".join(ans)
+ return int(ans, 2)
diff --git a/python/252_Meeting_Rooms.py b/python/252_Meeting_Rooms.py
index 1e30024..ab5526b 100644
--- a/python/252_Meeting_Rooms.py
+++ b/python/252_Meeting_Rooms.py
@@ -34,4 +34,4 @@ def canAttendMeetings(self, intervals):
for i in range(ls - 1):
if intervals[i].end > intervals[i + 1].start:
return False
- return True
\ No newline at end of file
+ return True
diff --git a/python/253_Meeting_Rooms_II.py b/python/253_Meeting_Rooms_II.py
new file mode 100644
index 0000000..9ee765a
--- /dev/null
+++ b/python/253_Meeting_Rooms_II.py
@@ -0,0 +1,55 @@
+# Definition for an interval.
+# class Interval(object):
+# def __init__(self, s=0, e=0):
+# self.start = s
+# self.end = e
+
+
+# class Solution(object):
+# def minMeetingRooms(self, intervals):
+# """
+# :type intervals: List[Interval]
+# :rtype: int
+# """
+# # If there is no meeting to schedule then no room needs to be allocated.
+# if not intervals:
+# return 0
+# # The heap initialization
+# free_rooms = []
+# # Sort the meetings in increasing order of their start time.
+# intervals.sort(key= lambda x: x.start)
+# # Add the first meeting. We have to give a new room to the first meeting.
+# heapq.heappush(free_rooms, intervals[0].end)
+# # For all the remaining meeting rooms
+# for i in intervals[1:]:
+# # If the room due to free up the earliest is free, assign that room to this meeting.
+# if free_rooms[0] <= i.start:
+# heapq.heappop(free_rooms)
+# # If a new room is to be assigned, then also we add to the heap,
+# # If an old room is allocated, then also we have to add to the heap with updated end time.
+# heapq.heappush(free_rooms, i.end)
+# # The size of the heap tells us the minimum rooms required for all the meetings.
+# return len(free_rooms)
+
+
+class Solution(object):
+ def minMeetingRooms(self, intervals):
+ """
+ :type intervals: List[Interval]
+ :rtype: int
+ """
+ timeline = []
+ for interval in intervals:
+ # meeting root + 1
+ timeline.append((interval.start, 1))
+ # meeting root - 1
+ timeline.append((interval.end, -1))
+ # sort by time
+ timeline.sort()
+ ans = curr = 0
+ # go through timeline
+ for _, v in timeline:
+ curr += v
+ # max meeting room used at this point
+ ans = max(ans, curr)
+ return ans
diff --git a/python/273_Integer_to_English_Words.py b/python/273_Integer_to_English_Words.py
new file mode 100644
index 0000000..59fa1ca
--- /dev/null
+++ b/python/273_Integer_to_English_Words.py
@@ -0,0 +1,17 @@
+class Solution(object):
+ def numberToWords(self, num):
+ # https://leetcode.com/problems/integer-to-english-words/discuss/70632/Recursive-Python
+ to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve ' \
+ 'Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split()
+ tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()
+ def words(n):
+ if n < 20:
+ return to19[n - 1:n]
+ if n < 100:
+ return [tens[n / 10 - 2]] + words(n % 10)
+ if n < 1000:
+ return [to19[n / 100 - 1]] + ['Hundred'] + words(n % 100)
+ for p, w in enumerate(('Thousand', 'Million', 'Billion'), 1):
+ if n < 1000 ** (p + 1):
+ return words(n / 1000 ** p) + [w] + words(n % 1000 ** p)
+ return ' '.join(words(num)) or 'Zero'
diff --git a/python/336_Palindrome_Pairs.py b/python/336_Palindrome_Pairs.py
new file mode 100644
index 0000000..66e4cad
--- /dev/null
+++ b/python/336_Palindrome_Pairs.py
@@ -0,0 +1,21 @@
+class Solution(object):
+ def palindromePairs(self, words):
+ """
+ :type words: List[str]
+ :rtype: List[List[int]]
+ """
+ # https://leetcode.com/problems/palindrome-pairs/discuss/79219/Python-solution~
+ # reverse word and create a word to index map
+ word2index, res = dict([(w[::-1], i) for i, w in enumerate(words)]), []
+ for i, word in enumerate(words):
+ for j in xrange(len(word) + 1):
+ # Use prefix and postfix
+ # rather than going through all posible combinations
+ prefix, postfix = word[:j], word[j:]
+ # prefix + postfix + reverse(prfix)
+ if prefix in word2index and i != word2index[prefix] and postfix == postfix[::-1]:
+ res.append([i, word2index[prefix]])
+ # reverse(postfix) + prefix + postfix
+ if j > 0 and postfix in word2index and i != word2index[postfix] and prefix == prefix[::-1]:
+ res.append([word2index[postfix], i])
+ return res
diff --git a/python/347_Top_K_Frequent_Elements.py b/python/347_Top_K_Frequent_Elements.py
new file mode 100644
index 0000000..3f7fc0b
--- /dev/null
+++ b/python/347_Top_K_Frequent_Elements.py
@@ -0,0 +1,10 @@
+class Solution(object):
+ def topKFrequent(self, nums, k):
+ """
+ :type nums: List[int]
+ :type k: int
+ :rtype: List[int]
+ """
+ counter = collections.Counter(nums)
+ return [k for k,v in counter.most_common(k)]
+ # return heapq.nlargest(k, count.keys(), key=count.get)
diff --git a/python/374_Guess_Number_Higher_or_Lower.py b/python/374_Guess_Number_Higher_or_Lower.py
index 403811d..c6dcbb8 100644
--- a/python/374_Guess_Number_Higher_or_Lower.py
+++ b/python/374_Guess_Number_Higher_or_Lower.py
@@ -19,4 +19,4 @@ def guessNumber(self, n):
elif res > 0:
begin = mid + 1
else:
- end = mid - 1
\ No newline at end of file
+ end = mid - 1
diff --git a/python/380_Insert_Delete_GetRandom.py b/python/380_Insert_Delete_GetRandom.py
new file mode 100644
index 0000000..f222d7d
--- /dev/null
+++ b/python/380_Insert_Delete_GetRandom.py
@@ -0,0 +1,33 @@
+import random
+
+class RandomizedSet(object):
+
+ def __init__(self):
+ self.num_to_idx = {}
+ self.num_list = []
+
+ def insert(self, val):
+ if val in self.num_to_idx:
+ return False
+ else:
+ self.num_list.append(val)
+ self.num_to_idx[val] = len(self.num_list) - 1
+ return True
+
+ def remove(self, val):
+ if val not in self.num_to_idx:
+ return False
+
+ idx = self.num_to_idx[val]
+ last = self.num_list[-1]
+
+ # swap last elem to current spot so you can pop the end
+ self.num_list[idx] = last
+ self.num_list.pop()
+ self.num_to_idx[last] = idx
+ del self.num_to_idx[val]
+
+ return True
+
+ def getRandom(self):
+ return random.choice(self.num_list)
diff --git a/python/392_Is_Subsequence.py b/python/392_Is_Subsequence.py
new file mode 100644
index 0000000..5cf66c0
--- /dev/null
+++ b/python/392_Is_Subsequence.py
@@ -0,0 +1,11 @@
+class Solution:
+ def isSubsequence(self, s: str, t: str) -> bool:
+ for a in s:
+ if a in t:
+ for b in range(0, len(t)):
+ if a==t[b]:
+ t=t[b+1:]
+ break
+ else:
+ return(False)
+ return(True)
diff --git a/python/400_Nth_Digit.py b/python/400_Nth_Digit.py
new file mode 100644
index 0000000..b1ece3b
--- /dev/null
+++ b/python/400_Nth_Digit.py
@@ -0,0 +1,18 @@
+class Solution(object):
+ def findNthDigit(self, n):
+ """
+ :type n: int
+ :rtype: int
+ """
+ # https://leetcode.com/problems/nth-digit/discuss/88363/Java-solution
+ count = 9
+ start = 1
+ curr_len = 1
+ while n > curr_len * count:
+ n -= curr_len * count
+ curr_len += 1
+ count *= 10
+ start *= 10
+ start += (n - 1) / curr_len
+ s = str(start)
+ return int(s[(n - 1) % curr_len]
diff --git a/python/409_Longest_Palindrome.py b/python/409_Longest_Palindrome.py
new file mode 100644
index 0000000..160f7b1
--- /dev/null
+++ b/python/409_Longest_Palindrome.py
@@ -0,0 +1,22 @@
+class Solution:
+ # https://leetcode.com/problems/longest-palindrome/solution/
+ # def longestPalindrome(self, s):
+ # ans = 0
+ # for v in collections.Counter(s).itervalues():
+ # ans += v / 2 * 2
+ # if ans % 2 == 0 and v % 2 == 1:
+ # ans += 1
+ # return ans
+ def longestPalindrome(self, s):
+ ans = 0
+ char_map = {}
+ for c in s:
+ char_map[c] = char_map.get(c, 0) + 1
+ for c in char_map.keys():
+ if char_map[c] % 2 == 0:
+ ans += char_map.pop(c)
+ else:
+ ans += char_map[c] / 2 * 2
+ if len(char_map) != 0:
+ ans += 1
+ return ans
\ No newline at end of file
diff --git a/python/414_Third_Maximum_Number.py b/python/414_Third_Maximum_Number.py
new file mode 100644
index 0000000..d2dee22
--- /dev/null
+++ b/python/414_Third_Maximum_Number.py
@@ -0,0 +1,20 @@
+class Solution(object):
+ def thirdMax(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ import Queue
+ pq = Queue.PriorityQueue(4)
+ check = set()
+ for n in nums:
+ if n in check:
+ continue
+ pq.put(n)
+ check.add(n)
+ if len(check) > 3:
+ check.remove(pq.get())
+ total = len(check)
+ while total < 3 and total > 1:
+ total -= 1
+ return pq.get()
diff --git a/python/415_Add_Strings.py b/python/415_Add_Strings.py
new file mode 100644
index 0000000..8166096
--- /dev/null
+++ b/python/415_Add_Strings.py
@@ -0,0 +1,53 @@
+class Solution(object):
+ # def addStrings(self, num1, num2):
+ # """
+ # :type num1: str
+ # :type num2: str
+ # :rtype: str
+ # """
+ # if num1 is None:
+ # num1 = '0'
+ # if num2 is None:
+ # num2 = '0'
+ # res = []
+ # carry = 0
+ # ls = min(len(num1), len(num2))
+ # pos = -1
+ # while pos + ls >= 0:
+ # curr = int(num1[pos]) + int(num2[pos]) + carry
+ # res.insert(0, str(curr % 10))
+ # carry = curr / 10
+ # pos -= 1
+ # while pos + len(num1) >= 0:
+ # curr = int(num1[pos]) + carry
+ # res.insert(0, str(curr % 10))
+ # carry = curr / 10
+ # pos -= 1
+ # while pos + len(num2) >= 0:
+ # curr = int(num2[pos]) + carry
+ # res.insert(0, str(curr % 10))
+ # carry = curr / 10
+ # pos -= 1
+ # if carry != 0:
+ # res.insert(0, str(carry))
+ # return ''.join(res)
+
+ def addStrings(self, num1, num2):
+ res = []
+ pos1 = len(num1) - 1
+ pos2 = len(num2) - 1
+ carry = 0
+ # This conditon is great
+ # https://leetcode.com/problems/add-strings/discuss/90436/Straightforward-Java-8-main-lines-25ms
+ while pos1 >= 0 or pos2 >= 0 or carry == 1:
+ digit1 = digit2 = 0
+ if pos1 >= 0:
+ digit1 = ord(num1[pos1]) - ord('0')
+ if pos2 >= 0:
+ digit2 = ord(num2[pos2]) - ord('0')
+ res.append(str((digit1 + digit2 + carry) % 10))
+ carry = (digit1 + digit2 + carry) / 10
+ pos1 -= 1
+ pos2 -= 1
+ # reverse res
+ return ''.join(res[::-1])
diff --git a/python/434_Number_of_Segments_in_a_String.py b/python/434_Number_of_Segments_in_a_String.py
new file mode 100644
index 0000000..5c643f2
--- /dev/null
+++ b/python/434_Number_of_Segments_in_a_String.py
@@ -0,0 +1,16 @@
+class Solution(object):
+ # https://leetcode.com/problems/number-of-segments-in-a-string/solution/
+ # def countSegments(self, s):
+ # """
+ # :type s: str
+ # :rtype: int
+ # """
+ # return len(s.split())
+
+ def countSegments(self, s):
+ segment_count = 0
+ for i in range(len(s)):
+ if (i == 0 or s[i-1] == ' ') and s[i] != ' ':
+ segment_count += 1
+
+ return segment_count
\ No newline at end of file
diff --git a/python/437_Path_Sum_III.py b/python/437_Path_Sum_III.py
new file mode 100644
index 0000000..8ae839c
--- /dev/null
+++ b/python/437_Path_Sum_III.py
@@ -0,0 +1,51 @@
+# Definition for a binary tree node.
+# class TreeNode(object):
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+
+# https://leetcode.com/problems/path-sum-iii/discuss/91892/Python-solution-with-detailed-explanation
+class Solution(object):
+ # def find_paths(self, root, target):
+ # if root:
+ # return int(root.val == target)
+ # + self.find_paths(root.left, target - root.val)
+ # + self.find_paths(root.right, target - root.val)
+ # return 0
+
+ # def pathSum(self, root, sum):
+ # """
+ # :type root: TreeNode
+ # :type sum: int
+ # :rtype: int
+ # """
+ # if root:
+ # return self.find_paths(root, sum)
+ # + self.pathSum(root.left, sum)
+ # + self.pathSum(root.right, sum)
+ # return 0
+
+ def pathSumHelper(self, root, target, so_far, cache):
+ if root:
+ # complement == 1, root->curr path
+ complement = so_far + root.val - target
+ if complement in cache:
+ # S->E path, sum(root->S)-sum(root->E) = target
+ self.result += cache[complement]
+ cache[so_far + root.val] = cache.get(so_far + root.val, 0) + 1
+ self.pathSumHelper(root.left, target, so_far + root.val, cache)
+ self.pathSumHelper(root.right, target, so_far + root.val, cache)
+ cache[so_far + root.val] -= 1
+ return
+
+ def pathSum(self, root, sum):
+ """
+ :type root: TreeNode
+ :type sum: int
+ :rtype: int
+ """
+ self.result = 0
+ self.pathSumHelper(root, sum, 0, {0: 1})
+ return self.result
diff --git a/python/438_Find_All_Anagrams_in_a_String.py b/python/438_Find_All_Anagrams_in_a_String.py
new file mode 100644
index 0000000..2867f1d
--- /dev/null
+++ b/python/438_Find_All_Anagrams_in_a_String.py
@@ -0,0 +1,68 @@
+class Solution(object):
+ def findAnagrams(self, s, p):
+ """
+ :type s: str
+ :type p: str
+ :rtype: List[int]
+ """
+ res = []
+ if s is None or p is None or len(s) == 0 or len(p) == 0:
+ return res
+ char_map = [0] * 256
+ for c in p:
+ char_map[ord(c)] += 1
+ left, right, count = 0, 0, len(p)
+ while right < len(s):
+ if char_map[ord(s[right])] >= 1:
+ count -= 1
+ char_map[ord(s[right])] -= 1
+ right += 1
+ if count == 0:
+ res.append(left)
+ if right - left == len(p):
+ if char_map[ord(s[left])] >= 0:
+ count += 1
+ char_map[ord(s[left])] += 1
+ left += 1
+ return res
+
+ # def findAnagrams(self, s, p):
+ # if len(s) < len(p):
+ # return []
+ # res = []
+ # p_len = len(p)
+ # bit_map = []
+ # for _ in range(26):
+ # bit_map.append(0)
+ # for c in p:
+ # bit_map[ord(c) - ord('a')] += 1
+ # s_p = str(bit_map)
+ # for i in range(26):
+ # bit_map[i] = 0
+ # for i in range(p_len - 1):
+ # bit_map[ord(s[i]) - ord('a')] += 1
+ # for i in range(p_len - 1, len(s)):
+ # bit_map[ord(s[i]) - ord('a')] += 1
+ # if i - p_len >= 0:
+ # bit_map[ord(s[i - p_len]) - ord('a')] -= 1
+ # if str(bit_map) == s_p:
+ # res.append(i - p_len + 1)
+ # return res
+
+ # def findAnagrams(self, s, p):
+ # """
+ # :type s: str
+ # :type p: str
+ # :rtype: List[int]
+ # """
+ # res = []
+ # pCounter = collections.Counter(p)
+ # sCounter = collections.Counter(s[:len(p)-1])
+ # for i in range(len(p)-1,len(s)):
+ # sCounter[s[i]] += 1 # include a new char in the char_map
+ # if sCounter == pCounter: # This step is O(1), since there are at most 26 English letters
+ # res.append(i-len(p)+1) # append the starting index
+ # sCounter[s[i-len(p)+1]] -= 1 # decrease the count of oldest char in the window
+ # if sCounter[s[i-len(p)+1]] == 0:
+ # del sCounter[s[i-len(p)+1]] # remove the count if it is 0
+ # return res
diff --git a/python/441_Arranging_Coins.py b/python/441_Arranging_Coins.py
new file mode 100644
index 0000000..eeeb750
--- /dev/null
+++ b/python/441_Arranging_Coins.py
@@ -0,0 +1,7 @@
+class Solution(object):
+ def arrangeCoins(self, n):
+ level = 0
+ while n > level:
+ level += 1
+ n -= level
+ return level
diff --git a/python/443_String_Compression.py b/python/443_String_Compression.py
new file mode 100644
index 0000000..c5bdeeb
--- /dev/null
+++ b/python/443_String_Compression.py
@@ -0,0 +1,18 @@
+class Solution(object):
+ def compress(self, chars):
+ """
+ :type chars: List[str]
+ :rtype: int
+ """
+ # https://leetcode.com/problems/string-compression/solution/
+ anchor = write = 0
+ for read, c in enumerate(chars):
+ if read + 1 == len(chars) or chars[read + 1] != c:
+ chars[write] = chars[anchor]
+ write += 1
+ if read > anchor:
+ for digit in str(read - anchor + 1):
+ chars[write] = digit
+ write += 1
+ anchor = read + 1
+ return write
\ No newline at end of file
diff --git a/python/448_Find_All_Numbers_Disappeared_in_an_Array.py b/python/448_Find_All_Numbers_Disappeared_in_an_Array.py
new file mode 100644
index 0000000..92a61e4
--- /dev/null
+++ b/python/448_Find_All_Numbers_Disappeared_in_an_Array.py
@@ -0,0 +1,18 @@
+class Solution(object):
+ def findDisappearedNumbers(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: List[int]
+ """
+ # https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/92956/Java-accepted-simple-solution
+ res = []
+ if nums:
+ n = len(nums)
+ for i in range(n):
+ val = abs(nums[i]) - 1
+ if nums[val] > 0:
+ nums[val] = -nums[val]
+ for i in range(n):
+ if nums[i] > 0:
+ res.append(i + 1)
+ return res
diff --git a/python/453_Minimum_Moves_to_Equal_Array_Elements.py b/python/453_Minimum_Moves_to_Equal_Array_Elements.py
new file mode 100644
index 0000000..db632b3
--- /dev/null
+++ b/python/453_Minimum_Moves_to_Equal_Array_Elements.py
@@ -0,0 +1,10 @@
+class Solution(object):
+ def minMoves(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ if nums is None or len(nums) == 0:
+ return 0
+ min_num = min(nums)
+ return sum([i - min_num for i in nums])
diff --git a/python/457_Circular_Array_Loop.py b/python/457_Circular_Array_Loop.py
new file mode 100644
index 0000000..1a2e2ee
--- /dev/null
+++ b/python/457_Circular_Array_Loop.py
@@ -0,0 +1,29 @@
+class Solution:
+ def circularArrayLoop(self, nums: List[int]) -> bool:
+ for i in range(len(nums)):
+ if nums[i] == 0:
+ continue
+
+ # if slow and fast pointers collide, then there exists a loop
+ slow = i
+ fast = self.index(nums, slow)
+ while nums[slow] * nums[fast] > 0 and nums[slow] * nums[self.index(nums, fast)] > 0:
+ if slow == fast and fast != self.index(nums, fast):
+ return True
+ elif slow == fast and fast == self.index(nums, fast):
+ break
+ slow = self.index(nums, slow)
+ fast = self.index(nums, self.index(nums, fast))
+
+ # set path to all 0s since it doesn't work
+ runner = i
+ value = nums[runner]
+ while nums[runner] * value > 0:
+ temp = self.index(nums, runner)
+ nums[runner] = 0
+ runner = temp
+ return False
+
+ def index(self, nums, index):
+ length = len(nums)
+ return (index + nums[index] + length) % length
diff --git a/python/458_Poor_Pigs.py b/python/458_Poor_Pigs.py
new file mode 100644
index 0000000..c667642
--- /dev/null
+++ b/python/458_Poor_Pigs.py
@@ -0,0 +1,13 @@
+class Solution(object):
+ def poorPigs(self, buckets, minutesToDie, minutesToTest):
+ """
+ :type buckets: int
+ :type minutesToDie: int
+ :type minutesToTest: int
+ :rtype: int
+ """
+ # https://leetcode.com/problems/poor-pigs/discuss/94266/Another-explanation-and-solution
+ pigs = 0
+ while (minutesToTest / minutesToDie + 1) ** pigs < buckets:
+ pigs += 1
+ return pigs
diff --git a/python/461_Hamming_Distance.py b/python/461_Hamming_Distance.py
new file mode 100644
index 0000000..7d3ed7a
--- /dev/null
+++ b/python/461_Hamming_Distance.py
@@ -0,0 +1,8 @@
+class Solution(object):
+ def hammingDistance(self, x, y):
+ """
+ :type x: int
+ :type y: int
+ :rtype: int
+ """
+ return bin(x ^ y).count('1')
diff --git a/python/463_Island_Perimeter.py b/python/463_Island_Perimeter.py
new file mode 100644
index 0000000..2b42b27
--- /dev/null
+++ b/python/463_Island_Perimeter.py
@@ -0,0 +1,22 @@
+class Solution(object):
+ def islandPerimeter(self, grid):
+ """
+ :type grid: List[List[int]]
+ :rtype: int
+ """
+ # https://leetcode.com/problems/island-perimeter/discuss/95001/clear-and-easy-java-solution
+ row_num = len(grid)
+ if row_num == 0 || len(grid[0]) == 0:
+ return 0
+ islands, overlaps = 0, 0
+ col_num = len(grid[0])
+ for i in range(row_num):
+ for j in range(col_num):
+ if (grid[i][j] == 1):
+ islands += 1
+ # careful about right and down
+ if (i < row_num - 1 && grid[i + 1][j] == 1):
+ overlaps += 1
+ if (j < col_num - 1 && grid[i][j + 1] == 1):
+ overlaps += 1
+ return islands * 4 - overlaps * 2
diff --git a/python/475_Heaters.py b/python/475_Heaters.py
new file mode 100644
index 0000000..90c7dde
--- /dev/null
+++ b/python/475_Heaters.py
@@ -0,0 +1,16 @@
+class Solution(object):
+ def findRadius(self, houses, heaters):
+ """
+ :type houses: List[int]
+ :type heaters: List[int]
+ :rtype: int
+ """
+ heaters = sorted(heaters) + [float('inf')]
+ i = r = 0
+ for x in sorted(houses):
+ # move to next range
+ while x >= sum(heaters[i:i + 2]) / 2.:
+ i += 1
+ # ans = hearter - hourse
+ r = max(r, abs(heaters[i] - x))
+ return r
diff --git a/python/479_Largest_Palindrome_Product.py b/python/479_Largest_Palindrome_Product.py
new file mode 100644
index 0000000..5d614de
--- /dev/null
+++ b/python/479_Largest_Palindrome_Product.py
@@ -0,0 +1,38 @@
+class Solution(object):
+ # def largestPalindrome(self, n):
+ # """
+ # :type n: int
+ # :rtype: int
+ # """
+ # if n == 1:
+ # return 9
+ # # https://leetcode.com/problems/largest-palindrome-product/discuss/96297/Java-Solution-using-assumed-max-palindrom
+ # upperBound = 10 ** n - 1
+ # lowerBound = upperBound / 10
+ # maxNum = upperBound * upperBound
+ # firstHalf = maxNum / (10 ** n)
+ # palindromFound = False
+ # palindrom = 0
+ # while not palindromFound:
+ # palindrom = int(str(firstHalf) + str(firstHalf)[::-1])
+ # for i in xrange(upperBound, lowerBound, -1):
+ # if i * i < palindrom:
+ # break
+ # if palindrom % i == 0:
+ # palindromFound = True
+ # break
+ # firstHalf -= 1
+ # return palindrom % 1337
+
+ def largestPalindrome(self, n):
+ # https://leetcode.com/problems/largest-palindrome-product/discuss/96305/Python-Solution-Using-Math-In-48ms
+ # https://leetcode.com/problems/largest-palindrome-product/discuss/96294/could-any-python-experts-share-their-codes-within-100ms
+ if n == 1:
+ return 9
+ for a in xrange(2, 9 * 10 ** (n - 1)):
+ hi = (10 ** n) - a
+ lo = int(str(hi)[::-1])
+ if a ** 2 - 4 * lo < 0:
+ continue
+ if (a ** 2 - 4 * lo) ** .5 == int((a ** 2 - 4 * lo) ** .5):
+ return (lo + 10 ** n * (10 ** n - a)) % 1337
diff --git a/python/482_License_Key_Formatting.py b/python/482_License_Key_Formatting.py
new file mode 100644
index 0000000..928151b
--- /dev/null
+++ b/python/482_License_Key_Formatting.py
@@ -0,0 +1,19 @@
+class Solution(object):
+ def licenseKeyFormatting(self, S, K):
+ """
+ :type S: str
+ :type K: int
+ :rtype: str
+ """
+ # https://leetcode.com/problems/license-key-formatting/discuss/96497/Python-solution
+ S = S.upper().replace('-', '')
+ ls = len(S)
+ if ls % K == 0:
+ pos = K
+ else:
+ pos = ls % K
+ res = S[:pos]
+ while pos < ls:
+ res += '-' + S[pos:pos + K]
+ pos += K
+ return res
diff --git a/python/485_Max_Consecutive_Ones.py b/python/485_Max_Consecutive_Ones.py
new file mode 100644
index 0000000..4d6ffc1
--- /dev/null
+++ b/python/485_Max_Consecutive_Ones.py
@@ -0,0 +1,18 @@
+class Solution(object):
+ def findMaxConsecutiveOnes(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ ans = 0
+ curr = 0
+ for n in nums:
+ if n == 1:
+ # Add 1 to curr when encounter 1
+ curr += 1
+ if curr > ans:
+ ans = curr
+ else:
+ # Add 1 to curr when encounter 1
+ curr = 0
+ return ans
diff --git a/python/509_Fibonacci_Number.py b/python/509_Fibonacci_Number.py
new file mode 100644
index 0000000..b4ddad7
--- /dev/null
+++ b/python/509_Fibonacci_Number.py
@@ -0,0 +1,30 @@
+class Solution(object):
+
+ def __init__(self):
+ self.memo = []
+ self.memo.append(0)
+ self.memo.append(1)
+
+ def fib(self, N):
+ """
+ DP with memo
+ :type N: int
+ :rtype: int
+ """
+ if N < len(self.memo):
+ return self.memo[N]
+ for i in range(len(self.memo), N + 1):
+ self.memo.append(self.memo[i - 1] + self.memo[i - 2])
+ return self.memo[N]
+
+ # def fib(self, N):
+ # """
+ # Recursively, O(n)
+ # :type N: int
+ # :rtype: int
+ # """
+ # if N == 0:
+ # return 0
+ # if N == 1:
+ # return 1
+ # return self.fib(N - 1) + self.fib(N - 2)
diff --git a/python/523_Continuous_Subarray_Sum.py b/python/523_Continuous_Subarray_Sum.py
new file mode 100644
index 0000000..d37ceeb
--- /dev/null
+++ b/python/523_Continuous_Subarray_Sum.py
@@ -0,0 +1,20 @@
+class Solution:
+ def checkSubarraySum(self, nums: List[int], k: int) -> bool:
+ # remeainders[0] = 0 is for when x == 0
+ remainders = dict()
+ remainders[0] = 0
+ pre_sum = 0
+
+ for idx, item in enumerate(nums):
+ pre_sum += item
+ remaind = pre_sum % k
+
+ # remainder doesnt exist then it has to be init
+ # if it exists, then check the prev one has the same remainder
+ if remaind not in remainders:
+ remainders[remaind] = idx + 1
+ elif remainders[remaind] < idx:
+ return True
+
+ return False
+
diff --git a/python/538_Convert_BST_to_Greater_Tree.py b/python/538_Convert_BST_to_Greater_Tree.py
new file mode 100644
index 0000000..5c567ba
--- /dev/null
+++ b/python/538_Convert_BST_to_Greater_Tree.py
@@ -0,0 +1,34 @@
+class Solution(object):
+ # https://leetcode.com/problems/convert-bst-to-greater-tree/solution/
+ # def __init__(self):
+ # self.total = 0
+
+ # def convertBST(self, root):
+ # if root is not None:
+ # self.convertBST(root.right)
+ # self.total += root.val
+ # root.val = self.total
+ # self.convertBST(root.left)
+ # return root
+
+ def convertBST(self, root):
+ total = 0
+
+ node = root
+ stack = []
+ while stack or node is not None:
+ # push all nodes up to (and including) this subtree's maximum on
+ # the stack.
+ while node is not None:
+ stack.append(node)
+ node = node.right
+
+ node = stack.pop()
+ total += node.val
+ node.val = total
+
+ # all nodes with values between the current and its parent lie in
+ # the left subtree.
+ node = node.left
+
+ return root
diff --git a/python/541_Reverse_String_II.py b/python/541_Reverse_String_II.py
new file mode 100644
index 0000000..08fcced
--- /dev/null
+++ b/python/541_Reverse_String_II.py
@@ -0,0 +1,23 @@
+class Solution:
+ def reverseStr(self, s: str, k: int) -> str:
+ N = len(s)
+ ans = ""
+ position = 0
+ while position < N:
+ nx = s[position : position + k]
+ ans = ans + nx[::-1] + s[position + k : position + 2 * k]
+ position += 2 * k
+ return ans
+
+ # def reverseStr(self, s: str, k: int) -> str:
+ # s = list(s)
+ # for i in range(0, len(s), 2*k):
+ # s[i:i+k] = reversed(s[i:i+k])
+ # return "".join(s)
+
+
+
+s1 = Solution()
+s="abcdefg"
+k=2
+print(s1.reverseStr(s,k))
diff --git a/python/543_Diameter_of_Binary_Tree.py b/python/543_Diameter_of_Binary_Tree.py
new file mode 100644
index 0000000..94a3164
--- /dev/null
+++ b/python/543_Diameter_of_Binary_Tree.py
@@ -0,0 +1,21 @@
+# Definition for a binary tree node.
+# class TreeNode(object):
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+class Solution(object):
+ # https://leetcode.com/problems/diameter-of-binary-tree/solution/
+ def diameterOfBinaryTree(self, root):
+ self.ans = 1
+ def depth(node):
+ if not node: return 0
+ L = depth(node.left)
+ R = depth(node.right)
+ self.ans = max(self.ans, L+R+1)
+ return max(L, R) + 1
+
+ depth(root)
+ # number of nodes - 1 = length
+ return self.ans - 1
diff --git a/python/547_Friend_Circles.py b/python/547_Friend_Circles.py
new file mode 100644
index 0000000..c1ae31b
--- /dev/null
+++ b/python/547_Friend_Circles.py
@@ -0,0 +1,92 @@
+class Solution(object):
+ def findCircleNum(self, M):
+ """
+ :type M: List[List[int]]
+ :rtype: int
+ """
+ # because
+ visited = [0] * len(M)
+ count = 0
+ for i in range(len(M)):
+ if visited[i] == 0:
+ self.dfs(M, visited, i)
+ count += 1
+ return count
+
+ def dfs(self, M, visited, i):
+ for j in range(len(M)):
+ if M[i][j] == 1 and visited[j] == 0:
+ visited[j] = 1
+ self.dfs(M, visited, j)
+
+ # def findCircleNum(self, M):
+ # # BFS
+ # visited = [0] * len(M)
+ # count = 0
+ # queue = []
+ # for i in range(len(M)):
+ # if visited[i] == 0:
+ # queue.append(i)
+ # while queue:
+ # curr = queue.pop(0)
+ # visited[curr] = 1
+ # for j in range(len(M)):
+ # if M[curr][j] == 1 and visited[j] == 0:
+ # queue.append(j)
+ # count += 1
+ # return count
+
+# def findCircleNum(self, M):
+# # Union Find
+# union = Union()
+# for i in range(len(M)):
+# union.add(i)
+# for i in range(len(M)):
+# for j in range(i + 1, len(M)):
+# if M[i][j] == 1:
+# union.union(i, j)
+# return union.count
+
+# class Union(object):
+# """
+# weighted quick union find
+# """
+# def __init__(self):
+# # both dic and list is fine
+# self.id = {}
+# self.sz = {}
+# self.count = 0
+
+# def count(self):
+# return self.count
+
+# def connected(self, p, q):
+# return self.find(p) == self.find(q)
+
+# def add(self, p):
+# # init
+# self.id[p] = p
+# self.sz[p] = 1
+# self.count += 1
+
+# def find(self, p):
+# """
+# find root of p, and compress path
+# """
+# while p != self.id[p]:
+# self.id[p] = self.id[self.id[p]]
+# p = self.id[p]
+# return p
+
+# def union(self, p, q):
+# """
+# connect p and q
+# """
+# i, j = self.find(p), self.find(q)
+# if i == j:
+# return
+# if self.sz[i] > self.sz[j]:
+# i, j = j, i
+# self.id[i] = j
+# self.sz[j] += self.sz[i]
+# self.count -= 1
diff --git a/python/557_Reverse_Words_in_a_String_III.py b/python/557_Reverse_Words_in_a_String_III.py
new file mode 100644
index 0000000..c862c21
--- /dev/null
+++ b/python/557_Reverse_Words_in_a_String_III.py
@@ -0,0 +1,7 @@
+class Solution(object):
+ def reverseWords(self, s):
+ """
+ :type s: str
+ :rtype: str
+ """
+ return ' '.join([word[::-1] for word in s.split(' ')])
diff --git a/python/560_Subarray_Sum_Equals_K.py b/python/560_Subarray_Sum_Equals_K.py
new file mode 100644
index 0000000..fae8c39
--- /dev/null
+++ b/python/560_Subarray_Sum_Equals_K.py
@@ -0,0 +1,17 @@
+class Solution(object):
+ def subarraySum(self, nums, k):
+ """
+ :type nums: List[int]
+ :type k: int
+ :rtype: int
+ """
+ sum_map = {}
+ sum_map[0] = 1
+ count = curr_sum = 0
+ for num in nums:
+ curr_sum += num
+ # Check if sum - k in hash
+ count += sum_map.get(curr_sum - k, 0)
+ # add curr_sum to hash
+ sum_map[curr_sum] = sum_map.get(curr_sum, 0) + 1
+ return count
diff --git a/python/572_Subtree_of_Another_Tree.py b/python/572_Subtree_of_Another_Tree.py
new file mode 100644
index 0000000..4d57049
--- /dev/null
+++ b/python/572_Subtree_of_Another_Tree.py
@@ -0,0 +1,39 @@
+# Definition for a binary tree node.
+# class TreeNode(object):
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+class Solution(object):
+ # https://leetcode.com/problems/subtree-of-another-tree/solution/
+ def isSubtree(self, s, t):
+ """
+ :type s: TreeNode
+ :type t: TreeNode
+ :rtype: bool
+ """
+ s_res = self.preorder(s, True)
+ t_res = self.preorder(t, True)
+ return t_res in s_res
+
+ def preorder(self, root, isLeft):
+ if root is None:
+ if isLeft:
+ return "lnull"
+ else:
+ return "rnull"
+ return "#" + str(root.val) + " " + self.preorder(root.left, True) + " " + self.preorder(root.right, False)
+
+ # def isSubtree(self, s, t):
+ # return self.traverse(s, t)
+
+ # def equals(self, x, y):
+ # if x is None and y is None:
+ # return True
+ # if x is None or y is None:
+ # return False
+ # return x.val == y.val and self.equals(x.left, y.left) and self.equals(x.right, y.right)
+
+ # def traverse(self, s, t):
+ # return s is not None and (self.equals(s, t) or self.traverse(s.left, t) or self.traverse(s.right, t))
diff --git a/python/581_Shortest_Unsorted_Continuous_Subarray.py b/python/581_Shortest_Unsorted_Continuous_Subarray.py
new file mode 100644
index 0000000..da7e893
--- /dev/null
+++ b/python/581_Shortest_Unsorted_Continuous_Subarray.py
@@ -0,0 +1,63 @@
+class Solution(object):
+ # https://leetcode.com/problems/shortest-unsorted-continuous-subarray/solution/
+ # def findUnsortedSubarray(self, nums):
+ # """
+ # :type nums: List[int]
+ # :rtype: int
+ # """
+ # snums = nums[::]
+ # snums.sort()
+ # start = len(nums)
+ # end = 0
+ # for i in range(len(nums)):
+ # if snums[i] != nums[i]:
+ # start = min(start, i)
+ # end = max(end, i)
+ # if end >= start:
+ # return end - start + 1
+ # return 0
+
+ def findUnsortedSubarray(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ stack = []
+ l, r = len(nums), 0
+ for i in range(len(nums)):
+ while len(stack) != 0 and nums[stack[-1]] > nums[i]:
+ l = min(l, stack.pop())
+ stack.append(i)
+ stack = []
+ for i in range(len(nums) - 1, -1, -1):
+ while len(stack) != 0 and nums[stack[-1]] < nums[i]:
+ r = max(r, stack.pop())
+ stack.append(i)
+ if r > l:
+ return r - l + 1
+ return 0
+
+ # def findUnsortedSubarray(self, nums):
+ # smin = 2 ** 31 -1
+ # smax = -2 ** 31
+ # flag = False
+ # for i in range(1, len(nums)):
+ # if nums[i] < nums[i-1]:
+ # flag = True
+ # if flag:
+ # smin = min(smin, nums[i])
+ # flag = False
+ # for i in range(len(nums)-2, -1, -1):
+ # if nums[i] > nums[i+1]:
+ # flag = True
+ # if flag:
+ # smax = max(smax, nums[i])
+ # for l in range(len(nums)):
+ # if smin < nums[l]:
+ # break
+ # for r in range(len(nums)-1, -1, -1):
+ # if smax > nums[r]:
+ # break
+ # if r > l:
+ # return r - l + 1
+ # return 0
diff --git a/python/605_Can_Place_Flowers.py b/python/605_Can_Place_Flowers.py
new file mode 100644
index 0000000..688357b
--- /dev/null
+++ b/python/605_Can_Place_Flowers.py
@@ -0,0 +1,20 @@
+class Solution(object):
+ def canPlaceFlowers(self, flowerbed, n):
+ """
+ :type flowerbed: List[int]
+ :type n: int
+ :rtype: bool
+ """
+ count = 0
+ for i in range(len(flowerbed)):
+ curr = flowerbed[i]
+ if i - 1 >= 0:
+ curr += flowerbed[i - 1]
+ if i + 1 < len(flowerbed):
+ curr += flowerbed[i + 1]
+ if curr == 0:
+ count += 1
+ flowerbed[i] = 1
+ if count >= n:
+ return True
+ return False
diff --git a/python/617_Merge_Two_Binary_Trees.py b/python/617_Merge_Two_Binary_Trees.py
new file mode 100644
index 0000000..af76326
--- /dev/null
+++ b/python/617_Merge_Two_Binary_Trees.py
@@ -0,0 +1,41 @@
+# Definition for a binary tree node.
+# class TreeNode(object):
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+class Solution(object):
+ def mergeTrees(self, t1, t2):
+ """
+ :type t1: TreeNode
+ :type t2: TreeNode
+ :rtype: TreeNode
+ """
+ if t1 is None:
+ return t2
+ if t2 is None:
+ return t1
+ t1.val += t2.val
+ t1.left = self.mergeTrees(t1.left, t2.left)
+ t1.right = self.mergeTrees(t1.right, t2.right)
+ return t1
+
+ # def mergeTrees(self, t1, t2):
+ # if t1 is None:
+ # return t2
+ # stack = [(t1, t2)]
+ # while len(stack) != 0:
+ # n1, n2 = stack.pop()
+ # if n1 is None or n2 is None:
+ # continue
+ # n1.val += n2.val
+ # if n1.left is None:
+ # n1.left = n2.left
+ # else:
+ # stack.insert(0, (n1.left, n2.left))
+ # if n1.right is None:
+ # n1.right = n2.right
+ # else:
+ # stack.insert(0, (n1.right, n2.right))
+ # return t1
diff --git a/python/628_Maximum_Product_of_Three_Numbers.py b/python/628_Maximum_Product_of_Three_Numbers.py
new file mode 100644
index 0000000..e955f84
--- /dev/null
+++ b/python/628_Maximum_Product_of_Three_Numbers.py
@@ -0,0 +1,30 @@
+class Solution(object):
+ # def maximumProduct(self, nums):
+ # """
+ # :type nums: List[int]
+ # :rtype: int
+ # """
+ # nums.sort()
+ # # Check min1*min2*max1 and max1*max2*max3
+ # return max(reduce(lambda x, y: x * y, nums[:2]) * nums[-1],
+ # reduce(lambda x, y: x * y, nums[-3:]))
+
+ def maximumProduct(self, nums):
+ min1 = min2 = float('inf')
+ max1 = max2 = max3 = float('-inf')
+ for num in nums:
+ if num <= min1:
+ min2 = min1
+ min1 = num
+ elif num <= min2:
+ min2 = num
+ if num >= max1:
+ max3 = max2
+ max2 = max1
+ max1 = num
+ elif num >= max2:
+ max3 = max2
+ max2 = num
+ elif num >= max3:
+ max3 = num
+ return max(min1 * min2 * max1, max1 * max2 * max3)
diff --git a/python/654_Maximum_Binary_Tree.py b/python/654_Maximum_Binary_Tree.py
new file mode 100644
index 0000000..4b7c4f0
--- /dev/null
+++ b/python/654_Maximum_Binary_Tree.py
@@ -0,0 +1,39 @@
+# Definition for a binary tree node.
+# class TreeNode(object):
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+
+class Solution(object):
+ def constructMaximumBinaryTree(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: TreeNode
+ """
+ # O (n^2) and O(n)
+ if nums is None or len(nums) == 0:
+ return None
+ max_index, max_value = 0, 0
+ for i, value in enumerate(nums):
+ if value >= max_value:
+ max_value = value
+ max_index = i
+ root = TreeNode(max_value)
+ root.left = self.constructMaximumBinaryTree(nums[:max_index])
+ root.right = self.constructMaximumBinaryTree(nums[max_index+1:])
+ return root
+
+ # def constructMaximumBinaryTree(self, nums):
+ # # https://leetcode.com/problems/maximum-binary-tree/discuss/106146/C++-O(N)-solution
+ # stack = []
+ # for value in nums:
+ # curr = TreeNode(value)
+ # while len(stack) != 0 and stack[-1].val < value:
+ # curr.left = stack[-1]
+ # stack.pop()
+ # if (len(stack) != 0):
+ # stack[-1].right = curr
+ # stack.append(curr)
+ # return stack[0]
diff --git a/python/665_Non-decreasing_Array.py b/python/665_Non-decreasing_Array.py
new file mode 100644
index 0000000..b2d01c2
--- /dev/null
+++ b/python/665_Non-decreasing_Array.py
@@ -0,0 +1,38 @@
+class Solution(object):
+ # def checkPossibility(self, nums):
+ # """
+ # :type nums: List[int]
+ # :rtype: bool
+ # """
+ # pos = None
+ # # Check if there are more than 2 broken point
+ # # record first index
+ # for i in range(len(nums) - 1):
+ # if nums[i] > nums[i + 1]:
+ # if pos is not None:
+ # return False
+ # pos = i
+ # if pos is None or pos == 0 or pos == len(nums) - 2:
+ # return True
+ # # Remove pos or remove pos + 1
+ # return (nums[pos - 1] <= nums[pos + 1] or nums[pos] <= nums[pos + 2])
+
+ def checkPossibility(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: bool
+ """
+ # https://leetcode.com/problems/non-decreasing-array/discuss/106826/JavaC%2B%2B-Simple-greedy-like-solution-with-explanation
+ broken_num = 0
+ for i in range(len(nums) - 1):
+ if (nums[i] > nums[i + 1]):
+ broken_num += 1
+ if broken_num >= 2:
+ return False
+ if (i - 1 < 0 or nums[i - 1] <= nums[i + 1]):
+ # Remove i
+ nums[i] = nums[i + 1]
+ else:
+ # Remove i + 1
+ nums[i + 1] = nums[i]
+ return True
diff --git a/python/668_Kth_Smallest_Number_in_Multiplication_Table.py b/python/668_Kth_Smallest_Number_in_Multiplication_Table.py
new file mode 100644
index 0000000..dcfd654
--- /dev/null
+++ b/python/668_Kth_Smallest_Number_in_Multiplication_Table.py
@@ -0,0 +1,19 @@
+class Solution:
+ def findKthNumber(self, m: int, n: int, k: int) -> int:
+ # https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/solution/
+ def enough(x):
+ count = 0
+ # ith row [i, 2*i, 3*i, ..., n*i]
+ # for each column, k = x // i
+ for i in range(1, m+1):
+ count += min(x // i, n)
+ return count >= k
+
+ lo, hi = 1, m * n
+ while lo < hi:
+ mi = (lo + hi) // 2
+ if not enough(mi):
+ lo = mi + 1
+ else:
+ hi = mi
+ return lo
diff --git a/python/671_Second_Minimum_Node_In_a_Binary_Tree.py b/python/671_Second_Minimum_Node_In_a_Binary_Tree.py
new file mode 100644
index 0000000..2c369b6
--- /dev/null
+++ b/python/671_Second_Minimum_Node_In_a_Binary_Tree.py
@@ -0,0 +1,45 @@
+# Definition for a binary tree node.
+# class TreeNode(object):
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+class Solution(object):
+ # def findSecondMinimumValue(self, root):
+ # """
+ # :type root: TreeNode
+ # :rtype: int
+ # """
+ # # Brute force
+ # values = set()
+ # self.dfs(root, values)
+ # ans, min_value = float('inf'), root.val
+ # for n in values:
+ # if min_value < n and n < ans:
+ # ans = n
+ # return ans if ans < float('inf') else -1
+
+ # def dfs(self, root, values):
+ # if not root:
+ # return
+ # values.add(root.val)
+ # self.dfs(root.left, values)
+ # self.dfs(root.right, values)
+
+ def findSecondMinimumValue(self, root):
+ if not root:
+ return -1
+ ans = float('inf')
+ min_val = root.val
+ stack = [root]
+ while stack:
+ curr = stack.pop()
+ if not curr:
+ continue
+ if min_val < curr.val < ans:
+ ans = curr.val
+ elif curr.val == min_val:
+ stack.append(curr.left)
+ stack.append(curr.right)
+ return ans if ans < float('inf') else -1
diff --git a/python/674_Longest_Continuous_Increasing_Subsequence.py b/python/674_Longest_Continuous_Increasing_Subsequence.py
new file mode 100644
index 0000000..00d2295
--- /dev/null
+++ b/python/674_Longest_Continuous_Increasing_Subsequence.py
@@ -0,0 +1,16 @@
+class Solution(object):
+ def findLengthOfLCIS(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ if not nums or len(nums) == 0:
+ return 0
+ ans = curr = 1
+ for i in range(len(nums) - 1):
+ if nums[i] < nums[i + 1]:
+ curr += 1
+ ans = max(ans, curr)
+ else:
+ curr = 1
+ return ans
diff --git a/python/680_Valid_Palindrome_II.py b/python/680_Valid_Palindrome_II.py
new file mode 100644
index 0000000..873e9db
--- /dev/null
+++ b/python/680_Valid_Palindrome_II.py
@@ -0,0 +1,30 @@
+class Solution(object):
+ # def validPalindrome(self, s):
+ # """
+ # :type s: str
+ # :rtype: bool
+ # """
+ # def is_pali_range(i, j):
+ # return all(s[k] == s[j - k + i] for k in range(i, j))
+
+ # for i in xrange(len(s) / 2):
+ # if s[i] != s[~i]:
+ # j = len(s) - 1 - i
+ # return is_pali_range(i + 1, j) or is_pali_range(i, j - 1)
+ # return True
+
+ # Actually we can make this solution more general
+ def validPalindrome(self, s):
+ return self.validPalindromeHelper(s, 0, len(s) - 1, 1)
+
+ def validPalindromeHelper(self, s, left, right, budget):
+ # Note that budget can be more than 1
+ while left < len(s) and right >= 0 and left <= right and s[left] == s[right]:
+ left += 1
+ right -= 1
+ if left >= len(s) or right < 0 or left >= right:
+ return True
+ if budget == 0:
+ return False
+ budget -= 1
+ return self.validPalindromeHelper(s, left + 1, right, budget) or self.validPalindromeHelper(s, left, right - 1, budget)
diff --git a/python/692_Top_K_Frequent_Words.py b/python/692_Top_K_Frequent_Words.py
new file mode 100644
index 0000000..1efc014
--- /dev/null
+++ b/python/692_Top_K_Frequent_Words.py
@@ -0,0 +1,29 @@
+class Solution(object):
+# def topKFrequent(self, words, k):
+# """
+# :type words: List[str]
+# :type k: int
+# :rtype: List[str]
+# """
+# counter = collections.Counter(words)
+# res = sorted(counter.items(), cmp=cmp_frequency, reverse=True)
+# return [k for k, _ in res[:k]]
+
+# def cmp_frequency(x, y):
+# if x[1] != y[1]:
+# return cmp(x[1], y[1])
+# return cmp(y[0], x[0])
+
+ # def topKFrequent(self, words, k):
+ # count = collections.Counter(words)
+ # candidates = count.keys()
+ # candidates.sort(key = lambda w: (-count[w], w))
+ # return candidates[:k]
+
+ def topKFrequent(self, words, k):
+ count = collections.Counter(words)
+ # Note that python heapq only support min heap
+ # So, we can make the value negative to create a max heap
+ heap = [(-freq, word) for word, freq in count.items()]
+ heapq.heapify(heap)
+ return [heapq.heappop(heap)[1] for _ in xrange(k)]
diff --git a/python/695_Max_Area_of_Island.py b/python/695_Max_Area_of_Island.py
new file mode 100644
index 0000000..1d622d4
--- /dev/null
+++ b/python/695_Max_Area_of_Island.py
@@ -0,0 +1,67 @@
+class Solution(object):
+ def maxAreaOfIsland(self, grid):
+ """
+ :type grid: List[List[int]]
+ :rtype: int
+ """
+ # because
+ ans = 0
+ for i in range(len(grid)):
+ for j in range(len(grid[0])):
+ if grid[i][j] == 1:
+ grid[i][j] = 0
+ ans = max(self.dfs(grid, i, j), ans)
+ # ans = max(self.bfs(grid, i, j), ans)
+ return ans
+
+ def dfs(self, grid, i, j):
+ # DFS based on stack
+ stack = [(i, j)]
+ area = 0
+ # Stack for DFS
+ while stack:
+ r, c = stack.pop(-1)
+ area += 1
+ for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
+ if (0 <= nr < len(grid) and
+ 0 <= nc < len(grid[0]) and grid[nr][nc]):
+ stack.append((nr, nc))
+ grid[nr][nc] = 0
+ return area
+
+ # def bfs(self, grid, x, y):
+ # # BFS based on queue
+ # queue = [(x, y)]
+ # area = 0
+ # # Stack for DFS
+ # while queue:
+ # i, j = queue.pop(0)
+ # area += 1
+ # if i - 1 >= 0 and grid[i - 1][j] == 1:
+ # grid[i - 1][j] = 0
+ # queue.append((i - 1, j))
+ # if i + 1 < len(grid) and grid[i + 1][j] == 1:
+ # grid[i + 1][j] = 0
+ # queue.append((i + 1, j))
+ # if j - 1 >= 0 and grid[i][j - 1] == 1:
+ # grid[i][j - 1] = 0
+ # queue.append((i, j - 1))
+ # if j + 1 < len(grid[0]) and grid[i][j + 1] == 1:
+ # grid[i][j + 1] = 0
+ # queue.append((i, j + 1))
+ # return area
+
+ # def maxAreaOfIsland(self, grid):
+ # # Recursive DFS
+ # seen = set()
+ # def area(r, c):
+ # if not (0 <= r < len(grid) and 0 <= c < len(grid[0])
+ # and (r, c) not in seen and grid[r][c]):
+ # return 0
+ # seen.add((r, c))
+ # return (1 + area(r+1, c) + area(r-1, c) +
+ # area(r, c-1) + area(r, c+1))
+
+ # return max(area(r, c)
+ # for r in range(len(grid))
+ # for c in range(len(grid[0])))
diff --git a/python/697_Degree_of_an_Array.py b/python/697_Degree_of_an_Array.py
new file mode 100644
index 0000000..b37e6f0
--- /dev/null
+++ b/python/697_Degree_of_an_Array.py
@@ -0,0 +1,41 @@
+class Solution(object):
+ # def findShortestSubArray(self, nums):
+ # """
+ # :type nums: List[int]
+ # :rtype: int
+ # """
+ # res = len(nums)
+ # counter = collections.Counter()
+ # for num in nums:
+ # counter[num] += 1
+ # degree = max(counter.values())
+ # for key, kdegree in counter.most_common():
+ # if degree != kdegree:
+ # break
+ # res = min(res, self.smallestSubArray(nums, key, degree))
+ # return res
+
+ # def smallestSubArray(self, nums, key, degree):
+ # start = nums.index(key)
+ # pos = start + 1
+ # degree -= 1
+ # while pos < len(nums) and degree != 0:
+ # if nums[pos] == key:
+ # degree -= 1
+ # pos += 1
+ # return pos - start
+
+ def findShortestSubArray(self, nums):
+ left, right, count = {}, {}, {}
+ for i, x in enumerate(nums):
+ if x not in left: left[x] = i
+ right[x] = i
+ count[x] = count.get(x, 0) + 1
+
+ ans = len(nums)
+ degree = max(count.values())
+ for x in count:
+ if count[x] == degree:
+ ans = min(ans, right[x] - left[x] + 1)
+
+ return ans
diff --git a/python/700_Search_in_a_Binary_Search_Tree.py b/python/700_Search_in_a_Binary_Search_Tree.py
new file mode 100644
index 0000000..c9147cb
--- /dev/null
+++ b/python/700_Search_in_a_Binary_Search_Tree.py
@@ -0,0 +1,33 @@
+# Definition for a binary tree node.
+# class TreeNode(object):
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+class Solution(object):
+ # def searchBST(self, root, val):
+ # """
+ # :type root: TreeNode
+ # :type val: int
+ # :rtype: TreeNode
+ # """
+ # # Recursive
+ # if not root:
+ # return None
+ # if root.val == val:
+ # return root
+ # elif root.val > val:
+ # return self.searchBST(root.left, val)
+ # else:
+ # return self.searchBST(root.right, val)
+
+ def searchBST(self, root, val):
+ while root:
+ if root.val == val:
+ return root
+ elif root.val > val:
+ root = root.left
+ else:
+ root = root.right
+ return root
diff --git a/python/703_Kth_Largest_Element_in_a_Stream.py b/python/703_Kth_Largest_Element_in_a_Stream.py
new file mode 100644
index 0000000..30c2ea7
--- /dev/null
+++ b/python/703_Kth_Largest_Element_in_a_Stream.py
@@ -0,0 +1,25 @@
+class KthLargest(object):
+
+ def __init__(self, k, nums):
+ self.nums = nums
+ self.k = k
+ # build min heap
+ heapq.heapify(self.nums)
+ # remove n - k smallest number
+ while len(self.nums) > k:
+ heapq.heappop(self.nums)
+
+ def add(self, val):
+ # add to heaq if it's less then k
+ if len(self.nums) < self.k:
+ heapq.heappush(self.nums, val)
+ elif val > self.nums[0]:
+ # if len(heaq) == k, and val greater than smallest num
+ # then pop smallest num than add val to heap
+ heapq.heapreplace(self.nums, val)
+ # return k largest
+ return self.nums[0]
+
+# Your KthLargest object will be instantiated and called as such:
+# obj = KthLargest(k, nums)
+# param_1 = obj.add(val)
diff --git a/python/706_Design_HashMap.py b/python/706_Design_HashMap.py
new file mode 100644
index 0000000..96aaa71
--- /dev/null
+++ b/python/706_Design_HashMap.py
@@ -0,0 +1,80 @@
+class MyHashMap(object):
+
+ # https://leetcode.com/problems/design-hashmap/discuss/152746/Java-Solution
+ def __init__(self):
+ """
+ Initialize your data structure here.
+ """
+ self.size = 10000
+ self.nodes = [None] * self.size
+
+ def put(self, key, value):
+ """
+ value will always be non-negative.
+ :type key: int
+ :type value: int
+ :rtype: void
+ """
+ index = hash(key) % self.size
+ if self.nodes[index] is None:
+ self.nodes[index] = ListNode(-1, -1)
+ prev = find(self.nodes[index], key)
+ if prev.next is None:
+ prev.next = ListNode(key, value)
+ else:
+ prev.next.val = value
+
+ def get(self, key):
+ """
+ Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
+ :type key: int
+ :rtype: int
+ """
+ index = hash(key) % self.size
+ if self.nodes[index] is None:
+ return -1
+ prev = find(self.nodes[index], key)
+ if prev.next is None:
+ return -1
+ else:
+ return prev.next.val
+
+ def remove(self, key):
+ """
+ Removes the mapping of the specified value key if this map contains a mapping for the key
+ :type key: int
+ :rtype: void
+ """
+ index = hash(key) % self.size
+ if self.nodes[index] is None:
+ return
+ prev = find(self.nodes[index], key)
+ if prev.next is None:
+ return
+ prev.next = prev.next.next
+
+
+def find(bucket, key):
+ # find prev node of this key
+ node = bucket
+ prev = None
+ while node is not None and node.key != key:
+ prev = node
+ node = node.next
+ return prev
+
+
+# Basic node in hash map
+class ListNode():
+
+ def __init__(self, key, val):
+ self.key = key
+ self.val = val
+ self.next = None
+
+
+# Your MyHashMap object will be instantiated and called as such:
+# obj = MyHashMap()
+# obj.put(key,value)
+# param_2 = obj.get(key)
+# obj.remove(key)
\ No newline at end of file
diff --git a/python/709_To_Lower_Case.py b/python/709_To_Lower_Case.py
new file mode 100644
index 0000000..ac86f9d
--- /dev/null
+++ b/python/709_To_Lower_Case.py
@@ -0,0 +1,17 @@
+class Solution(object):
+ def toLowerCase(self, str):
+ """
+ :type str: str
+ :rtype: str
+ """
+ res = []
+ gap = ord('a') - ord('A')
+ for c in str:
+ if ord(c) >= ord('A') and ord(c) <= ord('Z'):
+ res.append(chr(ord(c) + gap))
+ else:
+ res.append(c)
+ return ''.join(res)
+
+ # def toLowerCase(self, str):
+ # return str.lower()
diff --git a/python/716_Max_Stack.py b/python/716_Max_Stack.py
new file mode 100644
index 0000000..08e71c0
--- /dev/null
+++ b/python/716_Max_Stack.py
@@ -0,0 +1,56 @@
+class MaxStack(object):
+
+ def __init__(self):
+ """
+ initialize your data structure here.
+ """
+ self.stack = []
+ self.max_stack = []
+
+ def push(self, x):
+ """
+ :type x: int
+ :rtype: void
+ """
+ self.stack.append(x)
+ if len(self.max_stack) == 0:
+ self.max_stack.append(x)
+ return
+ if self.max_stack[-1] > x:
+ self.max_stack.append(self.max_stack[-1])
+ else:
+ self.max_stack.append(x)
+
+ def pop(self):
+ """
+ :rtype: int
+ """
+ if len(self.stack) != 0:
+ self.max_stack.pop(-1)
+ return self.stack.pop(-1)
+
+ def top(self):
+ """
+ :rtype: int
+ """
+ return self.stack[-1]
+
+ def peekMax(self):
+ """
+ :rtype: int
+ """
+ if len(self.max_stack) != 0:
+ return self.max_stack[-1]
+
+ def popMax(self):
+ """
+ :rtype: int
+ """
+ val = self.peekMax()
+ buff = []
+ while self.top() != val:
+ buff.append(self.pop())
+ self.pop()
+ while len(buff) != 0:
+ self.push(buff.pop(-1))
+ return val
diff --git a/python/717_1-bit_and_2-bit_Characters.py b/python/717_1-bit_and_2-bit_Characters.py
new file mode 100644
index 0000000..104441d
--- /dev/null
+++ b/python/717_1-bit_and_2-bit_Characters.py
@@ -0,0 +1,38 @@
+# We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).
+# Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.
+
+# Example 1:
+# Input:
+# bits = [1, 0, 0]
+# Output: True
+# Explanation:
+# The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.
+# Example 2:
+# Input:
+# bits = [1, 1, 1, 0]
+# Output: False
+# Explanation:
+# The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.
+# Note:
+
+# 1 <= len(bits) <= 1000.
+# bits[i] is always 0 or 1.
+
+# https://leetcode.com/problems/1-bit-and-2-bit-characters/solution/
+class Solution:
+ def isOneBitCharacter(self, bits: List[int]) -> bool:
+ pos = 0
+ # Go through bits
+ while pos < len(bits) - 1:
+ # if 1, pos + 2; if 0, pos + 1
+ pos += bits[pos] + 1
+ return pos == len(bits) - 1
+
+ # def isOneBitCharacter(self, bits):
+ # # From len - 2
+ # pos = len(bits) - 2
+ # # until encounter 0
+ # while pos >= 0 and bits[pos] > 0:
+ # pos -= 1
+ # # check if second last zero is even
+ # return (len(bits) - pos) % 2 == 0
diff --git a/python/720_Longest_Word_in_Dictionary.py b/python/720_Longest_Word_in_Dictionary.py
new file mode 100644
index 0000000..7c6249f
--- /dev/null
+++ b/python/720_Longest_Word_in_Dictionary.py
@@ -0,0 +1,36 @@
+class Solution(object):
+ # def longestWord(self, words):
+ # words.sort()
+ # words_set, longest_word = set(['']), ''
+ # for word in words:
+ # if word[:-1] in words_set:
+ # words_set.add(word)
+ # if len(word) > len(longest_word):
+ # longest_word = word
+ # return longest_word
+
+ # def longestWord(self, words):
+ # ans = ""
+ # wordset = set(words)
+ # for word in words:
+ # if len(word) > len(ans) or len(word) == len(ans) and word < ans:
+ # if all(word[:k] in wordset for k in xrange(1, len(word))):
+ # ans = word
+ # return ans
+
+ def longestWord(self, words):
+ Trie = lambda: collections.defaultdict(Trie)
+ trie = Trie()
+ END = True
+ for i, word in enumerate(words):
+ reduce(dict.__getitem__, word, trie)[END] = i
+ stack = trie.values()
+ ans = ""
+ while stack:
+ cur = stack.pop()
+ if END in cur:
+ word = words[cur[END]]
+ if len(word) > len(ans) or len(word) == len(ans) and word < ans:
+ ans = word
+ stack.extend([cur[letter] for letter in cur if letter != END])
+ return ans
diff --git a/python/724_Find_Pivot_Index.py b/python/724_Find_Pivot_Index.py
new file mode 100644
index 0000000..4581b29
--- /dev/null
+++ b/python/724_Find_Pivot_Index.py
@@ -0,0 +1,14 @@
+class Solution(object):
+ def pivotIndex(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ totalsum = sum(nums)
+ leftsum = 0
+ for i, v in enumerate(nums):
+ # leftsum == rightsum
+ if leftsum == totalsum - leftsum - v:
+ return i
+ leftsum += v
+ return -1
diff --git a/python/728_Self_Dividing_Numbers.py b/python/728_Self_Dividing_Numbers.py
new file mode 100644
index 0000000..f7e0bac
--- /dev/null
+++ b/python/728_Self_Dividing_Numbers.py
@@ -0,0 +1,7 @@
+class Solution:
+ def selfDividingNumbers(self, left: int, right: int) -> List[int]:
+ # check every digit
+ return [x for x in range(left, right+1) if all([int(i) != 0 and x % int(i)==0 for i in str(x)])]
+
+ # def selfDividingNumbers(self, left: int, right: int) -> List[int]:
+ # return [x for x in range(left, right+1) if all((i and (x % i==0) for i in map(int, str(x))))]
diff --git a/python/732_My_Calendar_III.py b/python/732_My_Calendar_III.py
new file mode 100644
index 0000000..6347108
--- /dev/null
+++ b/python/732_My_Calendar_III.py
@@ -0,0 +1,17 @@
+from sortedcontainers import SortedDict
+
+
+class MyCalendarThree:
+ def __init__(self):
+ self.timeline = SortedDict()
+
+ def book(self, start: int, end: int) -> int:
+ self.timeline[start] = self.timeline.get(start, 0) + 1
+ self.timeline[end] = self.timeline.get(end, 0) - 1
+
+ ans = 0
+ activeEvents = 0
+
+ for count in self.timeline.values():
+ activeEvents += count
+ ans = max(ans, activeEvents)
diff --git a/python/733_Flood_Fill.py b/python/733_Flood_Fill.py
new file mode 100644
index 0000000..db871a2
--- /dev/null
+++ b/python/733_Flood_Fill.py
@@ -0,0 +1,41 @@
+class Solution(object):
+ # def floodFill(self, image, sr, sc, newColor):
+ # """
+ # :type image: List[List[int]]
+ # :type sr: int
+ # :type sc: int
+ # :type newColor: int
+ # :rtype: List[List[int]]
+ # """
+ # r_ls, c_ls = len(image), len(image[0])
+ # color = image[sr][sc]
+ # if color == newColor:
+ # return image
+
+ # def dfs(r, c):
+ # if image[r][c] == color:
+ # image[r][c] = newColor
+ # if r - 1 >= 0: dfs(r - 1, c)
+ # if r + 1 < r_ls: dfs(r + 1, c)
+ # if c - 1 >= 0: dfs(r, c - 1)
+ # if c + 1 < c_ls: dfs(r, c + 1)
+
+ # dfs(sr, sc)
+ # return image
+
+ def floodFill(self, image, sr, sc, newColor):
+ # BFS with queue
+ r_ls, c_ls = len(image), len(image[0])
+ color = image[sr][sc]
+ if color == newColor:
+ return image
+ queue = [(sr, sc)]
+ while len(queue) > 0:
+ r, c = queue.pop(0)
+ if image[r][c] == color:
+ image[r][c] = newColor
+ if r - 1 >= 0: queue.append((r - 1, c))
+ if r + 1 < r_ls: queue.append((r + 1, c))
+ if c - 1 >= 0: queue.append((r, c - 1))
+ if c + 1 < c_ls: queue.append((r, c + 1))
+ return image
diff --git a/python/743_Network_Delay_Time.py b/python/743_Network_Delay_Time.py
new file mode 100644
index 0000000..72af66c
--- /dev/null
+++ b/python/743_Network_Delay_Time.py
@@ -0,0 +1,44 @@
+class Solution(object):
+ # def networkDelayTime(self, times, N, K):
+ # # DFS
+ # graph = collections.defaultdict(list)
+ # for u, v, w in times:
+ # graph[u].append((w, v))
+
+ # dist = {node: float('inf') for node in xrange(1, N + 1)}
+
+ # def dfs(node, elapsed):
+ # if elapsed >= dist[node]: return
+ # dist[node] = elapsed
+ # for time, nei in sorted(graph[node]):
+ # dfs(nei, elapsed + time)
+
+ # dfs(K, 0)
+ # ans = max(dist.values())
+ # return ans if ans < float('inf') else -1
+
+ def networkDelayTime(self, times, N, K):
+ # Dijkstra
+ graph = collections.defaultdict(list)
+ for u, v, w in times:
+ graph[u].append((v, w))
+
+ dist = {node: float('inf') for node in xrange(1, N + 1)}
+ seen = [False] * (N + 1)
+ dist[K] = 0
+
+ while True:
+ cand_node = -1
+ cand_dist = float('inf')
+ for i in xrange(1, N + 1):
+ if not seen[i] and dist[i] < cand_dist:
+ cand_dist = dist[i]
+ cand_node = i
+
+ if cand_node < 0: break
+ seen[cand_node] = True
+ for nei, d in graph[cand_node]:
+ dist[nei] = min(dist[nei], dist[cand_node] + d)
+
+ ans = max(dist.values())
+ return ans if ans < float('inf') else -1
diff --git a/python/751_IP_to_CIDR.py b/python/751_IP_to_CIDR.py
new file mode 100644
index 0000000..cf4c7b1
--- /dev/null
+++ b/python/751_IP_to_CIDR.py
@@ -0,0 +1,23 @@
+class Solution(object):
+ def ipToInt(self, ip):
+ ans = 0
+ for x in ip.split('.'):
+ ans = 256 * ans + int(x)
+ return ans
+
+ def intToIP(self, x):
+ return ".".join(str((x >> i) % 256)
+ for i in (24, 16, 8, 0))
+
+ def ipToCIDR(self, ip, n):
+ # Start value of IP
+ start = self.ipToInt(ip)
+ ans = []
+ while n:
+ # Last 1 of start or can start from 0
+ mask = max(33 - (start & -start).bit_length(),
+ 33 - n.bit_length())
+ ans.append(self.intToIP(start) + '/' + str(mask))
+ start += 1 << (32 - mask)
+ n -= 1 << (32 - mask)
+ return ans
diff --git a/python/760_Find_Anagram_Mappings.py b/python/760_Find_Anagram_Mappings.py
new file mode 100644
index 0000000..23d5f0f
--- /dev/null
+++ b/python/760_Find_Anagram_Mappings.py
@@ -0,0 +1,14 @@
+class Solution(object):
+ def anagramMappings(self, A, B):
+ """
+ :type A: List[int]
+ :type B: List[int]
+ :rtype: List[int]
+ """
+ val_index = {}
+ ans = []
+ for i, n in enumerate(B):
+ val_index[n] = i
+ for n in A:
+ ans.append(val_index[n])
+ return ans
diff --git a/python/766_Toeplitz_Matrix.py b/python/766_Toeplitz_Matrix.py
new file mode 100644
index 0000000..8790a92
--- /dev/null
+++ b/python/766_Toeplitz_Matrix.py
@@ -0,0 +1,12 @@
+class Solution(object):
+ def isToeplitzMatrix(self, matrix):
+ """
+ :type matrix: List[List[int]]
+ :rtype: bool
+ """
+ # Actually, we don't need to check the last row and column
+ for r in range(len(matrix) - 1):
+ for c in range(len(matrix[0]) - 1):
+ if matrix[r][c] != matrix[r + 1][c + 1]:
+ return False
+ return True
diff --git a/python/771_Jewels_and_Stones.py b/python/771_Jewels_and_Stones.py
new file mode 100644
index 0000000..ad34684
--- /dev/null
+++ b/python/771_Jewels_and_Stones.py
@@ -0,0 +1,15 @@
+class Solution(object):
+ def numJewelsInStones(self, J, S):
+ """
+ :type J: str
+ :type S: str
+ :rtype: int
+ """
+ if len(J) == 0 or len(S) == 0:
+ return 0
+ j_set = set(J)
+ ans = 0
+ for c in S:
+ if c in j_set:
+ ans += 1
+ return ans
diff --git a/python/784_Letter_Case_Permutation.py b/python/784_Letter_Case_Permutation.py
new file mode 100644
index 0000000..1466b2b
--- /dev/null
+++ b/python/784_Letter_Case_Permutation.py
@@ -0,0 +1,39 @@
+class Solution(object):
+ # def letterCasePermutation(self, S):
+ # ans = [[]]
+
+ # for char in S:
+ # n = len(ans)
+ # if char.isalpha():
+ # # Double the ans
+ # for i in xrange(n):
+ # ans.append(ans[i][:])
+ # ans[i].append(char.lower())
+ # ans[n + i].append(char.upper())
+ # else:
+ # # Normal append
+ # for i in xrange(n):
+ # ans[i].append(char)
+
+ # return map("".join, ans)
+
+ def letterCasePermutation(self, S):
+ B = sum(letter.isalpha() for letter in S)
+ ans = []
+
+ for bits in xrange(1 << B):
+ b = 0
+ word = []
+ for letter in S:
+ if letter.isalpha():
+ if (bits >> b) & 1:
+ word.append(letter.lower())
+ else:
+ word.append(letter.upper())
+
+ b += 1
+ else:
+ word.append(letter)
+
+ ans.append("".join(word))
+ return ans
diff --git a/python/804_Unique_Morse_Code_Words.py b/python/804_Unique_Morse_Code_Words.py
new file mode 100644
index 0000000..714a3b7
--- /dev/null
+++ b/python/804_Unique_Morse_Code_Words.py
@@ -0,0 +1,24 @@
+Morse_tab = [".-","-...","-.-.",
+ "-..",".","..-.","--.","....",
+ "..",".---","-.-",".-..","--",
+ "-.","---",".--.","--.-",".-.",
+ "...","-","..-","...-",".--",
+ "-..-","-.--","--.."]
+
+class Solution(object):
+ # https://leetcode.com/problems/unique-morse-code-words/solution/
+ def uniqueMorseRepresentations(self, words):
+ """
+ :type words: List[str]
+ :rtype: int
+ """
+ if len(words) == 0:
+ return 0
+ ans_set = set()
+ for word in words:
+ morsed = ""
+ for c in word:
+ morsed += Morse_tab[ord(c) - ord('a')]
+
+ ans_set.add(morsed)
+ return len(ans_set)
diff --git a/python/811_Subdomain_Visit_Count.py b/python/811_Subdomain_Visit_Count.py
new file mode 100644
index 0000000..40b4c40
--- /dev/null
+++ b/python/811_Subdomain_Visit_Count.py
@@ -0,0 +1,24 @@
+class Solution(object):
+ def subdomainVisits(self, cpdomains):
+ """
+ :type cpdomains: List[str]
+ :rtype: List[str]
+ """
+ domain_count = {}
+ for cpdomain in cpdomains:
+ count, domain = cpdomain.split(' ')
+ sub_domain = domain.split('.')
+ for i in range(len(sub_domain)):
+ curr = '.'.join(sub_domain[i:])
+ domain_count[curr] = domain_count.get(curr, 0) + int(count)
+ return [str(v) + ' ' + k for k, v in domain_count.items()]
+
+
+ # def subdomainVisits(self, cpdomains):
+ # # https://leetcode.com/problems/subdomain-visit-count/discuss/121770/Python-short-and-understandable-solution-68-ms
+ # counter = collections.Counter()
+ # for cpdomain in cpdomains:
+ # count, *domains = cpdomain.replace(" ",".").split(".")
+ # for i in range(len(domains)):
+ # counter[".".join(domains[i:])] += int(count)
+ # return [" ".join((str(v), k)) for k, v in counter.items()]
diff --git a/python/819_Most_Common_Word.py b/python/819_Most_Common_Word.py
new file mode 100644
index 0000000..c81b896
--- /dev/null
+++ b/python/819_Most_Common_Word.py
@@ -0,0 +1,13 @@
+class Solution(object):
+ def mostCommonWord(self, paragraph, banned):
+ """
+ :type paragraph: str
+ :type banned: List[str]
+ :rtype: str
+ """
+ # https://leetcode.com/problems/most-common-word/discuss/193268/python-one-liner
+ banned = set(banned)
+ count = collections.Counter(word for word in re.split('[ !?\',;.]',
+ paragraph.lower()) if word)
+ return max((item for item in count.items() if item[0] not in banned),
+ key=operator.itemgetter(1))[0]
diff --git a/python/832_Flipping_an_Image.py b/python/832_Flipping_an_Image.py
new file mode 100644
index 0000000..3494f2f
--- /dev/null
+++ b/python/832_Flipping_an_Image.py
@@ -0,0 +1,11 @@
+class Solution(object):
+ def flipAndInvertImage(self, A):
+ for row in A:
+ for i in xrange((len(row) + 1) / 2):
+ """
+ In Python, the shortcut row[~i] = row[-i-1] = row[len(row) - 1 - i]
+ helps us find the i-th value of the row, counting from the right.
+ """
+ row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1
+ return A
+ # return [[1 ^ i for i in row[::-1]] for row in A]
diff --git a/python/836_Rectangle_Overlap.py b/python/836_Rectangle_Overlap.py
new file mode 100644
index 0000000..6ebf235
--- /dev/null
+++ b/python/836_Rectangle_Overlap.py
@@ -0,0 +1,17 @@
+class Solution(object):
+ def isRectangleOverlap(self, rec1, rec2):
+ """
+ :type rec1: List[int]
+ :type rec2: List[int]
+ :rtype: bool
+ """
+ return not (rec1[2] <= rec2[0] or # left
+ rec1[3] <= rec2[1] or # bottom
+ rec1[0] >= rec2[2] or # right
+ rec1[1] >= rec2[3]) # top
+
+ # def isRectangleOverlap(self, rec1, rec2):
+ # def intersect(p_left, p_right, q_left, q_right):
+ # return min(p_right, q_right) > max(p_left, q_left)
+ # return (intersect(rec1[0], rec1[2], rec2[0], rec2[2]) and
+ # intersect(rec1[1], rec1[3], rec2[1], rec2[3]))
diff --git a/python/844_Backspace_String_Compare.py b/python/844_Backspace_String_Compare.py
new file mode 100644
index 0000000..89e7a80
--- /dev/null
+++ b/python/844_Backspace_String_Compare.py
@@ -0,0 +1,49 @@
+class Solution(object):
+ def backspaceCompare(self, S, T):
+ """
+ :type S: str
+ :type T: str
+ :rtype: bool
+ """
+ if S == T:
+ return True
+ s_stack = []
+ t_stack = []
+ for c in S:
+ if c != '#':
+ s_stack.append(c)
+ elif len(s_stack) != 0:
+ s_stack.pop(-1)
+ for c in T:
+ if c != '#':
+ t_stack.append(c)
+ elif len(t_stack) != 0:
+ t_stack.pop(-1)
+ return ''.join(s_stack) == ''.join(t_stack)
+
+ # def backspaceCompare(self, S, T):
+ # # https://leetcode.com/problems/backspace-string-compare/discuss/135603/C%2B%2BJavaPython-O(N)-time-and-O(1)-space
+ # back = lambda res, c: res[:-1] if c == '#' else res + c
+ # return reduce(back, S, "") == reduce(back, T, "")
+
+ # def backspaceCompare(self, S, T):
+ # def back(res, c):
+ # if c != '#': res.append(c)
+ # elif res: res.pop()
+ # return res
+ # return reduce(back, S, []) == reduce(back, T, [])
+
+
+ # def backspaceCompare(self, S, T):
+ # i, j = len(S) - 1, len(T) - 1
+ # backS = backT = 0
+ # while True:
+ # while i >= 0 and (backS or S[i] == '#'):
+ # backS += 1 if S[i] == '#' else -1
+ # i -= 1
+ # while j >= 0 and (backT or T[j] == '#'):
+ # backT += 1 if T[j] == '#' else -1
+ # j -= 1
+ # if not (i >= 0 and j >= 0 and S[i] == T[j]):
+ # return i == j == -1
+ # i, j = i - 1, j - 1
diff --git a/python/852_Peak_Index_in_a_Mountain_Array.py b/python/852_Peak_Index_in_a_Mountain_Array.py
new file mode 100644
index 0000000..406691a
--- /dev/null
+++ b/python/852_Peak_Index_in_a_Mountain_Array.py
@@ -0,0 +1,20 @@
+class Solution(object):
+ # def peakIndexInMountainArray(self, A):
+ # """
+ # :type A: List[int]
+ # :rtype: int
+ # """
+ # i = 0
+ # while A[i + 1] >= A[i]:
+ # i += 1
+ # return i
+
+ def peakIndexInMountainArray(self, A):
+ lo, hi = 0, len(A) - 1
+ while lo < hi:
+ mid = (lo + hi) / 2
+ if A[mid] < A[mid + 1]:
+ lo = mid + 1
+ else:
+ hi = mid
+ return lo
diff --git a/python/867_Transpose_Matrix.py b/python/867_Transpose_Matrix.py
new file mode 100644
index 0000000..61b3ded
--- /dev/null
+++ b/python/867_Transpose_Matrix.py
@@ -0,0 +1,23 @@
+class Solution(object):
+ def transpose(self, A):
+ """
+ :type A: List[List[int]]
+ :rtype: List[List[int]]
+ """
+ R, C = len(A), len(A[0])
+ ans = [[None] * R for _ in xrange(C)]
+ for r, row in enumerate(A):
+ for c, val in enumerate(row):
+ ans[c][r] = val
+ return ans
+ # Alternative Solution:
+ # return zip(*A)
+
+ # def transpose(self, A):
+ # res = []
+ # for i in range(len(A[0])):
+ # temp = []
+ # for j in range(len(A)):
+ # temp.append(A[j][i])
+ # res.append(temp)
+ # return res
diff --git a/python/868_Binary_Gap.py b/python/868_Binary_Gap.py
new file mode 100644
index 0000000..191d3d1
--- /dev/null
+++ b/python/868_Binary_Gap.py
@@ -0,0 +1,34 @@
+class Solution:
+
+ # def binaryGap(self, n: int) -> int:
+ # # Store index
+ # A = [i for i in xrange(32) if (N >> i) & 1]
+ # if len(A) < 2: return 0
+ # return max(A[i+1] - A[i] for i in xrange(len(A) - 1))
+
+
+ def binaryGap(self, n: int) -> int:
+ # one pass and store max
+ current = 1
+ last1 = -1
+ out = 0
+ while n > 0:
+ if n % 2 == 1:
+ if last1 >= 1:
+ out = max(out, current - last1)
+ last1 = current
+ current += 1
+ n = n // 2
+ return out
+
+ # def binaryGap(self, n: int) -> int:
+ # # one pass and store max
+ # res = 0
+ # last = -1
+ # # Get binary encoding with bin
+ # for i, curr in enumerate(bin(n)[2:]):
+ # if curr == '1':
+ # if last >= 0:
+ # res = max(res, i - last)
+ # last = i
+ # return res
diff --git a/python/872_Leaf-Similar_Trees.py b/python/872_Leaf-Similar_Trees.py
new file mode 100644
index 0000000..6b3c7b2
--- /dev/null
+++ b/python/872_Leaf-Similar_Trees.py
@@ -0,0 +1,31 @@
+# Definition for a binary tree node.
+# class TreeNode(object):
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+class Solution(object):
+ def leafSimilar(self, root1, root2):
+ """
+ :type root1: TreeNode
+ :type root2: TreeNode
+ :rtype: bool
+ """
+ if not root1 and not root2:
+ return True
+ leaf1 = []
+ leaf2 = []
+ self.dfs(root1, leaf1)
+ self.dfs(root2, leaf2)
+ if leaf1 == leaf2:
+ return True
+ return False
+
+ def dfs(self, node, leavels):
+ if not node:
+ return
+ if not node.left and not node.right:
+ leavels.append(node.val)
+ self.dfs(node.left, leavels)
+ self.dfs(node.right, leavels)
diff --git a/python/876_Middle_of_the_Linked_List.py b/python/876_Middle_of_the_Linked_List.py
new file mode 100644
index 0000000..845caaa
--- /dev/null
+++ b/python/876_Middle_of_the_Linked_List.py
@@ -0,0 +1,25 @@
+# Definition for singly-linked list.
+# class ListNode(object):
+# def __init__(self, x):
+# self.val = x
+# self.next = None
+
+class Solution(object):
+ # def middleNode(self, head):
+ # """
+ # :type head: ListNode
+ # :rtype: ListNode
+ # """
+ # res = []
+ # while head:
+ # res.append(head)
+ # head = head.next
+ # return res[len(res) / 2]
+
+ def middleNode(self, head):
+ # Fast point is 2 times faster than slow point
+ fast = slow = head
+ while fast and fast.next:
+ slow = slow.next
+ fast = fast.next.next
+ return slow
diff --git a/python/904_Fruit_Into_Baskets.py b/python/904_Fruit_Into_Baskets.py
new file mode 100644
index 0000000..27d393c
--- /dev/null
+++ b/python/904_Fruit_Into_Baskets.py
@@ -0,0 +1,57 @@
+class Solution(object):
+ # def totalFruit(self, tree):
+ # """
+ # :type tree: List[int]
+ # :rtype: int
+ # """
+ # basket, res, start = 2, 0, 0
+ # queue_map = {}
+ # for i, v in enumerate(tree):
+ # queue_map[v] = queue_map.get(v, 0) + 1
+ # if len(queue_map) > 2:
+ # queue_map[tree[start]] -= 1
+ # if queue_map[tree[start]] == 0:
+ # del queue_map[tree[start]]
+ # start += 1
+ # res = max(res, i - start + 1)
+ # return res
+
+ # https://leetcode.com/problems/fruit-into-baskets/solution/
+ # def totalFruit(self, tree):
+ # blocks = [(k, len(list(v)))
+ # for k, v in itertools.groupby(tree)]
+ # ans = i = 0
+ # while i < len(blocks):
+ # # We'll start our scan at block[i].
+ # # types : the different values of tree[i] seen
+ # # weight : the total number of trees represented
+ # # by blocks under consideration
+ # types, weight = set(), 0
+
+ # # For each block from i and going forward,
+ # for j in xrange(i, len(blocks)):
+ # # Add each block to consideration
+ # types.add(blocks[j][0])
+ # weight += blocks[j][1]
+ # # If we have 3 types, this is not a legal subarray
+ # if len(types) >= 3:
+ # i = j-1
+ # break
+ # ans = max(ans, weight)
+ # # If we go to the last block, then stop
+ # else:
+ # break
+ # return ans
+
+ def totalFruit(self, tree):
+ ans = i = 0
+ count = collections.Counter()
+ for j, x in enumerate(tree):
+ count[x] += 1
+ while len(count) >= 3:
+ count[tree[i]] -= 1
+ if count[tree[i]] == 0:
+ del count[tree[i]]
+ i += 1
+ ans = max(ans, j - i + 1)
+ return ans
diff --git a/python/905_Sort_Array_By_Parity.py b/python/905_Sort_Array_By_Parity.py
new file mode 100644
index 0000000..e742e79
--- /dev/null
+++ b/python/905_Sort_Array_By_Parity.py
@@ -0,0 +1,23 @@
+class Solution(object):
+ # def sortArrayByParity(self, A):
+ # """
+ # :type A: List[int]
+ # :rtype: List[int]
+ # """
+ # # Bad idea, O(nlogn)
+ # A.sort(key=lambda x: x % 2)
+ # return A
+
+ # def sortArrayByParity(self, A):
+ # return ([x for x in A if x % 2 == 0] +
+ # [x for x in A if x % 2 == 1])
+
+ def sortArrayByParity(self, A):
+ # Quit like quick sort or quick selection
+ lo, hi = 0, len(A) - 1
+ while lo < hi:
+ if A[lo] % 2 > A[hi] % 2:
+ A[lo], A[hi] = A[hi], A[lo]
+ if A[lo] % 2 == 0: lo += 1
+ if A[hi] % 2 == 1: hi -= 1
+ return A
diff --git a/python/922_Sort_Array_By_Parity_II.py b/python/922_Sort_Array_By_Parity_II.py
new file mode 100644
index 0000000..abae34b
--- /dev/null
+++ b/python/922_Sort_Array_By_Parity_II.py
@@ -0,0 +1,27 @@
+class Solution(object):
+ # def sortArrayByParityII(self, A):
+ # N = len(A)
+ # ans = [None] * N
+ # t = 0
+ # for i, x in enumerate(A):
+ # if x % 2 == 0:
+ # ans[t] = x
+ # t += 2
+ # t = 1
+ # for i, x in enumerate(A):
+ # if x % 2 == 1:
+ # ans[t] = x
+ # t += 2
+ # # We could have also used slice assignment:
+ # # ans[::2] = (x for x in A if x % 2 == 0)
+ # # ans[1::2] = (x for x in A if x % 2 == 1)
+ # return ans
+
+ def sortArrayByParityII(self, A):
+ odd = 1
+ for i in xrange(0, len(A), 2):
+ if A[i] % 2:
+ while A[odd] % 2:
+ odd += 2
+ A[i], A[odd] = A[odd], A[i]
+ return A
diff --git a/python/929_Unique_Email_Addresses.py b/python/929_Unique_Email_Addresses.py
new file mode 100644
index 0000000..ca434f2
--- /dev/null
+++ b/python/929_Unique_Email_Addresses.py
@@ -0,0 +1,11 @@
+class Solution(object):
+ def numUniqueEmails(self, emails):
+ """
+ :type emails: List[str]
+ :rtype: int
+ """
+ email_set = set()
+ for email in emails:
+ elements = email.split('@')
+ email_set.add(elements[0].split('+')[0].replace('.', '') + elements[1])
+ return len(email_set)
diff --git a/python/933_Number_of_Recent_Calls.py b/python/933_Number_of_Recent_Calls.py
new file mode 100644
index 0000000..4f00f4d
--- /dev/null
+++ b/python/933_Number_of_Recent_Calls.py
@@ -0,0 +1,19 @@
+class RecentCounter(object):
+
+ def __init__(self):
+ self.queue = []
+
+ def ping(self, t):
+ """
+ :type t: int
+ :rtype: int
+ """
+ self.queue.append(t)
+ while self.queue and self.queue[0] < t - 3000:
+ self.queue.pop(0)
+ return len(self.queue)
+
+
+# Your RecentCounter object will be instantiated and called as such:
+# obj = RecentCounter()
+# param_1 = obj.ping(t)
diff --git a/python/937_Reorder_Log_Files.py b/python/937_Reorder_Log_Files.py
new file mode 100644
index 0000000..4d2c6ba
--- /dev/null
+++ b/python/937_Reorder_Log_Files.py
@@ -0,0 +1,23 @@
+class Solution(object):
+ # def reorderLogFiles(self, logs):
+ # """
+ # :type logs: List[str]
+ # :rtype: List[str]
+ # """
+ # def f(log):
+ # id_, rest = log.split(" ", 1)
+ # return (0, rest, id_) if rest[0].isalpha() else (1,)
+
+ # # Python sort is stable, so digit with keep their order
+ # return sorted(logs, key = f)
+
+ def reorderLogFiles(self, logs):
+ letter_logs = []
+ digit_logs = []
+ for log in logs:
+ if log.split(' ')[1].isnumeric():
+ digit_logs.append(log)
+ else:
+ letter_logs.append(log)
+ return sorted(letter_logs, key=lambda x: x.split(' ')[1:] + x.split(' ')[0]) + digit_logs
+
\ No newline at end of file
diff --git a/python/945_Minimum_Increment_to_Make_Array_Unique.py b/python/945_Minimum_Increment_to_Make_Array_Unique.py
new file mode 100644
index 0000000..b559564
--- /dev/null
+++ b/python/945_Minimum_Increment_to_Make_Array_Unique.py
@@ -0,0 +1,37 @@
+class Solution(object):
+ def minIncrementForUnique(self, A):
+ """
+ :type A: List[int]
+ :rtype: int
+ """
+ if A is None or len(A) == 0:
+ return 0
+ res = 0
+ num_set = set()
+ duplicate = []
+ A.sort()
+ left, right = A[0], A[-1]
+ holes = right - left + 1
+ for v in A:
+ if v in num_set:
+ duplicate.append(v)
+ else:
+ num_set.add(v)
+ holes = holes - len(num_set)
+ # find a hole for these numbers
+ for hole in range(left + 1, right):
+ if holes == 0 or len(duplicate) == 0:
+ break
+ if hole not in num_set and hole > duplicate[0]:
+ res += hole - duplicate.pop(0)
+ holes -= 1
+ while len(duplicate) != 0:
+ right += 1
+ res += right - duplicate.pop(0)
+ return res
+
+
+if __name__ == '__main__':
+ s = Solution()
+ # print s.minIncrementForUnique([3, 2, 1, 2, 1, 7])
+ # print s.minIncrementForUnique([0, 2, 2])
diff --git a/python/946_Validate_Stack_Sequences.py b/python/946_Validate_Stack_Sequences.py
new file mode 100644
index 0000000..7fa1c31
--- /dev/null
+++ b/python/946_Validate_Stack_Sequences.py
@@ -0,0 +1,34 @@
+class Solution(object):
+ def validateStackSequences(self, pushed, popped):
+ """
+ :type pushed: List[int]
+ :type popped: List[int]
+ :rtype: bool
+ """
+ in_stack = []
+ pos = 0
+ while pos != len(pushed):
+ curr = pushed[pos]
+ while len(in_stack) > 0 and len(popped) > 0 and in_stack[-1] == popped[0]:
+ in_stack.pop(-1)
+ popped.pop(0)
+ if len(popped) == 0:
+ break
+ if curr == popped[0]:
+ popped.pop(0)
+ else:
+ in_stack.append(curr)
+ pos += 1
+ while len(in_stack) > 0 and len(popped) > 0 and in_stack[-1] == popped[0]:
+ in_stack.pop(-1)
+ popped.pop(0)
+ if len(in_stack) == 0:
+ return True
+ return False
+
+
+if __name__ == '__main__':
+ s = Solution()
+ # print s.validateStackSequences([1, 2, 3, 4, 5], [4, 5, 3, 2, 1])
+ # print s.validateStackSequences([2, 1, 0], [1, 2, 0])
+ print s.validateStackSequences([1, 0, 3, 2], [0, 1, 2, 3])
diff --git a/python/953_Verifying_an_Alien_Dictionary.py b/python/953_Verifying_an_Alien_Dictionary.py
new file mode 100644
index 0000000..706fe47
--- /dev/null
+++ b/python/953_Verifying_an_Alien_Dictionary.py
@@ -0,0 +1,32 @@
+class Solution(object):
+ def isAlienSorted(self, words, order):
+ """
+ :type words: List[str]
+ :type order: str
+ :rtype: bool
+ """
+ order_map = {}
+ for i, v in enumerate(order):
+ order_map[v] = i
+
+ def cmp_alien(x, y):
+ ls = min(len(x), len(y))
+ index = 0
+ while index < ls:
+ if x[index] != y[index]:
+ return order_map[x[index]] - order_map[y[index]]
+ index += 1
+ return len(x) - len(y)
+ pos = 0
+ while pos + 1 < len(words):
+ if cmp_alien(words[pos], words[pos + 1]) > 0:
+ return False
+ pos += 1
+ return True
+
+
+if __name__ == '__main__':
+ s = Solution()
+ print s.isAlienSorted(["hello","leetcode"], "hlabcdefgijkmnopqrstuvwxyz")
+ print s.isAlienSorted(["word","world","row"], "worldabcefghijkmnpqstuvxyz")
+ print s.isAlienSorted(["apple","app"], "abcdefghijklmnopqrstuvwxyz")
diff --git a/python/954_Array_of_Doubled_Pairs.py b/python/954_Array_of_Doubled_Pairs.py
new file mode 100644
index 0000000..4c052d5
--- /dev/null
+++ b/python/954_Array_of_Doubled_Pairs.py
@@ -0,0 +1,27 @@
+class Solution(object):
+ def canReorderDoubled(self, A):
+ """
+ :type A: List[int]
+ :rtype: bool
+ """
+ v_map = {}
+ A.sort(key=lambda x: abs(x))
+ for n in A:
+ v_map[n] = v_map.get(n, 0) + 1
+ for n in A:
+ if v_map[n] <= 0:
+ continue
+ if 2 * n in v_map and v_map[2 * n] > 0:
+ v_map[n] -= 1
+ v_map[2 * n] -= 1
+ else:
+ return False
+ return True
+
+
+if __name__ == '__main__':
+ s = Solution()
+ print s.canReorderDoubled([3, 1, 3, 6])
+ print s.canReorderDoubled([2, 1, 2, 6])
+ print s.canReorderDoubled([4, -2, 2, -4])
+ print s.canReorderDoubled([1, 2, 4, 16, 8, 4])
diff --git a/python/961_N-Repeated_Element_in_Size_2N_Array.py b/python/961_N-Repeated_Element_in_Size_2N_Array.py
new file mode 100644
index 0000000..4fa27e2
--- /dev/null
+++ b/python/961_N-Repeated_Element_in_Size_2N_Array.py
@@ -0,0 +1,18 @@
+import collections
+
+
+class Solution(object):
+ def repeatedNTimes(self, A):
+ """
+ :type A: List[int]
+ :rtype: int
+ """
+ counter = collections.Counter(A)
+ return counter.most_common(1)[0][0]
+
+
+if __name__ == '__main__':
+ s = Solution()
+ print s.repeatedNTimes([1, 2, 3, 3])
+ print s.repeatedNTimes([2, 1, 2, 5, 3, 2])
+ print s.repeatedNTimes([5, 1, 5, 2, 5, 3, 5, 4])
diff --git a/python/962_Maximum_Width_Ramp.py b/python/962_Maximum_Width_Ramp.py
new file mode 100644
index 0000000..21ad68d
--- /dev/null
+++ b/python/962_Maximum_Width_Ramp.py
@@ -0,0 +1,46 @@
+class Solution(object):
+ # def maxWidthRamp(self, A):
+ # """
+ # :type A: List[int]
+ # :rtype: int
+ # """
+ # # TLE
+ # if not A or len(A) == 0:
+ # return 0
+ # for ans in range(len(A) - 1, 0, -1):
+ # for i in range(len(A)):
+ # if i + ans > len(A) - 1:
+ # break
+ # if (A[i + ans] >= A[i]):
+ # return ans
+ # return 0
+
+ def maxWidthRamp(self, A):
+ ans = 0
+ m = float('inf')
+ # Sort index based on value
+ for i in sorted(range(len(A)), key=A.__getitem__):
+ ans = max(ans, i - m)
+ m = min(m, i)
+ return ans
+
+
+ # def maxWidthRamp(self, A):
+ # N = len(A)
+ # ans = 0
+ # candidates = [(A[N - 1], N - 1)]
+ # # candidates: i's decreasing, by increasing value of A[i]
+ # for i in xrange(N - 2, -1, -1):
+ # # Find largest j in candidates with A[j] >= A[i]
+ # jx = bisect.bisect(candidates, (A[i],))
+ # if jx < len(candidates):
+ # ans = max(ans, candidates[jx][1] - i)
+ # else:
+ # candidates.append((A[i], i))
+ # return ans
+
+
+if __name__ == '__main__':
+ s = Solution()
+ print s.maxWidthRamp([6, 0, 8, 2, 1, 5])
+ print s.maxWidthRamp([9, 8, 1, 0, 1, 9, 4, 0, 4, 1])
diff --git a/python/973_K_Closest_Points_to_Origin.py b/python/973_K_Closest_Points_to_Origin.py
new file mode 100644
index 0000000..b8240b9
--- /dev/null
+++ b/python/973_K_Closest_Points_to_Origin.py
@@ -0,0 +1,13 @@
+class Solution(object):
+ # def kClosest(self, points, K):
+ # """
+ # :type points: List[List[int]]
+ # :type K: int
+ # :rtype: List[List[int]]
+ # """
+ # # Sort
+ # return sorted(points, key=lambda x: x[0] ** 2 + x[1] ** 2)[:K]
+
+ def kClosest(self, points, K):
+ # K smallest heaq
+ return heapq.nsmallest(K, points, key=lambda x: x[0] ** 2 + x[1] ** 2)
diff --git a/python/977_Squares_of_a_Sorted_Array.py b/python/977_Squares_of_a_Sorted_Array.py
new file mode 100644
index 0000000..3c66191
--- /dev/null
+++ b/python/977_Squares_of_a_Sorted_Array.py
@@ -0,0 +1,31 @@
+class Solution(object):
+ # def sortedSquares(self, A):
+ # """
+ # :type A: List[int]
+ # :rtype: List[int]
+ # """
+ # # Directly sort
+ # return sorted(x * x for x in A)
+
+ def sortedSquares(self, A):
+ pos = 0
+ while pos < len(A) and A[pos] < 0:
+ pos += 1
+ # pos point to first positve
+ # npos point to larget negative
+ npos = pos - 1
+ res = []
+ while pos < len(A) and npos >= 0:
+ if A[npos] ** 2 < A[pos] ** 2:
+ res.append(A[npos] ** 2)
+ npos -= 1
+ else:
+ res.append(A[pos] ** 2)
+ pos +=1
+ while npos >= 0:
+ res.append(A[npos] ** 2)
+ npos -= 1
+ while pos < len(A):
+ res.append(A[pos] ** 2)
+ pos += 1
+ return res
diff --git a/python/981_Time_Based_Store.py b/python/981_Time_Based_Store.py
new file mode 100644
index 0000000..3320458
--- /dev/null
+++ b/python/981_Time_Based_Store.py
@@ -0,0 +1,26 @@
+from collections import defaultdict
+
+class TimeMap(object):
+
+ def __init__(self):
+ self.store = defaultdict(list)
+
+ def set(self, key, value, timestamp):
+ self.store[key].append((value, timestamp))
+
+ def get(self, key, timestamp):
+ values = self.store.get(key, [])
+ res = ""
+
+ l = 0
+ r = len(values) - 1
+
+ while l <= r:
+ mid = (l + r) // 2
+ if values[mid][1] <= timestamp:
+ l = mid + 1
+ res = values[mid][0]
+ else:
+ r = mid - 1
+
+ return res
diff --git a/python/997_Find_The_Town_Judge.py b/python/997_Find_The_Town_Judge.py
new file mode 100644
index 0000000..57e8ecd
--- /dev/null
+++ b/python/997_Find_The_Town_Judge.py
@@ -0,0 +1,21 @@
+class Solution:
+ def findJudge(self, N: int, trust: List[List[int]]) -> int:
+ if N==1:
+ return 1
+ d1={}
+ d2={}
+ for i, j in trust:
+ if j in d1:
+ d1[j]+=1
+ else:
+ d1[j]=1
+ if i in d2:
+ d2[i]+=1
+ else:
+ d2[i]=1
+ for i,j in d1.items():
+ if j==N-1:
+ if i not in d2:
+ return i
+ return -1
+