From 3edfcfd85db8a4d4fc15614cd13da8851d0402db Mon Sep 17 00:00:00 2001 From: Ignacio Chiazzo Date: Fri, 7 Dec 2018 00:27:27 -0500 Subject: [PATCH 1/3] Added utils class --- LeetcodeProblems/Add_Two_Numbers.js | 21 +++++++++++++++++---- LeetcodeProblems/BinaryGap.js | 1 + Main.js | 1 + utilsClasses/ListNode.js | 22 ++++++++++++++++++++++ 4 files changed, 41 insertions(+), 4 deletions(-) create mode 100644 utilsClasses/ListNode.js diff --git a/LeetcodeProblems/Add_Two_Numbers.js b/LeetcodeProblems/Add_Two_Numbers.js index f2b68d9..711a0a7 100644 --- a/LeetcodeProblems/Add_Two_Numbers.js +++ b/LeetcodeProblems/Add_Two_Numbers.js @@ -2,7 +2,8 @@ Add Two Numbers https://leetcode.com/problems/add-two-numbers/ -You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. +You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order +and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. @@ -20,16 +21,19 @@ Explanation: 342 + 465 = 807. * this.next = null; * } */ + +var ListNode = require('../utilsClasses/ListNode').ListNode; + /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ - + var addTwoNumbers = function(l1, l2) { - if(l1 === null) { + if(l1 === null) return (l2 === null) ? new ListNode(0) : l2; - } else if(l2 === null) + else if(l2 === null) return l1; var elem = l1.val + l2.val; @@ -62,3 +66,12 @@ var addTwoNumbers = function(l1, l2) { } return head; }; + + +var main = function() { + const list1 = ListNode.linkenList([1,2,3,4]); + const list2 = ListNode.linkenList([1,2,3,4]); + console.log(addTwoNumbers(list1, list2)); +} + +main(); \ No newline at end of file diff --git a/LeetcodeProblems/BinaryGap.js b/LeetcodeProblems/BinaryGap.js index f07f0d5..1a51e19 100644 --- a/LeetcodeProblems/BinaryGap.js +++ b/LeetcodeProblems/BinaryGap.js @@ -1,4 +1,5 @@ /* +Binary Gap https://leetcode.com/problems/binary-gap/description/ Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N. diff --git a/Main.js b/Main.js index 9689d6f..532b015 100644 --- a/Main.js +++ b/Main.js @@ -9,6 +9,7 @@ var main = async function() { for(i in problems) { console.log("Solving: " + problems[i] + ":"); const problem = require(PROBLEMS_FOLDER + problems[i]); + if (typeof(problem.main) !=='undefined') { problem.main(); console.log("End of the solution for : " + problems[i] + ",\n\n"); diff --git a/utilsClasses/ListNode.js b/utilsClasses/ListNode.js new file mode 100644 index 0000000..e9b433b --- /dev/null +++ b/utilsClasses/ListNode.js @@ -0,0 +1,22 @@ +class ListNode { + constructor(val) { + this.val = val; + this.next = null; + } + + static linkenList(arr) { + if(arr.length === 0) + return null; + + var first = new ListNode(arr[0]); + var head = first; + for(var i = 1; i <= arr.length; i++) { + head.next = new ListNode(arr[i]); + head = head.next; + } + + return first; + } +} + +module.exports.ListNode = ListNode; \ No newline at end of file From 815c560c75c344315185d266c23e9f72a63da201 Mon Sep 17 00:00:00 2001 From: Ignacio Chiazzo Date: Fri, 7 Dec 2018 01:36:50 -0500 Subject: [PATCH 2/3] Added gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..551a660 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +tips \ No newline at end of file From 9a03aa5518bb98aa15a59b82114b87d4525fd367 Mon Sep 17 00:00:00 2001 From: Ignacio Chiazzo Date: Fri, 7 Dec 2018 01:37:03 -0500 Subject: [PATCH 3/3] Rename problems and fix identation --- .../{BinaryGap.js => Binary_Gap.js} | 0 .../{CoinChange.js => Coin_Change.js} | 63 ++-------------- ...letionDistance.js => Deletion_Distance.js} | 0 ...ular-deque.js => Design_Circular_Deque.js} | 3 +- ...ape-The-Ghosts.js => Escape_The_Ghosts.js} | 3 +- .../{FloodFill.js => Flood_Fill.js} | 1 + ...Parentheses.js => Generate_Parentheses.js} | 2 +- .../{GroupAnagrams.js => Group_Anagrams.js} | 1 + ...st-cycle-ii.js => Linked_List_Cycle_II.js} | 16 +--- .../Longest_Consecutive_Sequence.js | 2 - .../Longest_Palindromic_Substring.js | 73 +++++++++---------- ...Lowest_Common_Ancestor_of_a_Binary_Tree.js | 68 ++++++++--------- ...MaximunSubarray.js => Maximun_Subarray.js} | 5 +- LeetcodeProblems/Minimum_Window_Substring.js | 1 - LeetcodeProblems/NQueens.js | 4 +- ...g.js => Number_of_Segments_in_a_String.js} | 3 +- ...tes.js => Permutations_With_Duplicates.js} | 0 ....js => Permutations_Without_Duplicates.js} | 0 ...p-addresses.js => Restore_IP_Addresses.js} | 3 +- LeetcodeProblems/Reverse_String_II.js | 18 ++--- LeetcodeProblems/Same_Tree.js | 18 ++--- ...y.js => SearchIng_Rotated_Sorted_Array.js} | 6 +- ...h-a-2D-Matrix.js => Search_a_2D_Matrix.js} | 2 +- ...-Matrix-II.js => Search_a_2D_Matrix_II.js} | 22 +++--- LeetcodeProblems/Simplify_Path.js | 1 - .../{Spiral-matrix.js => Spiral_Matrix.js} | 51 ++++++------- LeetcodeProblems/Symmetric_Tree.js | 24 +++--- .../{TicTacToe.js => Tic_Tac_Toe.js} | 0 ...Trees.js => Unique_Binary_Search_Trees.js} | 48 ++++++------ .../{UniquePaths.js => Unique_Paths.js} | 3 +- LeetcodeProblems/Valid_Parentheses.js | 3 +- 31 files changed, 189 insertions(+), 255 deletions(-) rename LeetcodeProblems/{BinaryGap.js => Binary_Gap.js} (100%) rename LeetcodeProblems/{CoinChange.js => Coin_Change.js} (58%) rename LeetcodeProblems/{deletionDistance.js => Deletion_Distance.js} (100%) rename LeetcodeProblems/{design-circular-deque.js => Design_Circular_Deque.js} (99%) rename LeetcodeProblems/{Escape-The-Ghosts.js => Escape_The_Ghosts.js} (98%) rename LeetcodeProblems/{FloodFill.js => Flood_Fill.js} (99%) rename LeetcodeProblems/{GenerateParentheses.js => Generate_Parentheses.js} (99%) rename LeetcodeProblems/{GroupAnagrams.js => Group_Anagrams.js} (98%) rename LeetcodeProblems/{linked-list-cycle-ii.js => Linked_List_Cycle_II.js} (88%) rename LeetcodeProblems/{MaximunSubarray.js => Maximun_Subarray.js} (93%) rename LeetcodeProblems/{number-of-Segments-in-a-String.js => Number_of_Segments_in_a_String.js} (96%) rename LeetcodeProblems/{PermutationsWithDuplicates.js => Permutations_With_Duplicates.js} (100%) rename LeetcodeProblems/{PermutationsWithoutDuplicates.js => Permutations_Without_Duplicates.js} (100%) rename LeetcodeProblems/{Restore-ip-addresses.js => Restore_IP_Addresses.js} (97%) rename LeetcodeProblems/{SearchInRotatedSortedArray.js => SearchIng_Rotated_Sorted_Array.js} (93%) rename LeetcodeProblems/{Search-a-2D-Matrix.js => Search_a_2D_Matrix.js} (99%) rename LeetcodeProblems/{Search-a-2D-Matrix-II.js => Search_a_2D_Matrix_II.js} (71%) rename LeetcodeProblems/{Spiral-matrix.js => Spiral_Matrix.js} (54%) rename LeetcodeProblems/{TicTacToe.js => Tic_Tac_Toe.js} (100%) rename LeetcodeProblems/{UniqueBinarySearchTrees.js => Unique_Binary_Search_Trees.js} (76%) rename LeetcodeProblems/{UniquePaths.js => Unique_Paths.js} (99%) diff --git a/LeetcodeProblems/BinaryGap.js b/LeetcodeProblems/Binary_Gap.js similarity index 100% rename from LeetcodeProblems/BinaryGap.js rename to LeetcodeProblems/Binary_Gap.js diff --git a/LeetcodeProblems/CoinChange.js b/LeetcodeProblems/Coin_Change.js similarity index 58% rename from LeetcodeProblems/CoinChange.js rename to LeetcodeProblems/Coin_Change.js index 47ab7e0..20e8769 100644 --- a/LeetcodeProblems/CoinChange.js +++ b/LeetcodeProblems/Coin_Change.js @@ -1,50 +1,20 @@ /* +Coin Change +https://leetcode.com/problems/coin-change/ -https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/description/ - -862. Shortest Subarray with Sum at Least K -Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. - -If there is no non-empty subarray with sum at least K, return -1. - - +You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. Example 1: -Input: A = [1], K = 1 -Output: 1 +Input: coins = [1, 2, 5], amount = 11 +Output: 3 +Explanation: 11 = 5 + 5 + 1 Example 2: -Input: A = [1,2], K = 4 +Input: coins = [2], amount = 3 Output: -1 -Example 3: - -Input: A = [2,-1,2], K = 3 -Output: 3 - - Note: - -1 <= A.length <= 50000 --10 ^ 5 <= A[i] <= 10 ^ 5 -1 <= K <= 10 ^ 9 -*/ - - -/* -Tree for solution - - - [pos, countOfNumbers, K] -[pos + 1, countOfNumbers, K] [pos + 1, countOfNumbers + 1, K - nums[pos]] [pos, countOfNumbers + 1, K - nums[pos]] -... - - [0, 0, 11] // [pos, countOfNumbers, K] - / | \ - [1, 0, 11] [1, 1, 10] [0, 1, 10] - / | \ / | \ / | \ -[2, 0, 11] [2, 1, 9] [1, 1, 9] [2, 0, 10] [2, 2, 8] [1, 2, 8] [1, 1, 10] [1, 2, 9] [0, 2, 9] -... +You may assume that you have an infinite number of each kind of coin. */ // Solution 3 @@ -132,24 +102,7 @@ var min = function(a, b, c) { return (b < c) ? b : c; } - function main() { - // console.log("-------------"); - // console.log("Approach 1") - // console.log(coinChange1([], 3)); - // console.log(coinChange1([2], 3)); - // console.log(coinChange1([1, 2, 5], 11)); - // console.log(coinChange1([3,7,405,436], 8839)); - // // console.log(coinChange1([370,417,408,156,143,434,168,83,177,280,117], 9953)); takes forever - - // console.log("-------------"); - // console.log("Approach 2") - // console.log(coinChange2([], 3)); - // console.log(coinChange2([2], 3)); - // console.log(coinChange2([1, 2, 5], 11)); - // console.log(coinChange2([3,7,405,436], 8839)); - // console.log(coinChange2([370,417,408,156,143,434,168,83,177,280,117], 9953)); - console.log("-------------"); console.log("Approach 3") console.log(coinChange3([], 3)); diff --git a/LeetcodeProblems/deletionDistance.js b/LeetcodeProblems/Deletion_Distance.js similarity index 100% rename from LeetcodeProblems/deletionDistance.js rename to LeetcodeProblems/Deletion_Distance.js diff --git a/LeetcodeProblems/design-circular-deque.js b/LeetcodeProblems/Design_Circular_Deque.js similarity index 99% rename from LeetcodeProblems/design-circular-deque.js rename to LeetcodeProblems/Design_Circular_Deque.js index 37d2494..f157f64 100644 --- a/LeetcodeProblems/design-circular-deque.js +++ b/LeetcodeProblems/Design_Circular_Deque.js @@ -1,4 +1,5 @@ /* +Design Circular Deque https://leetcode.com/problems/design-circular-deque/description/ Design your implementation of the circular double-ended queue (deque). @@ -145,5 +146,5 @@ var main = function(){ console.log(obj.insertFront(4)); console.log(obj.getFront()); } -main(); + module.exports.main = main; diff --git a/LeetcodeProblems/Escape-The-Ghosts.js b/LeetcodeProblems/Escape_The_Ghosts.js similarity index 98% rename from LeetcodeProblems/Escape-The-Ghosts.js rename to LeetcodeProblems/Escape_The_Ghosts.js index 4696340..9df11ea 100644 --- a/LeetcodeProblems/Escape-The-Ghosts.js +++ b/LeetcodeProblems/Escape_The_Ghosts.js @@ -1,8 +1,7 @@ /* +Escape The Ghosts https://leetcode.com/problems/escape-the-ghosts/description/ -789. Escape The Ghosts - You are playing a simplified Pacman game. You start at the point (0, 0), and your destination is (target[0], target[1]). There are several ghosts on the map, the i-th ghost starts at (ghosts[i][0], ghosts[i][1]). Each turn, you and all ghosts simultaneously *may* move in one of 4 cardinal directions: north, east, west, or south, going from the previous point to a new point 1 unit of distance away. diff --git a/LeetcodeProblems/FloodFill.js b/LeetcodeProblems/Flood_Fill.js similarity index 99% rename from LeetcodeProblems/FloodFill.js rename to LeetcodeProblems/Flood_Fill.js index e4f2f00..8228be6 100644 --- a/LeetcodeProblems/FloodFill.js +++ b/LeetcodeProblems/Flood_Fill.js @@ -1,4 +1,5 @@ /* +Flood Fill https://leetcode.com/problems/flood-fill/description/ An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). diff --git a/LeetcodeProblems/GenerateParentheses.js b/LeetcodeProblems/Generate_Parentheses.js similarity index 99% rename from LeetcodeProblems/GenerateParentheses.js rename to LeetcodeProblems/Generate_Parentheses.js index 69f19af..227bbc4 100644 --- a/LeetcodeProblems/GenerateParentheses.js +++ b/LeetcodeProblems/Generate_Parentheses.js @@ -1,4 +1,5 @@ /* +Generate Parentheses https://leetcode.com/problems/generate-parentheses Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. @@ -31,7 +32,6 @@ var generateParenthesesApproach1 = function(n) { @param {string} leftParenthesis Amount for parenthesis left to be added. @param {[string]} sol array that contains the solution found so far. */ - var genParAux = function(str, position, leftParentheses, sol) { if(position === str.length) { var ret = str + ")".repeat(leftParentheses); diff --git a/LeetcodeProblems/GroupAnagrams.js b/LeetcodeProblems/Group_Anagrams.js similarity index 98% rename from LeetcodeProblems/GroupAnagrams.js rename to LeetcodeProblems/Group_Anagrams.js index 3c491ef..6216408 100644 --- a/LeetcodeProblems/GroupAnagrams.js +++ b/LeetcodeProblems/Group_Anagrams.js @@ -1,4 +1,5 @@ /* +Group Anagrams https://leetcode.com/problems/group-anagrams/description/ Given an array of strings, group anagrams together. diff --git a/LeetcodeProblems/linked-list-cycle-ii.js b/LeetcodeProblems/Linked_List_Cycle_II.js similarity index 88% rename from LeetcodeProblems/linked-list-cycle-ii.js rename to LeetcodeProblems/Linked_List_Cycle_II.js index df45d91..4f5db0d 100644 --- a/LeetcodeProblems/linked-list-cycle-ii.js +++ b/LeetcodeProblems/Linked_List_Cycle_II.js @@ -1,4 +1,5 @@ /* +Linked List Cycle https://leetcode.com/problems/linked-list-cycle-ii/description/ Given a linked list, return the node where the cycle begins. If there is no cycle, return null. @@ -9,6 +10,7 @@ Follow up: Can you solve it without using extra space? */ +var ListNode = require('../utilsClasses/ListNode').ListNode; // Optimal solution /** @@ -59,15 +61,9 @@ var main = function() { const head = buildCycle(); console.log(detectCycle(head)); } -main(); - -function ListNode(val) { - this.val = val; - this.next = null; -} function buildCycle() { - var node1 = new ListNode(1); + var node1 = ListNode.linkenList([1,2,3,4,5]); var node2 = new ListNode(2); var node3 = new ListNode(3); var node4 = new ListNode(4); @@ -78,13 +74,7 @@ function buildCycle() { node3.next = node4; node4.next = node5; node5.next = node2; - - /* 1 -> 2 -> 3 -> 4 -> 5 - \ / - - - - - - - */ return node1; } -main(); module.exports.main = main; diff --git a/LeetcodeProblems/Longest_Consecutive_Sequence.js b/LeetcodeProblems/Longest_Consecutive_Sequence.js index 8b53879..9eb8816 100644 --- a/LeetcodeProblems/Longest_Consecutive_Sequence.js +++ b/LeetcodeProblems/Longest_Consecutive_Sequence.js @@ -1,6 +1,5 @@ /* Longest Consecutive Sequence - https://leetcode.com/problems/longest-consecutive-sequence/ Given an unsorted array of integers, find the length of the longest consecutive elements sequence. @@ -53,7 +52,6 @@ var longestConsecutive = function(nums) { return cons; }; - var main = function() { console.log(longestConsecutive([100, 1, 200, 3, 2, 400, 201])); console.log(longestConsecutive([1,2,3,4, 100, 1, 200, 3, 2, 400, 201])); diff --git a/LeetcodeProblems/Longest_Palindromic_Substring.js b/LeetcodeProblems/Longest_Palindromic_Substring.js index 7dd1bc9..f20aaeb 100644 --- a/LeetcodeProblems/Longest_Palindromic_Substring.js +++ b/LeetcodeProblems/Longest_Palindromic_Substring.js @@ -1,7 +1,6 @@ /* -https://leetcode.com/problems/longest-palindromic-substring/description/ - Longest Palindromic Substring +https://leetcode.com/problems/longest-palindromic-substring/description/ Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. @@ -16,7 +15,6 @@ Input: "cbbd" Output: "bb" */ - /** * @param {string} s * @return {string} @@ -25,46 +23,45 @@ var longestPalindrome = function(str) { if(str.length == 0) return ""; - var maxPal = 1; + var maxPal = 1; var posPalStart = 0; - var currentPalStart = 0; + var currentPalStart = 0; for(var i = 1; i < str.length; i++) { - if(str.charAt(i - 1) == str.charAt(i)) { - currentPalStart = i - 1; - var currentPal = 2; - var iter = 1; - 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) { - maxPal = currentPal; - posPalStart = currentPalStart; - } + if(str.charAt(i - 1) == str.charAt(i)) { + currentPalStart = i - 1; + var currentPal = 2; + var iter = 1; + 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) { + maxPal = currentPal; + posPalStart = currentPalStart; + } + } + + 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)) { + currentPalStart = i - iter; + iter++; + currentPal += 2; + } } - - 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)) { - currentPalStart = i - iter; - iter++; - currentPal += 2; - } - } - if(currentPal > maxPal) { - maxPal = currentPal; - posPalStart = currentPalStart; - } + if(currentPal > maxPal) { + maxPal = currentPal; + posPalStart = currentPalStart; } - - return str.slice(posPalStart, posPalStart + maxPal); + } + + return str.slice(posPalStart, posPalStart + maxPal); } var main = function() { diff --git a/LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree.js b/LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree.js index 8144035..9da37fd 100644 --- a/LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree.js +++ b/LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree.js @@ -1,6 +1,5 @@ /* Lowest Common Ancestor of a Binary Tree - https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. @@ -33,53 +32,56 @@ All of the nodes' values will be unique. p and q are different and both values will exist in the binary tree. */ +// Solution 1 var lowestCommonAncestor = function(root, p, q) { - if(root === null) { + if(root === null) return root; - } - if(p.val === root.val) { + if(p.val === root.val) return p; - } - if(q.val === root.val) { + if(q.val === root.val) return q; - } - if(lowestCommonAncestor(root.left, p, q)); + + const left = lowestCommonAncestor(root.left, p, q); const right = lowestCommonAncestor(root.right, p, q); - if(left !== null && right !== null) { + if(left !== null && right !== null) return root; - } return left !== null ? left : right; }; + +// Solution 2 var lowestCommonAncestor1 = function(root, p, q) { const pathToP = pathTo(root, p.val); - const pathToQ = pathTo(root, q.val); - var elem = null; - for(var i = 0; i < Math.min(pathToP.length, pathToQ.length); i++) { - if(pathToP[i] !== pathToQ[i]) { - return pathToP[i - 1]; - } - } + const pathToQ = pathTo(root, q.val); + + if(pathToP === null || pathToQ === null) + return null; + + if(pathToP.length === 1) + return pathToP[0]; + if(pathToQ.length === 1) + return pathToQ[0]; + + var iter = 0; + while(pathToP[iter + 1] === pathToQ[iter + 1]) + iter++ - return elem; + return pathToP[iter]; }; var pathTo = function(root, a) { - if(root === null) { - return null; - } - if(root.val === a) { - return [root.val]; - } - const left = pathTo(root.left, a); - if (left !== null) { - return [root.val] + left; - } - const right = pathTo(root.right, a); - if(right !== null) { - return [root.val] + right; - } + if(root === null) return null; -} + if(root.val === a) + return [root.val]; + const left = pathTo(root.left, a); + if (left !== null) + return [root.val].concat(left); + const right = pathTo(root.right, a); + if(right !== null) + return [root.val].concat(right); + + return null; +} diff --git a/LeetcodeProblems/MaximunSubarray.js b/LeetcodeProblems/Maximun_Subarray.js similarity index 93% rename from LeetcodeProblems/MaximunSubarray.js rename to LeetcodeProblems/Maximun_Subarray.js index 62029e9..652ffd7 100644 --- a/LeetcodeProblems/MaximunSubarray.js +++ b/LeetcodeProblems/Maximun_Subarray.js @@ -1,7 +1,7 @@ /* +Maximum Subarray https://leetcode.com/problems/maximum-subarray/submissions/1 -. Maximum Subarray Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: @@ -20,9 +20,8 @@ var maxSubArray = function(nums) { for(var i = 1; i < nums.length; i++) { currentMax = max(nums[i], currentMax + nums[i]); - if(currentMax > maxSub) { + if(currentMax > maxSub) maxSub = currentMax; - } } return maxSub; diff --git a/LeetcodeProblems/Minimum_Window_Substring.js b/LeetcodeProblems/Minimum_Window_Substring.js index 69403bc..426601e 100644 --- a/LeetcodeProblems/Minimum_Window_Substring.js +++ b/LeetcodeProblems/Minimum_Window_Substring.js @@ -1,6 +1,5 @@ /* Minimum Window Substring - https://leetcode.com/problems/minimum-window-substring/ Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). diff --git a/LeetcodeProblems/NQueens.js b/LeetcodeProblems/NQueens.js index 364672e..d4fe5be 100644 --- a/LeetcodeProblems/NQueens.js +++ b/LeetcodeProblems/NQueens.js @@ -1,4 +1,6 @@ -/* https://leetcode.com/problems/n-queens/description/ +/* +NQueens +https://leetcode.com/problems/n-queens/description/ Example: diff --git a/LeetcodeProblems/number-of-Segments-in-a-String.js b/LeetcodeProblems/Number_of_Segments_in_a_String.js similarity index 96% rename from LeetcodeProblems/number-of-Segments-in-a-String.js rename to LeetcodeProblems/Number_of_Segments_in_a_String.js index 0ba5c41..66a8f2e 100644 --- a/LeetcodeProblems/number-of-Segments-in-a-String.js +++ b/LeetcodeProblems/Number_of_Segments_in_a_String.js @@ -1,6 +1,5 @@ /* - -434. Number of Segments in a String +Number of Segments in a String https://leetcode.com/problems/number-of-segments-in-a-string/description/ Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. diff --git a/LeetcodeProblems/PermutationsWithDuplicates.js b/LeetcodeProblems/Permutations_With_Duplicates.js similarity index 100% rename from LeetcodeProblems/PermutationsWithDuplicates.js rename to LeetcodeProblems/Permutations_With_Duplicates.js diff --git a/LeetcodeProblems/PermutationsWithoutDuplicates.js b/LeetcodeProblems/Permutations_Without_Duplicates.js similarity index 100% rename from LeetcodeProblems/PermutationsWithoutDuplicates.js rename to LeetcodeProblems/Permutations_Without_Duplicates.js diff --git a/LeetcodeProblems/Restore-ip-addresses.js b/LeetcodeProblems/Restore_IP_Addresses.js similarity index 97% rename from LeetcodeProblems/Restore-ip-addresses.js rename to LeetcodeProblems/Restore_IP_Addresses.js index 6ec06c4..6cde69f 100644 --- a/LeetcodeProblems/Restore-ip-addresses.js +++ b/LeetcodeProblems/Restore_IP_Addresses.js @@ -1,8 +1,7 @@ /* +Restore IP Addresses https://leetcode.com/problems/restore-ip-addresses/description/ -93. Restore IP Addresses - Given a string containing only digits, restore it by returning all possible valid IP address combinations. Example: diff --git a/LeetcodeProblems/Reverse_String_II.js b/LeetcodeProblems/Reverse_String_II.js index 3c4c408..d17b02b 100644 --- a/LeetcodeProblems/Reverse_String_II.js +++ b/LeetcodeProblems/Reverse_String_II.js @@ -1,7 +1,5 @@ /* - Reverse String II - https://leetcode.com/problems/reverse-string-ii/description/ Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original. @@ -17,11 +15,11 @@ var reverseStr = function(s, k) { return s; var ret = ""; for(var iterK = 0; iterK * k < s.length; iterK = iterK + 2) { - const start = iterK * k; - const end = start + k - 1; - - ret += reverse(s, start, end); - ret += s.slice(end + 1, k * (iterK + 2)); + const start = iterK * k; + const end = start + k - 1; + + ret += reverse(s, start, end); + ret += s.slice(end + 1, k * (iterK + 2)); } return ret; @@ -30,11 +28,11 @@ var reverseStr = function(s, k) { var reverse = function(s, start, end) { var ret = ""; if(end >= s.length) - end = s.length - 1; + end = s.length - 1; while(start <= end) { - ret += s.charAt(end); - end--; + ret += s.charAt(end); + end--; } return ret; } diff --git a/LeetcodeProblems/Same_Tree.js b/LeetcodeProblems/Same_Tree.js index fad7b80..31b8664 100644 --- a/LeetcodeProblems/Same_Tree.js +++ b/LeetcodeProblems/Same_Tree.js @@ -1,8 +1,8 @@ /* - +Same Tree https://leetcode.com/problems/same-tree/description/ -Given two binary trees, write a function to check if they are the same or not. +Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example 1: @@ -47,11 +47,11 @@ Output: false * @return {boolean} */ 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); + 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/SearchInRotatedSortedArray.js b/LeetcodeProblems/SearchIng_Rotated_Sorted_Array.js similarity index 93% rename from LeetcodeProblems/SearchInRotatedSortedArray.js rename to LeetcodeProblems/SearchIng_Rotated_Sorted_Array.js index c01bdc2..90600fb 100644 --- a/LeetcodeProblems/SearchInRotatedSortedArray.js +++ b/LeetcodeProblems/SearchIng_Rotated_Sorted_Array.js @@ -1,8 +1,8 @@ /* -33. Search in Rotated Sorted Array -DescriptionHintsSubmissionsDiscussSolution -Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. +Search in Rotated Sorted Array +https://leetcode.com/problems/search-in-rotated-sorted-array/ +Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. diff --git a/LeetcodeProblems/Search-a-2D-Matrix.js b/LeetcodeProblems/Search_a_2D_Matrix.js similarity index 99% rename from LeetcodeProblems/Search-a-2D-Matrix.js rename to LeetcodeProblems/Search_a_2D_Matrix.js index c98263b..3e8f980 100644 --- a/LeetcodeProblems/Search-a-2D-Matrix.js +++ b/LeetcodeProblems/Search_a_2D_Matrix.js @@ -1,4 +1,5 @@ /* +Search a 2D Matrix https://leetcode.com/problems/search-a-2d-matrix/description/ Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: @@ -83,5 +84,4 @@ var main = function(){ console.log(searchMatrix(matrix, 3)); } -main(); module.exports.main = main; diff --git a/LeetcodeProblems/Search-a-2D-Matrix-II.js b/LeetcodeProblems/Search_a_2D_Matrix_II.js similarity index 71% rename from LeetcodeProblems/Search-a-2D-Matrix-II.js rename to LeetcodeProblems/Search_a_2D_Matrix_II.js index e4e0940..e34a2f5 100644 --- a/LeetcodeProblems/Search-a-2D-Matrix-II.js +++ b/LeetcodeProblems/Search_a_2D_Matrix_II.js @@ -1,7 +1,9 @@ /* +Search a 2D Matrix II https://leetcode.com/problems/search-a-2d-matrix-ii/description/ - Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: - Integers in each row are sorted in ascending from left to right. + +Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: +Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example: Consider the following matrix: @@ -23,18 +25,18 @@ Given target = 20, return false. */ var searchMatrix = function(matrix, target) { if (matrix.length == 0) - return false + return false var lastCol = matrix[0].length - 1; var firstRow = 0; while(lastCol >= 0 && firstRow < matrix.length) { - if(matrix[firstRow][lastCol] == target) { - return true; - } else if(matrix[firstRow][lastCol] > target) { - lastCol--; - } else { - firstRow++; - } + if(matrix[firstRow][lastCol] == target) { + return true; + } else if(matrix[firstRow][lastCol] > target) { + lastCol--; + } else { + firstRow++; + } } return false; diff --git a/LeetcodeProblems/Simplify_Path.js b/LeetcodeProblems/Simplify_Path.js index 58e6eb8..61d1208 100644 --- a/LeetcodeProblems/Simplify_Path.js +++ b/LeetcodeProblems/Simplify_Path.js @@ -1,6 +1,5 @@ /* Simplify Path - https://leetcode.com/problems/simplify-path/description/ Given an absolute path for a file (Unix-style), simplify it. diff --git a/LeetcodeProblems/Spiral-matrix.js b/LeetcodeProblems/Spiral_Matrix.js similarity index 54% rename from LeetcodeProblems/Spiral-matrix.js rename to LeetcodeProblems/Spiral_Matrix.js index 619e2ec..f11c512 100644 --- a/LeetcodeProblems/Spiral-matrix.js +++ b/LeetcodeProblems/Spiral_Matrix.js @@ -1,4 +1,5 @@ /* +Spiral Matrix https://leetcode.com/problems/spiral-matrix/description/ Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. @@ -30,38 +31,39 @@ Output: [1,2,3,4,8,12,11,10,9,5,6,7] var spiralOrder = function(matrix) { if(matrix.length === 0) - return []; + 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); - } + for(var i = 0; i < countRectangles; i++) + printRect(matrix, i, rowLength, colLength, retArray); + return 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++) { - retArray.push(matrix[firstRow][col]); - } - for(var row = firstRow + 1; row <= lastRow; row++) { - retArray.push(matrix[row][lastCol]); - } - if(firstRow === lastRow || firstCol === lastCol) { - return; - } - for(var col = lastCol - 1; col >= firstCol; col--) { - retArray.push(matrix[lastRow][col]); - } - for(var row = lastRow - 1; row > firstRow; row--) { - retArray.push(matrix[row][firstCol]); - } + const firstRow = i; + const firstCol = i; + const lastRow = rowLength - i - 1; + const lastCol = colLength - i - 1; + + for(var col = firstCol; col <= lastCol; col++) { + retArray.push(matrix[firstRow][col]); + } + for(var row = firstRow + 1; row <= lastRow; row++) { + retArray.push(matrix[row][lastCol]); + } + if(firstRow === lastRow || firstCol === lastCol) { + return; + } + for(var col = lastCol - 1; col >= firstCol; col--) { + retArray.push(matrix[lastRow][col]); + } + for(var row = lastRow - 1; row > firstRow; row--) { + retArray.push(matrix[row][firstCol]); + } } var main = function() { @@ -74,5 +76,4 @@ var main = function() { console.log(spiralOrder(matrix)); } -main(); module.exports.main = main; diff --git a/LeetcodeProblems/Symmetric_Tree.js b/LeetcodeProblems/Symmetric_Tree.js index 27ca75b..76b365f 100644 --- a/LeetcodeProblems/Symmetric_Tree.js +++ b/LeetcodeProblems/Symmetric_Tree.js @@ -1,6 +1,5 @@ /* Symmetric Tree - https://leetcode.com/problems/symmetric-tree/description/ Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). @@ -29,23 +28,24 @@ Bonus points if you could solve it both recursively and iteratively. * this.left = this.right = null; * } */ + /** * @param {TreeNode} root * @return {boolean} */ var isSymmetric = function(root) { - if(root === null) - return true; - return isSymetricAux(root.left, root.right); + 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) { - return false; - } - - return isSymetricAux(root1.left, root2.right) && isSymetricAux(root1.right, root2.left); + 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); } diff --git a/LeetcodeProblems/TicTacToe.js b/LeetcodeProblems/Tic_Tac_Toe.js similarity index 100% rename from LeetcodeProblems/TicTacToe.js rename to LeetcodeProblems/Tic_Tac_Toe.js diff --git a/LeetcodeProblems/UniqueBinarySearchTrees.js b/LeetcodeProblems/Unique_Binary_Search_Trees.js similarity index 76% rename from LeetcodeProblems/UniqueBinarySearchTrees.js rename to LeetcodeProblems/Unique_Binary_Search_Trees.js index 3e657f5..7e156a3 100644 --- a/LeetcodeProblems/UniqueBinarySearchTrees.js +++ b/LeetcodeProblems/Unique_Binary_Search_Trees.js @@ -1,9 +1,8 @@ /* +Unique Binary Search Trees https://leetcode.com/problems/unique-binary-search-trees/description/ -96. Unique Binary Search Trees - Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? Example: @@ -51,26 +50,25 @@ var numTrees2 = function(n) { var numTreesAux2 = function(leftMin, leftMax, memo) { const keyMemo = buildKey(leftMin, leftMax); - if(memo[keyMemo]) { + if(memo[keyMemo]) return memo[keyMemo] - } if(leftMin > leftMax) - return 0; + return 0; if(leftMin === leftMax) - return 1; + return 1; var count = 0; 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; - } else { - count += (left > 0) ? left : right; - } + const left = numTreesAux2(leftMin, i - 1, memo); + const right = numTreesAux2(i + 1, leftMax, memo); + + if(left > 0 && right > 0) { + count += left * right; + } else { + count += (left > 0) ? left : right; + } } memo[keyMemo] = count; @@ -89,21 +87,21 @@ var numTrees1 = function(n) { var numTreesAux1 = function(leftMin, leftMax) { if(leftMin > leftMax) - return 0; + return 0; if(leftMin === leftMax) - return 1; + return 1; var count = 0; 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; - } else { - count += (left > 0) ? left : right; - } + const left = numTreesAux1(leftMin, i - 1); + const right = numTreesAux1(i + 1, leftMax); + + if(left > 0 && right > 0) { + count += left * right; + } else { + count += (left > 0) ? left : right; + } } return count; @@ -126,6 +124,4 @@ var main = function() { console.log(numTrees3(5)); } -main(); - module.exports.main = main diff --git a/LeetcodeProblems/UniquePaths.js b/LeetcodeProblems/Unique_Paths.js similarity index 99% rename from LeetcodeProblems/UniquePaths.js rename to LeetcodeProblems/Unique_Paths.js index a80a38e..01f8be9 100644 --- a/LeetcodeProblems/UniquePaths.js +++ b/LeetcodeProblems/Unique_Paths.js @@ -1,6 +1,5 @@ /* - -62. Unique Paths +Unique Paths https://leetcode.com/problems/unique-paths/description/ A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). diff --git a/LeetcodeProblems/Valid_Parentheses.js b/LeetcodeProblems/Valid_Parentheses.js index c58f93c..710652f 100644 --- a/LeetcodeProblems/Valid_Parentheses.js +++ b/LeetcodeProblems/Valid_Parentheses.js @@ -1,6 +1,5 @@ /* Valid Parentheses - https://leetcode.com/problems/valid-parentheses/description/ Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. @@ -43,7 +42,7 @@ var isValid = function(s) { queue.unshift(elem); } else { if(queue.length === 0) - return false; + return false; const elemQueue = queue.shift(); if(elemQueue === "(" && elem !== ")" ||