diff --git a/.gitignore b/.gitignore index b830d05..97cf9d3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ tips -.DS_Store \ No newline at end of file +.DS_Store + +node_modules/ \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..dd5fef8 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,6 @@ +{ + "editor.formatOnSave": false, + "[javascript]": { + "editor.formatOnSave": true + } +} \ No newline at end of file diff --git a/LeetcodeProblems/Algorithms/3Sum.js b/LeetcodeProblems/Algorithms/3Sum.js index c5d4ec8..d200c04 100644 --- a/LeetcodeProblems/Algorithms/3Sum.js +++ b/LeetcodeProblems/Algorithms/3Sum.js @@ -23,28 +23,33 @@ A solution set is: * @param {number[]} nums * @return {number[][]} */ -var threeSum = function(nums) { +var threeSum = function (nums) { var ret = []; - nums.sort(function(a, b) { return a - b }); - for(var i = 0; i < nums.length; i++) { - if(i === 0 || i > 0 && nums[i] !== nums[i - 1]) { - var left = i + 1; - var right = nums.length - 1; - while(left < right) { - const sum = nums[left] + nums[right] + nums[i]; - if(left > i + 1 && nums[left] === nums[left - 1] || sum < 0) { - left++ - } else if(right < nums.length - 1 && nums[right] === nums[right + 1] || sum > 0) { - right--; - } else if(sum === 0) { - ret.push([nums[left], nums[right], nums[i]]); - left++; - right--; - } - } + nums.sort(function (a, b) { + return a - b; + }); + for (var i = 0; i < nums.length; i++) { + if (i === 0 || (i > 0 && nums[i] !== nums[i - 1])) { + var left = i + 1; + var right = nums.length - 1; + while (left < right) { + const sum = nums[left] + nums[right] + nums[i]; + if ((left > i + 1 && nums[left] === nums[left - 1]) || sum < 0) { + left++; + } else if ( + (right < nums.length - 1 && nums[right] === nums[right + 1]) || + sum > 0 + ) { + right--; + } else if (sum === 0) { + ret.push([nums[left], nums[right], nums[i]]); + left++; + right--; + } } + } } - + return ret; }; diff --git a/LeetcodeProblems/Algorithms/Add_Two_Numbers.js b/LeetcodeProblems/Algorithms/Add_Two_Numbers.js index 8d253bb..b5d4590 100644 --- a/LeetcodeProblems/Algorithms/Add_Two_Numbers.js +++ b/LeetcodeProblems/Algorithms/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 @@ -29,36 +29,33 @@ var ListNode = require('../../UtilsClasses/ListNode').ListNode; * @return {ListNode} */ -var addTwoNumbers = function(l1, l2) { - if(l1 === null) - return (l2 === null) ? new ListNode(0) : l2; - else if(l2 === null) - return l1; - +var addTwoNumbers = function (l1, l2) { + if (l1 === null) return l2 === null ? new ListNode(0) : l2; + else if (l2 === null) return l1; + var elem = l1.val + l2.val; var number = new ListNode(elem % 10); - var carry = (elem >= 10) ? 1 : 0; + var carry = elem >= 10 ? 1 : 0; l1 = l1.next; l2 = l2.next; - + const head = number; - while(l1 !== null || l2 !== null) { + while (l1 !== null || l2 !== null) { var elem = carry; - if(l1 !== null) { + if (l1 !== null) { elem += l1.val; l1 = l1.next; } - if(l2 !== null) { + if (l2 !== null) { elem += l2.val; l2 = l2.next; } - - number.next = new ListNode((elem % 10)); + + number.next = new ListNode(elem % 10); number = number.next; - carry = (elem >= 10) ? 1 : 0; + carry = elem >= 10 ? 1 : 0; } - if(carry === 1) - number.next = new ListNode(1); + if (carry === 1) number.next = new ListNode(1); return head; }; diff --git a/LeetcodeProblems/Algorithms/Award_Budget_Cuts.js b/LeetcodeProblems/Algorithms/Award_Budget_Cuts.js index b9efb99..af2a916 100644 --- a/LeetcodeProblems/Algorithms/Award_Budget_Cuts.js +++ b/LeetcodeProblems/Algorithms/Award_Budget_Cuts.js @@ -29,39 +29,39 @@ Constraints: [output] double */ -var cutAwardBadges = function(nums, newBadge) { +var cutAwardBadges = function (nums, newBadge) { var currentBadge = 0; - for(var i = 0; i < nums.length; i++) - currentBadge += nums[i]; + for (var i = 0; i < nums.length; i++) currentBadge += nums[i]; - if(currentBadge < newBadge) - return; + if (currentBadge < newBadge) return; const cap = findCap(nums, currentBadge, newBadge); var iter = 0; - while(iter >= 0 && nums[iter] > cap) { + while (iter >= 0 && nums[iter] > cap) { nums[iter] = cap; iter++; } return nums; -} +}; -var findCap = function(nums, currentBadge, newBadge) { - nums.sort(function(a, b) { return b - a }); - if(nums[nums.length - 1] * nums.length > newBadge) +var findCap = function (nums, currentBadge, newBadge) { + nums.sort(function (a, b) { + return b - a; + }); + if (nums[nums.length - 1] * nums.length > newBadge) return newBadge / nums.length; var diff = currentBadge - newBadge; var iter = 0; - while(iter < nums.length - 1 && diff > 0) { - const substraction = nums[iter] - nums[iter + 1] - diff -= (iter + 1) * substraction; + while (iter < nums.length - 1 && diff > 0) { + const substraction = nums[iter] - nums[iter + 1]; + diff -= (iter + 1) * substraction; iter++; } - return nums[iter] + (-diff) / iter; -} + return nums[iter] + -diff / iter; +}; module.exports.cutAwardBadges = cutAwardBadges; diff --git a/LeetcodeProblems/Algorithms/Backspace_String_Compare.js b/LeetcodeProblems/Algorithms/Backspace_String_Compare.js index f7051af..457fa55 100644 --- a/LeetcodeProblems/Algorithms/Backspace_String_Compare.js +++ b/LeetcodeProblems/Algorithms/Backspace_String_Compare.js @@ -37,15 +37,15 @@ Can you solve it in O(N) time and O(1) space? * @param {string} T * @return {boolean} */ -var backspaceCompare = function(S, T) { +var backspaceCompare = function (S, T) { var iterS = S.length - 1; var iterT = T.length - 1; - - while(iterS >= 0 || iterT >= 0) { - if(iterS >= 0 && S.charAt(iterS) === "#") { + + while (iterS >= 0 || iterT >= 0) { + if (iterS >= 0 && S.charAt(iterS) === "#") { var countBack = 0; - while(iterS >= 0 && (countBack > 0 || S[iterS] === "#")) { - if(iterS >= 0 && S[iterS] === "#") { + while (iterS >= 0 && (countBack > 0 || S[iterS] === "#")) { + if (iterS >= 0 && S[iterS] === "#") { countBack++; } else { countBack--; @@ -53,55 +53,49 @@ var backspaceCompare = function(S, T) { iterS--; } - } else if(iterT >= 0 && T.charAt(iterT) === "#") { - var countBack = 0; - while(iterT >= 0 && (countBack > 0 || T[iterT] === "#")) { - if(iterT >= 0 && T[iterT] === "#") { - countBack++; - } else { - countBack--; + } else if (iterT >= 0 && T.charAt(iterT) === "#") { + var countBack = 0; + while (iterT >= 0 && (countBack > 0 || T[iterT] === "#")) { + if (iterT >= 0 && T[iterT] === "#") { + countBack++; + } else { + countBack--; + } + + iterT--; } - - iterT--; - } } else { - if(iterS < 0 || iterT < 0 || S.charAt(iterS) !== T.charAt(iterT)) + if (iterS < 0 || iterT < 0 || S.charAt(iterS) !== T.charAt(iterT)) return false; - + iterS--; iterT--; } } - - return iterS < 0 && iterT < 0; + + return iterS < 0 && iterT < 0; }; -// Naive Aproach -var backspaceCompare2 = function(S, T) { +// Naive Aproach +var backspaceCompare2 = function (S, T) { var stackS = []; - for(var i = 0; i < S.length; i++) { - if(S.charAt(i) === "#") - stackS.shift(); - else - stackS.unshift(S.charAt(i)); + for (var i = 0; i < S.length; i++) { + if (S.charAt(i) === "#") stackS.shift(); + else stackS.unshift(S.charAt(i)); } - + var stackT = []; - for(var i = 0; i < T.length; i++) { - if(T.charAt(i) === "#") - stackT.shift(); - else - stackT.unshift(T.charAt(i)); + for (var i = 0; i < T.length; i++) { + if (T.charAt(i) === "#") stackT.shift(); + else stackT.unshift(T.charAt(i)); } - - while(stackS.length > 0 && stackT.length > 0) { + + while (stackS.length > 0 && stackT.length > 0) { var elemS = stackS.shift(); var elemT = stackT.shift(); - if(elemS !== elemT) - return false; - + if (elemS !== elemT) return false; } - + return stackS.length === 0 && stackT.length === 0; }; diff --git a/LeetcodeProblems/Algorithms/Best_Time_To_Buy_And_Sell_Stock_II.js b/LeetcodeProblems/Algorithms/Best_Time_To_Buy_And_Sell_Stock_II.js index 0dd7138..83d4460 100644 --- a/LeetcodeProblems/Algorithms/Best_Time_To_Buy_And_Sell_Stock_II.js +++ b/LeetcodeProblems/Algorithms/Best_Time_To_Buy_And_Sell_Stock_II.js @@ -32,27 +32,27 @@ Explanation: In this case, no transaction is done, i.e. max profit = 0. * @param {number[]} prices * @return {number} */ -var maxProfit = function(prices) { +var maxProfit = function (prices) { var profit = 0; var iter = 0; - - while(iter < prices.length) { - while(iter < prices.length - 1 && prices[iter] > prices[iter + 1]) { + + while (iter < prices.length) { + while (iter < prices.length - 1 && prices[iter] > prices[iter + 1]) { iter++; } const buy = prices[iter]; iter++; - while(iter < prices.length - 1 && prices[iter] < prices[iter + 1]) { + while (iter < prices.length - 1 && prices[iter] < prices[iter + 1]) { iter++; } - - if(iter < prices.length) { + + if (iter < prices.length) { const sell = prices[iter]; profit = profit + sell - buy; } } - + return profit; }; -module.exports.maxProfit = maxProfit; \ No newline at end of file +module.exports.maxProfit = maxProfit; diff --git a/LeetcodeProblems/Algorithms/Binary_Gap.js b/LeetcodeProblems/Algorithms/Binary_Gap.js index 4b07e8c..287327b 100644 --- a/LeetcodeProblems/Algorithms/Binary_Gap.js +++ b/LeetcodeProblems/Algorithms/Binary_Gap.js @@ -41,20 +41,19 @@ There aren't any consecutive pairs of 1's in the binary representation of 8, so * @param {number} N * @return {number} */ -var binaryGap = function(N) { +var binaryGap = function (N) { var maxDist = 0; var currentDist = 0; - while(N > 0) { + while (N > 0) { const bit = N % 2; N >>= 1; - if(bit === 1) { + if (bit === 1) { currentDist = 1; - while(N > 0 && N % 2 === 0 ) { + while (N > 0 && N % 2 === 0) { currentDist++; - N >>= 1; + N >>= 1; } - if(N !== 0 && currentDist > maxDist) - maxDist = currentDist; + if (N !== 0 && currentDist > maxDist) maxDist = currentDist; } } return maxDist; diff --git a/LeetcodeProblems/Algorithms/Clone_Graph.js b/LeetcodeProblems/Algorithms/Clone_Graph.js index 0531e8d..3e0b03b 100644 --- a/LeetcodeProblems/Algorithms/Clone_Graph.js +++ b/LeetcodeProblems/Algorithms/Clone_Graph.js @@ -45,54 +45,51 @@ You don't need to understand the serialization to solve the problem. * @param {UndirectedGraphNode} graph * @return {UndirectedGraphNode} */ -var cloneGraph = function(graph) { - if(!graph) - return graph; - +var cloneGraph = function (graph) { + if (!graph) return graph; + return dfs(graph, {}); }; -var dfs = function(graph, visited) { - if(visited[graph.label]) - return visited[graph.label]; - +var dfs = function (graph, visited) { + if (visited[graph.label]) return visited[graph.label]; + var newNode = new UndirectedGraphNode(graph.label); visited[newNode.label] = newNode; - - for(var i = 0; i < graph.neighbors.length; i++) { - const neighbor = dfs(graph.neighbors[i], visited); - newNode.neighbors.push(neighbor); + + for (var i = 0; i < graph.neighbors.length; i++) { + const neighbor = dfs(graph.neighbors[i], visited); + newNode.neighbors.push(neighbor); } - + return newNode; -} +}; // SOLUTION 2 Using DFS -var cloneGraphBFS = function(graph) { - if(graph === null) - return graph; - - var visitedMap = {}; - var queue = [graph]; - var copyReturn = new UndirectedGraphNode(graph.label); - visitedMap[graph.label] = copyReturn; - - while(queue.length > 0) { - var node = queue.shift(); - var nodeCopied = visitedMap[node.label]; - - for(var i = 0; i < node.neighbors.length; i++) { - var neighbor = node.neighbors[i]; - - if(!visitedMap[neighbor.label]) { - var copyNeighbor = new UndirectedGraphNode(neighbor.label); - visitedMap[neighbor.label] = copyNeighbor; - queue.push(neighbor); - } - - nodeCopied.neighbors.push(visitedMap[neighbor.label]); - } +var cloneGraphBFS = function (graph) { + if (graph === null) return graph; + + var visitedMap = {}; + var queue = [graph]; + var copyReturn = new UndirectedGraphNode(graph.label); + visitedMap[graph.label] = copyReturn; + + while (queue.length > 0) { + var node = queue.shift(); + var nodeCopied = visitedMap[node.label]; + + for (var i = 0; i < node.neighbors.length; i++) { + var neighbor = node.neighbors[i]; + + if (!visitedMap[neighbor.label]) { + var copyNeighbor = new UndirectedGraphNode(neighbor.label); + visitedMap[neighbor.label] = copyNeighbor; + queue.push(neighbor); + } + + nodeCopied.neighbors.push(visitedMap[neighbor.label]); } - - return copyReturn; -} + } + + return copyReturn; +}; diff --git a/LeetcodeProblems/Algorithms/Coin_Change.js b/LeetcodeProblems/Algorithms/Coin_Change.js index 51ca9a0..166fadf 100644 --- a/LeetcodeProblems/Algorithms/Coin_Change.js +++ b/LeetcodeProblems/Algorithms/Coin_Change.js @@ -19,86 +19,89 @@ Note: You may assume that you have an infinite number of each kind of coin. */ -// Solution 3 -var coinChange = function(coins, amount) { +// Solution 3 +var coinChange = function (coins, amount) { var memo = []; - for(var i = 0; i <= amount; i++) - memo[i] = Number.POSITIVE_INFINITY; + for (var i = 0; i <= amount; i++) memo[i] = Number.POSITIVE_INFINITY; memo[0] = 0; - for(var i = 0; i < coins.length; i++) { + for (var i = 0; i < coins.length; i++) { const coin = coins[i]; - for(var j = coin; j < memo.length; j++) + for (var j = coin; j < memo.length; j++) memo[j] = min2(memo[j], memo[j - coin] + 1); } - return (memo[amount] == Number.POSITIVE_INFINITY) ? -1 : memo[amount]; + return memo[amount] == Number.POSITIVE_INFINITY ? -1 : memo[amount]; }; -var min2 = function(a, b) { - return (a < b) ? a : b; -} +var min2 = function (a, b) { + return a < b ? a : b; +}; // Solution 2 -var buildMemoKey = function(position, amount) { +var buildMemoKey = function (position, amount) { return position + "-" + amount; -} +}; -var coinChange2 = function(coins, amount) { +var coinChange2 = function (coins, amount) { var memo = {}; - var solution = coinChangeAux2(coins, amount, 0, memo, Number.POSITIVE_INFINITY); + var solution = coinChangeAux2( + coins, + amount, + 0, + memo, + Number.POSITIVE_INFINITY + ); return solution == Number.POSITIVE_INFINITY ? -1 : solution; }; -var coinChangeAux2 = function(coins, amount, pos, memo) { +var coinChangeAux2 = function (coins, amount, pos, memo) { var key = buildMemoKey(pos, amount); - if(memo[key]) - return memo[key]; - - if(amount < 0) { - return Number.POSITIVE_INFINITY; - } else if(amount == 0) { + if (memo[key]) return memo[key]; + + if (amount < 0) { + return Number.POSITIVE_INFINITY; + } else if (amount == 0) { return 0; - } else if(pos >= coins.length) { + } else if (pos >= coins.length) { return Number.POSITIVE_INFINITY; } - + var left = coinChangeAux2(coins, amount, pos + 1, memo); var middle = 1 + coinChangeAux2(coins, amount - coins[pos], pos + 1, memo); var right = 1 + coinChangeAux2(coins, amount - coins[pos], pos, memo); - + var solution = min(left, middle, right); memo[key] = solution; return solution; -} +}; // Solution 1 naive -var coinChange1 = function(coins, amount) { +var coinChange1 = function (coins, amount) { var solution = coinChangeAux1(coins, amount, 0); return solution == Number.POSITIVE_INFINITY ? -1 : solution; }; -var coinChangeAux1 = function(coins, amount, pos) { - if(amount < 0) { - return Number.POSITIVE_INFINITY; - } else if(amount == 0) { +var coinChangeAux1 = function (coins, amount, pos) { + if (amount < 0) { + return Number.POSITIVE_INFINITY; + } else if (amount == 0) { return 0; - } else if(pos >= coins.length) { + } else if (pos >= coins.length) { return Number.POSITIVE_INFINITY; } - + var left = coinChangeAux1(coins, amount, pos + 1); var middle = 1 + coinChangeAux1(coins, amount - coins[pos], pos + 1); var right = 1 + coinChangeAux1(coins, amount - coins[pos], pos); - + var partialSol = min(left, middle, right); return partialSol; -} +}; -var min = function(a, b, c) { - if(a < b) - return (a < c) ? a : c; - return (b < c) ? b : c; -} +var min = function (a, b, c) { + if (a < b) return a < c ? a : c; + return b < c ? b : c; +}; module.exports.coinChange = coinChange; diff --git a/LeetcodeProblems/Algorithms/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js b/LeetcodeProblems/Algorithms/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js index e92372f..26a67d6 100644 --- a/LeetcodeProblems/Algorithms/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js +++ b/LeetcodeProblems/Algorithms/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js @@ -27,34 +27,57 @@ 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 * @param {number[]} inorder * @return {TreeNode} */ -var buildTree = function(preorder, inorder) { - if(preorder === null || inorder === null || preorder.length !== inorder.length) +var buildTree = function (preorder, inorder) { + if ( + preorder === null || + inorder === null || + preorder.length !== inorder.length + ) return nil; - - return buildTreeAux(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); + + return buildTreeAux( + preorder, + 0, + preorder.length - 1, + inorder, + 0, + inorder.length - 1 + ); }; -var buildTreeAux = function(preorder, pl, ph, inorder, il, ih) { - if(pl > ph || il > ih) - return null; - +var buildTreeAux = function (preorder, pl, ph, inorder, il, ih) { + if (pl > ph || il > ih) return null; + const rootValue = preorder[pl]; var countElementsLeft = 0; - while(inorder[il + countElementsLeft] !== rootValue) - countElementsLeft++; - + while (inorder[il + countElementsLeft] !== rootValue) countElementsLeft++; + var ret = new TreeNode(rootValue); - ret.left = buildTreeAux(preorder, pl + 1, pl + countElementsLeft, inorder, il, il + countElementsLeft - 1); - ret.right = buildTreeAux(preorder, pl + countElementsLeft + 1, ph, inorder, il + countElementsLeft + 1, ih); - + ret.left = buildTreeAux( + preorder, + pl + 1, + pl + countElementsLeft, + inorder, + il, + il + countElementsLeft - 1 + ); + ret.right = buildTreeAux( + preorder, + pl + countElementsLeft + 1, + ph, + inorder, + il + countElementsLeft + 1, + ih + ); + return ret; -} +}; -module.exports.buildTree = buildTree +module.exports.buildTree = buildTree; diff --git a/LeetcodeProblems/Algorithms/Deletion_Distance.js b/LeetcodeProblems/Algorithms/Deletion_Distance.js index 6e7dbd0..aaa8f97 100644 --- a/LeetcodeProblems/Algorithms/Deletion_Distance.js +++ b/LeetcodeProblems/Algorithms/Deletion_Distance.js @@ -20,91 +20,95 @@ output: 0 */ // Solution 3 Using DP -var deletionDistanceDP = function(str1, str2) { - if(str1.length === 0) - return str2.length; - if(str2.length === 0) - return str1.length; +var deletionDistanceDP = function (str1, str2) { + if (str1.length === 0) return str2.length; + if (str2.length === 0) return str1.length; var matrix = []; - for(var i = 0; i <= str1.length; i++) { + for (var i = 0; i <= str1.length; i++) { matrix[i] = []; - for(var j = 0; j <= str2.length; j++) { - if(i === 0) { + for (var j = 0; j <= str2.length; j++) { + if (i === 0) { matrix[i][j] = j; - } else if(j == 0) { + } else if (j == 0) { matrix[i][j] = i; - } else if(str1[i - 1] === str2[j - 1]) { - matrix[i][j] = matrix[i - 1][j - 1]; + } else if (str1[i - 1] === str2[j - 1]) { + matrix[i][j] = matrix[i - 1][j - 1]; } else { matrix[i][j] = 1 + min(matrix[i - 1][j], matrix[i][j - 1]); } } } - + return matrix[str1.length][str2.length]; -} +}; // Solution 2 Using memoization -var deletionDistance2 = function(str1, str2) { +var deletionDistance2 = function (str1, str2) { var memo = {}; return deletionDistanceAux2(str1, str2, 0, 0, memo); -} +}; -var deletionDistanceAux2 = function(str1, str2, pos1, pos2, memo) { +var deletionDistanceAux2 = function (str1, str2, pos1, pos2, memo) { const valueCashed = getValue(pos1, pos2, memo); - if(valueCashed !== undefined) - return valueCashed; + if (valueCashed !== undefined) return valueCashed; var result; - if(str1.length === pos1) - result = str2.length - pos2; - else if(str2.length === pos2) - result = str1.length - pos1; - else if(str1[pos1] === str2[pos2]) + if (str1.length === pos1) result = str2.length - pos2; + else if (str2.length === pos2) result = str1.length - pos1; + else if (str1[pos1] === str2[pos2]) result = deletionDistanceAux2(str1, str2, pos1 + 1, pos2 + 1, memo); - else - result = 1 + min(deletionDistanceAux2(str1, str2, pos1, pos2 + 1, memo), deletionDistanceAux2(str1, str2, pos1 + 1, pos2, memo)) + else + result = + 1 + + min( + deletionDistanceAux2(str1, str2, pos1, pos2 + 1, memo), + deletionDistanceAux2(str1, str2, pos1 + 1, pos2, memo) + ); return setValue(pos1, pos2, result, memo); -} +}; -var getMemoKey = function(pos1, pos2) { +var getMemoKey = function (pos1, pos2) { return pos1 + "-" + pos2; -} +}; -var getValue = function(pos1, pos2, memo) { +var getValue = function (pos1, pos2, memo) { const memoKey = getMemoKey(pos1, pos2); return memo[memoKey]; -} +}; -var setValue = function(pos1, pos2, value, memo) { +var setValue = function (pos1, pos2, value, memo) { const memoKey = getMemoKey(pos1, pos2); memo[memoKey] = value; return value; -} +}; // Solution 1 naive -var deletionDistance = function(str1, str2) { +var deletionDistance = function (str1, str2) { return deletionDistanceAux(str1, str2, 0, 0); -} - -var deletionDistanceAux = function(str1, str2, pos1, pos2) { - if(str1.length === pos1) - return str2.length - pos2; - - if(str2.length === pos2) - return str1.length - pos1; - - if(str1[pos1] === str2[pos2]) - return deletionDistanceAux(str1, str2, pos1 + 1, pos2 + 1); +}; + +var deletionDistanceAux = function (str1, str2, pos1, pos2) { + if (str1.length === pos1) return str2.length - pos2; - return 1 + min(deletionDistanceAux(str1, str2, pos1, pos2 + 1), deletionDistanceAux(str1, str2, pos1 + 1, pos2)); -} + if (str2.length === pos2) return str1.length - pos1; + + if (str1[pos1] === str2[pos2]) + return deletionDistanceAux(str1, str2, pos1 + 1, pos2 + 1); -var min = function(a, b) { - return (a < b) ? a : b; -} + return ( + 1 + + min( + deletionDistanceAux(str1, str2, pos1, pos2 + 1), + deletionDistanceAux(str1, str2, pos1 + 1, pos2) + ) + ); +}; + +var min = function (a, b) { + return a < b ? a : b; +}; module.exports.deletionDistance = deletionDistance; module.exports.deletionDistance2 = deletionDistance2; diff --git a/LeetcodeProblems/Algorithms/Design_Circular_Deque.js b/LeetcodeProblems/Algorithms/Design_Circular_Deque.js index df6a123..78aae78 100644 --- a/LeetcodeProblems/Algorithms/Design_Circular_Deque.js +++ b/LeetcodeProblems/Algorithms/Design_Circular_Deque.js @@ -40,94 +40,88 @@ Please do not use the built-in Deque library. * Initialize your data structure here. Set the size of the deque to be k. * @param {number} k */ -var MyCircularDeque = function(k) { +var MyCircularDeque = function (k) { this.queue = []; this.maxSize = k; }; /** -* Adds an item at the front of Deque. Return true if the operation is successful. -* @param {number} value -* @return {boolean} -*/ -MyCircularDeque.prototype.insertFront = function(value) { - if(this.isFull()) - return false; - - this.queue.unshift(value); + * Adds an item at the front of Deque. Return true if the operation is successful. + * @param {number} value + * @return {boolean} + */ +MyCircularDeque.prototype.insertFront = function (value) { + if (this.isFull()) return false; + + this.queue.unshift(value); return true; }; /** -* Adds an item at the rear of Deque. Return true if the operation is successful. -* @param {number} value -* @return {boolean} -*/ -MyCircularDeque.prototype.insertLast = function(value) { - if(this.isFull()) - return false; - + * Adds an item at the rear of Deque. Return true if the operation is successful. + * @param {number} value + * @return {boolean} + */ +MyCircularDeque.prototype.insertLast = function (value) { + if (this.isFull()) return false; + this.queue[this.queue.length] = value; return true; }; /** -* Deletes an item from the front of Deque. Return true if the operation is successful. -* @return {boolean} -*/ -MyCircularDeque.prototype.deleteFront = function() { - if(this.isEmpty()) - return false; - + * Deletes an item from the front of Deque. Return true if the operation is successful. + * @return {boolean} + */ +MyCircularDeque.prototype.deleteFront = function () { + if (this.isEmpty()) return false; + this.queue.shift(1); return true; }; /** -* Deletes an item from the rear of Deque. Return true if the operation is successful. -* @return {boolean} -*/ -MyCircularDeque.prototype.deleteLast = function() { - if(this.isEmpty()) - return false; - + * Deletes an item from the rear of Deque. Return true if the operation is successful. + * @return {boolean} + */ +MyCircularDeque.prototype.deleteLast = function () { + if (this.isEmpty()) return false; + this.queue.splice(this.queue.length - 1, 1); return true; }; /** -* Get the front item from the deque. -* @return {number} -*/ -MyCircularDeque.prototype.getFront = function() { - if(this.isEmpty()) - return -1; + * Get the front item from the deque. + * @return {number} + */ +MyCircularDeque.prototype.getFront = function () { + if (this.isEmpty()) return -1; return this.queue[0]; }; /** -* Get the last item from the deque. -* @return {number} -*/ -MyCircularDeque.prototype.getRear = function() { - if(this.isEmpty()) - return -1; + * Get the last item from the deque. + * @return {number} + */ +MyCircularDeque.prototype.getRear = function () { + if (this.isEmpty()) return -1; return this.queue[this.queue.length - 1]; }; /** -* Checks whether the circular deque is empty or not. -* @return {boolean} -*/ -MyCircularDeque.prototype.isEmpty = function() { + * Checks whether the circular deque is empty or not. + * @return {boolean} + */ +MyCircularDeque.prototype.isEmpty = function () { return this.queue.length === 0; }; /** -* Checks whether the circular deque is full or not. -* @return {boolean} -*/ -MyCircularDeque.prototype.isFull = function() { + * Checks whether the circular deque is full or not. + * @return {boolean} + */ +MyCircularDeque.prototype.isFull = function () { return this.queue.length === this.maxSize; }; diff --git a/LeetcodeProblems/Algorithms/Edit_Distance.js b/LeetcodeProblems/Algorithms/Edit_Distance.js index 73d4e47..771ee94 100644 --- a/LeetcodeProblems/Algorithms/Edit_Distance.js +++ b/LeetcodeProblems/Algorithms/Edit_Distance.js @@ -30,72 +30,71 @@ exection -> execution (insert 'u') */ // Optimal solution -var minDistance = function(word1, word2) { +var minDistance = function (word1, word2) { var matrix = []; - for(var i = 0; i <= word1.length; i++) { + for (var i = 0; i <= word1.length; i++) { matrix[i] = []; - for(var j = 0; j <= word2.length; j++) { - if(i === 0) - matrix[i][j] = j; - else if(j === 0) - matrix[i][j] = i; - else - matrix[i][j] = 0; + for (var j = 0; j <= word2.length; j++) { + if (i === 0) matrix[i][j] = j; + else if (j === 0) matrix[i][j] = i; + else matrix[i][j] = 0; } - }; - - for(var i = 1; i <= word1.length; i++) { - for(var j = 1; j <= word2.length; j++) { - if(word1.charAt(i - 1) === word2.charAt(j - 1)) { + } + + for (var i = 1; i <= word1.length; i++) { + for (var j = 1; j <= word2.length; j++) { + if (word1.charAt(i - 1) === word2.charAt(j - 1)) { matrix[i][j] = matrix[i - 1][j - 1]; } else { - matrix[i][j] = 1 + min( - matrix[i - 1][j - 1], - matrix[i - 1][j], // add - matrix[i][j - 1] // remove - ); + matrix[i][j] = + 1 + + min( + matrix[i - 1][j - 1], + matrix[i - 1][j], // add + matrix[i][j - 1] // remove + ); } } } - + return matrix[word1.length][word2.length]; }; -var min = function(a, b, c) { - if(a < b) { - return (a < c) ? a : c; +var min = function (a, b, c) { + if (a < b) { + return a < c ? a : c; } - return (b < c) ? b : c; -} + return b < c ? b : c; +}; //Solution 2 -var minDistance2 = function(word1, word2) { +var minDistance2 = function (word1, word2) { return minDistanceAux(word1, word2, 0, 0); -} - -var minDistanceAux = function(word1, word2, iter1, iter2) { - if(word1.length === iter1) - return word2.length - iter2; - - if(word2.length === iter2) - return word1.length - iter1; - - if(word1.charAt(iter1) === word2.charAt(iter2)) +}; + +var minDistanceAux = function (word1, word2, iter1, iter2) { + if (word1.length === iter1) return word2.length - iter2; + + if (word2.length === iter2) return word1.length - iter1; + + if (word1.charAt(iter1) === word2.charAt(iter2)) return minDistanceAux(word1, word2, iter1 + 1, iter2 + 1); - - return 1 + min( - minDistanceAux(word1, word2, iter1 + 1, iter2 + 1), - minDistanceAux(word1, word2, iter1, iter2 + 1), // add - minDistanceAux(word1, word2, iter1 + 1, iter2 ) // delete - ) + + return ( + 1 + + min( + minDistanceAux(word1, word2, iter1 + 1, iter2 + 1), + minDistanceAux(word1, word2, iter1, iter2 + 1), // add + minDistanceAux(word1, word2, iter1 + 1, iter2) // delete + ) + ); }; -var min = function(a, b, c) { - if(a < b) - return (a < c) ? a : c; - - return (b < c) ? b : c; -} +var min = function (a, b, c) { + if (a < b) return a < c ? a : c; + + return b < c ? b : c; +}; module.exports.minDistance = minDistance; module.exports.minDistance2 = minDistance2; diff --git a/LeetcodeProblems/Algorithms/Escape_The_Ghosts.js b/LeetcodeProblems/Algorithms/Escape_The_Ghosts.js index 06c5a53..ca30a52 100644 --- a/LeetcodeProblems/Algorithms/Escape_The_Ghosts.js +++ b/LeetcodeProblems/Algorithms/Escape_The_Ghosts.js @@ -42,21 +42,20 @@ The number of ghosts will not exceed 100. * @param {number[]} target * @return {boolean} */ -var escapeGhosts = function(ghosts, target) { - var distancePacman = getDistance([0,0], target); - for(ghost in ghosts) { +var escapeGhosts = function (ghosts, target) { + var distancePacman = getDistance([0, 0], target); + for (ghost in ghosts) { const distanceGhost = getDistance(ghosts[ghost], target); - if(distancePacman > distanceGhost) - return false + if (distancePacman > distanceGhost) return false; } - + return true; }; -var getDistance = function(a, b) { +var getDistance = function (a, b) { const horizontalMoves = Math.abs(a[0] - b[0]); const verticalMoves = Math.abs(a[1] - b[1]); return horizontalMoves + verticalMoves; -} +}; module.exports.escapeGhosts = escapeGhosts; diff --git a/LeetcodeProblems/Algorithms/Flood_Fill.js b/LeetcodeProblems/Algorithms/Flood_Fill.js index 93ee923..226ebcf 100644 --- a/LeetcodeProblems/Algorithms/Flood_Fill.js +++ b/LeetcodeProblems/Algorithms/Flood_Fill.js @@ -29,26 +29,25 @@ The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image The value of each color in image[i][j] and newColor will be an integer in [0, 65535]. */ -var floodFill = function(image, sr, sc, newColor) { +var floodFill = function (image, sr, sc, newColor) { var oldColor = image[sr][sc]; - - if(newColor == oldColor) - return image; - + + if (newColor == oldColor) return image; + image[sr][sc] = newColor; - - if(sr > 0 && image[sr - 1][sc] == oldColor) + + if (sr > 0 && image[sr - 1][sc] == oldColor) floodFill(image, sr - 1, sc, newColor); //Left - - if(sc > 0 && image[sr][sc - 1] == oldColor) + + if (sc > 0 && image[sr][sc - 1] == oldColor) floodFill(image, sr, sc - 1, newColor); //Up - if(sr < image.length - 1 && image[sr + 1][sc] == oldColor) + if (sr < image.length - 1 && image[sr + 1][sc] == oldColor) floodFill(image, sr + 1, sc, newColor); //Down - - if(sc < image[0].length - 1 && image[sr][sc + 1] == oldColor) + + if (sc < image[0].length - 1 && image[sr][sc + 1] == oldColor) floodFill(image, sr, sc + 1, newColor); // Right - + return image; }; diff --git a/LeetcodeProblems/Algorithms/Generate_Parenthesis.js b/LeetcodeProblems/Algorithms/Generate_Parenthesis.js index 2ee7df5..a84103f 100644 --- a/LeetcodeProblems/Algorithms/Generate_Parenthesis.js +++ b/LeetcodeProblems/Algorithms/Generate_Parenthesis.js @@ -16,65 +16,81 @@ For example, given n = 3, a solution set is: */ // ************************************************ Approach1 ************************************************ -var generateParenthesisApproach1 = function(n) { - if(n === 0) - return []; +var generateParenthesisApproach1 = function (n) { + if (n === 0) return []; var str = "(".repeat(n); - sol = []; - - genParAux(str, 0, 0, sol) + sol = []; + + genParAux(str, 0, 0, sol); return sol; }; -var genParAux = function(str, position, leftParentheses, sol) { - if(position === str.length) { +var genParAux = function (str, position, leftParentheses, sol) { + if (position === str.length) { var ret = str + ")".repeat(leftParentheses); sol.push(ret); return; } genParAux(str, position + 1, leftParentheses + 1, sol); // Don't insert anything - if(leftParentheses === 0) - return; + if (leftParentheses === 0) return; - for(var i = 1; i <= leftParentheses; i++) { + for (var i = 1; i <= leftParentheses; i++) { var parString = ")".repeat(i); var partSol = str.slice(0, position) + parString + str.slice(position); // Insert i parentheses in the position genParAux(partSol, position + i + 1, leftParentheses - i + 1, sol); - } -} + } +}; // ************************************************ Approach2 ************************************************ -var generateParenthesisApproach2 = function(n) { - if(n === 0) - return []; +var generateParenthesisApproach2 = function (n) { + if (n === 0) return []; var sol = []; - genParAuxApproach2("", 0, 0, 0, n * 2, sol) + genParAuxApproach2("", 0, 0, 0, n * 2, sol); return sol; -} +}; + +var genParAuxApproach2 = function ( + str, + leftPar, + rightPar, + index, + totalCharCount, + sol +) { + if (index === totalCharCount) { + if (rightPar === leftPar) sol.push(str); -var genParAuxApproach2 = function(str, leftPar, rightPar, index, totalCharCount, sol) { - if(index === totalCharCount) { - if(rightPar === leftPar) - sol.push(str); - return; } var strLeft = insertAt(str, index, "("); - genParAuxApproach2(strLeft, leftPar + 1, rightPar, index + 1, totalCharCount, sol); + genParAuxApproach2( + strLeft, + leftPar + 1, + rightPar, + index + 1, + totalCharCount, + sol + ); + + if (rightPar === leftPar) return; - if(rightPar === leftPar) - return; - var strRight = insertAt(str, index, ")"); - genParAuxApproach2(strRight, leftPar, rightPar + 1, index + 1, totalCharCount, sol); -} + genParAuxApproach2( + strRight, + leftPar, + rightPar + 1, + index + 1, + totalCharCount, + sol + ); +}; -var insertAt = function(str, position, value) { +var insertAt = function (str, position, value) { return str.slice(0, position) + value + str.slice(position); -} +}; module.exports.generateParenthesisApproach2 = generateParenthesisApproach2; diff --git a/LeetcodeProblems/Algorithms/Group_Anagrams.js b/LeetcodeProblems/Algorithms/Group_Anagrams.js index b205bb2..eb5a0e0 100644 --- a/LeetcodeProblems/Algorithms/Group_Anagrams.js +++ b/LeetcodeProblems/Algorithms/Group_Anagrams.js @@ -19,32 +19,29 @@ All inputs will be in lowercase. The order of your output does not matter. */ -var groupAnagrams = function(strs) { +var groupAnagrams = function (strs) { var ret = []; var hashMap = {}; - for(var i = 0; i < strs.length; i++) { + for (var i = 0; i < strs.length; i++) { const elem = strs[i]; const elemSorted = sortString(strs[i]); - - if(hashMap[elemSorted]) { + + if (hashMap[elemSorted]) { hashMap[elemSorted].push(elem); } else { hashMap[elemSorted] = [elem]; } } - for(key in hashMap) - ret.push(hashMap[key]); - + for (key in hashMap) ret.push(hashMap[key]); return ret; }; -var sortString = function(str) { - if(str.length === 0) - return str; - +var sortString = function (str) { + if (str.length === 0) return str; + return str.split("").sort().join(""); -} +}; module.exports.groupAnagrams = groupAnagrams; diff --git a/LeetcodeProblems/Algorithms/Implement_stack_using_queues.js b/LeetcodeProblems/Algorithms/Implement_stack_using_queues.js index a604cf2..efc3ea9 100644 --- a/LeetcodeProblems/Algorithms/Implement_stack_using_queues.js +++ b/LeetcodeProblems/Algorithms/Implement_stack_using_queues.js @@ -24,44 +24,42 @@ Depending on your language, queue may not be supported natively. You may simulat You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack). */ -class MyStack { +class MyStack { constructor() { this.q1 = []; this.q2 = []; - }; + } push(elem) { - if(this.q1.length > 0) { + if (this.q1.length > 0) { this.q1.push(elem); } else { - this.q2.push(elem); + this.q2.push(elem); } - }; + } pop() { - if(this.q1.length === 0 && this.q2.length === 0) - return null; + if (this.q1.length === 0 && this.q2.length === 0) return null; - if(this.q1.length > 0) { - while(this.q1.length > 1) { + if (this.q1.length > 0) { + while (this.q1.length > 1) { var elem = this.q1.shift(); this.q2.push(elem); } return this.q1.shift(); } else { - while(this.q2.length > 1) { + while (this.q2.length > 1) { var elem = this.q2.shift(); this.q1.push(elem); } return this.q2.shift(); } - }; + } top() { - if(this.q1.length === 0 && this.q2.length === 0) - return null; + if (this.q1.length === 0 && this.q2.length === 0) return null; - if(this.q1.length > 0) { + if (this.q1.length > 0) { var elem = this.pop(); this.q2.push(elem); return elem; @@ -70,11 +68,11 @@ class MyStack { this.q1.push(elem); return elem; } - }; + } empty() { return this.q1.length == 0 && this.q2.length === 0; - }; + } } -module.exports.MyStack = MyStack; \ No newline at end of file +module.exports.MyStack = MyStack; diff --git a/LeetcodeProblems/Algorithms/Kth_Largest_Element_in_an_Array.js b/LeetcodeProblems/Algorithms/Kth_Largest_Element_in_an_Array.js index 3f669b5..e2acb89 100644 --- a/LeetcodeProblems/Algorithms/Kth_Largest_Element_in_an_Array.js +++ b/LeetcodeProblems/Algorithms/Kth_Largest_Element_in_an_Array.js @@ -16,45 +16,43 @@ Note: You may assume k is always valid, 1 ≤ k ≤ array's length. */ - /** * @param {number[]} nums * @param {number} k * @return {number} */ -var findKthLargest = function(nums, k) { - for(var i = Math.floor(nums.length/2) - 1; i >= 0; i--) { +var findKthLargest = function (nums, k) { + for (var i = Math.floor(nums.length / 2) - 1; i >= 0; i--) { heapify(nums, nums.length, i); } - - for(var i = nums.length -1; i >= nums.length - k - 1 && i >= 0; i--) { + + for (var i = nums.length - 1; i >= nums.length - k - 1 && i >= 0; i--) { swap(nums, 0, i); heapify(nums, i, 0); } - + return nums[nums.length - k]; -} +}; -var heapify = function(nums, length, i) { +var heapify = function (nums, length, i) { var left = 2 * i + 1; var right = 2 * i + 2; - - if(left >= length) - return; - - if(nums[i] < nums[left] && (right >= length || nums[left] > nums[right])) { + + if (left >= length) return; + + if (nums[i] < nums[left] && (right >= length || nums[left] > nums[right])) { swap(nums, left, i); heapify(nums, length, left); - } else if(right < length && nums[right] > nums[i]) { - swap(nums, right, i) - heapify(nums, length, right) + } else if (right < length && nums[right] > nums[i]) { + swap(nums, right, i); + heapify(nums, length, right); } -} +}; -var swap = function(nums, a, b) { +var swap = function (nums, a, b) { const temp = nums[a]; nums[a] = nums[b]; nums[b] = temp; -} +}; module.exports.findKthLargest = findKthLargest; diff --git a/LeetcodeProblems/Algorithms/Linked_List_Cycle_II.js b/LeetcodeProblems/Algorithms/Linked_List_Cycle_II.js index 1a207af..01bee95 100644 --- a/LeetcodeProblems/Algorithms/Linked_List_Cycle_II.js +++ b/LeetcodeProblems/Algorithms/Linked_List_Cycle_II.js @@ -10,27 +10,26 @@ Follow up: Can you solve it without using extra space? */ -var ListNode = require('../../UtilsClasses/ListNode').ListNode; +var ListNode = require("../../UtilsClasses/ListNode").ListNode; // Optimal solution /** -* @param {ListNode} head -* @return {ListNode} -*/ -var detectCycle = function(head) { - if (head === null) - return null; + * @param {ListNode} head + * @return {ListNode} + */ +var detectCycle = function (head) { + if (head === null) return null; var slow = head; var fast = head; - while(fast.next !== null && fast.next.next !== null) { + while (fast.next !== null && fast.next.next !== null) { slow = slow.next; fast = fast.next.next; - if(fast == slow) { + if (fast == slow) { var a = head; var b = slow; - while(a !== b) { + while (a !== b) { a = a.next; b = b.next; } @@ -41,18 +40,18 @@ var detectCycle = function(head) { }; // Naiver solution using a Set -var detectCycle2 = function(head) { - if(head === null || head.next === null) { +var detectCycle2 = function (head) { + if (head === null || head.next === null) { return null; } var setNodes = new Set(); var iter = head; - while(iter !== null) { - if(setNodes.has(iter)) { + while (iter !== null) { + if (setNodes.has(iter)) { return iter; } setNodes.add(iter); - iter = iter.next + iter = iter.next; } return null; }; diff --git a/LeetcodeProblems/Algorithms/Longest_Consecutive_Sequence.js b/LeetcodeProblems/Algorithms/Longest_Consecutive_Sequence.js index 0381cbb..de06709 100644 --- a/LeetcodeProblems/Algorithms/Longest_Consecutive_Sequence.js +++ b/LeetcodeProblems/Algorithms/Longest_Consecutive_Sequence.js @@ -17,36 +17,33 @@ Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefor * @param {number[]} nums * @return {number} */ -var longestConsecutive = function(nums) { - if(nums.length === 0) - return 0; +var longestConsecutive = function (nums) { + if (nums.length === 0) return 0; var setNums = new Set(); - for(var i = 0; i < nums.length; i++) - setNums.add(nums[i]); - + for (var i = 0; i < nums.length; i++) setNums.add(nums[i]); + var cons = 1; var currentCons = 1; - for(var i = 0; i < nums.length; i++) { + for (var i = 0; i < nums.length; i++) { var number = nums[i]; - if(setNums.has(number)) { + if (setNums.has(number)) { setNums.delete(number); - + var prevNum = number - 1; - while(setNums.has(prevNum)){ + while (setNums.has(prevNum)) { currentCons++; setNums.delete(prevNum); prevNum--; } - + var nextNum = number + 1; - while(setNums.has(nextNum)){ + while (setNums.has(nextNum)) { currentCons++; setNums.delete(nextNum); nextNum++; } - - if(currentCons > cons) - cons = currentCons + + if (currentCons > cons) cons = currentCons; } currentCons = 1; } diff --git a/LeetcodeProblems/Algorithms/Longest_Palindromic_Substring.js b/LeetcodeProblems/Algorithms/Longest_Palindromic_Substring.js index 8c32bec..3cdf567 100644 --- a/LeetcodeProblems/Algorithms/Longest_Palindromic_Substring.js +++ b/LeetcodeProblems/Algorithms/Longest_Palindromic_Substring.js @@ -19,48 +19,55 @@ Output: "bb" * @param {string} s * @return {string} */ -var longestPalindrome = function(str) { - if(str.length == 0) - return ""; - - var maxPal = 1; - var posPalStart = 0; +var longestPalindrome = function (str) { + if (str.length == 0) return ""; + + var maxPal = 1; + var posPalStart = 0; var currentPalStart = 0; - for(var i = 1; i < str.length; i++) { - if(str.charAt(i - 1) == str.charAt(i)) { + for (var i = 1; i < str.length; i++) { + if (str.charAt(i - 1) == str.charAt(i)) { currentPalStart = i - 1; - var currentPal = 2; + var currentPal = 2; var iter = 1; - while(i - iter - 1 >= 0 && i + iter < str.length && str.charAt(i - iter - 1) == str.charAt(i + iter)) { + while ( + i - iter - 1 >= 0 && + i + iter < str.length && + str.charAt(i - iter - 1) == str.charAt(i + iter) + ) { currentPalStart = i - iter - 1; iter++; currentPal += 2; } - } - if(currentPal > maxPal) { + } + if (currentPal > maxPal) { maxPal = currentPal; posPalStart = currentPalStart; } } - - for(var i = 1; i < str.length - 1; i++) { - if(str.charAt(i - 1) == str.charAt(i + 1)) { + + for (var i = 1; i < str.length - 1; i++) { + if (str.charAt(i - 1) == str.charAt(i + 1)) { currentPal = 1; var iter = 1; - while(i - iter >= 0 && i + iter < str.length && str.charAt(i - iter) == str.charAt(i + iter)) { + while ( + i - iter >= 0 && + i + iter < str.length && + str.charAt(i - iter) == str.charAt(i + iter) + ) { currentPalStart = i - iter; iter++; currentPal += 2; } } - if(currentPal > maxPal) { + if (currentPal > maxPal) { maxPal = currentPal; posPalStart = currentPalStart; } } - + return str.slice(posPalStart, posPalStart + maxPal); -} +}; -module.exports.longestPalindrome = longestPalindrome +module.exports.longestPalindrome = longestPalindrome; diff --git a/LeetcodeProblems/Algorithms/Lowest_Common_Ancestor_of_a_Binary_Tree.js b/LeetcodeProblems/Algorithms/Lowest_Common_Ancestor_of_a_Binary_Tree.js index d4ccd11..8aa9a49 100644 --- a/LeetcodeProblems/Algorithms/Lowest_Common_Ancestor_of_a_Binary_Tree.js +++ b/LeetcodeProblems/Algorithms/Lowest_Common_Ancestor_of_a_Binary_Tree.js @@ -34,64 +34,58 @@ All of the nodes' values will be unique. p and q are different and both values will exist in the binary tree. */ - -var TreeNode = require('../../UtilsClasses/TreeNode').TreeNode; +var TreeNode = require("../../UtilsClasses/TreeNode").TreeNode; // Solution 1 -var lowestCommonAncestor = function(root, p, q) { - if(root === null) - return root; - if(p.val === root.val) - return p; - if(q.val === root.val) - return q; +var lowestCommonAncestor = function (root, p, q) { + if (root === null) return root; + if (p.val === root.val) return p; + if (q.val === root.val) return q; const left = lowestCommonAncestor(root.left, p, q); const right = lowestCommonAncestor(root.right, p, q); - if(left !== null && right !== null) - return root; + if (left !== null && right !== null) return root; return left !== null ? left : right; }; // Solution 2 -var lowestCommonAncestor2 = function(root, p, q) { +var lowestCommonAncestor2 = function (root, p, q) { var pathToP = pathTo(root, p.val); var pathToQ = pathTo(root, q.val); - if(pathToP.length === 0 || pathToQ === 0) - return null; + if (pathToP.length === 0 || pathToQ === 0) return null; var iter = 0; - while(iter < pathToP.length - 1 && iter < pathToQ.length - 1 && pathToP[iter + 1] === pathToQ[iter + 1]) { - if(root.left !== null && root.left.val === pathToP[iter + 1]) { - root = root.left; + while ( + iter < pathToP.length - 1 && + iter < pathToQ.length - 1 && + pathToP[iter + 1] === pathToQ[iter + 1] + ) { + if (root.left !== null && root.left.val === pathToP[iter + 1]) { + root = root.left; } else { - root = root.right; + root = root.right; } iter++; } - + return root; }; -var pathTo = function(root, value) { - if(root === null) - return []; - +var pathTo = function (root, value) { + if (root === null) return []; + var list = [root.val]; - if(root.val === value) - return list; + if (root.val === value) return list; const left = pathTo(root.left, value); - if (left.length > 0) - return list.concat(left); + if (left.length > 0) return list.concat(left); + + const right = pathTo(root.right, value); + if (right.length > 0) return list.concat(right); - const right = pathTo(root.right, value); - if(right.length > 0) - return list.concat(right); - return []; -} +}; module.exports.lowestCommonAncestor = lowestCommonAncestor; module.exports.lowestCommonAncestor2 = lowestCommonAncestor2; diff --git a/LeetcodeProblems/Algorithms/Majority_Element.js b/LeetcodeProblems/Algorithms/Majority_Element.js index 3b48dda..fd5b62d 100644 --- a/LeetcodeProblems/Algorithms/Majority_Element.js +++ b/LeetcodeProblems/Algorithms/Majority_Element.js @@ -18,30 +18,27 @@ Output: 2 Note: You should have a better solution than O(N) */ - /** * @param {number[]} nums * @return {number} */ -var majorityElement = function(nums) { - if(nums.length === 0) - return -1; - +var majorityElement = function (nums) { + if (nums.length === 0) return -1; + var candidate = nums[0]; var proves = 1; - - for(var i = 1; i < nums.length; i++) { - if(nums[i] === candidate) - proves++; + + for (var i = 1; i < nums.length; i++) { + if (nums[i] === candidate) proves++; else { proves--; - if(proves === 0) { + if (proves === 0) { candidate = nums[i]; proves = 1; } } } - + return candidate; }; diff --git a/LeetcodeProblems/Algorithms/Max_Area_Of_Island.js b/LeetcodeProblems/Algorithms/Max_Area_Of_Island.js index 32c82a2..65d171a 100644 --- a/LeetcodeProblems/Algorithms/Max_Area_Of_Island.js +++ b/LeetcodeProblems/Algorithms/Max_Area_Of_Island.js @@ -27,26 +27,37 @@ Note: The length of each dimension in the given grid does not exceed 50. * @param {number[][]} grid * @return {number} */ -var maxAreaOfIsland = function(grid) { +var maxAreaOfIsland = function (grid) { var maxArea = 0; - for(var i = 0; i < grid.length; i++) { - for(var j = 0; j < grid[0].length; j++) { - maxArea = Math.max(markIsland(i, j, grid), maxArea); - } + for (var i = 0; i < grid.length; i++) { + for (var j = 0; j < grid[0].length; j++) { + maxArea = Math.max(markIsland(i, j, grid), maxArea); + } } return maxArea; }; -var markIsland = function(row, col, grid) { - if(row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] == 0) { - return 0; +var markIsland = function (row, col, grid) { + if ( + row < 0 || + row >= grid.length || + col < 0 || + col >= grid[0].length || + grid[row][col] == 0 + ) { + return 0; } grid[row][col] = 0; - return 1 + markIsland(row + 1, col, grid) + markIsland(row - 1, col, grid) - + markIsland(row, col +1, grid) + markIsland(row, col - 1, grid); -} + return ( + 1 + + markIsland(row + 1, col, grid) + + markIsland(row - 1, col, grid) + + markIsland(row, col + 1, grid) + + markIsland(row, col - 1, grid) + ); +}; module.exports.maxAreaOfIsland = maxAreaOfIsland; diff --git a/LeetcodeProblems/Algorithms/Maximal_Square.js b/LeetcodeProblems/Algorithms/Maximal_Square.js index b0a45fc..6801298 100644 --- a/LeetcodeProblems/Algorithms/Maximal_Square.js +++ b/LeetcodeProblems/Algorithms/Maximal_Square.js @@ -16,53 +16,51 @@ Input: Output: 4 */ - /** * @param {character[][]} matrix * @return {number} */ -var maximalSquare = function(matrix) { +var maximalSquare = function (matrix) { var maxSquare = 0; - for(var i = 0; i < matrix.length; i++) { - for(var j = 0; j < matrix[0].length; j++) { - if(matrix[i][j] === "1") { // found a 1 + for (var i = 0; i < matrix.length; i++) { + for (var j = 0; j < matrix[0].length; j++) { + if (matrix[i][j] === "1") { + // found a 1 const currentMaxSideLength = getCurrentMaxSideLength(matrix, i, j); - if(currentMaxSideLength ** 2 > maxSquare) + if (currentMaxSideLength ** 2 > maxSquare) maxSquare = currentMaxSideLength ** 2; - } + } } } - + return maxSquare; }; -var getCurrentMaxSideLength = function(matrix, i, j) { +var getCurrentMaxSideLength = function (matrix, i, j) { var max = 1; - while(i + max < matrix.length && j + max < matrix[0].length) { + while (i + max < matrix.length && j + max < matrix[0].length) { var lastRow = i + max; var lastCol = j + max; - + // check last column - var iterRow = i; - while(iterRow <= lastRow){ - if(matrix[iterRow][lastCol] === "0") - return max; - + var iterRow = i; + while (iterRow <= lastRow) { + if (matrix[iterRow][lastCol] === "0") return max; + iterRow++; } - + // check last row var iterCol = j; - while(iterCol <= lastCol) { - if(matrix[lastRow][iterCol] === "0") - return max; + while (iterCol <= lastCol) { + if (matrix[lastRow][iterCol] === "0") return max; iterCol++; } - + max++; } - + return max; -} +}; module.exports.maximalSquare = maximalSquare; diff --git a/LeetcodeProblems/Algorithms/Maximun_Subarray.js b/LeetcodeProblems/Algorithms/Maximun_Subarray.js index b05309c..9935bab 100644 --- a/LeetcodeProblems/Algorithms/Maximun_Subarray.js +++ b/LeetcodeProblems/Algorithms/Maximun_Subarray.js @@ -14,24 +14,21 @@ Follow up: */ - -var maxSubArray = function(nums) { - if(nums.length == 0) - return 0; +var maxSubArray = function (nums) { + if (nums.length == 0) return 0; var maxSub = nums[0]; var currentMax = nums[0]; - - for(var i = 1; i < nums.length; i++) { + + for (var i = 1; i < nums.length; i++) { currentMax = max(nums[i], currentMax + nums[i]); - if(currentMax > maxSub) - maxSub = currentMax; + if (currentMax > maxSub) maxSub = currentMax; } return maxSub; }; -var max = function(i, j) { - return (i > j) ? i : j; -} +var max = function (i, j) { + return i > j ? i : j; +}; module.exports.maxSubArray = maxSubArray; diff --git a/LeetcodeProblems/Algorithms/Min_Stack.js b/LeetcodeProblems/Algorithms/Min_Stack.js index 0ee04fc..5bd592a 100644 --- a/LeetcodeProblems/Algorithms/Min_Stack.js +++ b/LeetcodeProblems/Algorithms/Min_Stack.js @@ -20,7 +20,6 @@ minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2. */ - class MinStack { constructor() { this.minStack = []; @@ -30,47 +29,40 @@ class MinStack { } push(value) { - if(this.countStack === this.stack.length) - this.stack.push(value); - else - this.stack[this.countStack] = value; + if (this.countStack === this.stack.length) this.stack.push(value); + else this.stack[this.countStack] = value; this.countStack++; - + const min = this.getMin(); - if(min === null || min >= value) { - if(this.countMinStack === this.minStack.length) + if (min === null || min >= value) { + if (this.countMinStack === this.minStack.length) this.minStack.push(value); - else - this.minStack[this.countMinStack] = value; + else this.minStack[this.countMinStack] = value; this.countMinStack++; } } pop() { - if(this.countStack === 0) - return null; + if (this.countStack === 0) return null; var elem = this.stack[this.countStack - 1]; this.countStack--; - - if(elem === this.minStack[this.countMinStack - 1]) - this.countMinStack--; + + if (elem === this.minStack[this.countMinStack - 1]) this.countMinStack--; return elem; } top() { - if(this.countStack === 0) - return null; - + if (this.countStack === 0) return null; + return this.stack[this.countStack - 1]; } getMin() { - if(this.countMinStack === 0) - return null; + if (this.countMinStack === 0) return null; - return this.minStack[this.countMinStack - 1] + return this.minStack[this.countMinStack - 1]; } } diff --git a/LeetcodeProblems/Algorithms/Minimum_Window_Substring.js b/LeetcodeProblems/Algorithms/Minimum_Window_Substring.js index 24beeab..1658deb 100644 --- a/LeetcodeProblems/Algorithms/Minimum_Window_Substring.js +++ b/LeetcodeProblems/Algorithms/Minimum_Window_Substring.js @@ -15,31 +15,34 @@ If there is no such window in S that covers all characters in T, return the empt If there is such window, you are guaranteed that there will always be only one unique minimum window in S. */ +var minWindow = function (s, t) { + if (t.length === 0 || s.length < t.length) return ""; -var minWindow = function(s, t) { - if(t.length === 0 || s.length < t.length) - return ""; - var start = 0; var end = 0; var solutionStart, solutionEnd; var hashT = getHash(t); var currentHash = {}; var currentCount = 0; - while(end < s.length) { + while (end < s.length) { const letter = s.charAt(end); - if(hashT[letter]) { - currentHash[letter] = (currentHash[letter]) ? currentHash[letter] + 1 : 1; - if(currentHash[letter] <= hashT[letter]) - currentCount++; - if(currentCount === t.length) { - while(hashT[s[start]] === undefined || currentHash[s[start]] > hashT[s[start]]) { - if(currentHash[s[start]] !== undefined) + if (hashT[letter]) { + currentHash[letter] = currentHash[letter] ? currentHash[letter] + 1 : 1; + if (currentHash[letter] <= hashT[letter]) currentCount++; + if (currentCount === t.length) { + while ( + hashT[s[start]] === undefined || + currentHash[s[start]] > hashT[s[start]] + ) { + if (currentHash[s[start]] !== undefined) currentHash[s[start]] = currentHash[s[start]] - 1; - + start++; } - if(solutionEnd === undefined || end - start < solutionEnd - solutionStart) { + if ( + solutionEnd === undefined || + end - start < solutionEnd - solutionStart + ) { solutionStart = start; solutionEnd = end; } @@ -51,17 +54,17 @@ var minWindow = function(s, t) { } end++; } - + return s.slice(solutionStart, solutionEnd + 1); -}; +}; -var getHash = function(t) { +var getHash = function (t) { var hash = {}; - for(var i = 0; i < t.length; i++) { + for (var i = 0; i < t.length; i++) { const letter = t.charAt(i); - hash[letter] = (hash[letter]) ? hash[letter] + 1 : 1; + hash[letter] = hash[letter] ? hash[letter] + 1 : 1; } return hash; -} +}; module.exports.minWindow = minWindow; diff --git a/LeetcodeProblems/Algorithms/NQueens.js b/LeetcodeProblems/Algorithms/NQueens.js index 2f2674f..d416e9f 100644 --- a/LeetcodeProblems/Algorithms/NQueens.js +++ b/LeetcodeProblems/Algorithms/NQueens.js @@ -17,50 +17,69 @@ Output: [ ".Q.."] ] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above. -*/ - +*/ /** * @param {number} n * @return {string[][]} */ -var solveNQueens = function(n) { +var solveNQueens = function (n) { var sol = []; solveNQueensAux(n, 0, new Set(), new Set(), new Set(), [], sol); return parseSolutions(sol, n); }; -var solveNQueensAux = function(n, row, diagonalDiffs, diagonalSums, cols, currentSol, sol) { - if(row == n) { - sol.push(currentSol); - return; +var solveNQueensAux = function ( + n, + row, + diagonalDiffs, + diagonalSums, + cols, + currentSol, + sol +) { + if (row == n) { + sol.push(currentSol); + return; } - - for(var i = 0; i < n; i++) { + + for (var i = 0; i < n; i++) { const diagonalDiff = i - row; const diagonalSum = i + row; - if(!diagonalDiffs.has(diagonalDiff) && !cols.has(i) && !diagonalSums.has(diagonalSum)) { + if ( + !diagonalDiffs.has(diagonalDiff) && + !cols.has(i) && + !diagonalSums.has(diagonalSum) + ) { diagonalDiffs.add(diagonalDiff); diagonalSums.add(diagonalSum); cols.add(i); - solveNQueensAux(n, row + 1, diagonalDiffs, diagonalSums, cols, [...currentSol, ...[[row, i]]], sol); + solveNQueensAux( + n, + row + 1, + diagonalDiffs, + diagonalSums, + cols, + [...currentSol, ...[[row, i]]], + sol + ); cols.delete(i); diagonalDiffs.delete(diagonalDiff); diagonalSums.delete(diagonalSum); } } -} +}; -var parseSolutions = function(sols, n) { +var parseSolutions = function (sols, n) { var matrixes = []; - for(var i = 0; i < sols.length; i++) { + for (var i = 0; i < sols.length; i++) { var sol = sols[i]; var matrix = []; - for(var row = 0; row < n; row++) { - matrix[row] = [] + for (var row = 0; row < n; row++) { + matrix[row] = []; const queenPos = sol[row]; - for(var col = 0; col < n; col++) { - matrix[row] += (queenPos[1] == col) ? "Q" : "."; + for (var col = 0; col < n; col++) { + matrix[row] += queenPos[1] == col ? "Q" : "."; } } @@ -68,6 +87,6 @@ var parseSolutions = function(sols, n) { } return matrixes; -} +}; module.exports.solveNQueens = solveNQueens; diff --git a/LeetcodeProblems/Algorithms/Number_of_Islands.js b/LeetcodeProblems/Algorithms/Number_of_Islands.js index 705dd63..1f250aa 100644 --- a/LeetcodeProblems/Algorithms/Number_of_Islands.js +++ b/LeetcodeProblems/Algorithms/Number_of_Islands.js @@ -25,40 +25,38 @@ Input: Output: 3 */ - /* * @param {character[][]} grid * @return {number} */ -var numIslands = function(grid) { - if(grid.length === 0) - return 0; - +var numIslands = function (grid) { + if (grid.length === 0) return 0; + var countIslands = 0; const rowsCount = grid.length; const columnsCount = grid[0].length; - for(var i = 0; i < rowsCount; i++) { - for(var j = 0; j < columnsCount; j++) { - if(grid[i][j] == 1) { + for (var i = 0; i < rowsCount; i++) { + for (var j = 0; j < columnsCount; j++) { + if (grid[i][j] == 1) { countIslands++; colorIsland(grid, i, j, rowsCount, columnsCount); } } } - + return countIslands; }; -var colorIsland = function(grid, i, j, rowsCount, columnsCount) { - if(i < 0 || j < 0 || i >= rowsCount || j >= columnsCount || grid[i][j] == 0) - return; - +var colorIsland = function (grid, i, j, rowsCount, columnsCount) { + if (i < 0 || j < 0 || i >= rowsCount || j >= columnsCount || grid[i][j] == 0) + return; + grid[i][j] = 0; - + colorIsland(grid, i - 1, j, rowsCount, columnsCount); colorIsland(grid, i + 1, j, rowsCount, columnsCount); colorIsland(grid, i, j - 1, rowsCount, columnsCount); colorIsland(grid, i, j + 1, rowsCount, columnsCount); -} +}; module.exports.numIslands = numIslands; diff --git a/LeetcodeProblems/Algorithms/Number_of_Segments_in_a_String.js b/LeetcodeProblems/Algorithms/Number_of_Segments_in_a_String.js index cb33afb..047e4f8 100644 --- a/LeetcodeProblems/Algorithms/Number_of_Segments_in_a_String.js +++ b/LeetcodeProblems/Algorithms/Number_of_Segments_in_a_String.js @@ -12,24 +12,22 @@ Input: "Hello, my name is John" Output: 5 */ - /** * @param {string} s * @return {number} */ -var countSegments = function(s) { +var countSegments = function (s) { var count = 0; var i = 0; - while(i < s.length) { - if(s[i] !== " ") { + while (i < s.length) { + if (s[i] !== " ") { count++; - while(i < s.length && s[i] !== " ") - i++; + while (i < s.length && s[i] !== " ") i++; } i++; } - + return count; }; diff --git a/LeetcodeProblems/Algorithms/Permutations.js b/LeetcodeProblems/Algorithms/Permutations.js index 478eda6..00c3e9c 100644 --- a/LeetcodeProblems/Algorithms/Permutations.js +++ b/LeetcodeProblems/Algorithms/Permutations.js @@ -18,24 +18,24 @@ Output: ] */ -var permute = function(nums) { +var permute = function (nums) { return permuteAux(nums, 0, [], new Set()); }; -var permuteAux = function(nums, pos, currentSol, set) { - if(pos === nums.length) { +var permuteAux = function (nums, pos, currentSol, set) { + if (pos === nums.length) { return [currentSol]; } var ret = []; - for(var i = 0; i < nums.length; i++) { - if(!set.has(nums[i])) { - set.add(nums[i]) + for (var i = 0; i < nums.length; i++) { + if (!set.has(nums[i])) { + set.add(nums[i]); var sol = permuteAux(nums, pos + 1, currentSol.concat(nums[i]), set); ret = [...ret, ...sol]; set.delete(nums[i]); } } return ret; -} +}; module.exports.permute = permute; diff --git a/LeetcodeProblems/Algorithms/Permutations_II.js b/LeetcodeProblems/Algorithms/Permutations_II.js index ba86bb5..e806385 100644 --- a/LeetcodeProblems/Algorithms/Permutations_II.js +++ b/LeetcodeProblems/Algorithms/Permutations_II.js @@ -15,29 +15,28 @@ Output: ] */ - -var permuteUnique = function(nums) { +var permuteUnique = function (nums) { var map = {}; - for(var i = 0; i < nums.length; i++) { - var value = nums[i]; - map[value] = (map[value]) ? map[value] + 1 : 1; + for (var i = 0; i < nums.length; i++) { + var value = nums[i]; + map[value] = map[value] ? map[value] + 1 : 1; } - + return permuteUniqueAux(nums.length, map, []); }; -var permuteUniqueAux = function(n, map, currentSol) { - if(currentSol.length === n) { +var permuteUniqueAux = function (n, map, currentSol) { + if (currentSol.length === n) { return [currentSol]; } var ret = []; - for(var num in map) { + for (var num in map) { const occ = map[num]; - if(occ === 1) { + if (occ === 1) { delete map[num]; } else { - map[num] = occ -1 ; + map[num] = occ - 1; } ret = [...ret, ...permuteUniqueAux(n, map, currentSol.concat(num))]; map[num] = occ; diff --git a/LeetcodeProblems/Algorithms/Permutations_With_Duplicates.js b/LeetcodeProblems/Algorithms/Permutations_With_Duplicates.js index 3746a24..5ef1ba5 100644 --- a/LeetcodeProblems/Algorithms/Permutations_With_Duplicates.js +++ b/LeetcodeProblems/Algorithms/Permutations_With_Duplicates.js @@ -1,32 +1,32 @@ - - // Permutations without -var subsetWithoutDuplicates = function(nums) { - if(nums.lenght == 0){ +var subsetWithoutDuplicates = function (nums) { + if (nums.lenght == 0) { return; } var solution = []; subsetWithoutDuplicatesAux(nums, [], solution); return solution; -} +}; -var subsetWithoutDuplicatesAux = function(nums, current, sol) { - if(nums.length == 0){ +var subsetWithoutDuplicatesAux = function (nums, current, sol) { + if (nums.length == 0) { sol.push(current); } var setNums = new Set(); nums.forEach((value, index) => { - if(setNums.has(value)) { + if (setNums.has(value)) { return; } setNums.add(value); - var newCurrent = [...current, value] - - var newNum = nums.filter(function(num, idx) { return index !== idx}); + var newCurrent = [...current, value]; + + var newNum = nums.filter(function (num, idx) { + return index !== idx; + }); subsetWithoutDuplicatesAux(newNum, newCurrent, sol); - }) -} + }); +}; module.exports.subsetWithoutDuplicates = subsetWithoutDuplicates; diff --git a/LeetcodeProblems/Algorithms/Permutations_Without_Duplicates.js b/LeetcodeProblems/Algorithms/Permutations_Without_Duplicates.js index 3a0463f..281a283 100644 --- a/LeetcodeProblems/Algorithms/Permutations_Without_Duplicates.js +++ b/LeetcodeProblems/Algorithms/Permutations_Without_Duplicates.js @@ -19,25 +19,27 @@ Output: */ // Permutations without Duplicates -var subsetWithoutDuplicates = function(nums) { - if(nums.lenght == 0){ +var subsetWithoutDuplicates = function (nums) { + if (nums.lenght == 0) { return; } var solution = []; subsetWithoutDuplicatesAux(nums, [], solution); return solution; -} +}; -var subsetWithoutDuplicatesAux = function(nums, current, sol) { - if(nums.length == 0){ +var subsetWithoutDuplicatesAux = function (nums, current, sol) { + if (nums.length == 0) { sol.push(current); } - for(var i = 0; i < nums.length; i++) { - var newCurrent = [...current, nums[i]] - var newNums = nums.filter(function(num, index) { return index !== i }); + for (var i = 0; i < nums.length; i++) { + var newCurrent = [...current, nums[i]]; + var newNums = nums.filter(function (num, index) { + return index !== i; + }); subsetWithoutDuplicatesAux(newNums, newCurrent, sol); } -} +}; module.exports.subsetWithoutDuplicates = subsetWithoutDuplicates; diff --git a/LeetcodeProblems/Algorithms/Regular_Expression_Matching.js b/LeetcodeProblems/Algorithms/Regular_Expression_Matching.js index b90d2aa..33feabf 100644 --- a/LeetcodeProblems/Algorithms/Regular_Expression_Matching.js +++ b/LeetcodeProblems/Algorithms/Regular_Expression_Matching.js @@ -51,43 +51,51 @@ Output: false * @param {*} p */ - -var isMatch = function(s, p) { +var isMatch = function (s, p) { return isMatchAux(s, p, 0, 0); }; -var isMatchAux = function(str, pattern, posStr, posPat) { - if(posStr == str.length) +var isMatchAux = function (str, pattern, posStr, posPat) { + if (posStr == str.length) return posPat == pattern.length || canBeZero(pattern, posPat); - if(posPat < pattern.length - 1 && pattern.charAt(posPat + 1) == "*") { + if (posPat < pattern.length - 1 && pattern.charAt(posPat + 1) == "*") { const valuePattern = pattern.charAt(posPat); posPat = posPat + 2; - if (isMatchAux(str, pattern, posStr, posPat)) { // 0 matches - return true + if (isMatchAux(str, pattern, posStr, posPat)) { + // 0 matches + return true; } - - while(posStr < str.length && (str.charAt(posStr) === valuePattern || valuePattern === ".")) { - if(isMatchAux(str, pattern, posStr + 1, posPat)) { + + while ( + posStr < str.length && + (str.charAt(posStr) === valuePattern || valuePattern === ".") + ) { + if (isMatchAux(str, pattern, posStr + 1, posPat)) { return true; } posStr++; } - } else if(str.charAt(posStr) === pattern.charAt(posPat) || pattern.charAt(posPat) === ".") { + } else if ( + str.charAt(posStr) === pattern.charAt(posPat) || + pattern.charAt(posPat) === "." + ) { return isMatchAux(str, pattern, posStr + 1, posPat + 1); } - + return false; -} +}; -var canBeZero = function(pattern, posPat) { - while(posPat < pattern.length && pattern.charAt(posPat) == "*" || - posPat < pattern.length - 1 && pattern.charAt(posPat + 1) == "*") { +var canBeZero = function (pattern, posPat) { + while ( + (posPat < pattern.length && pattern.charAt(posPat) == "*") || + (posPat < pattern.length - 1 && pattern.charAt(posPat + 1) == "*") + ) { posPat++; } - + return posPat == pattern.length; -} +}; module.exports.isMatch = isMatch; diff --git a/LeetcodeProblems/Algorithms/Remove_Invalid_Parentheses.js b/LeetcodeProblems/Algorithms/Remove_Invalid_Parentheses.js index 8d193f5..34a93d8 100644 --- a/LeetcodeProblems/Algorithms/Remove_Invalid_Parentheses.js +++ b/LeetcodeProblems/Algorithms/Remove_Invalid_Parentheses.js @@ -24,49 +24,47 @@ Output: [""] * @param {string} s * @return {string[]} */ -var removeInvalidParentheses = function(s) { +var removeInvalidParentheses = function (s) { var queue = []; var visited = new Set(); queue.push(s); var result = []; var found = false; - - while(queue.length !== 0) { + + while (queue.length !== 0) { var str = queue.shift(); - if(isValid(str)) { + if (isValid(str)) { result.push(str); found = true; - } else if(!found){ - for(var i = 0; i < s.length; i++) { - if(str[i] === "(" || str[i] === ")") { + } else if (!found) { + for (var i = 0; i < s.length; i++) { + if (str[i] === "(" || str[i] === ")") { var subStr = str.slice(0, i) + str.slice(i + 1, s.length); - if(!visited.has(subStr)) { - queue.push(subStr); + if (!visited.has(subStr)) { + queue.push(subStr); visited.add(subStr); } - } + } } } } - + return result; }; -var isValid = function(s) { +var isValid = function (s) { var leftCount = 0; var iter = 0; - while(iter < s.length) { - if(s[iter] === "(") - leftCount++; - else if(s[iter] === ")") { + while (iter < s.length) { + if (s[iter] === "(") leftCount++; + else if (s[iter] === ")") { leftCount--; - if(leftCount < 0) - return false; + if (leftCount < 0) return false; } iter++; - } - + } + return leftCount === 0; -} +}; module.exports.removeInvalidParentheses = removeInvalidParentheses; diff --git a/LeetcodeProblems/Algorithms/Restore_IP_Addresses.js b/LeetcodeProblems/Algorithms/Restore_IP_Addresses.js index 578b970..fcba749 100644 --- a/LeetcodeProblems/Algorithms/Restore_IP_Addresses.js +++ b/LeetcodeProblems/Algorithms/Restore_IP_Addresses.js @@ -10,34 +10,42 @@ Input: "25525511135" Output: ["255.255.11.135", "255.255.111.35"] */ -var restoreIpAddresses = function(s) { +var restoreIpAddresses = function (s) { var restore = restoreInputBits("", s, 4); var ret = []; - for(var i = 0; i < restore.length; i++) { + for (var i = 0; i < restore.length; i++) { ret.push(restore[i].join(".")); } return ret; }; -var restoreInputBits = function(partial, s, num) { - if(s.length == 0 && num == 0 ) - return [partial]; - if(s.length < num || s.length > num * 3 || num == 0) - return []; - - const oneNum = restoreInputBits([...partial, s.slice(0, 1)], s.slice(1), num - 1); - - if(s.length === 1 || s.slice(0, 1) === "0") - return oneNum - - const twoNums = restoreInputBits([...partial, s.slice(0, 2)], s.slice(2), num - 1); - if(s.length === 2 || s.slice(0, 3) > 255) - return [...oneNum, ...twoNums] - - const threeNums = restoreInputBits([...partial, s.slice(0, 3)], s.slice(3), num - 1); +var restoreInputBits = function (partial, s, num) { + if (s.length == 0 && num == 0) return [partial]; + if (s.length < num || s.length > num * 3 || num == 0) return []; + + const oneNum = restoreInputBits( + [...partial, s.slice(0, 1)], + s.slice(1), + num - 1 + ); + + if (s.length === 1 || s.slice(0, 1) === "0") return oneNum; + + const twoNums = restoreInputBits( + [...partial, s.slice(0, 2)], + s.slice(2), + num - 1 + ); + if (s.length === 2 || s.slice(0, 3) > 255) return [...oneNum, ...twoNums]; + + const threeNums = restoreInputBits( + [...partial, s.slice(0, 3)], + s.slice(3), + num - 1 + ); return [...oneNum, ...twoNums, ...threeNums]; -} +}; module.exports.restoreIpAddresses = restoreIpAddresses; diff --git a/LeetcodeProblems/Algorithms/Reverse_String_II.js b/LeetcodeProblems/Algorithms/Reverse_String_II.js index 429520f..4e83723 100644 --- a/LeetcodeProblems/Algorithms/Reverse_String_II.js +++ b/LeetcodeProblems/Algorithms/Reverse_String_II.js @@ -11,31 +11,29 @@ The string consists of lower English letters only. Length of the given string and k will in the range [1, 10000] */ -var reverseStr = function(s, k) { - if(k <= 1) - return s; +var reverseStr = function (s, k) { + if (k <= 1) return s; var ret = ""; - for(var iterK = 0; iterK * k < s.length; iterK = iterK + 2) { + for (var iterK = 0; iterK * k < s.length; iterK = iterK + 2) { const start = iterK * k; - const end = start + k - 1; - + const end = start + k - 1; + ret += reverse(s, start, end); - ret += s.slice(end + 1, k * (iterK + 2)); + ret += s.slice(end + 1, k * (iterK + 2)); } - + return ret; }; -var reverse = function(s, start, end) { +var reverse = function (s, start, end) { var ret = ""; - if(end >= s.length) - end = s.length - 1; - - while(start <= end) { + if (end >= s.length) end = s.length - 1; + + while (start <= end) { ret += s.charAt(end); end--; } return ret; -} +}; module.exports.reverseStr = reverseStr; diff --git a/LeetcodeProblems/Algorithms/Same_Tree.js b/LeetcodeProblems/Algorithms/Same_Tree.js index 31b8664..3d08ace 100644 --- a/LeetcodeProblems/Algorithms/Same_Tree.js +++ b/LeetcodeProblems/Algorithms/Same_Tree.js @@ -32,7 +32,7 @@ Input: 1 1 [1,2,1], [1,1,2] Output: false -*/ +*/ /** * Definition for a binary tree node. @@ -46,12 +46,10 @@ Output: false * @param {TreeNode} q * @return {boolean} */ -var isSameTree = function(p, q) { - if(p === null) - return q === null; - - if(q === null || p.val !== q.val) - return false; - +var isSameTree = function (p, q) { + if (p === null) return q === null; + + if (q === null || p.val !== q.val) return false; + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }; diff --git a/LeetcodeProblems/Algorithms/SearchIng_Rotated_Sorted_Array.js b/LeetcodeProblems/Algorithms/SearchIng_Rotated_Sorted_Array.js index 702f357..72a4451 100644 --- a/LeetcodeProblems/Algorithms/SearchIng_Rotated_Sorted_Array.js +++ b/LeetcodeProblems/Algorithms/SearchIng_Rotated_Sorted_Array.js @@ -22,36 +22,36 @@ Output: -1 */ - /** * @param {number[]} nums * @param {number} target * @return {number} */ -var search = function(nums, target) { - return searchAux(nums, target, 0, nums.length -1); +var search = function (nums, target) { + return searchAux(nums, target, 0, nums.length - 1); }; -var searchAux = function(nums, target, start, end) { - if (start > end) - return - 1; - var middle = Math.trunc((start + end) /2); - - if(nums[middle] == target) { +var searchAux = function (nums, target, start, end) { + if (start > end) return -1; + var middle = Math.trunc((start + end) / 2); + + if (nums[middle] == target) { return middle; } - - if(nums[middle] < nums[nums.length - 1]) { // right part sorted - if(nums[middle] < target && nums[nums.length - 1] >= target) { + + if (nums[middle] < nums[nums.length - 1]) { + // right part sorted + if (nums[middle] < target && nums[nums.length - 1] >= target) { return searchAux(nums, target, middle + 1, end); } return searchAux(nums, target, start, middle - 1); - } else { // left part sorted - if(nums[0] <= target && nums[middle] > target) { + } else { + // left part sorted + if (nums[0] <= target && nums[middle] > target) { return searchAux(nums, target, start, middle - 1); } return searchAux(nums, target, middle + 1, end); } -} +}; module.exports.search = search; diff --git a/LeetcodeProblems/Algorithms/Search_a_2D_Matrix.js b/LeetcodeProblems/Algorithms/Search_a_2D_Matrix.js index 6348c4c..b774a17 100644 --- a/LeetcodeProblems/Algorithms/Search_a_2D_Matrix.js +++ b/LeetcodeProblems/Algorithms/Search_a_2D_Matrix.js @@ -33,28 +33,25 @@ Output: false * @param {number} target * @return {boolean} */ -var searchMatrix = function(matrix, target) { - if(matrix.length === 0) - return false; +var searchMatrix = function (matrix, target) { + if (matrix.length === 0) return false; return searchMatrixAux(matrix, 0, matrix.length - 1, target); }; -var searchMatrixAux = function(matrix, firstRow, lastRow, target) { - if(firstRow === lastRow) { - var iter = 0; - while(iter < matrix[0].length) { - if(matrix[firstRow][iter] === target) - return true; +var searchMatrixAux = function (matrix, firstRow, lastRow, target) { + if (firstRow === lastRow) { + var iter = 0; + while (iter < matrix[0].length) { + if (matrix[firstRow][iter] === target) return true; iter++; } } else { var middle = Math.floor((firstRow + lastRow) / 2); // 0 - if(target > matrix[middle][matrix[0].length - 1]) - return searchMatrixAux(matrix, middle + 1, lastRow, target) - else - return searchMatrixAux(matrix, firstRow, middle, target) + if (target > matrix[middle][matrix[0].length - 1]) + return searchMatrixAux(matrix, middle + 1, lastRow, target); + else return searchMatrixAux(matrix, firstRow, middle, target); } - + return false; }; diff --git a/LeetcodeProblems/Algorithms/Search_a_2D_Matrix_II.js b/LeetcodeProblems/Algorithms/Search_a_2D_Matrix_II.js index c96c95d..899f72e 100644 --- a/LeetcodeProblems/Algorithms/Search_a_2D_Matrix_II.js +++ b/LeetcodeProblems/Algorithms/Search_a_2D_Matrix_II.js @@ -19,26 +19,25 @@ Given target = 20, return false. */ /** -* @param {number[][]} matrix -* @param {number} target -* @return {boolean} -*/ -var searchMatrix = function(matrix, target) { - if (matrix.length == 0) - return false + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function (matrix, target) { + if (matrix.length == 0) return false; var lastCol = matrix[0].length - 1; var firstRow = 0; - - while(lastCol >= 0 && firstRow < matrix.length) { - if(matrix[firstRow][lastCol] == target) { + + while (lastCol >= 0 && firstRow < matrix.length) { + if (matrix[firstRow][lastCol] == target) { return true; - } else if(matrix[firstRow][lastCol] > target) { + } else if (matrix[firstRow][lastCol] > target) { lastCol--; } else { firstRow++; } } - + return false; }; diff --git a/LeetcodeProblems/Algorithms/Set_Matrix_Zeroes.js b/LeetcodeProblems/Algorithms/Set_Matrix_Zeroes.js index 908411a..a2a6b18 100644 --- a/LeetcodeProblems/Algorithms/Set_Matrix_Zeroes.js +++ b/LeetcodeProblems/Algorithms/Set_Matrix_Zeroes.js @@ -43,22 +43,21 @@ Could you devise a constant space solution? * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. */ -var setZeroes = function(matrix) { - if(matrix.length === 0) - return; - +var setZeroes = function (matrix) { + if (matrix.length === 0) return; + var pivotRow = -1; var pivotCol = -1; var iterRow = 0; var iterCol = 0; var found = false; - + // Find a pivot - while(!found && iterRow < matrix.length) { + while (!found && iterRow < matrix.length) { iterCol = 0; - while(!found && iterCol < matrix[0].length) { - if(matrix[iterRow][iterCol] === 0) { - found = true + while (!found && iterCol < matrix[0].length) { + if (matrix[iterRow][iterCol] === 0) { + found = true; pivotRow = iterRow; pivotCol = iterCol; } @@ -66,46 +65,39 @@ var setZeroes = function(matrix) { } iterRow++; } - - if (!found) - return; - + + if (!found) return; + // Update the Column value - for(var i = 0; i < matrix.length; i++) { - if(i == pivotRow) - continue - for(var j = 0; j < matrix[0].length; j++) { - if(j == pivotCol) - continue; - if(matrix[i][j] === 0) { + for (var i = 0; i < matrix.length; i++) { + if (i == pivotRow) continue; + for (var j = 0; j < matrix[0].length; j++) { + if (j == pivotCol) continue; + if (matrix[i][j] === 0) { matrix[i][pivotCol] = 0; matrix[pivotRow][j] = 0; } } } - - for(var i = 0; i < matrix.length; i++) - if(matrix[i][pivotCol] === 0 && i !== pivotRow) - fillRow(matrix, i); - - for(var i = 0; i < matrix[0].length; i++) - if(matrix[pivotRow][i] === 0 && i !== pivotCol) - fillCol(matrix, i); - + + for (var i = 0; i < matrix.length; i++) + if (matrix[i][pivotCol] === 0 && i !== pivotRow) fillRow(matrix, i); + + for (var i = 0; i < matrix[0].length; i++) + if (matrix[pivotRow][i] === 0 && i !== pivotCol) fillCol(matrix, i); + fillCol(matrix, pivotCol); fillRow(matrix, pivotRow); return matrix; }; -var fillRow = function(matrix, row) { - for(var i = 0; i < matrix[0].length; i++) - matrix[row][i] = 0; -} +var fillRow = function (matrix, row) { + for (var i = 0; i < matrix[0].length; i++) matrix[row][i] = 0; +}; -var fillCol = function(matrix, col) { - for(var i = 0; i < matrix.length; i++) - matrix[i][col] = 0; -} +var fillCol = function (matrix, col) { + for (var i = 0; i < matrix.length; i++) matrix[i][col] = 0; +}; module.exports.setZeroes = setZeroes; diff --git a/LeetcodeProblems/Algorithms/Simplify_Path.js b/LeetcodeProblems/Algorithms/Simplify_Path.js index 70e17f7..4a3be37 100644 --- a/LeetcodeProblems/Algorithms/Simplify_Path.js +++ b/LeetcodeProblems/Algorithms/Simplify_Path.js @@ -20,24 +20,24 @@ Another corner case is the path might contain multiple slashes '/' together, suc In this case, you should ignore redundant slashes and return "/home/foo". */ - -var simplifyPath = function(path) { +var simplifyPath = function (path) { var queue = []; - var iter = path.length - 1; - while(iter >= 0) { - if(path.charAt(iter) === "/") { + var iter = path.length - 1; + while (iter >= 0) { + if (path.charAt(iter) === "/") { iter--; - } else if(path.slice(iter - 1, iter + 1) == "/.") { - iter -= 2; - } else if(path.slice(iter - 2, iter + 1) === "/..") { - iter -= 3; - queue.unshift("/.."); - } else { // it's a characteriter + } else if (path.slice(iter - 1, iter + 1) == "/.") { + iter -= 2; + } else if (path.slice(iter - 2, iter + 1) === "/..") { + iter -= 3; + queue.unshift("/.."); + } else { + // it's a characteriter const endChars = iter; - while(iter >= 0 && path.charAt(iter) !== "/") { + while (iter >= 0 && path.charAt(iter) !== "/") { iter--; } - if(queue.length > 0 && queue[0] === "/..") { + if (queue.length > 0 && queue[0] === "/..") { queue.shift(); } else { queue.push("/" + path.slice(iter + 1, endChars + 1)); @@ -45,19 +45,19 @@ var simplifyPath = function(path) { } } var ret = ""; - - while(queue.length > 0) { + + while (queue.length > 0) { elem = queue.shift(); - if(elem == "/..") { - while(queue.length > 0 && queue.shift == "/..") { + if (elem == "/..") { + while (queue.length > 0 && queue.shift == "/..") { elem += "/.."; } - elem = (queue.length > 0) ? elem : ""; + elem = queue.length > 0 ? elem : ""; } else { ret = elem + ret; } } - return (ret.length == 0) ? "/" : ret; + return ret.length == 0 ? "/" : ret; }; module.exports.simplifyPath = simplifyPath; diff --git a/LeetcodeProblems/Algorithms/Spiral_Matrix.js b/LeetcodeProblems/Algorithms/Spiral_Matrix.js index 96f078e..79cfd7f 100644 --- a/LeetcodeProblems/Algorithms/Spiral_Matrix.js +++ b/LeetcodeProblems/Algorithms/Spiral_Matrix.js @@ -24,47 +24,45 @@ Input: Output: [1,2,3,4,8,12,11,10,9,5,6,7] */ - /** * @param {number[][]} matrix * @return {number[]} */ -var spiralOrder = function(matrix) { - if(matrix.length === 0) - return []; - - var retArray = []; - const rowLength = matrix.length; - const colLength = matrix[0].length; - const countRectangles = Math.ceil(Math.min(colLength, rowLength)/2) - for(var i = 0; i < countRectangles; i++) - printRect(matrix, i, rowLength, colLength, retArray); +var spiralOrder = function (matrix) { + if (matrix.length === 0) return []; + + var retArray = []; + const rowLength = matrix.length; + const colLength = matrix[0].length; + const countRectangles = Math.ceil(Math.min(colLength, rowLength) / 2); + for (var i = 0; i < countRectangles; i++) + printRect(matrix, i, rowLength, colLength, retArray); - return retArray; + return retArray; }; -var printRect = function(matrix, i, rowLength, colLength, retArray) { +var printRect = function (matrix, i, rowLength, colLength, retArray) { const firstRow = i; const firstCol = i; const lastRow = rowLength - i - 1; const lastCol = colLength - i - 1; - - for(var col = firstCol; col <= lastCol; col++) { + + for (var col = firstCol; col <= lastCol; col++) { retArray.push(matrix[firstRow][col]); } - for(var row = firstRow + 1; row <= lastRow; row++) { + for (var row = firstRow + 1; row <= lastRow; row++) { retArray.push(matrix[row][lastCol]); } - if(firstRow === lastRow || firstCol === lastCol) { + if (firstRow === lastRow || firstCol === lastCol) { return; } - for(var col = lastCol - 1; col >= firstCol; col--) { + for (var col = lastCol - 1; col >= firstCol; col--) { retArray.push(matrix[lastRow][col]); } - for(var row = lastRow - 1; row > firstRow; row--) { + for (var row = lastRow - 1; row > firstRow; row--) { retArray.push(matrix[row][firstCol]); } -} +}; module.exports.spiralOrder = spiralOrder; diff --git a/LeetcodeProblems/Algorithms/Subarray_Sum_Equals_K.js b/LeetcodeProblems/Algorithms/Subarray_Sum_Equals_K.js index 1dca41c..6b2eb9e 100644 --- a/LeetcodeProblems/Algorithms/Subarray_Sum_Equals_K.js +++ b/LeetcodeProblems/Algorithms/Subarray_Sum_Equals_K.js @@ -1,4 +1,3 @@ - /* Subarray Sum Equals K https://leetcode.com/problems/subarray-sum-equals-k/ @@ -13,50 +12,45 @@ The length of the array is in range [1, 20,000]. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. */ - /** * @param {number[]} nums * @param {number} k * @return {number} */ - // Solution 1 -var subarraySum = function(nums, k) { +// Solution 1 +var subarraySum = function (nums, k) { var ret = 0; - for(var i = 0; i < nums.length; i++) { + for (var i = 0; i < nums.length; i++) { var count = 0; - for(var j = i; j < nums.length; j++) { + for (var j = i; j < nums.length; j++) { count += nums[j]; - if(count === k) - ret++; + if (count === k) ret++; } } - + return ret; }; - // Solution 2 -var subarraySum2 = function(nums, k) { - if(nums.length === 0) - return 0; - +var subarraySum2 = function (nums, k) { + if (nums.length === 0) return 0; + var sums = []; sums[0] = 0; var count = 0; - for(var i = 0; i < nums.length; i++) { + for (var i = 0; i < nums.length; i++) { count += nums[i]; sums[i + 1] = count; } - - var ret = 0; - for(var i = 0; i < sums.length - 1; i++) { - for(var j = i + 1; j < sums.length; j++) { - if(sums[j] - sums[i] === k) - ret++; + + var ret = 0; + for (var i = 0; i < sums.length - 1; i++) { + for (var j = i + 1; j < sums.length; j++) { + if (sums[j] - sums[i] === k) ret++; } } - + return ret; }; diff --git a/LeetcodeProblems/Algorithms/Subsets.js b/LeetcodeProblems/Algorithms/Subsets.js index 7b26f17..0289b59 100644 --- a/LeetcodeProblems/Algorithms/Subsets.js +++ b/LeetcodeProblems/Algorithms/Subsets.js @@ -22,19 +22,19 @@ Output: ] */ - - -var subsets = function(nums) { +var subsets = function (nums) { var ret = []; - + subsetByPosition = function (nums, position, current) { - if(position == nums.length) { + if (position == nums.length) { return [current]; } var currentRight = current.slice().concat([nums[position]]); - return subsetByPosition(nums, position + 1, currentRight).concat(subsetByPosition(nums, position + 1, current)); - } - + return subsetByPosition(nums, position + 1, currentRight).concat( + subsetByPosition(nums, position + 1, current) + ); + }; + return subsetByPosition(nums, 0, []); }; diff --git a/LeetcodeProblems/Algorithms/Sum_Of_Square_Numbers.js b/LeetcodeProblems/Algorithms/Sum_Of_Square_Numbers.js index ae97bb9..fc104dc 100644 --- a/LeetcodeProblems/Algorithms/Sum_Of_Square_Numbers.js +++ b/LeetcodeProblems/Algorithms/Sum_Of_Square_Numbers.js @@ -18,18 +18,17 @@ Output: False * @param {number} c * @return {boolean} */ -var judgeSquareSum = function(c) { +var judgeSquareSum = function (c) { var iter = 0; var set = new Set(); - while(iter ** 2 <= c) { + while (iter ** 2 <= c) { var square = iter * iter; - if(square * 2 === c || set.has(c - square)) - return true; + if (square * 2 === c || set.has(c - square)) return true; set.add(square); iter++; } - + return false; }; diff --git a/LeetcodeProblems/Algorithms/Swap_Nodes_In_Pairs.js b/LeetcodeProblems/Algorithms/Swap_Nodes_In_Pairs.js index 0ee2002..abd4ce7 100644 --- a/LeetcodeProblems/Algorithms/Swap_Nodes_In_Pairs.js +++ b/LeetcodeProblems/Algorithms/Swap_Nodes_In_Pairs.js @@ -24,25 +24,24 @@ You may not modify the values in the list's nodes, only nodes itself may be chan * @param {ListNode} head * @return {ListNode} */ -var swapPairs = function(head) { - if(head === null || head.next === null) - return head - var previous = null; - var current = head; - var following = (head.next != null) ? head.next.next : null; +var swapPairs = function (head) { + if (head === null || head.next === null) return head; + var previous = null; + var current = head; + var following = head.next != null ? head.next.next : null; head = head.next; - - while(current !== null && current.next !== null) { - var next = current.next; - next.next = current; - if(previous != null) - previous.next = next; - current.next = following; - previous = current; - current = following; - following = (current !== null && current.next != null) ? current.next.next : null; + + while (current !== null && current.next !== null) { + var next = current.next; + next.next = current; + if (previous != null) previous.next = next; + current.next = following; + previous = current; + current = following; + following = + current !== null && current.next != null ? current.next.next : null; } - + return head; }; diff --git a/LeetcodeProblems/Algorithms/Symmetric_Tree.js b/LeetcodeProblems/Algorithms/Symmetric_Tree.js index 76b365f..3d273bf 100644 --- a/LeetcodeProblems/Algorithms/Symmetric_Tree.js +++ b/LeetcodeProblems/Algorithms/Symmetric_Tree.js @@ -33,19 +33,20 @@ Bonus points if you could solve it both recursively and iteratively. * @param {TreeNode} root * @return {boolean} */ -var isSymmetric = function(root) { - if(root === null) - return true; +var isSymmetric = function (root) { + if (root === null) return true; return isSymetricAux(root.left, root.right); }; -var isSymetricAux = function(root1, root2) { - if(root1 === null) - return root2 === null; - - if(root2 === null || root1.val !== root2.val) { +var isSymetricAux = function (root1, root2) { + if (root1 === null) return root2 === null; + + if (root2 === null || root1.val !== root2.val) { return false; } - - return isSymetricAux(root1.left, root2.right) && isSymetricAux(root1.right, root2.left); -} + + return ( + isSymetricAux(root1.left, root2.right) && + isSymetricAux(root1.right, root2.left) + ); +}; diff --git a/LeetcodeProblems/Algorithms/Tic_Tac_Toe.js b/LeetcodeProblems/Algorithms/Tic_Tac_Toe.js index f3dcfc0..e3a7144 100644 --- a/LeetcodeProblems/Algorithms/Tic_Tac_Toe.js +++ b/LeetcodeProblems/Algorithms/Tic_Tac_Toe.js @@ -1,14 +1,13 @@ - class TicTacToe { constructor() { this.matrix = []; - for(var i = 0; i < 3; i++) { + for (var i = 0; i < 3; i++) { this.matrix[i] = []; - for(var j = 0; j < 3; j++) { + for (var j = 0; j < 3; j++) { this.matrix[i][j] = "-"; } } - }; + } validToken(token) { if (token == "X" || token == "0" || token == "-") { @@ -20,41 +19,45 @@ class TicTacToe { addToken(x, y, token) { // Check valid positions - if(this.validToken(token)) { + if (this.validToken(token)) { this.matrix[x][y] = token; } - }; + } printBoard() { console.log("-------"); - for(var row = 0; row < 3; row ++) { - console.log(this.matrix[row][0] + "|" - + this.matrix[row][1] + "|" - + this.matrix[row][2]); // Check new line; + for (var row = 0; row < 3; row++) { + console.log( + this.matrix[row][0] + + "|" + + this.matrix[row][1] + + "|" + + this.matrix[row][2] + ); // Check new line; } console.log("------- \n"); } isBoardFull() { - for(var row = 0; row < 3; row ++) { - for(var col = 0; col < 3; col ++) { - if(this.matrix[row][col] === "-") { + for (var row = 0; row < 3; row++) { + for (var col = 0; col < 3; col++) { + if (this.matrix[row][col] === "-") { console.log("Is not full"); return false; } - } + } } console.log("Is full"); return true; } makeMove(str) { - if(this.isBoardFull()) { + if (this.isBoardFull()) { throw "Error Board is Full"; } - for(var row = 0; row < 3; row ++) { - for(var col = 0; col < 3; col ++) { - if(this.matrix[row][col] === "-") { + for (var row = 0; row < 3; row++) { + for (var col = 0; col < 3; col++) { + if (this.matrix[row][col] === "-") { this.addToken(row, col, str); return true; } diff --git a/LeetcodeProblems/Algorithms/Unique_Binary_Search_Trees.js b/LeetcodeProblems/Algorithms/Unique_Binary_Search_Trees.js index b469951..54f2fca 100644 --- a/LeetcodeProblems/Algorithms/Unique_Binary_Search_Trees.js +++ b/LeetcodeProblems/Algorithms/Unique_Binary_Search_Trees.js @@ -1,4 +1,3 @@ - /* Unique Binary Search Trees https://leetcode.com/problems/unique-binary-search-trees/description/ @@ -24,88 +23,81 @@ DP Solution: https://www.programcreek.com/2014/05/leetcode-unique-binary-search- // Solution 3 using DP var numTrees3 = function (n) { - if (n == 0) - return 0 + if (n == 0) return 0; var map = []; map[0] = 1; map[1] = 1; - for(var i = 2; i <= n; i++) { + for (var i = 2; i <= n; i++) { var currentI = 0; - for(var j = 0; j < i; j++) { + for (var j = 0; j < i; j++) { currentI += map[j] * map[i - j - 1]; } map[i] = currentI; } return map[n]; -} +}; // Solution 2 (Solution 1 + Memoization) -var numTrees2 = function(n) { +var numTrees2 = function (n) { var memo = {}; return numTreesAux2(1, n, memo); }; -var numTreesAux2 = function(leftMin, leftMax, memo) { +var numTreesAux2 = function (leftMin, leftMax, memo) { const keyMemo = buildKey(leftMin, leftMax); - if(memo[keyMemo]) - return memo[keyMemo] - - if(leftMin > leftMax) - return 0; - - if(leftMin === leftMax) - return 1; - + if (memo[keyMemo]) return memo[keyMemo]; + + if (leftMin > leftMax) return 0; + + if (leftMin === leftMax) return 1; + var count = 0; - for(var i = leftMin; i <= leftMax; i++){ + for (var i = leftMin; i <= leftMax; i++) { const left = numTreesAux2(leftMin, i - 1, memo); - const right = numTreesAux2(i + 1, leftMax, memo); - - if(left > 0 && right > 0) { - count += left * right; + const right = numTreesAux2(i + 1, leftMax, memo); + + if (left > 0 && right > 0) { + count += left * right; } else { - count += (left > 0) ? left : right; + count += left > 0 ? left : right; } - } - + } + memo[keyMemo] = count; return count; -} +}; -var buildKey = function(a, b) { +var buildKey = function (a, b) { return a + "-" + b; -} - +}; // Solution 1 -var numTrees1 = function(n) { +var numTrees1 = function (n) { return numTreesAux1(1, n); }; -var numTreesAux1 = function(leftMin, leftMax) { - if(leftMin > leftMax) - return 0; - - if(leftMin === leftMax) - return 1; - +var numTreesAux1 = function (leftMin, leftMax) { + if (leftMin > leftMax) return 0; + + if (leftMin === leftMax) return 1; + var count = 0; - for(var i = leftMin; i <= leftMax; i++){ + for (var i = leftMin; i <= leftMax; i++) { const left = numTreesAux1(leftMin, i - 1); - const right = numTreesAux1(i + 1, leftMax); - - if(left > 0 && right > 0) { - count += left * right; + const right = numTreesAux1(i + 1, leftMax); + + if (left > 0 && right > 0) { + count += left * right; } else { - count += (left > 0) ? left : right; + count += left > 0 ? left : right; } - } - + } + return count; -} +}; module.exports.numTrees1 = numTrees1; module.exports.numTrees2 = numTrees2; diff --git a/LeetcodeProblems/Algorithms/Unique_Paths.js b/LeetcodeProblems/Algorithms/Unique_Paths.js index b7ba36c..492bb5f 100644 --- a/LeetcodeProblems/Algorithms/Unique_Paths.js +++ b/LeetcodeProblems/Algorithms/Unique_Paths.js @@ -26,68 +26,71 @@ Output: 28 // Solution 1 // This solution is a naive solution implementing a binary tree and visiting each node. -var uniquePaths1 = function(m, n) { - return uniquePathsAux(0, 0, m, n) +var uniquePaths1 = function (m, n) { + return uniquePathsAux(0, 0, m, n); }; -var uniquePathsAux = function(row, col, rowLength, colLength) { - if(row >= rowLength || col >= colLength) { +var uniquePathsAux = function (row, col, rowLength, colLength) { + if (row >= rowLength || col >= colLength) { return 0; } - if(row == rowLength - 1 && col == colLength - 1) { + if (row == rowLength - 1 && col == colLength - 1) { return 1; } - - return uniquePathsAux(row + 1, col, rowLength, colLength) + + + return ( + uniquePathsAux(row + 1, col, rowLength, colLength) + uniquePathsAux(row, col + 1, rowLength, colLength) + ); }; // Solution 2 // This solution is solution 1 but memoized. -var uniquePaths2 = function(m, n) { +var uniquePaths2 = function (m, n) { var memo = {}; - return uniquePathsAux2(0, 0, m, n, memo) + return uniquePathsAux2(0, 0, m, n, memo); }; -var uniquePathsAux2 = function(row, col, rowLength, colLength, memo) { - if(memo[memoKey(row, col)]) { +var uniquePathsAux2 = function (row, col, rowLength, colLength, memo) { + if (memo[memoKey(row, col)]) { return memo[row + "-" + col]; } - if(row >= rowLength || col >= colLength) { + if (row >= rowLength || col >= colLength) { return 0; } - if(row == rowLength - 1 && col == colLength - 1) { + if (row == rowLength - 1 && col == colLength - 1) { return 1; } - - var result = uniquePathsAux(row + 1, col, rowLength, colLength, memo) + + + var result = + uniquePathsAux(row + 1, col, rowLength, colLength, memo) + uniquePathsAux(row, col + 1, rowLength, colLength, memo); memo[memoKey(row, col)] = result; return result; }; -var memoKey = function(row, col) { +var memoKey = function (row, col) { return row + "-" + col; -} +}; // Solution 3 // This solution uses Dinamic Programming -var uniquePaths3 = function(m, n) { +var uniquePaths3 = function (m, n) { var matrix = []; - for(var i = 0; i < m; i++) { + for (var i = 0; i < m; i++) { matrix[i] = []; - for(var j = 0; j < n; j++) { - if(i == 0 || j == 0) { + for (var j = 0; j < n; j++) { + if (i == 0 || j == 0) { matrix[i][j] = 1; - } else{ - matrix[i][j] = 0; + } else { + matrix[i][j] = 0; } } } - - for(var row = 1; row < m; row++) { - for(var col = 1; col < n; col++) { - matrix[row][col] = matrix[row - 1][col] + matrix[row][col - 1] + + for (var row = 1; row < m; row++) { + for (var col = 1; col < n; col++) { + matrix[row][col] = matrix[row - 1][col] + matrix[row][col - 1]; } } diff --git a/LeetcodeProblems/Algorithms/Valid_Parentheses.js b/LeetcodeProblems/Algorithms/Valid_Parentheses.js index c65f037..2e5ae5e 100644 --- a/LeetcodeProblems/Algorithms/Valid_Parentheses.js +++ b/LeetcodeProblems/Algorithms/Valid_Parentheses.js @@ -32,28 +32,28 @@ Input: "{[]}" Output: true */ -var isValid = function(s) { +var isValid = function (s) { var stack = []; - for(var i = 0; i < s.length; i++) { + for (var i = 0; i < s.length; i++) { var elem = s.charAt(i); - if(elem === ")" || elem === "]" || elem === "}") { - if(stack.length === 0) - return false; + if (elem === ")" || elem === "]" || elem === "}") { + if (stack.length === 0) return false; var lasPar = stack.shift(); - if(!valid(lasPar, elem)) - return false; + if (!valid(lasPar, elem)) return false; } else { stack.unshift(elem); } } - + return stack.length === 0; }; -var valid = function(parOpen, parClose) { - return parOpen === "(" && parClose === ")" || - parOpen === "[" && parClose === "]" || - parOpen === "{" && parClose === "}"; -} +var valid = function (parOpen, parClose) { + return ( + (parOpen === "(" && parClose === ")") || + (parOpen === "[" && parClose === "]") || + (parOpen === "{" && parClose === "}") + ); +}; module.exports.isValid = isValid; diff --git a/LeetcodeProblems/Algorithms/Verify_Preorder_Serialization_of_a_Binary_Tree.js b/LeetcodeProblems/Algorithms/Verify_Preorder_Serialization_of_a_Binary_Tree.js index 1fed956..77abc31 100644 --- a/LeetcodeProblems/Algorithms/Verify_Preorder_Serialization_of_a_Binary_Tree.js +++ b/LeetcodeProblems/Algorithms/Verify_Preorder_Serialization_of_a_Binary_Tree.js @@ -32,36 +32,32 @@ Input: "9,#,#,1" Output: false */ - /** * @param {string} preorder * @return {boolean} */ -var isValidSerialization = function(preorder) { - if(preorder.length === 0) - return true; +var isValidSerialization = function (preorder) { + if (preorder.length === 0) return true; - if(preorder.charAt(0) === "#") - return preorder.length === 1; + if (preorder.charAt(0) === "#") return preorder.length === 1; var countP = 2; var iter = 1; - while(iter <= preorder.length && preorder.charAt(iter - 1) !== ",") - iter++; + while (iter <= preorder.length && preorder.charAt(iter - 1) !== ",") iter++; - while(countP > 0 && iter < preorder.length) { - if(preorder.charAt(iter) === "#") { + while (countP > 0 && iter < preorder.length) { + if (preorder.charAt(iter) === "#") { countP--; iter += 2; } else { countP++; iter += 2; - while(iter <= preorder.length && preorder.charAt(iter - 1) !== ",") + while (iter <= preorder.length && preorder.charAt(iter - 1) !== ",") iter++; } } - return countP === 0 && iter >= preorder.length; + return countP === 0 && iter >= preorder.length; }; module.exports.isValidSerialization = isValidSerialization; diff --git a/LeetcodeProblems/Algorithms/merge_k_sorted_lists.js b/LeetcodeProblems/Algorithms/merge_k_sorted_lists.js index 5a83da1..3d84d7f 100644 --- a/LeetcodeProblems/Algorithms/merge_k_sorted_lists.js +++ b/LeetcodeProblems/Algorithms/merge_k_sorted_lists.js @@ -15,48 +15,45 @@ Input: Output: 1->1->2->3->4->4->5->6 */ -const ListNodeTestHelper = require('../../utilsClasses/ListNodeTestHelper'); +const ListNodeTestHelper = require("../../utilsClasses/ListNodeTestHelper"); -var ListNode = require('../../utilsClasses/ListNode').ListNode; +var ListNode = require("../../utilsClasses/ListNode").ListNode; + +var mergeKLists = function (lists) { + if (lists.length === 0) return null; -var mergeKLists = function(lists) { - if(lists.length === 0) - return null; - var queue = []; - for(var i = 0; i < lists.length; i++) - queue.push(lists[i]); - - while(queue.length > 1) { + for (var i = 0; i < lists.length; i++) queue.push(lists[i]); + + while (queue.length > 1) { list1 = queue.shift(); list2 = queue.shift(); queue.push(mergeLists(list1, list2)); } - + return queue.shift(); }; -var mergeLists = function(list1, list2) { - if(list1 === null) { +var mergeLists = function (list1, list2) { + if (list1 === null) { return list2; - } else if(list2 === null) - return list1; - + } else if (list2 === null) return list1; + var iter1 = list1; - var iter2 = list2; + var iter2 = list2; var head; - - if(iter1.val < iter2.val) { + + if (iter1.val < iter2.val) { head = iter1; - iter1 = iter1.next + iter1 = iter1.next; } else { head = iter2; iter2 = iter2.next; } var iterHead = head; - while(iter1 !== null && iter2 !== null) { - if(iter1.val < iter2.val) { + while (iter1 !== null && iter2 !== null) { + if (iter1.val < iter2.val) { iterHead.next = iter1; iter1 = iter1.next; } else { @@ -66,14 +63,14 @@ var mergeLists = function(list1, list2) { iterHead = iterHead.next; iterHead.next = null; } - - if(iter1 !== null) { + + if (iter1 !== null) { iterHead.next = iter1; - } else if(iter2 !== null) { + } else if (iter2 !== null) { iterHead.next = iter2; } - + return head; -} +}; module.exports.mergeKLists = mergeKLists;