From 0c2f6dad3a10fffeb283965148d0519dac68a7f5 Mon Sep 17 00:00:00 2001 From: Arshdeep Singh Date: Sat, 2 Oct 2021 15:42:07 +0530 Subject: [PATCH 01/15] Added C++ code for Diameter of Binary Tree (#257) * Adding code of Diameter of Binary Tree for Cpp * Update README.md --- README.md | 2 +- .../diameterOfBinaryTree.cpp | 31 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 algorithms/cpp/diameterOfBinaryTree/diameterOfBinaryTree.cpp diff --git a/README.md b/README.md index 12aa7478..0bfb7b47 100644 --- a/README.md +++ b/README.md @@ -216,7 +216,7 @@ LeetCode |572|[Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/) | [Python](./algorithms/python/SubtreeOfAnotherTree/isSubtree.py)|Easy| |563|[Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/) | [Python](./algorithms/python/BinaryTreeTilt/findTilt.py)|Easy| |547|[Friend Circles](https://leetcode.com/problems/friend-circles/) | [C++](./algorithms/cpp/friendCircles/FriendCircles.cpp)|Medium| -|543|[Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [Python](./algorithms/python/DiameterOfBinaryTree/diameterOfBinaryTree.py)|Easy| +|543|[Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [C++](./algorithms/cpp/diameterOfBinaryTree/diameterOfBinaryTree.cpp), [Python](./algorithms/python/DiameterOfBinaryTree/diameterOfBinaryTree.py)|Easy| |538|[Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) | [Python](./algorithms/python/ConvertBSTtoGreaterTree/convertBST.py)|Easy| |532|[K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array/) | [Python](./algorithms/python/K-diffPairsInAnArray/findPairs.py)|Easy| |520|[Detect Capital](https://leetcode.com/problems/detect-capital/) | [C++](./algorithms/cpp/detectCapital/DetectCapital.cpp)|Easy| diff --git a/algorithms/cpp/diameterOfBinaryTree/diameterOfBinaryTree.cpp b/algorithms/cpp/diameterOfBinaryTree/diameterOfBinaryTree.cpp new file mode 100644 index 00000000..bb5aa6df --- /dev/null +++ b/algorithms/cpp/diameterOfBinaryTree/diameterOfBinaryTree.cpp @@ -0,0 +1,31 @@ +// Source : https://leetcode.com/problems/add-and-search-word-data-structure-design/ +// Author : Arshdeep Singh +// Date : 2021-10-01 +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +private: + int diameter; + int maxDepth(TreeNode* root) { + if(root==NULL) return 0; + int left = maxDepth(root->left); + int right = maxDepth(root->right); + diameter = max(diameter, left + right); + return 1 + max(left, right); + } +public: + int diameterOfBinaryTree(TreeNode* root) { + diameter = 0; + maxDepth(root); + return diameter; + } +}; From 36168cc9e1304d538d6b934b45c0c2f31240b4e4 Mon Sep 17 00:00:00 2001 From: Pier Carlo Cadoppi Date: Fri, 12 Nov 2021 07:44:57 +0100 Subject: [PATCH 02/15] grammar (#259) --- algorithms/cpp/twoSum/twoSum.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/algorithms/cpp/twoSum/twoSum.cpp b/algorithms/cpp/twoSum/twoSum.cpp index dc0680f8..f0e9692e 100644 --- a/algorithms/cpp/twoSum/twoSum.cpp +++ b/algorithms/cpp/twoSum/twoSum.cpp @@ -46,8 +46,8 @@ class Solution { // // 1) Traverse the array one by one // 2) just put the `target - num[i]`(not `num[i]`) into the map - // so, when we checking the next num[i], if we found it is exisited in the map. - // which means we found the second one. + // so, when we checking the next num[i], if we found it existed in the map, + // it means we found the second one. // vector twoSum(vector &numbers, int target) { unordered_map m; @@ -55,7 +55,7 @@ class Solution { for(int i=0; i Date: Fri, 12 Nov 2021 14:46:08 +0800 Subject: [PATCH 03/15] Fix possible out of bound array access (#254) Should check array size before accessing the second to fourth bytes of utf8 as there might be not enough data left in the array. --- algorithms/cpp/UTF8Validation/UTF8Validation.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/algorithms/cpp/UTF8Validation/UTF8Validation.cpp b/algorithms/cpp/UTF8Validation/UTF8Validation.cpp index 619b8ab6..5b0fe7ac 100644 --- a/algorithms/cpp/UTF8Validation/UTF8Validation.cpp +++ b/algorithms/cpp/UTF8Validation/UTF8Validation.cpp @@ -67,6 +67,10 @@ class Solution { return false; } + // invalid utf-8 as it doesn't have enough 10xxxxxx + if (i + len > data.size()) { + return false; + } for (int j=i+1; j < i+len; j++) { //checking 10xxxxxx if ( (data[j] & 0xC0) != 0x80 ) { @@ -75,11 +79,6 @@ class Solution { } i += len ; - - if (i > data.size()) { - return false; - } - } return true; } From cf082223dd1c05b4cd460ce5d2063e4f04ef558f Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Thu, 22 Jul 2021 17:32:40 +0800 Subject: [PATCH 04/15] New Problem Solution - "1935. Maximum Number of Words You Can Type" --- README.md | 1 + .../MaximumNumberOfWordsYouCanType.cpp | 64 +++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp diff --git a/README.md b/README.md index 0bfb7b47..20a9c568 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|1935|[Maximum Number of Words You Can Type](https://leetcode.com/problems/maximum-number-of-words-you-can-type/) | [C++](./algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp)|Easy| |1882|[Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers/) | [C++](./algorithms/cpp/processTasksUsingServers/ProcessTasksUsingServers.cpp)|Medium| |1881|[Maximum Value after Insertion](https://leetcode.com/problems/maximum-value-after-insertion/) | [C++](./algorithms/cpp/maximumValueAfterInsertion/MaximumValueAfterInsertion.cpp)|Medium| |1880|[Check if Word Equals Summation of Two Words](https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/) | [C++](./algorithms/cpp/checkIfWordEqualsSummationOfTwoWords/CheckIfWordEqualsSummationOfTwoWords.cpp)|Easy| diff --git a/algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp b/algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp new file mode 100644 index 00000000..8b1cd357 --- /dev/null +++ b/algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp @@ -0,0 +1,64 @@ +// Source : https://leetcode.com/problems/maximum-number-of-words-you-can-type/ +// Author : Hao Chen +// Date : 2021-07-22 + +/***************************************************************************************************** + * + * There is a malfunctioning keyboard where some letter keys do not work. All other keys on the + * keyboard work properly. + * + * Given a string text of words separated by a single space (no leading or trailing spaces) and a + * string brokenLetters of all distinct letter keys that are broken, return the number of words in + * text you can fully type using this keyboard. + * + * Example 1: + * + * Input: text = "hello world", brokenLetters = "ad" + * Output: 1 + * Explanation: We cannot type "world" because the 'd' key is broken. + * + * Example 2: + * + * Input: text = "leet code", brokenLetters = "lt" + * Output: 1 + * Explanation: We cannot type "leet" because the 'l' and 't' keys are broken. + * + * Example 3: + * + * Input: text = "leet code", brokenLetters = "e" + * Output: 0 + * Explanation: We cannot type either word because the 'e' key is broken. + * + * Constraints: + * + * 1 <= text.length <= 10^4 + * 0 <= brokenLetters.length <= 26 + * text consists of words separated by a single space without any leading or trailing spaces. + * Each word only consists of lowercase English letters. + * brokenLetters consists of distinct lowercase English letters. + ******************************************************************************************************/ + +class Solution { +public: + int canBeTypedWords(string text, string brokenLetters) { + vector borken(26, false); + + for (auto ch : brokenLetters) { + borken[ch - 'a'] = true; + } + + text += ' '; + int cnt = 0; + for (int i = 0; i < text.size(); i++ ) { + if ( text[i] == ' ') continue; + + bool skip = false; + for (; text[i] != ' '; i++ ) { + if (borken[text[i] - 'a'] == true ) skip = true; + } + if ( !skip ) cnt++; + } + + return cnt; + } +}; From 0391e520514e06a7fd837b595f8e126fe217dfaf Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Fri, 12 Nov 2021 14:59:12 +0800 Subject: [PATCH 05/15] New Problem Solution - "1945. Sum of Digits of String After Convert" --- README.md | 1 + .../SumOfDigitsOfStringAfterConvert.cpp | 77 +++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp diff --git a/README.md b/README.md index 20a9c568..4345c749 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|1945|[Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert/) | [C++](/Users/chenhao/GitHub/leetcode/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp)|Easy| |1935|[Maximum Number of Words You Can Type](https://leetcode.com/problems/maximum-number-of-words-you-can-type/) | [C++](./algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp)|Easy| |1882|[Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers/) | [C++](./algorithms/cpp/processTasksUsingServers/ProcessTasksUsingServers.cpp)|Medium| |1881|[Maximum Value after Insertion](https://leetcode.com/problems/maximum-value-after-insertion/) | [C++](./algorithms/cpp/maximumValueAfterInsertion/MaximumValueAfterInsertion.cpp)|Medium| diff --git a/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp b/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp new file mode 100644 index 00000000..d2dcfe72 --- /dev/null +++ b/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp @@ -0,0 +1,77 @@ +// Source : https://leetcode.com/problems/sum-of-digits-of-string-after-convert/ +// Author : Hao Chen +// Date : 2021-11-12 + +/***************************************************************************************************** + * + * You are given a string s consisting of lowercase English letters, and an integer k. + * + * First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., + * replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with + * the sum of its digits. Repeat the transform operation k times in total. + * + * For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following + * operations: + * + * Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124 + * Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17 + * Transform #2: 17 ➝ 1 + 7 ➝ 8 + * + * Return the resulting integer after performing the operations described above. + * + * Example 1: + * + * Input: s = "iiii", k = 1 + * Output: 36 + * Explanation: The operations are as follows: + * - Convert: "iiii" ➝ "(9)(9)(9)(9)" ➝ "9999" ➝ 9999 + * - Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36 + * Thus the resulting integer is 36. + * + * Example 2: + * + * Input: s = "leetcode", k = 2 + * Output: 6 + * Explanation: The operations are as follows: + * - Convert: "leetcode" ➝ "(12)(5)(5)(20)(3)(15)(4)(5)" ➝ "12552031545" ➝ 12552031545 + * - Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33 + * - Transform #2: 33 ➝ 3 + 3 ➝ 6 + * Thus the resulting integer is 6. + * + * Example 3: + * + * Input: s = "zbax", k = 2 + * Output: 8 + * + * Constraints: + * + * 1 <= s.length <= 100 + * 1 <= k <= 10 + * s consists of lowercase English letters. + ******************************************************************************************************/ + +class Solution { +public: + int sumChar(char c) { + int x = c - 'a' + 1; + return x < 10 ? x : x / 10 + x % 10; + } + int sumInt(int x) { + int s = 0; + while( x > 0 ) { + s += x % 10; + x /= 10; + } + return s; + } + int getLucky(string s, int k) { + int result = 0; + for (auto c : s) { + result += sumChar(c); + } + for (; k > 1 ; k--) { + result = sumInt(result); + } + return result; + } +}; From 322889d77f4611627d91e7c09a8a0bc7227f2f8e Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Fri, 12 Nov 2021 15:00:15 +0800 Subject: [PATCH 06/15] New Problem Solution - "1946. Largest Number After Mutating Substring" --- README.md | 1 + .../LargestNumberAfterMutatingSubstring.cpp | 68 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp diff --git a/README.md b/README.md index 4345c749..43c07fe4 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|1946|[Largest Number After Mutating Substring](https://leetcode.com/problems/largest-number-after-mutating-substring/) | [C++](/Users/chenhao/GitHub/leetcode/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp)|Medium| |1945|[Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert/) | [C++](/Users/chenhao/GitHub/leetcode/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp)|Easy| |1935|[Maximum Number of Words You Can Type](https://leetcode.com/problems/maximum-number-of-words-you-can-type/) | [C++](./algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp)|Easy| |1882|[Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers/) | [C++](./algorithms/cpp/processTasksUsingServers/ProcessTasksUsingServers.cpp)|Medium| diff --git a/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp b/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp new file mode 100644 index 00000000..7dd3c765 --- /dev/null +++ b/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp @@ -0,0 +1,68 @@ +// Source : https://leetcode.com/problems/largest-number-after-mutating-substring/ +// Author : Hao Chen +// Date : 2021-11-12 + +/***************************************************************************************************** + * + * You are given a string num, which represents a large integer. You are also given a 0-indexed + * integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d + * maps to digit change[d]. + * + * You may choose to mutate a single substring of num. To mutate a substring, replace each digit + * num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]). + * + * Return a string representing the largest possible integer after mutating (or choosing not to) a + * single substring of num. + * + * A substring is a contiguous sequence of characters within the string. + * + * Example 1: + * + * Input: num = "132", change = [9,8,5,0,3,6,4,2,6,8] + * Output: "832" + * Explanation: Replace the substring "1": + * - 1 maps to change[1] = 8. + * Thus, "132" becomes "832". + * "832" is the largest number that can be created, so return it. + * + * Example 2: + * + * Input: num = "021", change = [9,4,3,5,7,2,1,9,0,6] + * Output: "934" + * Explanation: Replace the substring "021": + * - 0 maps to change[0] = 9. + * - 2 maps to change[2] = 3. + * - 1 maps to change[1] = 4. + * Thus, "021" becomes "934". + * "934" is the largest number that can be created, so return it. + * + * Example 3: + * + * Input: num = "5", change = [1,4,7,5,3,2,5,6,9,4] + * Output: "5" + * Explanation: "5" is already the largest number that can be created, so return it. + * + * Constraints: + * + * 1 <= num.length <= 10^5 + * num consists of only digits 0-9. + * change.length == 10 + * 0 <= change[d] <= 9 + ******************************************************************************************************/ + +class Solution { +public: + string maximumNumber(string num, vector& change) { + bool replace = false; + for(int i=0; i change[n] && replace ) { + break; + } + } + return num; + } +}; From 8055bef28f09ae1b3d923c989bff6e336ea7c136 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Fri, 12 Nov 2021 15:32:57 +0800 Subject: [PATCH 07/15] New Problem Solution - "1876. Substrings of Size Three with Distinct Characters" --- README.md | 1 + ...ringsOfSizeThreeWithDistinctCharacters.cpp | 67 +++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp diff --git a/README.md b/README.md index 43c07fe4..f3f57fa7 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ LeetCode |1882|[Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers/) | [C++](./algorithms/cpp/processTasksUsingServers/ProcessTasksUsingServers.cpp)|Medium| |1881|[Maximum Value after Insertion](https://leetcode.com/problems/maximum-value-after-insertion/) | [C++](./algorithms/cpp/maximumValueAfterInsertion/MaximumValueAfterInsertion.cpp)|Medium| |1880|[Check if Word Equals Summation of Two Words](https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/) | [C++](./algorithms/cpp/checkIfWordEqualsSummationOfTwoWords/CheckIfWordEqualsSummationOfTwoWords.cpp)|Easy| +|1876|[Substrings of Size Three with Distinct Characters](https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/submissions/) | [C++](/Users/chenhao/GitHub/leetcode/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp)|Easy| |1871|[Jump Game VII](https://leetcode.com/problems/jump-game-vii/) | [C++](./algorithms/cpp/jumpGame/jumpGame.VII.cpp)|Medium| |1870|[Minimum Speed to Arrive on Time](https://leetcode.com/problems/minimum-speed-to-arrive-on-time/) | [C++](./algorithms/cpp/minimumSpeedToArriveOnTime/MinimumSpeedToArriveOnTime.cpp)|Medium| |1869|[Longer Contiguous Segments of Ones than Zeros](https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros/) | [C++](./algorithms/cpp/longerContiguousSegmentsOfOnesThanZeros/LongerContiguousSegmentsOfOnesThanZeros.cpp)|Easy| diff --git a/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp b/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp new file mode 100644 index 00000000..fd5972f2 --- /dev/null +++ b/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp @@ -0,0 +1,67 @@ +// Source : https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/submissions/ +// Author : Hao Chen +// Date : 2021-11-12 + +/***************************************************************************************************** + * + * A string is good if there are no repeated characters. + * + * Given a string s, return the number of good substrings of length three in s. + * + * Note that if there are multiple occurrences of the same substring, every occurrence should be + * counted. + * + * A substring is a contiguous sequence of characters in a string. + * + * Example 1: + * + * Input: s = "xyzzaz" + * Output: 1 + * Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". + * The only good substring of length 3 is "xyz". + * + * Example 2: + * + * Input: s = "aababcabc" + * Output: 4 + * Explanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc". + * The good substrings are "abc", "bca", "cab", and "abc". + * + * Constraints: + * + * 1 <= s.length <= 100 + * s consists of lowercase English letters. + ******************************************************************************************************/ + +class Solution { +public: + int countGoodSubstrings(string s) { + char exist[26] = {0}; + + int cnt = 0, c = 0; + + + for (int i = 0; i 2) { + char ch = s[i-3]-'a'; + exist[ch]--; + if ( exist[ch] == 0 ) c--; + } + + exist[ch]++; + if (exist[ch] == 1 ) { + c++; + } + + if ( c == 3 ){ + cnt++; + } + + + } + + return cnt; + } +}; From ab313d18dfb0e626c88f04444786ffbfac7c1c31 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Fri, 12 Nov 2021 15:51:52 +0800 Subject: [PATCH 08/15] New Problem Solution - "1877. Minimize Maximum Pair Sum in Array" --- README.md | 1 + .../MinimizeMaximumPairSumInArray.cpp | 53 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp diff --git a/README.md b/README.md index f3f57fa7..de39418e 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ LeetCode |1882|[Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers/) | [C++](./algorithms/cpp/processTasksUsingServers/ProcessTasksUsingServers.cpp)|Medium| |1881|[Maximum Value after Insertion](https://leetcode.com/problems/maximum-value-after-insertion/) | [C++](./algorithms/cpp/maximumValueAfterInsertion/MaximumValueAfterInsertion.cpp)|Medium| |1880|[Check if Word Equals Summation of Two Words](https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/) | [C++](./algorithms/cpp/checkIfWordEqualsSummationOfTwoWords/CheckIfWordEqualsSummationOfTwoWords.cpp)|Easy| +|1877|[Minimize Maximum Pair Sum in Array](https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/) | [C++](/Users/chenhao/GitHub/leetcode/minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp)|Medium| |1876|[Substrings of Size Three with Distinct Characters](https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/submissions/) | [C++](/Users/chenhao/GitHub/leetcode/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp)|Easy| |1871|[Jump Game VII](https://leetcode.com/problems/jump-game-vii/) | [C++](./algorithms/cpp/jumpGame/jumpGame.VII.cpp)|Medium| |1870|[Minimum Speed to Arrive on Time](https://leetcode.com/problems/minimum-speed-to-arrive-on-time/) | [C++](./algorithms/cpp/minimumSpeedToArriveOnTime/MinimumSpeedToArriveOnTime.cpp)|Medium| diff --git a/minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp b/minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp new file mode 100644 index 00000000..ead47d11 --- /dev/null +++ b/minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp @@ -0,0 +1,53 @@ +// Source : https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/ +// Author : Hao Chen +// Date : 2021-11-12 + +/***************************************************************************************************** + * + * The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a + * list of pairs. + * + * For example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be + * max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8. + * + * Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: + * + * Each element of nums is in exactly one pair, and + * The maximum pair sum is minimized. + * + * Return the minimized maximum pair sum after optimally pairing up the elements. + * + * Example 1: + * + * Input: nums = [3,5,2,3] + * Output: 7 + * Explanation: The elements can be paired up into pairs (3,3) and (5,2). + * The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. + * + * Example 2: + * + * Input: nums = [3,5,4,2,4,6] + * Output: 8 + * Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2). + * The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. + * + * Constraints: + * + * n == nums.length + * 2 <= n <= 10^5 + * n is even. + * 1 <= nums[i] <= 10^5 + ******************************************************************************************************/ + +class Solution { +public: + int minPairSum(vector& nums) { + sort(nums.begin(), nums.end()); + int i = 0, j = nums.size() - 1; + int m = 0; + for(int i = 0, j = nums.size() - 1; i < j; i++,j--) { + m = max(m, nums[i] + nums[j]); + } + return m; + } +}; From 202f09881531994046f79237c993b425339f0889 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Fri, 12 Nov 2021 15:58:28 +0800 Subject: [PATCH 09/15] fix the wrong directory & file position --- README.md | 8 ++++---- .../LargestNumberAfterMutatingSubstring.cpp | 0 .../MinimizeMaximumPairSumInArray.cpp | 0 .../SubstringsOfSizeThreeWithDistinctCharacters.cpp | 0 .../SumOfDigitsOfStringAfterConvert.cpp | 0 5 files changed, 4 insertions(+), 4 deletions(-) rename {largestNumberAfterMutatingSubstring => algorithms/cpp/largestNumberAfterMutatingSubstring}/LargestNumberAfterMutatingSubstring.cpp (100%) rename {minimizeMaximumPairSumInArray => algorithms/cpp/minimizeMaximumPairSumInArray}/MinimizeMaximumPairSumInArray.cpp (100%) rename {substringsOfSizeThreeWithDistinctCharacters => algorithms/cpp/substringsOfSizeThreeWithDistinctCharacters}/SubstringsOfSizeThreeWithDistinctCharacters.cpp (100%) rename {sumOfDigitsOfStringAfterConvert => algorithms/cpp/sumOfDigitsOfStringAfterConvert}/SumOfDigitsOfStringAfterConvert.cpp (100%) diff --git a/README.md b/README.md index de39418e..f777728b 100644 --- a/README.md +++ b/README.md @@ -9,14 +9,14 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | -|1946|[Largest Number After Mutating Substring](https://leetcode.com/problems/largest-number-after-mutating-substring/) | [C++](/Users/chenhao/GitHub/leetcode/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp)|Medium| -|1945|[Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert/) | [C++](/Users/chenhao/GitHub/leetcode/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp)|Easy| +|1946|[Largest Number After Mutating Substring](https://leetcode.com/problems/largest-number-after-mutating-substring/) | [C++](./algorithms/cpp/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp)|Medium| +|1945|[Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert/) | [C++](./algorithms/cpp/leetcode/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp)|Easy| |1935|[Maximum Number of Words You Can Type](https://leetcode.com/problems/maximum-number-of-words-you-can-type/) | [C++](./algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp)|Easy| |1882|[Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers/) | [C++](./algorithms/cpp/processTasksUsingServers/ProcessTasksUsingServers.cpp)|Medium| |1881|[Maximum Value after Insertion](https://leetcode.com/problems/maximum-value-after-insertion/) | [C++](./algorithms/cpp/maximumValueAfterInsertion/MaximumValueAfterInsertion.cpp)|Medium| |1880|[Check if Word Equals Summation of Two Words](https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/) | [C++](./algorithms/cpp/checkIfWordEqualsSummationOfTwoWords/CheckIfWordEqualsSummationOfTwoWords.cpp)|Easy| -|1877|[Minimize Maximum Pair Sum in Array](https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/) | [C++](/Users/chenhao/GitHub/leetcode/minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp)|Medium| -|1876|[Substrings of Size Three with Distinct Characters](https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/submissions/) | [C++](/Users/chenhao/GitHub/leetcode/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp)|Easy| +|1877|[Minimize Maximum Pair Sum in Array](https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/) | [C++](./algorithms/cpp/minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp)|Medium| +|1876|[Substrings of Size Three with Distinct Characters](https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/submissions/) | [C++](./algorithms/cpp/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp)|Easy| |1871|[Jump Game VII](https://leetcode.com/problems/jump-game-vii/) | [C++](./algorithms/cpp/jumpGame/jumpGame.VII.cpp)|Medium| |1870|[Minimum Speed to Arrive on Time](https://leetcode.com/problems/minimum-speed-to-arrive-on-time/) | [C++](./algorithms/cpp/minimumSpeedToArriveOnTime/MinimumSpeedToArriveOnTime.cpp)|Medium| |1869|[Longer Contiguous Segments of Ones than Zeros](https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros/) | [C++](./algorithms/cpp/longerContiguousSegmentsOfOnesThanZeros/LongerContiguousSegmentsOfOnesThanZeros.cpp)|Easy| diff --git a/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp b/algorithms/cpp/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp similarity index 100% rename from largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp rename to algorithms/cpp/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp diff --git a/minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp b/algorithms/cpp/minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp similarity index 100% rename from minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp rename to algorithms/cpp/minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp diff --git a/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp b/algorithms/cpp/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp similarity index 100% rename from substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp rename to algorithms/cpp/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp diff --git a/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp b/algorithms/cpp/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp similarity index 100% rename from sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp rename to algorithms/cpp/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp From ecb5b88532d6b521272cc11246dc728415e3ed16 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Mon, 15 Nov 2021 19:53:24 +0800 Subject: [PATCH 10/15] New Problem Solution - "1884. Egg Drop With 2 Eggs and N Floors" --- README.md | 1 + .../EggDropWith2EggsAndNFloors.cpp | 89 +++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 algorithms/cpp/eggDropWith2EggsAndNFloors/EggDropWith2EggsAndNFloors.cpp diff --git a/README.md b/README.md index f777728b..0ab766d0 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ LeetCode |1946|[Largest Number After Mutating Substring](https://leetcode.com/problems/largest-number-after-mutating-substring/) | [C++](./algorithms/cpp/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp)|Medium| |1945|[Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert/) | [C++](./algorithms/cpp/leetcode/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp)|Easy| |1935|[Maximum Number of Words You Can Type](https://leetcode.com/problems/maximum-number-of-words-you-can-type/) | [C++](./algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp)|Easy| +|1884|[Egg Drop With 2 Eggs and N Floors](https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/) | [C++](./algorithms/cpp/eggDropWith2EggsAndNFloors/EggDropWith2EggsAndNFloors.cpp)|Medium| |1882|[Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers/) | [C++](./algorithms/cpp/processTasksUsingServers/ProcessTasksUsingServers.cpp)|Medium| |1881|[Maximum Value after Insertion](https://leetcode.com/problems/maximum-value-after-insertion/) | [C++](./algorithms/cpp/maximumValueAfterInsertion/MaximumValueAfterInsertion.cpp)|Medium| |1880|[Check if Word Equals Summation of Two Words](https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/) | [C++](./algorithms/cpp/checkIfWordEqualsSummationOfTwoWords/CheckIfWordEqualsSummationOfTwoWords.cpp)|Easy| diff --git a/algorithms/cpp/eggDropWith2EggsAndNFloors/EggDropWith2EggsAndNFloors.cpp b/algorithms/cpp/eggDropWith2EggsAndNFloors/EggDropWith2EggsAndNFloors.cpp new file mode 100644 index 00000000..b56331a5 --- /dev/null +++ b/algorithms/cpp/eggDropWith2EggsAndNFloors/EggDropWith2EggsAndNFloors.cpp @@ -0,0 +1,89 @@ +// Source : https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/ +// Author : Hao Chen +// Date : 2021-11-15 + +/***************************************************************************************************** + * + * You are given two identical eggs and you have access to a building with n floors labeled from 1 to + * n. + * + * You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher + * than f will break, and any egg dropped at or below floor f will not break. + * + * In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the + * egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in + * future moves. + * + * Return the minimum number of moves that you need to determine with certainty what the value of f is. + * + * Example 1: + * + * Input: n = 2 + * Output: 2 + * Explanation: We can drop the first egg from floor 1 and the second egg from floor 2. + * If the first egg breaks, we know that f = 0. + * If the second egg breaks but the first egg didn't, we know that f = 1. + * Otherwise, if both eggs survive, we know that f = 2. + * + * Example 2: + * + * Input: n = 100 + * Output: 14 + * Explanation: One optimal strategy is: + * - Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting + * from floor 1 and going up one at a time to find f within 7 more drops. Total drops is 1 + 7 = 8. + * - If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is + * between 9 + * and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 + * more + * drops. Total drops is 2 + 12 = 14. + * - If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors + * 34, 45, + * 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100. + * Regardless of the outcome, it takes at most 14 drops to determine f. + * + * Constraints: + * + * 1 <= n <= 1000 + ******************************************************************************************************/ + +/* + 1 floor - 1 attemp + 2 floors - 2 attemps + 3 floors - 2 attemps + 4 floors - 3 attemps + 5 floors - 3 attemps + 6 floors - 3 attemps + 7 floors - 4 attemps + ... + 11 floors - 5 attemps + ... + 16 floors - 6 attemps + ... + 22 floors - 7 attemps + ... + + we can see: + floor(1) = 1 + floor(2) = 2 + floor(4) = 3 + floor(7) = 4 + floor(11) = 5 + floor(16) = 6 + floor(22) = 7 + ... + + */ + + +class Solution { +public: + int twoEggDrop(int n) { + int c = 1, i=1; + while(c < n) { + c += i; + i++; + } + return c==n ? i : i-1; + } +}; From e00c0f6094f1a835cdbc48c4a0587f373830d76d Mon Sep 17 00:00:00 2001 From: Ektedar Alam Date: Mon, 31 Jan 2022 03:05:11 -0500 Subject: [PATCH 11/15] Adding Swim In Rising Water Problem LeetCode #776 (#269) --- README.md | 1 + .../SwimInRisingWater/swim_in_rising_water.py | 41 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 algorithms/python/SwimInRisingWater/swim_in_rising_water.py diff --git a/README.md b/README.md index 0ab766d0..4cbdb6eb 100644 --- a/README.md +++ b/README.md @@ -196,6 +196,7 @@ LeetCode |830|[Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups/) | [Python](./algorithms/python/PositionsOfLargeGroups/largeGroupPositions.py)|Easy| |820|[Short Encoding of Words](https://leetcode.com/problems/short-encoding-of-words/) | [C++](./algorithms/cpp/shortEncodingOfWords/ShortEncodingOfWords.cpp)|Medium| |804|[Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [C++](./algorithms/cpp/uniqueMorseCodeWords/UniqueMorseCodeWords.cpp)|Easy| +|776|[Swim In Rising Water](https://leetcode.com/problems/swim-in-rising-water/description/) | [Python](./algorithms/python/SwimInRisingWater/swim_in_rising_water.py)|Hard| |771|[Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/description) | [C++](./algorithms/cpp/jewelsAndStones/JewelsAndStones.cpp)|Easy| |747|[Largest Number At Least Twice of Others](https://leetcode.com/problems/largest-number-at-least-twice-of-others/) | [Python](./algorithms/python/LargestNumberAtLeastTwiceOfOthers/dominantIndex.py)|Easy| |746|[Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) | [C++](./algorithms/cpp/minCostClimbingStairs/MinCostClimbingStairs.cpp), [Python](./algorithms/python/MinCostClimbingStairs/minCostClimbingStairs.py)|Easy| diff --git a/algorithms/python/SwimInRisingWater/swim_in_rising_water.py b/algorithms/python/SwimInRisingWater/swim_in_rising_water.py new file mode 100644 index 00000000..0b689ab6 --- /dev/null +++ b/algorithms/python/SwimInRisingWater/swim_in_rising_water.py @@ -0,0 +1,41 @@ +""" +Solution to LeetCode problem Swim in Rising Water (#778) +Difficulty: Hard + +Explanation: +We are approaching the problem through Djikstras Algorith. Essentially a BFS but with a minimum heap. The neighbors that you are adding into the queue, you are only popping the minimum value neighbor. Amongst those popped value you are checking if that value is the max value seen so far. If it is, then you have found the solution. +""" +from heapq import heappush, heappop +from typing import List + +class Solution: + def swimInWater(self, grid: List[List[int]]) -> int: + src, dst = grid[0][0], grid[len(grid)-1][len(grid)-1] + visited = set() + heap_queue = [(src, 0, 0)] # src, row, col + output = 0 + directions = [(0, 1), (1, 0), (-1, 0), (0, -1)] + while heap_queue: + current, row, col = heappop(heap_queue) + output = max(current, output) + + # if we already hit the destination, break out of the loop + if current == dst: + break + + for x, y in directions: + dx, dy = row+x, col+y + if self.check_bounds(dx, dy, grid) and (dx, dy) not in visited: + heappush(heap_queue, (grid[dx][dy], dx, dy)) + visited.add((dx, dy)) + return output + + def check_bounds(self, r, c, grid) -> bool: + if 0 <= r < len(grid[0]) and 0 <= c < len(grid): + return True + return False + + +if __name__ == "__main__": + grid = [[0, 2], [1, 3]] + print(Solution().swimInWater(grid)) \ No newline at end of file From 637015090a62063ce21e3b42f4aeb662f0edcacc Mon Sep 17 00:00:00 2001 From: Will <73602111+willmccarten@users.noreply.github.com> Date: Mon, 31 Jan 2022 03:06:01 -0500 Subject: [PATCH 12/15] New java solution to problem 1946 and updated readme (#268) * Create Java solution for problem 1946 ran fine on leetcode, but was having some potential issues with unwanted non printable ascii characters * update readme for java solution on 1946 --- README.md | 2 +- .../largestNumberAfterMutatingSubstring.java | 81 +++++++++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 algorithms/java/src/LargestNumberAfterMutatingSubstring/largestNumberAfterMutatingSubstring.java diff --git a/README.md b/README.md index 4cbdb6eb..d3d78a84 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | -|1946|[Largest Number After Mutating Substring](https://leetcode.com/problems/largest-number-after-mutating-substring/) | [C++](./algorithms/cpp/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp)|Medium| +|1946|[Largest Number After Mutating Substring](https://leetcode.com/problems/largest-number-after-mutating-substring/) | [C++](./algorithms/cpp/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp), [Java](./algorithms/java/src/LargestNumberAfterMutatingSubtring/largestNumberAfterMutatingSubstring.java)|Medium| |1945|[Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert/) | [C++](./algorithms/cpp/leetcode/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp)|Easy| |1935|[Maximum Number of Words You Can Type](https://leetcode.com/problems/maximum-number-of-words-you-can-type/) | [C++](./algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp)|Easy| |1884|[Egg Drop With 2 Eggs and N Floors](https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/) | [C++](./algorithms/cpp/eggDropWith2EggsAndNFloors/EggDropWith2EggsAndNFloors.cpp)|Medium| diff --git a/algorithms/java/src/LargestNumberAfterMutatingSubstring/largestNumberAfterMutatingSubstring.java b/algorithms/java/src/LargestNumberAfterMutatingSubstring/largestNumberAfterMutatingSubstring.java new file mode 100644 index 00000000..ae4d53df --- /dev/null +++ b/algorithms/java/src/LargestNumberAfterMutatingSubstring/largestNumberAfterMutatingSubstring.java @@ -0,0 +1,81 @@ +/***************************************************************************************************** + * + * You are given a string num, which represents a large integer. You are also given a 0-indexed + * integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d + * maps to digit change[d]. + * + * You may choose to mutate a single substring of num. To mutate a substring, replace each digit + * num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]). + * + * Return a string representing the largest possible integer after mutating (or choosing not to) a + * single substring of num. + * + * A substring is a contiguous sequence of characters within the string. + * + * Example 1: + * + * Input: num = "132", change = [9,8,5,0,3,6,4,2,6,8] + * Output: "832" + * Explanation: Replace the substring "1": + * - 1 maps to change[1] = 8. + * Thus, "132" becomes "832". + * "832" is the largest number that can be created, so return it. + * + * Example 2: + * + * Input: num = "021", change = [9,4,3,5,7,2,1,9,0,6] + * Output: "934" + * Explanation: Replace the substring "021": + * - 0 maps to change[0] = 9. + * - 2 maps to change[2] = 3. + * - 1 maps to change[1] = 4. + * Thus, "021" becomes "934". + * "934" is the largest number that can be created, so return it. + * + * Example 3: + * + * Input: num = "5", change = [1,4,7,5,3,2,5,6,9,4] + * Output: "5" + * Explanation: "5" is already the largest number that can be created, so return it. + * + * Constraints: + * + * 1 <= num.length <= 10^5 + * num consists of only digits 0-9. + * change.length == 10 + * 0 <= change[d] <= 9 + ******************************************************************************************************/ + +class Solution { + public String maximumNumber(String num, int[] change) { + + //make flag for checking replacement + boolean shouldReplace = false; + + //work through substring + for(int i = 0; i < num.length(); i++){ + + //subtract zero to get correct ascii conversion + char a = num.charAt(i); + char curr = (char)(a - '0'); + + if(curr < change[curr]){ + + char c = (char)(change[curr] + '0'); + + num = num.replace(num.charAt(i), c); + + shouldReplace = true; + + }else if((curr > change[curr]) && (shouldReplace)){ + + break; + + } + } + + return num; + } +} + + From d2ce5c665d3ddb9b48ae4726e1a83a3f65eb5662 Mon Sep 17 00:00:00 2001 From: Will <73602111+willmccarten@users.noreply.github.com> Date: Mon, 31 Jan 2022 03:07:11 -0500 Subject: [PATCH 13/15] Added a java solution to problem 48 and updated the readme for it (#267) * Creat RotateImage.java for problem #48 solution and explanation to problem #48 * Create solution to problem 48, Rotating Image I needed to remake the commit because i was unaware the hashtag symbol would create a link to the issue number lol sorry * update Readme for java solution on problem 48 adding a java solution to the readme for problem 48 * Update Readme...I added an extra space added an extra space after [Java] and that made it look wrong and I forgot to preview it. Fixed now --- README.md | 2 +- .../java/src/RotateImage/rotateImage.java | 53 +++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 algorithms/java/src/RotateImage/rotateImage.java diff --git a/README.md b/README.md index d3d78a84..9976304c 100644 --- a/README.md +++ b/README.md @@ -514,7 +514,7 @@ LeetCode |51|[N-Queens](https://leetcode.com/problems/n-queens/)| [C++](./algorithms/cpp/nQueens/nQueuens.cpp)|Hard| |50|["Pow(x, n)"](https://leetcode.com/problems/powx-n/)| [C++](./algorithms/cpp/pow/pow.cpp), [Java](./algorithms/java/src/powXn/PowXn.java)|Medium| |49|[Group Anagrams](https://leetcode.com/problems/anagrams/)| [C++](./algorithms/cpp/anagrams/GroupAnagrams.cpp)|Medium| -|48|[Rotate Image](https://leetcode.com/problems/rotate-image/)| [C++](./algorithms/cpp/rotateImage/rotateImage.cpp)|Medium| +|48|[Rotate Image](https://leetcode.com/problems/rotate-image/)| [C++](./algorithms/cpp/rotateImage/rotateImage.cpp), [Java](./algorithms/java/src/RotateImage/rotateImage.java)|Medium| |47|[Permutations II](https://leetcode.com/problems/permutations-ii/)| [C++](./algorithms/cpp/permutations/permutations.II.cpp)|Hard| |46|[Permutations](https://leetcode.com/problems/permutations/)| [C++](./algorithms/cpp/permutations/permutations.cpp)|Medium| |45|[Jump Game II](https://leetcode.com/problems/jump-game-ii/)| [C++](./algorithms/cpp/jumpGame/jumpGame.II.cpp)|Hard| diff --git a/algorithms/java/src/RotateImage/rotateImage.java b/algorithms/java/src/RotateImage/rotateImage.java new file mode 100644 index 00000000..2bba2be7 --- /dev/null +++ b/algorithms/java/src/RotateImage/rotateImage.java @@ -0,0 +1,53 @@ +/* + +You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). + +You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. + + Example 1: +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] +Output: [[7,4,1],[8,5,2],[9,6,3]] + +Example 2: +Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] +Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] + +Constraints: + +n == matrix.length == matrix[i].length +1 <= n <= 20 +-1000 <= matrix[i][j] <= 1000 + +*/ + + +//when looking for a pattern, we notice that there numbers in groups of four that change positions with one another +//approach: find the positions of those four and swamp them with their right neighbor to make the 90 degree turn + +class Solution { + public void rotate(int[][] matrix) { + + int n = matrix.length; //given + + //adding one and dividing with int division accounts for both odd and even length of n + for (int i = 0; i < ((n + 1) / 2); i ++) { + + for (int j = 0; j < (n / 2); j++) { + + //Starts with far edges and works its way back to the left + //hold first of group, use to replace in final swap + int temp = matrix[n - j - 1][i]; + + //keep replacing with group member on next side of the square + matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]; + matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1]; + matrix[j][n - i - 1] = matrix[i][j]; + + //finally replace last spot with first spot held in temp + matrix[i][j] = temp; + + //move to next group with index incrementation + } + } + } +} From 505198061b0c3fca66ef4b47005f233422f17df7 Mon Sep 17 00:00:00 2001 From: Jordan Kirkland <73541159+jkirkland722@users.noreply.github.com> Date: Mon, 31 Jan 2022 03:09:02 -0500 Subject: [PATCH 14/15] Added python solutions and corrected 128 to medium (#263) --- README.md | 4 ++-- .../LongestConsecutive.py | 18 ++++++++++++++++++ .../python/SingleNumberII/SingleNumberII.py | 15 +++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 algorithms/python/LongestConsecutiveSequence/LongestConsecutive.py create mode 100644 algorithms/python/SingleNumberII/SingleNumberII.py diff --git a/README.md b/README.md index 9976304c..a146bd02 100644 --- a/README.md +++ b/README.md @@ -425,7 +425,7 @@ LeetCode |140|[Word Break II](https://leetcode.com/problems/word-break-ii/)| [C++](./algorithms/cpp/wordBreak/wordBreak.II.cpp)|Hard| |139|[Word Break](https://leetcode.com/problems/word-break/)| [C++](./algorithms/cpp/wordBreak/wordBreak.cpp)|Medium| |138|[Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/)| [C++](./algorithms/cpp/copyListWithRandomPointer/copyListWithRandomPointer.cpp), [Python](./algorithms/python/CopyListWithRandomPointer/copyRandomList.py)|Hard| -|137|[Single Number II](https://leetcode.com/problems/single-number-ii/)| [C++](./algorithms/cpp/singleNumber/singleNumber.II.cpp)|Medium| +|137|[Single Number II](https://leetcode.com/problems/single-number-ii/)| [C++](./algorithms/cpp/singleNumber/singleNumber.II.cpp), [Python](./algorithms/python/SingleNumberII/SingleNumberII.py)|Medium| |136|[Single Number](https://leetcode.com/problems/single-number/)| [C++](./algorithms/cpp/singleNumber/singleNumber.cpp)|Medium| |135|[Candy](https://leetcode.com/problems/candy/)| [C++](./algorithms/cpp/candy/candy.cpp)|Hard| |134|[Gas Station](https://leetcode.com/problems/gas-station/)| [C++](./algorithms/cpp/gasStation/gasStation.cpp)|Medium| @@ -434,7 +434,7 @@ LeetCode |131|[Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/)| [C++](./algorithms/cpp/palindromePartitioning/palindromePartitioning.cpp)|Medium| |130|[Surrounded Regions](https://leetcode.com/problems/surrounded-regions/)| [C++](./algorithms/cpp/surroundedRegions/surroundedRegions.cpp)|Medium| |129|[Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/)| [C++](./algorithms/cpp/sumRootToLeafNumber/sumRootToLeafNumber.cpp), [Python](./algorithms/python/SumRootToLeafNumbers/sumNumbers.py)|Medium| -|128|[Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [C++](./algorithms/cpp/longestConsecutiveSequence/longestConsecutiveSequence.cpp)|Hard| +|128|[Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [C++](./algorithms/cpp/longestConsecutiveSequence/longestConsecutiveSequence.cpp), [Python](./algorithms/python/LongestConsecutiveSequence/LongestConsecutive.py)|Medium| |127|[Word Ladder](https://leetcode.com/problems/word-ladder/)| [C++](./algorithms/cpp/wordLadder/wordLadder.cpp)|Medium| |126|[Word Ladder II](https://leetcode.com/problems/word-ladder-ii/)| [C++](./algorithms/cpp/wordLadder/wordLadder.II.cpp)|Hard| |125|[Valid Palindrome](https://leetcode.com/problems/valid-palindrome/)| [C++](./algorithms/cpp/validPalindrome/validPalindrome.cpp), [Java](./algorithms/java/src/validPalindrome/ValidPalindrome.java)|Easy| diff --git a/algorithms/python/LongestConsecutiveSequence/LongestConsecutive.py b/algorithms/python/LongestConsecutiveSequence/LongestConsecutive.py new file mode 100644 index 00000000..2da021df --- /dev/null +++ b/algorithms/python/LongestConsecutiveSequence/LongestConsecutive.py @@ -0,0 +1,18 @@ +def longestConsecutive(self, nums): + + #first, create a hashmap + hm = set(nums) + longest = 0 + #find the longest consecutive sequence from each number in the new + #hashmap (set) + for num in hm: + if (num - 1) not in hm: + current = num + 1 + cons = 1 + while current in hm: + current += 1 + cons += 1 + if cons > longest: + longest = cons + + return longest \ No newline at end of file diff --git a/algorithms/python/SingleNumberII/SingleNumberII.py b/algorithms/python/SingleNumberII/SingleNumberII.py new file mode 100644 index 00000000..85a5fa39 --- /dev/null +++ b/algorithms/python/SingleNumberII/SingleNumberII.py @@ -0,0 +1,15 @@ +def singleNumber(self, nums): + + #1. make hashmap + #2. while traversing list, add each element + #3. remove it once it has been seen 3 times + #4. finally, the only value left is the one we're looking for + + hashmap = defaultdict(int) + for num in nums: + hashmap[num] += 1 + if hashmap[num] == 3: + del hashmap[num] + + singleNum = hashmap.keys()[0] + return singleNum From 125c4d8d7e3a4700d7b2dc5b6e7137f84da884e3 Mon Sep 17 00:00:00 2001 From: Emdadul Haque Date: Sat, 9 Apr 2022 11:30:24 +0600 Subject: [PATCH 15/15] Update README.md (#271) --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index a146bd02..2bf93af3 100644 --- a/README.md +++ b/README.md @@ -563,7 +563,6 @@ LeetCode |2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)| [C++](./algorithms/cpp/addTwoNumbers/addTwoNumbers.cpp)|Medium| |1|[Two Sum](https://leetcode.com/problems/two-sum/)| [C++](./algorithms/cpp/twoSum/twoSum.cpp), [Go](./algorithms/golang/twoSum/twoSum.go)|Easy| -l ### LeetCode Shell