From a165f91de73f3ed6a8382f3183ab716a9b19a60a Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Wed, 4 Sep 2019 22:13:05 +0800 Subject: [PATCH 01/84] Fix style --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5c8a494..7221ed4 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,9 @@ 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). + +## 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. @@ -94,7 +96,7 @@ Also, there are open source implementations for basic data structs and algorithm | 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) | @@ -217,7 +219,7 @@ Also, there are open source implementations for basic data structs and algorithm |---| ----- | | 4 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | -# Other Leetcode Repos +## Other Leetcode Repos 1. [haoel's leetcode](https://github.com/haoel/leetcode) 2. [soulmachine's leetcode](https://github.com/soulmachine/leetcode) From 3d1573545a1ab2b02e21858e027a03d47145d009 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Tue, 24 Sep 2019 22:37:41 +0800 Subject: [PATCH 02/84] 019_Remove_Nth_Node_From_End_of_List --- README.md | 1 + .../019_Remove_Nth_Node_From_End_of_List.java | 63 +++++++++++++++++++ .../019_Remove_Nth_Node_From_End_of_List.py | 13 +++- 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 java/019_Remove_Nth_Node_From_End_of_List.java diff --git a/README.md b/README.md index 7221ed4..965389d 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Also, there are open source implementations for basic data structs and algorithm | 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)| | 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/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: From 0081e4b86810df62ee2b728e63d8804facd15c24 Mon Sep 17 00:00:00 2001 From: YOGESH BHAKHAR <31646304+yogesh-mca17du@users.noreply.github.com> Date: Mon, 28 Oct 2019 20:28:30 +0530 Subject: [PATCH 03/84] 204_Count_Primes cpp solution (#5) 204_Count_Primes cpp solution contributed by @yogesh-mca17du --- CountingPrimes.cpp | 148 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 CountingPrimes.cpp diff --git a/CountingPrimes.cpp b/CountingPrimes.cpp new file mode 100644 index 0000000..35d66f2 --- /dev/null +++ b/CountingPrimes.cpp @@ -0,0 +1,148 @@ +// Source : https://leetcode.com/problems/count-primes/ + + +/********************************************************************************** + * + * Description: + * Count the number of prime numbers less than a non-negative number, n. + * + * Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. + * + * Let's start with a isPrime function. To determine if a number is prime, we need to check if + * it is not divisible by any number less than n. The runtime complexity of isPrime function + * would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? + * + * As we know the number must not be divisible by any number > 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*i1){ + n = atoi(argv[1]); + } + + cout << endl << n << " : " << countPrimes(n) << endl; + + return 0; +} From 172fd36c3c464613d9191ab8496454fd6742d262 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Mon, 28 Oct 2019 23:21:11 +0800 Subject: [PATCH 04/84] Add 204_Count_Primes Python and Java solution based on CPP Solution --- README.md | 1 + .../204_Count_Primes.cpp | 30 +++++++++++-------- java/204_Count_Primes.java | 20 +++++++++++++ ...04_Count Primes.py => 204_Count_Primes.py} | 2 +- 4 files changed, 40 insertions(+), 13 deletions(-) rename CountingPrimes.cpp => cpp/204_Count_Primes.cpp (93%) create mode 100644 java/204_Count_Primes.java rename python/{204_Count Primes.py => 204_Count_Primes.py} (96%) diff --git a/README.md b/README.md index 965389d..8e71a07 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,7 @@ 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) | +| 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) | 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) | | 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)| diff --git a/CountingPrimes.cpp b/cpp/204_Count_Primes.cpp similarity index 93% rename from CountingPrimes.cpp rename to cpp/204_Count_Primes.cpp index 35d66f2..6757a45 100644 --- a/CountingPrimes.cpp +++ b/cpp/204_Count_Primes.cpp @@ -1,6 +1,5 @@ // Source : https://leetcode.com/problems/count-primes/ - /********************************************************************************** * * Description: @@ -113,20 +112,26 @@ #include using namespace std; -int countPrimes(int n) { +int countPrimes(int n) +{ vector isPrimer(n, true); - for(int i=2; i*i1){ + if (argc > 1) + { n = atoi(argv[1]); } - - cout << endl << n << " : " << countPrimes(n) << endl; + + cout << endl + << n << " : " << countPrimes(n) << endl; return 0; } 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/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 From 8ee7faa18dc0cc146fde6e61a3ad6bc6d4ce3020 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Fri, 21 Feb 2020 17:42:16 +0800 Subject: [PATCH 05/84] 485_Max_Consecutive_Ones --- README.md | 3 ++- java/485_Max_Consecutive_Ones.java | 17 +++++++++++++++++ python/485_Max_Consecutive_Ones.py | 18 ++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 java/485_Max_Consecutive_Ones.java create mode 100644 python/485_Max_Consecutive_Ones.py diff --git a/README.md b/README.md index 8e71a07..e433933 100644 --- a/README.md +++ b/README.md @@ -156,8 +156,9 @@ Also, there are open source implementations for basic data structs and algorithm | 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) | +| 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. | | 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 | | 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 | 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/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 From d55c6b23772cc01e3e2f0769b7e8838814c7a11e Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 22 Feb 2020 17:17:31 +0800 Subject: [PATCH 06/84] 1260_Shift_2D_Grid --- README.md | 1 + java/1260_Shift_2D_Grid.java | 32 ++++++++++++++++++++++++++++++++ python/1260_Shift_2D_Grid.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 java/1260_Shift_2D_Grid.java create mode 100644 python/1260_Shift_2D_Grid.py diff --git a/README.md b/README.md index e433933..2b84253 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,7 @@ Also, there are open source implementations for basic data structs and algorithm | 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) | | 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) | +| 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) | | # | To Understand | |---| ----- | 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/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 From 85132d6b6db56ea43f4f3260a0036759f47e75a6 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 23 Feb 2020 21:49:27 +0800 Subject: [PATCH 07/84] 1337_The_K_Weakest_Rows_in_a_Matrix --- README.md | 1 + java/1337_The_K_Weakest_Rows_in_a_Matrix.java | 30 +++++++++++++++++ python/1337_The_K_Weakest_Rows_in_a_Matrix.py | 33 +++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 java/1337_The_K_Weakest_Rows_in_a_Matrix.java create mode 100644 python/1337_The_K_Weakest_Rows_in_a_Matrix.py diff --git a/README.md b/README.md index 2b84253..568351e 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,7 @@ Also, there are open source implementations for basic data structs and algorithm | 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) | | 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) | | 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) | +| 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) | | # | To Understand | |---| ----- | 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/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 From d90e3fe1cf427407472abdf97ef8023e4338c7fc Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 29 Feb 2020 19:14:31 +0800 Subject: [PATCH 08/84] 1089_Duplicate_Zeros --- README.md | 1 + java/1089_Duplicate_Zeros.java | 28 ++++++++++++++++++++++++++++ python/1089_Duplicate_Zeros.py | 26 ++++++++++++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 java/1089_Duplicate_Zeros.java create mode 100644 python/1089_Duplicate_Zeros.py diff --git a/README.md b/README.md index 568351e..de7018e 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,7 @@ Also, there are open source implementations for basic data structs and algorithm | 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) | | 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) | | 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) | | 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) | 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/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] From 136d3fbcf8e52c1b7812d9232929171930765f6d Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sun, 1 Mar 2020 20:03:11 +0800 Subject: [PATCH 09/84] 1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number --- README.md | 1 + ...s_Are_Smaller_Than_the_Current_Number.java | 34 +++++++++++++++++++ ...ers_Are_Smaller_Than_the_Current_Number.py | 34 +++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 java/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java create mode 100644 python/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py diff --git a/README.md b/README.md index de7018e..843a0f7 100644 --- a/README.md +++ b/README.md @@ -220,6 +220,7 @@ Also, there are open source implementations for basic data structs and algorithm | 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) | | 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) | | 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) | +| 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) | | # | To Understand | |---| ----- | 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/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] From f1e724ab59689b0038a5c1509fb30594e12f0c3e Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Tue, 3 Mar 2020 20:36:22 +0800 Subject: [PATCH 10/84] 1108_Defanging_an_IP_Address --- README.md | 1 + java/1108_Defanging_an_IP_Address.java | 22 ++++++++++++++++++++++ python/1108_Defanging_an_IP_Address.py | 12 ++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 java/1108_Defanging_an_IP_Address.java create mode 100644 python/1108_Defanging_an_IP_Address.py diff --git a/README.md b/README.md index 843a0f7..a56aa38 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,7 @@ Also, there are open source implementations for basic data structs and algorithm | 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) | | 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) | | 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) | | 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) | | 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) | 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/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) From ca2860c73b950a6fd2ea7280d3329f9ab42d2418 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 23 May 2020 20:23:31 +0800 Subject: [PATCH 11/84] Add current project --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a56aa38..280d8cc 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ Remember solutions are only solutions to given problems. If you want full study 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. From 3bc1561a5e68a111df7c73c92c9b5fef793b9a6c Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 25 Jun 2020 22:44:17 +0800 Subject: [PATCH 12/84] 1480_Running_Sum_of_1d_Array --- README.md | 1 + java/1480_Running_Sum_of_1d_Array.java | 11 +++++++++++ python/1480_Running_Sum_of_1d_Array.py | 11 +++++++++++ 3 files changed, 23 insertions(+) create mode 100644 java/1480_Running_Sum_of_1d_Array.java create mode 100644 python/1480_Running_Sum_of_1d_Array.py diff --git a/README.md b/README.md index 280d8cc..52283e4 100644 --- a/README.md +++ b/README.md @@ -224,6 +224,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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) | | 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) | | 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 | | # | To Understand | |---| ----- | 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..e41ad2a --- /dev/null +++ b/java/1480_Running_Sum_of_1d_Array.java @@ -0,0 +1,11 @@ +class Solution { + public int[] runningSum(int[] nums) { + if (nums.length <= 1) return nums; + int accu = nums[0]; + for (int i = 1; i < nums.length; i++) { + accu += nums[i]; + nums[i] = accu; + } + return nums; + } +} 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) From a2c32380bbd23055ee252109cdc4b700a4530b22 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 25 Jun 2020 22:49:48 +0800 Subject: [PATCH 13/84] Remove accu in 1480_Running_Sum_of_1d_Array --- java/1480_Running_Sum_of_1d_Array.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/java/1480_Running_Sum_of_1d_Array.java b/java/1480_Running_Sum_of_1d_Array.java index e41ad2a..15ba2ee 100644 --- a/java/1480_Running_Sum_of_1d_Array.java +++ b/java/1480_Running_Sum_of_1d_Array.java @@ -1,11 +1,8 @@ class Solution { public int[] runningSum(int[] nums) { if (nums.length <= 1) return nums; - int accu = nums[0]; - for (int i = 1; i < nums.length; i++) { - accu += nums[i]; - nums[i] = accu; - } + for (int i = 1; i < nums.length; i++) + nums[i] += nums[i - 1]; return nums; } } From bab8addbc6e1d675b7f1cf86dd09b335166704e0 Mon Sep 17 00:00:00 2001 From: Aayush Srivastava Date: Thu, 23 Jul 2020 19:29:43 +0530 Subject: [PATCH 14/84] Add 1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py and 1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py (#8) * 1290_Convert_Binary_Number_In_A_Linked_List_To_Integer.py * 1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py Contributed by @srivastavaayu --- README.md | 2 + ...nary_Number_in_a_Linked_List_to_Integer.py | 47 +++++++++++++++++++ ...ber_of_Steps_to_Reduce_a_Number_to_Zero.py | 44 +++++++++++++++++ 3 files changed, 93 insertions(+) create mode 100644 python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py create mode 100644 python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py diff --git a/README.md b/README.md index 52283e4..82c2b9d 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,9 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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) | | 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/srivastavaayu/leetcode-1/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 | | 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/srivastavaayu/leetcode-1/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 | | 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 | 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..f545bf7 --- /dev/null +++ b/python/1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py @@ -0,0 +1,47 @@ +''' +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!=None): + head=head.next + binary_numbers_list.append(head.val) + answer=0 + power=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/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..799751f --- /dev/null +++ b/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py @@ -0,0 +1,44 @@ +''' +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 + From a1806544d0a26e7f6a05441badb3478efa3a8f79 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 23 Jul 2020 22:11:02 +0800 Subject: [PATCH 15/84] Change link of 1290 and 1342. Fix code style --- README.md | 4 +-- ...nary_Number_in_a_Linked_List_to_Integer.py | 19 ++++++------ ...ber_of_Steps_to_Reduce_a_Number_to_Zero.py | 30 ++++++++++++++----- 3 files changed, 34 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 82c2b9d..ab93f98 100644 --- a/README.md +++ b/README.md @@ -222,9 +222,9 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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) | | 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/srivastavaayu/leetcode-1/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 | +| 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 | | 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/srivastavaayu/leetcode-1/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 | +| 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 | 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 index f545bf7..f5b13ee 100644 --- 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 @@ -33,15 +33,16 @@ class Solution: def getDecimalValue(self, head: ListNode) -> int: - binary_numbers_list=[] + binary_numbers_list = [] binary_numbers_list.append(head.val) - while(head.next!=None): - head=head.next + while(head.next is not None): + head = head.next binary_numbers_list.append(head.val) - answer=0 - power=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 + 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/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py b/python/1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py index 799751f..3769ac8 100644 --- 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 @@ -32,13 +32,27 @@ class Solution: def numberOfSteps (self, num: int) -> int: - steps=0 - while(num>0): - if(num%2==0): - num=num/2 - steps+=1 + steps = 0 + while(num > 0): + if(num % 2 == 0): + num = num / 2 + steps + =1 else: - num=num-1 - steps+=1 + 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 From 1be32de7207e3fd7ccd75ddcc9471eda79af18c8 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Mon, 3 Aug 2020 22:13:26 +0800 Subject: [PATCH 16/84] 717_1-bit_and_2-bit_Characters --- README.md | 1 + java/717_1-bit_and_2-bit_Characters.java | 44 ++++++++++++++++++++++++ python/717_1-bit_and_2-bit_Characters.py | 38 ++++++++++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 java/717_1-bit_and_2-bit_Characters.java create mode 100644 python/717_1-bit_and_2-bit_Characters.py diff --git a/README.md b/README.md index ab93f98..5017d3c 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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) | | 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) | diff --git a/java/717_1-bit_and_2-bit_Characters.java b/java/717_1-bit_and_2-bit_Characters.java new file mode 100644 index 0000000..8e560c8 --- /dev/null +++ b/java/717_1-bit_and_2-bit_Characters.java @@ -0,0 +1,44 @@ +/* +We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). + +Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero. + +Example 1: +Input: +bits = [1, 0, 0] +Output: True +Explanation: +The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character. +Example 2: +Input: +bits = [1, 1, 1, 0] +Output: False +Explanation: +The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character. +Note: + +1 <= len(bits) <= 1000. +bits[i] is always 0 or 1. +*/ + +// https://leetcode.com/problems/1-bit-and-2-bit-characters/solution/ +class Solution { + public boolean isOneBitCharacter(int[] bits) { + int pos = 0; + // Go through bits + while (pos < bits.length - 1) { + // if 1, pos + 2; if 0, pos + 1 + pos += bits[pos] + 1; + } + return pos == bits.length - 1; + } + + /* public boolean isOneBitCharacter(int[] bits) { + // From len - 2 + int i = bits.length - 2; + // until encounter 0 + while (i >= 0 && bits[i] > 0) i--; + // check if second last zero is even + return (bits.length - i) % 2 == 0; + } */ +} diff --git a/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 From bb4c1563b7a9fa63c3b9201654b741371a292022 Mon Sep 17 00:00:00 2001 From: nishithgadhiya <66241520+nishithgadhiya@users.noreply.github.com> Date: Thu, 1 Oct 2020 17:13:20 +0530 Subject: [PATCH 17/84] 1599_Maximum_Profit_of_Operating_a_Centennial_Wheel (#10) 1599_Maximum_Profit_of_Operating_a_Centennial_Wheel by @nishithgadhiya --- ..._Profit_of_Operating_a_Centennial_Wheel.py | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 python/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py 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)) + From eaaab364b4a79f17b9613b95cec105dc0d7e0657 Mon Sep 17 00:00:00 2001 From: sohel0707 <51533929+sohel0707@users.noreply.github.com> Date: Thu, 1 Oct 2020 17:15:08 +0530 Subject: [PATCH 18/84] 997_Find_The_Town_Judge (#9) 997_Find_The_Town_Judge by @sohel0707 --- python/997_Find_The_Town_Judge.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 python/997_Find_The_Town_Judge.py 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 + From d8d138dec5696e8c7794d789ef382f55464c0c01 Mon Sep 17 00:00:00 2001 From: nishithgadhiya <66241520+nishithgadhiya@users.noreply.github.com> Date: Thu, 1 Oct 2020 17:17:23 +0530 Subject: [PATCH 19/84] Create 541_Reverse_String_II (#11) 541_Reverse_String_II by @nishithgadhiya --- python/541_Reverse_String_II.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 python/541_Reverse_String_II.py diff --git a/python/541_Reverse_String_II.py b/python/541_Reverse_String_II.py new file mode 100644 index 0000000..c1a959e --- /dev/null +++ b/python/541_Reverse_String_II.py @@ -0,0 +1,17 @@ +class Solution: + def reverseStr(self, s, k): + 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 + + + +s1 = Solution() +s="abcdefg" +k=2 +print(s1.reverseStr(s,k)) From c820d5499f2b0d5fc2fab521bbb6bd327d73143d Mon Sep 17 00:00:00 2001 From: Mansi Mehndiratta Date: Fri, 2 Oct 2020 18:51:23 +0530 Subject: [PATCH 20/84] Add 1323_maximum_69_number (#15) 1323_maximum_69_number by @Mansi2814 --- python/1323_maximum_69_number | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 python/1323_maximum_69_number diff --git a/python/1323_maximum_69_number b/python/1323_maximum_69_number new file mode 100644 index 0000000..c755b0e --- /dev/null +++ b/python/1323_maximum_69_number @@ -0,0 +1,3 @@ +class Solution: + def maximum69Number (self, num: int) -> int: + return(str(num).replace('6','9',1)) From b0b006961da321de20f6804dfde0b5fb6cd8c646 Mon Sep 17 00:00:00 2001 From: arun-aditya <42905401+arun-aditya@users.noreply.github.com> Date: Fri, 2 Oct 2020 18:56:25 +0530 Subject: [PATCH 21/84] Add 011_containerwithmostwater (#13) Add 011_containerwithmostwater Java solution by @arun-aditya --- java/011_containerwithmostwater.java | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 java/011_containerwithmostwater.java diff --git a/java/011_containerwithmostwater.java b/java/011_containerwithmostwater.java new file mode 100644 index 0000000..4b82cc0 --- /dev/null +++ b/java/011_containerwithmostwater.java @@ -0,0 +1,20 @@ +class Solution { + public int maxArea(int[] height) { + + int max=0; + int left=0; + int right=height.length-1; + + while(left Date: Fri, 2 Oct 2020 18:58:24 +0530 Subject: [PATCH 22/84] Create 012_integertoroman.java (#12) Added JAVA solution for leetcode 012 integertoroman, by @arun-aditya --- java/012_integertoroman.java | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 java/012_integertoroman.java diff --git a/java/012_integertoroman.java b/java/012_integertoroman.java new file mode 100644 index 0000000..cb7a777 --- /dev/null +++ b/java/012_integertoroman.java @@ -0,0 +1,21 @@ +public String intToRoman(int num) { + Map 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(); +} From 35646045f5b44fd8c76db0404fe277d79ae71904 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Fri, 2 Oct 2020 21:38:58 +0800 Subject: [PATCH 23/84] Refine 1323, add Java solution and link --- README.md | 1 + java/1323_Maximum_69_Number.java | 19 +++++++++++++++++++ python/1323_Maximum_69_Number.py | 4 ++++ python/1323_maximum_69_number | 3 --- 4 files changed, 24 insertions(+), 3 deletions(-) create mode 100644 java/1323_Maximum_69_Number.java create mode 100644 python/1323_Maximum_69_Number.py delete mode 100644 python/1323_maximum_69_number diff --git a/README.md b/README.md index 5017d3c..4e678e4 100644 --- a/README.md +++ b/README.md @@ -224,6 +224,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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) | | 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 | +| 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) | 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/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/1323_maximum_69_number b/python/1323_maximum_69_number deleted file mode 100644 index c755b0e..0000000 --- a/python/1323_maximum_69_number +++ /dev/null @@ -1,3 +0,0 @@ -class Solution: - def maximum69Number (self, num: int) -> int: - return(str(num).replace('6','9',1)) From 83a0bbd3e3f7cad588af2094dcd67daee418b297 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Fri, 2 Oct 2020 22:21:49 +0800 Subject: [PATCH 24/84] Refine 011_Container_With_Most_Water --- .gitignore | 2 +- README.md | 1 + java/011_Container_With_Most_Water.java | 16 +++++++ java/011_containerwithmostwater.java | 20 --------- python/011_Container_With_Most_Water.py | 55 ++++++------------------- 5 files changed, 31 insertions(+), 63 deletions(-) create mode 100644 java/011_Container_With_Most_Water.java delete mode 100644 java/011_containerwithmostwater.java 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 4e678e4..5a761f0 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 7 | [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/007_Reverse_Integer.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/007_Reverse_Integer.java) | Overflow when the result is greater than 2147483647 or less than -2147483648. | 8 | [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/008_String_to_Integer(atoi).py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/008_String_to_Integer(atoi).java) | Overflow, Space, and negative number | | 9 | [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/009_Palindrome_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/009_Palindrome_Number.java) | Get the len and check left and right with 10^len, 10 | +| 11 | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/011_Container_With_Most_Water.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/011_Container_With_Most_Water.java) | 1. Brute Force, O(n^2) and O(1)
2. Two points, O(n) and O(1) | | 12 | [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/012_Integer_to_Roman.py) | [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) | diff --git a/java/011_Container_With_Most_Water.java b/java/011_Container_With_Most_Water.java new file mode 100644 index 0000000..c873867 --- /dev/null +++ b/java/011_Container_With_Most_Water.java @@ -0,0 +1,16 @@ +class Solution { + public int maxArea(int[] height) { + + int maxArea = 0; + int left = 0; + int right = height.length - 1; + + while (left < right) { + maxArea = Math.max(maxArea, (right - left) * Math.min(height[left], height[right])); + // Two points + if (height[left] < height[right]) left++; + else right--; + } + return maxArea; + } +} diff --git a/java/011_containerwithmostwater.java b/java/011_containerwithmostwater.java deleted file mode 100644 index 4b82cc0..0000000 --- a/java/011_containerwithmostwater.java +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { - public int maxArea(int[] height) { - - int max=0; - int left=0; - int right=height.length-1; - - while(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 From 1ca0f6e50f5733586bdb29168d21f3ef66fba59a Mon Sep 17 00:00:00 2001 From: diwansimranbanu <72291969+diwansimranbanu@users.noreply.github.com> Date: Sat, 3 Oct 2020 20:00:54 +0530 Subject: [PATCH 25/84] Add 728_Self_Dividing_Numbers.java (#24) Added 728_Self_Dividing_Numbers Java Solution by @diwansimranbanu --- java/728_Self_Dividing_Numbers.java | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 java/728_Self_Dividing_Numbers.java diff --git a/java/728_Self_Dividing_Numbers.java b/java/728_Self_Dividing_Numbers.java new file mode 100644 index 0000000..d9cf8eb --- /dev/null +++ b/java/728_Self_Dividing_Numbers.java @@ -0,0 +1,35 @@ +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) + { + if(digit == 0 || num % digit != 0) + { + isTrue = false; + break; + } + else + { + temp /= 10; + digit = temp%10; + } + } + return isTrue; + + } + +} From 1c8b68332c8903a6add8fe4555daa8d16ecd2073 Mon Sep 17 00:00:00 2001 From: diwansimranbanu <72291969+diwansimranbanu@users.noreply.github.com> Date: Sat, 3 Oct 2020 20:03:11 +0530 Subject: [PATCH 26/84] Add 868_Binary_Gap.py (#23) Added 868_Binary_Gap Python solution, by @diwansimranbanu --- python/868_Binary_Gap.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 python/868_Binary_Gap.py diff --git a/python/868_Binary_Gap.py b/python/868_Binary_Gap.py new file mode 100644 index 0000000..0c4f0d7 --- /dev/null +++ b/python/868_Binary_Gap.py @@ -0,0 +1,14 @@ +class Solution: + def binaryGap(self, n: int) -> int: + 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) + From 257bda525f490f1717e8abdaf3e4bf32832c8e8d Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 3 Oct 2020 22:56:06 +0800 Subject: [PATCH 27/84] Add 728 link --- README.md | 1 + java/728_Self_Dividing_Numbers.java | 24 ++++++++---------------- python/728_Self_Dividing_Numbers.py | 7 +++++++ 3 files changed, 16 insertions(+), 16 deletions(-) create mode 100644 python/728_Self_Dividing_Numbers.py diff --git a/README.md b/README.md index 5a761f0..b5c822d 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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) | diff --git a/java/728_Self_Dividing_Numbers.java b/java/728_Self_Dividing_Numbers.java index d9cf8eb..eeb12af 100644 --- a/java/728_Self_Dividing_Numbers.java +++ b/java/728_Self_Dividing_Numbers.java @@ -1,35 +1,27 @@ class Solution { - public List selfDividingNumbers(int left, int right) - { + public List selfDividingNumbers(int left, int right) { LinkedList list = new LinkedList(); - for(int i = left; i <= right; i++) - { + for(int i = left; i <= right; i++) { if(isSelfDiving(i)) list.add(i); } return list; } - public boolean isSelfDiving(int num) - { + public boolean isSelfDiving(int num) { int digit = num % 10; int temp = num; boolean isTrue = true; - while(temp != 0) - { - if(digit == 0 || num % digit != 0) - { + while(temp != 0) { + // 0 is special + if(digit == 0 || num % digit != 0) { isTrue = false; break; - } - else - { + } else { temp /= 10; - digit = temp%10; + digit = temp % 10; } } return isTrue; - } - } 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))))] From 417ccfd22cc7c1f661e7a8c82e3567da6bf2441b Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 3 Oct 2020 23:34:32 +0800 Subject: [PATCH 28/84] Refine 868 and add link --- README.md | 1 + java/868_Binary_Gap.java | 27 +++++++++++++++++++++++++++ python/868_Binary_Gap.py | 30 +++++++++++++++++++++++++----- 3 files changed, 53 insertions(+), 5 deletions(-) create mode 100644 java/868_Binary_Gap.java diff --git a/README.md b/README.md index b5c822d..2f18788 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 844 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/844_Backspace_String_Compare.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/844_Backspace_String_Compare.java) | 1. Stack pop when encounters #, O(n) and O(n)
2. Compare string from end to start, O(n) and O(1) | | 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/852_Peak_Index_in_a_Mountain_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/852_Peak_Index_in_a_Mountain_Array.java) | 1. Scan the array until encountering decline, O(n) and O(1)
2. Binary seach with additional check for [i + 1], O(logn) and O(1) | | 867 | [Transpose Matrix](https://leetcode.com/problems/transpose-matrix/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/867_Transpose_Matrix.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/867_Transpose_Matrix.java) | Res[i][j] = A[j][i] | +| 868 | [Binary Gap](https://leetcode.com/problems/binary-gap/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/868_Binary_Gap.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/868_Binary_Gap.java) | 1. Store index and check, O(logn) and O(logn)
2. One pass and store max, O(logn) and O(1) | | 872 | [Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/872_Leaf-Similar_Trees.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/872_Leaf-Similar_Trees.java) | DFS (stack or recursion) get leaf value sequence and compare, O(n) and O(n) | | 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/876_Middle_of_the_Linked_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/876_Middle_of_the_Linked_List.java) | 1. Copy to array, O(n) and O(n)
2. Fast and slow point, where fast point is 2 times faster than slow point, O(n) and O(1) | | 904 | [Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/904_Fruit_Into_Baskets.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/904_Fruit_Into_Baskets.java) | 1. Scan through blocks of tree, O(n) and O(n)
2. Mainten a sliding window with start and curr point, O(n) and O(n). | 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/python/868_Binary_Gap.py b/python/868_Binary_Gap.py index 0c4f0d7..191d3d1 100644 --- a/python/868_Binary_Gap.py +++ b/python/868_Binary_Gap.py @@ -1,14 +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: - current= 1 + # one pass and store max + current = 1 last1 = -1 out = 0 while n > 0: - if n%2 == 1: + if n % 2 == 1: if last1 >= 1: out = max(out, current - last1) last1 = current current += 1 - n = n//2 - return(out) - + 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 From 1692022faf4245b544499062c7de41d80fe89861 Mon Sep 17 00:00:00 2001 From: ruchit2801 <39343253+ruchit2801@users.noreply.github.com> Date: Mon, 5 Oct 2020 21:07:12 +0530 Subject: [PATCH 29/84] Add 1310_XOR_Queries_of_a_Subarray (#22) * Add 206_Reverse_Linked_List CPP solution * Add 1310_XOR_Queries_of_a_Subarray Python Solution by @ruchit2801 --- cpp/206_Reverse_Linked_List.cpp | 26 ++++++++++++++++++++++++ python/1310_XOR_Queries_of_a_Subarray.py | 10 +++++++++ 2 files changed, 36 insertions(+) create mode 100644 cpp/206_Reverse_Linked_List.cpp create mode 100644 python/1310_XOR_Queries_of_a_Subarray.py diff --git a/cpp/206_Reverse_Linked_List.cpp b/cpp/206_Reverse_Linked_List.cpp new file mode 100644 index 0000000..56aefc2 --- /dev/null +++ b/cpp/206_Reverse_Linked_List.cpp @@ -0,0 +1,26 @@ +/** + * 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; + ListNode* p=head; + ListNode* c=head->next; + head->next=NULL; + while(c->next){ + ListNode* n = c->next; + c->next=p; + p=c; + c=n; + } + c->next=p; + return c; + } +}; 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..3f1d1fb --- /dev/null +++ b/python/1310_XOR_Queries_of_a_Subarray.py @@ -0,0 +1,10 @@ +class Solution: + def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: + pref = [0] + for e in arr: + pref.append(e ^ pref[-1]) + ans = [] + for [l, r] in queries: + ans.append(pref[r+1] ^ pref[l]) + return ans + From f8a6d7656212440abd8943df0437d1f080d514f4 Mon Sep 17 00:00:00 2001 From: ruchit2801 <39343253+ruchit2801@users.noreply.github.com> Date: Mon, 5 Oct 2020 21:09:30 +0530 Subject: [PATCH 30/84] Add 668_Kth_Smallest_Number_in_Multiplication_Table (#21) * Add 668_Kth_Smallest_Number_in_Multiplication_Table CPP solution, by @ruchit2801 --- ...mallest_Number_in_Multiplication_Table.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp 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..1b8e6ab --- /dev/null +++ b/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp @@ -0,0 +1,28 @@ +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=k; + } + + int findKthNumber(int n1, int n2, int k) { + ll l=0, r=n1*n2,ans; + while(l<=r){ + ll m = l +(r-l)/2; + if(valid(m,n1,n2,k)){ + ans=m; + r=m-1; + } + else{ + l=m+1; + } + } + return ans; + } +}; From 6699908944916c29a7edd73cbe406d1e3c2b1a85 Mon Sep 17 00:00:00 2001 From: ruchit2801 <39343253+ruchit2801@users.noreply.github.com> Date: Tue, 6 Oct 2020 17:33:57 +0530 Subject: [PATCH 31/84] Add 412_Fizz_Buzz (#20) * Add 412_Fizz_Buzz CPP solution, by @ruchit2801 --- cpp/412_Fizz_Buzz.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 cpp/412_Fizz_Buzz.cpp diff --git a/cpp/412_Fizz_Buzz.cpp b/cpp/412_Fizz_Buzz.cpp new file mode 100644 index 0000000..7bbee33 --- /dev/null +++ b/cpp/412_Fizz_Buzz.cpp @@ -0,0 +1,15 @@ +#define pb push_back +class Solution { +public: + vector fizzBuzz(int n) { + int i; + vector s; + for(i=0;i Date: Tue, 6 Oct 2020 20:07:31 +0800 Subject: [PATCH 32/84] 009_Palindrome_Number Python 3 Support (#26) * Upgrade 009_Palindrome_Number.py for Python 3 support, by @peterhuang1kimo --- python/009_Palindrome_Number.py | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/python/009_Palindrome_Number.py b/python/009_Palindrome_Number.py index b18b89d..af6890f 100644 --- a/python/009_Palindrome_Number.py +++ b/python/009_Palindrome_Number.py @@ -9,23 +9,17 @@ class Solution(object): def isPalindrome(self, x): if x < 0: return False - ls = 0 + ls = len(str(x)) tmp = x - while tmp != 0: - ls += 1 - tmp = tmp // 10 - tmp = x - for i in range(ls/2): - right = tmp % 10 + for i in range(int(ls/2)): + right = int(tmp % 10) left = tmp / (10 ** (ls - 2 * i - 1)) - left = left % 10 - # print left, right + left = int(left % 10) if left != right: return False tmp = tmp // 10 return True - # def isPalindrome(self, x): # #leetcode book # if x < 0: @@ -62,4 +56,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) From 29c53b5cc09b19a7ef1d51396ecf3d7637989692 Mon Sep 17 00:00:00 2001 From: peterhuang1kimo Date: Tue, 6 Oct 2020 20:10:09 +0800 Subject: [PATCH 33/84] 035_Search_Insert_Position Python 3 Support (#27) * Update 035_Search_Insert_Position.py for Python 3 support, by @peterhuang1kimo --- python/035_Search_Insert_Position.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) 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)) + From 772205f49a84c45cf9d9d784397f979e1e7379a7 Mon Sep 17 00:00:00 2001 From: arun-aditya <42905401+arun-aditya@users.noreply.github.com> Date: Tue, 6 Oct 2020 19:03:23 +0530 Subject: [PATCH 34/84] Update 009_Palindrome_Number.java (#14) * Added a simpler and easy to understand code in java, by @arun-aditya --- java/009_Palindrome_Number.java | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/java/009_Palindrome_Number.java b/java/009_Palindrome_Number.java index 1dc03ae..0d3150c 100644 --- a/java/009_Palindrome_Number.java +++ b/java/009_Palindrome_Number.java @@ -38,4 +38,26 @@ public boolean isPalindrome(int x) { } return true; } -} \ No newline at end of file +} + +// simpler code + +class Solution { + public boolean isPalindrome(int x) { + int r,s=0,number=x; + if(number<0){ + return false; + } + while (number!=0){ + r=number%10; + s= s*10 +r; + number/=10; + } + if (s==x){ + return true; + } + else { + return false; + } + } +} From b1d74a51fa18e7789e6e21dc5ad8e7fbe1bc9824 Mon Sep 17 00:00:00 2001 From: Mansi Mehndiratta Date: Tue, 6 Oct 2020 19:07:40 +0530 Subject: [PATCH 35/84] Add 1304_Find_N_Unique_Integers_Sum_up_to_Zero (#16) * Add 1304_Find_N_Unique_Integers_Sum_up_to_Zero Python Solution, by @Mansi2814 --- python/1304_Find_N_Unique_Integers_Sum_up_to_Zero | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 python/1304_Find_N_Unique_Integers_Sum_up_to_Zero diff --git a/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero b/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero new file mode 100644 index 0000000..141ecaa --- /dev/null +++ b/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero @@ -0,0 +1,11 @@ +class Solution: + def sumZero(self, n: int) -> List[int]: + sum = 0 + list = [] + + for i in range(1,n): + list.append(i) + sum = sum +i + list.append(-sum) + return list + From a99c1d0b4aa6f95dd82d51e8b2dc570bf6972419 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Tue, 6 Oct 2020 21:58:22 +0800 Subject: [PATCH 36/84] Refine 1304_Find_N_Unique_Integers_Sum_up_to_Zero --- README.md | 1 + ...4_Find_N_Unique_Integers_Sum_up_to_Zero.java | 9 +++++++++ .../1304_Find_N_Unique_Integers_Sum_up_to_Zero | 11 ----------- ...304_Find_N_Unique_Integers_Sum_up_to_Zero.py | 17 +++++++++++++++++ 4 files changed, 27 insertions(+), 11 deletions(-) create mode 100644 java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java delete mode 100644 python/1304_Find_N_Unique_Integers_Sum_up_to_Zero create mode 100644 python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py diff --git a/README.md b/README.md index 2f18788..7febeaf 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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) | | 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 | | 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) | 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/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero b/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero deleted file mode 100644 index 141ecaa..0000000 --- a/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero +++ /dev/null @@ -1,11 +0,0 @@ -class Solution: - def sumZero(self, n: int) -> List[int]: - sum = 0 - list = [] - - for i in range(1,n): - list.append(i) - sum = sum +i - list.append(-sum) - return list - 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)] From b5166888c26873d230193a97d5ca39daf4c3212b Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Wed, 7 Oct 2020 23:43:37 +0800 Subject: [PATCH 37/84] Refine 012_Integer_to_Roman --- README.md | 2 +- java/012_Integer_to_Roman.java | 23 +++++++++++++++++++++++ java/012_integertoroman.java | 21 --------------------- 3 files changed, 24 insertions(+), 22 deletions(-) create mode 100644 java/012_Integer_to_Roman.java delete mode 100644 java/012_integertoroman.java diff --git a/README.md b/README.md index 7febeaf..edf614c 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 8 | [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/008_String_to_Integer(atoi).py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/008_String_to_Integer(atoi).java) | Overflow, Space, and negative number | | 9 | [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/009_Palindrome_Number.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/009_Palindrome_Number.java) | Get the len and check left and right with 10^len, 10 | | 11 | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/011_Container_With_Most_Water.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/011_Container_With_Most_Water.java) | 1. Brute Force, O(n^2) and O(1)
2. Two points, O(n) and O(1) | -| 12 | [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/012_Integer_to_Roman.py) | [Background knowledge](http://www.rapidtables.com/convert/number/how-number-to-roman-numerals.htm) Just like 10-digit number, divide and minus | +| 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| diff --git a/java/012_Integer_to_Roman.java b/java/012_Integer_to_Roman.java new file mode 100644 index 0000000..8683029 --- /dev/null +++ b/java/012_Integer_to_Roman.java @@ -0,0 +1,23 @@ +class Solution { + public String intToRoman(int num) { + Map 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/012_integertoroman.java b/java/012_integertoroman.java deleted file mode 100644 index cb7a777..0000000 --- a/java/012_integertoroman.java +++ /dev/null @@ -1,21 +0,0 @@ -public String intToRoman(int num) { - Map 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(); -} From 7ffaa0dff9dcb5eec9caa5462cc13317a0514aa2 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Wed, 7 Oct 2020 23:59:23 +0800 Subject: [PATCH 38/84] Refine 206_Reverse_Linked_List --- README.md | 2 +- cpp/206_Reverse_Linked_List.cpp | 30 +++++++++++++----------- java/206_Reverse_Linked_List.java | 38 +++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 14 deletions(-) create mode 100644 java/206_Reverse_Linked_List.java diff --git a/README.md b/README.md index edf614c..f164996 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 198 | [House Robber](https://leetcode.com/problems/house-robber/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/198_House_Robber.py) | f(k) = max(f(k – 2) + num[k], f(k – 1)), O(n) and O(1) | | 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/200_Number_of_Islands.py) | 1. Quick union find, O(nlogn) and O(n^2)
2. BFS with marks, O(n^2) and O(1) | | 204 | [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/204_Count_Primes.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/204_Count_Primes.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/204_Count_Primes.cpp) | [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity), O(nloglogn) and O(n) | -| 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/206_Reverse_Linked_List.py) | 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) | +| 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) | | 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| diff --git a/cpp/206_Reverse_Linked_List.cpp b/cpp/206_Reverse_Linked_List.cpp index 56aefc2..84bf495 100644 --- a/cpp/206_Reverse_Linked_List.cpp +++ b/cpp/206_Reverse_Linked_List.cpp @@ -8,19 +8,23 @@ */ class Solution { public: - ListNode* reverseList(ListNode* head) { - if(head==NULL)return NULL; - if(head->next==NULL) return head; - ListNode* p=head; - ListNode* c=head->next; - head->next=NULL; - while(c->next){ - ListNode* n = c->next; - c->next=p; - p=c; - c=n; + 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; } - c->next=p; - return c; + curr->next = previous; + return curr; } }; 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); + }*/ +} From 7e0d4d5939f0e5be493a97d39716878c3cdf1fae Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 8 Oct 2020 09:53:52 +0800 Subject: [PATCH 39/84] Refine 1310_XOR_Queries_of_a_Subarray --- README.md | 1 + cpp/1310_XOR_Queries_of_a_Subarray.cpp | 12 ++++++++++++ java/1310_XOR_Queries_of_a_Subarray.java | 14 ++++++++++++++ python/1310_XOR_Queries_of_a_Subarray.py | 8 +++++++- 4 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 cpp/1310_XOR_Queries_of_a_Subarray.cpp create mode 100644 java/1310_XOR_Queries_of_a_Subarray.java diff --git a/README.md b/README.md index f164996..7c27167 100644 --- a/README.md +++ b/README.md @@ -228,6 +228,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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) | 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/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/python/1310_XOR_Queries_of_a_Subarray.py b/python/1310_XOR_Queries_of_a_Subarray.py index 3f1d1fb..86cdd7b 100644 --- a/python/1310_XOR_Queries_of_a_Subarray.py +++ b/python/1310_XOR_Queries_of_a_Subarray.py @@ -1,10 +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] From 4882b9dcd8eec0d1f73fa3a4053013fccb7d226a Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Fri, 9 Oct 2020 20:54:50 +0800 Subject: [PATCH 40/84] Refine 668_Kth_Smallest_Number_in_Multiplication_Table --- README.md | 1 + ...mallest_Number_in_Multiplication_Table.cpp | 37 ++++++++++--------- ...allest_Number_in_Multiplication_Table.java | 22 +++++++++++ ...Smallest_Number_in_Multiplication_Table.py | 19 ++++++++++ 4 files changed, 61 insertions(+), 18 deletions(-) create mode 100644 java/668_Kth_Smallest_Number_in_Multiplication_Table.java create mode 100644 python/668_Kth_Smallest_Number_in_Multiplication_Table.py diff --git a/README.md b/README.md index 7c27167..33e94f7 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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. | diff --git a/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp b/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp index 1b8e6ab..1476598 100644 --- a/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp +++ b/cpp/668_Kth_Smallest_Number_in_Multiplication_Table.cpp @@ -1,26 +1,27 @@ 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=k; + return cnt >= k; } - + int findKthNumber(int n1, int n2, int k) { - ll l=0, r=n1*n2,ans; - while(l<=r){ - ll m = l +(r-l)/2; - if(valid(m,n1,n2,k)){ - ans=m; - r=m-1; - } - else{ - l=m+1; + 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/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/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 From efa47f2ca8ad458f4a09d8780ddac1e1c3fcd984 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Sat, 10 Oct 2020 21:40:01 +0800 Subject: [PATCH 41/84] Add 412_Fizz_Buzz.cpp link --- README.md | 2 +- cpp/412_Fizz_Buzz.cpp | 14 +++++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 33e94f7..218bd89 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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) | diff --git a/cpp/412_Fizz_Buzz.cpp b/cpp/412_Fizz_Buzz.cpp index 7bbee33..3a7dd5d 100644 --- a/cpp/412_Fizz_Buzz.cpp +++ b/cpp/412_Fizz_Buzz.cpp @@ -4,11 +4,15 @@ class Solution { vector fizzBuzz(int n) { int i; vector s; - for(i=0;i Date: Sun, 11 Oct 2020 23:20:23 +0800 Subject: [PATCH 42/84] Refine 541_Reverse_String_II --- README.md | 1 + java/541_Reverse_String_II.java | 16 ++++++++++++++++ python/541_Reverse_String_II.py | 8 +++++++- 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 java/541_Reverse_String_II.java diff --git a/README.md b/README.md index 218bd89..7163b06 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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. | | 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. | 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/python/541_Reverse_String_II.py b/python/541_Reverse_String_II.py index c1a959e..08fcced 100644 --- a/python/541_Reverse_String_II.py +++ b/python/541_Reverse_String_II.py @@ -1,5 +1,5 @@ class Solution: - def reverseStr(self, s, k): + def reverseStr(self, s: str, k: int) -> str: N = len(s) ans = "" position = 0 @@ -9,6 +9,12 @@ def reverseStr(self, s, 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() From fa2b50452d07f5f754976b744777353424d3600b Mon Sep 17 00:00:00 2001 From: peterhuang1kimo Date: Mon, 19 Oct 2020 22:23:06 +0800 Subject: [PATCH 43/84] Upgrade 072_Edit_Distance.py to python 3 (#28) * Upgrade 072_Edit_Distance.py to python 3, by @peterhuang1kimo --- python/072_Edit_Distance.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) 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")) From 09bbdf890a71b1820793f29cd05e20db623acef6 Mon Sep 17 00:00:00 2001 From: hvsalesforce <73243807+hvsalesforce@users.noreply.github.com> Date: Wed, 28 Oct 2020 19:55:37 +0530 Subject: [PATCH 44/84] Create 066_Plus_One.java (#33) * Create 066_Plus_One.java, by @hvsalesforce --- java/066_Plus_One.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 java/066_Plus_One.java 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; + } + } +} From bb21f19083c4e2d07ed3278bea4017c1f0080b33 Mon Sep 17 00:00:00 2001 From: N Bhanu Prakash Reddy <32775691+bhanu1131@users.noreply.github.com> Date: Wed, 28 Oct 2020 20:02:45 +0530 Subject: [PATCH 45/84] Create 282_Expression_Add_Operators.cpp (#32) * Create 282_Expression_Add_Operators.cpp, by @bhanu1131 --- cpp/282_Expression_Add_Operators.cpp | 53 ++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 cpp/282_Expression_Add_Operators.cpp 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 Date: Thu, 29 Oct 2020 17:45:36 +0530 Subject: [PATCH 46/84] Create 1248_count_number_of_nice_sub_arrays.cpp (#31) * Create 1248_count_number_of_nice_sub_arrays.cpp, @bhanu1131 --- cpp/1248_count_number_of_nice_sub_arrays.cpp | 42 ++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 cpp/1248_count_number_of_nice_sub_arrays.cpp 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; + } +}; From 5dadae95e823c758f0e9d3f665d09b4a8d30f66a Mon Sep 17 00:00:00 2001 From: N Bhanu Prakash Reddy <32775691+bhanu1131@users.noreply.github.com> Date: Sat, 31 Oct 2020 19:56:35 +0530 Subject: [PATCH 47/84] Create 923_3_sum_with_multiplicity.cpp (#30) * Create 923_3_sum_with_multiplicity.cpp, by @bhanu1131 --- cpp/923_3_sum_with_multiplicity.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 cpp/923_3_sum_with_multiplicity.cpp 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); + } +}; From e0168c2d226d7f2341f9c160a8b119299d0d56ec Mon Sep 17 00:00:00 2001 From: N Bhanu Prakash Reddy <32775691+bhanu1131@users.noreply.github.com> Date: Sun, 1 Nov 2020 19:46:27 +0530 Subject: [PATCH 48/84] Create 201_bitwise_and_of_numbers_range.cpp (#29) * Create 201_bitwise_and_of_numbers_range.cpp, by @bhanu1131 --- cpp/201_bitwise_and_of_numbers_range.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 cpp/201_bitwise_and_of_numbers_range.cpp 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< Date: Sun, 1 Nov 2020 22:26:23 -0800 Subject: [PATCH 49/84] Add 457_Circular_Array_Loop.py (#34) * Add 457_Circular_Array_Loop.py, by @yuchenliu15 --- python/457_Circular_Array_Loop.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 python/457_Circular_Array_Loop.py 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 From 1371de2631d745efba39de41b51c3424e35da434 Mon Sep 17 00:00:00 2001 From: Yuchen Liu Date: Thu, 5 Nov 2020 01:56:38 -0800 Subject: [PATCH 50/84] Fix 067_Add_Binary for Python 3 (#35) * Fix 067_Add_Binary.py for Python, @yuchenliu15 --- python/067_Add_Binary.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 5397bbe4a87dba82dc9fa57abf09a4346aa63f46 Mon Sep 17 00:00:00 2001 From: Yuchen Liu Date: Wed, 25 Nov 2020 05:23:53 -0800 Subject: [PATCH 51/84] Add 168 python solution (#38) * Add 168_Excel_Sheet_Column_Title.py, by @yuchenliu15 --- python/168_Excel_Sheet_Column_Title.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 python/168_Excel_Sheet_Column_Title.py diff --git a/python/168_Excel_Sheet_Column_Title.py b/python/168_Excel_Sheet_Column_Title.py new file mode 100644 index 0000000..582b853 --- /dev/null +++ b/python/168_Excel_Sheet_Column_Title.py @@ -0,0 +1,8 @@ +class Solution: + def convertToTitle(self, n: int) -> str: + res = "" + while n > 0: + n -= 1 + res = chr(65 + n % 26) + res + n //= 26 + return res From 056459464f15df885538aa90f6db882a2f4dbd20 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 4 Mar 2021 21:41:19 +0800 Subject: [PATCH 52/84] Fix python/146_LRU_Cache --- python/146_LRU_Cache.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) 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: From baa5e3186814951036effb1eed4eb611dbf19ece Mon Sep 17 00:00:00 2001 From: Mohan Kumar Paluru <46961568+mohankumarpaluru@users.noreply.github.com> Date: Sun, 18 Jul 2021 20:58:20 +0530 Subject: [PATCH 53/84] Update 009_Palindrome_Number.py (#42) A trick to make it simple and a lot faster --- python/009_Palindrome_Number.py | 34 ++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/python/009_Palindrome_Number.py b/python/009_Palindrome_Number.py index af6890f..8dc7ce5 100644 --- a/python/009_Palindrome_Number.py +++ b/python/009_Palindrome_Number.py @@ -6,19 +6,27 @@ # """ class Solution(object): - 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: 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 From 8207d2c71f39423777cbc7e68550c7ff56895ba7 Mon Sep 17 00:00:00 2001 From: Anish Sachdeva <38917450+anishLearnsToCode@users.noreply.github.com> Date: Wed, 4 Aug 2021 16:00:58 +0200 Subject: [PATCH 54/84] Adds leetcode-algorithms by anish in Other LeetCode repos section (#45) Co-authored-by: Anish Sachdeva --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 7163b06..be64f81 100644 --- a/README.md +++ b/README.md @@ -241,9 +241,10 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal |---| ----- | | 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) From 998b2da1cf107a54a6d3b60b21076660aa530839 Mon Sep 17 00:00:00 2001 From: dvlpsh Date: Sun, 5 Dec 2021 17:47:36 +0530 Subject: [PATCH 55/84] Add 1533_Kth_Missing_Positive_Number.java (#48) * Add Kth_Missing_Positive_Number.java Contributed by @dvlpsh --- java/1533_Kth_Missing_Positive_Number.java | 47 ++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 java/1533_Kth_Missing_Positive_Number.java diff --git a/java/1533_Kth_Missing_Positive_Number.java b/java/1533_Kth_Missing_Positive_Number.java new file mode 100644 index 0000000..c7b0dab --- /dev/null +++ b/java/1533_Kth_Missing_Positive_Number.java @@ -0,0 +1,47 @@ +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=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; + + } +} From ecdb28240dfeedb8ff7948e109062f32fa312d46 Mon Sep 17 00:00:00 2001 From: Paras Yadav <62833829+parascoding@users.noreply.github.com> Date: Sun, 5 Dec 2021 17:51:59 +0530 Subject: [PATCH 56/84] =?UTF-8?q?Create=20Minimize=20the=20Difference=20Be?= =?UTF-8?q?tween=20Target=20and=20Chosen=20Elements=20[19=E2=80=A6=20(#47)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Create Minimize the Difference Between Target and Chosen Elements [1981].java Contributed by @parascoding --- ...ce_Between_Target_and_Chosen_Elements.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java 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..80eebe4 --- /dev/null +++ b/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java @@ -0,0 +1,28 @@ +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 Date: Sun, 5 Dec 2021 20:53:42 +0800 Subject: [PATCH 57/84] Refine 1981 and 1539 format and link --- README.md | 2 + java/1533_Kth_Missing_Positive_Number.java | 47 ------------------- java/1539_Kth_Missing_Positive_Number.java | 43 +++++++++++++++++ ...ce_Between_Target_and_Chosen_Elements.java | 37 ++++++++------- 4 files changed, 64 insertions(+), 65 deletions(-) delete mode 100644 java/1533_Kth_Missing_Positive_Number.java create mode 100644 java/1539_Kth_Missing_Positive_Number.java diff --git a/README.md b/README.md index be64f81..3bcb819 100644 --- a/README.md +++ b/README.md @@ -236,6 +236,8 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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 | +| 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 | | # | To Understand | |---| ----- | diff --git a/java/1533_Kth_Missing_Positive_Number.java b/java/1533_Kth_Missing_Positive_Number.java deleted file mode 100644 index c7b0dab..0000000 --- a/java/1533_Kth_Missing_Positive_Number.java +++ /dev/null @@ -1,47 +0,0 @@ -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=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/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/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java b/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java index 80eebe4..02f474a 100644 --- a/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java +++ b/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java @@ -1,28 +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); + 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 Date: Sun, 5 Dec 2021 21:00:42 +0800 Subject: [PATCH 58/84] Change 012 to Python3 --- python/012_Integer_to_Roman.py | 38 +++++++++++++++++----------------- 1 file changed, 19 insertions(+), 19 deletions(-) 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] From 76137fae30d194b02305ad40855e3f4e75060275 Mon Sep 17 00:00:00 2001 From: Deeksha Tripathi <87656035+Deeeeksha@users.noreply.github.com> Date: Tue, 25 Jan 2022 19:17:40 +0530 Subject: [PATCH 59/84] Add 165_Compare_Version_Numbers (#50) * 165 CompareVersion Solution Contributed by @Deeeeksha --- python/165_Compare_Version_Numbers.py | 29 +++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 python/165_Compare_Version_Numbers.py 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]) Date: Sun, 13 Mar 2022 00:39:55 -0500 Subject: [PATCH 60/84] Create 1189_Maximum_Number_of_Balloons.java (#52) * Create 1189_Maximum_Number_of_Balloons.java * Create 1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py Contributed by @ChesterChangLiu --- java/1189_Maximum_Number_of_Balloons.java | 19 +++++++++++++++++++ ...haracters_That_Have_Odd_Counts_Solution.py | 12 ++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 java/1189_Maximum_Number_of_Balloons.java create mode 100644 python/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py diff --git a/java/1189_Maximum_Number_of_Balloons.java b/java/1189_Maximum_Number_of_Balloons.java new file mode 100644 index 0000000..a37f5e0 --- /dev/null +++ b/java/1189_Maximum_Number_of_Balloons.java @@ -0,0 +1,19 @@ +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; + } +} 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 From d984eb0629e7418d27c800c181a50fee0fd829b1 Mon Sep 17 00:00:00 2001 From: Bithiah Koshy <63845509+vintagemind@users.noreply.github.com> Date: Sun, 13 Mar 2022 16:41:10 +1100 Subject: [PATCH 61/84] Made syntax changes to 005_Longest_Palindromic_Substring.py (#51) Contributed by @vintagemind --- python/005_Longest_Palindromic_Substring.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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")) From dfa3459d9510b1d275f750fe7a76160c7c74cd2f Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Tue, 15 Mar 2022 20:08:47 +0800 Subject: [PATCH 62/84] Add 1189 link & javadev's solution --- README.md | 1 + java/1189_Maximum_Number_of_Balloons.java | 21 +++++++++++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3bcb819..8182c7f 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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 | diff --git a/java/1189_Maximum_Number_of_Balloons.java b/java/1189_Maximum_Number_of_Balloons.java index a37f5e0..4564c55 100644 --- a/java/1189_Maximum_Number_of_Balloons.java +++ b/java/1189_Maximum_Number_of_Balloons.java @@ -1,19 +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])))); + }*/ } From a7808fbba1a349b740c793b9d35a7f816c50950f Mon Sep 17 00:00:00 2001 From: Danny Sepler Date: Mon, 20 Jun 2022 09:36:54 -0400 Subject: [PATCH 63/84] 002 Add Two Numbers: Remove floating point errors (#56) Contributed by @dannysepler --- python/002_Add_Two_Numbers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 250a8c7c7577d8da32b54aeb01e001bbb0eb346a Mon Sep 17 00:00:00 2001 From: Danny Sepler Date: Wed, 22 Jun 2022 20:39:07 -0400 Subject: [PATCH 64/84] 207: Course Schedule (#57) * Add 207_Course_Schedule.py, detect cycle Contributed by @dannysepler --- README.md | 1 + python/207_Course_Schedule.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 python/207_Course_Schedule.py diff --git a/README.md b/README.md index 8182c7f..de13851 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/200_Number_of_Islands.py) | 1. Quick union find, O(nlogn) and O(n^2)
2. BFS with marks, O(n^2) and O(1) | | 204 | [Count Primes](https://leetcode.com/problems/count-primes/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/204_Count_Primes.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/204_Count_Primes.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/204_Count_Primes.cpp) | [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity), O(nloglogn) and O(n) | | 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/206_Reverse_Linked_List.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/206_Reverse_Linked_List.java) [CPP](https://github.com/qiyuangong/leetcode/blob/master/cpp/206_Reverse_Linked_List.cpp) | 1. Stack, O(n) and O(n)
2. Traverse on prev and curr, then curr.next = prev, O(n) and O(1)
3. Recursion, O(n) and O(1) | +| 207 | [Course Schedule](https://leetcode.com/problems/course-schedule/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/207_Course_Schedule.py) | Cycle detection problem | | 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/213_House_Robber_II.py) | f(k) = max(f(k – 2) + num[k], max(dp[0~ls-2],dp[1~ls-1], O(n) and O(1)| | 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/215_Kth_Largest_Element_in_an_Array.py) [Java](https://github.com/qiyuangong/leetcode/blob/master/java/215_Kth_Largest_Element_in_an_Array.java) | 1. Sort, O(n) and O(n)
2. Heap, O(nlgk) and O(n)
3. Quick selection, O(klgn) and O(n)| | 216 | [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/216_Combination_Sum_III.py) | Generate all combinations of length k and keep those that sum to n| 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 From 69d3c1139aebf96b111de28954e9e714ebe3ae01 Mon Sep 17 00:00:00 2001 From: Naveen <70085321+naveen701526@users.noreply.github.com> Date: Thu, 23 Jun 2022 06:14:33 +0530 Subject: [PATCH 65/84] Add 013_roman_to_integer file in java (#54) * Roman in table Contributed by @naveen701526 --- java/013_Roman_to_Integer.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 java/013_Roman_to_Integer.java 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 From d8ab69f400e69ad87abafeb3e938d70e79144667 Mon Sep 17 00:00:00 2001 From: Danny Sepler Date: Sun, 17 Jul 2022 10:50:40 -0400 Subject: [PATCH 66/84] Implement 380, 441, and 981 (#59) * 380_Insert_Delete_GetRandom.py * 441_Arranging_Coins.py * 981_Time_Based_Store.py Contributed by @dannysepler --- README.md | 3 +++ python/380_Insert_Delete_GetRandom.py | 33 +++++++++++++++++++++++++++ python/441_Arranging_Coins.py | 7 ++++++ python/981_Time_Based_Store.py | 26 +++++++++++++++++++++ 4 files changed, 69 insertions(+) create mode 100644 python/380_Insert_Delete_GetRandom.py create mode 100644 python/441_Arranging_Coins.py create mode 100644 python/981_Time_Based_Store.py diff --git a/README.md b/README.md index de13851..2d866fc 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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) | @@ -153,6 +154,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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. | @@ -225,6 +227,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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) | 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/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/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 From aaec50a10beb8dd3d4726c94431656333fc473ba Mon Sep 17 00:00:00 2001 From: BHwi <43560497+BHwi@users.noreply.github.com> Date: Thu, 29 Sep 2022 20:12:01 +0900 Subject: [PATCH 67/84] Added Java solutions for 17, 22 / Python solutions for 2413, 2409, 1909 (#60) * 2413_Smallest_Even_Multiple * 2409_Count_Days_Spent_Together * 1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing In a brute-force way. * Add 17_Letter_Combinations_of_a_Phone_Number.java * Add 22_Generate_Parentheses.java Contributed by @BHwi BHwi Co-authored-by: LONGNEW <40235475+LONGNEW@users.noreply.github.com> --- ...Letter_Combinations_of_a_Phone_Number.java | 40 +++++++++++++++++++ java/22_Generate_Parentheses.java | 26 ++++++++++++ ...t_to_Make_the_Array_Strictly_Increasing.py | 37 +++++++++++++++++ python/2409_Count_Days_Spent_Together.py | 38 ++++++++++++++++++ python/2413_Smallest_Even_Multiple.py | 15 +++++++ 5 files changed, 156 insertions(+) create mode 100644 java/17_Letter_Combinations_of_a_Phone_Number.java create mode 100644 java/22_Generate_Parentheses.java create mode 100644 python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py create mode 100644 python/2409_Count_Days_Spent_Together.py create mode 100644 python/2413_Smallest_Even_Multiple.py 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/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/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/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 + From 183f57fae70231251d39261272de11ae86650046 Mon Sep 17 00:00:00 2001 From: Subin Kim <70996958+green-study@users.noreply.github.com> Date: Sun, 2 Oct 2022 10:07:12 +0900 Subject: [PATCH 68/84] Added java solution for 14 / python solution for 2420 (#61) * Added java solution for 14 / python solution for 2420 * Added : 055_Jump_Game.java Co-authored-by: LONGNEW <40235475+LONGNEW@users.noreply.github.com> Co-authored-by: BHwi --- README.md | 3 ++ java/014_Longest_Common_Prefix.java | 33 +++++++++++++++++++ java/055_Jump_Game.java | 49 ++++++++++++++++++++++++++++ python/2420_Find_All_Good_Indices.py | 38 +++++++++++++++++++++ 4 files changed, 123 insertions(+) create mode 100644 java/014_Longest_Common_Prefix.java create mode 100644 java/055_Jump_Game.java create mode 100644 python/2420_Find_All_Good_Indices.py diff --git a/README.md b/README.md index 2d866fc..dd66ade 100644 --- a/README.md +++ b/README.md @@ -242,7 +242,10 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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 | | # | To Understand | |---| ----- | 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/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/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 From a4519f360108598d27065a63c4b3d8ba24823519 Mon Sep 17 00:00:00 2001 From: Shekhar verma Date: Fri, 7 Oct 2022 05:20:03 +0530 Subject: [PATCH 69/84] Added solution for 392_is_subsequence (#62) * Added solution for 392_is_subsequence * Fixed the code style Co-authored-by: Shekhar-Inochi --- python/392_Is_Subsequence.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 python/392_Is_Subsequence.py 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) From 81abc9f71ef6b05312aa0500388cd017d2cbfc51 Mon Sep 17 00:00:00 2001 From: parkjonggyeong18 <81209336+parkjonggyeong18@users.noreply.github.com> Date: Sat, 8 Oct 2022 11:51:15 +0900 Subject: [PATCH 70/84] Create 732_My_Calendar_III.py (#64) * Added solution for Add 732_My_Calendar_III.py problem from Leetcode Contributed by @parkjonggyeong18 --- python/732_My_Calendar_III.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 python/732_My_Calendar_III.py 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) From b11d3c9d07350a681e492e77fd4541fde88a50ec Mon Sep 17 00:00:00 2001 From: LONGNEW <40235475+LONGNEW@users.noreply.github.com> Date: Sat, 8 Oct 2022 22:58:28 +0900 Subject: [PATCH 71/84] Add 2429_Minimize_XOR.py (#63) * Added solution for 2429. Minimize XOR with Python3 Contributed by @LONGNEW --- README.md | 1 + python/2429_Minimize_XOR.py | 44 +++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 python/2429_Minimize_XOR.py diff --git a/README.md b/README.md index dd66ade..df026f7 100644 --- a/README.md +++ b/README.md @@ -246,6 +246,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 1981 | [Minimize the Difference Between Target and Chosen Elements](https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java) | DP memo[row][sum] to avoid recomputing | | 2409 | [Count Days Spent Together](https://leetcode.com/problems/count-days-spent-together/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2409_Count_Days_Spent_Together.py)| Use month as a day | | 2413 | [Smallest Even Multiple](https://leetcode.com/problems/smallest-even-multiple/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2413_Smallest_Even_Multiple.py)| Check the n is multiply by 2 | +| 2429 | [Minimize XOR](https://leetcode.com/problems/minimize-xor/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2429_Minimize_XOR.py.py) | check the num1, num2 with length and replace "0" compare with num1. | | # | To Understand | |---| ----- | diff --git a/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) From 354044a9eebe2eb8b520b1966cfbf160b1922fa8 Mon Sep 17 00:00:00 2001 From: BHwi <43560497+BHwi@users.noreply.github.com> Date: Sat, 8 Oct 2022 22:59:10 +0900 Subject: [PATCH 72/84] Add java solution for 34 (#65) * Add 034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java Contributed by @BHwi --- ...t_Position_of_Element_in_Sorted_Array.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 java/034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java 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; + } +} From e686121fe601b68816976f2b3b4bb352b31fcf21 Mon Sep 17 00:00:00 2001 From: Subin Kim <70996958+green-study@users.noreply.github.com> Date: Mon, 17 Oct 2022 14:50:33 +0900 Subject: [PATCH 73/84] Added 015_3Sum.java (#67) * Added 015_3Sum.java Contributed by @green-study --- java/015_3Sum.java | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 java/015_3Sum.java 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 + } +} + From fefe70c3ce3fee059a5421fcb27333e431fea8d9 Mon Sep 17 00:00:00 2001 From: LONGNEW <40235475+LONGNEW@users.noreply.github.com> Date: Sun, 30 Oct 2022 12:24:08 +0900 Subject: [PATCH 74/84] Add 523_Continuous_Subarray_Sum.py (#68) * Add 523_Continuous_Subarray_Sum.py Contributed by @LONGNEW --- README.md | 1 + python/523_Continuous_Subarray_Sum.py | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 python/523_Continuous_Subarray_Sum.py diff --git a/README.md b/README.md index df026f7..c34ae3b 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal | 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 | 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 + From 67a842233a5d2d8b13330eb9128c62414d88669f Mon Sep 17 00:00:00 2001 From: Sitesh Pattanaik <12951458+spattk@users.noreply.github.com> Date: Sat, 5 Nov 2022 03:22:39 -0700 Subject: [PATCH 75/84] Added 787 in Java (#69) * Add 787 java. Contributed by @spattk --- java/787_Cheapest_Flight_Within_K_Stops.java | 41 ++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 java/787_Cheapest_Flight_Within_K_Stops.java 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 Date: Sat, 5 Nov 2022 19:23:17 +0900 Subject: [PATCH 76/84] Added 026_Remove_Duplicates_from_Sorted_Array.java (#70) * Added 026_Remove_Duplicates_from_Sorted_Array.java Contributed by @green-study --- .../026_Remove_Duplicates_from_Sorted_Array.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 java/026_Remove_Duplicates_from_Sorted_Array.java 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; + } +} + From b3bd2dded4966d9fecde33fcff5ce4ceba8b672b Mon Sep 17 00:00:00 2001 From: BHwi <43560497+BHwi@users.noreply.github.com> Date: Sat, 12 Nov 2022 00:08:04 +0900 Subject: [PATCH 77/84] Added 049_Group_Anagrams.java, 129_Contains_Duplicate_II.java (#72) * Added java solution for 049_Group_Anagrams.java * Added java solution for 129_Contains_Duplicate_II.java Contributed by @BHwi --- java/049_Group_Anagrams.java | 42 +++++++++++++++++++++++++++ java/219_Contains_Duplicate_II.java | 44 +++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 java/049_Group_Anagrams.java create mode 100644 java/219_Contains_Duplicate_II.java 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/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; + } +} From 7951e9e57697ccbd7d968b48d13fe2a4b77d2c85 Mon Sep 17 00:00:00 2001 From: Subin Kim <70996958+green-study@users.noreply.github.com> Date: Sun, 27 Nov 2022 11:56:54 +0900 Subject: [PATCH 78/84] Added 039_Combination_Sum.java (#75) * Added 039_Combination_Sum.java Contributed by @green-study --- java/039_Combination_Sum.java | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 java/039_Combination_Sum.java 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); + } + } + } +} + From 9c0ddc4ef9522c90ef020cb0608f86acded02f12 Mon Sep 17 00:00:00 2001 From: LONGNEW <40235475+LONGNEW@users.noreply.github.com> Date: Mon, 28 Nov 2022 20:47:14 +0900 Subject: [PATCH 79/84] Update Q1, Q7 answer (#76) * Update 001_Two_Sum.py * Update 007_Reverse_Integer.py Contributed by @LONGNEW --- python/001_Two_Sum.py | 7 +---- python/007_Reverse_Integer.py | 50 ++++++++++------------------------- 2 files changed, 15 insertions(+), 42 deletions(-) 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/007_Reverse_Integer.py b/python/007_Reverse_Integer.py index a125d47..9f3f20f 100644 --- a/python/007_Reverse_Integer.py +++ b/python/007_Reverse_Integer.py @@ -1,39 +1,17 @@ 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 - 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 + value = 2 ** 31 + x = int(x) + if -value <= x < value: + return x + return 0 + From b369d126fe6e5fb5ab5111e745222f34ed3aa533 Mon Sep 17 00:00:00 2001 From: Subin Kim <70996958+green-study@users.noreply.github.com> Date: Sun, 4 Dec 2022 11:34:34 +0900 Subject: [PATCH 80/84] Update 006_ZigZag_conversion.java (#77) * Update 006_ZigZag_conversion.java Contributed by @green-study --- java/006_ZigZag_Conversion.java | 34 ++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) 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 Date: Thu, 16 Feb 2023 13:46:59 +0530 Subject: [PATCH 81/84] 2553_Separate_the_Digits_in_an_Array.cpp (#78) * Contributed by @ritikraj018 --- cpp/2553_Separate_the_Digits_in_an_Array.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 cpp/2553_Separate_the_Digits_in_an_Array.cpp 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; + } +}; From 5a52cd9b54553d68ee10cfe87044bed79ee5fb93 Mon Sep 17 00:00:00 2001 From: Yuchen Zhou <72342196+ROMEEZHOU@users.noreply.github.com> Date: Tue, 21 Mar 2023 21:31:55 -0400 Subject: [PATCH 82/84] Add a new method for 007_Reverse_Integer.py (#80) * Add a new method for 007 reverse integer Contributed by @ROMEEZHOU --- python/007_Reverse_Integer.py | 39 +++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/python/007_Reverse_Integer.py b/python/007_Reverse_Integer.py index 9f3f20f..19aeba8 100644 --- a/python/007_Reverse_Integer.py +++ b/python/007_Reverse_Integer.py @@ -1,17 +1,34 @@ class Solution: def reverse(self, x): # https://leetcode.com/problems/reverse-integer/ - flag = True if x < 0 else False - if flag: +# flag = True if x < 0 else False +# if flag: +# x = -x +# x = str(x)[::-1] + +# if flag: +# x = "-" + x + +# value = 2 ** 31 +# x = int(x) +# if -value <= x < value: +# return x +# return 0 + + is_neg = False + if x < 0: x = -x - x = str(x)[::-1] + is_neg = True - if flag: - x = "-" + x + res = 0 + while x > 0: + res *= 10 + res += x % 10 + x //= 10 + if is_neg: + res = -res - value = 2 ** 31 - x = int(x) - if -value <= x < value: - return x - return 0 - + if res < -2**31 or res > 2**31-1: + return 0 + return res + \ No newline at end of file From 9adfbdf343963ee16696aa85f0846fe544105430 Mon Sep 17 00:00:00 2001 From: Ajay <86017484+ajay2614@users.noreply.github.com> Date: Fri, 19 May 2023 13:05:04 +0530 Subject: [PATCH 83/84] Create 442_Find_All_Duplicates_in_an_Array.java (#81) Contributed by @ajay2614 --- java/442_Find_All_Duplicates_in_an_Array.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 java/442_Find_All_Duplicates_in_an_Array.java 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 Date: Tue, 3 Oct 2023 06:22:10 -0400 Subject: [PATCH 84/84] 88. Merge Sorted Array Java (#82) Added the solution to 'Merge Sorted Array' which is number 88 in LeetCode Contributed by @avash-poudel --- java/088_Merge_Sorted_Array.java | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 java/088_Merge_Sorted_Array.java 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