diff --git a/InterviewTips/README.md b/InterviewTips/README.md new file mode 100644 index 0000000..d5a5f34 --- /dev/null +++ b/InterviewTips/README.md @@ -0,0 +1,32 @@ +# Clarification Questions +- What is the input type and output type +- Questions to ask for number type inputs +1. are there any negative numbers? +2. are they integers? +3. What is the range of the number + +- Questions to ask for string type inputs +1. Any special characters? e.g. spaces, Uppercase, lowercase, emoji, new line character, etc... +2. range/length of the string + +- Questions to ask for array type inputs +1. dimension: 1d, 2d, 3d +2. the content type, based on which more questions should be asked +3. any empty values? + +# Detail-orientation +Edge cases + +# Efficient communication +use terminology to express the algo. Below is a list: +- bianry search +- divide and counter +- two pointers... + +# Recommended flow +1. ask clarification questions +2. use terminiology to communicate our thoughts concisely with interviewer +3. start coding +4. run some test case to debug +5. ask the interviewer some questions + diff --git a/JS-langauge-specific-notes/README.md b/JS-langauge-specific-notes/README.md new file mode 100644 index 0000000..44309d6 --- /dev/null +++ b/JS-langauge-specific-notes/README.md @@ -0,0 +1,6 @@ +# MAX INTEGER +(Number.MAX_SAFE_INTEGER)[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER] + +# Check whether a data structure is an array +(Array.isArray(nums))[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray] + diff --git a/README.md b/README.md index c127c96..14cc624 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # Algorithms Using JS -Solutions to algorithm problems written in JavaScript +Templates to common algorithm problems written in JavaScript # To Test 1. run `yarn install` or `npm install` at the root of this project diff --git a/alienDictionary.js b/alienDictionary.js deleted file mode 100644 index e4cf309..0000000 --- a/alienDictionary.js +++ /dev/null @@ -1,161 +0,0 @@ -// 269. Alien Dictionary -// Hard - -// There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language. - -// Example 1: - -// Input: -// [ -// "wrt", -// "wrf", -// "er", -// "ett", -// "rftt" -// ] - -// Output: "wertf" -// Example 2: - -// Input: -// [ -// "z", -// "x" -// ] - -// Output: "zx" -// Example 3: - -// Input: -// [ -// "z", -// "x", -// "z" -// ] - -// Output: "" - -// Explanation: The order is invalid, so return "". -// Note: - -// You may assume all letters are in lowercase. -// If the order is invalid, return an empty string. -// There may be multiple valid order of letters, return any one of them is fine. - - -/** - * @param {string[]} words - * @return {string} - */ -var alienOrder = function(words) { - let res = "" - const graph = buildGraph(words)["graph"] - const isValid = buildGraph(words).isValid - if(!isValid) return "" - - const indegree = getInDgree(graph) - const orderedArr = [] - const isGraph = false; - - Object.keys(indegree).forEach((char)=>{ - - if(indegree[char] === 0 ) { - insertCharIntoOrderedArr(char, orderedArr) - } - }) - - // orderedArr - while (!isOrderedArrEmpty(orderedArr)) { - const curChar = getFirstCharInOrderedArr(orderedArr); - res += curChar; - // neighbors in degree -1 - const neighbors = graph[curChar] - neighbors.forEach((char) => { - indegree[char]-- - if (indegree[char] == 0 ) { - insertCharIntoOrderedArr(char, orderedArr) - } - }) - } - - if (res.length !== Object.keys(graph).length) return "" - return res -}; - -function isOrderedArrEmpty (orderedArr) { - for (let i = 0 ; i < orderedArr.length ; i++) { - if(orderedArr[i]!== undefined) { - return false - } - } - return true; -} - -function getFirstCharInOrderedArr (orderedArr) { - for (let i = 0 ; i < orderedArr.length ; i++) { - if(orderedArr[i] !== undefined){ - const res = orderedArr[i] - orderedArr[i] = undefined - return res - } - } -} - -function insertCharIntoOrderedArr (char, orderedArr) { - const ENGALPHABET = "abcdefghijklmnopqrstuvwxyz" - const idx = ENGALPHABET.indexOf(char) - orderedArr[idx] = char - return orderedArr -} - - - - -function getInDgree (graph) { - let inDegree = {} - Object.keys(graph).forEach( (char) => { - inDegree[char] = inDegree[char] || 0; - const neighbors = graph[char]; - neighbors.forEach((ch)=>{ - inDegree[ch] = inDegree[ch] || 0; - inDegree[ch]++ - }) - }) - - return inDegree - -} - -//build a graph with nodes -function buildGraph (words) { - let isValid = true - const graph = {} - for (let word of words) { - for (let char of word) { - graph[char] = new Set() - } - } - - for (let i = 0; i < words.length - 1 ; i++) { - - const curWord = words[i] - const nextWord = words[i+1] - - for (var j = 0; j < Math.min(curWord.length, nextWord.length); j++) { - - if(curWord[j] !== nextWord[j]) { - - graph[curWord[j]].add(nextWord[j]) - break - }else { - if(curWord[j+1] && !nextWord[j+1]){ - isValid = false - } - } - } - - } - return {graph,isValid} -} - - diff --git a/average-of-levels-in-binary-tree.js b/average-of-levels-in-binary-tree.js deleted file mode 100644 index adec4a7..0000000 --- a/average-of-levels-in-binary-tree.js +++ /dev/null @@ -1,56 +0,0 @@ -// 637. Average of Levels in Binary Tree -// Easy - -// 1298 - -// 167 - -// Add to List - -// Share -// Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. -// Example 1: -// Input: -// 3 -// / \ -// 9 20 -// / \ -// 15 7 -// Output: [3, 14.5, 11] -// Explanation: -// The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. - -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number[]} - */ - -var averageOfLevels = function(root) { - const res = [] - const queue = [root] - - while(queue.length) { - let sum = 0; - const count = queue.length; - - for (let i = 0; i < count; i++) { - const curNode = queue.shift() - sum += curNode.val; - if(curNode.left) {queue.push(curNode.left)} - if(curNode.right) {queue.push(curNode.right)} - } - - res.push(sum/count) - } - - return res - -}; diff --git a/binary-search-tree-iterator.js b/binary-search-tree-iterator.js deleted file mode 100644 index 09874a9..0000000 --- a/binary-search-tree-iterator.js +++ /dev/null @@ -1,77 +0,0 @@ -// 173. Binary Search Tree Iterator -// Medium - - -// Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. - -// Calling next() will return the next smallest number in the BST. - - -// Example: - - - -// BSTIterator iterator = new BSTIterator(root); -// iterator.next(); // return 3 -// iterator.next(); // return 7 -// iterator.hasNext(); // return true -// iterator.next(); // return 9 -// iterator.hasNext(); // return true -// iterator.next(); // return 15 -// iterator.hasNext(); // return true -// iterator.next(); // return 20 -// iterator.hasNext(); // return false - - -// Note: - -// next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. -// You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called. - -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - */ -var BSTIterator = function(root) { - this.allNodes = []; - dfs(root, this.allNodes); - this.curIdx = 0; -}; - -function dfs (root, allNodes) { - if(!root) return - dfs(root.left, allNodes) - allNodes.push(root.val) - dfs(root.right, allNodes) -} -/** - * @return the next smallest number - * @return {number} - */ -BSTIterator.prototype.next = function() { - const curNode = this.allNodes[this.curIdx] - this.curIdx++; - return curNode; -}; - -/** - * @return whether we have a next smallest number - * @return {boolean} - */ -BSTIterator.prototype.hasNext = function() { - return this.curIdx < this.allNodes.length -}; - -/** - * Your BSTIterator object will be instantiated and called as such: - * var obj = new BSTIterator(root) - * var param_1 = obj.next() - * var param_2 = obj.hasNext() - */ \ No newline at end of file diff --git a/binarySearch/basicTemplate.js b/binarySearch/basicTemplate.js new file mode 100644 index 0000000..be94edb --- /dev/null +++ b/binarySearch/basicTemplate.js @@ -0,0 +1,24 @@ +function binarySearch (nums, target) { + if(!nums || !Array.isArray(nums) || !nums.length ) return -1; + + let start = 0; + let end = nums.length - 1; + + while (start + 1 < end) { + const mid = Math.floor(start - (start - end) / 2); + if(nums[mid] === target) { + return mid; + } else if (nums[mid] > target) { + end = mid; + } else { + start = mid + } + } + + if(nums[start] === target) return start + if(nums[end] === target) return end + + return -1; +} + +module.exports = binarySearch diff --git a/binarySearch/basicTemplate.test.js b/binarySearch/basicTemplate.test.js new file mode 100644 index 0000000..5acbaf7 --- /dev/null +++ b/binarySearch/basicTemplate.test.js @@ -0,0 +1,5 @@ +const binarySearch = require('./basicTemplate.js'); + +test(`binarySearch`, () => { + expect(binarySearch([1,2,3], 2)).toEqual(1); + }); \ No newline at end of file diff --git a/binarySearch/findFirstAndLastPositionOfElementInSortedArray.js b/binarySearch/findFirstAndLastPositionOfElementInSortedArray.js new file mode 100644 index 0000000..3715e97 --- /dev/null +++ b/binarySearch/findFirstAndLastPositionOfElementInSortedArray.js @@ -0,0 +1,47 @@ + +function findFirstAndLst (nums, target) { + let res = [-1, -1]; + if(!nums || !Array.isArray(nums) || !nums.length) { + return res; + } + + let start = 0; + let end = nums.length - 1; + // find start + while (start + 1 < end ) { + const mid = Math.floor( start - (start - end) / 2); + if (nums[mid] >= target ) { + end = mid + } else { + start = mid + } + } + + if ( nums[start] === target ) { + res[0] = start + } else if ( nums[end] === target) { + res[0] = end + } + + start = 0; + end = nums.length - 1; + // find end + while (start + 1 < end ) { + const mid = Math.floor( start - (start - end) / 2); + if (nums[mid] > target ) { + end = mid + } else { + start = mid + } + } + + if ( nums[end] === target ) { + res[1] = end + } else if ( nums[start] === target) { + res[1] = start + } + + return res; +} + +module.exports = findFirstAndLst diff --git a/binarySearch/findFirstAndLastPositionOfElementInSortedArray.test.js b/binarySearch/findFirstAndLastPositionOfElementInSortedArray.test.js new file mode 100644 index 0000000..bdc9d51 --- /dev/null +++ b/binarySearch/findFirstAndLastPositionOfElementInSortedArray.test.js @@ -0,0 +1,5 @@ +const findFirstAndLastPositionOfElementInSortedArray = require('./findFirstAndLastPositionOfElementInSortedArray.js'); + +test(`findFirstAndLastPositionOfElementInSortedArray`, () => { + expect(findFirstAndLastPositionOfElementInSortedArray([1,2,2,2,2,3], 2)).toEqual([1, 4]); +}); \ No newline at end of file diff --git a/binarySearch/searchInRotatedSortedArray.js b/binarySearch/searchInRotatedSortedArray.js new file mode 100644 index 0000000..55e6394 --- /dev/null +++ b/binarySearch/searchInRotatedSortedArray.js @@ -0,0 +1,37 @@ +function searchInRotatedSortedArray (nums, target) { + if(!nums || !Array.isArray(nums) || !nums.length ) return -1; + + let start = 0; + let end = nums.length - 1; + + while (start + 1 < end) { + const mid = Math.floor(start - (start - end) / 2); + if(nums[mid] === target) { + return mid; + } + + + if (nums[mid] >= nums[start]) { + if (target >= nums[start] && target < nums[mid]) { + end = mid + } else { + start = mid + } + } else { + if(target <= nums[end] && target > nums[mid]) { + start = mid + } else { + end = mid + } + } + } + + if(nums[start] === target) return start + if(nums[end] === target) return end + + return -1; + +} + + +module.exports = searchInRotatedSortedArray; \ No newline at end of file diff --git a/binarySearch/searchInRotatedSortedArray.test.js b/binarySearch/searchInRotatedSortedArray.test.js new file mode 100644 index 0000000..6cffaa6 --- /dev/null +++ b/binarySearch/searchInRotatedSortedArray.test.js @@ -0,0 +1,7 @@ + +const searchInRotatedSortedArray = require('./searchInRotatedSortedArray.js'); + +test(`searchInRotatedSortedArray`, () => { + expect(searchInRotatedSortedArray([4, 5, 1, 2, 3], 2)).toEqual(3); +}); + diff --git a/binaryTreeZigzagLevelOrderTraversal.js b/binaryTreeZigzagLevelOrderTraversal.js deleted file mode 100644 index e30f1fe..0000000 --- a/binaryTreeZigzagLevelOrderTraversal.js +++ /dev/null @@ -1,68 +0,0 @@ -//https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ -// 103. Binary Tree Zigzag Level Order Traversal -// Medium - -// Share -// Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). - -// For example: -// Given binary tree [3,9,20,null,null,15,7], -// 3 -// / \ -// 9 20 -// / \ -// 15 7 -// return its zigzag level order traversal as: -// [ -// [3], -// [20,9], -// [15,7] -// ] - - -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number[][]} - */ -var zigzagLevelOrder = function(root) { - if (!root) return [] - const res = [] - let leftToRight = true; - const queue =[root] - - while(queue.length) { - const curLevelNodes = []; - const curLevelLen = queue.length - - for(let i = 0; i < curLevelLen; i++){ - - if(leftToRight){ - - curNode = queue.shift(); - curLevelNodes.push(curNode.val) - - curNode.left && queue.push(curNode.left) - curNode.right && queue.push(curNode.right) - } else { - curNode = queue.pop(); - curLevelNodes.push(curNode.val) - curNode.right && queue.unshift(curNode.right) - curNode.left && queue.unshift(curNode.left) - } - - } - leftToRight = !leftToRight - res.push(curLevelNodes) - - } - return res - -}; diff --git a/bubbleSort.js b/bubbleSort.js deleted file mode 100644 index 3af2fd3..0000000 --- a/bubbleSort.js +++ /dev/null @@ -1,30 +0,0 @@ -// take in an unsorted arr -// return a sorted arr -// sorts in place -function bubbleSort(arr) { - if(!Array.isArray(arr)) return [] - - const arrCopy = arr.slice() - //sorts an element at a time - let count = 0; - - while (count < arrCopy.length - 1) { - arrCopy.forEach((ele, idx)=>{ - //exclude the last element - //exclude the number of elements that have been sorted - if(idx !== arrCopy.length - 1 - count) { - if(ele > arrCopy[idx + 1]) { - arrCopy[idx] = arrCopy[idx + 1] - arrCopy[idx + 1] = ele - } - } - }) - count++ - } - - console.log("arrCopy", arrCopy) - - return arrCopy -} - -module.exports = bubbleSort; diff --git a/checkIsPrime.js b/checkIsPrime.js deleted file mode 100644 index 8784d06..0000000 --- a/checkIsPrime.js +++ /dev/null @@ -1,139 +0,0 @@ -// // check whether a number is a prime number - -//correct answer : less effective, O(n)=n, faster - -function isPriNum (num){ - if (num%1 !== 0 | num ===1){ - return false; - } - - if(num === 2){ - return true - } - if (num%2 === 0){ - return false - } - - else{ - for (var a = num-2; a >= 2; a = a-2){ - if (num%a === 0){ - return false - } - } - return true - } -} - -console.log(isPriNum(1)); -console.log(isPriNum(2)); -console.log(isPriNum(3)); -console.log(isPriNum(4)); -console.log(isPriNum(5)); -console.log(isPriNum(6)); -console.log(isPriNum(53)); - - - -// one of the best ways - -// a^1/2 - - -// If a number is not a prime, it will be the result of x*y, xa^1/2 - - - - -//correct answer : less effective, O(n)=n -// second try by Jun - - - -// function isPriNum (num){ -// if (num%1 !== 0 | num ===1){ -// return false; -// } - -// // if(num ===2){ -// // return true -// // } - - -// else{ -// for (var a= num-1; a >= 2; a--){ -// if (num%a ===0){ -// return false -// } -// } -// return true -// } -// } -// // console.log(isPriNum(1.5)); -// console.log(isPriNum(1)); -// console.log(isPriNum(2)); -// console.log(isPriNum(3)); -// console.log(isPriNum(4)); -// console.log(isPriNum(5)); -// console.log(isPriNum(6)); -// console.log(isPriNum(13)); - - - - - - - - - - - - - -//correct answer : very ineffective, O(n)=n^2 - -// first try by Jun - - -// function isPriNum (num){ -// if (num%1 !== 0 | num ===1){ -// return false; -// } -// else{ -// if (num === 2){ -// return true -// } - -// else{ -// var priNumArr = [2]; -// for (var i = 3; i<= num; i++ ){ -// for (var j=0; j= 0;i--){ -// resLefStr+=leftStr[i] - -// } -// if (resLefStr===rightStr){ -// return true; -// } -// else{ -// return false; -// } - - -// } diff --git a/cloneGraph.js b/cloneGraph.js deleted file mode 100644 index 0dc9b23..0000000 --- a/cloneGraph.js +++ /dev/null @@ -1,132 +0,0 @@ -//https://leetcode.com/problems/clone-graph/ -// 133. Clone Graph -// Medium - -// 1848 - -// 1384 - -// Add to List - -// Share -// Given a reference of a node in a connected undirected graph. - -// Return a deep copy (clone) of the graph. - -// Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors. - -// class Node { -// public int val; -// public List neighbors; -// } - - -// Test case format: - -// For simplicity sake, each node's value is the same as the node's index (1-indexed). For example, the first node with val = 1, the second node with val = 2, and so on. The graph is represented in the test case using an adjacency list. - -// Adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. - -// The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph. - - - -// Example 1: - - -// Input: adjList = [[2,4],[1,3],[2,4],[1,3]] -// Output: [[2,4],[1,3],[2,4],[1,3]] -// Explanation: There are 4 nodes in the graph. -// 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). -// 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). -// 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). -// 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). -// Example 2: - - -// Input: adjList = [[]] -// Output: [[]] -// Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. -// Example 3: - -// Input: adjList = [] -// Output: [] -// Explanation: This an empty graph, it does not have any nodes. -// Example 4: - - -// Input: adjList = [[2],[1]] -// Output: [[2],[1]] - - -// Constraints: - -// 1 <= Node.val <= 100 -// Node.val is unique for each node. -// Number of Nodes will not exceed 100. -// There is no repeated edges and no self-loops in the graph. -// The Graph is connected and all nodes can be visited starting from the given node. - - -var cloneGraph = function(node) { - //get all nodes - const oldNodeArr = getAllNodes(node) - - - //find a mapping between old nodes and new nodes - const newNodeArr = cloneAndMapAllNodes(oldNodeArr) - - connectNewNodesBasedOnOldNodes(oldNodeArr, newNodeArr) - //duplicate the edges - - return newNodeArr[0] -}; - -function connectNewNodesBasedOnOldNodes(oldNodeArr, newNodeArr) { - oldNodeArr.forEach( - (node, idx) =>{ - const newNode = newNodeArr[idx] - node.neighbors.forEach((neighbor)=>{ - const neighborIdx = oldNodeArr.indexOf(neighbor) - newNode.neighbors.push(newNodeArr[neighborIdx]) - }) - } - ) -} - -function cloneAndMapAllNodes (oldNodeArr) { - const newNodesArr = [] - oldNodeArr.forEach((node)=>{ - newNodesArr.push(new Node(node.val)) - }) - return newNodesArr -} - -function cloneAndMapAllNodes (oldNodeArr) { - const newNodesArr = [] - oldNodeArr.forEach((node)=>{ - newNodesArr.push(new Node(node.val)) - }) - return newNodesArr -} - -function getAllNodes (head) { - if(!head) return [] - const visited = new Set() - visited.add(head) - const queue = [head]; - const res = []; - while(queue.length) { - const curNode = queue.shift(); - res.push(curNode) - - curNode.neighbors.forEach((neighbor)=>{ - if (!visited.has(neighbor)) { - visited.add(neighbor) - queue.push(neighbor) - } - }) - } - - return res -} diff --git a/coinGame.js b/coinGame.js deleted file mode 100644 index 7250dc2..0000000 --- a/coinGame.js +++ /dev/null @@ -1,55 +0,0 @@ -//Challenge: -// Here is the rule for a coin game: -// Two people paly this game together -// Everyone can pick 1~3 coins at a time -// who grabs the last coins is winner -// Suppose the players are rational -// write a function to determine if you can win when seeing a fixed amount of coins - - - - -function canWil (numCoin){ - if numCoin%4 === 0{ - return "false" - } - else{ - return "true" - } - -} - - -//1 -//2 -//3 -// get 4 for the other player -// 8 -// 12 - -// 1,2,3 -// 1,2,3 - -// 1:-win -// 2:-win -// 3:-win -// 4:-1,lose -// 4:-2,lose -// 4:-2,lose -// 5:-1(-1)-3 win -// 5:-1(-2)-2 -// 5:-1(-3)-1 -// 6:-2 win -// 7: -3 win -// 8: lose - - - -// +4 win -// 6-2+4 win -// 7-3+4 win - - - - - diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal.js b/construct-binary-tree-from-preorder-and-inorder-traversal.js deleted file mode 100644 index 0f03ad3..0000000 --- a/construct-binary-tree-from-preorder-and-inorder-traversal.js +++ /dev/null @@ -1,48 +0,0 @@ -//https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ -// Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal -// Medimum -// Given preorder and inorder traversal of a tree, construct the binary tree. - -// Note: -// You may assume that duplicates do not exist in the tree. - -// For example, given - -// preorder = [3,9,20,15,7] -// inorder = [9,3,15,20,7] -// Return the following binary tree: - -// 3 -// / \ -// 9 20 -// / \ -// 15 7 - - -var buildTree = function(preorder, inorder) { - //edge case - if(!preorder || preorder.length < 1) { - return null - } - const rootVal = preorder[0] - const root = new TreeNode(rootVal) - - //exit condition - if(preorder.length === 1 ) { - return root - } - - const rootIndexInorder = inorder.indexOf(rootVal) - - const preorderLeft = preorder.slice(1,rootIndexInorder+1) - const preorderRight = preorder.slice(rootIndexInorder+1) - - const inorderLeft = inorder.slice(0,rootIndexInorder) - const inorderRight = inorder.slice(rootIndexInorder+1) - - root.left = buildTree(preorderLeft, inorderLeft) - root.right = buildTree(preorderRight, inorderRight) - - return root - -}; \ No newline at end of file diff --git a/count-sort.js b/count-sort.js deleted file mode 100644 index ea5a38f..0000000 --- a/count-sort.js +++ /dev/null @@ -1,21 +0,0 @@ -// take in an unsorted arr -// return a sorted arr -function countSort(arr) { - if(!Array.isArray(arr)) return [] - const counts = [] - const res = [] - // the index of counts is the value of the element to be sorted - arr.forEach((intEle)=>{ - counts[intEle] = counts[intEle] ? counts[intEle]+1 : 1 - }) - - counts.forEach((intEle, idx)=>{ - while(intEle !== undefined && intEle>0 ) { - res.push(idx) - intEle-- - } - }) - - return res; -} -module.exports = countSort; diff --git a/decodeQQId.js b/decodeQQId.js deleted file mode 100644 index 05b1280..0000000 --- a/decodeQQId.js +++ /dev/null @@ -1,35 +0,0 @@ -//A QQid is a string of numbers -//This challenge is to decode a QQid -//You are given a encoded QQid -//You will get the correct QQId by following the steps below -//1. Delete the first number, move the 2nd number to the end of the QQid -//2. Delete the 3rd number, move the 4th number to the end of the QQid -//3. Delete the 5th number, move the 6th number to the end of the QQid -//... -//keep doing so until there is no number left -//concat all the deleted numbers in deletion order -//the concated string is the decoded id - -function decodeQQId (encodedQQId) { - if (typeof (encodedQQId) !== 'string') { - return '' - } - let decodedQQId = ''; - let start = 0; - let end = encodedQQId.length; - - while (start < end) { - if (start % 2 === 0) { - decodedQQId += encodedQQId.charAt(start) - start++ - } else { - encodedQQId += encodedQQId.charAt(start) - start++ - end++ - } - } - - return decodedQQId -} - -module.exports = decodeQQId diff --git a/decodeQQId.test.js b/decodeQQId.test.js deleted file mode 100644 index 58154bc..0000000 --- a/decodeQQId.test.js +++ /dev/null @@ -1,6 +0,0 @@ -const decodeQQId = require('./decodeQQId.js'); - - -test(`decodeQQId`, () => { - expect(decodeQQId('631758924')).toEqual('615947283'); - }); diff --git a/findPrimeFactors.js b/findPrimeFactors.js deleted file mode 100644 index fe819ea..0000000 --- a/findPrimeFactors.js +++ /dev/null @@ -1,61 +0,0 @@ -// write a function to find all the prime factors of a number -// e.g -//8[2] -//6[2,3] -//9[3] - -// n is a postive interger -// n, n - - - -// O(n) -// function primeFactors(n){ -// var divisor=2; -// var result=[]; -// while(n>2){ -// if(n%divisor===0){ -// if(result.indexOf(divisor)==-1){ -// result.push(divisor) -// } -// n=n/divisor -// } -// else{ -// divisor++ -// } -// } -// return result -// } - - - -//O(n^2) -// function isNotPrime(Arr,n){ -// for(var j=0; j0;i--){ - if (a%i===0&&b%i===0){ - return i - } - - } -} - -// Euclidean algorithm -//辗转相除法 \ No newline at end of file diff --git a/happy-number.js b/happy-number.js deleted file mode 100644 index 2a9b894..0000000 --- a/happy-number.js +++ /dev/null @@ -1,44 +0,0 @@ -// 202. Happy Number -// Easy - -// Write an algorithm to determine if a number n is "happy". - -// A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. - -// Return True if n is a happy number, and False if not. - -// Example: - -// Input: 19 -// Output: true -// Explanation: -// 12 + 92 = 82 -// 82 + 22 = 68 -// 62 + 82 = 100 -// 12 + 02 + 02 = 1 - -/** - * @param {number} n - * @return {boolean} - */ -var isHappy = function(n) { - var res = [] - return helper(n, res) -}; - -function sumSquaresOfDigits (n) { - const digitsArr = n.toString().split("") - let sum = 0; - digitsArr.forEach((d)=>{ - sum += 1*d*d - }) - return sum -} - -function helper (n, res) { - const sum = sumSquaresOfDigits(n) - if(sum == 1) return true - if(res.indexOf(sum) > -1) return false - res.push(sum) - return helper(sum, res) -} \ No newline at end of file diff --git a/inorder-successor-in-BST.js b/inorder-successor-in-BST.js deleted file mode 100644 index bbc9194..0000000 --- a/inorder-successor-in-BST.js +++ /dev/null @@ -1,87 +0,0 @@ -// https://leetcode.com/problems/inorder-successor-in-bst/ - -// 285. Inorder Successor in BST -// Medium - -// Add to List - -// Share -// Given a binary search tree and a node in it, find the in-order successor of that node in the BST. - -// The successor of a node p is the node with the smallest key greater than p.val. - - - -// Example 1: - - -// Input: root = [2,1,3], p = 1 -// Output: 2 -// Explanation: 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type. -// Example 2: - - -// Input: root = [5,3,6,2,4,null,null,1], p = 6 -// Output: null -// Explanation: There is no in-order successor of the current node, so the answer is null. - - -// Note: - -// If the given node has no in-order successor in the tree, return null. -// It's guaranteed that the values of the tree are unique. - - -var inorderSuccessor = function(root, p) { - let allNodes = []; - dfs(root, allNodes) - console.log(allNodes) - for (let i = 0; i < allNodes.length; i++ ) { - if(allNodes[i] === p) { - return i === allNodes.length ? null : allNodes[i+1] - } - - } -}; - -function dfs (root, allNodes ) { - if (!root) { - return - } - dfs(root.left, allNodes) - allNodes.push(root) - dfs(root.right, allNodes) -} - -// 奇技淫巧 -// 强行退出dfs 遍历法 - -var inorderSuccessor = function(root, p) { - let allNodes = []; - try { - dfs(root, allNodes, p) - } - catch{ - } - return p === allNodes[allNodes.length-1] ? null : allNodes[allNodes.length-1] -}; - - -function dfs (root, allNodes, p) { - - if (!root) { - return - } - - dfs(root.left, allNodes, p) - - allNodes.push(root) - - if (allNodes[allNodes.length - 2] === p ) { - throw(err) - return - } - - dfs(root.right, allNodes, p) - -} \ No newline at end of file diff --git a/insert-into-a-binary-search-tree.js b/insert-into-a-binary-search-tree.js deleted file mode 100644 index 7f69ac7..0000000 --- a/insert-into-a-binary-search-tree.js +++ /dev/null @@ -1,75 +0,0 @@ -// 701. Insert into a Binary Search Tree -// Medium - -// Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. - -// Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them. - -// For example, - -// Given the tree: -// 4 -// / \ -// 2 7 -// / \ -// 1 3 -// And the value to insert: 5 -// You can return this binary search tree: - -// 4 -// / \ -// 2 7 -// / \ / -// 1 3 5 -// This tree is also valid: - -// 5 -// / \ -// 2 7 -// / \ -// 1 3 -// \ -// 4 - - -// Constraints: - -// The number of nodes in the given tree will be between 0 and 10^4. -// Each node will have a unique integer value from 0 to -10^8, inclusive. -// -10^8 <= val <= 10^8 -// It's guaranteed that val does not exist in the original BST. - - - -var insertIntoBST = function(root, val) { - if (!root) return new TreeNode(val) - const head = root; - - while (root) { - if (!root.left && !root.right) { - if (root.val < val) { - root.right = new TreeNode(val) - }else { - root.left = new TreeNode(val) - } - return head; - } - - - if (root.val < val) { - if(!root.right){ - root.right = new TreeNode(val); - return head - } - root = root.right - } else if (root.val > val) { - if(!root.left){ - root.left = new TreeNode(val); - return head - } - root = root.left - } - } - - return null; -}; diff --git a/insertionSort.js b/insertionSort.js deleted file mode 100644 index a0ddd76..0000000 --- a/insertionSort.js +++ /dev/null @@ -1,139 +0,0 @@ -//https://www.hackerrank.com/challenges/insertionsort1 - - -// From HackerRank - -// Problem Statement - -// Sorting -// One common task for computers is to sort data. For example, people might want to see all their files on a computer sorted by size. Since sorting is a simple problem with many different possible solutions, it is often used to introduce the study of algorithms. - -// Insertion Sort -// These challenges will cover Insertion Sort, a simple and intuitive sorting algorithm. We will first start with an already sorted list. - -// Insert element into sorted list -// Given a sorted list with an unsorted number e in the rightmost cell, can you write some simple code to insert e into the array so that it remains sorted? - -// Print the array every time a value is shifted in the array until the array is fully sorted. The goal of this challenge is to follow the correct order of insertion sort. - -// Guideline: You can copy the value of e to a variable and consider its cell "empty". Since this leaves an extra cell empty on the right, you can shift everything over until V can be inserted. This will create a duplicate of each value, but when you reach the right spot, you can replace it with e. - -// Input Format -// There will be two lines of input: - -// Size - the size of the array -// Arr - the unsorted array of integers -// Output Format -// On each line, output the entire array every time an item is shifted in it. - -// Constraints -// 1≤Size≤1000 -// −10000≤e≤10000,e∈Arr - -// Sample Input - -// 5 -// 2 4 6 8 3 -// Sample Output - -// 2 4 6 8 8 -// 2 4 6 6 8 -// 2 4 4 6 8 -// 2 3 4 6 8 -// Explanation - -// 3 is removed from the end of the array. -// In the 1st line 8>3, so 8 is shifted one cell to the right. -// In the 2nd line 6>3, so 6 is shifted one cell to the right. -// In the 3rd line 4>3, so 4 is shifted one cell to the right. -// In the 4th line 2<3, so 3 is placed at position 2. - -// Task - -// Complete the method insertionSort which takes in one parameter: - -// Arr - an array with the value e in the right-most cell. - - - - -// function processData1(input) { - //Enter your code here - var input = input.split("\n")[1].split(" "); - var toSort = input[input.length-1]; - for (var i=input.length-2; i>=0; i--){ - if (input[i]>toSort){ - input[i+1]=input[i]; - } - else{ - break; - } - console.log(input.join(" ")); - } - input[i+1]=toSort - console.log(input.join(" ")); -} - -// processData1("10\n2 3 4 5 6 7 8 9 12 11") - - - - - -// Problem Statement - -// In Insertion Sort Part 1, you sorted one element into an array. Using the same approach repeatedly, can you sort an entire unsorted array? - -// Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted array, one element at a time? Note that in the first step, when you consider an element with just the first element - that is already "sorted" since there's nothing to its left that is smaller. - -// In this challenge, don't print every time you move an element. Instead, print the array after each iteration of the insertion-sort, i.e., whenever the next element is placed at its correct position. - -// Since the array composed of just the first element is already "sorted", begin printing from the second element and on. - -// Input Format -// There will be two lines of input: - -// s - the size of the array -// ar - a list of numbers that makes up the array -// Output Format -// On each line, output the entire array at every iteration. - -// Constraints -// 1≤s≤1000 -// −10000≤x≤10000,x∈ar - -// Sample Input - -// 6 -// 1 4 3 5 6 2 -// Sample Output - -// 1 4 3 5 6 2 -// 1 3 4 5 6 2 -// 1 3 4 5 6 2 -// 1 3 4 5 6 2 -// 1 2 3 4 5 6 -// Explanation -// Insertion Sort checks 4 first and doesn't need to move it, so it just prints out the array. Next, 3 is inserted next to 1, and the array is printed out. This continues one element at a time until the entire array is sorted. - -// Task -// The method insertionSort takes in one parameter: ar, an unsorted array. Use an Insertion Sort Algorithm to sort the entire array. - - -function processData(input) { - //Enter your code here - var unsortedArr = input.split("\n")[1].split(" "); - for (var i = 1; i< unsortedArr.length; i++){ - var curEle = unsortedArr[i]; - for (var j = i-1; j>=0 ;j-- ){ - if (+unsortedArr[j]>+curEle){ - unsortedArr[j+1] = unsortedArr[j] - } - else{ - break; - } - } - unsortedArr[j+1]=curEle; - console.log(unsortedArr.join(" ")); - } -} diff --git a/lca.js b/lca.js deleted file mode 100644 index bb56cec..0000000 --- a/lca.js +++ /dev/null @@ -1,31 +0,0 @@ -// 236. Lowest Common Ancestor of a Binary Tree -// Medium - - -// Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. - -// According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” - -// Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4] - - - - -//https://www.youtube.com/watch?v=13m9ZCB8gjw - - -var lowestCommonAncestor = function(root, p, q) { - if (!root) return null; - if (root === p ) return root; - if (root === q) return root; - - const left = lowestCommonAncestor(root.left, p, q) - const right = lowestCommonAncestor(root.right, p, q) - - if(left && right) return root; - if(!left && !right) return null; - - if(left) return left - - return right -}; \ No newline at end of file diff --git a/merge-k-sorted-lists.js b/merge-k-sorted-lists.js deleted file mode 100644 index c43b074..0000000 --- a/merge-k-sorted-lists.js +++ /dev/null @@ -1,112 +0,0 @@ -// 23. Merge k Sorted Lists -// Hard - -// Add to List - -// Share -// Given an array of linked-lists lists, each linked list is sorted in ascending order. - -// Merge all the linked-lists into one sort linked-list and return it. - - - -// Example 1: - -// Input: lists = [[1,4,5],[1,3,4],[2,6]] -// Output: [1,1,2,3,4,4,5,6] -// Explanation: The linked-lists are: -// [ -// 1->4->5, -// 1->3->4, -// 2->6 -// ] -// merging them into one sorted list: -// 1->1->2->3->4->4->5->6 -// Example 2: - -// Input: lists = [] -// Output: [] -// Example 3: - -// Input: lists = [[]] -// Output: [] - -//brutal force method -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode[]} lists - * @return {ListNode} - */ -var mergeKLists = function(lists) { - const headOfLists = []; - let res = null; - let pointer = null; - - lists.forEach((listHead, idx)=>{ - headOfLists[idx] = listHead - }) - - // get through all the nodes - while (!checkAllNull(headOfLists)) { - const minIdx = getMinIdx(headOfLists); - - - // if not minIdx? - if (minIdx !== undefined) { - const curMinNode = new ListNode(headOfLists[minIdx].val) - //build new list - if (!res) { - res = curMinNode - pointer = res; - } else { - pointer.next = curMinNode; - pointer = pointer.next; - } - // move the header pointer - headOfLists[minIdx] = headOfLists[minIdx].next - } - - } - - return res; - -}; - -function checkAllNull (arr) { - let res = true; - for (let i = 0; i < arr.length; i++) { - // while element is not null or undefined - if(arr[i]) { - res = false; - break; - } - } - return res; -} - -function getMinIdx (arr) { - let minIdx; - for (let i = 0 ; i < arr.length; i++) { - const curNode = arr[i] - if(curNode) { - if (!minIdx) { - minIdx = [i] - } else if (curNode.val < arr[minIdx].val) { - minIdx = i - } - } - } - return minIdx; -} - - - -// K 路归并算法 K-way merge -// Priority Queue - diff --git a/merge-two-binary-trees.js b/merge-two-binary-trees.js deleted file mode 100644 index 9ff0c2b..0000000 --- a/merge-two-binary-trees.js +++ /dev/null @@ -1,48 +0,0 @@ -// https://leetcode.com/problems/merge-two-binary-trees/ -// 617. Merge Two Binary Trees -// Easy - -// Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. - -// You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. - -// Example 1: - -// Input: -// Tree 1 Tree 2 -// 1 2 -// / \ / \ -// 3 2 1 3 -// / \ \ -// 5 4 7 -// Output: -// Merged tree: -// 3 -// / \ -// 4 5 -// / \ \ -// 5 4 7 - -// https://leetcode.com/problems/merge-two-binary-trees/solution/ - -// Solution1 : recursion - - -var mergeTrees = function(t1, t2) { - - if (!t1 && !t2) {return null} - if (!t1) {return t2} - if (!t2) {return t1} - - const root = new TreeNode(t1.val + t2.val) //3 - - const left = mergeTrees(t1.left, t2.left) //4 - 5 null - - const right = mergeTrees(t1.right, t2.right) // - - root.left = left; - root.right = right; - - return root -}; - diff --git a/mergeTwoSortedArries.js b/mergeTwoSortedArries.js deleted file mode 100644 index 78f8b4b..0000000 --- a/mergeTwoSortedArries.js +++ /dev/null @@ -1,32 +0,0 @@ -//merge two sorted arries - -function mergeTwoSortedArrs(arr1, arr2) { - var resArr = []; - - var changingArr1 = arr1; - var changingArr2 = arr2; - - while (changingArr1.length>0&& changingArr2.length>0){ - if (changingArr1[0] <= changingArr2[0]) { - var elementToBePushed = changingArr1.shift(); - - } else { - elementToBePushed = changingArr2.shift(); - } - - resArr.push(elementToBePushed); - } - if (changingArr1.length>0){ - var remainingArr = changingArr1; - } - - if (changingArr2.length>0){ - remainingArr = changingArr2; - } - - resArr = resArr.concat(remainingArr); - return resArr - -} - -mergeTwoSortedArrs([1, 2, 4, 5, 6, 7, 8, 9],[3, 5, 7, 29,100]) diff --git a/nary-tree-preorder-traversal.js b/nary-tree-preorder-traversal.js deleted file mode 100644 index b0314b5..0000000 --- a/nary-tree-preorder-traversal.js +++ /dev/null @@ -1,49 +0,0 @@ -//https://leetcode.com/problems/n-ary-tree-preorder-traversal/ -// 589. N-ary Tree Preorder Traversal - -// Given an n-ary tree, return the preorder traversal of its nodes' values. - -// Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). - -// Follow up: - -// Recursive solution is trivial, could you do it iteratively? - -// Example 1: - -// Input: root = [1,null,3,2,4,null,5,6] -// Output: [1,3,5,6,2,4] -// Example 2: - -// Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] -// Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10] - -// Constraints: - -// The height of the n-ary tree is less than or equal to 1000 -// The total number of nodes is between [0, 10^4] -/** - * // Definition for a Node. - * function Node(val, children) { - * this.val = val; - * this.children = children; - * }; - */ - -/** - * @param {Node} root - * @return {number[]} - */ -var preorder = function(root) { - let res = [] - helper(root, res) - return res; -}; - -var helper = function (root, res) { - if(!root) return - res.push(root.val) - for(let i = 0; i < root.children.length; i++) { - helper(root.children[i], res) - } -} diff --git a/naryTreeLevelOrderTraversal.js b/naryTreeLevelOrderTraversal.js deleted file mode 100644 index 619123c..0000000 --- a/naryTreeLevelOrderTraversal.js +++ /dev/null @@ -1,57 +0,0 @@ -// https://leetcode.com/problems/n-ary-tree-level-order-traversal/ -// 429. N-ary Tree Level Order Traversal -// Medium - -// Given an n-ary tree, return the level order traversal of its nodes' values. - -// Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). - -// Example 1: - -// Input: root = [1,null,3,2,4,null,5,6] -// Output: [[1],[3,2,4],[5,6]] -// Example 2: - -// Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] -// Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]] - -// Constraints: - -// The height of the n-ary tree is less than or equal to 1000 -// The total number of nodes is between [0, 10^4] - -/** - * // Definition for a Node. - * function Node(val,children) { - * this.val = val; - * this.children = children; - * }; - */ - -/** - * @param {Node} root - * @return {number[][]} - */ -var levelOrder = function(root) { - if(!root) return [] - const res = [[root.val]] - const queue = []; - queue.push(root) - - while (queue.length > 0 ){ - const currentArr = []; - let numOfCurElements = queue.length - while (numOfCurElements > 0 ){ - const node = queue.shift() - - for (let i = 0; i < node.children.length; i++) { - queue.push(node.children[i]) - currentArr.push(node.children[i].val); - } - numOfCurElements-- - } - if (currentArr.length) {res.push(currentArr)} - } - - return res; -}; diff --git a/nthFibonacciNumber.js b/nthFibonacciNumber.js deleted file mode 100644 index e6c9430..0000000 --- a/nthFibonacciNumber.js +++ /dev/null @@ -1,148 +0,0 @@ -// find the nth fibonacci number - - - - -function fibNumber (n){ - - if (n>0 && n%1 === 0){ - - - var n1 = 1 - var n2 = 1 - - for(var i=2; i2){ - -// for(var i=2; i2){ - -// for(var i=2; i=0.10.0" } @@ -8252,8 +8238,7 @@ } }, "jest": { - "version": "26.2.1", - "resolved": "https://registry.npmjs.org/jest/-/jest-26.2.1.tgz", + "version": "https://registry.npmjs.org/jest/-/jest-26.2.1.tgz", "integrity": "sha512-0uQtQchWwE9xn6ScavTyKpdOqzaDByRhNpqWHVC/WPhikgXL7pkEEZLFFhMhiYcb7l9pdy9jm9wyHfBJYCf9xQ==", "dev": true, "requires": { diff --git a/package.json b/package.json index f67ef26..38cee58 100644 --- a/package.json +++ b/package.json @@ -1,22 +1,22 @@ { - "name": "algorithm_using_js", - "version": "1.0.0", - "description": "", - "main": "Day.1-1checkIsPrime.js", - "scripts": { - "test": "jest" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/injune1123/Algorithm_using_JS.git" - }, - "author": "", - "license": "ISC", - "bugs": { - "url": "https://github.com/injune1123/Algorithm_using_JS/issues" - }, - "homepage": "https://github.com/injune1123/Algorithm_using_JS#readme", - "devDependencies": { - "jest": "^26.2.1" - } -} + "name": "algorithm_using_js", + "version": "1.0.0", + "description": "", + "main": "Day.1-1checkIsPrime.js", + "scripts": { + "test": "jest" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/injune1123/Algorithm_using_JS.git" + }, + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/injune1123/Algorithm_using_JS/issues" + }, + "homepage": "https://github.com/injune1123/Algorithm_using_JS#readme", + "devDependencies": { + "jest": "^26.2.1" + } + } \ No newline at end of file diff --git a/populating-next-pointers-in-each-node.js b/populating-next-pointers-in-each-node.js deleted file mode 100644 index baef7c0..0000000 --- a/populating-next-pointers-in-each-node.js +++ /dev/null @@ -1,58 +0,0 @@ -//https://leetcode.com/problems/populating-next-right-pointers-in-each-node/ - -// 116. Populating Next Right Pointers in Each Node -// Medium - -// You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: - -// struct Node { -// int val; -// Node *left; -// Node *right; -// Node *next; -// } -// Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. - -// Initially, all next pointers are set to NULL. - -// - -/** - * // Definition for a Node. - * function Node(val, left, right, next) { - * this.val = val === undefined ? null : val; - * this.left = left === undefined ? null : left; - * this.right = right === undefined ? null : right; - * this.next = next === undefined ? null : next; - * }; - */ - -/** - * @param {Node} root - * @return {Node} - */ -var connect = function(root) { - if (!root) return null - let currentLevel = [root]; - let nextLevel = []; - - while (currentLevel.length > 0 ){ - let i = 0 - - while( i < currentLevel.length) { - - if (currentLevel[i+1]) { currentLevel[i].next = currentLevel[i+1] } - const curNode = currentLevel[i]; - i++ - - if (curNode.left) { nextLevel.push(curNode.left) } - if (curNode.right) { nextLevel.push(curNode.right) } - - } - - currentLevel = nextLevel; - nextLevel = [] - } - - return root -}; \ No newline at end of file diff --git a/quickSort.js b/quickSort.js deleted file mode 100644 index eec9830..0000000 --- a/quickSort.js +++ /dev/null @@ -1,67 +0,0 @@ -// find a pivot (the left most element) -// two sentinels (left, right) -// sentinels start to move toward each other -// left sentinel will look for number that is larger than pivot -// right sentinel will look for number is smaller than pivot -// right sentinel moves first towards the left, if sh/e meet a number, stop -// left sentinel moves now towards the right, if sh/e meet a number, stop -// if left sentinel finds a number and right sentinel also finds one -// swap -// when the left sentinel meets the right sentinel at indexX -// swap the pivot with the number at IndexX -// divide the problem into smaller ones: a left chunk and right chunk -// repeat the above action for the left half -// repeat the above action for the right half - -function helper(arr, left, right) { - if (left >= right) { - return; - } - - const pivot = arr[left] - const leftBoundary = left //pivot - const rightBoundary = right - - // right sentinel moves first towards the left - // if sh/e meet a number that is smaller than pivot, stop - while (left < right) { - while(left < right && arr[right] >= pivot ) { - right-- - } - // stops if left = right or arrCopy(right) <= pivot - while(left < right && arr[left] <= pivot) { - left++ - } - - if (left < right) { - swapEleInArr(arr, left, right) - } - } - - swapEleInArr(arr, leftBoundary, right) - - helper(arr, leftBoundary, left - 1) - helper(arr,left + 1, rightBoundary) -} - -function quickSort (arr) { - if(!Array.isArray(arr)) return [] - - const arrCopy = arr.slice() - - let leftIdx = 0; - let rightIdx = arrCopy.length -1; - - helper(arrCopy, leftIdx, rightIdx) - - return arrCopy -} - -//It's not a pure function -function swapEleInArr(arr, idxA, idxB){ - const temp = arr[idxA] - arr[idxA] = arr[idxB] - arr[idxB] = temp -} - -module.exports = quickSort; diff --git a/removeDuplicatesInArr.js b/removeDuplicatesInArr.js deleted file mode 100644 index a420509..0000000 --- a/removeDuplicatesInArr.js +++ /dev/null @@ -1,63 +0,0 @@ -//remove duplicates from an Array without using index of - -// this method is using objects like dictionaries. -function removeArrDuplicates (arr){ - var checkDuplicateObj = {}; - var resArr = []; - for(var i =0; i=0;i--){ - res+=str[i] - } - return res -} -} - -// recursion -// function reverseString (str){ - -// if (str.length===0){ -// return str -// } -// return reverseString(str.substring(1))+str.charAt(0) - -// } - -// Q2 add the function to the prototype of string - -// String.prototype.reverseString = function(){ - -// res = "" -// for (var i = this.length - 1; i >= 0; i--) { -// res += this[i] -// } -// return res - -// } - - -// "".reverseString() diff --git a/reverseEachWordInAPhrase.js b/reverseEachWordInAPhrase.js deleted file mode 100644 index cc69980..0000000 --- a/reverseEachWordInAPhrase.js +++ /dev/null @@ -1,53 +0,0 @@ -//From leetcode -//https://leetcode.com/problems/two-sum/ - -// reverse each word in a phrase - - -// The most awesome way of slving this problem! In one line!!! -function reverseWordsInPhrase (str){ - return str.split(" ").reverse().join(" ").split('').reverse().join(" "); - -} - -reverseWordsInPhrase("I am a good girl"); - -// function reverseWordsInPhrase(sentence){ -// resSentence=""; -// var wordsArr = sentence.split(" "); -// for (var i=0; i=0; j--){ -// resCurWord+=curWord[j]; -// } -// resSentence+=resCurWord+" " -// console.log(resSentence) -// } -// return resSentence.substring(0,sentence.length) -// } - - - - -// function reverseWordsInPhrase(sentence){ -// var wordsArr = sentence.split(" "); -// for (var i=0; i val) { - return searchBST(root.left, val) - } - - if(root.val < val) { - return searchBST(root.right, val) - } -}; \ No newline at end of file diff --git a/serializeAndDeserializeBinaryTree.js b/serializeAndDeserializeBinaryTree.js deleted file mode 100644 index 7fd8cb2..0000000 --- a/serializeAndDeserializeBinaryTree.js +++ /dev/null @@ -1,107 +0,0 @@ -//https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ -// 297. Serialize and Deserialize Binary Tree - -// Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. - -// Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. - -// Example: - -// You may serialize the following tree: - -// 1 -// / \ -// 2 3 -// / \ -// 4 5 - -// as "[1,2,3,null,null,4,5]" -// Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. - -// Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless. - - -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ - -/** - * Encodes a tree to a single string. - * - * @param {TreeNode} root - * @return {string} - */ -var serialize = function(root) { - let res = [] - if(!root) return "" - - let queue = [root] - while(queue.length) { - const curNode = queue.shift() - curNode ? res.push(curNode.val) : res.push("#") - if (curNode) { - curNode.left ? queue.push(curNode.left) : queue.push(null) - curNode.right ? queue.push(curNode.right) : queue.push(null) - } - } - return res.join() -}; - -/** -* Decodes your encoded data to tree. -* -* @param {string} data -* @return {TreeNode} -*/ - -/*1,2,3,#,#,4,5,#,#,#,# -*/ - -var deserialize = function(data) { - if(!data.length) return null - const valArr = data.split(","); - let parentNodeIdx = 0 - let childNodeIdx = 1 - const head = new TreeNode(valArr[0]) - const nodeQueue = [head] - let leftChild = true - - while(nodeQueue.length){ - - if (valArr[childNodeIdx] == "#") { - childNodeIdx++ - if(!leftChild) { - nodeQueue.shift() - } - leftChild = !leftChild - - continue; - } - const curChildNode = new TreeNode(valArr[childNodeIdx]) - - if(leftChild) { - nodeQueue[0].left = curChildNode - nodeQueue.push(curChildNode) - childNodeIdx++ - } else { - nodeQueue[0].right = curChildNode - nodeQueue.push(curChildNode) - childNodeIdx++ - } - //check whether - if(!leftChild) { - nodeQueue.shift() - } - leftChild = !leftChild - } - return head -}; - -/** -* Your functions will be called as such: -* deserialize(serialize(root)); -*/ diff --git a/sorting_algorithms.test.js b/sorting_algorithms.test.js deleted file mode 100644 index 788d582..0000000 --- a/sorting_algorithms.test.js +++ /dev/null @@ -1,19 +0,0 @@ -const countSort = require('./count-sort.js'); -const bubbleSort = require('./bubbleSort.js'); -const quickSort = require('./quickSort.js'); - -const runTest = (sortfuncs) => { - sortfuncs.forEach( - (sortfunc) => { - test(`${sortfunc.name}countSort: orders integers`, () => { - expect(sortfunc([5,3,5,2,8])).toEqual([2,3,5,5,8]); - expect(sortfunc([])).toEqual([]); - expect(sortfunc(null)).toEqual([]); - expect(sortfunc(1234)).toEqual([]); - }); - } - ) -} - -runTest([countSort, bubbleSort, quickSort]) - diff --git a/swapNumers.js b/swapNumers.js deleted file mode 100644 index 4036183..0000000 --- a/swapNumers.js +++ /dev/null @@ -1,37 +0,0 @@ -// write a function to swap two numbers, without using any temporarily varibale - -function swap (a,b) { - - console.log(a); - console.log(b); - -//your code goes here - - a=a-b; - b=a+b; - a=b-a; -// your code ends - console.log(b); - console.log(a); - -} - - - -function swap (a,b) { - - console.log("a="+a); - console.log("b="+b); - - a=a.toString()+"-"+b.toString() - b=+a.slice(a.indexOf("-")+1) - a=+a.slice(0,a.indexOf("-")) - - console.log("b="+b); - console.log("a="+a); - -} - - - - diff --git a/twoSum.js b/twoSum.js deleted file mode 100644 index 7bad2b0..0000000 --- a/twoSum.js +++ /dev/null @@ -1,45 +0,0 @@ -// Given an array of integers, find two numbers such that they add up to a specific target number. - -// The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. - -// You may assume that each input would have exactly one solution. - -// Input: numbers={2, 7, 11, 15}, target=9 -// Output: index1=1, index2=2 - - -// O(n) -var twoSum = function(nums, target) { - var map={}; - for (var i=0; i= upperLimit) return false; - - if (! helper(node.right, val, upperLimit)) return false; - if (! helper(node.left, lowerLimit, val)) return false; - return true; - -} diff --git a/wordLadder.js b/wordLadder.js deleted file mode 100644 index e084567..0000000 --- a/wordLadder.js +++ /dev/null @@ -1,84 +0,0 @@ -// 127. Word Ladder -// Medium -// Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: - -// Only one letter can be changed at a time. -// Each transformed word must exist in the word list. -// Note: - -// Return 0 if there is no such transformation sequence. -// All words have the same length. -// All words contain only lowercase alphabetic characters. -// You may assume no duplicates in the word list. -// You may assume beginWord and endWord are non-empty and are not the same. -// Example 1: - -// Input: -// beginWord = "hit", -// endWord = "cog", -// wordList = ["hot","dot","dog","lot","log","cog"] - -// Output: 5 - -// Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", -// return its length 5. -// Example 2: - -// Input: -// beginWord = "hit" -// endWord = "cog" -// wordList = ["hot","dot","dog","lot","log"] - -// Output: 0 - -// Explanation: The endWord "cog" is not in wordList, therefore no possible transformation. -/** - * @param {string} beginWord - * @param {string} endWord - * @param {string[]} wordList - * @return {number} - */ - -// use distance hash - -var ladderLength = function(beginWord, endWord, wordList) { - const queue = [beginWord] - const distance = {[beginWord]: 1} - - while(queue.length > 0) { - const curWord = queue.shift() - - if (curWord === endWord){ - return distance[curWord] - } - for ( let nextWord of getNextWords(curWord)) { - - - if( wordList.indexOf(nextWord) === -1 || distance.hasOwnProperty(nextWord)) { - continue; - } - - queue.push(nextWord) - - distance[nextWord] = distance[curWord] + 1 - } - } - - return 0 - -}; - - -function getNextWords (word) { - const words = []; - const engLetters = 'abcdefghijklmnopqrstuvwxyz' - for(let i = 0; i < word.length; i++) { - for(let j = 0; j < engLetters.length; j++) { - if(engLetters[j] === word[i]){ - continue; - } - words.push( word.slice(0,i) + engLetters[j] + word.slice(i+1)) - } - } - return words -} diff --git a/yarn.lock b/yarn.lock index e7e4030..d0aa5dd 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2172,15 +2172,6 @@ "merge-stream" "^2.0.0" "supports-color" "^7.0.0" -"jest@^26.2.1": - "integrity" "sha512-0uQtQchWwE9xn6ScavTyKpdOqzaDByRhNpqWHVC/WPhikgXL7pkEEZLFFhMhiYcb7l9pdy9jm9wyHfBJYCf9xQ==" - "resolved" "https://registry.npmjs.org/jest/-/jest-26.2.1.tgz" - "version" "26.2.1" - dependencies: - "@jest/core" "^26.2.1" - "import-local" "^3.0.2" - "jest-cli" "^26.2.1" - "js-tokens@^4.0.0": "integrity" "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" "resolved" "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz"