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 b932ab6..c34ae3b 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,12 @@
# Python & JAVA Solutions for Leetcode (inspired by [haoel's leetcode](https://github.com/haoel/leetcode))
-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).
+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).
+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.
@@ -16,11 +20,13 @@ Also, there are open source implementations for basic data structs and algorithm
| 7 | [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/007_Reverse_Integer.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/007_Reverse_Integer.java) | Overflow when the result is greater than 2147483647 or less than -2147483648.
| 8 | [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/008_String_to_Integer(atoi).py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/008_String_to_Integer(atoi).java) | Overflow, Space, and negative number |
| 9 | [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/009_Palindrome_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/009_Palindrome_Number.java) | Get the len and check left and right with 10^len, 10 |
-| 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)| |
@@ -65,9 +71,9 @@ Also, there are open source implementations for basic data structs and algorithm
| 153 | [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/153_Find_Minimum_in_Rotated_Sorted_Array.py) | Binary search with conditions, A[l] > A[r] |
| 154 | [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/154_Find_Minimum_in_Rotated_Sorted_Array_II.py) | Binary search with conditions, A[l] > A[r], A[l]=A[mid]=A[r] |
| 155 | [Min Stack](https://leetcode.com/problems/min-stack/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/155_Min_Stack.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/155_Min_Stack.java) | Add another stack for min stack, maintance this stack when the main stack pop or push: 1. Only push min, such that len(minStack)<=len(Stack) 2. Push min again when current top is min, such that len(minStack)=len(Stack) |
-| 156 | [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) ♥| [Python](https://github.com/qiyuangong/leetcode/blob/master/python/156_Binary_Tree_Upside_Down.py) | p.left = parent.right, parent.right = p.right, p.right = parent, parent = p.left, p = left |
+| 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|
@@ -78,7 +84,9 @@ Also, there are open source implementations for basic data structs and algorithm
| 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|
@@ -86,13 +94,15 @@ Also, there are open source implementations for basic data structs and algorithm
| 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) |
+| 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) |
@@ -123,6 +133,7 @@ Also, there are open source implementations for basic data structs and algorithm
| 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) |
@@ -134,7 +145,8 @@ Also, there are open source implementations for basic data structs and algorithm
| 405 | [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/405_Convert_a_Number_to_Hexadecimal.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/405_Convert_a_Number_to_Hexadecimal.java) | [Two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) 1. Bit manipulate, each time handle 4 digits
2. Python (hex) and Java API (toHexString & Integer.toHexString) |
| 408 | [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/) ♥ | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/408_Valid_Word_Abbreviation.py) | Go over abbr and word, O(n) and O(1) |
| 409 | [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/description/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/409_Longest_Palindrome.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/409_Longest_Palindrome.java) | Length of Palindrome is always 2n or 2n + 1. So, get all possible 2*n, and choose a single one as 1 if it exists. |
-| 412 | [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/412_Fizz_Buzz.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/412_Fizz_Buzz.java) | 1. From 1 to n, condition check
2. Condition check and string connect |
+| 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) |
@@ -142,55 +154,109 @@ Also, there are open source implementations for basic data structs and algorithm
| 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)|
+| 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/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/179_Largest_Number.java b/java/179_Largest_Number.java
index 3613777..1455406 100644
--- a/java/179_Largest_Number.java
+++ b/java/179_Largest_Number.java
@@ -29,7 +29,6 @@ public String largestNumber(int[] nums) {
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/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/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/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 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/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/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/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/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/665_Non-decreasing_Array.java b/java/665_Non-decreasing_Array.java
new file mode 100644
index 0000000..20eefb9
--- /dev/null
+++ b/java/665_Non-decreasing_Array.java
@@ -0,0 +1,29 @@
+class Solution {
+ /* public boolean checkPossibility(int[] nums) {
+ int pos = -1;
+ for (int i = 0; i < nums.length - 1; i++) {
+ if (nums[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/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/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= 0 && bits[i] > 0) i--;
+ // check if second last zero is even
+ return (bits.length - i) % 2 == 0;
+ } */
+}
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/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/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= 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/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/905_Sort_Array_By_Parity.java b/java/905_Sort_Array_By_Parity.java
index 699d304..09619cd 100644
--- a/java/905_Sort_Array_By_Parity.java
+++ b/java/905_Sort_Array_By_Parity.java
@@ -1,6 +1,10 @@
class Solution {
- /*public int[] sortArrayByParity(int[] A) {
- Array.sort(A, (a, b)-> Integer.compare(a%2, b%2));
+/* 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;
}*/
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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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
+