diff --git a/README.md b/README.md index 0bfb7b473..2bf93af3b 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,15 @@ 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), [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| |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++](./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| @@ -190,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| @@ -418,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| @@ -427,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| @@ -507,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| @@ -556,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 diff --git a/algorithms/cpp/UTF8Validation/UTF8Validation.cpp b/algorithms/cpp/UTF8Validation/UTF8Validation.cpp index 619b8ab63..5b0fe7ac1 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; } diff --git a/algorithms/cpp/eggDropWith2EggsAndNFloors/EggDropWith2EggsAndNFloors.cpp b/algorithms/cpp/eggDropWith2EggsAndNFloors/EggDropWith2EggsAndNFloors.cpp new file mode 100644 index 000000000..b56331a59 --- /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; + } +}; diff --git a/algorithms/cpp/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp b/algorithms/cpp/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp new file mode 100644 index 000000000..7dd3c7652 --- /dev/null +++ b/algorithms/cpp/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; + } +}; diff --git a/algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp b/algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp new file mode 100644 index 000000000..8b1cd3571 --- /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; + } +}; diff --git a/algorithms/cpp/minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp b/algorithms/cpp/minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp new file mode 100644 index 000000000..ead47d112 --- /dev/null +++ b/algorithms/cpp/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; + } +}; diff --git a/algorithms/cpp/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp b/algorithms/cpp/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp new file mode 100644 index 000000000..fd5972f20 --- /dev/null +++ b/algorithms/cpp/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; + } +}; diff --git a/algorithms/cpp/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp b/algorithms/cpp/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp new file mode 100644 index 000000000..d2dcfe724 --- /dev/null +++ b/algorithms/cpp/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; + } +}; diff --git a/algorithms/cpp/twoSum/twoSum.cpp b/algorithms/cpp/twoSum/twoSum.cpp index dc0680f8a..f0e9692ee 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 change[curr]) && (shouldReplace)){ + + break; + + } + } + + return num; + } +} + + diff --git a/algorithms/java/src/RotateImage/rotateImage.java b/algorithms/java/src/RotateImage/rotateImage.java new file mode 100644 index 000000000..2bba2be71 --- /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 + } + } + } +} diff --git a/algorithms/python/LongestConsecutiveSequence/LongestConsecutive.py b/algorithms/python/LongestConsecutiveSequence/LongestConsecutive.py new file mode 100644 index 000000000..2da021df2 --- /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 000000000..85a5fa39f --- /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 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 000000000..0b689ab6b --- /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