diff --git a/LeetcodeProblems/3Sum.js b/LeetcodeProblems/3Sum.js index e5aee95..c5d4ec8 100644 --- a/LeetcodeProblems/3Sum.js +++ b/LeetcodeProblems/3Sum.js @@ -18,7 +18,6 @@ A solution set is: [-1, -1, 2] ] */ -const assert = require('assert'); /** * @param {number[]} nums @@ -49,26 +48,4 @@ var threeSum = function(nums) { return ret; }; -var main = function() { - test(); -} - -var test = function () { - assert.deepEqual(threeSum([]), []); - assert.deepEqual(threeSum([0]), []); - assert.deepEqual(threeSum([0, 0]), []); - assert.deepEqual( - threeSum([0, 0, 0]), - [[0, 0, 0]] - ); - assert.deepEqual( - threeSum([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), - [[0, 0, 0]] - ); - assert.deepEqual( - threeSum([-1, 0, 1, 2, -1, -4]), - [ [ -1, 2, -1 ], [ 0, 1, -1 ] ] - ); -} - -module.exports.main = main; +module.exports.threeSum = threeSum; diff --git a/LeetcodeProblems/Add_Two_Numbers.js b/LeetcodeProblems/Add_Two_Numbers.js index 53a00c1..958448f 100644 --- a/LeetcodeProblems/Add_Two_Numbers.js +++ b/LeetcodeProblems/Add_Two_Numbers.js @@ -21,10 +21,8 @@ Explanation: 342 + 465 = 807. * this.next = null; * } */ -const assert = require('assert'); -const ListNodeTestHelper = require('../utilsClasses/ListNodeTestHelper'); var ListNode = require('../UtilsClasses/ListNode').ListNode; - + /** * @param {ListNode} l1 * @param {ListNode} l2 @@ -64,31 +62,4 @@ var addTwoNumbers = function(l1, l2) { return head; }; -var main = function() { - test(); -} - -function test() { - const list1 = ListNode.linkenList([1,2,3,4]); - const list2 = ListNode.linkenList([1,2,3,4]); - ListNodeTestHelper.assertList( - addTwoNumbers(list1, list2), - [2, 4, 6, 8] - ); - - const list3 = ListNode.linkenList([1]); - const list4 = ListNode.linkenList([1,2]); - ListNodeTestHelper.assertList( - addTwoNumbers(list3, list4), - [2, 2] - ); - - const list5 = ListNode.linkenList([]); - const list6 = ListNode.linkenList([1,2]); - ListNodeTestHelper.assertList( - addTwoNumbers(list5, list6), - [1, 2] - ); -} - -module.exports.main = main; +module.exports.addTwoNumbers = addTwoNumbers; diff --git a/LeetcodeProblems/Award_Budget_Cuts.js b/LeetcodeProblems/Award_Budget_Cuts.js index 1a8ad15..b9efb99 100644 --- a/LeetcodeProblems/Award_Budget_Cuts.js +++ b/LeetcodeProblems/Award_Budget_Cuts.js @@ -29,8 +29,6 @@ Constraints: [output] double */ -const assert = require('assert'); - var cutAwardBadges = function(nums, newBadge) { var currentBadge = 0; for(var i = 0; i < nums.length; i++) @@ -66,19 +64,4 @@ var findCap = function(nums, currentBadge, newBadge) { return nums[iter] + (-diff) / iter; } -var main = function() { - test(); -} - -function test() { - assert.deepEqual( - cutAwardBadges([2, 100, 50, 120, 1000], 190), - [ 47, 47, 47, 47, 2 ] - ); - assert.deepEqual( - cutAwardBadges([2, 100, 50, 120, 1000], 5), - [ 1, 1, 1, 1, 1 ] - ); -} - -module.exports.main = main; +module.exports.cutAwardBadges = cutAwardBadges; diff --git a/LeetcodeProblems/Backspace_String_Compare.js b/LeetcodeProblems/Backspace_String_Compare.js index 67c4126..f7051af 100644 --- a/LeetcodeProblems/Backspace_String_Compare.js +++ b/LeetcodeProblems/Backspace_String_Compare.js @@ -31,7 +31,6 @@ Follow up: Can you solve it in O(N) time and O(1) space? */ -const assert = require('assert'); /** * @param {string} S @@ -106,20 +105,5 @@ var backspaceCompare2 = function(S, T) { return stackS.length === 0 && stackT.length === 0; }; -var main = function() { - test(); -} - -function test() { - assert.equal(backspaceCompare("ab#c", "ad#c"), true); // true - assert.equal(backspaceCompare("ab##", "c#d#"), true); // true - assert.equal(backspaceCompare("a##c", "#a#c"), true); // true - assert.equal(backspaceCompare("a#c", "b"), false); // false - - assert.equal(backspaceCompare2("ab#c", "ad#c"), true); // true - assert.equal(backspaceCompare2("ab##", "c#d#"), true); // true - assert.equal(backspaceCompare2("a##c", "#a#c"), true); // true - assert.equal(backspaceCompare2("a#c", "b"), false); // false -} - -module.exports.main = main; +module.exports.backspaceCompare = backspaceCompare; +module.exports.backspaceCompare2 = backspaceCompare2; diff --git a/LeetcodeProblems/Best_Time_To_Buy_And_Sell_Stock_II.js b/LeetcodeProblems/Best_Time_To_Buy_And_Sell_Stock_II.js index 1179880..0dd7138 100644 --- a/LeetcodeProblems/Best_Time_To_Buy_And_Sell_Stock_II.js +++ b/LeetcodeProblems/Best_Time_To_Buy_And_Sell_Stock_II.js @@ -27,7 +27,6 @@ Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0. */ -const assert = require('assert'); /** * @param {number[]} prices @@ -56,13 +55,4 @@ var maxProfit = function(prices) { return profit; }; -var main = function() { - test(); -} - -function test() { - assert.equal(maxProfit([7,1,5,3,6,4]), 7); - assert.equal(maxProfit([7,1,5,3320,6,4]), 3319); -} - -module.exports.main = main; \ No newline at end of file +module.exports.maxProfit = maxProfit; \ No newline at end of file diff --git a/LeetcodeProblems/Binary_Gap.js b/LeetcodeProblems/Binary_Gap.js index 0385125..4b07e8c 100644 --- a/LeetcodeProblems/Binary_Gap.js +++ b/LeetcodeProblems/Binary_Gap.js @@ -36,7 +36,6 @@ Explanation: 8 in binary is 0b1000. There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0. */ -const assert = require('assert'); /** * @param {number} N @@ -61,13 +60,4 @@ var binaryGap = function(N) { return maxDist; }; -var main = function() { - test(); -} - -function test() { - assert.equal(binaryGap(22), 2); // 10110 - assert.equal(binaryGap(8), 0); // 1000 -} - -module.exports.main = main; +module.exports.binaryGap = binaryGap; diff --git a/LeetcodeProblems/Clone_Graph.js b/LeetcodeProblems/Clone_Graph.js index ee74cdd..0531e8d 100644 --- a/LeetcodeProblems/Clone_Graph.js +++ b/LeetcodeProblems/Clone_Graph.js @@ -40,7 +40,6 @@ You don't need to understand the serialization to solve the problem. * } */ - // SOLUTION 1 Using DFS /** * @param {UndirectedGraphNode} graph diff --git a/LeetcodeProblems/Coin_Change.js b/LeetcodeProblems/Coin_Change.js index 716465c..51ca9a0 100644 --- a/LeetcodeProblems/Coin_Change.js +++ b/LeetcodeProblems/Coin_Change.js @@ -18,7 +18,6 @@ Output: -1 Note: You may assume that you have an infinite number of each kind of coin. */ -const assert = require('assert'); // Solution 3 var coinChange = function(coins, amount) { @@ -102,16 +101,4 @@ var min = function(a, b, c) { return (b < c) ? b : c; } -function main() { - test(); -} - -function test() { - assert.equal(coinChange([], 3), -1); - assert.equal(coinChange([2], 3), -1); - assert.equal(coinChange([1, 2, 5], 11), 3); - assert.equal(coinChange([3, 7, 405, 436], 8839), 25); - assert.equal(coinChange([370, 417, 408, 156, 143, 434, 168, 83, 177, 280, 117], 9953), 24); -} - -module.exports.main = main; \ No newline at end of file +module.exports.coinChange = coinChange; diff --git a/LeetcodeProblems/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js b/LeetcodeProblems/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js index da702cc..03a5dc1 100644 --- a/LeetcodeProblems/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js +++ b/LeetcodeProblems/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js @@ -27,8 +27,6 @@ Return the following binary tree: * this.left = this.right = null; * } */ -const assert = require('assert'); - var TreeNode = require('../UtilsClasses/TreeNode').TreeNode; /** @@ -59,12 +57,4 @@ var buildTreeAux = function(preorder, pl, ph, inorder, il, ih) { return ret; } -var main = function() { - test(); -} - -function test() { - console.log(buildTree([3,9,20,15,7], [9,3,15,20,7])); -} - -module.exports.main = main +module.exports.buildTree = buildTree diff --git a/LeetcodeProblems/Deletion_Distance.js b/LeetcodeProblems/Deletion_Distance.js index 2714fb3..6e7dbd0 100644 --- a/LeetcodeProblems/Deletion_Distance.js +++ b/LeetcodeProblems/Deletion_Distance.js @@ -18,7 +18,6 @@ output: 9 input: str1 = "", str2 = "" output: 0 */ -const assert = require('assert'); // Solution 3 Using DP var deletionDistanceDP = function(str1, str2) { @@ -107,25 +106,6 @@ var min = function(a, b) { return (a < b) ? a : b; } -function main() { - test(); -} - -function test() { - assert.equal(deletionDistance("dog", "frog"), 3); - assert.equal(deletionDistance("some", "some"), 0); - assert.equal(deletionDistance("some", "thing"), 9); - assert.equal(deletionDistance("", ""), 0); - - assert.equal(deletionDistance2("dog", "frog"), 3); - assert.equal(deletionDistance2("some", "some"), 0); - assert.equal(deletionDistance2("some", "thing"), 9); - assert.equal(deletionDistance2("", ""), 0); - - assert.equal(deletionDistanceDP("dog", "frog"), 3); - assert.equal(deletionDistanceDP("some", "some"), 0); - assert.equal(deletionDistanceDP("some", "thing"), 9); - assert.equal(deletionDistanceDP("", ""), 0); -} - -module.exports.main = main +module.exports.deletionDistance = deletionDistance; +module.exports.deletionDistance2 = deletionDistance2; +module.exports.deletionDistanceDP = deletionDistanceDP; diff --git a/LeetcodeProblems/Design_Circular_Deque.js b/LeetcodeProblems/Design_Circular_Deque.js index 60dace9..df6a123 100644 --- a/LeetcodeProblems/Design_Circular_Deque.js +++ b/LeetcodeProblems/Design_Circular_Deque.js @@ -35,7 +35,6 @@ All values will be in the range of [0, 1000]. The number of operations will be in the range of [1, 1000]. Please do not use the built-in Deque library. */ -const assert = require('assert'); /** * Initialize your data structure here. Set the size of the deque to be k. @@ -132,21 +131,4 @@ MyCircularDeque.prototype.isFull = function() { return this.queue.length === this.maxSize; }; -var main = function(){ - test(); -}; - -var test = function() { - const obj = new MyCircularDeque(3); - assert.equal(obj.insertLast(1), true); - assert.equal(obj.insertLast(2), true); - assert.equal(obj.insertFront(3), true); - assert.equal(obj.insertFront(4), false); - assert.equal(obj.getRear(), 2); - assert.equal(obj.isFull(), true); - assert.equal(obj.deleteLast(), true); - assert.equal(obj.insertFront(4), true); - assert.equal(obj.getFront(), 4); -} - -module.exports.main = main; +module.exports.MyCircularDeque = MyCircularDeque; diff --git a/LeetcodeProblems/Edit_Distance.js b/LeetcodeProblems/Edit_Distance.js index c337677..73d4e47 100644 --- a/LeetcodeProblems/Edit_Distance.js +++ b/LeetcodeProblems/Edit_Distance.js @@ -28,7 +28,6 @@ enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') */ -const assert = require('assert'); // Optimal solution var minDistance = function(word1, word2) { @@ -98,16 +97,5 @@ var min = function(a, b, c) { return (b < c) ? b : c; } -var main = function() { - test(); -} - -function test() { - assert.equal(minDistance("ros", "horse"), 3); - assert.equal(minDistance("intention", "execution"), 5); - - assert.equal(minDistance2("ros", "horse"), 3); - assert.equal(minDistance2("intention", "execution"), 5); -} - -module.exports.main = main; +module.exports.minDistance = minDistance; +module.exports.minDistance2 = minDistance2; diff --git a/LeetcodeProblems/Escape_The_Ghosts.js b/LeetcodeProblems/Escape_The_Ghosts.js index 3e8ee10..06c5a53 100644 --- a/LeetcodeProblems/Escape_The_Ghosts.js +++ b/LeetcodeProblems/Escape_The_Ghosts.js @@ -36,7 +36,6 @@ Note: All points have coordinates with absolute value <= 10000. The number of ghosts will not exceed 100. */ -const assert = require('assert'); /** * @param {number[][]} ghosts @@ -60,14 +59,4 @@ var getDistance = function(a, b) { return horizontalMoves + verticalMoves; } -var main = function() { - test(); -} - -function test() { - assert.equal(escapeGhosts([[1, 0], [0, 3]], [0, 1]), true); - assert.equal(escapeGhosts([[1, 0]], [2, 0]), false); - assert.equal(escapeGhosts([[2, 0]], [1, 0]), true); -} - -module.exports.main = main \ No newline at end of file +module.exports.escapeGhosts = escapeGhosts; diff --git a/LeetcodeProblems/Flood_Fill.js b/LeetcodeProblems/Flood_Fill.js index 14ed4e3..93ee923 100644 --- a/LeetcodeProblems/Flood_Fill.js +++ b/LeetcodeProblems/Flood_Fill.js @@ -28,7 +28,6 @@ The length of image and image[0] will be in the range [1, 50]. The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length. The value of each color in image[i][j] and newColor will be an integer in [0, 65535]. */ -const assert = require('assert'); var floodFill = function(image, sr, sc, newColor) { var oldColor = image[sr][sc]; @@ -53,15 +52,4 @@ var floodFill = function(image, sr, sc, newColor) { return image; }; -function main() { - test(); -} - -function test() { - assert.deepEqual( - [ [ 2, 2, 2 ], [ 2, 2, 0 ], [ 2, 0, 1 ] ], - floodFill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2) - ); -} - -module.exports.main = main; +module.exports.floodFill = floodFill; diff --git a/LeetcodeProblems/Generate_Parenthesis.js b/LeetcodeProblems/Generate_Parenthesis.js index 323b6ef..2ee7df5 100644 --- a/LeetcodeProblems/Generate_Parenthesis.js +++ b/LeetcodeProblems/Generate_Parenthesis.js @@ -77,18 +77,4 @@ var insertAt = function(str, position, value) { return str.slice(0, position) + value + str.slice(position); } -function main() { - console.log("Approach 1"); - [0, 1, 2, 3].forEach(function(elem) { - console.log(`${elem}: ${generateParenthesisApproach2(elem)}`); - }) - - console.log("-------------"); - - console.log("Approach 2"); - [0, 1, 2, 3].forEach(function(elem) { - console.log(`${elem}: ${generateParenthesisApproach2(elem)}`); - }) -} - -module.exports.main = main +module.exports.generateParenthesisApproach2 = generateParenthesisApproach2; diff --git a/LeetcodeProblems/Group_Anagrams.js b/LeetcodeProblems/Group_Anagrams.js index 230af77..b205bb2 100644 --- a/LeetcodeProblems/Group_Anagrams.js +++ b/LeetcodeProblems/Group_Anagrams.js @@ -18,7 +18,6 @@ Note: All inputs will be in lowercase. The order of your output does not matter. */ -const assert = require('assert'); var groupAnagrams = function(strs) { var ret = []; @@ -48,15 +47,4 @@ var sortString = function(str) { return str.split("").sort().join(""); } -var main = function() { - test(); -} - -function test() { - assert.deepEqual( - groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]), - [ [ 'eat', 'tea', 'ate' ], [ 'tan', 'nat' ], [ 'bat' ] ] - ) -} - -module.exports.main = main; +module.exports.groupAnagrams = groupAnagrams; diff --git a/LeetcodeProblems/Implement_stack_using_queues.js b/LeetcodeProblems/Implement_stack_using_queues.js index 9f33c41..a604cf2 100644 --- a/LeetcodeProblems/Implement_stack_using_queues.js +++ b/LeetcodeProblems/Implement_stack_using_queues.js @@ -23,7 +23,7 @@ You must use only standard operations of a queue -- which means only push to bac Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue. You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack). */ -const assert = require('assert'); + class MyStack { constructor() { this.q1 = []; @@ -77,23 +77,4 @@ class MyStack { }; } -var main = function() { - test(); -} - -var test = function () { - var myStack = new MyStack(); - myStack.push(4); - myStack.push(3); - myStack.push(2); - myStack.push(1); - assert.equal(myStack.pop(), 1); - assert.equal(myStack.top(), 2); - myStack.push(1); - assert.equal(myStack.top(), 1); - assert.equal(myStack.pop(), 1); - assert.equal(myStack.pop(), 2); - assert.equal(myStack.pop(), 3); -} - -module.exports.main = main; +module.exports.MyStack = MyStack; \ No newline at end of file diff --git a/LeetcodeProblems/Kth_Largest_Element_in_an_Array.js b/LeetcodeProblems/Kth_Largest_Element_in_an_Array.js index 51ed6cb..3f669b5 100644 --- a/LeetcodeProblems/Kth_Largest_Element_in_an_Array.js +++ b/LeetcodeProblems/Kth_Largest_Element_in_an_Array.js @@ -15,7 +15,7 @@ Output: 4 Note: You may assume k is always valid, 1 ≤ k ≤ array's length. */ -const assert = require('assert'); + /** * @param {number[]} nums @@ -57,15 +57,4 @@ var swap = function(nums, a, b) { nums[b] = temp; } -var main = function(nums) { - test(); -} - -function test() { - assert.equal(findKthLargest([3,2,1,5,6,4], 2), 5); - assert.equal(findKthLargest([3,2,3,1,2,4,5,5,6], 4), 4); - assert.equal(findKthLargest([0], 1), 0); - assert.equal(findKthLargest([], 1), undefined); -} - -module.exports.main = main; +module.exports.findKthLargest = findKthLargest; diff --git a/LeetcodeProblems/Linked_List_Cycle_II.js b/LeetcodeProblems/Linked_List_Cycle_II.js index 9573e63..311932c 100644 --- a/LeetcodeProblems/Linked_List_Cycle_II.js +++ b/LeetcodeProblems/Linked_List_Cycle_II.js @@ -9,7 +9,7 @@ Note: Do not modify the linked list. Follow up: Can you solve it without using extra space? */ -const assert = require('assert'); + var ListNode = require('../UtilsClasses/ListNode').ListNode; // Optimal solution @@ -57,34 +57,4 @@ var detectCycle2 = function(head) { return null; }; -var main = function() { - test(); -} - -var test = function() { - const cycle = buildCycle(); - var list = cycle.list; - var nodeCycle = cycle.nodeCycle; - assert.equal(detectCycle(list), nodeCycle); -} - -function buildCycle() { - var node1 = ListNode.linkenList([1,2,3,4,5]); - var node2 = new ListNode(2); - var node3 = new ListNode(3); - var node4 = new ListNode(4); - var node5 = new ListNode(5); - - node1.next = node2; - node2.next = node3; - node3.next = node4; - node4.next = node5; - node5.next = node2; - - return { - list: node1, - nodeCycle: node2, - }; -} - -module.exports.main = main; +module.exports.detectCycle = detectCycle; diff --git a/LeetcodeProblems/Longest_Consecutive_Sequence.js b/LeetcodeProblems/Longest_Consecutive_Sequence.js index 290d9ea..0381cbb 100644 --- a/LeetcodeProblems/Longest_Consecutive_Sequence.js +++ b/LeetcodeProblems/Longest_Consecutive_Sequence.js @@ -12,7 +12,6 @@ Input: [100, 4, 200, 1, 3, 2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. */ -const assert = require('assert'); /** * @param {number[]} nums @@ -54,16 +53,4 @@ var longestConsecutive = function(nums) { return cons; }; -var main = function() { - test(); -} - -function test() { - assert.equal(longestConsecutive([100, 1, 200, 3, 2, 400, 201]), 3); - assert.equal(longestConsecutive([1,2,3,4, 100, 1, 200, 3, 2, 400, 201]), 4); - assert.equal(longestConsecutive([1, 400, 201, 403, 398]), 1); - assert.equal(longestConsecutive([]), 0); - assert.equal(longestConsecutive([2]), 1); -} - -module.exports.main +module.exports.longestConsecutive = longestConsecutive; diff --git a/LeetcodeProblems/Longest_Palindromic_Substring.js b/LeetcodeProblems/Longest_Palindromic_Substring.js index 74a2447..8c32bec 100644 --- a/LeetcodeProblems/Longest_Palindromic_Substring.js +++ b/LeetcodeProblems/Longest_Palindromic_Substring.js @@ -14,7 +14,6 @@ Example 2: Input: "cbbd" Output: "bb" */ -const assert = require('assert'); /** * @param {string} s @@ -64,17 +63,4 @@ var longestPalindrome = function(str) { return str.slice(posPalStart, posPalStart + maxPal); } -var main = function() { - test(); -} - -function test() { - assert.equal(longestPalindrome("pabcdcbte"), "bcdcb"); - assert.equal(longestPalindrome("bb"), "bb"); - assert.equal(longestPalindrome(""), ""); - assert.equal(longestPalindrome("bbb"), "bbb"); - assert.equal(longestPalindrome("bbbb"), "bbbb"); - assert.equal(longestPalindrome("ptabbbbat"), "tabbbbat"); -} - -module.exports.main = main +module.exports.longestPalindrome = longestPalindrome diff --git a/LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree.js b/LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree.js index c4f0168..1d6c129 100644 --- a/LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree.js +++ b/LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree.js @@ -33,7 +33,7 @@ Note: All of the nodes' values will be unique. p and q are different and both values will exist in the binary tree. */ -const assert = require('assert'); + var TreeNode = require('../UtilsClasses/TreeNode').TreeNode; @@ -93,37 +93,5 @@ var pathTo = function(root, value) { return []; } -var main = function() { - var root = new TreeNode(3); - - var right = new TreeNode(1); - right.left = new TreeNode(0); - right.right = new TreeNode(8); - root.right = right; - - var left = new TreeNode(5); - left.left = new TreeNode(6); - - var tempRight = new TreeNode(2); - tempRight.left = new TreeNode(7); - tempRight.right = new TreeNode(4); - left.right = tempRight; - - root.left = left; - - // _______3______ - // / \ - // ___5__ ___1__ - // / \ / \ - // 6 _2 0 8 - // / \ - // 7 4 - - console.log(lowestCommonAncestor(root, left, tempRight.right)); - console.log(lowestCommonAncestor(root, left, right)); - - console.log(lowestCommonAncestor2(root, left, tempRight.right)); - console.log(lowestCommonAncestor2(root, left, right)); -} - -module.exports.main = main; +module.exports.lowestCommonAncestor = lowestCommonAncestor; +module.exports.lowestCommonAncestor2 = lowestCommonAncestor2; diff --git a/LeetcodeProblems/Majority_Element.js b/LeetcodeProblems/Majority_Element.js index f1114f8..3b48dda 100644 --- a/LeetcodeProblems/Majority_Element.js +++ b/LeetcodeProblems/Majority_Element.js @@ -17,7 +17,7 @@ Output: 2 Note: You should have a better solution than O(N) */ -const assert = require('assert'); + /** * @param {number[]} nums @@ -45,14 +45,4 @@ var majorityElement = function(nums) { return candidate; }; -var main = function() { - test(); -} - -function test() { - assert.equal(majorityElement([2,2,3]), 2); - assert.equal(majorityElement([2,3,2]), 2); - assert.equal(majorityElement([1,1,1,2,3,45,1,2,4,1,1]), 1); -} - -module.exports.main = main +module.exports.majorityElement = majorityElement; diff --git a/LeetcodeProblems/Maximal_Square.js b/LeetcodeProblems/Maximal_Square.js index 014d4a8..b0a45fc 100644 --- a/LeetcodeProblems/Maximal_Square.js +++ b/LeetcodeProblems/Maximal_Square.js @@ -15,7 +15,7 @@ Input: Output: 4 */ -const assert = require('assert'); + /** * @param {character[][]} matrix @@ -65,18 +65,4 @@ var getCurrentMaxSideLength = function(matrix, i, j) { return max; } -var main = function() { - test(); -} - -function test() { - assert.equal(maximalSquare([["1","0"]]), 1); - assert.equal(maximalSquare([["1"]]), 1); - assert.equal(maximalSquare([["0"]]), 0); - assert.equal( - maximalSquare([["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]), - 4 - ); -} - -module.exports.main = main +module.exports.maximalSquare = maximalSquare; diff --git a/LeetcodeProblems/Maximun_Subarray.js b/LeetcodeProblems/Maximun_Subarray.js index c159a43..b05309c 100644 --- a/LeetcodeProblems/Maximun_Subarray.js +++ b/LeetcodeProblems/Maximun_Subarray.js @@ -13,7 +13,7 @@ Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: */ -const assert = require('assert'); + var maxSubArray = function(nums) { if(nums.length == 0) @@ -34,15 +34,4 @@ var max = function(i, j) { return (i > j) ? i : j; } -var main = function() { - test(); -} - -function test() { - assert.equal(maxSubArray([]), 0); - assert.equal(maxSubArray([-4]), -4); - assert.equal(maxSubArray([2]), 2); - assert.equal(maxSubArray([4,1,-1,4,5,6,7,-200]), 26); -} - -module.exports.main = main; \ No newline at end of file +module.exports.maxSubArray = maxSubArray; diff --git a/LeetcodeProblems/Min_Stack.js b/LeetcodeProblems/Min_Stack.js index 3ee0f78..0ee04fc 100644 --- a/LeetcodeProblems/Min_Stack.js +++ b/LeetcodeProblems/Min_Stack.js @@ -19,7 +19,7 @@ minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2. */ -const assert = require('assert'); + class MinStack { constructor() { @@ -74,19 +74,4 @@ class MinStack { } } -var main = function() { - test(); -} - -function test() { - var minStack = new MinStack(); - minStack.push(-2); - minStack.push(0); - minStack.push(-3); - assert.equal(minStack.getMin(), -3); - assert.equal(minStack.pop(), -3); - assert.equal(minStack.top(), 0); - assert.equal(minStack.getMin(), -2); -} - -module.exports.main = main; \ No newline at end of file +module.exports.MinStack = MinStack; diff --git a/LeetcodeProblems/Minimum_Window_Substring.js b/LeetcodeProblems/Minimum_Window_Substring.js index 2769963..24beeab 100644 --- a/LeetcodeProblems/Minimum_Window_Substring.js +++ b/LeetcodeProblems/Minimum_Window_Substring.js @@ -14,7 +14,7 @@ Note: If there is no such window in S that covers all characters in T, return the empty string "". If there is such window, you are guaranteed that there will always be only one unique minimum window in S. */ -const assert = require('assert'); + var minWindow = function(s, t) { if(t.length === 0 || s.length < t.length) @@ -64,17 +64,4 @@ var getHash = function(t) { return hash; } -var main = function() { - test(); -} - -function test() { - assert.equal(minWindow("ADOBECODEBANC", "ABC"), "BANC"); - assert.equal(minWindow("caaec", "cae"), "aec"); - assert.equal(minWindow("bbacbb", "ab"), "ba"); - assert.equal(minWindow("abba", "b"), "b"); - assert.equal(minWindow("abba", "a"), "a"); - assert.equal(minWindow("abba", ""), ""); -} - -module.exports.main +module.exports.minWindow = minWindow; diff --git a/LeetcodeProblems/NQueens.js b/LeetcodeProblems/NQueens.js index f78d3b8..2f2674f 100644 --- a/LeetcodeProblems/NQueens.js +++ b/LeetcodeProblems/NQueens.js @@ -18,7 +18,7 @@ Output: [ ] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above. */ -const assert = require('assert'); + /** * @param {number} n @@ -70,29 +70,4 @@ var parseSolutions = function(sols, n) { return matrixes; } -var main = function(n) { - printMatrixes(solveNQueens(4), 4); - printMatrixes(solveNQueens(5), 5); - printMatrixes(solveNQueens(6), 6); -} - -var test = function() { -} - -var printMatrixes = function(matrixes, n) { - console.log("Start solution of n: " + n); - for(var i = 0; i < matrixes.length; i++) { - printMatrix(matrixes[i]); - } - console.log("End solution of n: " + n); -} - -var printMatrix = function(matrix) { - console.log("------------"); - for(var i = 0; i < matrix.length; i++) { - console.log(matrix[i]); - } - console.log("------------"); -} - -module.exports.main = main; +module.exports.solveNQueens = solveNQueens; diff --git a/LeetcodeProblems/Number_of_Islands.js b/LeetcodeProblems/Number_of_Islands.js index 248ea49..705dd63 100644 --- a/LeetcodeProblems/Number_of_Islands.js +++ b/LeetcodeProblems/Number_of_Islands.js @@ -24,7 +24,7 @@ Input: Output: 3 */ -const assert = require('assert'); + /* * @param {character[][]} grid @@ -61,23 +61,4 @@ var colorIsland = function(grid, i, j, rowsCount, columnsCount) { colorIsland(grid, i, j + 1, rowsCount, columnsCount); } -var main = function() { - test(); -} - -function test() { - assert.equal(numIslands([[1]]), 1); - assert.equal(numIslands([]), 0); - assert.equal(numIslands( - [ - ["1","1","1","1","0"], - ["1","1","0","1","0"], - ["1","1","0","0","0"], - ["0","0","0","0","0"] - ], - ), - 1 - ); -} - -module.exports.main = main; \ No newline at end of file +module.exports.numIslands = numIslands; diff --git a/LeetcodeProblems/Number_of_Segments_in_a_String.js b/LeetcodeProblems/Number_of_Segments_in_a_String.js index a6c367a..cb33afb 100644 --- a/LeetcodeProblems/Number_of_Segments_in_a_String.js +++ b/LeetcodeProblems/Number_of_Segments_in_a_String.js @@ -11,7 +11,7 @@ Example: Input: "Hello, my name is John" Output: 5 */ -const assert = require('assert'); + /** * @param {string} s @@ -33,17 +33,4 @@ var countSegments = function(s) { return count; }; -function main() { - test(); -} - -function test() { - assert.equal(countSegments(" "), 0); - assert.equal(countSegments(" "), 0); - assert.equal(countSegments("ab cd ef"), 3); - assert.equal(countSegments(" ab cd ef"), 3); - assert.equal(countSegments("ab cd ef "), 3); - assert.equal(countSegments(" ab cd ef "), 3); -} - -module.exports.main = main +module.exports.countSegments = countSegments; diff --git a/LeetcodeProblems/Permutations.js b/LeetcodeProblems/Permutations.js index f04f128..478eda6 100644 --- a/LeetcodeProblems/Permutations.js +++ b/LeetcodeProblems/Permutations.js @@ -17,7 +17,6 @@ Output: [3,2,1] ] */ -const assert = require('assert'); var permute = function(nums) { return permuteAux(nums, 0, [], new Set()); @@ -39,24 +38,4 @@ var permuteAux = function(nums, pos, currentSol, set) { return ret; } -var main = function() { test(); -} - -function test() { - // assert.deepEqual( - assert.deepEqual(permute([]), [ [] ]); - assert.deepEqual(permute([1]), [ [ 1 ] ]); - assert.deepEqual( - permute([1,2,3]), - [ - [ 1, 2, 3 ], - [ 1, 3, 2 ], - [ 2, 1, 3 ], - [ 2, 3, 1 ], - [ 3, 1, 2 ], - [ 3, 2, 1 ] - ] - ); -} - -module.exports.main = main; +module.exports.permute = permute; diff --git a/LeetcodeProblems/Permutations_II.js b/LeetcodeProblems/Permutations_II.js index 22093fe..ba86bb5 100644 --- a/LeetcodeProblems/Permutations_II.js +++ b/LeetcodeProblems/Permutations_II.js @@ -14,7 +14,7 @@ Output: [2,1,1] ] */ -const assert = require('assert'); + var permuteUnique = function(nums) { var map = {}; @@ -46,35 +46,4 @@ var permuteUniqueAux = function(n, map, currentSol) { return ret; }; -var main = function() { - test(); -} - -function test() { - assert.deepEqual( - permuteUnique([1,1,2]), - [ [ '1', '1', '2' ], [ '1', '2', '1' ], [ '2', '1', '1' ] ] - ); - assert.deepEqual( - permuteUnique([1,3,2,1]), - [ - [ '1', '1', '2', '3' ], - [ '1', '1', '3', '2' ], - [ '1', '2', '1', '3' ], - [ '1', '2', '3', '1' ], - [ '1', '3', '1', '2' ], - [ '1', '3', '2', '1' ], - [ '2', '1', '1', '3' ], - [ '2', '1', '3', '1' ], - [ '2', '3', '1', '1' ], - [ '3', '1', '1', '2' ], - [ '3', '1', '2', '1' ], - [ '3', '2', '1', '1' ] - ] - ); - assert.deepEqual(permuteUnique([]), [ [] ]); - - assert.deepEqual(permuteUnique([1,1]), [ [ '1', '1' ] ]); -} - -module.exports.main = main; \ No newline at end of file +module.exports.permuteUnique = permuteUnique; diff --git a/LeetcodeProblems/Permutations_With_Duplicates.js b/LeetcodeProblems/Permutations_With_Duplicates.js index e9fccc5..3746a24 100644 --- a/LeetcodeProblems/Permutations_With_Duplicates.js +++ b/LeetcodeProblems/Permutations_With_Duplicates.js @@ -1,4 +1,4 @@ -const assert = require('assert'); + // Permutations without var subsetWithoutDuplicates = function(nums) { @@ -29,28 +29,4 @@ var subsetWithoutDuplicatesAux = function(nums, current, sol) { }) } -function main() { - test(); -} - -var test = function() { - assert.deepEqual( - subsetWithoutDuplicates([1,1,2,3]), - [ - [ 1, 1, 2, 3 ], - [ 1, 1, 3, 2 ], - [ 1, 2, 1, 3 ], - [ 1, 2, 3, 1 ], - [ 1, 3, 1, 2 ], - [ 1, 3, 2, 1 ], - [ 2, 1, 1, 3 ], - [ 2, 1, 3, 1 ], - [ 2, 3, 1, 1 ], - [ 3, 1, 1, 2 ], - [ 3, 1, 2, 1 ], - [ 3, 2, 1, 1 ] - ] - ); -} -main(); -module.exports.main = main; \ No newline at end of file +module.exports.subsetWithoutDuplicates = subsetWithoutDuplicates; diff --git a/LeetcodeProblems/Permutations_Without_Duplicates.js b/LeetcodeProblems/Permutations_Without_Duplicates.js index b5b0a1b..3a0463f 100644 --- a/LeetcodeProblems/Permutations_Without_Duplicates.js +++ b/LeetcodeProblems/Permutations_Without_Duplicates.js @@ -17,19 +17,18 @@ Output: [3,2,1] ] */ -const assert = require('assert'); -// Permutations wihto -var subsetWithDuplicates = function(nums) { +// Permutations without Duplicates +var subsetWithoutDuplicates = function(nums) { if(nums.lenght == 0){ return; } var solution = []; - subsetWithDuplicatesAux(nums, [], solution); + subsetWithoutDuplicatesAux(nums, [], solution); return solution; } -var subsetWithDuplicatesAux = function(nums, current, sol) { +var subsetWithoutDuplicatesAux = function(nums, current, sol) { if(nums.length == 0){ sol.push(current); } @@ -37,26 +36,8 @@ var subsetWithDuplicatesAux = function(nums, current, sol) { for(var i = 0; i < nums.length; i++) { var newCurrent = [...current, nums[i]] var newNums = nums.filter(function(num, index) { return index !== i }); - subsetWithDuplicatesAux(newNums, newCurrent, sol); + subsetWithoutDuplicatesAux(newNums, newCurrent, sol); } } - -function main() { - test(); -} - -var test = function() { - assert.deepEqual( - subsetWithDuplicates([1,2,3]), - [ - [ 1, 2, 3 ], - [ 1, 3, 2 ], - [ 2, 1, 3 ], - [ 2, 3, 1 ], - [ 3, 1, 2 ], - [ 3, 2, 1 ] - ] - ); -} -module.exports.main = main; \ No newline at end of file +module.exports.subsetWithoutDuplicates = subsetWithoutDuplicates; diff --git a/LeetcodeProblems/Regular_Expression_Matching.js b/LeetcodeProblems/Regular_Expression_Matching.js index 3aaedf0..b90d2aa 100644 --- a/LeetcodeProblems/Regular_Expression_Matching.js +++ b/LeetcodeProblems/Regular_Expression_Matching.js @@ -50,7 +50,7 @@ Output: false * @param {*} s * @param {*} p */ -const assert = require('assert'); + var isMatch = function(s, p) { return isMatchAux(s, p, 0, 0); @@ -90,17 +90,4 @@ var canBeZero = function(pattern, posPat) { return posPat == pattern.length; } -var main = function(){ - test(); -} - -var test = function(n) { - assert.equal(isMatch("aa", "a"), false); - assert.equal(isMatch("aa", "a*"), true); - assert.equal(isMatch("a","ab*"), true); - assert.equal(isMatch("ab", ".*"), true); - assert.equal(isMatch("aab", "c*a*b"), true); - assert.equal(isMatch("mississippi", "mis*is*p*."), false); -} - -module.exports.main = main; +module.exports.isMatch = isMatch; diff --git a/LeetcodeProblems/Remove_Invalid_Parentheses.js b/LeetcodeProblems/Remove_Invalid_Parentheses.js index fdb4fab..8d193f5 100644 --- a/LeetcodeProblems/Remove_Invalid_Parentheses.js +++ b/LeetcodeProblems/Remove_Invalid_Parentheses.js @@ -19,7 +19,6 @@ Example 3: Input: ")(" Output: [""] */ -const assert = require('assert'); /** * @param {string} s @@ -70,15 +69,4 @@ var isValid = function(s) { return leftCount === 0; } -var main = function() { - test(); -} - -var test = function(n) { - assert.equal(removeInvalidParentheses("))))(()"), "()"); - assert.equal(removeInvalidParentheses("(()"), "()"); - assert.equal(removeInvalidParentheses("(d))()"), "(d)()"); - assert.equal(removeInvalidParentheses("(())"), "(())"); -} - -module.exports.main = main; \ No newline at end of file +module.exports.removeInvalidParentheses = removeInvalidParentheses; diff --git a/LeetcodeProblems/Restore_IP_Addresses.js b/LeetcodeProblems/Restore_IP_Addresses.js index 2394963..578b970 100644 --- a/LeetcodeProblems/Restore_IP_Addresses.js +++ b/LeetcodeProblems/Restore_IP_Addresses.js @@ -9,7 +9,6 @@ Example: Input: "25525511135" Output: ["255.255.11.135", "255.255.111.35"] */ -const assert = require('assert'); var restoreIpAddresses = function(s) { var restore = restoreInputBits("", s, 4); @@ -41,13 +40,4 @@ var restoreInputBits = function(partial, s, num) { return [...oneNum, ...twoNums, ...threeNums]; } -var main = function() { - test(); -} - -var test = function(n) { - assert.deepEqual(restoreIpAddresses("010010"), [ '0.10.0.10', '0.100.1.0']); - assert.deepEqual(restoreIpAddresses("25525511135"), [ '255.255.11.135', '255.255.111.35' ]); -} - -module.exports.main = main +module.exports.restoreIpAddresses = restoreIpAddresses; diff --git a/LeetcodeProblems/Reverse_String_II.js b/LeetcodeProblems/Reverse_String_II.js index d277483..429520f 100644 --- a/LeetcodeProblems/Reverse_String_II.js +++ b/LeetcodeProblems/Reverse_String_II.js @@ -10,7 +10,6 @@ Restrictions: The string consists of lower English letters only. Length of the given string and k will in the range [1, 10000] */ -const assert = require('assert'); var reverseStr = function(s, k) { if(k <= 1) @@ -39,15 +38,4 @@ var reverse = function(s, start, end) { return ret; } -var main = function(){ - test(); -} - -var test = function(n) { - assert.equal(reverseStr("abcdefg", 2), "bacdfeg"); - assert.equal(reverseStr("abcdefg", 3), "cbadefg"); - assert.equal(reverseStr("abcdefg", 1), "abcdefg"); - assert.equal(reverseStr("abcdefg", 0), "abcdefg"); -} - -module.exports.main = main +module.exports.reverseStr = reverseStr; diff --git a/LeetcodeProblems/SearchIng_Rotated_Sorted_Array.js b/LeetcodeProblems/SearchIng_Rotated_Sorted_Array.js index d095215..702f357 100644 --- a/LeetcodeProblems/SearchIng_Rotated_Sorted_Array.js +++ b/LeetcodeProblems/SearchIng_Rotated_Sorted_Array.js @@ -21,7 +21,7 @@ Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 */ -const assert = require('assert'); + /** * @param {number[]} nums @@ -54,12 +54,4 @@ var searchAux = function(nums, target, start, end) { } } -var main = function(n) { - test(); -} - -var test = function() { - assert.equal(search([4,5,6,7,0,1,2], 5), 1); -} -main() -module.exports.main = main; +module.exports.search = search; diff --git a/LeetcodeProblems/Search_a_2D_Matrix.js b/LeetcodeProblems/Search_a_2D_Matrix.js index 0a0b835..6348c4c 100644 --- a/LeetcodeProblems/Search_a_2D_Matrix.js +++ b/LeetcodeProblems/Search_a_2D_Matrix.js @@ -27,7 +27,6 @@ matrix = [ target = 13 Output: false */ -const assert = require('assert'); /** * @param {number[][]} matrix @@ -58,17 +57,5 @@ var searchMatrixAux = function(matrix, firstRow, lastRow, target) { return false; }; - -var main = function(){ - test(); -} -var test = function(n) { - assert.equal(searchMatrix([], 0), false); - assert.equal(searchMatrix([[1], [3]], 3), true); - assert.equal(searchMatrix([[1], [3]], 1), true); - const matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]]; - assert.equal(searchMatrix(matrix, 3), true); -} - -module.exports.main = main; +module.exports.searchMatrix = searchMatrix; diff --git a/LeetcodeProblems/Search_a_2D_Matrix_II.js b/LeetcodeProblems/Search_a_2D_Matrix_II.js index 7085dc3..c96c95d 100644 --- a/LeetcodeProblems/Search_a_2D_Matrix_II.js +++ b/LeetcodeProblems/Search_a_2D_Matrix_II.js @@ -17,7 +17,6 @@ Example: Given target = 5, return true. Given target = 20, return false. */ -const assert = require('assert'); /** * @param {number[][]} matrix @@ -43,22 +42,4 @@ var searchMatrix = function(matrix, target) { return false; }; -const matrix1 = [ - [1,4,7, 11,15], - [2,5,8, 12,19], - [3,6,9, 16,22], - [10,13,14, 17,24], - [18,21,23, 26,30] -]; - -var main = function(n) { - test(); -} - -var test = function(n) { - assert.equal(searchMatrix(matrix1, 5), true); - assert.equal(searchMatrix(matrix1, 0), false); - assert.equal(searchMatrix(matrix1, 15), true); -} - -module.exports.main = main; +module.exports.searchMatrix = searchMatrix; diff --git a/LeetcodeProblems/Set_Matrix_Zeroes.js b/LeetcodeProblems/Set_Matrix_Zeroes.js index d92d8eb..908411a 100644 --- a/LeetcodeProblems/Set_Matrix_Zeroes.js +++ b/LeetcodeProblems/Set_Matrix_Zeroes.js @@ -39,8 +39,6 @@ A simple improvement uses O(m + n) space, but still not the best solution. Could you devise a constant space solution? */ -const assert = require('assert'); - /** * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. @@ -110,15 +108,4 @@ var fillCol = function(matrix, col) { matrix[i][col] = 0; } -var main = function() { - test(); -} - -var test = function() { - assert.deepEqual( - setZeroes([[1,1,1],[1,0,1],[1,1,1]]), - [[1, 0, 1], [0, 0, 0], [1, 0, 1]] - ); -} - -module.exports.main = main; +module.exports.setZeroes = setZeroes; diff --git a/LeetcodeProblems/Simplify_Path.js b/LeetcodeProblems/Simplify_Path.js index fdb6d2f..70e17f7 100644 --- a/LeetcodeProblems/Simplify_Path.js +++ b/LeetcodeProblems/Simplify_Path.js @@ -19,7 +19,7 @@ In this case, you should return "/". Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo". */ -const assert = require('assert'); + var simplifyPath = function(path) { var queue = []; @@ -60,17 +60,4 @@ var simplifyPath = function(path) { return (ret.length == 0) ? "/" : ret; }; -var main = function(){ - test(); -} - -var test = function() { - assert.equal(simplifyPath("/../c"), "/c"); - assert.equal(simplifyPath("/.."), "/"); - assert.equal(simplifyPath("/home/"), "/home"); // => "/home" - assert.equal(simplifyPath("/a/./b/../../c/"), "/c"); // => "/c" - assert.equal(simplifyPath("/a/../../b/../c//.//"), "/c"); // => "/c" - assert.equal(simplifyPath("/a//b////c/d//././/.."), "/a/b/c") // => "/a/b/c" -} - -module.exports.main = main +module.exports.simplifyPath = simplifyPath; diff --git a/LeetcodeProblems/Spiral_Matrix.js b/LeetcodeProblems/Spiral_Matrix.js index b3e293a..96f078e 100644 --- a/LeetcodeProblems/Spiral_Matrix.js +++ b/LeetcodeProblems/Spiral_Matrix.js @@ -23,7 +23,7 @@ Input: ] Output: [1,2,3,4,8,12,11,10,9,5,6,7] */ -const assert = require('assert'); + /** * @param {number[][]} matrix @@ -67,17 +67,4 @@ var printRect = function(matrix, i, rowLength, colLength, retArray) { } } -var main = function() { - const matrix = [ - [ 1, 2, 3 ], - [ 4, 5, 6 ], - [ 7, 8, 9 ] - ] - - assert.deepEqual( - spiralOrder(matrix), - [1, 2, 3, 6, 9, 8, 7, 4, 5] - ) -} - -module.exports.main = main; +module.exports.spiralOrder = spiralOrder; diff --git a/LeetcodeProblems/Subarray_Sum_Equals_K.js b/LeetcodeProblems/Subarray_Sum_Equals_K.js index 0f75e13..1dca41c 100644 --- a/LeetcodeProblems/Subarray_Sum_Equals_K.js +++ b/LeetcodeProblems/Subarray_Sum_Equals_K.js @@ -12,7 +12,7 @@ Note: 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]. */ -const assert = require('assert'); + /** * @param {number[]} nums @@ -60,15 +60,4 @@ var subarraySum2 = function(nums, k) { return ret; }; -var main = function() { - test(); -} - -var test = function() { - assert.strictEqual(subarraySum([1,1,1], 2), 2); - assert.strictEqual(subarraySum([1], 0), 0); - assert.strictEqual(subarraySum([0], 0), 1); - assert.strictEqual(subarraySum([0,0,0,0,0], 0), 15); -} - -module.exports.main = main; +module.exports.subarraySum = subarraySum; diff --git a/LeetcodeProblems/Subsets.js b/LeetcodeProblems/Subsets.js index 014ab43..7b26f17 100644 --- a/LeetcodeProblems/Subsets.js +++ b/LeetcodeProblems/Subsets.js @@ -22,7 +22,7 @@ Output: ] */ -const assert = require('assert'); + var subsets = function(nums) { var ret = []; @@ -38,21 +38,4 @@ var subsets = function(nums) { return subsetByPosition(nums, 0, []); }; -function main() { - test(); -} - -function test() { - assert.deepEqual(subsets([]), [[]]); - assert.deepEqual(subsets([1]), [[1], []]); - assert.deepEqual( - subsets([1,2]), - [[1, 2], [1], [2], []] - ); - assert.deepEqual( - subsets([1, 2, 3]), - [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []] - ); -} - -module.exports.main = main; +module.exports.subsets = subsets; diff --git a/LeetcodeProblems/Sum_Of_Square_Numbers.js b/LeetcodeProblems/Sum_Of_Square_Numbers.js index 2146a45..ae97bb9 100644 --- a/LeetcodeProblems/Sum_Of_Square_Numbers.js +++ b/LeetcodeProblems/Sum_Of_Square_Numbers.js @@ -14,8 +14,6 @@ Input: 3 Output: False */ -const assert = require('assert'); - /** * @param {number} c * @return {boolean} @@ -35,18 +33,4 @@ var judgeSquareSum = function(c) { return false; }; -var main = function() { - test(); -} - -var test = function() { - assert.strictEqual(judgeSquareSum(0), true); - assert.strictEqual(judgeSquareSum(1), true); - assert.strictEqual(judgeSquareSum(5), true); - assert.strictEqual(judgeSquareSum(16), true); - assert.strictEqual(judgeSquareSum(24), false); - assert.strictEqual(judgeSquareSum(25), true); -} - -module.exports.main = main; - +module.exports.judgeSquareSum = judgeSquareSum; diff --git a/LeetcodeProblems/Swap_Nodes_In_Pairs.js b/LeetcodeProblems/Swap_Nodes_In_Pairs.js index 54c1faf..0ee2002 100644 --- a/LeetcodeProblems/Swap_Nodes_In_Pairs.js +++ b/LeetcodeProblems/Swap_Nodes_In_Pairs.js @@ -12,9 +12,6 @@ Note: Your algorithm should use only constant extra space. You may not modify the values in the list's nodes, only nodes itself may be changed. */ -const assert = require('assert'); -const ListNode = require('../UtilsClasses/ListNode').ListNode; -const ListNodeTestHelper = require('../utilsClasses/ListNodeTestHelper'); /** * Definition for singly-linked list. @@ -49,15 +46,4 @@ var swapPairs = function(head) { return head; }; -var main = function() { - test(); -} - -var test = function () { - ListNodeTestHelper.assertList(swapPairs(ListNode.linkenList([1,2,3,4])), [2,1,4,3]); - ListNodeTestHelper.assertList(swapPairs(ListNode.linkenList([])), []); - ListNodeTestHelper.assertList(swapPairs(ListNode.linkenList([1])), [1]); - ListNodeTestHelper.assertList(swapPairs(ListNode.linkenList([1,2])), [2, 1]); -} - -module.exports.main = main; +module.exports.swapPairs = swapPairs; diff --git a/LeetcodeProblems/Tic_Tac_Toe.js b/LeetcodeProblems/Tic_Tac_Toe.js index 363a14a..f3dcfc0 100644 --- a/LeetcodeProblems/Tic_Tac_Toe.js +++ b/LeetcodeProblems/Tic_Tac_Toe.js @@ -26,11 +26,13 @@ class TicTacToe { }; 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; } + console.log("------- \n"); } isBoardFull() { @@ -46,41 +48,19 @@ class TicTacToe { return true; } - makeMove() { + makeMove(str) { 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] === "-") { - this.addToken(row, col, "0"); + this.addToken(row, col, str); + return true; } - } + } } } } -var main = function() { - console.log("TBD"); -} - -module.exports.main = main; - -ticTacToe = new TicTacToe(); -ticTacToe.isBoardFull(); -ticTacToe.addToken(0,1,"X"); -ticTacToe.printBoard(); -var iter = 0; -while(iter < 8) { - ticTacToe.makeMove(); - iter++; -} - -console.log("after 8 moves"); -ticTacToe.isBoardFull(); -ticTacToe.printBoard(); -ticTacToe.makeMove(); - -ticTacToe.printBoard(); -ticTacToe.addToken(0,0,"X"); -ticTacToe.printBoard(); +module.exports.TicTacToe = TicTacToe; diff --git a/LeetcodeProblems/Unique_Binary_Search_Trees.js b/LeetcodeProblems/Unique_Binary_Search_Trees.js index 3bf1c2c..b469951 100644 --- a/LeetcodeProblems/Unique_Binary_Search_Trees.js +++ b/LeetcodeProblems/Unique_Binary_Search_Trees.js @@ -22,8 +22,6 @@ Given n = 3, there are a total of 5 unique BST's: DP Solution: https://www.programcreek.com/2014/05/leetcode-unique-binary-search-trees-java/ */ -const assert = require('assert'); - // Solution 3 using DP var numTrees3 = function (n) { if (n == 0) @@ -109,25 +107,6 @@ var numTreesAux1 = function(leftMin, leftMax) { return count; } -var main = function() { - test(); -} - -var test = function () { - assert.strictEqual(numTrees1(1), 1); - assert.strictEqual(numTrees1(2), 2); - assert.strictEqual(numTrees1(3), 5); - assert.strictEqual(numTrees1(5), 42); - - assert.strictEqual(numTrees2(1), 1); - assert.strictEqual(numTrees2(2), 2); - assert.strictEqual(numTrees2(3), 5); - assert.strictEqual(numTrees2(5), 42); - - assert.strictEqual(numTrees3(1), 1); - assert.strictEqual(numTrees3(2), 2); - assert.strictEqual(numTrees3(3), 5); - assert.strictEqual(numTrees3(5), 42); -} - -module.exports.main = main \ No newline at end of file +module.exports.numTrees1 = numTrees1; +module.exports.numTrees2 = numTrees2; +module.exports.numTrees3 = numTrees3; diff --git a/LeetcodeProblems/Unique_Paths.js b/LeetcodeProblems/Unique_Paths.js index 0a0092e..b7ba36c 100644 --- a/LeetcodeProblems/Unique_Paths.js +++ b/LeetcodeProblems/Unique_Paths.js @@ -26,8 +26,6 @@ Output: 28 // Solution 1 // This solution is a naive solution implementing a binary tree and visiting each node. -const assert = require('assert'); - var uniquePaths1 = function(m, n) { return uniquePathsAux(0, 0, m, n) }; @@ -96,13 +94,6 @@ var uniquePaths3 = function(m, n) { return matrix[m - 1][n - 1]; }; -var main = function() { - test(); -} - -var test = function() { - assert.strictEqual(uniquePaths1(10,4), 220); - assert.strictEqual(uniquePaths1(3,2), 3); -} - -module.exports.main = main; \ No newline at end of file +module.exports.uniquePaths1 = uniquePaths1; +module.exports.uniquePaths2 = uniquePaths1; +module.exports.uniquePaths3 = uniquePaths3; diff --git a/LeetcodeProblems/Valid_Parentheses.js b/LeetcodeProblems/Valid_Parentheses.js index f4d5bc0..c65f037 100644 --- a/LeetcodeProblems/Valid_Parentheses.js +++ b/LeetcodeProblems/Valid_Parentheses.js @@ -32,8 +32,6 @@ Input: "{[]}" Output: true */ -const assert = require('assert'); - var isValid = function(s) { var stack = []; for(var i = 0; i < s.length; i++) { @@ -58,16 +56,4 @@ var valid = function(parOpen, parClose) { parOpen === "{" && parClose === "}"; } -var main = function(){ - test(); -} - -var test = function () { - assert.strictEqual(isValid(""), true); - assert.strictEqual(isValid("()"), true); - assert.strictEqual(isValid("([)]"), false); - assert.strictEqual(isValid("{[()]}{[()]}"), true); - assert.strictEqual(isValid("{[())()]}"), false); -} - -module.exports.main = main +module.exports.isValid = isValid; diff --git a/LeetcodeProblems/Verify_Preorder_Serialization_of_a_Binary_Tree.js b/LeetcodeProblems/Verify_Preorder_Serialization_of_a_Binary_Tree.js index 4576c3c..1fed956 100644 --- a/LeetcodeProblems/Verify_Preorder_Serialization_of_a_Binary_Tree.js +++ b/LeetcodeProblems/Verify_Preorder_Serialization_of_a_Binary_Tree.js @@ -31,7 +31,7 @@ Example 3: Input: "9,#,#,1" Output: false */ -const assert = require('assert'); + /** * @param {string} preorder @@ -64,17 +64,4 @@ var isValidSerialization = function(preorder) { return countP === 0 && iter >= preorder.length; }; -var main = function() { - test(); -} - -var test = function() { - assert.strictEqual(isValidSerialization(""), true); - assert.strictEqual(isValidSerialization(""), true); - assert.strictEqual(isValidSerialization("#"), true); - assert.strictEqual(isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#"), true); - assert.strictEqual(isValidSerialization("9,#,92,#,#"), true); - assert.strictEqual(isValidSerialization("9,3,4,#,#,1,#,#,#,2,#,6,#,#"), false); -}; - -module.exports.main = main; +module.exports.isValidSerialization = isValidSerialization; diff --git a/LeetcodeProblems/merge_k_sorted_lists.js b/LeetcodeProblems/merge_k_sorted_lists.js index c36fa4d..ab07395 100644 --- a/LeetcodeProblems/merge_k_sorted_lists.js +++ b/LeetcodeProblems/merge_k_sorted_lists.js @@ -14,7 +14,7 @@ Input: ] Output: 1->1->2->3->4->4->5->6 */ -const assert = require('assert'); + const ListNodeTestHelper = require('../utilsClasses/ListNodeTestHelper'); var ListNode = require('../UtilsClasses/ListNode').ListNode; @@ -76,29 +76,4 @@ var mergeLists = function(list1, list2) { return head; } -var main = function() { - test(); -} - -function test() { - assert.deepEqual(mergeKLists([]), null); - assert.deepEqual( - mergeKLists([null]), - null - ); - assert.deepEqual( - mergeKLists([null, null]), - null - ); - - var list1 = ListNode.linkenList([1,2,3]); - var list2 = ListNode.linkenList([2,3,4]); - var list3 = ListNode.linkenList([5,6]); - var list4 = ListNode.linkenList([1,5]); - ListNodeTestHelper.assertList( - mergeKLists([list1, list2, list3, list4]), - [1, 1, 2, 2, 3, 3, 4, 5, 5, 6] - ); -} - -module.exports.main = main; \ No newline at end of file +module.exports.mergeKLists = mergeKLists; diff --git a/LeetcodeProblemsTests/3Sum_Test.js b/LeetcodeProblemsTests/3Sum_Test.js new file mode 100644 index 0000000..84f4b44 --- /dev/null +++ b/LeetcodeProblemsTests/3Sum_Test.js @@ -0,0 +1,22 @@ +const assert = require('assert'); +const threeSum = require('../LeetcodeProblems/3Sum').threeSum; + +var test = function () { + assert.deepEqual(threeSum([]), []); + assert.deepEqual(threeSum([0]), []); + assert.deepEqual(threeSum([0, 0]), []); + assert.deepEqual( + threeSum([0, 0, 0]), + [[0, 0, 0]] + ); + assert.deepEqual( + threeSum([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), + [[0, 0, 0]] + ); + assert.deepEqual( + threeSum([-1, 0, 1, 2, -1, -4]), + [ [ -1, 2, -1 ], [ 0, 1, -1 ] ] + ); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Add_Two_Numbers_Test.js b/LeetcodeProblemsTests/Add_Two_Numbers_Test.js new file mode 100644 index 0000000..4c16541 --- /dev/null +++ b/LeetcodeProblemsTests/Add_Two_Numbers_Test.js @@ -0,0 +1,29 @@ +const assert = require('assert'); +const addTwoNumbers = require('../LeetcodeProblems/Add_Two_Numbers').addTwoNumbers; +const ListNodeTestHelper = require('../utilsClasses/ListNodeTestHelper'); +var ListNode = require('../UtilsClasses/ListNode').ListNode; + +function test() { + const list1 = ListNode.linkenList([1,2,3,4]); + const list2 = ListNode.linkenList([1,2,3,4]); + ListNodeTestHelper.assertList( + addTwoNumbers(list1, list2), + [2, 4, 6, 8] + ); + + const list3 = ListNode.linkenList([1]); + const list4 = ListNode.linkenList([1,2]); + ListNodeTestHelper.assertList( + addTwoNumbers(list3, list4), + [2, 2] + ); + + const list5 = ListNode.linkenList([]); + const list6 = ListNode.linkenList([1,2]); + ListNodeTestHelper.assertList( + addTwoNumbers(list5, list6), + [1, 2] + ); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Award_Budget_Cuts_Test.js b/LeetcodeProblemsTests/Award_Budget_Cuts_Test.js new file mode 100644 index 0000000..9950f95 --- /dev/null +++ b/LeetcodeProblemsTests/Award_Budget_Cuts_Test.js @@ -0,0 +1,15 @@ +const assert = require('assert'); +const cutAwardBadges = require('../LeetcodeProblems/Award_Budget_Cuts').cutAwardBadges; + +function test() { + assert.deepEqual( + cutAwardBadges([2, 100, 50, 120, 1000], 190), + [ 47, 47, 47, 47, 2 ] + ); + assert.deepEqual( + cutAwardBadges([2, 100, 50, 120, 1000], 5), + [ 1, 1, 1, 1, 1 ] + ); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Backspace_String_Compare_Test.js b/LeetcodeProblemsTests/Backspace_String_Compare_Test.js new file mode 100644 index 0000000..5cef889 --- /dev/null +++ b/LeetcodeProblemsTests/Backspace_String_Compare_Test.js @@ -0,0 +1,18 @@ +const assert = require('assert'); +const backspaceCompare = require('../LeetcodeProblems/Backspace_String_Compare').backspaceCompare; +const backspaceCompare2 = require('../LeetcodeProblems/Backspace_String_Compare').backspaceCompare2; + +function test() { + assert.equal(backspaceCompare("ab#c", "ad#c"), true); // true + assert.equal(backspaceCompare("ab##", "c#d#"), true); // true + assert.equal(backspaceCompare("a##c", "#a#c"), true); // true + assert.equal(backspaceCompare("a#c", "b"), false); // false + + assert.equal(backspaceCompare2("ab#c", "ad#c"), true); // true + assert.equal(backspaceCompare2("ab##", "c#d#"), true); // true + assert.equal(backspaceCompare2("a##c", "#a#c"), true); // true + assert.equal(backspaceCompare2("a#c", "b"), false); // false +} +test(); + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Best_Time_To_Buy_And_Sell_Stock_II_Test.js b/LeetcodeProblemsTests/Best_Time_To_Buy_And_Sell_Stock_II_Test.js new file mode 100644 index 0000000..4fa85a9 --- /dev/null +++ b/LeetcodeProblemsTests/Best_Time_To_Buy_And_Sell_Stock_II_Test.js @@ -0,0 +1,9 @@ +const assert = require('assert'); +const maxProfit = require('../LeetcodeProblems/Best_Time_To_Buy_And_Sell_Stock_II').maxProfit; + +function test() { + assert.equal(maxProfit([7,1,5,3,6,4]), 7); + assert.equal(maxProfit([7,1,5,3320,6,4]), 3319); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Binary_Gap_Test.js b/LeetcodeProblemsTests/Binary_Gap_Test.js new file mode 100644 index 0000000..033cf4d --- /dev/null +++ b/LeetcodeProblemsTests/Binary_Gap_Test.js @@ -0,0 +1,9 @@ +const assert = require('assert'); +const binaryGap = require('../LeetcodeProblems/Binary_Gap').binaryGap; + +function test() { + assert.equal(binaryGap(22), 2); // 10110 + assert.equal(binaryGap(8), 0); // 1000 +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Clone_Graph_Test.js b/LeetcodeProblemsTests/Clone_Graph_Test.js new file mode 100644 index 0000000..ea8b26b --- /dev/null +++ b/LeetcodeProblemsTests/Clone_Graph_Test.js @@ -0,0 +1,5 @@ +var test = function() { + // TODO +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Coin_Change_Test.js b/LeetcodeProblemsTests/Coin_Change_Test.js new file mode 100644 index 0000000..ffce9af --- /dev/null +++ b/LeetcodeProblemsTests/Coin_Change_Test.js @@ -0,0 +1,12 @@ +const assert = require('assert'); +const coinChange = require('../LeetcodeProblems/Coin_Change').coinChange; + +function test() { + assert.equal(coinChange([], 3), -1); + assert.equal(coinChange([2], 3), -1); + assert.equal(coinChange([1, 2, 5], 11), 3); + assert.equal(coinChange([3, 7, 405, 436], 8839), 25); + assert.equal(coinChange([370, 417, 408, 156, 143, 434, 168, 83, 177, 280, 117], 9953), 24); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal_Test.js b/LeetcodeProblemsTests/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal_Test.js new file mode 100644 index 0000000..72ec134 --- /dev/null +++ b/LeetcodeProblemsTests/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal_Test.js @@ -0,0 +1,9 @@ +const assert = require('assert'); +var buildTree = require('../LeetcodeProblems/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal').buildTree; + +function test() { + // TODO + console.log(buildTree([3,9,20,15,7], [9,3,15,20,7])); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Deletion_Distance_Test.js b/LeetcodeProblemsTests/Deletion_Distance_Test.js new file mode 100644 index 0000000..2d9d0f3 --- /dev/null +++ b/LeetcodeProblemsTests/Deletion_Distance_Test.js @@ -0,0 +1,23 @@ +const assert = require('assert'); +var deletionDistance = require('../LeetcodeProblems/Deletion_Distance').deletionDistance; +var deletionDistance2 = require('../LeetcodeProblems/Deletion_Distance').deletionDistance2; +var deletionDistanceDP = require('../LeetcodeProblems/Deletion_Distance').deletionDistanceDP; + +function test() { + assert.equal(deletionDistance("dog", "frog"), 3); + assert.equal(deletionDistance("some", "some"), 0); + assert.equal(deletionDistance("some", "thing"), 9); + assert.equal(deletionDistance("", ""), 0); + + assert.equal(deletionDistance2("dog", "frog"), 3); + assert.equal(deletionDistance2("some", "some"), 0); + assert.equal(deletionDistance2("some", "thing"), 9); + assert.equal(deletionDistance2("", ""), 0); + + assert.equal(deletionDistanceDP("dog", "frog"), 3); + assert.equal(deletionDistanceDP("some", "some"), 0); + assert.equal(deletionDistanceDP("some", "thing"), 9); + assert.equal(deletionDistanceDP("", ""), 0); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Design_Circular_Deque_Test.js b/LeetcodeProblemsTests/Design_Circular_Deque_Test.js new file mode 100644 index 0000000..6d0a6ea --- /dev/null +++ b/LeetcodeProblemsTests/Design_Circular_Deque_Test.js @@ -0,0 +1,17 @@ +const assert = require('assert'); +var MyCircularDeque = require('../LeetcodeProblems/Design_Circular_Deque').MyCircularDeque; + +var test = function() { + const obj = new MyCircularDeque(3); + assert.equal(obj.insertLast(1), true); + assert.equal(obj.insertLast(2), true); + assert.equal(obj.insertFront(3), true); + assert.equal(obj.insertFront(4), false); + assert.equal(obj.getRear(), 2); + assert.equal(obj.isFull(), true); + assert.equal(obj.deleteLast(), true); + assert.equal(obj.insertFront(4), true); + assert.equal(obj.getFront(), 4); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Edit_Distance_Test.js b/LeetcodeProblemsTests/Edit_Distance_Test.js new file mode 100644 index 0000000..7a02e8a --- /dev/null +++ b/LeetcodeProblemsTests/Edit_Distance_Test.js @@ -0,0 +1,13 @@ +const assert = require('assert'); +var minDistance = require('../LeetcodeProblems/Edit_Distance').minDistance; +var minDistance2 = require('../LeetcodeProblems/Edit_Distance').minDistance2; + +function test() { + assert.equal(minDistance("ros", "horse"), 3); + assert.equal(minDistance("intention", "execution"), 5); + + assert.equal(minDistance2("ros", "horse"), 3); + assert.equal(minDistance2("intention", "execution"), 5); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Escape_The_Ghosts_Test.js b/LeetcodeProblemsTests/Escape_The_Ghosts_Test.js new file mode 100644 index 0000000..59c23e2 --- /dev/null +++ b/LeetcodeProblemsTests/Escape_The_Ghosts_Test.js @@ -0,0 +1,11 @@ + +const assert = require('assert'); +var escapeGhosts = require('../LeetcodeProblems/Escape_The_Ghosts').escapeGhosts; + +function test() { + assert.equal(escapeGhosts([[1, 0], [0, 3]], [0, 1]), true); + assert.equal(escapeGhosts([[1, 0]], [2, 0]), false); + assert.equal(escapeGhosts([[2, 0]], [1, 0]), true); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Flood_Fill_Test.js b/LeetcodeProblemsTests/Flood_Fill_Test.js new file mode 100644 index 0000000..e99050f --- /dev/null +++ b/LeetcodeProblemsTests/Flood_Fill_Test.js @@ -0,0 +1,11 @@ +const assert = require('assert'); +const floodFill = require('../LeetcodeProblems/Flood_Fill').floodFill; + +function test() { + assert.deepEqual( + [ [ 2, 2, 2 ], [ 2, 2, 0 ], [ 2, 0, 1 ] ], + floodFill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2) + ); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Generate_Parenthesis_Test.js b/LeetcodeProblemsTests/Generate_Parenthesis_Test.js new file mode 100644 index 0000000..ea8b26b --- /dev/null +++ b/LeetcodeProblemsTests/Generate_Parenthesis_Test.js @@ -0,0 +1,5 @@ +var test = function() { + // TODO +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Group_Anagrams_Test.js b/LeetcodeProblemsTests/Group_Anagrams_Test.js new file mode 100644 index 0000000..b8c9e43 --- /dev/null +++ b/LeetcodeProblemsTests/Group_Anagrams_Test.js @@ -0,0 +1,11 @@ +const assert = require('assert'); +const groupAnagrams = require('../LeetcodeProblems/Group_Anagrams').groupAnagrams; + +function test() { + assert.deepEqual( + groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]), + [ [ 'eat', 'tea', 'ate' ], [ 'tan', 'nat' ], [ 'bat' ] ] + ) +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Implement_stack_using_queues_Test.js b/LeetcodeProblemsTests/Implement_stack_using_queues_Test.js new file mode 100644 index 0000000..131d63c --- /dev/null +++ b/LeetcodeProblemsTests/Implement_stack_using_queues_Test.js @@ -0,0 +1,19 @@ +const assert = require('assert'); +const MyStack = require('../LeetcodeProblems/Implement_stack_using_queues').MyStack; + +var test = function () { + var myStack = new MyStack(); + myStack.push(4); + myStack.push(3); + myStack.push(2); + myStack.push(1); + assert.equal(myStack.pop(), 1); + assert.equal(myStack.top(), 2); + myStack.push(1); + assert.equal(myStack.top(), 1); + assert.equal(myStack.pop(), 1); + assert.equal(myStack.pop(), 2); + assert.equal(myStack.pop(), 3); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Kth_Largest_Element_in_an_Array_Test.js b/LeetcodeProblemsTests/Kth_Largest_Element_in_an_Array_Test.js new file mode 100644 index 0000000..17ac1f2 --- /dev/null +++ b/LeetcodeProblemsTests/Kth_Largest_Element_in_an_Array_Test.js @@ -0,0 +1,11 @@ +const assert = require('assert'); +const findKthLargest = require('../LeetcodeProblems/Kth_Largest_Element_in_an_Array').findKthLargest; + +function test() { + assert.equal(findKthLargest([3,2,1,5,6,4], 2), 5); + assert.equal(findKthLargest([3,2,3,1,2,4,5,5,6], 4), 4); + assert.equal(findKthLargest([0], 1), 0); + assert.equal(findKthLargest([], 1), undefined); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Linked_List_Cycle_II_Test.js b/LeetcodeProblemsTests/Linked_List_Cycle_II_Test.js new file mode 100644 index 0000000..e4873bf --- /dev/null +++ b/LeetcodeProblemsTests/Linked_List_Cycle_II_Test.js @@ -0,0 +1,31 @@ +const assert = require('assert'); +var ListNode = require('../UtilsClasses/ListNode').ListNode; +const detectCycle = require('../LeetcodeProblems/Linked_List_Cycle_II').detectCycle; + +var test = function() { + const cycle = buildCycle(); + var list = cycle.list; + var nodeCycle = cycle.nodeCycle; + assert.equal(detectCycle(list), nodeCycle); +} + +function buildCycle() { + var node1 = ListNode.linkenList([1,2,3,4,5]); + var node2 = new ListNode(2); + var node3 = new ListNode(3); + var node4 = new ListNode(4); + var node5 = new ListNode(5); + + node1.next = node2; + node2.next = node3; + node3.next = node4; + node4.next = node5; + node5.next = node2; + + return { + list: node1, + nodeCycle: node2, + }; +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Longest_Consecutive_Sequence_Test.js b/LeetcodeProblemsTests/Longest_Consecutive_Sequence_Test.js new file mode 100644 index 0000000..f1ef053 --- /dev/null +++ b/LeetcodeProblemsTests/Longest_Consecutive_Sequence_Test.js @@ -0,0 +1,12 @@ +const assert = require('assert'); +const longestConsecutive = require('../LeetcodeProblems/Longest_Consecutive_Sequence').longestConsecutive; + +function test() { + assert.equal(longestConsecutive([100, 1, 200, 3, 2, 400, 201]), 3); + assert.equal(longestConsecutive([1,2,3,4, 100, 1, 200, 3, 2, 400, 201]), 4); + assert.equal(longestConsecutive([1, 400, 201, 403, 398]), 1); + assert.equal(longestConsecutive([]), 0); + assert.equal(longestConsecutive([2]), 1); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Longest_Palindromic_Substring_Test.js b/LeetcodeProblemsTests/Longest_Palindromic_Substring_Test.js new file mode 100644 index 0000000..c177ff4 --- /dev/null +++ b/LeetcodeProblemsTests/Longest_Palindromic_Substring_Test.js @@ -0,0 +1,13 @@ +const assert = require('assert'); +const longestPalindrome = require('../LeetcodeProblems/Longest_Palindromic_Substring').longestPalindrome; + +function test() { + assert.equal(longestPalindrome("pabcdcbte"), "bcdcb"); + assert.equal(longestPalindrome("bb"), "bb"); + assert.equal(longestPalindrome(""), ""); + assert.equal(longestPalindrome("bbb"), "bbb"); + assert.equal(longestPalindrome("bbbb"), "bbbb"); + assert.equal(longestPalindrome("ptabbbbat"), "tabbbbat"); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Lowest_Common_Ancestor_of_a_Binary_Tree_Test.js b/LeetcodeProblemsTests/Lowest_Common_Ancestor_of_a_Binary_Tree_Test.js new file mode 100644 index 0000000..dc66300 --- /dev/null +++ b/LeetcodeProblemsTests/Lowest_Common_Ancestor_of_a_Binary_Tree_Test.js @@ -0,0 +1,39 @@ +const assert = require('assert'); +var TreeNode = require('../UtilsClasses/TreeNode').TreeNode; +const lowestCommonAncestor = require('../LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree').lowestCommonAncestor; +const lowestCommonAncestor2 = require('../LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree').lowestCommonAncestor2; + +var test = function() { + var root = new TreeNode(3); + + var right = new TreeNode(1); + right.left = new TreeNode(0); + right.right = new TreeNode(8); + root.right = right; + + var left = new TreeNode(5); + left.left = new TreeNode(6); + + var tempRight = new TreeNode(2); + tempRight.left = new TreeNode(7); + tempRight.right = new TreeNode(4); + left.right = tempRight; + + root.left = left; + + // _______3______ + // / \ + // ___5__ ___1__ + // / \ / \ + // 6 _2 0 8 + // / \ + // 7 4 + + console.log(lowestCommonAncestor(root, left, tempRight.right)); + console.log(lowestCommonAncestor(root, left, right)); + + console.log(lowestCommonAncestor2(root, left, tempRight.right)); + console.log(lowestCommonAncestor2(root, left, right)); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Majority_Element_Test.js b/LeetcodeProblemsTests/Majority_Element_Test.js new file mode 100644 index 0000000..6d573b1 --- /dev/null +++ b/LeetcodeProblemsTests/Majority_Element_Test.js @@ -0,0 +1,10 @@ +const assert = require('assert'); +const majorityElement = require('../LeetcodeProblems/Majority_Element').majorityElement; + +function test() { + assert.equal(majorityElement([2,2,3]), 2); + assert.equal(majorityElement([2,3,2]), 2); + assert.equal(majorityElement([1,1,1,2,3,45,1,2,4,1,1]), 1); +} + +module.exports.test = test diff --git a/LeetcodeProblemsTests/Maximal_Square_Test.js b/LeetcodeProblemsTests/Maximal_Square_Test.js new file mode 100644 index 0000000..accb1cc --- /dev/null +++ b/LeetcodeProblemsTests/Maximal_Square_Test.js @@ -0,0 +1,14 @@ +const assert = require('assert'); +const maximalSquare = require('../LeetcodeProblems/Maximal_Square').maximalSquare; + +function test() { + assert.equal(maximalSquare([["1","0"]]), 1); + assert.equal(maximalSquare([["1"]]), 1); + assert.equal(maximalSquare([["0"]]), 0); + assert.equal( + maximalSquare([["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]), + 4 + ); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Maximun_Subarray_Test.js b/LeetcodeProblemsTests/Maximun_Subarray_Test.js new file mode 100644 index 0000000..434b43b --- /dev/null +++ b/LeetcodeProblemsTests/Maximun_Subarray_Test.js @@ -0,0 +1,11 @@ +const assert = require('assert'); +const maxSubArray = require('../LeetcodeProblems/Maximun_Subarray').maxSubArray; + +function test() { + assert.equal(maxSubArray([]), 0); + assert.equal(maxSubArray([-4]), -4); + assert.equal(maxSubArray([2]), 2); + assert.equal(maxSubArray([4,1,-1,4,5,6,7,-200]), 26); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Min_Stack_Test.js b/LeetcodeProblemsTests/Min_Stack_Test.js new file mode 100644 index 0000000..0f608f2 --- /dev/null +++ b/LeetcodeProblemsTests/Min_Stack_Test.js @@ -0,0 +1,15 @@ +const assert = require('assert'); +const MinStack = require('../LeetcodeProblems/Min_Stack').MinStack; + +function test() { + var minStack = new MinStack(); + minStack.push(-2); + minStack.push(0); + minStack.push(-3); + assert.equal(minStack.getMin(), -3); + assert.equal(minStack.pop(), -3); + assert.equal(minStack.top(), 0); + assert.equal(minStack.getMin(), -2); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Minimum_Window_Substring_Test.js b/LeetcodeProblemsTests/Minimum_Window_Substring_Test.js new file mode 100644 index 0000000..602a944 --- /dev/null +++ b/LeetcodeProblemsTests/Minimum_Window_Substring_Test.js @@ -0,0 +1,13 @@ +const assert = require('assert'); +const minWindow = require('../LeetcodeProblems/Minimum_Window_Substring').minWindow; + +function test() { + assert.equal(minWindow("ADOBECODEBANC", "ABC"), "BANC"); + assert.equal(minWindow("caaec", "cae"), "aec"); + assert.equal(minWindow("bbacbb", "ab"), "ba"); + assert.equal(minWindow("abba", "b"), "b"); + assert.equal(minWindow("abba", "a"), "a"); + assert.equal(minWindow("abba", ""), ""); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/NQueens_Test.js b/LeetcodeProblemsTests/NQueens_Test.js new file mode 100644 index 0000000..bb9fdb9 --- /dev/null +++ b/LeetcodeProblemsTests/NQueens_Test.js @@ -0,0 +1,28 @@ +const assert = require('assert'); +const solveNQueens = require('../LeetcodeProblems/NQueens').solveNQueens; + +// TODO: Add assertions + +var test = function() { + printMatrixes(solveNQueens(4), 4); + printMatrixes(solveNQueens(5), 5); + printMatrixes(solveNQueens(6), 6); +} + +var printMatrixes = function(matrixes, n) { + console.log("Start solution of n: " + n); + for(var i = 0; i < matrixes.length; i++) { + printMatrix(matrixes[i]); + } + console.log("End solution of n: " + n); +} + +var printMatrix = function(matrix) { + console.log("------------"); + for(var i = 0; i < matrix.length; i++) { + console.log(matrix[i]); + } + console.log("------------"); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Number_of_Islands_Test.js b/LeetcodeProblemsTests/Number_of_Islands_Test.js new file mode 100644 index 0000000..d28ac2c --- /dev/null +++ b/LeetcodeProblemsTests/Number_of_Islands_Test.js @@ -0,0 +1,19 @@ +const assert = require('assert'); +const numIslands = require('../LeetcodeProblems/Number_of_Islands').numIslands; + +function test() { + assert.equal(numIslands([[1]]), 1); + assert.equal(numIslands([]), 0); + assert.equal(numIslands( + [ + ["1","1","1","1","0"], + ["1","1","0","1","0"], + ["1","1","0","0","0"], + ["0","0","0","0","0"] + ], + ), + 1 + ); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Number_of_Segments_in_a_String_Test.js b/LeetcodeProblemsTests/Number_of_Segments_in_a_String_Test.js new file mode 100644 index 0000000..51fd2b4 --- /dev/null +++ b/LeetcodeProblemsTests/Number_of_Segments_in_a_String_Test.js @@ -0,0 +1,13 @@ +const assert = require('assert'); +const countSegments = require('../LeetcodeProblems/Number_of_Segments_in_a_String').countSegments; + +function test() { + assert.equal(countSegments(" "), 0); + assert.equal(countSegments(" "), 0); + assert.equal(countSegments("ab cd ef"), 3); + assert.equal(countSegments(" ab cd ef"), 3); + assert.equal(countSegments("ab cd ef "), 3); + assert.equal(countSegments(" ab cd ef "), 3); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Permutations_II_Test.js b/LeetcodeProblemsTests/Permutations_II_Test.js new file mode 100644 index 0000000..5c802df --- /dev/null +++ b/LeetcodeProblemsTests/Permutations_II_Test.js @@ -0,0 +1,30 @@ +const assert = require('assert'); +const permuteUnique = require('../LeetcodeProblems/Permutations_II').permuteUnique; + +function test() { + assert.deepEqual( + permuteUnique([1,1,2]), + [ [ '1', '1', '2' ], [ '1', '2', '1' ], [ '2', '1', '1' ] ] + ); + assert.deepEqual( + permuteUnique([1,3,2,1]), + [ + [ '1', '1', '2', '3' ], + [ '1', '1', '3', '2' ], + [ '1', '2', '1', '3' ], + [ '1', '2', '3', '1' ], + [ '1', '3', '1', '2' ], + [ '1', '3', '2', '1' ], + [ '2', '1', '1', '3' ], + [ '2', '1', '3', '1' ], + [ '2', '3', '1', '1' ], + [ '3', '1', '1', '2' ], + [ '3', '1', '2', '1' ], + [ '3', '2', '1', '1' ] + ] + ); + assert.deepEqual(permuteUnique([]), [ [] ]); + assert.deepEqual(permuteUnique([1,1]), [ [ '1', '1' ] ]); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Permutations_Test.js b/LeetcodeProblemsTests/Permutations_Test.js new file mode 100644 index 0000000..2c8ab25 --- /dev/null +++ b/LeetcodeProblemsTests/Permutations_Test.js @@ -0,0 +1,20 @@ +const assert = require('assert'); +const permute = require('../LeetcodeProblems/Permutations').permute; + +function test() { + assert.deepEqual(permute([]), [ [] ]); + assert.deepEqual(permute([1]), [ [ 1 ] ]); + assert.deepEqual( + permute([1,2,3]), + [ + [ 1, 2, 3 ], + [ 1, 3, 2 ], + [ 2, 1, 3 ], + [ 2, 3, 1 ], + [ 3, 1, 2 ], + [ 3, 2, 1 ] + ] + ); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Permutations_With_Duplicates_Test.js b/LeetcodeProblemsTests/Permutations_With_Duplicates_Test.js new file mode 100644 index 0000000..d9f6e09 --- /dev/null +++ b/LeetcodeProblemsTests/Permutations_With_Duplicates_Test.js @@ -0,0 +1,24 @@ +const assert = require('assert'); +const subsetWithoutDuplicates = require('../LeetcodeProblems/Permutations_With_Duplicates').subsetWithoutDuplicates; + +var test = function() { + assert.deepEqual( + subsetWithoutDuplicates([1,1,2,3]), + [ + [ 1, 1, 2, 3 ], + [ 1, 1, 3, 2 ], + [ 1, 2, 1, 3 ], + [ 1, 2, 3, 1 ], + [ 1, 3, 1, 2 ], + [ 1, 3, 2, 1 ], + [ 2, 1, 1, 3 ], + [ 2, 1, 3, 1 ], + [ 2, 3, 1, 1 ], + [ 3, 1, 1, 2 ], + [ 3, 1, 2, 1 ], + [ 3, 2, 1, 1 ] + ] + ); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Permutations_Without_Duplicates_Test.js b/LeetcodeProblemsTests/Permutations_Without_Duplicates_Test.js new file mode 100644 index 0000000..4340221 --- /dev/null +++ b/LeetcodeProblemsTests/Permutations_Without_Duplicates_Test.js @@ -0,0 +1,18 @@ +const assert = require('assert'); +const subsetWithoutDuplicates = require('../LeetcodeProblems/Permutations_Without_Duplicates').subsetWithoutDuplicates; + +var test = function() { + assert.deepEqual( + subsetWithoutDuplicates([1,2,3]), + [ + [ 1, 2, 3 ], + [ 1, 3, 2 ], + [ 2, 1, 3 ], + [ 2, 3, 1 ], + [ 3, 1, 2 ], + [ 3, 2, 1 ] + ] + ); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Regular_Expression_Matching_Test.js b/LeetcodeProblemsTests/Regular_Expression_Matching_Test.js new file mode 100644 index 0000000..3e01fa4 --- /dev/null +++ b/LeetcodeProblemsTests/Regular_Expression_Matching_Test.js @@ -0,0 +1,13 @@ +const assert = require('assert'); +const isMatch = require('../LeetcodeProblems/Regular_Expression_Matching').isMatch; + +var test = function() { + assert.equal(isMatch("aa", "a"), false); + assert.equal(isMatch("aa", "a*"), true); + assert.equal(isMatch("a","ab*"), true); + assert.equal(isMatch("ab", ".*"), true); + assert.equal(isMatch("aab", "c*a*b"), true); + assert.equal(isMatch("mississippi", "mis*is*p*."), false); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Remove_Invalid_Parentheses_Test.js b/LeetcodeProblemsTests/Remove_Invalid_Parentheses_Test.js new file mode 100644 index 0000000..9ab47a7 --- /dev/null +++ b/LeetcodeProblemsTests/Remove_Invalid_Parentheses_Test.js @@ -0,0 +1,11 @@ +const assert = require('assert'); +const removeInvalidParentheses = require('../LeetcodeProblems/Remove_Invalid_Parentheses').removeInvalidParentheses; + +var test = function() { + assert.equal(removeInvalidParentheses("))))(()"), "()"); + assert.equal(removeInvalidParentheses("(()"), "()"); + assert.equal(removeInvalidParentheses("(d))()"), "(d)()"); + assert.equal(removeInvalidParentheses("(())"), "(())"); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Restore_IP_Addresses_Test.js b/LeetcodeProblemsTests/Restore_IP_Addresses_Test.js new file mode 100644 index 0000000..3905d19 --- /dev/null +++ b/LeetcodeProblemsTests/Restore_IP_Addresses_Test.js @@ -0,0 +1,9 @@ +const assert = require('assert'); +const restoreIpAddresses = require('../LeetcodeProblems/Restore_IP_Addresses').restoreIpAddresses; + +var test = function() { + assert.deepEqual(restoreIpAddresses("010010"), [ '0.10.0.10', '0.100.1.0']); + assert.deepEqual(restoreIpAddresses("25525511135"), [ '255.255.11.135', '255.255.111.35' ]); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Reverse_String_II_Test.js b/LeetcodeProblemsTests/Reverse_String_II_Test.js new file mode 100644 index 0000000..37169da --- /dev/null +++ b/LeetcodeProblemsTests/Reverse_String_II_Test.js @@ -0,0 +1,11 @@ +const assert = require('assert'); +const reverseStr = require('../LeetcodeProblems/Reverse_String_II').reverseStr; + +var test = function() { + assert.equal(reverseStr("abcdefg", 2), "bacdfeg"); + assert.equal(reverseStr("abcdefg", 3), "cbadefg"); + assert.equal(reverseStr("abcdefg", 1), "abcdefg"); + assert.equal(reverseStr("abcdefg", 0), "abcdefg"); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Same_Tree_Test.js b/LeetcodeProblemsTests/Same_Tree_Test.js new file mode 100644 index 0000000..ea8b26b --- /dev/null +++ b/LeetcodeProblemsTests/Same_Tree_Test.js @@ -0,0 +1,5 @@ +var test = function() { + // TODO +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/SearchIng_Rotated_Sorted_Array_Test.js b/LeetcodeProblemsTests/SearchIng_Rotated_Sorted_Array_Test.js new file mode 100644 index 0000000..c0b0d38 --- /dev/null +++ b/LeetcodeProblemsTests/SearchIng_Rotated_Sorted_Array_Test.js @@ -0,0 +1,8 @@ +const assert = require('assert'); +const search = require('../LeetcodeProblems/SearchIng_Rotated_Sorted_Array').search; + +var test = function() { + assert.equal(search([4,5,6,7,0,1,2], 5), 1); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Search_a_2D_Matrix_II_Test.js b/LeetcodeProblemsTests/Search_a_2D_Matrix_II_Test.js new file mode 100644 index 0000000..8491aba --- /dev/null +++ b/LeetcodeProblemsTests/Search_a_2D_Matrix_II_Test.js @@ -0,0 +1,18 @@ +const assert = require('assert'); +const searchMatrix = require('../LeetcodeProblems/Search_a_2D_Matrix_II').searchMatrix; + +const matrix1 = [ + [1,4,7, 11,15], + [2,5,8, 12,19], + [3,6,9, 16,22], + [10,13,14, 17,24], + [18,21,23, 26,30] +]; + +var test = function() { + assert.equal(searchMatrix(matrix1, 5), true); + assert.equal(searchMatrix(matrix1, 0), false); + assert.equal(searchMatrix(matrix1, 15), true); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Search_a_2D_Matrix_Test.js b/LeetcodeProblemsTests/Search_a_2D_Matrix_Test.js new file mode 100644 index 0000000..1c0a741 --- /dev/null +++ b/LeetcodeProblemsTests/Search_a_2D_Matrix_Test.js @@ -0,0 +1,12 @@ +const assert = require('assert'); +const searchMatrix = require('../LeetcodeProblems/Search_a_2D_Matrix').searchMatrix; + +var test = function() { + assert.equal(searchMatrix([], 0), false); + assert.equal(searchMatrix([[1], [3]], 3), true); + assert.equal(searchMatrix([[1], [3]], 1), true); + const matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]]; + assert.equal(searchMatrix(matrix, 3), true); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Set_Matrix_Zeroes_Test.js b/LeetcodeProblemsTests/Set_Matrix_Zeroes_Test.js new file mode 100644 index 0000000..494ec09 --- /dev/null +++ b/LeetcodeProblemsTests/Set_Matrix_Zeroes_Test.js @@ -0,0 +1,11 @@ +const assert = require('assert'); +const setZeroes = require('../LeetcodeProblems/Set_Matrix_Zeroes').setZeroes; + +var test = function() { + assert.deepEqual( + setZeroes([[1,1,1],[1,0,1],[1,1,1]]), + [[1, 0, 1], [0, 0, 0], [1, 0, 1]] + ); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Simplify_Path_Test.js b/LeetcodeProblemsTests/Simplify_Path_Test.js new file mode 100644 index 0000000..f34a896 --- /dev/null +++ b/LeetcodeProblemsTests/Simplify_Path_Test.js @@ -0,0 +1,13 @@ +const assert = require('assert'); +const simplifyPath = require('../LeetcodeProblems/Simplify_Path').simplifyPath; + +var test = function() { + assert.equal(simplifyPath("/../c"), "/c"); + assert.equal(simplifyPath("/.."), "/"); + assert.equal(simplifyPath("/home/"), "/home"); // => "/home" + assert.equal(simplifyPath("/a/./b/../../c/"), "/c"); // => "/c" + assert.equal(simplifyPath("/a/../../b/../c//.//"), "/c"); // => "/c" + assert.equal(simplifyPath("/a//b////c/d//././/.."), "/a/b/c") // => "/a/b/c" +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Spiral_Matrix_Test.js b/LeetcodeProblemsTests/Spiral_Matrix_Test.js new file mode 100644 index 0000000..d7c9dd6 --- /dev/null +++ b/LeetcodeProblemsTests/Spiral_Matrix_Test.js @@ -0,0 +1,17 @@ +const assert = require('assert'); +const spiralOrder = require('../LeetcodeProblems/Spiral_Matrix').spiralOrder; + +var test = function() { + const matrix = [ + [ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ] + ] + + assert.deepEqual( + spiralOrder(matrix), + [1, 2, 3, 6, 9, 8, 7, 4, 5] + ) +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Subarray_Sum_Equals_K_Test.js b/LeetcodeProblemsTests/Subarray_Sum_Equals_K_Test.js new file mode 100644 index 0000000..3edf120 --- /dev/null +++ b/LeetcodeProblemsTests/Subarray_Sum_Equals_K_Test.js @@ -0,0 +1,11 @@ +const assert = require('assert'); +const subarraySum = require('../LeetcodeProblems/Subarray_Sum_Equals_K').subarraySum; + +var test = function() { + assert.strictEqual(subarraySum([1,1,1], 2), 2); + assert.strictEqual(subarraySum([1], 0), 0); + assert.strictEqual(subarraySum([0], 0), 1); + assert.strictEqual(subarraySum([0,0,0,0,0], 0), 15); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Subsets_Test.js b/LeetcodeProblemsTests/Subsets_Test.js new file mode 100644 index 0000000..f103e90 --- /dev/null +++ b/LeetcodeProblemsTests/Subsets_Test.js @@ -0,0 +1,17 @@ +const assert = require('assert'); +const subsets = require('../LeetcodeProblems/Subsets').subsets; + +function test() { + assert.deepEqual(subsets([]), [[]]); + assert.deepEqual(subsets([1]), [[1], []]); + assert.deepEqual( + subsets([1,2]), + [[1, 2], [1], [2], []] + ); + assert.deepEqual( + subsets([1, 2, 3]), + [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []] + ); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Sum_Of_Square_Numbers_Test.js b/LeetcodeProblemsTests/Sum_Of_Square_Numbers_Test.js new file mode 100644 index 0000000..41c777a --- /dev/null +++ b/LeetcodeProblemsTests/Sum_Of_Square_Numbers_Test.js @@ -0,0 +1,13 @@ +const assert = require('assert'); +const judgeSquareSum = require('../LeetcodeProblems/Sum_Of_Square_Numbers').judgeSquareSum; + +var test = function() { + assert.strictEqual(judgeSquareSum(0), true); + assert.strictEqual(judgeSquareSum(1), true); + assert.strictEqual(judgeSquareSum(5), true); + assert.strictEqual(judgeSquareSum(16), true); + assert.strictEqual(judgeSquareSum(24), false); + assert.strictEqual(judgeSquareSum(25), true); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Swap_Nodes_In_Pairs_Test.js b/LeetcodeProblemsTests/Swap_Nodes_In_Pairs_Test.js new file mode 100644 index 0000000..ef0785d --- /dev/null +++ b/LeetcodeProblemsTests/Swap_Nodes_In_Pairs_Test.js @@ -0,0 +1,13 @@ +const assert = require('assert'); +const ListNode = require('../UtilsClasses/ListNode').ListNode; +const ListNodeTestHelper = require('../utilsClasses/ListNodeTestHelper'); +const swapPairs = require('../LeetcodeProblems/Swap_Nodes_In_Pairs').swapPairs; + +var test = function () { + ListNodeTestHelper.assertList(swapPairs(ListNode.linkenList([1,2,3,4])), [2,1,4,3]); + ListNodeTestHelper.assertList(swapPairs(ListNode.linkenList([])), []); + ListNodeTestHelper.assertList(swapPairs(ListNode.linkenList([1])), [1]); + ListNodeTestHelper.assertList(swapPairs(ListNode.linkenList([1,2])), [2, 1]); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Symmetric_Tree_Test.js b/LeetcodeProblemsTests/Symmetric_Tree_Test.js new file mode 100644 index 0000000..ea8b26b --- /dev/null +++ b/LeetcodeProblemsTests/Symmetric_Tree_Test.js @@ -0,0 +1,5 @@ +var test = function() { + // TODO +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Tic_Tac_Toe_Test.js b/LeetcodeProblemsTests/Tic_Tac_Toe_Test.js new file mode 100644 index 0000000..ef69075 --- /dev/null +++ b/LeetcodeProblemsTests/Tic_Tac_Toe_Test.js @@ -0,0 +1,25 @@ +const TicTacToe = require('../LeetcodeProblems/Tic_Tac_Toe').TicTacToe; + +var test = function() { + ticTacToe = new TicTacToe(); + ticTacToe.isBoardFull(); + ticTacToe.addToken(0, 1, "X"); + ticTacToe.printBoard(); + var iter = 0; + + while(iter < 8) { + console.log(iter); + const str = (iter % 2 == 0) ? "0" : "X" + ticTacToe.makeMove(str); + iter++; + } + + console.log("after 8 moves"); + ticTacToe.isBoardFull(); + ticTacToe.printBoard(); + + ticTacToe.addToken(0,0,"X"); + ticTacToe.printBoard(); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Unique_Binary_Search_Trees_Test.js b/LeetcodeProblemsTests/Unique_Binary_Search_Trees_Test.js new file mode 100644 index 0000000..604e489 --- /dev/null +++ b/LeetcodeProblemsTests/Unique_Binary_Search_Trees_Test.js @@ -0,0 +1,23 @@ +const assert = require('assert'); +const numTrees1 = require('../LeetcodeProblems/Unique_Binary_Search_Trees').numTrees1; +const numTrees2 = require('../LeetcodeProblems/Unique_Binary_Search_Trees').numTrees2; +const numTrees3 = require('../LeetcodeProblems/Unique_Binary_Search_Trees').numTrees3; + +var test = function () { + assert.strictEqual(numTrees1(1), 1); + assert.strictEqual(numTrees1(2), 2); + assert.strictEqual(numTrees1(3), 5); + assert.strictEqual(numTrees1(5), 42); + + assert.strictEqual(numTrees2(1), 1); + assert.strictEqual(numTrees2(2), 2); + assert.strictEqual(numTrees2(3), 5); + assert.strictEqual(numTrees2(5), 42); + + assert.strictEqual(numTrees3(1), 1); + assert.strictEqual(numTrees3(2), 2); + assert.strictEqual(numTrees3(3), 5); + assert.strictEqual(numTrees3(5), 42); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Unique_Paths_Test.js b/LeetcodeProblemsTests/Unique_Paths_Test.js new file mode 100644 index 0000000..6334b95 --- /dev/null +++ b/LeetcodeProblemsTests/Unique_Paths_Test.js @@ -0,0 +1,17 @@ +const assert = require('assert'); +const uniquePaths1 = require('../LeetcodeProblems/Unique_Paths').uniquePaths1; +const uniquePaths2 = require('../LeetcodeProblems/Unique_Paths').uniquePaths2; +const uniquePaths3 = require('../LeetcodeProblems/Unique_Paths').uniquePaths3; + +var test = function() { + assert.strictEqual(uniquePaths1(10,4), 220); + assert.strictEqual(uniquePaths1(3,2), 3); + + assert.strictEqual(uniquePaths2(10,4), 220); + assert.strictEqual(uniquePaths2(3,2), 3); + + assert.strictEqual(uniquePaths3(10,4), 220); + assert.strictEqual(uniquePaths3(3,2), 3); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Valid_Parentheses_Test.js b/LeetcodeProblemsTests/Valid_Parentheses_Test.js new file mode 100644 index 0000000..7e3baee --- /dev/null +++ b/LeetcodeProblemsTests/Valid_Parentheses_Test.js @@ -0,0 +1,12 @@ +const assert = require('assert'); +const isValid = require('../LeetcodeProblems/Valid_Parentheses').isValid; + +var test = function () { + assert.strictEqual(isValid(""), true); + assert.strictEqual(isValid("()"), true); + assert.strictEqual(isValid("([)]"), false); + assert.strictEqual(isValid("{[()]}{[()]}"), true); + assert.strictEqual(isValid("{[())()]}"), false); +} + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/Verify_Preorder_Serialization_of_a_Binary_Tree_Test.js b/LeetcodeProblemsTests/Verify_Preorder_Serialization_of_a_Binary_Tree_Test.js new file mode 100644 index 0000000..9f8b65d --- /dev/null +++ b/LeetcodeProblemsTests/Verify_Preorder_Serialization_of_a_Binary_Tree_Test.js @@ -0,0 +1,13 @@ +const assert = require('assert'); +const isValidSerialization = require('../LeetcodeProblems/Verify_Preorder_Serialization_of_a_Binary_Tree').isValidSerialization; + +var test = function() { + assert.strictEqual(isValidSerialization(""), true); + assert.strictEqual(isValidSerialization(""), true); + assert.strictEqual(isValidSerialization("#"), true); + assert.strictEqual(isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#"), true); + assert.strictEqual(isValidSerialization("9,#,92,#,#"), true); + assert.strictEqual(isValidSerialization("9,3,4,#,#,1,#,#,#,2,#,6,#,#"), false); +}; + +module.exports.test = test; diff --git a/LeetcodeProblemsTests/merge_k_sorted_lists_Test.js b/LeetcodeProblemsTests/merge_k_sorted_lists_Test.js new file mode 100644 index 0000000..42d0a89 --- /dev/null +++ b/LeetcodeProblemsTests/merge_k_sorted_lists_Test.js @@ -0,0 +1,27 @@ +const assert = require('assert'); +const ListNodeTestHelper = require('../utilsClasses/ListNodeTestHelper'); +var ListNode = require('../UtilsClasses/ListNode').ListNode; +const mergeKLists = require('../LeetcodeProblems/merge_k_sorted_lists').mergeKLists; + +function test() { + assert.deepEqual(mergeKLists([]), null); + assert.deepEqual( + mergeKLists([null]), + null + ); + assert.deepEqual( + mergeKLists([null, null]), + null + ); + + var list1 = ListNode.linkenList([1,2,3]); + var list2 = ListNode.linkenList([2,3,4]); + var list3 = ListNode.linkenList([5,6]); + var list4 = ListNode.linkenList([1,5]); + ListNodeTestHelper.assertList( + mergeKLists([list1, list2, list3, list4]), + [1, 1, 2, 2, 3, 3, 4, 5, 5, 6] + ); +} + +module.exports.test = test; diff --git a/Main.js b/Main.js index 532b015..82723cf 100644 --- a/Main.js +++ b/Main.js @@ -1,20 +1,20 @@ const fs = require('fs'); -const PROBLEMS_FOLDER = './LeetcodeProblems/'; +const TESTS_FOLDER = './LeetcodeProblemsTests/'; const REGEX_PATTERN_HIDDEN_FILES = /(^|\/)\.[^\/\.]/g; var main = async function() { try { const problems = await loadProblems(); - for(i in problems) { - console.log("Solving: " + problems[i] + ":"); - const problem = require(PROBLEMS_FOLDER + problems[i]); + for(i in problems) { + console.log("Solving: " + problems[i]); + const problem = require(TESTS_FOLDER + problems[i]); - if (typeof(problem.main) !=='undefined') { - problem.main(); - console.log("End of the solution for : " + problems[i] + ",\n\n"); + if (typeof(problem.test) !=='undefined') { + problem.test(); + console.log("End of the solution for : " + problems[i] + " \n\n"); } else { - console.warn(problem, "The problem " + problems[i] + " doesn't have a main method implemented."); + console.warn(problem, "The problem " + problems[i] + " doesn't have a test method implemented."); } } } catch (error) { @@ -24,7 +24,7 @@ var main = async function() { var loadProblems = () => { return new Promise(function (resolve, reject) { - fs.readdir(PROBLEMS_FOLDER, (error, files) => { + fs.readdir(TESTS_FOLDER, (error, files) => { if (error) { reject(error); } else { diff --git a/README.md b/README.md index 162bfd1..342de61 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,14 @@ Solutions of algorithm problems using Javascript. https://ignacio-chiazzo.github.io/Algorithms-Leetcode-Javascript/ -### Run Scripts +### Structure +The solutions are located under /LeetcodeProblems. Each solutions exports the main function(s) which to be tested. Each problem has a test file located under /LeetcodeProblemsTest. + -Each problem has a main function exported which prints some cases (Tests are going to be added soon 😉)). -To run a specific problem in your console run `node ` (e.g. `node LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree.js`). +### Run Scripts +To run all the test run `node Main.js` in the console. -You can also run all the problems by running the `Main.js` file. +To run a specific problem in your console, go to the file test, add the call to the test function (`test()` ) and run in the console `node ` (e.g. `node LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree.js`). ### Leetcode Problems @@ -80,3 +82,10 @@ You can also run all the problems by running the `Main.js` file. Other languages provides built-in classes (e.g Linked List, Tree, etc). This module contains util classes to use in your problems. +### Contributions + +If you want to contribute to this repo by adding a problem you should: + +1) Add the description of the problem at the top of the file. +2) Add a test file with some test cases. The test file must export a `test()` function which should run all the tests of the file. +3) Add your problem to the Readme so that your problem shows up in the list of solutions.