From 056459464f15df885538aa90f6db882a2f4dbd20 Mon Sep 17 00:00:00 2001 From: Qiyuan Gong Date: Thu, 4 Mar 2021 21:41:19 +0800 Subject: [PATCH 01/33] 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 02/33] 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 03/33] 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 04/33] 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 05/33] =?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 06/33] 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 07/33] 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 08/33] 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 09/33] 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 10/33] 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 11/33] 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 12/33] 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 13/33] 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 14/33] 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 15/33] 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 16/33] 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 17/33] 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 18/33] 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 19/33] 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 20/33] 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 21/33] 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 22/33] 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 23/33] 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 24/33] 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 25/33] 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 26/33] 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 27/33] 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 28/33] 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 29/33] 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 30/33] 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 31/33] 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 32/33] 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 33/33] 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