diff --git a/.eslintrc.json b/.eslintrc.json index 06bf556..e864da5 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -10,6 +10,7 @@ "sourceType": "module" }, "rules": { + "camelcase": "error", "indent": [ "error", 2 diff --git a/DesignDataStructure/designI.js b/DesignDataStructure/designI.js index e3112c5..090eac0 100644 --- a/DesignDataStructure/designI.js +++ b/DesignDataStructure/designI.js @@ -21,6 +21,8 @@ The data structure should be efficient enough to accommodate the operations acco Frequency: Least frequent. */ +/* +example: class effStructure { this.maxHeap = []; @@ -33,4 +35,5 @@ class effStructure { 3) deleteMin(): O(log N) 4) deleteMax(): O(log N) 5) Insert(log N) -6) Delete: O(log N) \ No newline at end of file +6) Delete: O(log N) +*/ \ No newline at end of file diff --git a/LeetcodeProblems/Algorithms/easy/2Sum.js b/LeetcodeProblems/Algorithms/easy/2Sum.js new file mode 100644 index 0000000..3cf3682 --- /dev/null +++ b/LeetcodeProblems/Algorithms/easy/2Sum.js @@ -0,0 +1,55 @@ +/** +2 Sum +https://leetcode.com/problems/two-sum/ + +Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. + +You may assume that each input would have exactly one solution, and you may not use the same element twice. + +You can return the answer in any order. + +Example 1: +Input: nums = [2,7,11,15], target = 9 +Output: [0,1] +Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. + +Example 2: +Input: nums = [3,2,4], target = 6 +Output: [1,2] + +Example 3: +Input: nums = [3,3], target = 6 +Output: [0,1] + +*/ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function (nums, target) { + let map = {}; + for (let i = 0; i < nums.length; i++) { + const sum = target - nums[i]; + if (sum in map) { + return [map[sum], i]; + } else { + map[nums[i]] = i; + } + } +}; + +//Another method +var twoSum2 = function (nums, target) { + for (let i = 0; i < nums.length; i++) { + for (let j = i + 1; j < nums.length; j++) { + if (nums[i] + nums[j] === target) { + return [i, j]; + } + } + } +}; + +module.exports.twoSum = twoSum; +module.exports.twoSum2 = twoSum2; diff --git a/LeetcodeProblems/Algorithms/Award_Budget_Cuts.js b/LeetcodeProblems/Algorithms/easy/Award_Budget_Cuts.js similarity index 100% rename from LeetcodeProblems/Algorithms/Award_Budget_Cuts.js rename to LeetcodeProblems/Algorithms/easy/Award_Budget_Cuts.js diff --git a/LeetcodeProblems/Algorithms/Backspace_String_Compare.js b/LeetcodeProblems/Algorithms/easy/Backspace_String_Compare.js similarity index 100% rename from LeetcodeProblems/Algorithms/Backspace_String_Compare.js rename to LeetcodeProblems/Algorithms/easy/Backspace_String_Compare.js diff --git a/LeetcodeProblems/Algorithms/easy/Best_Time_to_buy_and_sell_stock.js b/LeetcodeProblems/Algorithms/easy/Best_Time_to_buy_and_sell_stock.js new file mode 100644 index 0000000..a94d16b --- /dev/null +++ b/LeetcodeProblems/Algorithms/easy/Best_Time_to_buy_and_sell_stock.js @@ -0,0 +1,95 @@ +/* +121. Best Time to Buy and Sell Stock +https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ + +Problem: +You are given an array prices where prices[i] is the price of a given stock on the ith day. + +You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. + +Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. + + + +Example 1: + +Input: prices = [7,1,5,3,6,4] +Output: 5 +Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. +Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. +Example 2: + +Input: prices = [7,6,4,3,1] +Output: 0 +Explanation: In this case, no transactions are done and the max profit = 0. + +Constraints: + +1 <= prices.length <= 10^5 +0 <= prices[i] <= 10^4 +*/ +/* +Approach: +We will use a Two pointers strategy (Left and Right pointers). +The first will start pointing to the first element, and the right to the second position of array. +The Left is to buy stock and Right is to sell stock + +We initialize our maxProfitValue as 0. + +Now we will start our while loop, and we will run till our +Right pointer less than the array's length. + +For Example: +prices=[7,1,5,3,6,4] +Note: +prices[left] --> buy stock +prices[right] --> sell stock +We will check the price at the right and left pointer + +step 1: + +price[left]=7 price[right]=1 profit=-6 +here, price[left] is greater than price[right], so we will move the left pointer to the right position +and increment our right pointer by 1. We always want our left point to be the minimum. + +step 2: + +price[left]=1 price[right]=5 profit=4 +here, price[left] is less than price[right], which means we will get profit, +so we will update our maxProfitValue and move our right pointer alone + +step 3: + +price[left]=1 price[right]=3 profit=2 +here, price[left] is less than price[right], we will get profit, so we will compare the maxProfitValue with the current profit. +We will update our maxProfitValue and move our right pointer alone + +step 4: + +price[left]=1 price[right]=6 profit=5 +same logic as above + +step 5: + +price[left]=1 price[right]=4 profit=3 +same logic as above +*/ + +const maxProfit = (prices) => { + let left = 0; // Buy + let right = 1; // sell + let maxProfitValue = 0; + while (right < prices.length) { + if (prices[left] < prices[right]) { + let profit = prices[right] - prices[left]; // our current profit + + maxProfitValue = Math.max(maxProfitValue, profit); + } else { + left = right; + } + right++; + } + return maxProfitValue; +}; + +module.exports.maxProfit = maxProfit; diff --git a/LeetcodeProblems/Algorithms/Binary_Gap.js b/LeetcodeProblems/Algorithms/easy/Binary_Gap.js similarity index 100% rename from LeetcodeProblems/Algorithms/Binary_Gap.js rename to LeetcodeProblems/Algorithms/easy/Binary_Gap.js diff --git a/LeetcodeProblems/Algorithms/easy/Bit_Reverse_To_Make_Numbers_Equal.js b/LeetcodeProblems/Algorithms/easy/Bit_Reverse_To_Make_Numbers_Equal.js new file mode 100644 index 0000000..524f63f --- /dev/null +++ b/LeetcodeProblems/Algorithms/easy/Bit_Reverse_To_Make_Numbers_Equal.js @@ -0,0 +1,80 @@ +/* +3226. Number of Bit Changes to Make Two Integers Equal +https://leetcode.com/problems/number-of-bit-changes-to-make-two-integers-equal/description/ + +You are given two positive integers n and k. + +You can choose any bit in the binary representation of n that is equal to 1 and change it to 0. + +Return the number of changes needed to make n equal to k. If it is impossible, return -1. + +Example 1: + +Input: n = 13, k = 4 + +Output: 2 + +Explanation: +Initially, the binary representations of n and k are n = (1101)base2 and k = (0100)base2. +We can change the first and fourth bits of n. The resulting integer is n = (0100)base2 = k. + + +Example 2: + +Input: n = 21, k = 21 + +Output: 0 + +Explanation: +n and k are already equal, so no changes are needed. + +Example 3: + +Input: n = 14, k = 13 + +Output: -1 + +Explanation: +It is not possible to make n equal to k. + +Constraints: + +1 <= n, k <= 10^6 + +*/ + +/* +Approach +Check if transformation is possible: + +Use a bitwise AND operation to ensure all 1 bits in k are also 1 bits in n. If not, return -1. +Calculate the number of changes: + +Use a bitwise XOR operation to identify differing bits between n and k. +Count the number of 1s in the result of the XOR operation. +*/ + +/** + * @param {number} n + * @param {number} k + * @return {number} + */ +var minChanges = function bitChanges(n, k) { + // Check if transformation is possible + if ((n & k) !== k) { + return -1; + } + + // Calculate the number of changes + let changes = 0; + let diff = n ^ k; + + while (diff > 0) { + changes += diff & 1; + diff >>= 1; + } + + return changes; +}; + +module.exports.minChanges = minChanges; diff --git a/LeetcodeProblems/Algorithms/Deletion_Distance.js b/LeetcodeProblems/Algorithms/easy/Deletion_Distance.js similarity index 100% rename from LeetcodeProblems/Algorithms/Deletion_Distance.js rename to LeetcodeProblems/Algorithms/easy/Deletion_Distance.js diff --git a/LeetcodeProblems/Algorithms/Flood_Fill.js b/LeetcodeProblems/Algorithms/easy/Flood_Fill.js similarity index 100% rename from LeetcodeProblems/Algorithms/Flood_Fill.js rename to LeetcodeProblems/Algorithms/easy/Flood_Fill.js diff --git a/LeetcodeProblems/Algorithms/easy/Happy_Number.js b/LeetcodeProblems/Algorithms/easy/Happy_Number.js new file mode 100644 index 0000000..ebbfd39 --- /dev/null +++ b/LeetcodeProblems/Algorithms/easy/Happy_Number.js @@ -0,0 +1,58 @@ +/** +Happy Number +https://leetcode.com/problems/happy-number/ + +Write an algorithm to determine if a number n is happy. + +A happy number is a number defined by the following process: + + Starting with any positive integer, replace the number by the sum of the squares of its digits. + Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. + Those numbers for which this process ends in 1 are happy. + +Return true if n is a happy number, and false if not. + +Example 1: +Input: n = 19 +Output: true +Explanation: +1^2 + 9^2 = 82 +8^2 + 2^2 = 68 +6^2 + 8^2 = 100 +1^2 + 0^2 + 0^2 = 1 + +Example 2: +Input: n = 2 +Output: false + +Example 3: +Input n = 7 +Output = true +Explanation: +7^2 = 49 +4^2 + 9^2 = 97 +9^2 + 7^2 = 130 +1^2 + 3^2 + 0^2 = 10 +1^2 + 0^2 = 1 + + */ + +/** + * @param {number} n + * @return {boolean} + */ +var isHappy = function(n) { + return checkHappyNumber(n); +}; + +function checkHappyNumber(n){ + let strNumber = n.toString(); + let splitNumber = strNumber.split(""); + if(splitNumber.length <= 1){ + return (n === 1 || n === 7)? true:false; + } + const digit = splitNumber.reduce((a,b)=> parseInt(a) + Math.pow(parseInt(b),2),0); + return checkHappyNumber(digit); +} + +module.exports.isHappy = isHappy; diff --git a/LeetcodeProblems/Algorithms/Implement_stack_using_queues.js b/LeetcodeProblems/Algorithms/easy/Implement_stack_using_queues.js similarity index 100% rename from LeetcodeProblems/Algorithms/Implement_stack_using_queues.js rename to LeetcodeProblems/Algorithms/easy/Implement_stack_using_queues.js diff --git a/LeetcodeProblems/Algorithms/easy/Lexographic_smallest_after_swap.js b/LeetcodeProblems/Algorithms/easy/Lexographic_smallest_after_swap.js new file mode 100644 index 0000000..1a4571d --- /dev/null +++ b/LeetcodeProblems/Algorithms/easy/Lexographic_smallest_after_swap.js @@ -0,0 +1,81 @@ +/* +3216. Lexicographically Smallest String After a Swap +https://leetcode.com/problems/lexicographically-smallest-string-after-a-swap/description/ + +Problem: +Given a string s containing only digits, return the lexicographically smallest string +that can be obtained after swapping adjacent digits in s with the same parity at most once. + +Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, +have the same parity, while 6 and 9 do not. + +Example 1: + +Input: s = "45320" + +Output: "43520" + +Explanation: + +s[1] == '5' and s[2] == '3' both have the same parity, and swapping them results in the lexicographically smallest string. + +Example 2: + +Input: s = "001" + +Output: "001" + +Explanation: + +There is no need to perform a swap because s is already the lexicographically smallest. + + +Constraints: + +2 <= s.length <= 100 +s consists only of digits. +*/ + +/* +Approach: + +Checking if the present digit is greater than the next digit, if yes then checking the parity of the digit. +if both have the same parity swap the number. since this operation can be done at max once, break the loop after the first swap. +return the updated number + +What is parity of a number? +Parity: the property of an integer of whether it is even or odd + +how to check the parity of the number: +- using the & operation on the last bit, +- if (last bit)&1 == 1, means the last bit was 1. means Odd (ex: 3 has a bit representation of 11) +- if (last bit)&1 == 0, means last bit was 0. means Even number ( ex: 2 has a bit representation of 10) + +*/ + + +/** + * @param {string} s + * @return {string} + */ +var getSmallestString = function(s) { + let arr = s.split("").map(Number); + + const getParity = (num) => { + if(num&1 === 0) return "even"; + else return "odd"; + }; + + for(let i = 0; i< s.length - 1; i++) { + if(arr[i] > arr[i+1] && getParity(arr[i]) === getParity(arr[i + 1])) { + let tmp = arr[i+1]; + arr[i+1] = arr[i]; + arr[i] = tmp; + break; + } + } + + return arr.join(""); +}; + +module.exports.getSmallestString = getSmallestString; \ No newline at end of file diff --git a/LeetcodeProblems/Algorithms/easy/Longest_Common_Prefix.js b/LeetcodeProblems/Algorithms/easy/Longest_Common_Prefix.js new file mode 100644 index 0000000..2468131 --- /dev/null +++ b/LeetcodeProblems/Algorithms/easy/Longest_Common_Prefix.js @@ -0,0 +1,34 @@ +/** +Longest Common Prefix +https://leetcode.com/problems/longest-common-prefix/ + +Write a function to find the longest common prefix string amongst an array of strings. + +If there is no common prefix, return an empty string "". + +Example 1: +Input: strs = ["flower","flow","flight"] +Output: "fl" + +Example 2: +Input: strs = ["dog","racecar","car"] +Output: "" +Explanation: There is no common prefix among the input strings. + +*/ + +/** + * @param {string[]} strs + * @return {string} + */ +var longestCommonPrefix = function(strs) { + if(strs.length === 0) return ""; + + return strs.reduce((result, curr)=>{ + let i = 0; + while(result[i] && curr[i] && result[i] === curr[i]) i++; + return result.slice(0, i); + }); +}; + +module.exports.longestCommonPrefix = longestCommonPrefix; \ No newline at end of file diff --git a/LeetcodeProblems/Algorithms/Majority_Element.js b/LeetcodeProblems/Algorithms/easy/Majority_Element.js similarity index 100% rename from LeetcodeProblems/Algorithms/Majority_Element.js rename to LeetcodeProblems/Algorithms/easy/Majority_Element.js diff --git a/LeetcodeProblems/Algorithms/Maximun_Subarray.js b/LeetcodeProblems/Algorithms/easy/Maximun_Subarray.js similarity index 100% rename from LeetcodeProblems/Algorithms/Maximun_Subarray.js rename to LeetcodeProblems/Algorithms/easy/Maximun_Subarray.js diff --git a/LeetcodeProblems/Algorithms/Min_Stack.js b/LeetcodeProblems/Algorithms/easy/Min_Stack.js similarity index 100% rename from LeetcodeProblems/Algorithms/Min_Stack.js rename to LeetcodeProblems/Algorithms/easy/Min_Stack.js diff --git a/LeetcodeProblems/Algorithms/Number_of_Segments_in_a_String.js b/LeetcodeProblems/Algorithms/easy/Number_of_Segments_in_a_String.js similarity index 100% rename from LeetcodeProblems/Algorithms/Number_of_Segments_in_a_String.js rename to LeetcodeProblems/Algorithms/easy/Number_of_Segments_in_a_String.js diff --git a/LeetcodeProblems/Algorithms/Reverse_String_II.js b/LeetcodeProblems/Algorithms/easy/Reverse_String_II.js similarity index 100% rename from LeetcodeProblems/Algorithms/Reverse_String_II.js rename to LeetcodeProblems/Algorithms/easy/Reverse_String_II.js diff --git a/LeetcodeProblems/Algorithms/Same_Tree.js b/LeetcodeProblems/Algorithms/easy/Same_Tree.js similarity index 100% rename from LeetcodeProblems/Algorithms/Same_Tree.js rename to LeetcodeProblems/Algorithms/easy/Same_Tree.js diff --git a/LeetcodeProblems/Algorithms/easy/Shuffle_String.js b/LeetcodeProblems/Algorithms/easy/Shuffle_String.js new file mode 100644 index 0000000..bf3395f --- /dev/null +++ b/LeetcodeProblems/Algorithms/easy/Shuffle_String.js @@ -0,0 +1,33 @@ +/** + You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. + +Return the shuffled string. + + + +Example 1: + +Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3] +Output: "leetcode" +Explanation: As shown, "codeleet" becomes "leetcode" after shuffling. + +Example 2: + +Input: s = "abc", indices = [0,1,2] +Output: "abc" +Explanation: After shuffling, each character remains in its position. + + */ + +/** + * @param {string} s + * @param {number[]} indices + * @return {string} + */ +var restoreString = function(s, indices) { + let arrshuffle = []; + indices.forEach((sindex, index) => arrshuffle[sindex] = s.charAt(index)); + return arrshuffle.join(""); +}; + +module.exports.restoreString = restoreString; \ No newline at end of file diff --git a/LeetcodeProblems/Algorithms/Sum_Of_Square_Numbers.js b/LeetcodeProblems/Algorithms/easy/Sum_Of_Square_Numbers.js similarity index 100% rename from LeetcodeProblems/Algorithms/Sum_Of_Square_Numbers.js rename to LeetcodeProblems/Algorithms/easy/Sum_Of_Square_Numbers.js diff --git a/LeetcodeProblems/Algorithms/Symmetric_Tree.js b/LeetcodeProblems/Algorithms/easy/Symmetric_Tree.js similarity index 100% rename from LeetcodeProblems/Algorithms/Symmetric_Tree.js rename to LeetcodeProblems/Algorithms/easy/Symmetric_Tree.js diff --git a/LeetcodeProblems/Algorithms/Tic_Tac_Toe.js b/LeetcodeProblems/Algorithms/easy/Tic_Tac_Toe.js similarity index 100% rename from LeetcodeProblems/Algorithms/Tic_Tac_Toe.js rename to LeetcodeProblems/Algorithms/easy/Tic_Tac_Toe.js diff --git a/LeetcodeProblems/Algorithms/Valid_Parentheses.js b/LeetcodeProblems/Algorithms/easy/Valid_Parentheses.js similarity index 100% rename from LeetcodeProblems/Algorithms/Valid_Parentheses.js rename to LeetcodeProblems/Algorithms/easy/Valid_Parentheses.js diff --git a/LeetcodeProblems/Algorithms/Edit_Distance.js b/LeetcodeProblems/Algorithms/hard/Edit_Distance.js similarity index 100% rename from LeetcodeProblems/Algorithms/Edit_Distance.js rename to LeetcodeProblems/Algorithms/hard/Edit_Distance.js diff --git a/LeetcodeProblems/Algorithms/hard/First_Missing_Positive.js b/LeetcodeProblems/Algorithms/hard/First_Missing_Positive.js new file mode 100644 index 0000000..8bb6ed3 --- /dev/null +++ b/LeetcodeProblems/Algorithms/hard/First_Missing_Positive.js @@ -0,0 +1,51 @@ +/* +41. First Missing Positive +https://leetcode.com/problems/first-missing-positive/ +Problem: +Given an unsorted integer array nums. Return the smallest positive integer that is not present in nums. +You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space. +Example 1: +Input: nums = [1,2,0] +Output: 3 +Explanation: The numbers in the range [1,2] are all in the array. +Example 2: +Input: nums = [3,4,-1,1] +Output: 2 +Explanation: 1 is in the array but 2 is missing. +Example 3: +Input: nums = [7,8,9,11,12] +Output: 1 +Explanation: The smallest positive integer 1 is missing. +Constraints: +1 <= nums.length <= 10^5 +-2^31 <= nums[i] <= 2^31 - 1 +Explanation +Initialize n +const n = nums.length; +This line sets the variable n to the length of the input array nums. It represents the size of the array. +This is the cyclic sort algorithm. It iterates through the array and, in each step, it checks if the current element nums[i] is within the valid range (1 to n) and not in its correct position. If so, it swaps the element with the one at its correct position. +After the cyclic sort, this loop searches for the first element that is out of place. If nums[i] is not equal to i + 1, it means that i + 1 is the smallest missing positive integer, and it is returned. +Return Next Positive Integer if All Elements Are in Place, +If all elements are in their correct positions, the function returns the next positive integer after the maximum element in the array (n + 1). +*/ + + +/** + * @param {number[]} nums + * @return {number} + */ +var firstMissingPositive = function(nums) { + const n = nums.length; + + for (let i = 0; i < n; i++) + while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] !== nums[i]) + [nums[nums[i] - 1], nums[i]] = [nums[i], nums[nums[i] - 1]]; + + for (let i = 0; i < n; i++) + if (nums[i] !== i + 1) + return i + 1; + + return n + 1; +}; + +module.exports.firstMissingPositive = firstMissingPositive; \ No newline at end of file diff --git a/LeetcodeProblems/Algorithms/Longest_Consecutive_Sequence.js b/LeetcodeProblems/Algorithms/hard/Longest_Consecutive_Sequence.js similarity index 100% rename from LeetcodeProblems/Algorithms/Longest_Consecutive_Sequence.js rename to LeetcodeProblems/Algorithms/hard/Longest_Consecutive_Sequence.js diff --git a/LeetcodeProblems/Algorithms/Minimum_Window_Substring.js b/LeetcodeProblems/Algorithms/hard/Minimum_Window_Substring.js similarity index 60% rename from LeetcodeProblems/Algorithms/Minimum_Window_Substring.js rename to LeetcodeProblems/Algorithms/hard/Minimum_Window_Substring.js index d3b5bd5..b58892f 100644 --- a/LeetcodeProblems/Algorithms/Minimum_Window_Substring.js +++ b/LeetcodeProblems/Algorithms/hard/Minimum_Window_Substring.js @@ -73,59 +73,59 @@ var getHash = function (t) { // Solution 2 // Similar idea code slightly different; var buildHash = function(t) { - let hash = {}; - let occ = 0; - for(var i = 0; i < t.length; i++) { - occ = hash[t[i]] == undefined ? 0 : hash[t[i]]; - hash[t[i]] = occ + 1; - } - return hash; -} + let hash = {}; + let occ = 0; + for(var i = 0; i < t.length; i++) { + occ = hash[t[i]] == undefined ? 0 : hash[t[i]]; + hash[t[i]] = occ + 1; + } + return hash; +}; var minWindow2 = function(s, t) { - var hashT = buildHash(t); - var start = 0; - var end = 0; - var countLeft = t.length; - var minWindow = ""; - var minWindowLeft = -1; - var maxWindowRight = -1; - - while(start < s.length && end < s.length) { - if(countLeft > 0) { // window does not contain all elements - if(hashT[s[end]] !== undefined) { - hashT[s[end]] = hashT[s[end]] - 1; - if(hashT[s[end]] >= 0) { - countLeft--; - } - } + var hashT = buildHash(t); + var start = 0; + var end = 0; + var countLeft = t.length; + var minWindowLeft = -1; + var maxWindowRight = -1; + + while(start < s.length && end < s.length) { + if(countLeft > 0) { // window does not contain all elements + if(hashT[s[end]] !== undefined) { + hashT[s[end]] = hashT[s[end]] - 1; + if(hashT[s[end]] >= 0) { + countLeft--; + } + } - if(countLeft > 0) { - end++; - } - } else { // found window - if(minWindowLeft == -1 || ((maxWindowRight - minWindowLeft + 1) > (end - start + 1)) ) { - minWindowLeft = start; - maxWindowRight = end; - } - if(hashT[s[start]] !== undefined) { - hashT[s[start]] = hashT[s[start]] + 1; - if(hashT[s[start]] > 0) { - countLeft++; - end++; - } - } - start++; + if(countLeft > 0) { + end++; + } + } else { // found window + if(minWindowLeft == -1 || ((maxWindowRight - minWindowLeft + 1) > (end - start + 1)) ) { + minWindowLeft = start; + maxWindowRight = end; + } + if(hashT[s[start]] !== undefined) { + hashT[s[start]] = hashT[s[start]] + 1; + if(hashT[s[start]] > 0) { + countLeft++; + end++; } + } + start++; } + } - if(minWindowLeft > -1) { - return s.substring(minWindowLeft, maxWindowRight + 1); - } + if(minWindowLeft > -1) { + return s.substring(minWindowLeft, maxWindowRight + 1); + } - return ""; + return ""; }; module.exports.minWindow = minWindow; +module.exports.minWindow2 = minWindow2; \ No newline at end of file diff --git a/LeetcodeProblems/Algorithms/NQueens.js b/LeetcodeProblems/Algorithms/hard/NQueens.js similarity index 100% rename from LeetcodeProblems/Algorithms/NQueens.js rename to LeetcodeProblems/Algorithms/hard/NQueens.js diff --git a/LeetcodeProblems/Algorithms/Regular_Expression_Matching.js b/LeetcodeProblems/Algorithms/hard/Regular_Expression_Matching.js similarity index 100% rename from LeetcodeProblems/Algorithms/Regular_Expression_Matching.js rename to LeetcodeProblems/Algorithms/hard/Regular_Expression_Matching.js diff --git a/LeetcodeProblems/Algorithms/Remove_Invalid_Parentheses.js b/LeetcodeProblems/Algorithms/hard/Remove_Invalid_Parentheses.js similarity index 100% rename from LeetcodeProblems/Algorithms/Remove_Invalid_Parentheses.js rename to LeetcodeProblems/Algorithms/hard/Remove_Invalid_Parentheses.js diff --git a/LeetcodeProblems/Algorithms/Set_Matrix_Zeroes.js b/LeetcodeProblems/Algorithms/hard/Set_Matrix_Zeroes.js similarity index 100% rename from LeetcodeProblems/Algorithms/Set_Matrix_Zeroes.js rename to LeetcodeProblems/Algorithms/hard/Set_Matrix_Zeroes.js diff --git a/LeetcodeProblems/Algorithms/merge_k_sorted_lists.js b/LeetcodeProblems/Algorithms/hard/merge_k_sorted_lists.js similarity index 100% rename from LeetcodeProblems/Algorithms/merge_k_sorted_lists.js rename to LeetcodeProblems/Algorithms/hard/merge_k_sorted_lists.js diff --git a/LeetcodeProblems/Algorithms/3Sum.js b/LeetcodeProblems/Algorithms/medium/3Sum.js similarity index 100% rename from LeetcodeProblems/Algorithms/3Sum.js rename to LeetcodeProblems/Algorithms/medium/3Sum.js diff --git a/LeetcodeProblems/Algorithms/3SumClosest.js b/LeetcodeProblems/Algorithms/medium/3SumClosest.js similarity index 67% rename from LeetcodeProblems/Algorithms/3SumClosest.js rename to LeetcodeProblems/Algorithms/medium/3SumClosest.js index 271821a..22f0734 100644 --- a/LeetcodeProblems/Algorithms/3SumClosest.js +++ b/LeetcodeProblems/Algorithms/medium/3SumClosest.js @@ -30,31 +30,31 @@ Constraints: * @param {number} target * @return {number} */ - var threeSumClosest = function(nums, target) { +var threeSumClosest = function(nums, target) { let mid = 1; let right = nums.length - 1; let currentSum = nums[0] + nums[mid] + nums[right]; let closest = currentSum; - nums.sort(function(a,b) {return a - b}) + nums.sort(function(a,b) {return a - b;}); for(var left = 0 ; left < nums.length - 1; left++) { - mid = left + 1; - right = nums.length - 1; + mid = left + 1; + right = nums.length - 1; - while(mid < right) { - currentSum = nums[left] + nums[mid] + nums[right]; + while(mid < right) { + currentSum = nums[left] + nums[mid] + nums[right]; - if(Math.abs(target - currentSum) < Math.abs(target - closest)) { - closest = currentSum; - } + if(Math.abs(target - currentSum) < Math.abs(target - closest)) { + closest = currentSum; + } - if(currentSum > target) { - right--; - } else { - mid++; - } + if(currentSum > target) { + right--; + } else { + mid++; } + } } return closest; diff --git a/LeetcodeProblems/Algorithms/Add_Two_Numbers.js b/LeetcodeProblems/Algorithms/medium/Add_Two_Numbers.js similarity index 95% rename from LeetcodeProblems/Algorithms/Add_Two_Numbers.js rename to LeetcodeProblems/Algorithms/medium/Add_Two_Numbers.js index 2169716..3daed64 100644 --- a/LeetcodeProblems/Algorithms/Add_Two_Numbers.js +++ b/LeetcodeProblems/Algorithms/medium/Add_Two_Numbers.js @@ -21,7 +21,7 @@ Explanation: 342 + 465 = 807. * this.next = null; * } */ -var ListNode = require("../../UtilsClasses/ListNode").ListNode; +var ListNode = require("../../../UtilsClasses/ListNode").ListNode; /** * @param {ListNode} l1 diff --git a/LeetcodeProblems/Algorithms/Best_Time_To_Buy_And_Sell_Stock_II.js b/LeetcodeProblems/Algorithms/medium/Best_Time_To_Buy_And_Sell_Stock_II.js similarity index 100% rename from LeetcodeProblems/Algorithms/Best_Time_To_Buy_And_Sell_Stock_II.js rename to LeetcodeProblems/Algorithms/medium/Best_Time_To_Buy_And_Sell_Stock_II.js diff --git a/LeetcodeProblems/Algorithms/Clone_Graph.js b/LeetcodeProblems/Algorithms/medium/Clone_Graph.js similarity index 100% rename from LeetcodeProblems/Algorithms/Clone_Graph.js rename to LeetcodeProblems/Algorithms/medium/Clone_Graph.js diff --git a/LeetcodeProblems/Algorithms/Coin_Change.js b/LeetcodeProblems/Algorithms/medium/Coin_Change.js similarity index 100% rename from LeetcodeProblems/Algorithms/Coin_Change.js rename to LeetcodeProblems/Algorithms/medium/Coin_Change.js diff --git a/LeetcodeProblems/Algorithms/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js b/LeetcodeProblems/Algorithms/medium/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js similarity index 95% rename from LeetcodeProblems/Algorithms/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js rename to LeetcodeProblems/Algorithms/medium/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js index 310624b..021301b 100644 --- a/LeetcodeProblems/Algorithms/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js +++ b/LeetcodeProblems/Algorithms/medium/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js @@ -27,7 +27,7 @@ Return the following binary tree: * this.left = this.right = null; * } */ -var TreeNode = require("../../UtilsClasses/TreeNode").TreeNode; +var TreeNode = require("../../../UtilsClasses/TreeNode").TreeNode; /** * @param {number[]} preorder diff --git a/LeetcodeProblems/Algorithms/Container_With_Most_Water.js b/LeetcodeProblems/Algorithms/medium/Container_With_Most_Water.js similarity index 84% rename from LeetcodeProblems/Algorithms/Container_With_Most_Water.js rename to LeetcodeProblems/Algorithms/medium/Container_With_Most_Water.js index 4b6098f..90b8373 100644 --- a/LeetcodeProblems/Algorithms/Container_With_Most_Water.js +++ b/LeetcodeProblems/Algorithms/medium/Container_With_Most_Water.js @@ -24,18 +24,18 @@ Output: 1 * @param {number[]} height * @return {number} */ - var maxArea = function(height) { +var maxArea = function(height) { let left = 0; let right = height.length - 1; let maxArea = calculateArea(left, right, height); while(left < right) { - if(height[left] < height[right]) { - left++ - } else { - right--; - } - maxArea = Math.max(maxArea, calculateArea(left, right, height)) + if(height[left] < height[right]) { + left++; + } else { + right--; + } + maxArea = Math.max(maxArea, calculateArea(left, right, height)); } return maxArea; }; @@ -44,6 +44,6 @@ var calculateArea = function(x, y, height) { let minHeight = height[x] > height[y] ? height[y] : height[x]; let width = y -x; return (width * minHeight); -} +}; module.exports.maxArea = maxArea; \ No newline at end of file diff --git a/LeetcodeProblems/Algorithms/Design_Circular_Deque.js b/LeetcodeProblems/Algorithms/medium/Design_Circular_Deque.js similarity index 100% rename from LeetcodeProblems/Algorithms/Design_Circular_Deque.js rename to LeetcodeProblems/Algorithms/medium/Design_Circular_Deque.js diff --git a/LeetcodeProblems/Algorithms/Escape_The_Ghosts.js b/LeetcodeProblems/Algorithms/medium/Escape_The_Ghosts.js similarity index 100% rename from LeetcodeProblems/Algorithms/Escape_The_Ghosts.js rename to LeetcodeProblems/Algorithms/medium/Escape_The_Ghosts.js diff --git a/LeetcodeProblems/Algorithms/Find_Anagrams.js b/LeetcodeProblems/Algorithms/medium/Find_Anagrams.js similarity index 59% rename from LeetcodeProblems/Algorithms/Find_Anagrams.js rename to LeetcodeProblems/Algorithms/medium/Find_Anagrams.js index 1d201b0..5624329 100644 --- a/LeetcodeProblems/Algorithms/Find_Anagrams.js +++ b/LeetcodeProblems/Algorithms/medium/Find_Anagrams.js @@ -30,51 +30,51 @@ The substring with start index = 2 is "ab", which is an anagram of "ab". * @param {string} p * @return {number[]} */ - var findAnagrams = function(s, p) { - if(s.length < p.length) { return [] } +var findAnagrams = function(s, p) { + if(s.length < p.length) { return []; } let start = 0; let end = p.length - 1; let hashBuild = {}; let countLeft = p.length; - let anagrams = [] + let anagrams = []; for(let e = 0; e < p.length; e++) { - hashBuild[p[e]] = hashBuild[p[e]] !== undefined ? hashBuild[p[e]] + 1 : 1; + hashBuild[p[e]] = hashBuild[p[e]] !== undefined ? hashBuild[p[e]] + 1 : 1; } for(let i = start; i < end; i++) { - if(hashBuild[s[i]] !== undefined) { - hashBuild[s[i]] = hashBuild[s[i]] - 1; - if(hashBuild[s[i]] >= 0) { - countLeft--; - } + if(hashBuild[s[i]] !== undefined) { + hashBuild[s[i]] = hashBuild[s[i]] - 1; + if(hashBuild[s[i]] >= 0) { + countLeft--; } + } } while(end < s.length) { - // check left - if(hashBuild[s[end]] !== undefined) { - hashBuild[s[end]] = hashBuild[s[end]] - 1; - if(hashBuild[s[end]] >= 0) { - countLeft--; - } - if(countLeft == 0) { - anagrams.push(start); - } + // check left + if(hashBuild[s[end]] !== undefined) { + hashBuild[s[end]] = hashBuild[s[end]] - 1; + if(hashBuild[s[end]] >= 0) { + countLeft--; } + if(countLeft == 0) { + anagrams.push(start); + } + } - // check right - if(hashBuild[s[start]] !== undefined) { - hashBuild[s[start]] = hashBuild[s[start]] + 1; - if(hashBuild[s[start]] >= 1) { - countLeft++; - } + // check right + if(hashBuild[s[start]] !== undefined) { + hashBuild[s[start]] = hashBuild[s[start]] + 1; + if(hashBuild[s[start]] >= 1) { + countLeft++; } + } - // slide window - end++; - start++; + // slide window + end++; + start++; } return anagrams; diff --git a/LeetcodeProblems/Algorithms/Find_Subarrays_With_Equal_Sum.js b/LeetcodeProblems/Algorithms/medium/Find_Subarrays_With_Equal_Sum.js similarity index 97% rename from LeetcodeProblems/Algorithms/Find_Subarrays_With_Equal_Sum.js rename to LeetcodeProblems/Algorithms/medium/Find_Subarrays_With_Equal_Sum.js index 3981e04..fa28d07 100644 --- a/LeetcodeProblems/Algorithms/Find_Subarrays_With_Equal_Sum.js +++ b/LeetcodeProblems/Algorithms/medium/Find_Subarrays_With_Equal_Sum.js @@ -35,7 +35,7 @@ Note that even though the subarrays have the same content, the two subarrays are * @param {number[]} nums * @return {boolean} */ - var findSubarrays = function (nums) { +var findSubarrays = function (nums) { const sumsSeen = new Set(); for (let i = 0; i < nums.length - 1; i++) { diff --git a/LeetcodeProblems/Algorithms/medium/Gas_Station.js b/LeetcodeProblems/Algorithms/medium/Gas_Station.js new file mode 100644 index 0000000..f7fe18c --- /dev/null +++ b/LeetcodeProblems/Algorithms/medium/Gas_Station.js @@ -0,0 +1,51 @@ +/** + * Problem: https://leetcode.com/problems/gas-station/description/ + */ +/* +There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. +You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. +You begin the journey with an empty tank at one of the gas stations. +Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, +otherwise return -1. +If there exists a solution, it is guaranteed to be unique + +Example 1: + +Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2] +Output: 3 + +*/ +/** + * @param {number[]} gas + * @param {number[]} cost + * @return {number} + */ +var canCompleteCircuit = function(gas, cost) { + var gasSum =0, costSum = 0; + var len = gas.length; + var result = 0; + + for (var i = 0; i < len; ++i) { + gasSum += gas[i]; + costSum += cost[i]; + } + + if (costSum > gasSum) + return -1; + else { + gasSum = costSum = 0; + for (i = 0; i < len; ++i) { + gasSum += gas[i]; + costSum += cost[i]; + if (costSum > gasSum) { + gasSum = 0; + costSum = 0; + result = i + 1; + } + } + } + + return result; +}; + +module.exports.canCompleteCircuit = canCompleteCircuit; \ No newline at end of file diff --git a/LeetcodeProblems/Algorithms/Generate_Parenthesis.js b/LeetcodeProblems/Algorithms/medium/Generate_Parenthesis.js similarity index 100% rename from LeetcodeProblems/Algorithms/Generate_Parenthesis.js rename to LeetcodeProblems/Algorithms/medium/Generate_Parenthesis.js diff --git a/LeetcodeProblems/Algorithms/Group_Anagrams.js b/LeetcodeProblems/Algorithms/medium/Group_Anagrams.js similarity index 100% rename from LeetcodeProblems/Algorithms/Group_Anagrams.js rename to LeetcodeProblems/Algorithms/medium/Group_Anagrams.js diff --git a/LeetcodeProblems/Algorithms/medium/K_Closest_Points_to_Origin.js b/LeetcodeProblems/Algorithms/medium/K_Closest_Points_to_Origin.js new file mode 100644 index 0000000..fa2fca5 --- /dev/null +++ b/LeetcodeProblems/Algorithms/medium/K_Closest_Points_to_Origin.js @@ -0,0 +1,46 @@ +/* +Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). + +The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). + +You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). + +Example 1 + +Input: points = [[1,3],[-2,2]], k = 1 +Output: [[-2,2]] +Explanation: +The distance between (1, 3) and the origin is sqrt(10). +The distance between (-2, 2) and the origin is sqrt(8). +Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. +We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. + +Example 2: + +Input: points = [[3,3],[5,-1],[-2,4]], k = 2 +Output: [[3,3],[-2,4]] +Explanation: The answer [[-2,4],[3,3]] would also be accepted. +*/ + +/** + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ + +var kClosest = function(points, k) { + const queue = []; + + for (let i = 0; i < points.length; i++) { + queue.push(points[i]); + queue.sort((a, b) => ((a[0] * a[0]) + (a[1] * a[1])) - ((b[0] * b[0]) + (b[1] * b[1]))); + + if (queue.length > k) { + queue.pop(); + } + } + + return queue; +}; + +module.exports.kClosest = kClosest; \ No newline at end of file diff --git a/LeetcodeProblems/Algorithms/Kth_Largest_Element_in_an_Array.js b/LeetcodeProblems/Algorithms/medium/Kth_Largest_Element_in_an_Array.js similarity index 100% rename from LeetcodeProblems/Algorithms/Kth_Largest_Element_in_an_Array.js rename to LeetcodeProblems/Algorithms/medium/Kth_Largest_Element_in_an_Array.js diff --git a/LeetcodeProblems/Algorithms/Linked_List_Cycle_II.js b/LeetcodeProblems/Algorithms/medium/Linked_List_Cycle_II.js similarity index 100% rename from LeetcodeProblems/Algorithms/Linked_List_Cycle_II.js rename to LeetcodeProblems/Algorithms/medium/Linked_List_Cycle_II.js diff --git a/LeetcodeProblems/Algorithms/Longest_Palindromic_Substring.js b/LeetcodeProblems/Algorithms/medium/Longest_Palindromic_Substring.js similarity index 100% rename from LeetcodeProblems/Algorithms/Longest_Palindromic_Substring.js rename to LeetcodeProblems/Algorithms/medium/Longest_Palindromic_Substring.js diff --git a/LeetcodeProblems/Algorithms/Longest_Substring.js b/LeetcodeProblems/Algorithms/medium/Longest_Substring.js similarity index 85% rename from LeetcodeProblems/Algorithms/Longest_Substring.js rename to LeetcodeProblems/Algorithms/medium/Longest_Substring.js index a6430f1..cc6726c 100644 --- a/LeetcodeProblems/Algorithms/Longest_Substring.js +++ b/LeetcodeProblems/Algorithms/medium/Longest_Substring.js @@ -32,8 +32,8 @@ s consists of English letters, digits, symbols and spaces. * @param {string} s * @return {number} */ - var lengthOfLongestSubstring = function(s) { - if(s.length == 0) { return 0 } +var lengthOfLongestSubstring = function(s) { + if(s.length == 0) { return 0; } var repeatedChars = new Set(); var maxLength = 1; @@ -45,15 +45,15 @@ s consists of English letters, digits, symbols and spaces. while(end + 1 < s.length && start < s.length) { if(repeatedChars.has(s.charAt(end + 1))) { if(repeatedChars.has(s.charAt(start))) { - currentMaxLength--; - repeatedChars.delete(s.charAt(start)) + currentMaxLength--; + repeatedChars.delete(s.charAt(start)); } - start++; + start++; } else { repeatedChars.add(s.charAt(end + 1)); currentMaxLength++; if(currentMaxLength > maxLength) { - maxLength = currentMaxLength; + maxLength = currentMaxLength; } end++; } diff --git a/LeetcodeProblems/Algorithms/Lowest_Common_Ancestor_of_a_Binary_Tree.js b/LeetcodeProblems/Algorithms/medium/Lowest_Common_Ancestor_of_a_Binary_Tree.js similarity index 100% rename from LeetcodeProblems/Algorithms/Lowest_Common_Ancestor_of_a_Binary_Tree.js rename to LeetcodeProblems/Algorithms/medium/Lowest_Common_Ancestor_of_a_Binary_Tree.js diff --git a/LeetcodeProblems/Algorithms/Max_Area_Of_Island.js b/LeetcodeProblems/Algorithms/medium/Max_Area_Of_Island.js similarity index 100% rename from LeetcodeProblems/Algorithms/Max_Area_Of_Island.js rename to LeetcodeProblems/Algorithms/medium/Max_Area_Of_Island.js diff --git a/LeetcodeProblems/Algorithms/Max_Consecutive_Ones_III.js b/LeetcodeProblems/Algorithms/medium/Max_Consecutive_Ones_III.js similarity index 70% rename from LeetcodeProblems/Algorithms/Max_Consecutive_Ones_III.js rename to LeetcodeProblems/Algorithms/medium/Max_Consecutive_Ones_III.js index 7766668..5344c66 100644 --- a/LeetcodeProblems/Algorithms/Max_Consecutive_Ones_III.js +++ b/LeetcodeProblems/Algorithms/medium/Max_Consecutive_Ones_III.js @@ -24,18 +24,18 @@ var longestOnes = function(nums, k) { let end = 0; let maxWindow = 0; while(start < nums.length && end < nums.length) { - if(k > 0 || nums[end] == 1) { - if(nums[end] == 0) { k--; } - maxWindow = Math.max(maxWindow, end - start + 1); - end++; - } else { // k = 0 and nums[end] == 0 - while(k == 0 && start < nums.length) { - if(nums[start] == 0) { - k++; - } - start++; - } + if(k > 0 || nums[end] == 1) { + if(nums[end] == 0) { k--; } + maxWindow = Math.max(maxWindow, end - start + 1); + end++; + } else { // k = 0 and nums[end] == 0 + while(k == 0 && start < nums.length) { + if(nums[start] == 0) { + k++; + } + start++; } + } } return maxWindow; diff --git a/LeetcodeProblems/Algorithms/Maximal_Square.js b/LeetcodeProblems/Algorithms/medium/Maximal_Square.js similarity index 100% rename from LeetcodeProblems/Algorithms/Maximal_Square.js rename to LeetcodeProblems/Algorithms/medium/Maximal_Square.js diff --git a/LeetcodeProblems/Algorithms/Maximise_Hour_Glass_Sum.js b/LeetcodeProblems/Algorithms/medium/Maximise_Hour_Glass_Sum.js similarity index 79% rename from LeetcodeProblems/Algorithms/Maximise_Hour_Glass_Sum.js rename to LeetcodeProblems/Algorithms/medium/Maximise_Hour_Glass_Sum.js index 124d4a2..55bfd3f 100644 --- a/LeetcodeProblems/Algorithms/Maximise_Hour_Glass_Sum.js +++ b/LeetcodeProblems/Algorithms/medium/Maximise_Hour_Glass_Sum.js @@ -31,18 +31,20 @@ Explanation: There is only one hourglass in the matrix, with the sum: 1 + 2 + 3 * @param {number[][]} grid * @return {number} */ - var maxSum = function(grid) { +var maxSum = function(grid) { const m = grid.length; const n = grid[0].length; if(m<3 || n < 3) { - return 0; + return 0; } let max = 0; for(let i = 0; i a-b); + let i = 0, j = nums.length - 1; + let max = -Infinity; + while (i < j) { + max = Math.max(max, nums[i++] + nums[j--]); + } + return max; +}; + +module.exports.minPairSum = minPairSum; diff --git a/LeetcodeProblems/Algorithms/Minimum_Add_To_Make_Parentheses_Valid.js b/LeetcodeProblems/Algorithms/medium/Minimum_Add_To_Make_Parentheses_Valid.js similarity index 69% rename from LeetcodeProblems/Algorithms/Minimum_Add_To_Make_Parentheses_Valid.js rename to LeetcodeProblems/Algorithms/medium/Minimum_Add_To_Make_Parentheses_Valid.js index 9181d20..3f88dc1 100644 --- a/LeetcodeProblems/Algorithms/Minimum_Add_To_Make_Parentheses_Valid.js +++ b/LeetcodeProblems/Algorithms/medium/Minimum_Add_To_Make_Parentheses_Valid.js @@ -33,15 +33,15 @@ var minAddToMakeValid = function(s) { var extraParClosing = 0; for(let i = 0; i < s.length; i++) { - if(s.charAt(i) == "(") { - opening++; - } else if(s.charAt(i) == ")") { - if(opening == 0) { - extraParClosing++; - } else { - opening--;; - } - } + if(s.charAt(i) == "(") { + opening++; + } else if(s.charAt(i) == ")") { + if(opening == 0) { + extraParClosing++; + } else { + opening--; + } + } } return extraParClosing + opening; }; @@ -52,18 +52,19 @@ var minAddToMakeValidUsingQueue = function(s) { var extraParClosing = 0; for(let i = 0; i < s.length; i++) { - if(s.charAt(i) == "(") { - queue.push(s.charAt(i)) - } else if(s.charAt(i) == ")") { - if(queue.length > 0) { - queue.pop(); - } else { - extraParClosing++; - } - } + if(s.charAt(i) == "(") { + queue.push(s.charAt(i)); + } else if(s.charAt(i) == ")") { + if(queue.length > 0) { + queue.pop(); + } else { + extraParClosing++; + } + } } return extraParClosing + queue.length; }; -module.exports.minAddToMakeValid = minAddToMakeValid; \ No newline at end of file +module.exports.minAddToMakeValid = minAddToMakeValid; +module.exports.minAddToMakeValidUsingQueue = minAddToMakeValidUsingQueue; \ No newline at end of file diff --git a/LeetcodeProblems/Algorithms/Minimum_Size_Subarray.js b/LeetcodeProblems/Algorithms/medium/Minimum_Size_Subarray.js similarity index 63% rename from LeetcodeProblems/Algorithms/Minimum_Size_Subarray.js rename to LeetcodeProblems/Algorithms/medium/Minimum_Size_Subarray.js index dcaa489..481531e 100644 --- a/LeetcodeProblems/Algorithms/Minimum_Size_Subarray.js +++ b/LeetcodeProblems/Algorithms/medium/Minimum_Size_Subarray.js @@ -24,8 +24,8 @@ Output: 0 * @param {number[]} nums * @return {number} */ - var minSubArrayLength = function(target, nums) { - if(nums.length == 0) { return 0 } +var minSubArrayLength = function(target, nums) { + if(nums.length == 0) { return 0; } let start = 0; let end = 0; @@ -34,20 +34,20 @@ Output: 0 let currentWindow = 1; while(start < nums.length && end < nums.length) { - currentWindow = (end + 1 - start) - if(currentSum >= target || (minWindow != 0 && currentWindow > minWindow) ) { - if(minWindow == 0 || minWindow > currentWindow ) { - minWindow = currentWindow; - if(minWindow == 1) { return 1 }; - } - currentSum -= nums[start]; - start++; - } else { - end++; - if(end < nums.length) { - currentSum += nums[end]; - } + currentWindow = (end + 1 - start); + if(currentSum >= target || (minWindow != 0 && currentWindow > minWindow) ) { + if(minWindow == 0 || minWindow > currentWindow ) { + minWindow = currentWindow; + if(minWindow == 1) { return 1; } } + currentSum -= nums[start]; + start++; + } else { + end++; + if(end < nums.length) { + currentSum += nums[end]; + } + } } return minWindow; diff --git a/LeetcodeProblems/Algorithms/medium/Next_Permutation.js b/LeetcodeProblems/Algorithms/medium/Next_Permutation.js new file mode 100644 index 0000000..30e496a --- /dev/null +++ b/LeetcodeProblems/Algorithms/medium/Next_Permutation.js @@ -0,0 +1,70 @@ +/** +Next Permutation +https://leetcode.com/problems/next-permutation/ + +A permutation of an array of integers is an arrangement of its members into a sequence or linear order. + +For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]. +The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). + +For example, the next permutation of arr = [1,2,3] is [1,3,2]. +Similarly, the next permutation of arr = [2,3,1] is [3,1,2]. +While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement. +Given an array of integers nums, find the next permutation of nums. + +The replacement must be in place and use only constant extra memory. + +Example 1: +Input: nums = [1,2,3] +Output: [1,3,2] + +Example 2: +Input: nums = [3,2,1] +Output: [1,2,3] + +Example 3: +Input: nums = [1,1,5] +Output: [1,5,1] + * + */ + +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ + +var nextPermutation = function(nums) { + let k = nums.length - 2; + while ( k >= 0 && nums[k] >= nums[k + 1]) { + --k; + } + if (k === -1) { + reverse(nums, 0, nums.length-1); + return; + } + + for (let l = nums.length - 1; l > k; l--) { + if (nums[l] > nums[k]) { + swap(nums, k, l); + break; + } + } + + reverse(nums, k + 1, nums.length -1); +}; + +function swap(arr, a, b) { + let temp = arr[a]; + arr[a] = arr[b]; + arr[b] = temp; +} + +function reverse(nums, start ,end) { + while(start < end) { + swap(nums, start, end); + start++; + end--; + } +} + +module.exports.nextPermutation = nextPermutation; diff --git a/LeetcodeProblems/Algorithms/Number_of_Islands.js b/LeetcodeProblems/Algorithms/medium/Number_of_Islands.js similarity index 100% rename from LeetcodeProblems/Algorithms/Number_of_Islands.js rename to LeetcodeProblems/Algorithms/medium/Number_of_Islands.js diff --git a/LeetcodeProblems/Algorithms/Permutations.js b/LeetcodeProblems/Algorithms/medium/Permutations.js similarity index 100% rename from LeetcodeProblems/Algorithms/Permutations.js rename to LeetcodeProblems/Algorithms/medium/Permutations.js diff --git a/LeetcodeProblems/Algorithms/Permutations_II.js b/LeetcodeProblems/Algorithms/medium/Permutations_II.js similarity index 100% rename from LeetcodeProblems/Algorithms/Permutations_II.js rename to LeetcodeProblems/Algorithms/medium/Permutations_II.js diff --git a/LeetcodeProblems/Algorithms/Permutations_In_String.js b/LeetcodeProblems/Algorithms/medium/Permutations_In_String.js similarity index 58% rename from LeetcodeProblems/Algorithms/Permutations_In_String.js rename to LeetcodeProblems/Algorithms/medium/Permutations_In_String.js index 17ea56c..8ddfb40 100644 --- a/LeetcodeProblems/Algorithms/Permutations_In_String.js +++ b/LeetcodeProblems/Algorithms/medium/Permutations_In_String.js @@ -26,9 +26,9 @@ s1 and s2 consist of lowercase English letters. * @param {string} s2 * @return {boolean} */ - var checkInclusion = function(s1, s2) { +var checkInclusion = function(s1, s2) { if(s1.length > s2.length) { - return false + return false; } let start = 0; @@ -37,37 +37,37 @@ s1 and s2 consist of lowercase English letters. let hashBuild = {}; for(var i = 0; i < s1.length; i++) { - hashBuild[s1[i]] = (hashBuild[s1[i]] || 0) + 1; + hashBuild[s1[i]] = (hashBuild[s1[i]] || 0) + 1; } for(var j = start; j < end; j++) { // TODO: didn't count upper bound - if(hashBuild[s2[j]] !== undefined) { - hashBuild[s2[j]] = hashBuild[s2[j]] - 1; - if(hashBuild[s2[j]] >= 0) { - countLeft--; - } + if(hashBuild[s2[j]] !== undefined) { + hashBuild[s2[j]] = hashBuild[s2[j]] - 1; + if(hashBuild[s2[j]] >= 0) { + countLeft--; } + } } while(end < s2.length) { - if(hashBuild[s2[end]] !== undefined) { - hashBuild[s2[end]] = hashBuild[s2[end]] - 1; - if(hashBuild[s2[end]] >= 0) { - countLeft--; - } + if(hashBuild[s2[end]] !== undefined) { + hashBuild[s2[end]] = hashBuild[s2[end]] - 1; + if(hashBuild[s2[end]] >= 0) { + countLeft--; } + } - if(countLeft == 0) { return true } + if(countLeft == 0) { return true; } - if(hashBuild[s2[start]] !== undefined) { - hashBuild[s2[start]] = hashBuild[s2[start]] + 1; - if(hashBuild[s2[start]] >= 1) { - countLeft++; - } + if(hashBuild[s2[start]] !== undefined) { + hashBuild[s2[start]] = hashBuild[s2[start]] + 1; + if(hashBuild[s2[start]] >= 1) { + countLeft++; } + } - start++; - end++; + start++; + end++; } return false; diff --git a/LeetcodeProblems/Algorithms/Permutations_With_Duplicates.js b/LeetcodeProblems/Algorithms/medium/Permutations_With_Duplicates.js similarity index 100% rename from LeetcodeProblems/Algorithms/Permutations_With_Duplicates.js rename to LeetcodeProblems/Algorithms/medium/Permutations_With_Duplicates.js diff --git a/LeetcodeProblems/Algorithms/Permutations_Without_Duplicates.js b/LeetcodeProblems/Algorithms/medium/Permutations_Without_Duplicates.js similarity index 100% rename from LeetcodeProblems/Algorithms/Permutations_Without_Duplicates.js rename to LeetcodeProblems/Algorithms/medium/Permutations_Without_Duplicates.js diff --git a/LeetcodeProblems/Algorithms/Restore_IP_Addresses.js b/LeetcodeProblems/Algorithms/medium/Restore_IP_Addresses.js similarity index 100% rename from LeetcodeProblems/Algorithms/Restore_IP_Addresses.js rename to LeetcodeProblems/Algorithms/medium/Restore_IP_Addresses.js diff --git a/LeetcodeProblems/Algorithms/medium/Reverse_Integer.js b/LeetcodeProblems/Algorithms/medium/Reverse_Integer.js new file mode 100644 index 0000000..058506e --- /dev/null +++ b/LeetcodeProblems/Algorithms/medium/Reverse_Integer.js @@ -0,0 +1,46 @@ +/** +Reverse Integer +https://leetcode.com/problems/reverse-integer/ + +Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. + +Assume the environment does not allow you to store 64-bit integers (signed or unsigned). + +Example 1: +Input: x = 123 +Output: 321 + +Example 2: +Input: x = -123 +Output: -321 + +Example 3: +Input: x = 120 +Output: 21 + + */ + +/** + * @param {number} x + * @return {number} + */ +var reverseInteger = function(x) { + const sign = x >= 0 ? 1 : -1; + + let baseNum = sign * x; + let builder = 0; + + while (baseNum > 0) { + const digit = baseNum % 10; + builder = builder * 10 + digit; + baseNum = (baseNum / 10) | 0; + } + + builder *= sign; + + const isWithinRange = (builder >= -Math.pow(2, 31) && builder <= Math.pow(2, 31) - 1); + + return isWithinRange ? builder : 0; +}; + +module.exports.reverseInteger = reverseInteger; \ No newline at end of file diff --git a/LeetcodeProblems/Algorithms/SearchIng_Rotated_Sorted_Array.js b/LeetcodeProblems/Algorithms/medium/SearchIng_Rotated_Sorted_Array.js similarity index 100% rename from LeetcodeProblems/Algorithms/SearchIng_Rotated_Sorted_Array.js rename to LeetcodeProblems/Algorithms/medium/SearchIng_Rotated_Sorted_Array.js diff --git a/LeetcodeProblems/Algorithms/Search_a_2D_Matrix.js b/LeetcodeProblems/Algorithms/medium/Search_a_2D_Matrix.js similarity index 100% rename from LeetcodeProblems/Algorithms/Search_a_2D_Matrix.js rename to LeetcodeProblems/Algorithms/medium/Search_a_2D_Matrix.js diff --git a/LeetcodeProblems/Algorithms/Search_a_2D_Matrix_II.js b/LeetcodeProblems/Algorithms/medium/Search_a_2D_Matrix_II.js similarity index 100% rename from LeetcodeProblems/Algorithms/Search_a_2D_Matrix_II.js rename to LeetcodeProblems/Algorithms/medium/Search_a_2D_Matrix_II.js diff --git a/LeetcodeProblems/Algorithms/Simplify_Path.js b/LeetcodeProblems/Algorithms/medium/Simplify_Path.js similarity index 100% rename from LeetcodeProblems/Algorithms/Simplify_Path.js rename to LeetcodeProblems/Algorithms/medium/Simplify_Path.js diff --git a/LeetcodeProblems/Algorithms/Spiral_Matrix.js b/LeetcodeProblems/Algorithms/medium/Spiral_Matrix.js similarity index 100% rename from LeetcodeProblems/Algorithms/Spiral_Matrix.js rename to LeetcodeProblems/Algorithms/medium/Spiral_Matrix.js diff --git a/LeetcodeProblems/Algorithms/Subarray_Sum_Equals_K.js b/LeetcodeProblems/Algorithms/medium/Subarray_Sum_Equals_K.js similarity index 100% rename from LeetcodeProblems/Algorithms/Subarray_Sum_Equals_K.js rename to LeetcodeProblems/Algorithms/medium/Subarray_Sum_Equals_K.js diff --git a/LeetcodeProblems/Algorithms/Subsets.js b/LeetcodeProblems/Algorithms/medium/Subsets.js similarity index 100% rename from LeetcodeProblems/Algorithms/Subsets.js rename to LeetcodeProblems/Algorithms/medium/Subsets.js diff --git a/LeetcodeProblems/Algorithms/Swap_Nodes_In_Pairs.js b/LeetcodeProblems/Algorithms/medium/Swap_Nodes_In_Pairs.js similarity index 100% rename from LeetcodeProblems/Algorithms/Swap_Nodes_In_Pairs.js rename to LeetcodeProblems/Algorithms/medium/Swap_Nodes_In_Pairs.js diff --git a/LeetcodeProblems/Algorithms/Time_Needed_Rearrange_Binary_String.js b/LeetcodeProblems/Algorithms/medium/Time_Needed_Rearrange_Binary_String.js similarity index 83% rename from LeetcodeProblems/Algorithms/Time_Needed_Rearrange_Binary_String.js rename to LeetcodeProblems/Algorithms/medium/Time_Needed_Rearrange_Binary_String.js index 87e5b89..603a914 100644 --- a/LeetcodeProblems/Algorithms/Time_Needed_Rearrange_Binary_String.js +++ b/LeetcodeProblems/Algorithms/medium/Time_Needed_Rearrange_Binary_String.js @@ -36,12 +36,14 @@ s[i] is either '0' or '1'. * @param {string} s * @return {number} */ - var secondsToRemoveOccurrences = function(s) { +var secondsToRemoveOccurrences = function(s) { let result = 0; - while (true) { - const replaced = s.replaceAll('01', '10'); + for(;;) { + const replaced = s.replaceAll("01", "10"); if (s === replaced) return result; s = replaced; result += 1; } -}; \ No newline at end of file +}; + +module.exports.secondsToRemoveOccurrences = secondsToRemoveOccurrences; diff --git a/LeetcodeProblems/Algorithms/medium/Top_K_Frequent_Elements.js b/LeetcodeProblems/Algorithms/medium/Top_K_Frequent_Elements.js new file mode 100644 index 0000000..80770cb --- /dev/null +++ b/LeetcodeProblems/Algorithms/medium/Top_K_Frequent_Elements.js @@ -0,0 +1,56 @@ +/* +Top K Frequent Elements +https://leetcode.com/problems/top-k-frequent-elements/description/ + +Given an integer array nums and an integer k, return the k most frequent elements. +You may return the answer in any order. + + +Example 1: + +Input: nums = [1,1,1,2,2,3], k = 2 +Output: [1,2] + + +Example 2: + +Input: nums = [1], k = 1 +Output: [1] + + +Constraints: + +1) 1 <= nums.length <= 10^5 +2) -10^4 <= nums[i] <= 10^4 +3) k is in the range [1, the number of unique elements in the array]. +4) It is guaranteed that the answer is unique. +*/ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function(nums, k) { + const freqMap = new Map(); + const bucket = []; + const result = []; + + for(let num of nums) { + freqMap.set(num, (freqMap.get(num) || 0) + 1); + } + + for(let [num, freq] of freqMap) { + bucket[freq] = (bucket[freq] || new Set()).add(num); + } + + for(let i = bucket.length-1; i >= 0; i--) { + if(bucket[i]) { + result.push(...bucket[i]); + if(result.length === k) break; + } + } + return result; +}; + +module.exports.topKFrequent = topKFrequent; diff --git a/LeetcodeProblems/Algorithms/Unique_Binary_Search_Trees.js b/LeetcodeProblems/Algorithms/medium/Unique_Binary_Search_Trees.js similarity index 100% rename from LeetcodeProblems/Algorithms/Unique_Binary_Search_Trees.js rename to LeetcodeProblems/Algorithms/medium/Unique_Binary_Search_Trees.js diff --git a/LeetcodeProblems/Algorithms/Unique_Paths.js b/LeetcodeProblems/Algorithms/medium/Unique_Paths.js similarity index 100% rename from LeetcodeProblems/Algorithms/Unique_Paths.js rename to LeetcodeProblems/Algorithms/medium/Unique_Paths.js diff --git a/LeetcodeProblems/Algorithms/Verify_Preorder_Serialization_of_a_Binary_Tree.js b/LeetcodeProblems/Algorithms/medium/Verify_Preorder_Serialization_of_a_Binary_Tree.js similarity index 100% rename from LeetcodeProblems/Algorithms/Verify_Preorder_Serialization_of_a_Binary_Tree.js rename to LeetcodeProblems/Algorithms/medium/Verify_Preorder_Serialization_of_a_Binary_Tree.js diff --git a/LeetcodeProblems/Databases/Classes_More_Than_5_Students.sql b/LeetcodeProblems/Databases/easy/Classes_More_Than_5_Students.sql similarity index 100% rename from LeetcodeProblems/Databases/Classes_More_Than_5_Students.sql rename to LeetcodeProblems/Databases/easy/Classes_More_Than_5_Students.sql diff --git a/LeetcodeProblems/Databases/Combine_Two_Tables.sql b/LeetcodeProblems/Databases/easy/Combine_Two_Tables.sql similarity index 100% rename from LeetcodeProblems/Databases/Combine_Two_Tables.sql rename to LeetcodeProblems/Databases/easy/Combine_Two_Tables.sql diff --git a/LeetcodeProblems/Databases/Customers_Who_Never_Order.sql b/LeetcodeProblems/Databases/easy/Customers_Who_Never_Order.sql similarity index 100% rename from LeetcodeProblems/Databases/Customers_Who_Never_Order.sql rename to LeetcodeProblems/Databases/easy/Customers_Who_Never_Order.sql diff --git a/LeetcodeProblems/Databases/Delete_Duplicate_Emails.sql b/LeetcodeProblems/Databases/easy/Delete_Duplicate_Emails.sql similarity index 100% rename from LeetcodeProblems/Databases/Delete_Duplicate_Emails.sql rename to LeetcodeProblems/Databases/easy/Delete_Duplicate_Emails.sql diff --git a/LeetcodeProblems/Databases/Duplicate_emails.sql b/LeetcodeProblems/Databases/easy/Duplicate_emails.sql similarity index 100% rename from LeetcodeProblems/Databases/Duplicate_emails.sql rename to LeetcodeProblems/Databases/easy/Duplicate_emails.sql diff --git a/LeetcodeProblems/Databases/Employees_Earning_More_Than_Their_Managers.sql b/LeetcodeProblems/Databases/easy/Employees_Earning_More_Than_Their_Managers.sql similarity index 100% rename from LeetcodeProblems/Databases/Employees_Earning_More_Than_Their_Managers.sql rename to LeetcodeProblems/Databases/easy/Employees_Earning_More_Than_Their_Managers.sql diff --git a/LeetcodeProblems/Databases/Reformat_Department_Table.sql b/LeetcodeProblems/Databases/easy/Reformat_Department_Table.sql similarity index 100% rename from LeetcodeProblems/Databases/Reformat_Department_Table.sql rename to LeetcodeProblems/Databases/easy/Reformat_Department_Table.sql diff --git a/LeetcodeProblems/Databases/Rising_Temperature.sql b/LeetcodeProblems/Databases/easy/Rising_Temperature.sql similarity index 100% rename from LeetcodeProblems/Databases/Rising_Temperature.sql rename to LeetcodeProblems/Databases/easy/Rising_Temperature.sql diff --git a/LeetcodeProblems/Databases/Second_highest_salary.sql b/LeetcodeProblems/Databases/easy/Second_highest_salary.sql similarity index 100% rename from LeetcodeProblems/Databases/Second_highest_salary.sql rename to LeetcodeProblems/Databases/easy/Second_highest_salary.sql diff --git a/LeetcodeProblems/Databases/Human_Traffic_of_Stadium.sql b/LeetcodeProblems/Databases/hard/Human_Traffic_of_Stadium.sql similarity index 100% rename from LeetcodeProblems/Databases/Human_Traffic_of_Stadium.sql rename to LeetcodeProblems/Databases/hard/Human_Traffic_of_Stadium.sql diff --git a/LeetcodeProblems/Databases/Trips_and_Users.sql b/LeetcodeProblems/Databases/hard/Trips_and_Users.sql similarity index 100% rename from LeetcodeProblems/Databases/Trips_and_Users.sql rename to LeetcodeProblems/Databases/hard/Trips_and_Users.sql diff --git a/LeetcodeProblems/Databases/Consecutive_Numbers.sql b/LeetcodeProblems/Databases/medium/Consecutive_Numbers.sql similarity index 100% rename from LeetcodeProblems/Databases/Consecutive_Numbers.sql rename to LeetcodeProblems/Databases/medium/Consecutive_Numbers.sql diff --git a/LeetcodeProblems/Databases/Department_Highest_Salary.sql b/LeetcodeProblems/Databases/medium/Department_Highest_Salary.sql similarity index 100% rename from LeetcodeProblems/Databases/Department_Highest_Salary.sql rename to LeetcodeProblems/Databases/medium/Department_Highest_Salary.sql diff --git a/LeetcodeProblems/Databases/Exchange_Seats.sql b/LeetcodeProblems/Databases/medium/Exchange_Seats.sql similarity index 100% rename from LeetcodeProblems/Databases/Exchange_Seats.sql rename to LeetcodeProblems/Databases/medium/Exchange_Seats.sql diff --git a/LeetcodeProblems/Databases/Rank_Scores.sql b/LeetcodeProblems/Databases/medium/Rank_Scores.sql similarity index 100% rename from LeetcodeProblems/Databases/Rank_Scores.sql rename to LeetcodeProblems/Databases/medium/Rank_Scores.sql diff --git a/LeetcodeProblems/Databases/nth_Highest_Salary.sql b/LeetcodeProblems/Databases/medium/nth_Highest_Salary.sql similarity index 100% rename from LeetcodeProblems/Databases/nth_Highest_Salary.sql rename to LeetcodeProblems/Databases/medium/nth_Highest_Salary.sql diff --git a/LeetcodeProblemsTests/Algorithms/3Sum_Closest_Test.js b/LeetcodeProblemsTests/Algorithms/3Sum_Closest_Test.js deleted file mode 100644 index af8e630..0000000 --- a/LeetcodeProblemsTests/Algorithms/3Sum_Closest_Test.js +++ /dev/null @@ -1,10 +0,0 @@ -const assert = require('assert'); -const threeSumClosest = require('../../LeetcodeProblems/Algorithms/3SumClosest').threeSumClosest; - -var test = function () { - assert.equal(2, threeSumClosest([-1, 2 , 1, -4], 1)); - assert.equal(0, threeSumClosest([0, 0, 0], 1)); - -} - -module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/3Sum_Test.js b/LeetcodeProblemsTests/Algorithms/3Sum_Test.js deleted file mode 100644 index cee1910..0000000 --- a/LeetcodeProblemsTests/Algorithms/3Sum_Test.js +++ /dev/null @@ -1,22 +0,0 @@ -const assert = require('assert'); -const threeSum = require('../../LeetcodeProblems/Algorithms/3Sum').threeSum; - -var test = function () { - assert.deepEqual(threeSum([]), []); - assert.deepEqual(threeSum([0]), []); - assert.deepEqual(threeSum([0, 0]), []); - assert.deepEqual( - threeSum([0, 0, 0]), - [[0, 0, 0]] - ); - assert.deepEqual( - threeSum([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), - [[0, 0, 0]] - ); - assert.deepEqual( - threeSum([-1, 0, 1, 2, -1, -4]), - [ [ -1, 2, -1 ], [ 0, 1, -1 ] ] - ); -} - -module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Best_Time_To_Buy_And_Sell_Stock_II_Test.js b/LeetcodeProblemsTests/Algorithms/Best_Time_To_Buy_And_Sell_Stock_II_Test.js deleted file mode 100644 index 5af376c..0000000 --- a/LeetcodeProblemsTests/Algorithms/Best_Time_To_Buy_And_Sell_Stock_II_Test.js +++ /dev/null @@ -1,9 +0,0 @@ -const assert = require('assert'); -const maxProfit = require('../../LeetcodeProblems/Algorithms/Best_Time_To_Buy_And_Sell_Stock_II').maxProfit; - -function test() { - assert.equal(maxProfit([7,1,5,3,6,4]), 7); - assert.equal(maxProfit([7,1,5,3320,6,4]), 3319); -} - -module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal_Test.js b/LeetcodeProblemsTests/Algorithms/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal_Test.js deleted file mode 100644 index 93b7aed..0000000 --- a/LeetcodeProblemsTests/Algorithms/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal_Test.js +++ /dev/null @@ -1,9 +0,0 @@ -const assert = require('assert'); -var buildTree = require('../../LeetcodeProblems/Algorithms/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal').buildTree; - -function test() { - // TODO - console.log(buildTree([3,9,20,15,7], [9,3,15,20,7])); -} - -module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Container_With_Most_Water_Test.js b/LeetcodeProblemsTests/Algorithms/Container_With_Most_Water_Test.js deleted file mode 100644 index 4006962..0000000 --- a/LeetcodeProblemsTests/Algorithms/Container_With_Most_Water_Test.js +++ /dev/null @@ -1,10 +0,0 @@ -const assert = require('assert'); -const maxArea = require('../../LeetcodeProblems/Algorithms/Container_With_Most_Water_Test').maxArea; - -function test() { - assert.equal(49, maxArea([1,8,6,2,5,4,8,3,7])); - assert.equal(1, maxArea([1,1])); - -} - -module.exports.test = test; \ No newline at end of file diff --git a/LeetcodeProblemsTests/Algorithms/Group_Anagrams_Test.js b/LeetcodeProblemsTests/Algorithms/Group_Anagrams_Test.js deleted file mode 100644 index be15de9..0000000 --- a/LeetcodeProblemsTests/Algorithms/Group_Anagrams_Test.js +++ /dev/null @@ -1,11 +0,0 @@ -const assert = require('assert'); -const groupAnagrams = require('../../LeetcodeProblems/Algorithms/Group_Anagrams').groupAnagrams; - -function test() { - assert.deepEqual( - groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]), - [ [ 'eat', 'tea', 'ate' ], [ 'tan', 'nat' ], [ 'bat' ] ] - ) -} - -module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Maximise_Hour_Glass_Sum.js b/LeetcodeProblemsTests/Algorithms/Maximise_Hour_Glass_Sum.js deleted file mode 100644 index 066b941..0000000 --- a/LeetcodeProblemsTests/Algorithms/Maximise_Hour_Glass_Sum.js +++ /dev/null @@ -1,9 +0,0 @@ -const assert = require('assert'); -const maxSum = require('../../LeetcodeProblems/Algorithms/Maximise_Hour_Glass_Sum').maxSum; - -function test() { - assert.equal(maxSum([[6,2,1,3],[4,2,1,5],[9,2,8,7],[4,1,2,9]]), 30); - assert.equal(maxSum([[1,2,3],[4,5,6],[7,8,9]]), 35); -} - -module.exports.test = test diff --git a/LeetcodeProblemsTests/Algorithms/Permutations_II_Test.js b/LeetcodeProblemsTests/Algorithms/Permutations_II_Test.js deleted file mode 100644 index 53f4449..0000000 --- a/LeetcodeProblemsTests/Algorithms/Permutations_II_Test.js +++ /dev/null @@ -1,30 +0,0 @@ -const assert = require('assert'); -const permuteUnique = require('../../LeetcodeProblems/Algorithms/Permutations_II').permuteUnique; - -function test() { - assert.deepEqual( - permuteUnique([1,1,2]), - [ [ '1', '1', '2' ], [ '1', '2', '1' ], [ '2', '1', '1' ] ] - ); - assert.deepEqual( - permuteUnique([1,3,2,1]), - [ - [ '1', '1', '2', '3' ], - [ '1', '1', '3', '2' ], - [ '1', '2', '1', '3' ], - [ '1', '2', '3', '1' ], - [ '1', '3', '1', '2' ], - [ '1', '3', '2', '1' ], - [ '2', '1', '1', '3' ], - [ '2', '1', '3', '1' ], - [ '2', '3', '1', '1' ], - [ '3', '1', '1', '2' ], - [ '3', '1', '2', '1' ], - [ '3', '2', '1', '1' ] - ] - ); - assert.deepEqual(permuteUnique([]), [ [] ]); - assert.deepEqual(permuteUnique([1,1]), [ [ '1', '1' ] ]); -} - -module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Restore_IP_Addresses_Test.js b/LeetcodeProblemsTests/Algorithms/Restore_IP_Addresses_Test.js deleted file mode 100644 index f7d1c4a..0000000 --- a/LeetcodeProblemsTests/Algorithms/Restore_IP_Addresses_Test.js +++ /dev/null @@ -1,9 +0,0 @@ -const assert = require('assert'); -const restoreIpAddresses = require('../../LeetcodeProblems/Algorithms/Restore_IP_Addresses').restoreIpAddresses; - -var test = function() { - assert.deepEqual(restoreIpAddresses("010010"), [ '0.10.0.10', '0.100.1.0']); - assert.deepEqual(restoreIpAddresses("25525511135"), [ '255.255.11.135', '255.255.111.35' ]); -} - -module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/SearchIng_Rotated_Sorted_Array_Test.js b/LeetcodeProblemsTests/Algorithms/SearchIng_Rotated_Sorted_Array_Test.js deleted file mode 100644 index 1e45c57..0000000 --- a/LeetcodeProblemsTests/Algorithms/SearchIng_Rotated_Sorted_Array_Test.js +++ /dev/null @@ -1,8 +0,0 @@ -const assert = require('assert'); -const search = require('../../LeetcodeProblems/Algorithms/SearchIng_Rotated_Sorted_Array').search; - -var test = function() { - assert.equal(search([4,5,6,7,0,1,2], 5), 1); -} - -module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Spiral_Matrix_Test.js b/LeetcodeProblemsTests/Algorithms/Spiral_Matrix_Test.js deleted file mode 100644 index 7ffe0f8..0000000 --- a/LeetcodeProblemsTests/Algorithms/Spiral_Matrix_Test.js +++ /dev/null @@ -1,17 +0,0 @@ -const assert = require('assert'); -const spiralOrder = require('../../LeetcodeProblems/Algorithms/Spiral_Matrix').spiralOrder; - -var test = function() { - const matrix = [ - [ 1, 2, 3 ], - [ 4, 5, 6 ], - [ 7, 8, 9 ] - ] - - assert.deepEqual( - spiralOrder(matrix), - [1, 2, 3, 6, 9, 8, 7, 4, 5] - ) -} - -module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Time_Needed_Rearrange_Binary_String_Test.js b/LeetcodeProblemsTests/Algorithms/Time_Needed_Rearrange_Binary_String_Test.js deleted file mode 100644 index c4e2f00..0000000 --- a/LeetcodeProblemsTests/Algorithms/Time_Needed_Rearrange_Binary_String_Test.js +++ /dev/null @@ -1,9 +0,0 @@ -const assert = require('assert'); -const secondsToRemoveOccurrences = require('../../LeetcodeProblems/Algorithms/Time_Needed_Rearrange_Binary_String').secondsToRemoveOccurrences; - -function test() { - assert.equal(secondsToRemoveOccurrences("0110101"), 4); - assert.equal(secondsToRemoveOccurrences("11100"), 0) -}; - -module.exports.test = test diff --git a/LeetcodeProblemsTests/Algorithms/Unique_Paths_Test.js b/LeetcodeProblemsTests/Algorithms/Unique_Paths_Test.js deleted file mode 100644 index 05d106a..0000000 --- a/LeetcodeProblemsTests/Algorithms/Unique_Paths_Test.js +++ /dev/null @@ -1,17 +0,0 @@ -const assert = require('assert'); -const uniquePaths1 = require('../../LeetcodeProblems/Algorithms/Unique_Paths').uniquePaths1; -const uniquePaths2 = require('../../LeetcodeProblems/Algorithms/Unique_Paths').uniquePaths2; -const uniquePaths3 = require('../../LeetcodeProblems/Algorithms/Unique_Paths').uniquePaths3; - -var test = function() { - assert.strictEqual(uniquePaths1(10,4), 220); - assert.strictEqual(uniquePaths1(3,2), 3); - - assert.strictEqual(uniquePaths2(10,4), 220); - assert.strictEqual(uniquePaths2(3,2), 3); - - assert.strictEqual(uniquePaths3(10,4), 220); - assert.strictEqual(uniquePaths3(3,2), 3); -} - -module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/easy/2Sum_Test.js b/LeetcodeProblemsTests/Algorithms/easy/2Sum_Test.js new file mode 100644 index 0000000..2fd2dbc --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/easy/2Sum_Test.js @@ -0,0 +1,19 @@ +const assert = require("assert"); +const twoSum = require("../../../LeetcodeProblems/Algorithms/easy/2Sum").twoSum; +const twoSum2 = require("../../../LeetcodeProblems/Algorithms/easy/2Sum").twoSum2; + +var testFirstSolution = function () { + assert.deepEqual([0,1], twoSum([2,7,11,15], 9)); + assert.deepEqual([1,2], twoSum([3,2,4], 6)); + assert.deepEqual([0,1], twoSum([3,3], 6)); +}; + +var testSecondSolution = function() { + assert.deepEqual([0,1], twoSum2([2,7,11,15], 9)); + assert.deepEqual([1,2], twoSum2([3,2,4], 6)); + assert.deepEqual([0,1], twoSum2([3,3], 6)); +}; + + +module.exports.testFirstSolution = testFirstSolution; +module.exports.testSecondSolution = testSecondSolution; diff --git a/LeetcodeProblemsTests/Algorithms/Award_Budget_Cuts_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Award_Budget_Cuts_Test.js similarity index 63% rename from LeetcodeProblemsTests/Algorithms/Award_Budget_Cuts_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Award_Budget_Cuts_Test.js index 93f1c07..797fb52 100644 --- a/LeetcodeProblemsTests/Algorithms/Award_Budget_Cuts_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Award_Budget_Cuts_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const cutAwardBadges = require('../../LeetcodeProblems/Algorithms/Award_Budget_Cuts').cutAwardBadges; +const assert = require("assert"); +const cutAwardBadges = require("../../../LeetcodeProblems/Algorithms/easy/Award_Budget_Cuts").cutAwardBadges; function test() { assert.deepEqual( diff --git a/LeetcodeProblemsTests/Algorithms/Backspace_String_Compare_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Backspace_String_Compare_Test.js similarity index 67% rename from LeetcodeProblemsTests/Algorithms/Backspace_String_Compare_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Backspace_String_Compare_Test.js index 29d0757..4b73dfe 100644 --- a/LeetcodeProblemsTests/Algorithms/Backspace_String_Compare_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Backspace_String_Compare_Test.js @@ -1,6 +1,6 @@ -const assert = require('assert'); -const backspaceCompare = require('../../LeetcodeProblems/Algorithms/Backspace_String_Compare').backspaceCompare; -const backspaceCompare2 = require('../../LeetcodeProblems/Algorithms/Backspace_String_Compare').backspaceCompare2; +const assert = require("assert"); +const backspaceCompare = require("../../../LeetcodeProblems/Algorithms/easy/Backspace_String_Compare").backspaceCompare; +const backspaceCompare2 = require("../../../LeetcodeProblems/Algorithms/easy/Backspace_String_Compare").backspaceCompare2; function test() { assert.equal(backspaceCompare("ab#c", "ad#c"), true); // true diff --git a/LeetcodeProblemsTests/Algorithms/easy/Best_Time_to_buy_and_sell_stock_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Best_Time_to_buy_and_sell_stock_Test.js new file mode 100644 index 0000000..db97988 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/easy/Best_Time_to_buy_and_sell_stock_Test.js @@ -0,0 +1,15 @@ +const assert = require("assert"); +const maxProfitEqual = require("../../../LeetcodeProblems/Algorithms/easy/Best_Time_to_buy_and_sell_stock").maxProfit; + +function test() { + assert.deepEqual( + maxProfit([7,1,5,3,6,4]), + 5 + ); + assert.deepEqual( + maxProfit([7,6,4,3,1]), + 0 + ); +} + +module.exports.test = test; \ No newline at end of file diff --git a/LeetcodeProblemsTests/Algorithms/Binary_Gap_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Binary_Gap_Test.js similarity index 51% rename from LeetcodeProblemsTests/Algorithms/Binary_Gap_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Binary_Gap_Test.js index 2754af7..c89a4a6 100644 --- a/LeetcodeProblemsTests/Algorithms/Binary_Gap_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Binary_Gap_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const binaryGap = require('../../LeetcodeProblems/Algorithms/Binary_Gap').binaryGap; +const assert = require("assert"); +const binaryGap = require("../../../LeetcodeProblems/Algorithms/easy/Binary_Gap").binaryGap; function test() { assert.equal(binaryGap(22), 2); // 10110 diff --git a/LeetcodeProblemsTests/Algorithms/easy/Bit_Reverse_To_Make_Numbers_Equal.js b/LeetcodeProblemsTests/Algorithms/easy/Bit_Reverse_To_Make_Numbers_Equal.js new file mode 100644 index 0000000..9af014e --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/easy/Bit_Reverse_To_Make_Numbers_Equal.js @@ -0,0 +1,20 @@ +const assert = require("assert"); +const bitReverseToMakeNumberEqual = require("../../../LeetcodeProblems/Algorithms/easy/Bit_Reverse_To_Make_Numbers_Equal").bitChanges; + + +function test() { + assert.deepEqual( + bitChanges(13, 4), + 2 + ); + assert.deepEqual( + bitChanges(21, 21), + 0 + ); + assert.deepEqual( + bitChanges(14, 13), + -1 +); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Deletion_Distance_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Deletion_Distance_Test.js similarity index 64% rename from LeetcodeProblemsTests/Algorithms/Deletion_Distance_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Deletion_Distance_Test.js index 0cfdb27..7ac3d80 100644 --- a/LeetcodeProblemsTests/Algorithms/Deletion_Distance_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Deletion_Distance_Test.js @@ -1,7 +1,7 @@ -const assert = require('assert'); -var deletionDistance = require('../../LeetcodeProblems/Algorithms/Deletion_Distance').deletionDistance; -var deletionDistance2 = require('../../LeetcodeProblems/Algorithms/Deletion_Distance').deletionDistance2; -var deletionDistanceDP = require('../../LeetcodeProblems/Algorithms/Deletion_Distance').deletionDistanceDP; +const assert = require("assert"); +var deletionDistance = require("../../../LeetcodeProblems/Algorithms/easy/Deletion_Distance").deletionDistance; +var deletionDistance2 = require("../../../LeetcodeProblems/Algorithms/easy/Deletion_Distance").deletionDistance2; +var deletionDistanceDP = require("../../../LeetcodeProblems/Algorithms/easy/Deletion_Distance").deletionDistanceDP; function test() { assert.equal(deletionDistance("dog", "frog"), 3); diff --git a/LeetcodeProblemsTests/Algorithms/Flood_Fill_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Flood_Fill_Test.js similarity index 57% rename from LeetcodeProblemsTests/Algorithms/Flood_Fill_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Flood_Fill_Test.js index 36a29bb..557af9f 100644 --- a/LeetcodeProblemsTests/Algorithms/Flood_Fill_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Flood_Fill_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const floodFill = require('../../LeetcodeProblems/Algorithms/Flood_Fill').floodFill; +const assert = require("assert"); +const floodFill = require("../../../LeetcodeProblems/Algorithms/easy/Flood_Fill").floodFill; function test() { assert.deepEqual( diff --git a/LeetcodeProblemsTests/Algorithms/easy/Happy_Number_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Happy_Number_Test.js new file mode 100644 index 0000000..00e198a --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/easy/Happy_Number_Test.js @@ -0,0 +1,9 @@ +const assert = require("assert"); +const isHappy = require("../../../LeetcodeProblems/Algorithms/easy/Happy_Number").isHappy; + +var test = function () { + assert.equal(isHappy(19),true); + assert.equal(isHappy(2),false); +}; + +module.exports.test = test; \ No newline at end of file diff --git a/LeetcodeProblemsTests/Algorithms/Implement_stack_using_queues_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Implement_stack_using_queues_Test.js similarity index 72% rename from LeetcodeProblemsTests/Algorithms/Implement_stack_using_queues_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Implement_stack_using_queues_Test.js index cdc8e7d..a5d1735 100644 --- a/LeetcodeProblemsTests/Algorithms/Implement_stack_using_queues_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Implement_stack_using_queues_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const MyStack = require('../../LeetcodeProblems/Algorithms/Implement_stack_using_queues').MyStack; +const assert = require("assert"); +const MyStack = require("../../../LeetcodeProblems/Algorithms/easy/Implement_stack_using_queues").MyStack; var test = function () { var myStack = new MyStack(); @@ -14,6 +14,6 @@ var test = function () { assert.equal(myStack.pop(), 1); assert.equal(myStack.pop(), 2); assert.equal(myStack.pop(), 3); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/easy/Lexographic_smallest_after_swap.js b/LeetcodeProblemsTests/Algorithms/easy/Lexographic_smallest_after_swap.js new file mode 100644 index 0000000..a6f1663 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/easy/Lexographic_smallest_after_swap.js @@ -0,0 +1,17 @@ +const assert = require("assert"); +const bitReverseToMakeNumberEqual = require("../../../LeetcodeProblems/Algorithms/easy/Lexographic_smallest_after_swap").getSmallestString; + + +function test() { + assert.deepEqual( + getSmallestString("45320"), + "43520" + ); + assert.deepEqual( + getSmallestString("001"), + "001" + ); +); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/easy/Longest_Common_Prefix_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Longest_Common_Prefix_Test.js new file mode 100644 index 0000000..7a7109a --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/easy/Longest_Common_Prefix_Test.js @@ -0,0 +1,11 @@ + +const assert = require("assert"); +const longestCommonPrefix = require("../../../LeetcodeProblems/Algorithms/easy/Longest_Common_Prefix").longestCommonPrefix; + +function test() { + assert.equal(longestCommonPrefix(["flower","flow","flight"]), "fl"); + assert.equal(longestCommonPrefix(["dog","racecar","car"]), ""); + assert.equal(longestCommonPrefix([]), ""); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Majority_Element_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Majority_Element_Test.js similarity index 50% rename from LeetcodeProblemsTests/Algorithms/Majority_Element_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Majority_Element_Test.js index 494d641..96c08b8 100644 --- a/LeetcodeProblemsTests/Algorithms/Majority_Element_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Majority_Element_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const majorityElement = require('../../LeetcodeProblems/Algorithms/Majority_Element').majorityElement; +const assert = require("assert"); +const majorityElement = require("../../../LeetcodeProblems/Algorithms/easy/Majority_Element").majorityElement; function test() { assert.equal(majorityElement([2,2,3]), 2); @@ -7,4 +7,4 @@ function test() { assert.equal(majorityElement([1,1,1,2,3,45,1,2,4,1,1]), 1); } -module.exports.test = test +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Maximun_Subarray_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Maximun_Subarray_Test.js similarity index 61% rename from LeetcodeProblemsTests/Algorithms/Maximun_Subarray_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Maximun_Subarray_Test.js index aeb6f0d..d408555 100644 --- a/LeetcodeProblemsTests/Algorithms/Maximun_Subarray_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Maximun_Subarray_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const maxSubArray = require('../../LeetcodeProblems/Algorithms/Maximun_Subarray').maxSubArray; +const assert = require("assert"); +const maxSubArray = require("../../../LeetcodeProblems/Algorithms/easy/Maximun_Subarray").maxSubArray; function test() { assert.equal(maxSubArray([]), 0); diff --git a/LeetcodeProblemsTests/Algorithms/Min_Stack_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Min_Stack_Test.js similarity index 70% rename from LeetcodeProblemsTests/Algorithms/Min_Stack_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Min_Stack_Test.js index 16fb7c6..d94fb53 100644 --- a/LeetcodeProblemsTests/Algorithms/Min_Stack_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Min_Stack_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const MinStack = require('../../LeetcodeProblems/Algorithms/Min_Stack').MinStack; +const assert = require("assert"); +const MinStack = require("../../../LeetcodeProblems/Algorithms/easy/Min_Stack").MinStack; function test() { var minStack = new MinStack(); diff --git a/LeetcodeProblemsTests/Algorithms/Number_of_Segments_in_a_String_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Number_of_Segments_in_a_String_Test.js similarity index 67% rename from LeetcodeProblemsTests/Algorithms/Number_of_Segments_in_a_String_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Number_of_Segments_in_a_String_Test.js index e78cd3e..a33787f 100644 --- a/LeetcodeProblemsTests/Algorithms/Number_of_Segments_in_a_String_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Number_of_Segments_in_a_String_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const countSegments = require('../../LeetcodeProblems/Algorithms/Number_of_Segments_in_a_String').countSegments; +const assert = require("assert"); +const countSegments = require("../../../LeetcodeProblems/Algorithms/easy/Number_of_Segments_in_a_String").countSegments; function test() { assert.equal(countSegments(" "), 0); diff --git a/LeetcodeProblemsTests/Algorithms/Reverse_String_II_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Reverse_String_II_Test.js similarity index 65% rename from LeetcodeProblemsTests/Algorithms/Reverse_String_II_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Reverse_String_II_Test.js index e86446d..897f97f 100644 --- a/LeetcodeProblemsTests/Algorithms/Reverse_String_II_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Reverse_String_II_Test.js @@ -1,11 +1,11 @@ -const assert = require('assert'); -const reverseStr = require('../../LeetcodeProblems/Algorithms/Reverse_String_II').reverseStr; +const assert = require("assert"); +const reverseStr = require("../../../LeetcodeProblems/Algorithms/easy/Reverse_String_II").reverseStr; var test = function() { assert.equal(reverseStr("abcdefg", 2), "bacdfeg"); assert.equal(reverseStr("abcdefg", 3), "cbadefg"); assert.equal(reverseStr("abcdefg", 1), "abcdefg"); assert.equal(reverseStr("abcdefg", 0), "abcdefg"); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Same_Tree_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Same_Tree_Test.js similarity index 95% rename from LeetcodeProblemsTests/Algorithms/Same_Tree_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Same_Tree_Test.js index ea8b26b..928d068 100644 --- a/LeetcodeProblemsTests/Algorithms/Same_Tree_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Same_Tree_Test.js @@ -1,5 +1,5 @@ var test = function() { // TODO -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/easy/Shuffle_String_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Shuffle_String_Test.js new file mode 100644 index 0000000..8ca038b --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/easy/Shuffle_String_Test.js @@ -0,0 +1,10 @@ +const assert = require("assert"); +const restoreString = require("../../../LeetcodeProblems/Algorithms/easy/Shuffle_String").restoreString; + +var test = function () { + assert.equal(restoreString("codeleet",[4,5,6,7,0,2,1,3]),"leetcode"); + assert.equal(restoreString("abc",[0,1,2]),"abc"); + assert.equal(restoreString("hacktoberfest",[9,10,11,12,4,5,6,7,8,0,1,2,3]),"festtoberhack"); +}; + +module.exports.test = test; \ No newline at end of file diff --git a/LeetcodeProblemsTests/Algorithms/Sum_Of_Square_Numbers_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Sum_Of_Square_Numbers_Test.js similarity index 69% rename from LeetcodeProblemsTests/Algorithms/Sum_Of_Square_Numbers_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Sum_Of_Square_Numbers_Test.js index c4f642b..1a93b94 100644 --- a/LeetcodeProblemsTests/Algorithms/Sum_Of_Square_Numbers_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Sum_Of_Square_Numbers_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const judgeSquareSum = require('../../LeetcodeProblems/Algorithms/Sum_Of_Square_Numbers').judgeSquareSum; +const assert = require("assert"); +const judgeSquareSum = require("../../../LeetcodeProblems/Algorithms/easy/Sum_Of_Square_Numbers").judgeSquareSum; var test = function() { assert.strictEqual(judgeSquareSum(0), true); @@ -8,6 +8,6 @@ var test = function() { assert.strictEqual(judgeSquareSum(16), true); assert.strictEqual(judgeSquareSum(24), false); assert.strictEqual(judgeSquareSum(25), true); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Symmetric_Tree_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Symmetric_Tree_Test.js similarity index 95% rename from LeetcodeProblemsTests/Algorithms/Symmetric_Tree_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Symmetric_Tree_Test.js index ea8b26b..928d068 100644 --- a/LeetcodeProblemsTests/Algorithms/Symmetric_Tree_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Symmetric_Tree_Test.js @@ -1,5 +1,5 @@ var test = function() { // TODO -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Tic_Tac_Toe_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Tic_Tac_Toe_Test.js similarity index 65% rename from LeetcodeProblemsTests/Algorithms/Tic_Tac_Toe_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Tic_Tac_Toe_Test.js index b9656ab..a9ae9e3 100644 --- a/LeetcodeProblemsTests/Algorithms/Tic_Tac_Toe_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Tic_Tac_Toe_Test.js @@ -1,14 +1,14 @@ -const TicTacToe = require('../../LeetcodeProblems/Algorithms/Tic_Tac_Toe').TicTacToe; +const TicTacToe = require("../../../LeetcodeProblems/Algorithms/easy/Tic_Tac_Toe").TicTacToe; var test = function() { - ticTacToe = new TicTacToe(); + let ticTacToe = new TicTacToe(); ticTacToe.isBoardFull(); ticTacToe.addToken(0, 1, "X"); ticTacToe.printBoard(); var iter = 0; while(iter < 8) { - const str = (iter % 2 == 0) ? "0" : "X" + const str = (iter % 2 == 0) ? "0" : "X"; ticTacToe.makeMove(str); iter++; } @@ -18,6 +18,6 @@ var test = function() { ticTacToe.addToken(0,0,"X"); ticTacToe.printBoard(); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Valid_Parentheses_Test.js b/LeetcodeProblemsTests/Algorithms/easy/Valid_Parentheses_Test.js similarity index 68% rename from LeetcodeProblemsTests/Algorithms/Valid_Parentheses_Test.js rename to LeetcodeProblemsTests/Algorithms/easy/Valid_Parentheses_Test.js index 8e54762..499a6ba 100644 --- a/LeetcodeProblemsTests/Algorithms/Valid_Parentheses_Test.js +++ b/LeetcodeProblemsTests/Algorithms/easy/Valid_Parentheses_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const isValid = require('../../LeetcodeProblems/Algorithms/Valid_Parentheses').isValid; +const assert = require("assert"); +const isValid = require("../../../LeetcodeProblems/Algorithms/easy/Valid_Parentheses").isValid; var test = function () { assert.strictEqual(isValid(""), true); @@ -7,6 +7,6 @@ var test = function () { assert.strictEqual(isValid("([)]"), false); assert.strictEqual(isValid("{[()]}{[()]}"), true); assert.strictEqual(isValid("{[())()]}"), false); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Edit_Distance_Test.js b/LeetcodeProblemsTests/Algorithms/hard/Edit_Distance_Test.js similarity index 53% rename from LeetcodeProblemsTests/Algorithms/Edit_Distance_Test.js rename to LeetcodeProblemsTests/Algorithms/hard/Edit_Distance_Test.js index f190880..46732ca 100644 --- a/LeetcodeProblemsTests/Algorithms/Edit_Distance_Test.js +++ b/LeetcodeProblemsTests/Algorithms/hard/Edit_Distance_Test.js @@ -1,6 +1,6 @@ -const assert = require('assert'); -var minDistance = require('../../LeetcodeProblems/Algorithms/Edit_Distance').minDistance; -var minDistance2 = require('../../LeetcodeProblems/Algorithms/Edit_Distance').minDistance2; +const assert = require("assert"); +var minDistance = require("../../../LeetcodeProblems/Algorithms/hard/Edit_Distance").minDistance; +var minDistance2 = require("../../../LeetcodeProblems/Algorithms/hard/Edit_Distance").minDistance2; function test() { assert.equal(minDistance("ros", "horse"), 3); diff --git a/LeetcodeProblemsTests/Algorithms/hard/First_Missing_Positive_Test.js b/LeetcodeProblemsTests/Algorithms/hard/First_Missing_Positive_Test.js new file mode 100644 index 0000000..8662c2c --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/hard/First_Missing_Positive_Test.js @@ -0,0 +1,19 @@ +const assert = require("assert"); +const bitReverseToMakeNumberEqual = require("../../../LeetcodeProblems/Algorithms/hard/First_Missing_Positive").firstMissingPositive; + +function test() { + assert.deepEqual( + firstMissingPositive([1,2,0]), + 3 + ); + assert.deepEqual( + firstMissingPositive([3,4,-1,1]), + 2 + ); + assert.deepEqual( + firstMissingPositive([7,8,9,11,12]), + 1 +); +} + +module.exports.test = test; \ No newline at end of file diff --git a/LeetcodeProblemsTests/Algorithms/Longest_Consecutive_Sequence_Test.js b/LeetcodeProblemsTests/Algorithms/hard/Longest_Consecutive_Sequence_Test.js similarity index 68% rename from LeetcodeProblemsTests/Algorithms/Longest_Consecutive_Sequence_Test.js rename to LeetcodeProblemsTests/Algorithms/hard/Longest_Consecutive_Sequence_Test.js index 6ad441d..96c2bf8 100644 --- a/LeetcodeProblemsTests/Algorithms/Longest_Consecutive_Sequence_Test.js +++ b/LeetcodeProblemsTests/Algorithms/hard/Longest_Consecutive_Sequence_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const longestConsecutive = require('../../LeetcodeProblems/Algorithms/Longest_Consecutive_Sequence').longestConsecutive; +const assert = require("assert"); +const longestConsecutive = require("../../../LeetcodeProblems/Algorithms/hard/Longest_Consecutive_Sequence").longestConsecutive; function test() { assert.equal(longestConsecutive([100, 1, 200, 3, 2, 400, 201]), 3); diff --git a/LeetcodeProblemsTests/Algorithms/Minimum_Window_Substring_Test.js b/LeetcodeProblemsTests/Algorithms/hard/Minimum_Window_Substring_Test.js similarity index 70% rename from LeetcodeProblemsTests/Algorithms/Minimum_Window_Substring_Test.js rename to LeetcodeProblemsTests/Algorithms/hard/Minimum_Window_Substring_Test.js index d18350e..452aacf 100644 --- a/LeetcodeProblemsTests/Algorithms/Minimum_Window_Substring_Test.js +++ b/LeetcodeProblemsTests/Algorithms/hard/Minimum_Window_Substring_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const minWindow = require('../../LeetcodeProblems/Algorithms/Minimum_Window_Substring').minWindow; +const assert = require("assert"); +const minWindow = require("../../../LeetcodeProblems/Algorithms/hard/Minimum_Window_Substring").minWindow; function test() { assert.equal(minWindow("ADOBECODEBANC", "ABC"), "BANC"); diff --git a/LeetcodeProblemsTests/Algorithms/NQueens_Test.js b/LeetcodeProblemsTests/Algorithms/hard/NQueens_Test.js similarity index 80% rename from LeetcodeProblemsTests/Algorithms/NQueens_Test.js rename to LeetcodeProblemsTests/Algorithms/hard/NQueens_Test.js index 9387762..18ed528 100644 --- a/LeetcodeProblemsTests/Algorithms/NQueens_Test.js +++ b/LeetcodeProblemsTests/Algorithms/hard/NQueens_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const solveNQueens = require('../../LeetcodeProblems/Algorithms/NQueens').solveNQueens; +// const assert = require("assert"); +const solveNQueens = require("../../../LeetcodeProblems/Algorithms/hard/NQueens").solveNQueens; // TODO: Add assertions @@ -7,7 +7,7 @@ var test = function() { printMatrixes(solveNQueens(4), 4); printMatrixes(solveNQueens(5), 5); printMatrixes(solveNQueens(6), 6); -} +}; var printMatrixes = function(matrixes, n) { console.log("Start solution of n: " + n); @@ -15,7 +15,7 @@ var printMatrixes = function(matrixes, n) { printMatrix(matrixes[i]); } console.log("End solution of n: " + n); -} +}; var printMatrix = function(matrix) { console.log("------------"); @@ -23,6 +23,6 @@ var printMatrix = function(matrix) { console.log(matrix[i]); } console.log("------------"); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Regular_Expression_Matching_Test.js b/LeetcodeProblemsTests/Algorithms/hard/Regular_Expression_Matching_Test.js similarity index 69% rename from LeetcodeProblemsTests/Algorithms/Regular_Expression_Matching_Test.js rename to LeetcodeProblemsTests/Algorithms/hard/Regular_Expression_Matching_Test.js index ffcf28d..c8ee882 100644 --- a/LeetcodeProblemsTests/Algorithms/Regular_Expression_Matching_Test.js +++ b/LeetcodeProblemsTests/Algorithms/hard/Regular_Expression_Matching_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const isMatch = require('../../LeetcodeProblems/Algorithms/Regular_Expression_Matching').isMatch; +const assert = require("assert"); +const isMatch = require("../../../LeetcodeProblems/Algorithms/hard/Regular_Expression_Matching").isMatch; var test = function() { assert.equal(isMatch("aa", "a"), false); @@ -8,6 +8,6 @@ var test = function() { assert.equal(isMatch("ab", ".*"), true); assert.equal(isMatch("aab", "c*a*b"), true); assert.equal(isMatch("mississippi", "mis*is*p*."), false); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Remove_Invalid_Parentheses_Test.js b/LeetcodeProblemsTests/Algorithms/hard/Remove_Invalid_Parentheses_Test.js similarity index 61% rename from LeetcodeProblemsTests/Algorithms/Remove_Invalid_Parentheses_Test.js rename to LeetcodeProblemsTests/Algorithms/hard/Remove_Invalid_Parentheses_Test.js index a0a1a48..6b8f995 100644 --- a/LeetcodeProblemsTests/Algorithms/Remove_Invalid_Parentheses_Test.js +++ b/LeetcodeProblemsTests/Algorithms/hard/Remove_Invalid_Parentheses_Test.js @@ -1,11 +1,11 @@ -const assert = require('assert'); -const removeInvalidParentheses = require('../../LeetcodeProblems/Algorithms/Remove_Invalid_Parentheses').removeInvalidParentheses; +const assert = require("assert"); +const removeInvalidParentheses = require("../../../LeetcodeProblems/Algorithms/hard/Remove_Invalid_Parentheses").removeInvalidParentheses; var test = function() { assert.equal(removeInvalidParentheses("))))(()"), "()"); assert.equal(removeInvalidParentheses("(()"), "()"); assert.equal(removeInvalidParentheses("(d))()"), "(d)()"); assert.equal(removeInvalidParentheses("(())"), "(())"); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Set_Matrix_Zeroes_Test.js b/LeetcodeProblemsTests/Algorithms/hard/Set_Matrix_Zeroes_Test.js similarity index 53% rename from LeetcodeProblemsTests/Algorithms/Set_Matrix_Zeroes_Test.js rename to LeetcodeProblemsTests/Algorithms/hard/Set_Matrix_Zeroes_Test.js index 732c4f1..39b9e87 100644 --- a/LeetcodeProblemsTests/Algorithms/Set_Matrix_Zeroes_Test.js +++ b/LeetcodeProblemsTests/Algorithms/hard/Set_Matrix_Zeroes_Test.js @@ -1,11 +1,11 @@ -const assert = require('assert'); -const setZeroes = require('../../LeetcodeProblems/Algorithms/Set_Matrix_Zeroes').setZeroes; +const assert = require("assert"); +const setZeroes = require("../../../LeetcodeProblems/Algorithms/hard/Set_Matrix_Zeroes").setZeroes; var test = function() { assert.deepEqual( setZeroes([[1,1,1],[1,0,1],[1,1,1]]), [[1, 0, 1], [0, 0, 0], [1, 0, 1]] ); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/merge_k_sorted_lists_Test.js b/LeetcodeProblemsTests/Algorithms/hard/merge_k_sorted_lists_Test.js similarity index 64% rename from LeetcodeProblemsTests/Algorithms/merge_k_sorted_lists_Test.js rename to LeetcodeProblemsTests/Algorithms/hard/merge_k_sorted_lists_Test.js index 4c563de..ba1051e 100644 --- a/LeetcodeProblemsTests/Algorithms/merge_k_sorted_lists_Test.js +++ b/LeetcodeProblemsTests/Algorithms/hard/merge_k_sorted_lists_Test.js @@ -1,7 +1,7 @@ -const assert = require('assert'); -const ListNodeTestHelper = require('../../UtilsClasses/ListNodeTestHelper'); -var ListNode = require('../../UtilsClasses/ListNode').ListNode; -const mergeKLists = require('../../LeetcodeProblems/Algorithms/merge_k_sorted_lists').mergeKLists; +const assert = require("assert"); +const ListNodeTestHelper = require("../../../UtilsClasses/ListNodeTestHelper"); +var ListNode = require("../../../UtilsClasses/ListNode").ListNode; +const mergeKLists = require("../../../LeetcodeProblems/Algorithms/hard/merge_k_sorted_lists").mergeKLists; function test() { assert.deepEqual(mergeKLists([]), null); diff --git a/LeetcodeProblemsTests/Algorithms/medium/3SumClosest_Test.js b/LeetcodeProblemsTests/Algorithms/medium/3SumClosest_Test.js new file mode 100644 index 0000000..a0f109c --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/3SumClosest_Test.js @@ -0,0 +1,10 @@ +const assert = require("assert"); +const threeSumClosest = + require("../../../LeetcodeProblems/Algorithms/medium/3SumClosest").threeSumClosest; + +var test = function () { + assert.equal(2, threeSumClosest([-1, 2, 1, -4], 1)); + assert.equal(0, threeSumClosest([0, 0, 0], 1)); +}; + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/medium/3Sum_Test.js b/LeetcodeProblemsTests/Algorithms/medium/3Sum_Test.js new file mode 100644 index 0000000..445c40b --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/3Sum_Test.js @@ -0,0 +1,19 @@ +const assert = require("assert"); +const threeSum = require("../../../LeetcodeProblems/Algorithms/medium/3Sum").threeSum; + +var test = function () { + assert.deepEqual(threeSum([]), []); + assert.deepEqual(threeSum([0]), []); + assert.deepEqual(threeSum([0, 0]), []); + assert.deepEqual(threeSum([0, 0, 0]), [[0, 0, 0]]); + assert.deepEqual( + threeSum([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), + [[0, 0, 0]] + ); + assert.deepEqual(threeSum([-1, 0, 1, 2, -1, -4]), [ + [-1, 2, -1], + [0, 1, -1], + ]); +}; + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Add_Two_Numbers_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Add_Two_Numbers_Test.js similarity index 67% rename from LeetcodeProblemsTests/Algorithms/Add_Two_Numbers_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Add_Two_Numbers_Test.js index 82f8168..9675a65 100644 --- a/LeetcodeProblemsTests/Algorithms/Add_Two_Numbers_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Add_Two_Numbers_Test.js @@ -1,7 +1,6 @@ -const assert = require('assert'); -const addTwoNumbers = require('../../LeetcodeProblems/Algorithms/Add_Two_Numbers').addTwoNumbers; -const ListNodeTestHelper = require('../../UtilsClasses/ListNodeTestHelper'); -var ListNode = require('../../UtilsClasses/ListNode').ListNode; +const addTwoNumbers = require("../../../LeetcodeProblems/Algorithms/medium/Add_Two_Numbers").addTwoNumbers; +const ListNodeTestHelper = require("../../../UtilsClasses/ListNodeTestHelper"); +var ListNode = require("../../../UtilsClasses/ListNode").ListNode; function test() { const list1 = ListNode.linkenList([1,2,3,4]); diff --git a/LeetcodeProblemsTests/Algorithms/medium/Best_Time_To_Buy_And_Sell_Stock_II_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Best_Time_To_Buy_And_Sell_Stock_II_Test.js new file mode 100644 index 0000000..7a2561c --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Best_Time_To_Buy_And_Sell_Stock_II_Test.js @@ -0,0 +1,9 @@ +const assert = require("assert"); +const maxProfit = require("../../../LeetcodeProblems/Algorithms/medium/Best_Time_To_Buy_And_Sell_Stock_II").maxProfit; + +function test() { + assert.equal(maxProfit([7,1,5,3,6,4]), 7); + assert.equal(maxProfit([7,1,5,3320,6,4]), 3319); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Clone_Graph_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Clone_Graph_Test.js similarity index 95% rename from LeetcodeProblemsTests/Algorithms/Clone_Graph_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Clone_Graph_Test.js index ea8b26b..928d068 100644 --- a/LeetcodeProblemsTests/Algorithms/Clone_Graph_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Clone_Graph_Test.js @@ -1,5 +1,5 @@ var test = function() { // TODO -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Coin_Change_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Coin_Change_Test.js similarity index 71% rename from LeetcodeProblemsTests/Algorithms/Coin_Change_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Coin_Change_Test.js index 4629e79..9bd9a50 100644 --- a/LeetcodeProblemsTests/Algorithms/Coin_Change_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Coin_Change_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const coinChange = require('../../LeetcodeProblems/Algorithms/Coin_Change').coinChange; +const assert = require("assert"); +const coinChange = require("../../../LeetcodeProblems/Algorithms/medium/Coin_Change").coinChange; function test() { assert.equal(coinChange([], 3), -1); diff --git a/LeetcodeProblemsTests/Algorithms/medium/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal_Test.js new file mode 100644 index 0000000..793d6fd --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal_Test.js @@ -0,0 +1,9 @@ +// const assert = require("assert"); +var buildTree = require("../../../LeetcodeProblems/Algorithms/medium/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal").buildTree; + +function test() { + // TODO + console.log(buildTree([3,9,20,15,7], [9,3,15,20,7])); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/medium/Container_With_Most_Water_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Container_With_Most_Water_Test.js new file mode 100644 index 0000000..7d52f78 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Container_With_Most_Water_Test.js @@ -0,0 +1,10 @@ +const assert = require("assert"); +const maxArea = require("../../../LeetcodeProblems/Algorithms/medium/Container_With_Most_Water").maxArea; + +function test() { + assert.equal(49, maxArea([1,8,6,2,5,4,8,3,7])); + assert.equal(1, maxArea([1,1])); + +} + +module.exports.test = test; \ No newline at end of file diff --git a/LeetcodeProblemsTests/Algorithms/Design_Circular_Deque_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Design_Circular_Deque_Test.js similarity index 74% rename from LeetcodeProblemsTests/Algorithms/Design_Circular_Deque_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Design_Circular_Deque_Test.js index 40f0b0e..5a3ddd2 100644 --- a/LeetcodeProblemsTests/Algorithms/Design_Circular_Deque_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Design_Circular_Deque_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -var MyCircularDeque = require('../../LeetcodeProblems/Algorithms/Design_Circular_Deque').MyCircularDeque; +const assert = require("assert"); +var MyCircularDeque = require("../../../LeetcodeProblems/Algorithms/medium/Design_Circular_Deque").MyCircularDeque; var test = function() { const obj = new MyCircularDeque(3); @@ -12,6 +12,6 @@ var test = function() { assert.equal(obj.deleteLast(), true); assert.equal(obj.insertFront(4), true); assert.equal(obj.getFront(), 4); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Escape_The_Ghosts_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Escape_The_Ghosts_Test.js similarity index 61% rename from LeetcodeProblemsTests/Algorithms/Escape_The_Ghosts_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Escape_The_Ghosts_Test.js index ec0f67d..8ce944c 100644 --- a/LeetcodeProblemsTests/Algorithms/Escape_The_Ghosts_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Escape_The_Ghosts_Test.js @@ -1,6 +1,6 @@ -const assert = require('assert'); -var escapeGhosts = require('../../LeetcodeProblems/Algorithms/Escape_The_Ghosts').escapeGhosts; +const assert = require("assert"); +var escapeGhosts = require("../../../LeetcodeProblems/Algorithms/medium/Escape_The_Ghosts").escapeGhosts; function test() { assert.equal(escapeGhosts([[1, 0], [0, 3]], [0, 1]), true); diff --git a/LeetcodeProblemsTests/Algorithms/Find_Anagrams_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Find_Anagrams_Test.js similarity index 67% rename from LeetcodeProblemsTests/Algorithms/Find_Anagrams_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Find_Anagrams_Test.js index 504e136..13de13a 100644 --- a/LeetcodeProblemsTests/Algorithms/Find_Anagrams_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Find_Anagrams_Test.js @@ -1,6 +1,6 @@ -const assert = require('assert'); -var findAnagrams = require('../../LeetcodeProblems/Algorithms/Find_Anagrams').findAnagrams; +const assert = require("assert"); +var findAnagrams = require("../../../LeetcodeProblems/Algorithms/medium/Find_Anagrams").findAnagrams; function test() { assert.deepEqual([], findAnagrams("AA", "BB")); diff --git a/LeetcodeProblemsTests/Algorithms/Find_Subarrays_With_Equal_Sum_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Find_Subarrays_With_Equal_Sum_Test.js similarity index 55% rename from LeetcodeProblemsTests/Algorithms/Find_Subarrays_With_Equal_Sum_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Find_Subarrays_With_Equal_Sum_Test.js index 09f692e..8a6ad5f 100644 --- a/LeetcodeProblemsTests/Algorithms/Find_Subarrays_With_Equal_Sum_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Find_Subarrays_With_Equal_Sum_Test.js @@ -1,10 +1,10 @@ -const assert = require('assert'); -const findSubarrays = require('../../LeetcodeProblems/Algorithms/Find_Subarrays_With_Equal_Sum').findSubarrays; +const assert = require("assert"); +const findSubarrays = require("../../../LeetcodeProblems/Algorithms/medium/Find_Subarrays_With_Equal_Sum").findSubarrays; var test = function () { assert.equal(findSubarrays([4,2,4]), true); assert.equal(findSubarrays([1,2,3,4,5]), false); assert.equal(findSubarrays([0,0,0]), true); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/medium/Gas_Station_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Gas_Station_Test.js new file mode 100644 index 0000000..ebee7ad --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Gas_Station_Test.js @@ -0,0 +1,11 @@ +const assert = require("assert"); +const canCompleteCircuit = require("../../../LeetcodeProblems/Algorithms/medium/Gas_Station").canCompleteCircuit; + +function test() { + assert.equal(3, canCompleteCircuit([1,2,3,4,5], [3,4,5,1,2])); + assert.equal(-1, canCompleteCircuit([1,2,3,4], [2,3,4,5])); + assert.equal(0, canCompleteCircuit([8,2,3,4], [2,3,4,5])); +} + +module.exports.test = test; + diff --git a/LeetcodeProblemsTests/Algorithms/Generate_Parenthesis_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Generate_Parenthesis_Test.js similarity index 95% rename from LeetcodeProblemsTests/Algorithms/Generate_Parenthesis_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Generate_Parenthesis_Test.js index ea8b26b..928d068 100644 --- a/LeetcodeProblemsTests/Algorithms/Generate_Parenthesis_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Generate_Parenthesis_Test.js @@ -1,5 +1,5 @@ var test = function() { // TODO -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/medium/Group_Anagrams_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Group_Anagrams_Test.js new file mode 100644 index 0000000..1588606 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Group_Anagrams_Test.js @@ -0,0 +1,11 @@ +const assert = require("assert"); +const groupAnagrams = require("../../../LeetcodeProblems/Algorithms/medium/Group_Anagrams").groupAnagrams; + +function test() { + assert.deepEqual( + groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]), + [ [ "eat", "tea", "ate" ], [ "tan", "nat" ], [ "bat" ] ] + ); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/medium/K_Closest_Points_to_Origin_Test.js b/LeetcodeProblemsTests/Algorithms/medium/K_Closest_Points_to_Origin_Test.js new file mode 100644 index 0000000..24a6f0e --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/K_Closest_Points_to_Origin_Test.js @@ -0,0 +1,23 @@ +const assert = require("assert"); +var kClosest = require("../../../LeetcodeProblems/Algorithms/medium/K_Closest_Points_to_Origin").kClosest; + +function test1() { + var points = [[1,3],[-2,2]]; + var output = [[-2,2]]; + assert.deepStrictEqual(kClosest(points,1), output); +} + +function test2() { + var points = [[3,3],[5,-1],[-2,4]]; + var output = [[-2,4],[3,3]]; + + assert.deepStrictEqual(kClosest(points,2).sort, output.sort); +} + +function test() { + test1(); + test2(); +} + +module.exports.test = test; + diff --git a/LeetcodeProblemsTests/Algorithms/Kth_Largest_Element_in_an_Array_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Kth_Largest_Element_in_an_Array_Test.js similarity index 61% rename from LeetcodeProblemsTests/Algorithms/Kth_Largest_Element_in_an_Array_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Kth_Largest_Element_in_an_Array_Test.js index a21900d..94ff0a5 100644 --- a/LeetcodeProblemsTests/Algorithms/Kth_Largest_Element_in_an_Array_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Kth_Largest_Element_in_an_Array_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const findKthLargest = require('../../LeetcodeProblems/Algorithms/Kth_Largest_Element_in_an_Array').findKthLargest; +const assert = require("assert"); +const findKthLargest = require("../../../LeetcodeProblems/Algorithms/medium/Kth_Largest_Element_in_an_Array").findKthLargest; function test() { assert.equal(findKthLargest([3,2,1,5,6,4], 2), 5); diff --git a/LeetcodeProblemsTests/Algorithms/Linked_List_Cycle_II_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Linked_List_Cycle_II_Test.js similarity index 72% rename from LeetcodeProblemsTests/Algorithms/Linked_List_Cycle_II_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Linked_List_Cycle_II_Test.js index 0206e8b..665843d 100644 --- a/LeetcodeProblemsTests/Algorithms/Linked_List_Cycle_II_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Linked_List_Cycle_II_Test.js @@ -1,13 +1,13 @@ -const assert = require('assert'); -var ListNode = require('../../UtilsClasses/ListNode').ListNode; -const detectCycle = require('../../LeetcodeProblems/Algorithms/Linked_List_Cycle_II').detectCycle; +const assert = require("assert"); +var ListNode = require("../../../UtilsClasses/ListNode").ListNode; +const detectCycle = require("../../../LeetcodeProblems/Algorithms/medium/Linked_List_Cycle_II").detectCycle; var test = function() { const cycle = buildCycle(); var list = cycle.list; var nodeCycle = cycle.nodeCycle; assert.equal(detectCycle(list), nodeCycle); -} +}; function buildCycle() { var node1 = ListNode.linkenList([1,2,3,4,5]); diff --git a/LeetcodeProblemsTests/Algorithms/Longest_Palindromic_Substring_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Longest_Palindromic_Substring_Test.js similarity index 68% rename from LeetcodeProblemsTests/Algorithms/Longest_Palindromic_Substring_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Longest_Palindromic_Substring_Test.js index 1b61abc..863a459 100644 --- a/LeetcodeProblemsTests/Algorithms/Longest_Palindromic_Substring_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Longest_Palindromic_Substring_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const longestPalindrome = require('../../LeetcodeProblems/Algorithms/Longest_Palindromic_Substring').longestPalindrome; +const assert = require("assert"); +const longestPalindrome = require("../../../LeetcodeProblems/Algorithms/medium/Longest_Palindromic_Substring").longestPalindrome; function test() { assert.equal(longestPalindrome("pabcdcbte"), "bcdcb"); diff --git a/LeetcodeProblemsTests/Algorithms/Longest_Substring_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Longest_Substring_Test.js similarity index 65% rename from LeetcodeProblemsTests/Algorithms/Longest_Substring_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Longest_Substring_Test.js index 09c073e..1595415 100644 --- a/LeetcodeProblemsTests/Algorithms/Longest_Substring_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Longest_Substring_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const lengthOfLongestSubstring = require('../../LeetcodeProblems/Algorithms/Longest_Substring').lengthOfLongestSubstring; +const assert = require("assert"); +const lengthOfLongestSubstring = require("../../../LeetcodeProblems/Algorithms/medium/Longest_Substring").lengthOfLongestSubstring; function test() { assert.equal(4, lengthOfLongestSubstring("abcdbcd")); diff --git a/LeetcodeProblemsTests/Algorithms/Lowest_Common_Ancestor_of_a_Binary_Tree_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Lowest_Common_Ancestor_of_a_Binary_Tree_Test.js similarity index 68% rename from LeetcodeProblemsTests/Algorithms/Lowest_Common_Ancestor_of_a_Binary_Tree_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Lowest_Common_Ancestor_of_a_Binary_Tree_Test.js index 0ec8727..af6d8ff 100644 --- a/LeetcodeProblemsTests/Algorithms/Lowest_Common_Ancestor_of_a_Binary_Tree_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Lowest_Common_Ancestor_of_a_Binary_Tree_Test.js @@ -1,7 +1,7 @@ -const assert = require('assert'); -var TreeNode = require('../../UtilsClasses/TreeNode').TreeNode; -const lowestCommonAncestor = require('../../LeetcodeProblems/Algorithms/Lowest_Common_Ancestor_of_a_Binary_Tree').lowestCommonAncestor; -const lowestCommonAncestor2 = require('../../LeetcodeProblems/Algorithms/Lowest_Common_Ancestor_of_a_Binary_Tree').lowestCommonAncestor2; +// const assert = require("assert"); +var TreeNode = require("../../../UtilsClasses/TreeNode").TreeNode; +const lowestCommonAncestor = require("../../../LeetcodeProblems/Algorithms/medium/Lowest_Common_Ancestor_of_a_Binary_Tree").lowestCommonAncestor; +const lowestCommonAncestor2 = require("../../../LeetcodeProblems/Algorithms/medium/Lowest_Common_Ancestor_of_a_Binary_Tree").lowestCommonAncestor2; var test = function() { var root = new TreeNode(3); @@ -34,6 +34,6 @@ var test = function() { console.log(lowestCommonAncestor2(root, left, tempRight.right)); console.log(lowestCommonAncestor2(root, left, right)); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Max_Area_Of_Island_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Max_Area_Of_Island_Test.js similarity index 82% rename from LeetcodeProblemsTests/Algorithms/Max_Area_Of_Island_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Max_Area_Of_Island_Test.js index 69bf4e1..28e8f34 100644 --- a/LeetcodeProblemsTests/Algorithms/Max_Area_Of_Island_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Max_Area_Of_Island_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const { maxAreaOfIsland } = require('../../LeetcodeProblems/Algorithms/Max_Area_Of_Island'); +const assert = require("assert"); +const { maxAreaOfIsland } = require("../../../LeetcodeProblems/Algorithms/medium/Max_Area_Of_Island"); function test1() { var matrix = [ @@ -11,7 +11,7 @@ function test1() { [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0] - ] + ]; assert.strictEqual(maxAreaOfIsland(matrix), 6); } @@ -24,7 +24,7 @@ function test2() { [0, 1, 0, 0, 1], [0, 1, 1, 0, 1], [0, 0, 0, 0, 0], - ] + ]; assert.strictEqual(maxAreaOfIsland(matrix), 5); } @@ -37,7 +37,7 @@ function test3() { [0, 1, 1, 1, 1], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], - ] + ]; assert.strictEqual(maxAreaOfIsland(matrix), 11); } @@ -48,4 +48,4 @@ function test() { test3(); } -module.exports.test = test +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Max_Consecutive_Ones_III_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Max_Consecutive_Ones_III_Test.js similarity index 67% rename from LeetcodeProblemsTests/Algorithms/Max_Consecutive_Ones_III_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Max_Consecutive_Ones_III_Test.js index 96b6986..3314c85 100644 --- a/LeetcodeProblemsTests/Algorithms/Max_Consecutive_Ones_III_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Max_Consecutive_Ones_III_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const longestOnes = require('../../LeetcodeProblems/Algorithms/Max_Consecutive_Ones_III').longestOnes; +const assert = require("assert"); +const longestOnes = require("../../../LeetcodeProblems/Algorithms/medium/Max_Consecutive_Ones_III").longestOnes; function test() { assert.equal(1, longestOnes([1], 1)); diff --git a/LeetcodeProblemsTests/Algorithms/Maximal_Square_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Maximal_Square_Test.js similarity index 69% rename from LeetcodeProblemsTests/Algorithms/Maximal_Square_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Maximal_Square_Test.js index 2aa2a6e..b29b21b 100644 --- a/LeetcodeProblemsTests/Algorithms/Maximal_Square_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Maximal_Square_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const maximalSquare = require('../../LeetcodeProblems/Algorithms/Maximal_Square').maximalSquare; +const assert = require("assert"); +const maximalSquare = require("../../../LeetcodeProblems/Algorithms/medium/Maximal_Square").maximalSquare; function test() { assert.equal(maximalSquare([["1","0"]]), 1); diff --git a/LeetcodeProblemsTests/Algorithms/medium/Maximise_Hour_Glass_Sum_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Maximise_Hour_Glass_Sum_Test.js new file mode 100644 index 0000000..f3f2cf2 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Maximise_Hour_Glass_Sum_Test.js @@ -0,0 +1,9 @@ +const assert = require("assert"); +const maxSum = require("../../../LeetcodeProblems/Algorithms/medium/Maximise_Hour_Glass_Sum").maxSum; + +function test() { + assert.equal(maxSum([[6,2,1,3],[4,2,1,5],[9,2,8,7],[4,1,2,9]]), 30); + assert.equal(maxSum([[1,2,3],[4,5,6],[7,8,9]]), 35); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/medium/Minimize_Maximum_Pair_Sum_In_Array_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Minimize_Maximum_Pair_Sum_In_Array_Test.js new file mode 100644 index 0000000..1842614 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Minimize_Maximum_Pair_Sum_In_Array_Test.js @@ -0,0 +1,10 @@ +const assert = require("assert"); +const minPairSum = require("../../../LeetcodeProblems/Algorithms/medium/Minimize_Maximum_Pair_Sum_In_Array").minPairSum; + +var test = function () { + assert.equal(minPairSum([3,5,2,3]), 7); + assert.equal(minPairSum([3,5,4,2,4,6]), 8); + assert.equal(minPairSum([1,1,1,1]), 2); +}; + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Minimum_Add_To_Make_Parentheses_Valid_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Minimum_Add_To_Make_Parentheses_Valid_Test.js similarity index 67% rename from LeetcodeProblemsTests/Algorithms/Minimum_Add_To_Make_Parentheses_Valid_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Minimum_Add_To_Make_Parentheses_Valid_Test.js index b175736..9c75aa4 100644 --- a/LeetcodeProblemsTests/Algorithms/Minimum_Add_To_Make_Parentheses_Valid_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Minimum_Add_To_Make_Parentheses_Valid_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const minAddToMakeValid = require('../../LeetcodeProblems/Algorithms/Minimum_Add_To_Make_Parentheses_Valid').minAddToMakeValid; +const assert = require("assert"); +const minAddToMakeValid = require("../../../LeetcodeProblems/Algorithms/medium/Minimum_Add_To_Make_Parentheses_Valid").minAddToMakeValid; var test = function() { assert.strictEqual(1, minAddToMakeValid("()(")); diff --git a/LeetcodeProblemsTests/Algorithms/Minimum_Size_Subarray_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Minimum_Size_Subarray_Test.js similarity index 75% rename from LeetcodeProblemsTests/Algorithms/Minimum_Size_Subarray_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Minimum_Size_Subarray_Test.js index 7d2c4d1..c5f8628 100644 --- a/LeetcodeProblemsTests/Algorithms/Minimum_Size_Subarray_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Minimum_Size_Subarray_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const minSubArrayLength = require('../../LeetcodeProblems/Algorithms/Minimum_Size_Subarray').minSubArrayLength; +const assert = require("assert"); +const minSubArrayLength = require("../../../LeetcodeProblems/Algorithms/medium/Minimum_Size_Subarray").minSubArrayLength; function test() { assert.equal(0, minSubArrayLength(10, [])); diff --git a/LeetcodeProblemsTests/Algorithms/medium/Next_Permutation_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Next_Permutation_Test.js new file mode 100644 index 0000000..f892f38 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Next_Permutation_Test.js @@ -0,0 +1,16 @@ +const assert = require("assert"); +const nextPermutation = require("../../../LeetcodeProblems/Algorithms/medium/Next_Permutation").nextPermutation; + +function test() { + let test1 = [1,2,3]; + let test2 = [3,2,1]; + let test3 = [1,1,5]; + nextPermutation(test1); + nextPermutation(test2); + nextPermutation(test3); + assert.deepEqual(test1, [1,3,2]); + assert.deepEqual(test2, [1,2,3]); + assert.deepEqual(test3, [1,5,1]); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Number_of_Islands_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Number_of_Islands_Test.js similarity index 67% rename from LeetcodeProblemsTests/Algorithms/Number_of_Islands_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Number_of_Islands_Test.js index cd07f85..f3ef5e6 100644 --- a/LeetcodeProblemsTests/Algorithms/Number_of_Islands_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Number_of_Islands_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const numIslands = require('../../LeetcodeProblems/Algorithms/Number_of_Islands').numIslands; +const assert = require("assert"); +const numIslands = require("../../../LeetcodeProblems/Algorithms/medium/Number_of_Islands").numIslands; function test() { assert.equal(numIslands([[1]]), 1); diff --git a/LeetcodeProblemsTests/Algorithms/medium/Permutations_II_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Permutations_II_Test.js new file mode 100644 index 0000000..20d1702 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Permutations_II_Test.js @@ -0,0 +1,30 @@ +const assert = require("assert"); +const permuteUnique = require("../../../LeetcodeProblems/Algorithms/medium/Permutations_II").permuteUnique; + +function test() { + assert.deepEqual( + permuteUnique([1,1,2]), + [ [ "1", "1", "2" ], [ "1", "2", "1" ], [ "2", "1", "1" ] ] + ); + assert.deepEqual( + permuteUnique([1,3,2,1]), + [ + [ "1", "1", "2", "3" ], + [ "1", "1", "3", "2" ], + [ "1", "2", "1", "3" ], + [ "1", "2", "3", "1" ], + [ "1", "3", "1", "2" ], + [ "1", "3", "2", "1" ], + [ "2", "1", "1", "3" ], + [ "2", "1", "3", "1" ], + [ "2", "3", "1", "1" ], + [ "3", "1", "1", "2" ], + [ "3", "1", "2", "1" ], + [ "3", "2", "1", "1" ] + ] + ); + assert.deepEqual(permuteUnique([]), [ [] ]); + assert.deepEqual(permuteUnique([1,1]), [ [ "1", "1" ] ]); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Permutations_In_String_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Permutations_In_String_Test.js similarity index 64% rename from LeetcodeProblemsTests/Algorithms/Permutations_In_String_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Permutations_In_String_Test.js index 33b4dbf..975bda8 100644 --- a/LeetcodeProblemsTests/Algorithms/Permutations_In_String_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Permutations_In_String_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const checkInclusion = require('../../LeetcodeProblems/Algorithms/Permutations_In_String').checkInclusion; +const assert = require("assert"); +const checkInclusion = require("../../../LeetcodeProblems/Algorithms/medium/Permutations_In_String").checkInclusion; function test() { assert.equal(false, checkInclusion("abc", "ab")); diff --git a/LeetcodeProblemsTests/Algorithms/Permutations_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Permutations_Test.js similarity index 70% rename from LeetcodeProblemsTests/Algorithms/Permutations_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Permutations_Test.js index 8fe85e0..1473732 100644 --- a/LeetcodeProblemsTests/Algorithms/Permutations_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Permutations_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const permute = require('../../LeetcodeProblems/Algorithms/Permutations').permute; +const assert = require("assert"); +const permute = require("../../../LeetcodeProblems/Algorithms/medium/Permutations").permute; function test() { assert.deepEqual(permute([]), [ [] ]); diff --git a/LeetcodeProblemsTests/Algorithms/Permutations_With_Duplicates_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Permutations_With_Duplicates_Test.js similarity index 68% rename from LeetcodeProblemsTests/Algorithms/Permutations_With_Duplicates_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Permutations_With_Duplicates_Test.js index ecbdf12..e355512 100644 --- a/LeetcodeProblemsTests/Algorithms/Permutations_With_Duplicates_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Permutations_With_Duplicates_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const subsetWithoutDuplicates = require('../../LeetcodeProblems/Algorithms/Permutations_With_Duplicates').subsetWithoutDuplicates; +const assert = require("assert"); +const subsetWithoutDuplicates = require("../../../LeetcodeProblems/Algorithms/medium/Permutations_With_Duplicates").subsetWithoutDuplicates; var test = function() { assert.deepEqual( @@ -19,6 +19,6 @@ var test = function() { [ 3, 2, 1, 1 ] ] ); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Permutations_Without_Duplicates_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Permutations_Without_Duplicates_Test.js similarity index 57% rename from LeetcodeProblemsTests/Algorithms/Permutations_Without_Duplicates_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Permutations_Without_Duplicates_Test.js index 60169e9..a22e4e7 100644 --- a/LeetcodeProblemsTests/Algorithms/Permutations_Without_Duplicates_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Permutations_Without_Duplicates_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const subsetWithoutDuplicates = require('../../LeetcodeProblems/Algorithms/Permutations_Without_Duplicates').subsetWithoutDuplicates; +const assert = require("assert"); +const subsetWithoutDuplicates = require("../../../LeetcodeProblems/Algorithms/medium/Permutations_Without_Duplicates").subsetWithoutDuplicates; var test = function() { assert.deepEqual( @@ -13,6 +13,6 @@ var test = function() { [ 3, 2, 1 ] ] ); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/medium/Restore_IP_Addresses_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Restore_IP_Addresses_Test.js new file mode 100644 index 0000000..17e2521 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Restore_IP_Addresses_Test.js @@ -0,0 +1,9 @@ +const assert = require("assert"); +const restoreIpAddresses = require("../../../LeetcodeProblems/Algorithms/medium/Restore_IP_Addresses").restoreIpAddresses; + +var test = function() { + assert.deepEqual(restoreIpAddresses("010010"), [ "0.10.0.10", "0.100.1.0"]); + assert.deepEqual(restoreIpAddresses("25525511135"), [ "255.255.11.135", "255.255.111.35" ]); +}; + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/medium/Reverse_Integer_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Reverse_Integer_Test.js new file mode 100644 index 0000000..627d72a --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Reverse_Integer_Test.js @@ -0,0 +1,11 @@ +const assert = require("assert"); +const reverseInteger = require("../../../LeetcodeProblems/Algorithms/medium/Reverse_Integer").reverseInteger; + +var test = function() { + assert.equal(reverseInteger(123), 321); + assert.equal(reverseInteger(-123), -321); + assert.equal(reverseInteger(120), 21); +}; + + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/medium/SearchIng_Rotated_Sorted_Array_Test.js b/LeetcodeProblemsTests/Algorithms/medium/SearchIng_Rotated_Sorted_Array_Test.js new file mode 100644 index 0000000..47bf614 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/SearchIng_Rotated_Sorted_Array_Test.js @@ -0,0 +1,8 @@ +const assert = require("assert"); +const search = require("../../../LeetcodeProblems/Algorithms/medium/SearchIng_Rotated_Sorted_Array").search; + +var test = function() { + assert.equal(search([4,5,6,7,0,1,2], 5), 1); +}; + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Search_a_2D_Matrix_II_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Search_a_2D_Matrix_II_Test.js similarity index 68% rename from LeetcodeProblemsTests/Algorithms/Search_a_2D_Matrix_II_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Search_a_2D_Matrix_II_Test.js index f7b27f8..5dff4a5 100644 --- a/LeetcodeProblemsTests/Algorithms/Search_a_2D_Matrix_II_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Search_a_2D_Matrix_II_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const searchMatrix = require('../../LeetcodeProblems/Algorithms/Search_a_2D_Matrix_II').searchMatrix; +const assert = require("assert"); +const searchMatrix = require("../../../LeetcodeProblems/Algorithms/medium/Search_a_2D_Matrix_II").searchMatrix; const matrix1 = [ [1,4,7, 11,15], @@ -13,6 +13,6 @@ var test = function() { assert.equal(searchMatrix(matrix1, 5), true); assert.equal(searchMatrix(matrix1, 0), false); assert.equal(searchMatrix(matrix1, 15), true); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Search_a_2D_Matrix_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Search_a_2D_Matrix_Test.js similarity index 67% rename from LeetcodeProblemsTests/Algorithms/Search_a_2D_Matrix_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Search_a_2D_Matrix_Test.js index f1e2856..f07b9c0 100644 --- a/LeetcodeProblemsTests/Algorithms/Search_a_2D_Matrix_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Search_a_2D_Matrix_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const searchMatrix = require('../../LeetcodeProblems/Algorithms/Search_a_2D_Matrix').searchMatrix; +const assert = require("assert"); +const searchMatrix = require("../../../LeetcodeProblems/Algorithms/medium/Search_a_2D_Matrix").searchMatrix; var test = function() { assert.equal(searchMatrix([], 0), false); @@ -7,6 +7,6 @@ var test = function() { assert.equal(searchMatrix([[1], [3]], 1), true); const matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]]; assert.equal(searchMatrix(matrix, 3), true); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Simplify_Path_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Simplify_Path_Test.js similarity index 60% rename from LeetcodeProblemsTests/Algorithms/Simplify_Path_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Simplify_Path_Test.js index d5d27cd..0b0c1ce 100644 --- a/LeetcodeProblemsTests/Algorithms/Simplify_Path_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Simplify_Path_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const simplifyPath = require('../../LeetcodeProblems/Algorithms/Simplify_Path').simplifyPath; +const assert = require("assert"); +const simplifyPath = require("../../../LeetcodeProblems/Algorithms/medium/Simplify_Path").simplifyPath; var test = function() { assert.equal(simplifyPath("/../c"), "/c"); @@ -7,7 +7,7 @@ var test = function() { assert.equal(simplifyPath("/home/"), "/home"); // => "/home" assert.equal(simplifyPath("/a/./b/../../c/"), "/c"); // => "/c" assert.equal(simplifyPath("/a/../../b/../c//.//"), "/c"); // => "/c" - assert.equal(simplifyPath("/a//b////c/d//././/.."), "/a/b/c") // => "/a/b/c" -} + assert.equal(simplifyPath("/a//b////c/d//././/.."), "/a/b/c"); // => "/a/b/c" +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/medium/Spiral_Matrix_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Spiral_Matrix_Test.js new file mode 100644 index 0000000..8002ee5 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Spiral_Matrix_Test.js @@ -0,0 +1,17 @@ +const assert = require("assert"); +const spiralOrder = require("../../../LeetcodeProblems/Algorithms/medium/Spiral_Matrix").spiralOrder; + +var test = function() { + const matrix = [ + [ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ] + ]; + + assert.deepEqual( + spiralOrder(matrix), + [1, 2, 3, 6, 9, 8, 7, 4, 5] + ); +}; + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Subarray_Sum_Equals_K_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Subarray_Sum_Equals_K_Test.js similarity index 63% rename from LeetcodeProblemsTests/Algorithms/Subarray_Sum_Equals_K_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Subarray_Sum_Equals_K_Test.js index b7697a6..8c85c57 100644 --- a/LeetcodeProblemsTests/Algorithms/Subarray_Sum_Equals_K_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Subarray_Sum_Equals_K_Test.js @@ -1,11 +1,11 @@ -const assert = require('assert'); -const subarraySum = require('../../LeetcodeProblems/Algorithms/Subarray_Sum_Equals_K').subarraySum; +const assert = require("assert"); +const subarraySum = require("../../../LeetcodeProblems/Algorithms/medium/Subarray_Sum_Equals_K").subarraySum; var test = function() { assert.strictEqual(subarraySum([1,1,1], 2), 2); assert.strictEqual(subarraySum([1], 0), 0); assert.strictEqual(subarraySum([0], 0), 1); assert.strictEqual(subarraySum([0,0,0,0,0], 0), 15); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Subsets_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Subsets_Test.js similarity index 72% rename from LeetcodeProblemsTests/Algorithms/Subsets_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Subsets_Test.js index 63bad19..de1a1b1 100644 --- a/LeetcodeProblemsTests/Algorithms/Subsets_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Subsets_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const subsets = require('../../LeetcodeProblems/Algorithms/Subsets').subsets; +const assert = require("assert"); +const subsets = require("../../../LeetcodeProblems/Algorithms/medium/Subsets").subsets; function test() { assert.deepEqual(subsets([]), [[]]); diff --git a/LeetcodeProblemsTests/Algorithms/Swap_Nodes_In_Pairs_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Swap_Nodes_In_Pairs_Test.js similarity index 55% rename from LeetcodeProblemsTests/Algorithms/Swap_Nodes_In_Pairs_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Swap_Nodes_In_Pairs_Test.js index 9a8e8f9..5a34ed4 100644 --- a/LeetcodeProblemsTests/Algorithms/Swap_Nodes_In_Pairs_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Swap_Nodes_In_Pairs_Test.js @@ -1,13 +1,13 @@ -const assert = require('assert'); -const ListNode = require('../../UtilsClasses/ListNode').ListNode; -const ListNodeTestHelper = require('../../UtilsClasses/ListNodeTestHelper'); -const swapPairs = require('../../LeetcodeProblems/Algorithms/Swap_Nodes_In_Pairs').swapPairs; +// const assert = require("assert"); +const ListNode = require("../../../UtilsClasses/ListNode").ListNode; +const ListNodeTestHelper = require("../../../UtilsClasses/ListNodeTestHelper"); +const swapPairs = require("../../../LeetcodeProblems/Algorithms/medium/Swap_Nodes_In_Pairs").swapPairs; var test = function () { ListNodeTestHelper.assertList(swapPairs(ListNode.linkenList([1,2,3,4])), [2,1,4,3]); ListNodeTestHelper.assertList(swapPairs(ListNode.linkenList([])), []); ListNodeTestHelper.assertList(swapPairs(ListNode.linkenList([1])), [1]); ListNodeTestHelper.assertList(swapPairs(ListNode.linkenList([1,2])), [2, 1]); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/medium/Time_Needed_Rearrange_Binary_String_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Time_Needed_Rearrange_Binary_String_Test.js new file mode 100644 index 0000000..ba01f9c --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Time_Needed_Rearrange_Binary_String_Test.js @@ -0,0 +1,9 @@ +const assert = require("assert"); +const secondsToRemoveOccurrences = require("../../../LeetcodeProblems/Algorithms/medium/Time_Needed_Rearrange_Binary_String").secondsToRemoveOccurrences; + +function test() { + assert.equal(secondsToRemoveOccurrences("0110101"), 4); + assert.equal(secondsToRemoveOccurrences("11100"), 0); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/medium/Top_K_Frequent_Elements_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Top_K_Frequent_Elements_Test.js new file mode 100644 index 0000000..6ccb077 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Top_K_Frequent_Elements_Test.js @@ -0,0 +1,10 @@ +const assert = require("assert"); +const topKFrequent = require("../../../LeetcodeProblems/Algorithms/medium/Top_K_Frequent_Elements").topKFrequent; + +var test = function () { + assert.deepEqual(topKFrequent([1,1,1,2,2,3], 2).sort(), [1,2]); + assert.deepEqual(topKFrequent([7,8,9,8,9,8], 2).sort(), [8,9]); + assert.deepEqual(topKFrequent([1,1,1,1], 1).sort(), [1]); +}; + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Unique_Binary_Search_Trees_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Unique_Binary_Search_Trees_Test.js similarity index 58% rename from LeetcodeProblemsTests/Algorithms/Unique_Binary_Search_Trees_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Unique_Binary_Search_Trees_Test.js index 9e66ece..96f28e2 100644 --- a/LeetcodeProblemsTests/Algorithms/Unique_Binary_Search_Trees_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Unique_Binary_Search_Trees_Test.js @@ -1,7 +1,7 @@ -const assert = require('assert'); -const numTrees1 = require('../../LeetcodeProblems/Algorithms/Unique_Binary_Search_Trees').numTrees1; -const numTrees2 = require('../../LeetcodeProblems/Algorithms/Unique_Binary_Search_Trees').numTrees2; -const numTrees3 = require('../../LeetcodeProblems/Algorithms/Unique_Binary_Search_Trees').numTrees3; +const assert = require("assert"); +const numTrees1 = require("../../../LeetcodeProblems/Algorithms/medium/Unique_Binary_Search_Trees").numTrees1; +const numTrees2 = require("../../../LeetcodeProblems/Algorithms/medium/Unique_Binary_Search_Trees").numTrees2; +const numTrees3 = require("../../../LeetcodeProblems/Algorithms/medium/Unique_Binary_Search_Trees").numTrees3; var test = function () { assert.strictEqual(numTrees1(1), 1); @@ -18,6 +18,6 @@ var test = function () { assert.strictEqual(numTrees3(2), 2); assert.strictEqual(numTrees3(3), 5); assert.strictEqual(numTrees3(5), 42); -} +}; module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/medium/Unique_Paths_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Unique_Paths_Test.js new file mode 100644 index 0000000..9330218 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/medium/Unique_Paths_Test.js @@ -0,0 +1,17 @@ +const assert = require("assert"); +const uniquePaths1 = require("../../../LeetcodeProblems/Algorithms/medium/Unique_Paths").uniquePaths1; +const uniquePaths2 = require("../../../LeetcodeProblems/Algorithms/medium/Unique_Paths").uniquePaths2; +const uniquePaths3 = require("../../../LeetcodeProblems/Algorithms/medium/Unique_Paths").uniquePaths3; + +var test = function() { + assert.strictEqual(uniquePaths1(10,4), 220); + assert.strictEqual(uniquePaths1(3,2), 3); + + assert.strictEqual(uniquePaths2(10,4), 220); + assert.strictEqual(uniquePaths2(3,2), 3); + + assert.strictEqual(uniquePaths3(10,4), 220); + assert.strictEqual(uniquePaths3(3,2), 3); +}; + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Algorithms/Verify_Preorder_Serialization_of_a_Binary_Tree_Test.js b/LeetcodeProblemsTests/Algorithms/medium/Verify_Preorder_Serialization_of_a_Binary_Tree_Test.js similarity index 70% rename from LeetcodeProblemsTests/Algorithms/Verify_Preorder_Serialization_of_a_Binary_Tree_Test.js rename to LeetcodeProblemsTests/Algorithms/medium/Verify_Preorder_Serialization_of_a_Binary_Tree_Test.js index 3dd59ef..9bab778 100644 --- a/LeetcodeProblemsTests/Algorithms/Verify_Preorder_Serialization_of_a_Binary_Tree_Test.js +++ b/LeetcodeProblemsTests/Algorithms/medium/Verify_Preorder_Serialization_of_a_Binary_Tree_Test.js @@ -1,5 +1,5 @@ -const assert = require('assert'); -const isValidSerialization = require('../../LeetcodeProblems/Algorithms/Verify_Preorder_Serialization_of_a_Binary_Tree').isValidSerialization; +const assert = require("assert"); +const isValidSerialization = require("../../../LeetcodeProblems/Algorithms/medium/Verify_Preorder_Serialization_of_a_Binary_Tree").isValidSerialization; var test = function() { assert.strictEqual(isValidSerialization(""), true); diff --git a/Maximal_square.js b/Maximal_square.js new file mode 100644 index 0000000..66da8c8 --- /dev/null +++ b/Maximal_square.js @@ -0,0 +1,56 @@ +/* +https://leetcode.com/problems/maximal-square +Maximal Area of Square + +Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. + +Example 1 Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] +Output: 4 + + +Example 2 Input: matrix = [["0","1"],["1","0"]] +Output: 1 + + +Example 3 Input: matrix = [["0"]] +Output: 0 + + +*/ + +/** + * @param {character[][]} matrix + * @return {number} + */ +var maximalSquare = function(matrix) { + var m = matrix.length; + var n = (matrix[0] || []).length; + var dp = Array(m).fill(0).map(() => Array(n)); + var max = 0; + + for (var k = 0; k < m; k++) { + dp[k][0] = matrix[k][0] === "1" ? 1 : 0; + max = Math.max(max, dp[k][0]); + } + + for (var p = 0; p < n; p++) { + dp[0][p] = matrix[0][p] === "1" ? 1 : 0; + max = Math.max(max, dp[0][p]); + } + + for (var i = 1; i < m; i++) { + for (var j = 1; j < n; j++) { + if (matrix[i][j] === "1") { + dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1; + max = Math.max(max, dp[i][j]); + } else { + dp[i][j] = 0; + } + } + } + + return max * max; + +}; + +module.exports.maximalSquare = maximalSquare; \ No newline at end of file diff --git a/Maximal_square_Test.js b/Maximal_square_Test.js new file mode 100644 index 0000000..e5436c5 --- /dev/null +++ b/Maximal_square_Test.js @@ -0,0 +1,38 @@ +const assert = require("assert"); +const {Maximalsquare } = require("../LeetcodeProblems/Maximal_square"); + +function test1() { + var matrix = [ + [1, 0, 1, 0, 0], + [1, 0, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 0, 0, 1, 0], + ]; + + assert.strictEqual(Maximalsquare(matrix), 4); +} + +function test2() { + var matrix = [ + [0, 1], + [1,0] + ]; + + assert.strictEqual(Maximalsquare(matrix), 1); +} + +function test3(){ + var matrix = [ + [0] + ]; + + assert.strictEqual(Maximalsquare(matrix), 0); +} + +function test() { + test1(); + test2(); + test3(); +} + +module.exports.test = test; diff --git a/README.md b/README.md index a46600f..01307b7 100644 --- a/README.md +++ b/README.md @@ -6,82 +6,97 @@ Solutions of algorithm problems using Javascript. https://ignacio-chiazzo.githu The solutions are located under `/LeetcodeProblems`. Each problem has a test file located under `/LeetcodeProblemsTest`. ### Run Tests -To run all the test run `node Test.js` in the console. -To run a specific problem in your console run `node ` (e.g. `node LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree.js`). +**Unit tests:** To run all the test run `node Test.js` in the console. To run a specific problem in your console run `node Test.js ` (e.g. `node Test.js ./LeetcodeProblemsTests/Algorithms/easy/2Sum_Test.js`). + +**Linter:** This repository uses [`es-lint`](https://eslint.org/docs/latest/user-guide/command-line-interface). To run all the tests you would need to install the packages by running `npm install` followed by `npx eslint LeetcodeProblems LeetcodeProblemsTests` which will run the eslint in all problems and tests. You can also use the [flag `--fix`](https://eslint.org/docs/latest/user-guide/command-line-interface#fixing-problems) which will automatically fix some of the errors. ### Leetcode Problems -| Name | Level | Link | -| - | - | - | -| [Edit Distance ](/LeetcodeProblems/Algorithms/Edit_Distance.js) | Hard | https://leetcode.com/problems/edit-distance/ | -| [Remove Invalid Parentheses ](/LeetcodeProblems/Algorithms/Remove_Invalid_Parentheses.js) | Hard | https://leetcode.com/problems/remove-invalid-parentheses/ | -| [Longest Consecutive Sequence ](/LeetcodeProblems/Algorithms/Longest_Consecutive_Sequence.js) | Hard | https://leetcode.com/problems/longest-consecutive-sequence/ | -| [Minimum Window Substring ](/LeetcodeProblems/Algorithms/Minimum_Window_Substring.js) | Hard | https://leetcode.com/problems/minimum-window-substring/ | -| [Regular Expression Matching ](/LeetcodeProblems/Algorithms/Regular_Expression_Matching.js) | Hard | https://leetcode.com/problems/regular-expression-matching/ | -| [NQueens ](/LeetcodeProblems/Algorithms/NQueens.js) | Hard | https://leetcode.com/problems/n-queens/ | -| [merge k sorted lists ](/LeetcodeProblems/Algorithms/merge_k_sorted_lists.js) | Hard | https://leetcode.com/problems/merge-k-sorted-lists/ | -| [Set Matrix Zeroes](/LeetcodeProblems/Algorithms/Set_Matrix_Zeroes.js) | Hard | https://leetcode.com/problems/set-matrix-zeroes/ | -| [Subarray Sum Equals K ](/LeetcodeProblems/Algorithms/Subarray_Sum_Equals_K.js) | Medium | https://leetcode.com/problems/subarray-sum-equals-k/ | -| [3Sum Closest](/LeetcodeProblems/Algorithms/3SumClosest.js) | Medium | https://leetcode.com/problems/3sum-closest/ | -| [3Sum ](/LeetcodeProblems/Algorithms/3Sum.js) | Medium | https://leetcode.com/problems/3sum/ | -| [NumberOfIslands ](/LeetcodeProblems/Algorithms/Number_of_Islands.js) | Medium | https://leetcode.com/problems/number-of-islands/ | -| [Swap Nodes in Pairs](/LeetcodeProblems/Algorithms/Swap_Nodes_in_Pairs.js) | Medium | https://leetcode.com/problems/swap-nodes-in-pairs/ | -| [Add Two Numbers ](/LeetcodeProblems/Algorithms/Add_Two_Numbers.js) | Medium | https://leetcode.com/problems/add-two-numbers/ | -| [Clone Graph ](/LeetcodeProblems/Algorithms/Clone_Graph.js) | Medium | https://leetcode.com/problems/clone-graph/ | -| [Coin Change ](/LeetcodeProblems/Algorithms/Coin_Change.js) | Medium | https://leetcode.com/problems/coin-change/ | -| [Container With Most Water](/LeetcodeProblems/Algorithms/Container_With_Most_Water.js) | Medium | https://leetcode.com/problems/container-with-most-water/ | -| [Design Circular Deque ](/LeetcodeProblems/Algorithms/Design_Circular_Deque.js) | Medium | https://leetcode.com/problems/design-circular-deque/ -| [Escape The Ghosts](/LeetcodeProblems/Algorithms/Escape_The_Ghosts.js) | Medium | https://leetcode.com/problems/escape-the-ghosts/ | -| [Find All Anagrams in a String](/LeetcodeProblems/Algorithms/Find_Anagrams.js) | Medium | https://leetcode.com/problems/find-all-anagrams-in-a-string/ | -| [Generate Parenthesis ](/LeetcodeProblems/Algorithms/Generate_Parenthesis.js) | Medium | https://leetcode.com/problems/generate-parentheses | -| [Group Anagrams ](/LeetcodeProblems/Algorithms/Group_Anagrams.js) | Medium | https://leetcode.com/problems/group-anagrams/ -| [Kth Largest Element in an Array ](/LeetcodeProblems/Algorithms/Kth_Largest_Element_in_an_Array.js) | Medium | https://leetcode.com/problems/kth-largest-element-in-an-array/ | -| [Linked List Cycle II ](/LeetcodeProblems/Algorithms/Linked_List_Cycle_II.js) | Medium | https://leetcode.com/problems/linked-list-cycle-ii/ | -| [Longest Palindromic Substring ](/LeetcodeProblems/Algorithms/Longest_Palindromic_Substring.js) | Medium | https://leetcode.com/problems/longest-palindromic-substring/| -| [Longest Substring Without Reapeating Characters](/LeetcodeProblems/Algorithms/Longest_Substring.js) | Medium | https://leetcode.com/problems/longest-substring-without-repeating-characters| -| [Max Area Of Island ](/LeetcodeProblems/Algorithms/Max_Area_Of_Island.js) | Medium | https://leetcode.com/problems/max-area-of-island/ | -| [Max Consecutive Ones III ](/LeetcodeProblems/Algorithms/Max_Consecutive_Ones_III.js) | Medium | https://leetcode.com/problems/max-consecutive-ones-iii | -| [Maximal Square ](/LeetcodeProblems/Algorithms/Maximal_Square.js) | Medium | https://leetcode.com/problems/maximal-square/ | -| [Minimum Add to Make Parentheses Valid ](/LeetcodeProblems/Algorithms/Minimum_Add_To_Make_Parentheses_Valid.js) | Medium | https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/ | -| [Minimum Size Subarray](/LeetcodeProblems/Algorithms/Minimum_Size_Subarray.js) | Medium | https://leetcode.com/problems/minimum-size-subarray-sum | -| [Permutations ](/LeetcodeProblems/Algorithms/Permutations.js) | Medium | https://leetcode.com/problems/permutations/ | -| [Permutations II ](/LeetcodeProblems/Algorithms/Permutations_II.js) | Medium | https://leetcode.com/problems/permutations-ii/ | -| [Permutation in String](/LeetcodeProblems/Algorithms/Permutations_In_String.js) | Medium | https://leetcode.com/problems/permutation-in-string/ | -| [Permutations Without Duplicates ](/LeetcodeProblems/Algorithms/Permutations_Without_Duplicates.js) | Medium | https://leetcode.com/problems/permutations/ | -| [Restore IP Addresses ](/LeetcodeProblems/Algorithms/Restore_IP_Addresses.js) | Medium | https://leetcode.com/problems/restore-ip-addresses/ | -| [SearchIng Rotated Sorted Array ](/LeetcodeProblems/Algorithms/SearchIng_Rotated_Sorted_Array.js) | Medium | https://leetcode.com/problems/search-in-rotated-sorted-array/ | -| [Search a 2D Matrix ](/LeetcodeProblems/Algorithms/Search_a_2D_Matrix.js) | Medium | https://leetcode.com/problems/search-a-2d-matrix/ | -| [Search a 2D Matrix II ](/LeetcodeProblems/Algorithms/Search_a_2D_Matrix_II.js) | Medium | https://leetcode.com/problems/search-a-2d-matrix/ | -| [Simplify Path ](/LeetcodeProblems/Algorithms/Simplify_Path.js) | Medium | https://leetcode.com/problems/simplify-path/ | -| [Spiral Matrix ](/LeetcodeProblems/Algorithms/Spiral_Matrix.js) | Medium | https://leetcode.com/problems/spiral-matrix/ | -| [Subsets ](/LeetcodeProblems/Algorithms/Subsets.js) | Medium | https://leetcode.com/problems/subsets/ | -| [Unique Binary Search Trees ](/LeetcodeProblems/Algorithms/Unique_Binary_Search_Trees.js) | Medium | https://leetcode.com/problems/unique-binary-search-trees/ | -| [Unique Paths ](/LeetcodeProblems/Algorithms/Unique_Paths.js) | Medium | https://leetcode.com/problems/unique-paths/ | -| [Verify Preorder Serialization of a Binary Tree ](/LeetcodeProblems/Algorithms/Verify_Preorder_Serialization_of_a_Binary_Tree.js) | Medium | https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ | -| [Construct Binary Tree from Preorder and Inorder Traversal ](/LeetcodeProblems/Algorithms/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js) | Medium | https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ | -| [Lowest Common Ancestor of a Binary Tree ](/LeetcodeProblems/Algorithms/Lowest_Common_Ancestor_of_a_Binary_Tree.js) | Medium | https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ | -| [Maximum Sum of an Hourglass](/LeetcodeProblems/Algorithms/Maximise_Hour_Glass_Sum.js) | Medium | https://leetcode.com/problems/maximum-sum-of-an-hourglass/ | -| [Time Needed to Rearrange a Binary String](/LeetcodeProblems/Algorithms/Time_Needed_Rearrange_Binary_String.js)| Medium | https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/ | -| [Find Subarrays With Equal Sum ](/LeetcodeProblems/Algorithms/Find_Subarrays_With_Equal_Sums.js) | Medium | https://leetcode.com/problems/find-subarrays-with-equal-sum/ | -| [Flood Fill ](/LeetcodeProblems/Algorithms/Flood_Fill.js) | Easy | https://leetcode.com/problems/flood-fill/ | -| [Implement stack using queues ](/LeetcodeProblems/Algorithms/Implement_stack_using_queues.js) | Easy | https://leetcode.com/problems/implement-stack-using-queues/ | -| [Number of Segments in a String ](/LeetcodeProblems/Algorithms/Number_of_Segments_in_a_String.js) | Easy | https://leetcode.com/problems/number-of-segments-in-a-string/ | -| [Maximun Subarray ](/LeetcodeProblems/Algorithms/Maximun_Subarray.js) | Easy | https://leetcode.com/problems/maximum-subarray | -| [Min Stack ](/LeetcodeProblems/Algorithms/Min_Stack.js) | Easy | https://leetcode.com/problems/min-stack/ | -| [Reverse String II ](/LeetcodeProblems/Algorithms/Reverse_String_II.js) | Easy | https://leetcode.com/problems/reverse-string-ii/ | -| [Same Tree ](/LeetcodeProblems/Algorithms/Same_Tree.js) | Easy | https://leetcode.com/problems/same-tree/ | -| [Sum Of Square Numbers ](/LeetcodeProblems/Algorithms/Sum_Of_Square_Numbers.js) | Easy | https://leetcode.com/problems/sum-of-square-numbers/ | -| [Symmetric Tree ](/LeetcodeProblems/Algorithms/Symmetric_Tree.js) | Easy | https://leetcode.com/problems/symmetric-tree/ | -| [Valid Parentheses ](/LeetcodeProblems/Algorithms/Valid_Parentheses.js) | Easy | https://leetcode.com/problems/valid-parentheses/ | -| [Backspace String Compare ](/LeetcodeProblems/Algorithms/Backspace_String_Compare.js) | Easy | https://leetcode.com/problems/backspace-string-compare/ | -| [Binary Gap ](/LeetcodeProblems/Algorithms/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ | -| [Binary Gap ](/LeetcodeProblems/Algorithms/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ | -| [Majority Element](/LeetcodeProblems/Algorithms/Majority_Element.js) | Easy | https://leetcode.com/problems/majority-element/ | -| [Tic Tac Toe ](/LeetcodeProblems/Algorithms/Tic_Tac_Toe.js) | | | -| [Permutations With Duplicates ](/LeetcodeProblems/Algorithms/Permutations_With_Duplicates.js) | | | -| [Deletion Distance](/LeetcodeProblems/Algorithms/Deletion_Distance.js) | | | -| [Award Budget Cuts](/LeetcodeProblems/Algorithms/Award_Budget_Cuts.js) | | | +| Name | Level | Link | +|----------------------------------------------------------------------------------------------------------------------------------------------------------------|--------|---------------------------------------------------------------------------------------------------------------------| +| [Edit Distance ](/LeetcodeProblems/Algorithms/hard/Edit_Distance.js) | Hard | https://leetcode.com/problems/edit-distance/ | +| [First Missing Positive ](/LeetcodeProblems/Algorithms/hard/First_Missing_Positive.js) | Hard | https://leetcode.com/problems/first-missing-positive/ | +| [Remove Invalid Parentheses ](/LeetcodeProblems/Algorithms/hard/Remove_Invalid_Parentheses.js) | Hard | https://leetcode.com/problems/remove-invalid-parentheses/ | +| [Longest Consecutive Sequence ](/LeetcodeProblems/Algorithms/hard/Longest_Consecutive_Sequence.js) | Hard | https://leetcode.com/problems/longest-consecutive-sequence/ | +| [Minimum Window Substring ](/LeetcodeProblems/Algorithms/hard/Minimum_Window_Substring.js) | Hard | https://leetcode.com/problems/minimum-window-substring/ | +| [Regular Expression Matching ](/LeetcodeProblems/Algorithms/hard/Regular_Expression_Matching.js) | Hard | https://leetcode.com/problems/regular-expression-matching/ | +| [NQueens ](/LeetcodeProblems/Algorithms/hard/NQueens.js) | Hard | https://leetcode.com/problems/n-queens/ | +| [merge k sorted lists ](/LeetcodeProblems/Algorithms/hard/merge_k_sorted_lists.js) | Hard | https://leetcode.com/problems/merge-k-sorted-lists/ | +| [Set Matrix Zeroes](/LeetcodeProblems/Algorithms/hard/Set_Matrix_Zeroes.js) | Hard | https://leetcode.com/problems/set-matrix-zeroes/ | +| [Subarray Sum Equals K ](/LeetcodeProblems/Algorithms/medium/Subarray_Sum_Equals_K.js) | Medium | https://leetcode.com/problems/subarray-sum-equals-k/ | +| [3Sum Closest](/LeetcodeProblems/Algorithms/medium/3SumClosest.js) | Medium | https://leetcode.com/problems/3sum-closest/ | +| [3Sum ](/LeetcodeProblems/Algorithms/medium/3Sum.js) | Medium | https://leetcode.com/problems/3sum/ | +| [NumberOfIslands ](/LeetcodeProblems/Algorithms/medium/Number_of_Islands.js) | Medium | https://leetcode.com/problems/number-of-islands/ | +| [Swap Nodes in Pairs](/LeetcodeProblems/Algorithms/medium/Swap_Nodes_in_Pairs.js) | Medium | https://leetcode.com/problems/swap-nodes-in-pairs/ | +| [Add Two Numbers ](/LeetcodeProblems/Algorithms/medium/Add_Two_Numbers.js) | Medium | https://leetcode.com/problems/add-two-numbers/ | +| [Clone Graph ](/LeetcodeProblems/Algorithms/medium/Clone_Graph.js) | Medium | https://leetcode.com/problems/clone-graph/ | +| [Coin Change ](/LeetcodeProblems/Algorithms/medium/Coin_Change.js) | Medium | https://leetcode.com/problems/coin-change/ | +| [Container With Most Water](/LeetcodeProblems/Algorithms/medium/Container_With_Most_Water.js) | Medium | https://leetcode.com/problems/container-with-most-water/ | +| [Design Circular Deque ](/LeetcodeProblems/Algorithms/medium/Design_Circular_Deque.js) | Medium | https://leetcode.com/problems/design-circular-deque/ +| [Escape The Ghosts](/LeetcodeProblems/Algorithms/medium/Escape_The_Ghosts.js) | Medium | https://leetcode.com/problems/escape-the-ghosts/ | +| [Find All Anagrams in a String](/LeetcodeProblems/Algorithms/medium/Find_Anagrams.js) | Medium | https://leetcode.com/problems/find-all-anagrams-in-a-string/ | +| [Generate Parenthesis ](/LeetcodeProblems/Algorithms/medium/Generate_Parenthesis.js) | Medium | https://leetcode.com/problems/generate-parentheses | +| [Group Anagrams ](/LeetcodeProblems/Algorithms/medium/Group_Anagrams.js) | Medium | https://leetcode.com/problems/group-anagrams/ +| [Kth Largest Element in an Array ](/LeetcodeProblems/Algorithms/medium/Kth_Largest_Element_in_an_Array.js) | Medium | https://leetcode.com/problems/kth-largest-element-in-an-array/ | +| [Linked List Cycle II ](/LeetcodeProblems/Algorithms/medium/Linked_List_Cycle_II.js) | Medium | https://leetcode.com/problems/linked-list-cycle-ii/ | +| [Longest Palindromic Substring ](/LeetcodeProblems/Algorithms/medium/Longest_Palindromic_Substring.js) | Medium | https://leetcode.com/problems/longest-palindromic-substring/ | +| [Longest Substring Without Reapeating Characters](/LeetcodeProblems/Algorithms/medium/Longest_Substring.js) | Medium | https://leetcode.com/problems/longest-substring-without-repeating-characters | +| [Max Area Of Island ](/LeetcodeProblems/Algorithms/medium/Max_Area_Of_Island.js) | Medium | https://leetcode.com/problems/max-area-of-island/ | +| [Max Consecutive Ones III ](/LeetcodeProblems/Algorithms/medium/Max_Consecutive_Ones_III.js) | Medium | https://leetcode.com/problems/max-consecutive-ones-iii | +| [Maximal Square ](/LeetcodeProblems/Algorithms/medium/Maximal_Square.js) | Medium | https://leetcode.com/problems/maximal-square/ | +| [Minimum Add to Make Parentheses Valid ](/LeetcodeProblems/Algorithms/medium/Minimum_Add_To_Make_Parentheses_Valid.js) | Medium | https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/ | +| [Minimum Size Subarray](/LeetcodeProblems/Algorithms/medium/Minimum_Size_Subarray.js) | Medium | https://leetcode.com/problems/minimum-size-subarray-sum | +| [Permutations ](/LeetcodeProblems/Algorithms/medium/Permutations.js) | Medium | https://leetcode.com/problems/permutations/ | +| [Permutations II ](/LeetcodeProblems/Algorithms/medium/Permutations_II.js) | Medium | https://leetcode.com/problems/permutations-ii/ | +| [Permutation in String](/LeetcodeProblems/Algorithms/medium/Permutations_In_String.js) | Medium | https://leetcode.com/problems/permutation-in-string/ | +| [Permutations Without Duplicates ](/LeetcodeProblems/Algorithms/medium/Permutations_Without_Duplicates.js) | Medium | https://leetcode.com/problems/permutations/ | +| [Restore IP Addresses ](/LeetcodeProblems/Algorithms/medium/Restore_IP_Addresses.js) | Medium | https://leetcode.com/problems/restore-ip-addresses/ | +| [SearchIng Rotated Sorted Array ](/LeetcodeProblems/Algorithms/medium/SearchIng_Rotated_Sorted_Array.js) | Medium | https://leetcode.com/problems/search-in-rotated-sorted-array/ | +| [Search a 2D Matrix ](/LeetcodeProblems/Algorithms/medium/Search_a_2D_Matrix.js) | Medium | https://leetcode.com/problems/search-a-2d-matrix/ | +| [Search a 2D Matrix II ](/LeetcodeProblems/Algorithms/medium/Search_a_2D_Matrix_II.js) | Medium | https://leetcode.com/problems/search-a-2d-matrix/ | +| [Simplify Path ](/LeetcodeProblems/Algorithms/medium/Simplify_Path.js) | Medium | https://leetcode.com/problems/simplify-path/ | +| [Spiral Matrix ](/LeetcodeProblems/Algorithms/medium/Spiral_Matrix.js) | Medium | https://leetcode.com/problems/spiral-matrix/ | +| [Subsets ](/LeetcodeProblems/Algorithms/medium/Subsets.js) | Medium | https://leetcode.com/problems/subsets/ | +| [Unique Binary Search Trees ](/LeetcodeProblems/Algorithms/medium/Unique_Binary_Search_Trees.js) | Medium | https://leetcode.com/problems/unique-binary-search-trees/ | +| [Unique Paths ](/LeetcodeProblems/Algorithms/medium/Unique_Paths.js) | Medium | https://leetcode.com/problems/unique-paths/ | +| [Verify Preorder Serialization of a Binary Tree ](/LeetcodeProblems/Algorithms/medium/Verify_Preorder_Serialization_of_a_Binary_Tree.js) | Medium | https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ | +| [Construct Binary Tree from Preorder and Inorder Traversal ](/LeetcodeProblems/Algorithms/medium/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js) | Medium | https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ | +| [Lowest Common Ancestor of a Binary Tree ](/LeetcodeProblems/Algorithms/medium/Lowest_Common_Ancestor_of_a_Binary_Tree.js) | Medium | https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ | +| [Maximum Sum of an Hourglass](/LeetcodeProblems/Algorithms/medium/Maximise_Hour_Glass_Sum.js) | Medium | https://leetcode.com/problems/maximum-sum-of-an-hourglass/ | +| [Next Permutation](/LeetcodeProblems/Algorithms/medium/Next_Permutation.js) | Medium | https://leetcode.com/problems/next-permutation/ | +| [Time Needed to Rearrange a Binary String](/LeetcodeProblems/Algorithms/medium/Time_Needed_Rearrange_Binary_String.js) | Medium | https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/ | +| [Find Subarrays With Equal Sum ](/LeetcodeProblems/Algorithms/medium/Find_Subarrays_With_Equal_Sums.js) | Medium | https://leetcode.com/problems/find-subarrays-with-equal-sum/ | +| [Reverse Integer](/LeetcodeProblems/Algorithms/medium/Reverse_Integer.js) | Medium | https://leetcode.com/problems/reverse-integer/ | +| [Minimize Maximum Pair Sum in Array ](/LeetcodeProblems/Algorithms/medium/Minimize_Maximum_Pair_Sum_In_Array.js) | Medium | https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/ | +| [Top K Frequent Elements ](/LeetcodeProblems/Algorithms/medium/Top_K_Frequent_Elements.js) | Medium | https://leetcode.com/problems/top-k-frequent-elements/ | +| [Gas Station](/LeetcodeProblems/Algorithms/medium/GasStation/index.js) | Medium | https://leetcode.com/problems/gas-station/description/ | +| [K Closest Points to Origin](/LeetcodeProblems/Algorithms/medium/K_Closest_Points_to_Origin.js/) | Medium | https://leetcode.com/problems/k-closest-points-to-origin/ +| [BestTimeToBuy](LeetcodeProblems/Algorithms/easy/Best_Time_To_Buy_And_Sell_Stock_II.js) | Medium | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii | +| [Best Time to Buy and Sell Stock](/LeetcodeProblems/Algorithms/easy/Best_Time_to_buy_and_sell_stock.js) | Easy | https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ +| [Flood Fill ](/LeetcodeProblems/Algorithms/easy/Flood_Fill.js) | Easy | https://leetcode.com/problems/flood-fill/ | +| [Implement stack using queues ](/LeetcodeProblems/Algorithms/easy/Implement_stack_using_queues.js) | Easy | https://leetcode.com/problems/implement-stack-using-queues/ | +| [Number of Segments in a String ](/LeetcodeProblems/Algorithms/easy/Number_of_Segments_in_a_String.js) | Easy | https://leetcode.com/problems/number-of-segments-in-a-string/ | +| [Maximun Subarray ](/LeetcodeProblems/Algorithms/easy/Maximun_Subarray.js) | Easy | https://leetcode.com/problems/maximum-subarray | +| [Min Stack ](/LeetcodeProblems/Algorithms/easy/Min_Stack.js) | Easy | https://leetcode.com/problems/min-stack/ | +| [Reverse String II ](/LeetcodeProblems/Algorithms/easy/Reverse_String_II.js) | Easy | https://leetcode.com/problems/reverse-string-ii/ | +| [Same Tree ](/LeetcodeProblems/Algorithms/easy/Same_Tree.js) | Easy | https://leetcode.com/problems/same-tree/ | +| [Sum Of Square Numbers ](/LeetcodeProblems/Algorithms/easy/Sum_Of_Square_Numbers.js) | Easy | https://leetcode.com/problems/sum-of-square-numbers/ | +| [Symmetric Tree ](/LeetcodeProblems/Algorithms/easy/Symmetric_Tree.js) | Easy | https://leetcode.com/problems/symmetric-tree/ | +| [Valid Parentheses ](/LeetcodeProblems/Algorithms/easy/Valid_Parentheses.js) | Easy | https://leetcode.com/problems/valid-parentheses/ | +| [Backspace String Compare ](/LeetcodeProblems/Algorithms/easy/Backspace_String_Compare.js) | Easy | https://leetcode.com/problems/backspace-string-compare/ | +| [Binary Gap ](/LeetcodeProblems/Algorithms/easy/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ | +| [Majority Element](/LeetcodeProblems/Algorithms/easy/Majority_Element.js) | Easy | https://leetcode.com/problems/majority-element/ | +| [Lexographically Smallest String After A Swap](/LeetcodeProblems/Algorithms/medium/Kth_Largest_Element_in_an_Array.js) | Easy | https://leetcode.com/problems/lexicographically-smallest-string-after-a-swap/ | +| [Longest Common Prefix](/LeetcodeProblems/Algorithms/easy/Longest_Common_Prefix.js) | Easy | https://leetcode.com/problems/longest-common-prefix/ | +| [Two Sum](/LeetcodeProblems/Algorithms/easy/2Sum.js) | Easy | https://leetcode.com/problems/two-sum/ | +| [Tic Tac Toe ](/LeetcodeProblems/Algorithms/easy/Tic_Tac_Toe.js) | Easy | | +| [Permutations With Duplicates ](/LeetcodeProblems/Algorithms/easy/Permutations_With_Duplicates.js) | Easy | | +| [Deletion Distance](/LeetcodeProblems/Algorithms/easy/Deletion_Distance.js) | Easy | | +| [Award Budget Cuts](/LeetcodeProblems/Algorithms/easy/Award_Budget_Cuts.js) | Easy | | +| [Happy Number](/LeetcodeProblems/Algorithms/easy/Happy_Number.js) | Easy | https://leetcode.com/problems/happy-number/ | +| [Shuffle String](/LeetcodeProblems/Algorithms/easy/Shuffle_String.js) | Easy | https://leetcode.com/problems/shuffle-string/ | +| [Reverse bit to make number equal](/LeetcodeProblems/Algorithms/easy/Bit_Reverse_To_Make_Numbers_Equal.js.js) | Easy | https://leetcode.com/problems/number-of-bit-changes-to-make-two-integers-equal/ | ### Sorting Algorithms | Algoritmhs | @@ -92,20 +107,20 @@ To run a specific problem in your console run `node ` (e.g. ### Databases | Problems | Level | Link | |-|-|-| -| [Trips and Users](/LeetcodeProblems/Databases/Trips_and_Users.sql) | Hard | https://leetcode.com/problems/trips-and-users/ | -| [Human Traffic of Stadium](/LeetcodeProblems/Databases/Human_Traffic_of_Stadium.sql) | Hard | https://leetcode.com/problems/human-traffic-of-stadium | -| [Rank Scores](/LeetcodeProblems/Databases/Rank_Scores.sql) | Medium | https://leetcode.com/problems/rank-scores | -| [Consecutive Numbers](/LeetcodeProblems/Databases/Consecutive_Numbers.sql) | Medium | https://leetcode.com/problems/consecutive-numbers | -| [Department Highest Salary](/LeetcodeProblems/Databases/Department_Highest_Salary.sql) | Medium | https://leetcode.com/problems/department-highest-salary | -| [Exchange Seats](/LeetcodeProblems/Databases/Exchange_Seats.sql) | Medium | https://leetcode.com/problems/exchange-seats | -| [Nth Highest Salary](/LeetcodeProblems/Databases/nth_Highest_Salary.sql) | Medium | https://leetcode.com/problems/nth-highest-salary | -| [Combine Two Tables](/LeetcodeProblems/Databases/Combine_Two_Tables.sql) | Easy | https://leetcode.com/problems/combine-two-tables | -| [Second Highest Salary](/LeetcodeProblems/Databases/Second_highest_salary.sql)| Easy | https://leetcode.com/problems/second-highest-salary | -| [Customers Who Never Order](/LeetcodeProblems/Databases/Customers_Who_Never_Order.sql)| Easy | https://leetcode.com/problems/customers-who-never-order | -| [Reformat Department Table](/LeetcodeProblems/Databases/Reformat_Department_Table.sql) | Easy | https://leetcode.com/problems/reformat-department-table | -| [Employees Earning More Than Their Managers](/LeetcodeProblems/Databases/Employees_Earning_More_Than_Their_Managers.sql) | Easy | https://leetcode.com/problems/employees-earning-more-than-their-managers/ | -| [Delete Duplicate Emails](LeetcodeProblems/Databases/Delete_Duplicate_Emails.sql) | Easy | https://leetcode.com/problems/delete-duplicate-emails | -| [Rising Temperature](LeetcodeProblems/Databases/Rising_Temperature.sql) | Easy | https://leetcode.com/problems/rising-temperature | +| [Trips and Users](/LeetcodeProblems/Databases/hard/Trips_and_Users.sql) | Hard | https://leetcode.com/problems/trips-and-users/ | +| [Human Traffic of Stadium](/LeetcodeProblems/Databases/hard/Human_Traffic_of_Stadium.sql) | Hard | https://leetcode.com/problems/human-traffic-of-stadium | +| [Rank Scores](/LeetcodeProblems/Databases/medium/Rank_Scores.sql) | Medium | https://leetcode.com/problems/rank-scores | +| [Consecutive Numbers](/LeetcodeProblems/Databases/medium/Consecutive_Numbers.sql) | Medium | https://leetcode.com/problems/consecutive-numbers | +| [Department Highest Salary](/LeetcodeProblems/Databases/medium/Department_Highest_Salary.sql) | Medium | https://leetcode.com/problems/department-highest-salary | +| [Exchange Seats](/LeetcodeProblems/Databases/medium/Exchange_Seats.sql) | Medium | https://leetcode.com/problems/exchange-seats | +| [Nth Highest Salary](/LeetcodeProblems/Databases/medium/nth_Highest_Salary.sql) | Medium | https://leetcode.com/problems/nth-highest-salary | +| [Combine Two Tables](/LeetcodeProblems/Databases/easy/Combine_Two_Tables.sql) | Easy | https://leetcode.com/problems/combine-two-tables | +| [Second Highest Salary](/LeetcodeProblems/Databases/easy/Second_highest_salary.sql)| Easy | https://leetcode.com/problems/second-highest-salary | +| [Customers Who Never Order](/LeetcodeProblems/Databases/easy/Customers_Who_Never_Order.sql)| Easy | https://leetcode.com/problems/customers-who-never-order | +| [Reformat Department Table](/LeetcodeProblems/Databases/easy/Reformat_Department_Table.sql) | Easy | https://leetcode.com/problems/reformat-department-table | +| [Employees Earning More Than Their Managers](/LeetcodeProblems/Databases/easy/Employees_Earning_More_Than_Their_Managers.sql) | Easy | https://leetcode.com/problems/employees-earning-more-than-their-managers/ | +| [Delete Duplicate Emails](LeetcodeProblems/Databases/easy/Delete_Duplicate_Emails.sql) | Easy | https://leetcode.com/problems/delete-duplicate-emails | +| [Rising Temperature](LeetcodeProblems/Databases/easy/Rising_Temperature.sql) | Easy | https://leetcode.com/problems/rising-temperature | ### UtilsClasses diff --git a/SortingAlgorithms/QuickSort.js b/SortingAlgorithms/QuickSort.js index 69db83b..a6bae1f 100644 --- a/SortingAlgorithms/QuickSort.js +++ b/SortingAlgorithms/QuickSort.js @@ -1,39 +1,40 @@ function swap(items, leftIndex, rightIndex){ - var temp = items[leftIndex]; - items[leftIndex] = items[rightIndex]; - items[rightIndex] = temp; + var temp = items[leftIndex]; + items[leftIndex] = items[rightIndex]; + items[rightIndex] = temp; } function partition(items, left, right) { - var pivot = items[Math.floor((right + left) / 2)], //middle element - i = left, //left pointer - j = right; //right pointer - while (i <= j) { - while (items[i] < pivot) { - i++; - } - while (items[j] > pivot) { - j--; - } - if (i <= j) { - swap(items, i, j); //sawpping two elements - i++; - j--; - } + var pivot = items[Math.floor((right + left) / 2)], //middle element + i = left, //left pointer + j = right; //right pointer + while (i <= j) { + while (items[i] < pivot) { + i++; } - return i; + while (items[j] > pivot) { + j--; + } + if (i <= j) { + swap(items, i, j); //sawpping two elements + i++; + j--; + } + } + return i; } function quickSort(items, left, right) { - var index; - if (items.length > 1) { - index = partition(items, left, right); //index returned from partition - if (left < index - 1) { //more elements on the left side of the pivot - quickSort(items, left, index - 1); - } - if (index < right) { //more elements on the right side of the pivot - quickSort(items, index, right); - } + var index; + if (items.length > 1) { + index = partition(items, left, right); //index returned from partition + if (left < index - 1) { //more elements on the left side of the pivot + quickSort(items, left, index - 1); + } + if (index < right) { //more elements on the right side of the pivot + quickSort(items, index, right); } - return items; + } + return items; } +module.exports.quickSort = quickSort; diff --git a/SortingAlgorithms/heapSort.js b/SortingAlgorithms/heapSort.js index bae4570..e846b0d 100644 --- a/SortingAlgorithms/heapSort.js +++ b/SortingAlgorithms/heapSort.js @@ -1,16 +1,17 @@ // Testing Gist var heapSort = function(arr) { var n = arr.length; - for(var i = Math.floor(n/2) - 1; i >= 0; i--) + for(let i = Math.floor(n/2) - 1; i >= 0; i--) { heapify(arr, n, i); + } - for(var i = n - 1; i >= 0; i--) { + for(let i = n - 1; i >= 0; i--) { swap(arr, 0, i); heapify(arr, i, 0); } return arr; -} +}; var heapify = function(arr, n, i) { var left = 2 * i + 1; @@ -32,17 +33,17 @@ var heapify = function(arr, n, i) { swap(arr, i, right); heapify(arr, n, right); } -} +}; var swap = function(arr, a, b) { var temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; -} +}; console.log(heapSort([14, 1, 10, 2, 3, 5, 6, 4, 7, 11, 12, 13])); console.log(heapSort([])); console.log(heapSort([1])); console.log(heapSort([2, 1])); -console.log(heapSort([1,7,2,3,4,1,10,2,3,4,5])) +console.log(heapSort([1,7,2,3,4,1,10,2,3,4,5])); diff --git a/Test.js b/Test.js index 3b5c27f..f1c8c87 100644 --- a/Test.js +++ b/Test.js @@ -1,38 +1,116 @@ -const fs = require('fs'); +/* eslint-disable no-useless-escape */ +/* eslint-disable no-undef */ +const fs = require("fs"); + +const PROBLEMS_FOLDERS = [ + "./LeetcodeProblems/Algorithms/easy/", + "./LeetcodeProblems/Algorithms/medium/", + "./LeetcodeProblems/Algorithms/hard/" +]; + +const TESTS_FOLDERS = [ + "./LeetcodeProblemsTests/Algorithms/easy/", + "./LeetcodeProblemsTests/Algorithms/medium/", + "./LeetcodeProblemsTests/Algorithms/hard/" +]; -const TESTS_FOLDER = './LeetcodeProblemsTests/Algorithms/'; const REGEX_PATTERN_HIDDEN_FILES = /(^|\/)\.[^\/\.]/g; -var test_all = async function() { +const getAllTests = async function (paths) { + let problems = []; + for(const i in paths) { + const folder = paths[i]; + const newProblems = await loadProblemsFiles(folder); // await + problems = problems.concat(newProblems); + } + return problems; +}; + +const runAllTests = async function (problems) { try { - const problems = await loadProblems(); - for(i in problems) { - console.log("Solving: " + problems[i]); - const problem = require(TESTS_FOLDER + problems[i]); - - if (typeof(problem.test) !=='undefined') { - problem.test(); - console.log("✅ Tests for " + problems[i] + " run successfully \n"); - } else { - console.warn(problem, "🔴 The problem " + problems[i] + " doesn't have a test method implemented.\n"); - } + console.log(problems); + var solvePromises = problems.map(solveProblem); + + await Promise.all(solvePromises); + } catch (error) { + console.log(error); + throw new Error(error); + } +}; + +const solveProblem = (problem) => { + try { + console.log("Solving: " + problem); + + const tests = require(problem); + console.log("*".repeat(100)); + if (Object.keys(tests).length == 0) { + console.warn("🔴 The problem " + problem + " doesn't have a test method implemented.\n"); + return; } + for(testIdx in tests) { + tests[testIdx](); + } + console.log("✅ Tests for " + problem + " run successfully \n"); } catch (error) { + console.log(error); throw new Error(error); } -} +}; -var loadProblems = () => { +const loadProblemsFiles = (folder) => { return new Promise(function (resolve, reject) { - fs.readdir(TESTS_FOLDER, (error, files) => { + fs.readdir(folder, (error, files) => { if (error) { reject(error); } else { - problems = files.filter(item => !(REGEX_PATTERN_HIDDEN_FILES).test(item)); - resolve(problems); + console.log(folder); + newProblems = files.filter((item) => !REGEX_PATTERN_HIDDEN_FILES.test(item)); + newProblems = newProblems.map((item) => folder + item); + + resolve(newProblems); } - }) + }); }); +}; + +const getMissingTests = async function (tests, problems) { + const hasTestStatus = problems.reduce((status, problemPath) => { + const baseIndex = PROBLEMS_FOLDERS.findIndex((basePath) => + problemPath.startsWith(basePath) + ); + + let testPath = problemPath + .replace(PROBLEMS_FOLDERS[baseIndex], TESTS_FOLDERS[baseIndex]) + .replace(/\.js$/, "_Test.js"); + + status.push({ + problem: problemPath, + hasTest: tests.includes(testPath) + }); + + return status; + }, []); + const missingTests = hasTestStatus.filter((stat) => !stat.hasTest); + console.log("Total Problems:", problems.length); + console.log("Missing Tests:", missingTests.length); + + if(missingTests.length) { + console.table(missingTests); + } +}; + +async function runScript() { + if (process.argv.length > 2) { + const path = process.argv.pop(); + solveProblem(path); + } else { + const problems = await getAllTests(PROBLEMS_FOLDERS); + const tests = await getAllTests(TESTS_FOLDERS); + + await runAllTests(tests); + await getMissingTests(tests, problems); + } } -test_all(); +runScript(); \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index c490ac5..9d02572 100644 --- a/package-lock.json +++ b/package-lock.json @@ -904,9 +904,9 @@ } }, "node_modules/word-wrap": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", - "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.4.tgz", + "integrity": "sha512-2V81OA4ugVo5pRo46hAoD2ivUJx8jXmWXfUkY4KFNw0hEptvN0QfH3K4nHiwzGeKl5rFKedV48QVoqYavy4YpA==", "dev": true, "engines": { "node": ">=0.10.0" @@ -1588,9 +1588,9 @@ } }, "word-wrap": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", - "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.4.tgz", + "integrity": "sha512-2V81OA4ugVo5pRo46hAoD2ivUJx8jXmWXfUkY4KFNw0hEptvN0QfH3K4nHiwzGeKl5rFKedV48QVoqYavy4YpA==", "dev": true }, "wrappy": { diff --git a/pull_request_template.md b/pull_request_template.md new file mode 100644 index 0000000..a2e90bb --- /dev/null +++ b/pull_request_template.md @@ -0,0 +1,10 @@ +## Title of the problem + +## Checklist before requesting a review +- [ ] I have checked the [guide](https://github.com/ignacio-chiazzo/Algorithms-Leetcode-Javascript#contributions) for contributions. +- [ ] I have added the description at the top of the solution file. +- [ ] I have added a test file for the problem. +- [ ] I have added an entry to the [README](https://github.com/ignacio-chiazzo/Algorithms-Leetcode-Javascript/blob/master/README.md) file with a link to the new file. +- [ ] I have run linter (`npx eslint LeetcodeProblems LeetcodeProblemsTests`) and unit tests (`node Test.js`) and they pass. [More info](https://github.com/ignacio-chiazzo/Algorithms-Leetcode-Javascript#run-tests). + +Check the [guide](https://github.com/ignacio-chiazzo/Algorithms-Leetcode-Javascript#contributions) and [this PR](https://github.com/ignacio-chiazzo/Algorithms-Leetcode-Javascript/pull/39) example. diff --git a/utilsClasses/ListNodeTestHelper.js b/utilsClasses/ListNodeTestHelper.js index 2e18a18..cd17e5e 100644 --- a/utilsClasses/ListNodeTestHelper.js +++ b/utilsClasses/ListNodeTestHelper.js @@ -1,4 +1,4 @@ -const assert = require('assert'); +const assert = require("assert"); var assertList = function(list, expectedArr) { const listlength = list ? list.length() : 0; @@ -7,6 +7,6 @@ var assertList = function(list, expectedArr) { assert.strictEqual(list.val, expectedArr[i]); list = list.next; } -} +}; module.exports.assertList = assertList; \ No newline at end of file