├── DataStructures ├── LRUCache │ └── LRUCache.js ├── LinkedLists │ ├── MinStack.js │ ├── HasCycle.js │ ├── Dequeue.js │ ├── DynamicArray.js │ ├── Stack.js │ ├── ReverseLinkedListRecursive.js │ ├── AddTwoNums.js │ ├── Intersection.js │ └── Queue.js ├── Graphs │ ├── Vertex.js │ ├── Graph.js │ ├── GraphDFSIterative.js │ ├── GraphIsTree.js │ ├── StringChain2.js │ ├── StringChain.js │ ├── SocialNetwork.js │ └── WordLadderB.js ├── BinaryTrees │ ├── BSTNode.js │ ├── LongestPath.js │ ├── BinaryTree.js │ ├── BinaryTreePaths.js │ ├── PureRecursionTrees.js │ ├── IsBST.js │ ├── MergeBinaryTrees.js │ ├── MergeBinaryTrees.java │ ├── TreeExpression.js │ └── TreeEach.js ├── Tries │ ├── TrieNode.js │ ├── DictAsTrie.js │ ├── Scrabble.js │ └── Trie.js ├── QuadTrees │ ├── Point.js │ └── QuadTree.js ├── Heaps │ └── FibonacciHeap.js ├── UnionFind │ ├── QuickUnion.js │ ├── QuickFind.js │ └── WeightedQuickUnion.js ├── N-aryTrees │ └── Copy.js └── HashTables │ └── HashTable.js ├── .gitignore ├── Other ├── Archive │ ├── OOPArchive │ │ ├── ParkingLot.js │ │ ├── Elevator │ │ │ ├── ListNode.js │ │ │ ├── Button.js │ │ │ ├── ElevatorButton.js │ │ │ ├── FloorButton.js │ │ │ ├── Person.js │ │ │ ├── Queue.js │ │ │ ├── Script.md │ │ │ └── Floor.js │ │ ├── Date.js │ │ ├── new.js │ │ ├── prototype.js │ │ └── Dates.js │ ├── SortColors │ │ ├── sortColors.py │ │ └── sortColors.java │ ├── PowerSet.py │ ├── staticNeuralNetwork │ │ ├── referenceTest.js │ │ └── staticNeuralNetwork.js │ ├── Combinations.java │ └── graph.swift ├── InterviewQuestions │ ├── SQL_Toptal.md │ ├── Javascript_Toptal.md │ ├── InformationalInterviewQuestions.md │ └── JobListings.md ├── ComputationalFinance │ └── Event Study │ │ ├── MyEventStudy.pdf │ │ └── eventStudy.py ├── RegEx │ ├── RegExGolf.txt │ └── PatternMatching.js ├── MachineLearning │ └── GoogleTutorial │ │ ├── hello_world.py │ │ ├── dogs.py │ │ ├── pipeline.py │ │ ├── iris.py │ │ └── classifier.py ├── Frontend │ ├── jQDOM.js │ └── xss.html ├── FunctionalProgramming │ ├── abstraction.js │ ├── asyncMap.js │ ├── ForEach.js │ ├── functionBind.js │ └── StarWars.js └── assets │ ├── clean.js │ ├── git-author-rewrite.sh │ └── builder.js ├── AlgorithmProblems ├── Math │ ├── DigitSum.js │ ├── IsPrime.js │ ├── IsPowerOfTwo.js │ ├── Compress.js │ ├── SquareAreas.js │ ├── PoisonPigs.js │ ├── TrailingZeros.js │ ├── SumMultiples.js │ ├── ToBinary.js │ ├── Base7.js │ ├── ReverseInt.js │ ├── Random7.js │ ├── FindPrime.js │ ├── SumSquareDifference.js │ ├── SumPrimes.js │ ├── Triangular.js │ ├── ClosestSteakhouses.js │ ├── Power.js │ ├── LimitingReagent.js │ ├── LargestPrimeFactor.js │ ├── AddLarge.js │ └── LogicalOperators.js ├── Matrices │ ├── Inverse.js │ ├── Scale.js │ ├── DiagonalDifference.js │ ├── Transpose.js │ ├── RectangleIslands.js │ ├── RatPath2.js │ ├── ToeplitzMatrix.js │ ├── RatPath.js │ ├── BooleanMatrix.js │ ├── NumberIslands.js │ ├── NumberIslands2.js │ ├── SpiralMatrix.js │ ├── LargestIslands.js │ ├── RatPathGeneral.js │ ├── Multiply.js │ └── IsValidSudoku.js ├── Arrays │ ├── Swap.js │ ├── Unique.js │ ├── MedianTwoSortedArrays.js │ ├── ObjShallowEqual.js │ ├── MergeKSortedNaive.js │ ├── ReverseChunks.js │ ├── MoveZeroes.js │ ├── PlusOne.js │ ├── SubArraySum.js │ ├── AllProducts.js │ ├── TwoSumPairs.js │ ├── PlusMult.js │ ├── SortedBitArraySearch.js │ ├── SortedTwoSum.js │ ├── Arbitrage.js │ ├── SubArraySumK.js │ ├── MergeIntervals2.js │ ├── NthSmallestMissing.js │ ├── BinarySearch.js │ ├── ThreeSum.js │ ├── PermuteArray.js │ ├── TwoSum.js │ ├── GroupAnagrams.js │ ├── GroupAnagramsNaive.js │ ├── NumberOfOnes.js │ ├── ShortestSequenceContainingSet.js │ ├── ShortestSubArray.js │ ├── MergeArraysOrdered.js │ └── MaxPopulation.js ├── DynamicProgramming │ ├── LongestPalindromicSubsequence.js │ ├── MaxProfit.js │ ├── HouseRobber.js │ ├── NumWaysCoinChange.js │ ├── LatticePathsDP.js │ ├── McNugget.js │ ├── Jump.js │ ├── LargestPrimeFactorMemo.js │ ├── KnapSack.js │ ├── NumWays.js │ ├── ReverseCoinChange.js │ ├── LargestRectangleHistogramII.js │ ├── LongestNonRepeatingSubstringEfficient.js │ ├── LargestRectangleHistogramI.js │ ├── RainWater.js │ ├── LongestNonRepeatingSubstring.js │ ├── FlipZeros.js │ ├── Steps.js │ ├── MinimumWindowSubstringWithRepeats.js │ ├── HouseRobber2.js │ └── SlidingWindowMaximum.js ├── Recursion │ ├── TowerOfHanoi.js │ ├── PowerSetUnique.js │ ├── NonConsecutiveOnes.js │ ├── RockPaperScissors.js │ ├── FlattenArray.js │ ├── BitCombinations.js │ ├── FlattenObject.js │ ├── KnapSackNaive.js │ ├── ParensPermutations.js │ ├── Telephone.js │ ├── CoinChange.js │ ├── Permutations.js │ ├── URLTree.js │ ├── CapitalPermutations.js │ └── Combinations.js ├── Sorting │ ├── InsertionSort.js │ ├── BubbleSort.js │ ├── AnagramGroups.js │ ├── SortColors.js │ ├── SelectionSort.js │ ├── SortByDecimal.js │ ├── CountingSort.js │ ├── BitArraySort.js │ ├── SortDigits.js │ ├── Quickselect.js │ └── Heapsort.js └── Strings │ ├── Convert.js │ ├── LongestCommonPrefix.js │ ├── CompressString.js │ ├── StringPermutations.js │ ├── NonrepeatingSubstring.js │ ├── LongestPalindromeSubsequence.js │ ├── LongestPalindrome.js │ ├── AnagramPalindrome.js │ ├── ReverseVowels.js │ ├── AllAnagrams.js │ ├── PowerDigitSum.js │ ├── CompareStringsConstantSpace.js │ ├── FindAnagrams.js │ ├── PigLatin.js │ └── ParseExpression.js ├── .jshintrc ├── package.json ├── OOP ├── Cards.js └── Drone.js └── README.md /DataStructures/LRUCache/LRUCache.js: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | package-lock.json 4 | -------------------------------------------------------------------------------- /Other/Archive/OOPArchive/ParkingLot.js: -------------------------------------------------------------------------------- 1 | function ParkingLot() { 2 | 3 | } 4 | -------------------------------------------------------------------------------- /DataStructures/LinkedLists/MinStack.js: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | this.storage = []; 3 | } 4 | -------------------------------------------------------------------------------- /Other/InterviewQuestions/SQL_Toptal.md: -------------------------------------------------------------------------------- 1 | # 44 Essential SQL Questions 2 | 3 | Source: [Toptal](https://www.toptal.com/java/interview-questions) 4 | -------------------------------------------------------------------------------- /Other/ComputationalFinance/Event Study/MyEventStudy.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spiterman/ToyProblems/HEAD/Other/ComputationalFinance/Event Study/MyEventStudy.pdf -------------------------------------------------------------------------------- /DataStructures/Graphs/Vertex.js: -------------------------------------------------------------------------------- 1 | class Vertex { 2 | constructor(value) { 3 | this.value = value; 4 | this.edges = {}; 5 | } 6 | } 7 | 8 | module.exports = Vertex; 9 | -------------------------------------------------------------------------------- /DataStructures/BinaryTrees/BSTNode.js: -------------------------------------------------------------------------------- 1 | function bstNode(value) { 2 | this.value = value; 3 | this.left = null; 4 | this.right = null; 5 | } 6 | 7 | module.exports = bstNode; 8 | -------------------------------------------------------------------------------- /Other/InterviewQuestions/Javascript_Toptal.md: -------------------------------------------------------------------------------- 1 | # 36 Essential JavaScript Interview Questions 2 | 3 | Source: 4 | [Toptal] (https://www.toptal.com/javascript/interview-questions) 5 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/DigitSum.js: -------------------------------------------------------------------------------- 1 | //Digit Sum 2 | //Add the digits in a number 3 | 4 | function digitSum (n) { 5 | return String(n) 6 | .split('') 7 | .reduce((x, y) => Number(x) + Number(y)); 8 | } 9 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/IsPrime.js: -------------------------------------------------------------------------------- 1 | function isPrime(num){ 2 | var limit = Math.sqrt(num) 3 | 4 | for(var i = 2; i <= limit; i++){ 5 | if(num % i === 0) return false 6 | } 7 | 8 | return true; 9 | } 10 | -------------------------------------------------------------------------------- /DataStructures/Tries/TrieNode.js: -------------------------------------------------------------------------------- 1 | class TrieNode { 2 | constructor(char) { 3 | this.children = {}; 4 | this.char = char; 5 | this.isWord = false; 6 | } 7 | } 8 | 9 | module.exports = TrieNode; 10 | -------------------------------------------------------------------------------- /Other/RegEx/RegExGolf.txt: -------------------------------------------------------------------------------- 1 | Regex Golf 2 | 3 | Warmup 4 | foo 5 | 6 | Anchors 7 | k$ 8 | 9 | Ranges 10 | ^[a-f].[^g-z][^m] 11 | 12 | 13 | Backrefs 14 | (\w{3}).*\1 15 | 16 | Abba 17 | ^(?!.*(.)(.)\2\1) 18 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/IsPowerOfTwo.js: -------------------------------------------------------------------------------- 1 | var isPowerOfTwo = function(n) { 2 | if(n === 1) {return true} 3 | if(n % 2 === 1 || n === 0) {return false} 4 | return isPowerOfTwo(n/2) 5 | }; 6 | 7 | module.exports = isPowerOfTwo; 8 | -------------------------------------------------------------------------------- /Other/Archive/OOPArchive/Elevator/ListNode.js: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | constructor(floorNumber) { 3 | this.floorNumber = floorNumber; 4 | this.next = null; 5 | this.prev = null; 6 | } 7 | } 8 | 9 | module.exports = ListNode; 10 | -------------------------------------------------------------------------------- /DataStructures/QuadTrees/Point.js: -------------------------------------------------------------------------------- 1 | class Point { 2 | constructor(x, y, name, radius) { 3 | this.x = x; 4 | this.y = y; 5 | this.name = name || ""; 6 | this.radius = radius|| 3; 7 | } 8 | } 9 | 10 | module.exports = Point; 11 | -------------------------------------------------------------------------------- /Other/MachineLearning/GoogleTutorial/hello_world.py: -------------------------------------------------------------------------------- 1 | from sklearn import tree 2 | 3 | veatures = [[140, 1], [130, 1], [150, 0], [170, 0]] 4 | labels = [0, 0, 1, 1] 5 | clf = tree.DecisionTreeClassifier() 6 | clf = clf.fit(features, labels 7 | 8 | print clf.predict([[160, 0]]) 9 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/Compress.js: -------------------------------------------------------------------------------- 1 | function compress(s) { 2 | if(!s) return ""; 3 | var result = s[0]; 4 | for(var i = 1; i < s.length; i++){ 5 | if(s[i] !== s[i - 1]){ 6 | result += s[i] 7 | } 8 | } 9 | return result; 10 | } 11 | -------------------------------------------------------------------------------- /Other/Archive/OOPArchive/Elevator/Button.js: -------------------------------------------------------------------------------- 1 | class Button { 2 | constructor() { 3 | this.isLit = false; 4 | } 5 | turnOnLight(){ 6 | this.isLit = true; 7 | } 8 | turnOffLight(){ 9 | this.isLit = false; 10 | } 11 | } 12 | 13 | module.exports = Button; 14 | -------------------------------------------------------------------------------- /DataStructures/Tries/DictAsTrie.js: -------------------------------------------------------------------------------- 1 | const Trie = require("./Trie"); 2 | const fs = require("fs"); 3 | 4 | const dictionary = fs.readFileSync("./dictionary.txt").toString().split("\n"); 5 | 6 | let trie = new Trie(); 7 | trie.addWords(dictionary); 8 | 9 | module.exports = trie; 10 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/Inverse.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an NxN matrix return its inverse. 3 | That is, return the matrix which when multiplied 4 | by the input returns the identity matrix. 5 | 6 | Example: 7 | 8 | Input: 9 | [[1, 2], 10 | [4, 5]] 11 | 12 | Output: 13 | [[1, 4], 14 | [2, 5]] 15 | */ 16 | -------------------------------------------------------------------------------- /DataStructures/Graphs/Graph.js: -------------------------------------------------------------------------------- 1 | const Vertex = require('./DataStructures/Graphs/Vertex'); 2 | 3 | class Graph { 4 | constructor() { 5 | this.vertices = {}; 6 | } 7 | 8 | addVertex(value) { 9 | this.vertices[value] = new Vertex(value); 10 | } 11 | } 12 | 13 | module.exports = Graph; 14 | -------------------------------------------------------------------------------- /DataStructures/Heaps/FibonacciHeap.js: -------------------------------------------------------------------------------- 1 | class FibHeapNode { 2 | constructor(key) { 3 | this.key = key; 4 | this.isLoser = false; 5 | this.parentNode = null; 6 | this.rightSibling = null; 7 | this.leftSibling = null; 8 | this.child = null; 9 | this.degree = 0; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/SquareAreas.js: -------------------------------------------------------------------------------- 1 | function squareAreas(area) { 2 | let result = []; 3 | 4 | while(area > 0) { 5 | let square = Math.floor(Math.sqrt(area)); 6 | area -= square * square; 7 | result.push(square * square); 8 | } 9 | return result; 10 | } 11 | 12 | console.log(squareAreas(194)); 13 | -------------------------------------------------------------------------------- /Other/Frontend/jQDOM.js: -------------------------------------------------------------------------------- 1 | function $(domElement){ 2 | // console.log(Array.prototype.slice.call(arguments)); 3 | 4 | var html = document.getElementsByClassName(domElement); 5 | return html; 6 | } 7 | 8 | $.prototype.onClick = function(cb){ 9 | cb(); 10 | }; 11 | 12 | console.log($('test')); 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/Swap.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that swaps two elements in an array 3 | */ 4 | 5 | function Swap(arr, i, j){ 6 | // ES5 7 | // var temp = arr[i]; 8 | // arr[i] = arr[j]; 9 | // arr[j] = temp; 10 | 11 | // ES6 12 | [arr[i], arr[j]] = [arr[j], arr[i]]; 13 | } 14 | 15 | module.exports = Swap 16 | -------------------------------------------------------------------------------- /Other/MachineLearning/GoogleTutorial/dogs.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | greyhouds = 500 4 | labs = 500 5 | 6 | grey_height = 28 + 4 * np.random.randn(greyhouds) 7 | lab_height = 24 + 4 * np.random.randn(labs) 8 | 9 | plt.hist([grey_height, lab_height], stacked=True, color=['r', 'b']) 10 | plt.show() 11 | -------------------------------------------------------------------------------- /Other/Archive/SortColors/sortColors.py: -------------------------------------------------------------------------------- 1 | def sortColors(arr): 2 | result = [] 3 | count = [0, 0, 0] 4 | 5 | for i in arr: 6 | count[i] += 1 7 | 8 | for index, val in enumerate(count): 9 | while val > 0: 10 | result.append(index) 11 | val -= 1 12 | 13 | return result 14 | 15 | print sortColors([1, 2, 0, 2, 0]) 16 | -------------------------------------------------------------------------------- /Other/Archive/OOPArchive/Elevator/ElevatorButton.js: -------------------------------------------------------------------------------- 1 | const Button = require("./Button"); 2 | 3 | class ElevatorButton extends Button { 4 | constructor(floorNumber) { 5 | super(); 6 | this.floorNumber = floorNumber; 7 | } 8 | getFloorNumber(){ 9 | return this.FloorNumber; 10 | } 11 | } 12 | 13 | module.exports = ElevatorButton; 14 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/LongestPalindromicSubsequence.js: -------------------------------------------------------------------------------- 1 | function longestPalindromicSequence(str) { 2 | let strArr = []; 3 | 4 | for(let i = 0; i < str.length; i++) { 5 | strArr.push("|"); 6 | strArr.push(str[i]); 7 | } 8 | strArr.push("|") 9 | 10 | console.log(strArr) 11 | } 12 | 13 | longestPalindromicSequence("hello world") 14 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/Unique.js: -------------------------------------------------------------------------------- 1 | function unique(arr) { 2 | let set = {}; 3 | let result = []; 4 | 5 | arr.forEach((item) => { 6 | set[item] = true; 7 | }); 8 | for(let key in set) { 9 | result.push(Number(key)); 10 | } 11 | return result; 12 | } 13 | 14 | console.log(unique([1, 2, 3, 4, 4, 3, 2, 1])); 15 | 16 | module.exports = unique; 17 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/MaxProfit.js: -------------------------------------------------------------------------------- 1 | function maxProfit(prices) { 2 | let maxProfit = 0; 3 | let minPrice = Infinity; 4 | 5 | prices.forEach((price) => { 6 | minPrice = Math.min(price, minPrice); 7 | maxProfit = Math.max(price - minPrice, maxProfit); 8 | }) 9 | return maxProfit; 10 | } 11 | 12 | console.log(maxProfit([7, 1, 5, 3, 6, 4])) 13 | -------------------------------------------------------------------------------- /Other/Archive/OOPArchive/Elevator/FloorButton.js: -------------------------------------------------------------------------------- 1 | const Button = require("./Button"); 2 | 3 | class FloorButton extends Button { 4 | constructor(direction, elevatorController) { 5 | super(); 6 | this.direction; 7 | this.elevatorController; 8 | } 9 | getDirection(){ 10 | return this.direction; 11 | } 12 | } 13 | 14 | module.exports = FloorButton; 15 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/PoisonPigs.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | function poisonPigs(buckets, minutesToDie, minutesToTest) { 4 | let testInterval = minutesToTest / minutesToDie + 1; 5 | let numberOfPigs = 0; 6 | while(Math.pow(testInterval, numberOfPigs) < buckets) { 7 | numberOfPigs++; 8 | } 9 | 10 | return numberOfPigs; 11 | } 12 | 13 | 14 | module.exports = poisonPigs; 15 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/TowerOfHanoi.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that returns the minimum number of moves it takes to solve the tower of Hanoi. 3 | Examples: 4 | Hanoi(1) => 1 5 | Hanoi(2) => 3 6 | Hanoi(3) => 7 7 | Hanoi(4) = 15 8 | */ 9 | 10 | const Hanoi = (discs) => discs === 0? 0 : 2 * Hanoi(discs - 1) + 1 11 | 12 | // Test 13 | // console.log(Hanoi(4)) 14 | 15 | module.exports = Hanoi; 16 | -------------------------------------------------------------------------------- /AlgorithmProblems/Sorting/InsertionSort.js: -------------------------------------------------------------------------------- 1 | function insertionSort(arr) { 2 | for(let i = 0; i < arr.length; i++) { 3 | let j = i; 4 | while(j >= 0 && arr[j-1] > arr[j]) { 5 | [arr[j], arr[j-1]] = [arr[j-1], arr[j]]; 6 | j--; 7 | } 8 | } 9 | return arr; 10 | } 11 | 12 | // console.log(insertionSort([3, 2, 1, 6, 4, 8, 10, 39, 28, 57, 25])); 13 | 14 | module.exports = insertionSort; 15 | -------------------------------------------------------------------------------- /AlgorithmProblems/Sorting/BubbleSort.js: -------------------------------------------------------------------------------- 1 | function bubbleSort(arr) { 2 | for(let i = arr.length; i > 0; i--) { 3 | for (let j = 0; j < i - 1; j++) { 4 | if(arr[j] > arr[j+1]) { 5 | [arr[j], arr[j+1]] = [arr[j+1], arr[j]]; 6 | } 7 | } 8 | } 9 | return arr; 10 | } 11 | 12 | 13 | // console.log(bubbleSort([3, 2, 1, 6, 4, 8, 10, 39, 28, 57, 25])); 14 | 15 | module.exports = bubbleSort; 16 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/PowerSetUnique.js: -------------------------------------------------------------------------------- 1 | function powerSetUnique(str) { 2 | let subSets = new Set(); 3 | 4 | function createSubSet(substr, depth) { 5 | if(depth === str.length) { 6 | subSets.add(substr); 7 | return; 8 | } 9 | createSubSet(substr + str[depth], depth + 1) 10 | createSubSet(substr, depth + 1) 11 | } 12 | 13 | createSubSet("", 0); 14 | return subSets; 15 | } 16 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/MedianTwoSortedArrays.js: -------------------------------------------------------------------------------- 1 | function medianTwoSorted(arr1, arr2) { 2 | let i = 0; 3 | let j = 0; 4 | 5 | while(i + j < arr1.length) { 6 | if(arr1[i] < arr2[j]) { 7 | i++; 8 | } else { 9 | j++; 10 | } 11 | } 12 | return i > j ? (arr1[i - 1] + arr2[j])/2 : (arr1[i] + arr2[j - 1])/2 13 | } 14 | 15 | console.log(medianTwoSorted([1, 12, 17, 26, 38, 70], [2, 13, 15, 30, 45, 60])) 16 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/Scale.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that takes in a constant and a matrix 3 | and scales every element in that matrix by that constant 4 | */ 5 | 6 | function Scale(constant, matrix){ 7 | for(var i = 0; i< matrix.length; i++){ 8 | for(var j = 0; j= len(input)): 5 | return 6 | 7 | letter = input[index] 8 | temp = [] 9 | 10 | for i in helper.superSet: 11 | temp.append(i) 12 | temp.append(i + letter) 13 | 14 | helper.superSet = temp 15 | helper(index + 1) 16 | 17 | helper.superSet = [""] 18 | helper(0) 19 | 20 | return helper.superSet 21 | -------------------------------------------------------------------------------- /AlgorithmProblems/Sorting/SortColors.js: -------------------------------------------------------------------------------- 1 | function sortColors(arr){ 2 | var result = []; 3 | var count = [0, 0, 0]; 4 | 5 | for(var i = 0; i < arr.length; i++){ 6 | count[arr[i]] += 1; 7 | } 8 | 9 | for(var j = 0; j < count.length; j++){ 10 | while(count[j] > 0){ 11 | result.push(j) 12 | count[j] -= 1; 13 | } 14 | } 15 | return result; 16 | } 17 | 18 | console.log(sortColors([0, 1, 1, 2, 0, 2, 1, 0])); 19 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/TrailingZeros.js: -------------------------------------------------------------------------------- 1 | var trailingZeroes = function(num) { 2 | let result = 0; 3 | let power = 1; 4 | 5 | while(Math.floor(num / Math.pow(5, power)) > 0) { 6 | result += Math.floor(num / Math.pow(5, power)); 7 | power++ 8 | } 9 | return result; 10 | }; 11 | 12 | // Given a number, figure out how many trailing zeroes the factorial of that number will have 13 | // http://www.purplemath.com/modules/factzero.htm 14 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/Convert.js: -------------------------------------------------------------------------------- 1 | function convert(str) { 2 | // YOUR WORK HERE 3 | let counts = {} 4 | for(let i = 0; i < str.length; i++){ 5 | counts[str[i]] ? counts[str[i]] += 1 : counts[str[i]] = 1; 6 | } 7 | let result = "" 8 | for(let key in counts) { 9 | result += counts[key] + key 10 | } 11 | return result; 12 | } 13 | 14 | // Tests 15 | // console.log(convert("banana")) 16 | 17 | module.exports = convert; 18 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/HouseRobber.js: -------------------------------------------------------------------------------- 1 | function houseRobber(arr) { 2 | let minusTwoMax = arr[0] 3 | let minusOneMax = arr[1]; 4 | 5 | let max; 6 | 7 | for(let i = 2; i < arr.length; i++) { 8 | max = Math.max(minusTwoMax + arr[i], minusOneMax); 9 | minusTwoMax = minusOneMax; 10 | minusOneMax = max; 11 | } 12 | 13 | return max; 14 | } 15 | 16 | 17 | console.log(houseRobber([1, 2, 4, 1, 5, 12, 5, 1])); 18 | -------------------------------------------------------------------------------- /Other/Archive/OOPArchive/Date.js: -------------------------------------------------------------------------------- 1 | function newDate(month, day, year){ 2 | this.month = month; 3 | this.day = day; 4 | this.year = year; 5 | }; 6 | 7 | var d1 = new newDate(08, 14, 1991); 8 | var d2 = new newDate(10, 13, 2016); 9 | 10 | function difference(d1, d2){ 11 | var years = d2.year - d1.year; 12 | var day = d2.day - d1.day; 13 | var month = d2.month - d1.month; 14 | 15 | return years; 16 | }; 17 | 18 | console.log(difference(d1, d2)); 19 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/SumMultiples.js: -------------------------------------------------------------------------------- 1 | // Sum Multiples 2 | // Sums all numbers that are divisible by 3 and 5 3 | 4 | var sumMultiples = function(n){ 5 | var result = []; 6 | var i = 0; 7 | 8 | while(i < n){ 9 | if(i % 3 === 0 || i % 5 === 0){ 10 | result.push(i); 11 | } 12 | i++ 13 | } 14 | 15 | return result.reduce(function(prev, curr){ 16 | return prev + curr 17 | }) 18 | 19 | } 20 | 21 | console.log(sumMultiples(1000)) 22 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/NumWaysCoinChange.js: -------------------------------------------------------------------------------- 1 | function numWaysCoinChange(coins, target) { 2 | let result = new Array(target + 1).fill(0); 3 | result[0] = 1; 4 | coins.forEach((coin, index) => { 5 | for(let i = 1; i < result.length; i++ ){ 6 | if(i - coin >= 0) { 7 | result[i] = result[i] + result[i - coin]; 8 | } 9 | } 10 | }) 11 | return result[target]; 12 | } 13 | 14 | console.log(numWaysCoinChange([1, 2, 3], 10)); 15 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/NonConsecutiveOnes.js: -------------------------------------------------------------------------------- 1 | function NonConsecutiveOnes(n) { 2 | let result = []; 3 | 4 | function recurse(substr) { 5 | if(substr.length === n) { 6 | result.push(substr); 7 | return; 8 | } 9 | recurse(substr + 0); 10 | if(substr[substr.length - 1] !== "1") { 11 | recurse(substr + 1) 12 | } 13 | } 14 | 15 | recurse(""); 16 | return result; 17 | } 18 | 19 | 20 | console.log(NonConsecutiveOnes(4)); 21 | -------------------------------------------------------------------------------- /AlgorithmProblems/Sorting/SelectionSort.js: -------------------------------------------------------------------------------- 1 | function selectionSort(arr) { 2 | 3 | for(let i = 0; i < arr.length; i++) { 4 | let min = i; 5 | for(let j = i; j < arr.length; j++) { 6 | if(arr[j] < arr[min]) { 7 | min = j; 8 | } 9 | } 10 | [arr[min], arr[i]] = [arr[i], arr[min]]; 11 | } 12 | return arr; 13 | } 14 | 15 | console.log(selectionSort([3, 2, 1, 6, 4, 8, 10, 39, 28, 57, 25])); 16 | 17 | module.exports = selectionSort; 18 | -------------------------------------------------------------------------------- /Other/Archive/SortColors/sortColors.java: -------------------------------------------------------------------------------- 1 | class Main 2 | { 3 | public static void main (){ 4 | System.out.println(SortColors.compute([0, 1, 1, 2, 0, 2, 1, 0])); 5 | } 6 | } 7 | 8 | class SortColors 9 | { 10 | private static int[] count = [0, 0, 0]; 11 | 12 | 13 | public static int [] compute(int [] arr){ 14 | 15 | for(int i = 0; i < arr.length; i = i + 1) { 16 | count[arr[i]] += 1; 17 | } 18 | 19 | return count 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/ObjShallowEqual.js: -------------------------------------------------------------------------------- 1 | function objShallowEqual(obj1, obj2) { 2 | if(Object.keys(obj1).length !== Object.keys(obj2).length ) { 3 | return false; 4 | } 5 | for(let k in obj1) { 6 | if(!(k in obj2) || obj1[k] !== obj2[k]) { 7 | return false 8 | } 9 | } 10 | return true; 11 | } 12 | 13 | // let a = {a: 1, b: 3} 14 | // let b = {a: 1, b: 2} 15 | 16 | 17 | // console.log(objShallowEqual(a, b)) 18 | 19 | 20 | module.exports = objShallowEqual; 21 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/LatticePathsDP.js: -------------------------------------------------------------------------------- 1 | function latticePaths(width, height) { 2 | let memo = {'0.0':1} 3 | function helper(x, y) { 4 | if(x < 0 || y < 0){ 5 | return 0; 6 | } 7 | if((`${x}.${y}` in memo)){ 8 | return memo[`${x}.${y}`]; 9 | } 10 | let newCell = helper(x - 1, y) + helper(x, y - 1) 11 | memo[`${x}.${y}`] = newCell; 12 | return newCell; 13 | } 14 | return helper(width, height); 15 | } 16 | 17 | latticePaths(3, 4) 18 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/ToBinary.js: -------------------------------------------------------------------------------- 1 | function toBinary(int) { 2 | let exponent = 0; 3 | let result = ''; 4 | 5 | while (Math.pow(2, exponent) * 2 < int) { 6 | exponent++; 7 | } 8 | 9 | while(int > 0) { 10 | let num = Math.pow(2, exponent); 11 | 12 | if(int >= num) { 13 | int -= num; 14 | result += 1 15 | } else { 16 | result += 0; 17 | } 18 | exponent--; 19 | } 20 | 21 | return result; 22 | } 23 | 24 | module.exports = toBinary; 25 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/MergeKSortedNaive.js: -------------------------------------------------------------------------------- 1 | 2 | // Space: O(NK) 3 | // Time: O(NK log(NK)) 4 | 5 | function mergeKSortedNaive(arrays) { 6 | let result = []; 7 | arrays.forEach(arr => { 8 | result = result.concat(arr); 9 | }); 10 | 11 | result.sort((a, b) => { 12 | return a - b; 13 | }); 14 | 15 | return result; 16 | } 17 | 18 | 19 | let arrs = [ 20 | [5, 6, 8, 16], 21 | [3, 7, 12, 13], 22 | [1, 10, 11, 15], 23 | [2, 4, 9, 14], 24 | ] 25 | 26 | console.log(mergeKSortedNaive(arrs)); 27 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/DiagonalDifference.js: -------------------------------------------------------------------------------- 1 | function DiagonalDifference(matrix) { 2 | var firstDiagonal = 0; 3 | var secondDiagonal = 0; 4 | 5 | for(var index = 0; index < matrix.length; index++){ 6 | firstDiagonal += matrix[index][index]; 7 | secondDiagonal += matrix[index][matrix.length - 1 - index]; 8 | } 9 | 10 | return Math.abs(firstDiagonal - secondDiagonal); 11 | } 12 | 13 | 14 | console.log(DiagonalDifference([[11, 2, 4],[4, 5, 6], 15 | [10, 8, -12]])) 16 | 17 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/RockPaperScissors.js: -------------------------------------------------------------------------------- 1 | function rockPaperScissors(rounds) { 2 | let result = []; 3 | 4 | function recurse(substr, depth) { 5 | if(depth >= rounds) { 6 | return result.push(substr); 7 | } 8 | recurse(substr + 'r', depth + 1); 9 | recurse(substr + 'p', depth + 1); 10 | recurse(substr + 's', depth + 1); 11 | } 12 | 13 | recurse('', 0); 14 | return result; 15 | } 16 | 17 | console.log(rockPaperScissors(4)); 18 | 19 | module.exports = rockPaperScissors; 20 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/FlattenArray.js: -------------------------------------------------------------------------------- 1 | function flattenArray(arr) { 2 | let result = []; 3 | function recurse(a) { 4 | for(let i = 0; i < a.length; i++) { 5 | if(typeof a[i] === 'object') { 6 | recurse(a[i]); 7 | } else { 8 | result.push(a[i]); 9 | } 10 | } 11 | } 12 | recurse(arr, '') 13 | return result; 14 | } 15 | 16 | // let a = [1, [2, 3, [4, 5, 6, [7]]], [8, 9, 10, [11, 12]]]; 17 | // console.log(flattenArray(a)); 18 | 19 | module.exports = flattenArray; 20 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/ReverseChunks.js: -------------------------------------------------------------------------------- 1 | function reverseChunks(arr, k) { 2 | // YOUR WORK HERE 3 | let index = 0; 4 | for(var i = 0; i < arr.length; i++) { 5 | if(i % k === k - 1) { 6 | reverse(arr, index, i); 7 | index = i + 1; 8 | } 9 | } 10 | reverse(arr, index, arr.length - 1); 11 | return arr; 12 | } 13 | 14 | function reverse(arr, i, j) { 15 | while(i < j) { 16 | [arr[i],arr[j]] = [arr[j],arr[i]] 17 | i++ 18 | j-- 19 | } 20 | } 21 | 22 | module.exports = reverseChunks; 23 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/Base7.js: -------------------------------------------------------------------------------- 1 | var convertToBase7 = function(num) { 2 | let result = ""; 3 | let sign = ""; 4 | if(num < 0) { 5 | sign = "-"; 6 | } 7 | if(num === 0) { 8 | return "0"; 9 | } 10 | num = Math.abs(num); 11 | while(num > 0) { 12 | let mod = num % 7; 13 | num = (num - mod)/7; 14 | result = mod + result; 15 | } 16 | return sign + result; 17 | }; 18 | 19 | 20 | /* 21 | Prompt 22 | https://leetcode.com/problems/base-7/description/ 23 | */ 24 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/ReverseInt.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} x 3 | * @return {number} 4 | */ 5 | var reverse = function(x) { 6 | let strInt = (x + "").split("").reverse(); 7 | let sign = 1; 8 | 9 | if(strInt[strInt.length - 1] === "-") { 10 | sign = -1; 11 | strInt.pop(); 12 | } 13 | 14 | let newInt = parseInt(strInt.join("")) 15 | 16 | if(newInt > (Math.pow(2, 31) - 1) || newInt < (Math.pow(-2, 31))) { 17 | return 0; 18 | } 19 | 20 | return newInt * sign; 21 | }; 22 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/Random7.js: -------------------------------------------------------------------------------- 1 | function foo5() { 2 | return Math.floor(Math.random() * 5) + 1 3 | } 4 | 5 | function foo7() { 6 | let result = 5 * foo5() + foo5() - 5; 7 | if(result < 22) { 8 | return result % 7 + 1; 9 | } 10 | return foo7(); 11 | } 12 | 13 | function test(num) { 14 | let result = {}; 15 | while (num > 0) { 16 | let n = foo7(); 17 | result[n] ? result[n] += 1 : result[n] = 1; 18 | num--; 19 | } 20 | return result; 21 | } 22 | 23 | console.log(test(10000000)); 24 | 25 | module.exports = foo7; 26 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/FindPrime.js: -------------------------------------------------------------------------------- 1 | var findPrime = function(n) { 2 | var memo = {1: 2, 2:3} 3 | var count = 2; 4 | 5 | function isPrime(num){ 6 | var limit = Math.max(Math.sqrt(num), memo[count]) 7 | 8 | for(var k in memo){ 9 | if(num % memo[k] === 0){ return false } 10 | } 11 | count++ 12 | memo[count] = num; 13 | return true; 14 | } 15 | 16 | var num = 2 17 | 18 | while(count <= n){ 19 | isPrime(num) 20 | num++ 21 | } 22 | 23 | return memo[n]; 24 | } 25 | 26 | console.log(findPrime(10001)) 27 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/MoveZeroes.js: -------------------------------------------------------------------------------- 1 | // const Swap = require('./Swap.js'); 2 | 3 | var moveZeroes = function(nums) { 4 | var back = 0 5 | var front = 0 6 | 7 | while(front < nums.length) { 8 | if(nums[back] !== 0){ 9 | back++ 10 | } else if(nums[front] !== 0 ) { 11 | Swap(nums, front, back) 12 | // [nums[front], nums[back]] = [nums[back], nums[front]]; 13 | back++ 14 | } 15 | front++; 16 | } 17 | return nums 18 | }; 19 | 20 | 21 | console.log(moveZeroes([1, 0, 2, 3, 8, 0, 2, 1, 0])); 22 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/SumSquareDifference.js: -------------------------------------------------------------------------------- 1 | // Sum Square Difference 2 | // Finds the difference between the square of the sum, and the sum of the squares 3 | 4 | var sumSquareDifference = function(n){ 5 | 6 | var square = function(x){ 7 | return x * x 8 | } 9 | 10 | var num1 = 0; 11 | var num2 = 0; 12 | 13 | for(var i = 1; i <= n; i++){ 14 | num1 += square(i) 15 | } 16 | 17 | for(var j = 1; j <= n; j++){ 18 | num2 += j 19 | } 20 | num2 = square(num2) 21 | 22 | return num2 - num1 23 | 24 | } 25 | console.log(sumSquareDifference(100)) 26 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/BitCombinations.js: -------------------------------------------------------------------------------- 1 | function BitCombinations(num) { 2 | let result = []; 3 | function helper(bits, depth) { 4 | if (depth === 0) { 5 | result.push(bits); 6 | return; 7 | } 8 | helper(bits + 0, depth - 1); 9 | helper(bits + 1, depth - 1); 10 | } 11 | helper('', num) 12 | return result; 13 | } 14 | 15 | console.log(BitCombinations(2)); 16 | // [ '00', '01', '10', '11' ] 17 | console.log(BitCombinations(3)); 18 | // [ '000', '001', '010', '011', '100', '101', '110', '111' ] 19 | 20 | module.exports = BitCombinations; 21 | -------------------------------------------------------------------------------- /Other/Archive/OOPArchive/new.js: -------------------------------------------------------------------------------- 1 | function Person(a){ 2 | this.a = a; 3 | } 4 | Person.prototype.talk = function(){ 5 | console.log('I say: ', this.a); 6 | } 7 | 8 | function spawn(constructor){ 9 | var obj = {}; 10 | Object.setPrototypeOf(obj, constructor.prototype); 11 | constructor.apply(obj, ) 12 | 13 | return obj; 14 | } 15 | //1. Create a new Object 16 | //2. Set prototype to the constructor's prototype 17 | //3. Execute the constructor with 'this' 18 | //4. Return created object 19 | 20 | var crockford = spawn(Person, 'Semicolons'); 21 | 22 | // crockford.talk(); 23 | 24 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/FlattenObject.js: -------------------------------------------------------------------------------- 1 | function flattenObject(obj) { 2 | let result = {}; 3 | function recurse(o, substr) { 4 | for(let key in o) { 5 | let resultKey = substr.length === 0 ? key : `${substr}.${key}`; 6 | if(typeof o[key] === 'object') { 7 | recurse(o[key], resultKey); 8 | } else { 9 | result[resultKey] = o[key]; 10 | } 11 | } 12 | } 13 | recurse(obj, '') 14 | return result; 15 | } 16 | 17 | // let o = {a: {b : { c: 2 }}, d: 5, e: {f : 4} } ; 18 | // console.log(flattenObject(o)); 19 | 20 | module.exports = flattenObject; 21 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/SumPrimes.js: -------------------------------------------------------------------------------- 1 | // Sum Primes 2 | // Sums all the prime numbers below a given number as input 3 | 4 | var isPrime = function(n){ 5 | for(var i = 2; i <= Math.sqrt(n); i++) { 6 | if(n % i === 0){ 7 | return false; 8 | } 9 | } 10 | return true; 11 | } 12 | 13 | var sumPrimes = function(n){ 14 | var result = []; 15 | 16 | for(var i = 2; i < n; i++){ 17 | if(isPrime(i)){ 18 | result.push(i); 19 | } 20 | } 21 | 22 | return result.reduce(function(prev, curr){ 23 | return prev + curr; 24 | }) 25 | } 26 | 27 | console.log(sumPrimes(2000000)) 28 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/Triangular.js: -------------------------------------------------------------------------------- 1 | function Triangular(n) { 2 | var maxCheck = Math.sqrt(n/2) 3 | //Only need to check up to sqrt(n/2) 4 | //Because as n -> Infinity 5 | //And if n = a^2 + b^2 6 | //Where a and b are triangular 7 | //And a < b 8 | //Then a -> b 9 | 10 | var memo = {"1" : 1}; 11 | var index = 2; 12 | 13 | while(index <= maxCheck) { 14 | var last = memo[index - 1]; 15 | var next = last + index; 16 | if(Math.pow(last, 2) + Math.pow(next, 2) === n){ 17 | return true; 18 | } 19 | memo[index] = next; 20 | index++; 21 | } 22 | return false; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Other/Archive/OOPArchive/prototype.js: -------------------------------------------------------------------------------- 1 | function talk() { 2 | console.log(this.sound); 3 | }; 4 | 5 | var animal = { 6 | talk 7 | }; 8 | 9 | var cat = { 10 | sound: 'meow' 11 | } 12 | 13 | 14 | function hey(name){ 15 | this.name = name; 16 | } 17 | 18 | 19 | var a = new hey('hello'); 20 | 21 | hey.prototype.sup = function(){ 22 | console.log('sup') 23 | } 24 | 25 | // console.log(a) 26 | 27 | // console.log(Object.getPrototypeOf(a)) 28 | console.log(Object) 29 | 30 | // console.log(hey.prototype) 31 | 32 | 33 | // Object.setPrototypeOf(cat, animal); 34 | 35 | // console.log(cat.prototype) 36 | // cat.talk(); 37 | -------------------------------------------------------------------------------- /AlgorithmProblems/Sorting/SortByDecimal.js: -------------------------------------------------------------------------------- 1 | let nums = []; 2 | for (let i=0; i < 100; i++) { 3 | nums.push(Math.floor(Math.random() * 1000)/1000 + Math.floor(Math.random() * 1000)); 4 | } 5 | 6 | 7 | // console.log(nums) 8 | 9 | function sortByDecimal(nums) { 10 | nums.forEach((num, index) => { 11 | let str = num + ''; 12 | nums[index] = str.split('.'); 13 | }) 14 | 15 | nums.sort((a, b) => { 16 | return a[1] - b[1] 17 | }) 18 | 19 | nums.forEach((num, index) => { 20 | nums[index] = Number(num[0] + '.' + num[1]); 21 | }) 22 | return nums; 23 | } 24 | 25 | 26 | 27 | console.log(sortByDecimal(nums)) 28 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/McNugget.js: -------------------------------------------------------------------------------- 1 | 2 | function mcNugget(num) { 3 | let nuggets = []; 4 | 5 | 6 | for(let i = 0; i <= num; i++) { 7 | nuggets.push(0); 8 | } 9 | 10 | nuggets[0] = 1; 11 | 12 | let boxSizes = [6, 9, 20]; 13 | 14 | 15 | for(let size = 0; size < boxSizes.length; size++) { 16 | for(let i = 1; i <= num; i++) { 17 | if((i - boxSizes[size]) >= 0 && nuggets[i - boxSizes[size]] === 1) { 18 | nuggets[i] = 1; 19 | } 20 | } 21 | if(nuggets[num] === 1) { 22 | return true; 23 | } 24 | } 25 | return false; 26 | } 27 | 28 | 29 | console.log(mcNugget(19)) 30 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/Jump.js: -------------------------------------------------------------------------------- 1 | function jump(arr){ 2 | var cache = {0:0}; 3 | 4 | for(var i = 0; i < arr.length; i++){ 5 | var steps = arr[i]; 6 | 7 | if(cache[arr.length - 1] !== undefined){ 8 | return cache[arr.length - 1] 9 | } 10 | 11 | for(var j = 0; j <= steps; j++){ 12 | 13 | if(cache[i + j] !== undefined){ 14 | 15 | cache[i + j] = Math.min((cache[i] + 1), cache[i + j]) 16 | 17 | } else { 18 | cache[i + j] = cache[i] + 1; 19 | } 20 | } 21 | } 22 | 23 | return cache[arr.length - 1]; 24 | 25 | } 26 | 27 | console.log(jump([2, 1, 3, 1, 4, 1, 2, 0, 3, 2, 5])) 28 | -------------------------------------------------------------------------------- /DataStructures/LinkedLists/HasCycle.js: -------------------------------------------------------------------------------- 1 | function Node (val) { 2 | // TODO 3 | var obj = {}; 4 | obj.value = val || null; 5 | obj.next = null; 6 | return obj; 7 | } 8 | 9 | var a = Node('a'); 10 | var b = Node('b'); 11 | var c = Node('c'); 12 | var d = Node('d'); 13 | var e = Node('e'); 14 | 15 | a.next = b; 16 | b.next = c; 17 | c.next = d; 18 | d.next = e; 19 | e.next = b; 20 | 21 | 22 | var hasCycle = function(linkedList){ 23 | //Your beautiful code here 24 | 25 | var slow = linkedList; 26 | var fast = linkedList.next; 27 | 28 | while(fast){ 29 | if() 30 | 31 | } 32 | 33 | 34 | return false; 35 | }; 36 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/KnapSackNaive.js: -------------------------------------------------------------------------------- 1 | function knapSackNaive(values, weights, capacity) { 2 | let maxValue = 0; 3 | 4 | function addItem(currentValue, currentWeight, index){ 5 | if(currentWeight > capacity || index > weights.length) { 6 | return; 7 | } 8 | if(currentValue > maxValue){ 9 | maxValue = currentValue; 10 | } 11 | 12 | addItem(currentValue + values[index], currentWeight + weights[index], index + 1); 13 | addItem(currentValue, currentWeight, index + 1); 14 | } 15 | 16 | addItem(0, 0, 0); 17 | 18 | 19 | return maxValue; 20 | } 21 | 22 | console.log(knapSackNaive([6, 10, 12], [1, 2, 3], 5)) 23 | -------------------------------------------------------------------------------- /AlgorithmProblems/Sorting/CountingSort.js: -------------------------------------------------------------------------------- 1 | function countingSort(arr, min, max) { 2 | let count = new Array(max - min + 1) 3 | 4 | count.fill(0) 5 | 6 | for(let i = 0; i < arr.length; i++){ 7 | count[arr[i] - min] = count[arr[i] - min] + 1 8 | 9 | } 10 | 11 | let z = 0 12 | 13 | for(let j = min; j < max; j++){ 14 | if(count[j - min] > 0) { 15 | arr[z] = j 16 | z++ 17 | count[j - min] = count[j - min] - 1 18 | } 19 | } 20 | 21 | return arr; 22 | } 23 | 24 | // console.log(countingSort([57, 87, 98, 95, 68, 62, 51, 93], 50, 100)) 25 | module.exports = countingSort; 26 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/LongestCommonPrefix.js: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/longest-common-prefix/submissions/ 2 | 3 | /** 4 | * @param {string[]} strs 5 | * @return {string} 6 | */ 7 | var longestCommonPrefix = function(strs) { 8 | let prefix = ""; 9 | if(strs.length === 0) return prefix; 10 | 11 | for(let j = 0; j < strs[0].length; j++) { 12 | let char = strs[0][j]; 13 | 14 | for(let i = 0; i < strs.length; i++) { 15 | if(j >= strs[i].length || strs[i][j] !== char) { 16 | return prefix; 17 | } 18 | } 19 | prefix += char; 20 | } 21 | return prefix; 22 | }; 23 | -------------------------------------------------------------------------------- /Other/Frontend/xss.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
5 |

Hello World

6 | 7 | 8 |
9 | 10 | 11 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Other/FunctionalProgramming/abstraction.js: -------------------------------------------------------------------------------- 1 | function square(num){ 2 | return num * num; 3 | }; 4 | 5 | function power(base, exponent){ 6 | var result = 1; 7 | var exp = exponent; 8 | while(exp > 0){ 9 | result *= base; 10 | exp-- 11 | } 12 | return result; 13 | }; 14 | 15 | function newSquare(base){ 16 | return power(base, 2); 17 | } 18 | 19 | function fullName(firstName){ 20 | return function(lastName){ 21 | return 'Hello, my name is ' + firstName + ' ' + lastName + '. It is nice to meet you!'; 22 | } 23 | } 24 | 25 | console.log(fullName('Sergey')('Piterman')); 26 | 27 | // console.log(power(2, 3)); 28 | // console.log(newSquare(3)); 29 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/PlusOne.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, write a function that handles adding one two the array 3 | 4 | Examples: 5 | [7, 6, 2] => [7, 6, 3] 6 | [1,0,0] => [1,0,1] 7 | [9,9,9] => [1, 0, 0, 0] 8 | */ 9 | 10 | function plusOne(arr){ 11 | let carry = 1; 12 | let i = arr.length - 1; 13 | 14 | while(carry && i >= 0){ 15 | let num = arr[i] + 1; 16 | if(num === 10) { 17 | arr[i] = 0; 18 | } else { 19 | arr[i] += 1; 20 | carry = 0; 21 | } 22 | i--; 23 | } 24 | if(carry){ 25 | arr.unshift(1) 26 | } 27 | return arr; 28 | } 29 | 30 | // console.log(plusOne([1, 9, 9])) 31 | 32 | module.exports = plusOne; 33 | -------------------------------------------------------------------------------- /Other/FunctionalProgramming/asyncMap.js: -------------------------------------------------------------------------------- 1 | function wait3For1(callback){ 2 | setTimeout(function(){ 3 | callback('one') 4 | }, 300) 5 | } 6 | 7 | function wait2For5(callback){ 8 | setTimeout(function(){ 9 | callback('five') 10 | }, 200) 11 | } 12 | 13 | 14 | function asyncMap(tasks, callback){ 15 | return callback( 16 | tasks.map((item) => 17 | item((element) => element))) 18 | } 19 | 20 | asyncMap([wait3For1, wait2For5], function(arr){ 21 | console.log(arr) //expect ['one', 'two'] 22 | }); 23 | 24 | //Keep getting [undefined, undefined] 25 | //I'm pretty sure it's because I'm not doing the callbacks wait2For5 and wait3For1 correctly, but not sure what the problem is 26 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/SubArraySum.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of positive integers and a target value, return true if there is a subarray of consecutive elements that sum up to this target value. 3 | */ 4 | 5 | function subArraySum(arr, target) { 6 | let start = 0; 7 | let currentSum = 0; 8 | 9 | for(let end = 0; end < arr.length; end++){ 10 | if(currentSum === target) { 11 | return true; 12 | } 13 | currentSum += arr[end]; 14 | 15 | while(currentSum > target) { 16 | currentSum -= arr[start] 17 | start++; 18 | } 19 | } 20 | return currentSum === target; 21 | } 22 | 23 | module.exports = subArraySum; 24 | // console.log(subArraySum([6,12,1,7,5,2,3], 12)); 25 | -------------------------------------------------------------------------------- /Other/FunctionalProgramming/ForEach.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a ForEach function that performs an operation on each element in a collection 3 | Shoud work on arrays and objects 4 | */ 5 | 6 | function ForEach(collection, callback) { 7 | if(Array.isArray(collection)){ 8 | for(let index = 0; index < collection.length; index++){ 9 | callback(collection[index], index, collection); 10 | } 11 | return; 12 | } 13 | for(let key in collection) { 14 | callback(collection[key], key, collection); 15 | } 16 | } 17 | 18 | 19 | // Tests 20 | // ForEach([1, 2, 3], (item) => console.log(item)); 21 | // ForEach({1:"a", 2:"b", 3:"c"}, (item) => console.log(item)); 22 | 23 | module.exports = ForEach; 24 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/Transpose.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a matrix return its transpose: 3 | 4 | Example: 5 | 6 | Input: 7 | [[1, 2], 8 | [4, 5], 9 | [7, 8]] 10 | 11 | Output: 12 | [[1, 4, 7], 13 | [2, 5, 8]] 14 | */ 15 | 16 | 17 | function Transpose(matrix) { 18 | let result = []; 19 | for(let i = 0; i < matrix[0].length; i++) { 20 | let newRow = []; 21 | for(let j = 0; j < matrix.length; j++) { 22 | newRow.push(matrix[j][i]); 23 | } 24 | result.push(newRow); 25 | } 26 | return result; 27 | } 28 | 29 | console.log(Transpose( 30 | [[1, 2], 31 | [4, 5], 32 | [7, 8]])); 33 | 34 | console.log(Transpose( 35 | [[1, 0, 0], 36 | [0, 1, 0]])); 37 | 38 | module.exports = Transpose; 39 | -------------------------------------------------------------------------------- /DataStructures/BinaryTrees/LongestPath.js: -------------------------------------------------------------------------------- 1 | function bstNode (value) { 2 | this.value = value; 3 | this.left = null; 4 | this.right = null; 5 | } 6 | 7 | function LongestPath(root){ 8 | let result = 0; 9 | 10 | function dfs(current, depth){ 11 | if(depth > result) { result = depth;} 12 | if(current === null) return; 13 | dfs(current.left, depth+1); 14 | dfs(current.right,depth+1); 15 | } 16 | 17 | dfs(root, 0); 18 | return result; 19 | } 20 | 21 | 22 | // let root = new bstNode(1); 23 | // root.left = new bstNode(2) 24 | // root.right = new bstNode(3); 25 | // root.right.right = new bstNode(4); 26 | // 27 | // console.log(LongestPath(root)); 28 | 29 | module.exports = LongestPath; 30 | -------------------------------------------------------------------------------- /Other/MachineLearning/GoogleTutorial/pipeline.py: -------------------------------------------------------------------------------- 1 | # import a dataset 2 | from sklearn import datasets 3 | iris = datasets.load_iris() 4 | 5 | x = iris.dataset 6 | y = iris.target 7 | 8 | from sklearn.cross_validation import train_test_split 9 | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5) 10 | 11 | from sklearn.neighbors import KNeighborsClassifier 12 | my_classifier = KNeighborsClassifier() 13 | 14 | # from sklearn import tree 15 | # my_classifier = tree.DecisionTreeClassifier() 16 | 17 | 18 | my_classifier.fit(X_train, y_train) 19 | 20 | predictions = my_classifier.predict(X_test) 21 | 22 | from sklearn.metrics import accuracy_score 23 | print accuracy_score(y_test, predictions) 24 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/AllProducts.js: -------------------------------------------------------------------------------- 1 | function findAllProducts(arr) { 2 | let forwardMultiples = []; 3 | let backwardMultiples = []; 4 | 5 | let total = 1; 6 | for(let i = 0; i < arr.length; i++) { 7 | forwardMultiples.push(total); //O(N) 8 | total *= arr[i]; 9 | } 10 | 11 | total = 1; 12 | 13 | for(let i = arr.length - 1; i >= 0; i--) { 14 | backwardMultiples.push(total); //O(N) 15 | total *= arr[i]; 16 | } 17 | 18 | backwardMultiples.reverse() //O(N) 19 | 20 | let result = []; 21 | 22 | for(let i = 0; i < arr.length; i++) { 23 | result.push(forwardMultiples[i] * backwardMultiples[i]); 24 | } 25 | 26 | return result; 27 | 28 | } 29 | 30 | findAllProducts([1, 2, 3, 4, 5]) 31 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/RectangleIslands.js: -------------------------------------------------------------------------------- 1 | // function rectangleIslands(matrix) { 2 | // let total = 0; 3 | // 4 | // for(let i = 0; i < matrix.length; i++) { 5 | // for(let j = 0; j < matrix[i].length; j++) { 6 | // if(matrix[i][j] === 1 && ((i - 1) < 0 || matrix[i - 1][j] === 0) && ((j - 1) < 0 || matrix[i][j - 1] === 0) ) { 7 | // total++; 8 | // } 9 | // } 10 | // } 11 | // return total; 12 | // } 13 | 14 | 15 | 16 | // let matrix = [[1, 1, 1, 0], 17 | // [1, 1, 1, 0], 18 | // [1, 1, 1, 0], 19 | // [1, 1, 1, 0], 20 | // [0, 0, 0, 1]]; 21 | // 22 | // console.log(rectangleIslands(matrix)); 23 | 24 | module.exports = rectangleIslands; 25 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/ParensPermutations.js: -------------------------------------------------------------------------------- 1 | function ParensPermutations(num) { 2 | let result = []; 3 | 4 | function recurse(substr, left, right) { 5 | if(left === 0 && right === 0) { 6 | result.push(substr); 7 | return; 8 | } if (left === 0){ 9 | recurse(substr + ')', left, right - 1); 10 | } else if(left < right) { 11 | recurse(substr + ')', left, right - 1); 12 | recurse(substr + '(', left - 1, right); 13 | } else { 14 | recurse(substr + '(', left - 1, right); 15 | } 16 | } 17 | recurse('', num, num); 18 | return result; 19 | } 20 | 21 | // let result = ParensPermutations(6); 22 | // console.log(result.length) 23 | 24 | module.exports = ParensPermutations; 25 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/TwoSumPairs.js: -------------------------------------------------------------------------------- 1 | function twoSumPairs(arr, target) { 2 | let counts = {}; 3 | arr.forEach((item) => { 4 | counts[item] = counts[item] === undefined? 1 : counts[item] + 1 5 | }) 6 | 7 | let total = 0; 8 | for (let key in counts) { 9 | let k = Number(key) 10 | if(counts[target - k] && (k != target - k)) { 11 | total += counts[target - k] * counts[key]; 12 | delete counts[key]; 13 | delete counts[target - k]; 14 | } 15 | } 16 | 17 | if(target/2 in counts) { 18 | let n = counts[target/2] 19 | total += (n * (n-1))/2 20 | } 21 | 22 | return total; 23 | } 24 | 25 | console.log(twoSumPairs([1,1,3,2,2,2], 4)) // 5 26 | console.log(twoSumPairs([1,1,3,2,2,2], 5)) // 3 27 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/PlusMult.js: -------------------------------------------------------------------------------- 1 | function plusMult(A) { 2 | // Write your code here 3 | let even = A[0] % 2; 4 | let odd = A[1] % 2; 5 | 6 | for(let i = 2; i < A.length; i += 2) { 7 | if(i % 4 === 0) { 8 | even = (even + A[i]) % 2 9 | } else { 10 | even = (even * A[i]) % 2 11 | } 12 | } 13 | 14 | for(let i = 3; i < A.length; i += 2) { 15 | if((i - 1) % 4 === 0) { 16 | odd = (odd + A[i]) % 2 17 | } else { 18 | odd = (odd * A[i]) % 2 19 | } 20 | } 21 | 22 | 23 | if(Math.abs(even % 2) > Math.abs(odd % 2)) return "EVEN" 24 | if(Math.abs(even % 2) < Math.abs(odd % 2)) return "ODD" 25 | return "NEUTRAL" 26 | } 27 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/CompressString.js: -------------------------------------------------------------------------------- 1 | function compress(str) { 2 | let currentLetterCount = 0; 3 | let currentLetter = ""; 4 | let result = []; 5 | 6 | for(let i = 0; i < str.length; i++) { 7 | 8 | if(str[i] !== currentLetter) { 9 | result.push(currentLetter); 10 | currentLetter = str[i]; 11 | if(currentLetterCount > 1) { 12 | result.push(String(currentLetterCount)); 13 | } 14 | currentLetterCount = 1; 15 | } else { 16 | currentLetterCount += 1; 17 | } 18 | } 19 | 20 | result.push(currentLetter) 21 | if(currentLetterCount > 1) { 22 | result.push(currentLetterCount) 23 | } 24 | 25 | return result.join(""); 26 | } 27 | 28 | console.log(compress("AABCCCCAAAB")) 29 | -------------------------------------------------------------------------------- /Other/RegEx/PatternMatching.js: -------------------------------------------------------------------------------- 1 | function processData(input) { 2 | var data = input.split('\n'); 3 | var n = Number(data[0]); 4 | var q = Number(data[n + 1]); 5 | 6 | var patterns = []; 7 | var count = []; 8 | 9 | //Create RegExp objects 10 | for(var i = n + 2; i < data.length; i++){ 11 | patterns.push(new RegExp(data[i])); 12 | }; 13 | 14 | patterns.forEach((pattern) => { 15 | var counter = 0; 16 | for(var i = 1; i <= n; i++){ 17 | if(pattern.test(data[i])){ 18 | counter++; 19 | } 20 | } 21 | count.push(counter); 22 | }); 23 | 24 | //console.log(count) 25 | //console.log(patterns); 26 | //console.log(n, q); 27 | 28 | } 29 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/StringPermutations.js: -------------------------------------------------------------------------------- 1 | function stringPermutations(str) { 2 | let result = ['']; 3 | let index = 0; 4 | 5 | while(index < str.length) { 6 | let temp = []; 7 | for(let i = 0; i < result.length; i++) { 8 | let word = result[i]; 9 | for(let j = 0; j <= word.length; j++) { 10 | temp.push(addLetterToWord(word, str[index], j)); 11 | } 12 | } 13 | index++; 14 | result = temp; 15 | } 16 | return result; 17 | } 18 | 19 | // console.log(stringPermutations('abcd')); 20 | 21 | function addLetterToWord(word, letter, index) { 22 | let test = word.split(''); 23 | test.splice(index, 0, letter); 24 | return test.join('') 25 | } 26 | 27 | // console.log(addLetterToWord('', 'd', 3)) 28 | -------------------------------------------------------------------------------- /DataStructures/UnionFind/QuickUnion.js: -------------------------------------------------------------------------------- 1 | class QuickUnion { 2 | // Lazy Approach 3 | constructor(size) { 4 | this.ids = []; 5 | for(let i = 0; i < size; i++) { 6 | this.ids.push(i); 7 | } 8 | } 9 | 10 | root(id) { 11 | while(this.ids[id] !== id) { 12 | id = this.ids[id]; 13 | } 14 | return id; 15 | } 16 | 17 | union(id1, id2) { 18 | let root1 = this.root(id1); 19 | let root2 = this.root(id2); 20 | 21 | this.ids[root1] = root2; 22 | } 23 | 24 | connected(id1, id2) { 25 | return this.root(id1) === this.root(id2); 26 | } 27 | } 28 | 29 | 30 | let u = new QuickUnion(10) 31 | 32 | u.union(4, 3) 33 | u.union(3, 8) 34 | u.union(8, 9) 35 | 36 | u.union(0, 1) 37 | 38 | console.log(u.root(9)) 39 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/SortedBitArraySearch.js: -------------------------------------------------------------------------------- 1 | // Given a sorted array of 0s and 1s, retun the number of Ones 2 | 3 | function sortedBitSearch(arr) { 4 | let front = 0; 5 | let back = arr.length - 1; 6 | let mid = Math.floor(back/2); 7 | 8 | // Slightly modified binary search 9 | // When the mid is a zero, set front to mid and increment by 1 10 | // When the mid is a 1, just set the back equal to mid 11 | while(front < back) { 12 | if (arr[mid] === 0) { 13 | front = mid + 1; 14 | } else { 15 | back = mid; 16 | } 17 | mid = Math.floor((front + back)/2); 18 | } 19 | return arr[mid] === 0 ? 0 : arr.length - mid; 20 | } 21 | 22 | console.log(sortedBitSearch([0,0,0,0, 1])); 23 | 24 | module.exports = sortedBitSearch; 25 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/SortedTwoSum.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an arry of sorted integers and a target value, 3 | return the pair of indices of the arry who's value add up to the target. 4 | Otherwise return [-1, -1] 5 | 6 | Example: 7 | Input: [-5, 1, 3, 6, 7], -2 => Output: [0,2] 8 | Input: [1, 9, 10], 8 => Output: [-1,-1] 9 | */ 10 | 11 | function sortedTwoSum(arr, target) { 12 | let i = 0; 13 | let j = arr.length - 1; 14 | 15 | while (i < j){ 16 | if(arr[i] + arr[j] === target) { 17 | return [i, j] 18 | } 19 | if(arr[i] + arr[j] > target) { 20 | j--; 21 | } else { 22 | i++; 23 | } 24 | } 25 | return [-1, -1] 26 | } 27 | 28 | module.exports = sortedTwoSum; 29 | 30 | // console.log(sortedTwoSum([1, 2, 3, 4, 5], 10)); 31 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/ClosestSteakhouses.js: -------------------------------------------------------------------------------- 1 | function closestSteakhouses(coordinates, numberOfHouses) { 2 | let distances = []; 3 | 4 | coordinates.forEach((coordinate, index) => { 5 | distances.push({coordinate, index, distance: calculateDistance(coordinate)}) 6 | }) 7 | 8 | distances.sort((a, b) => { 9 | return a.distance - b.distance; 10 | }) 11 | 12 | let result = []; 13 | 14 | for(let i = 0; i < Math.min(numberOfHouses, coordinates.length); i++) { 15 | result.push(distances[i].coordinate); 16 | } 17 | 18 | return result; 19 | } 20 | 21 | function calculateDistance(coordinate) { 22 | return Math.sqrt(Math.pow(coordinate[0], 2) + Math.pow(coordinate[1], 2)); 23 | } 24 | 25 | console.log(closestSteakhouses([[1,-1],[3,4], [2,5],[1,2]], 2)) 26 | -------------------------------------------------------------------------------- /DataStructures/Graphs/GraphDFSIterative.js: -------------------------------------------------------------------------------- 1 | function dfs(graph,start) { 2 | let result = []; 3 | let seen = new Set(); 4 | let stack = []; 5 | 6 | stack.push(start); 7 | // seen.add(start); 8 | 9 | while(stack.length) { 10 | let current = stack.pop(); 11 | let neighbors = graph[current]; 12 | 13 | if(!seen.has(current)) { 14 | result.push(current); 15 | seen.add(current); 16 | } 17 | 18 | neighbors.forEach(n => { 19 | if(!seen.has(n)) { 20 | stack.push(n); 21 | } 22 | }) 23 | } 24 | 25 | return result; 26 | } 27 | 28 | let graph = { 29 | "1": ["8"], 30 | "8": ["1", "9", "3"], 31 | "3": ["8", "5", "2"], 32 | "5": ["3"], 33 | "2": ["3", "9"], 34 | "9": ["8", "2"] 35 | } 36 | 37 | dfs(graph, "1"); 38 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/Arbitrage.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Complete the function below. 3 | */ 4 | function arbitrage(quotes) { 5 | //Step 1. Split quotes up into an array of arrays containing floats 6 | var arr = []; 7 | quotes.forEach((item) => { 8 | var lst = item.split(' '); 9 | lst.forEach((entry, index) => { 10 | lst[index] = Number(entry); 11 | }); 12 | arr.push(lst); 13 | }); 14 | //Step 2. 15 | var result = []; 16 | 17 | arr.forEach((item) => { 18 | var total = 100000; 19 | item.forEach((entry)=> total /= entry); 20 | if(total > 100000){ 21 | result.push(Math.floor(total - 100000)); 22 | } else { 23 | result.push(0); 24 | } 25 | }); 26 | return result; 27 | }; 28 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/NonrepeatingSubstring.js: -------------------------------------------------------------------------------- 1 | function nonrepeatSubstring(str) { 2 | // YOUR WORK HERE 3 | let longest = ""; 4 | let current = ""; 5 | let seen = {}; 6 | let start = 0; 7 | let end = 0; 8 | 9 | while(end < str.length){ 10 | if(!(str[end] in seen)){ 11 | current += str[end]; 12 | seen[str[end]] = true; 13 | if(current.length > longest.length){ 14 | longest = current; 15 | } 16 | end++; 17 | } else { 18 | if(str[start] === str[end]){ 19 | start++; 20 | end++; 21 | current = str.slice(start, end); 22 | } else { 23 | delete seen[str[start]]; 24 | start++; 25 | } 26 | } 27 | } 28 | return longest; 29 | } 30 | 31 | console.log(nonrepeatSubstring("012345abbcddeffgghij")); 32 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/Power.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that raises a base to an exponent that runs in logarithmic time 3 | */ 4 | 5 | function Power(base, exponent) { 6 | if(!Number.isInteger(exponent)) { 7 | return 'This function cannot handle roots'; 8 | } 9 | if(exponent < 0){ 10 | return 1/Power(base, -exponent); 11 | } 12 | if(exponent === 0){ 13 | return 1; 14 | } 15 | if(exponent % 2 === 0){ 16 | return Power(base * base, exponent/2); 17 | } 18 | return base * Power(base * base, (exponent - 1)/2); 19 | } 20 | 21 | // Clever Implementation 22 | // const Power = (base, exponent) => !exponent? 1 : exponent % 2 ? base * Power(base, exponent - 1) : Power(base * base, exponent/2); 23 | 24 | // console.log(Power(5, 2)) 25 | 26 | 27 | module.exports = Power; 28 | -------------------------------------------------------------------------------- /AlgorithmProblems/Sorting/BitArraySort.js: -------------------------------------------------------------------------------- 1 | function sortBitArray(arr) { 2 | let back = 0; 3 | let front = arr.length - 1; 4 | 5 | while(back < front) { 6 | if(arr[back] === 1 && arr[front] === 0){ 7 | [arr[back], arr[front]] = [arr[front], arr[back]]; 8 | } 9 | if(arr[back] === 0){ 10 | back++; 11 | } 12 | if(arr[front] === 1){ 13 | front-- 14 | } 15 | } 16 | return arr; 17 | } 18 | 19 | function sortBits(arr) { 20 | let i = 0; 21 | let j = 0; 22 | 23 | while(j < arr.length) { 24 | if(arr[j] === 0) { 25 | arr[j] = 1 26 | arr[i] = 0 27 | i++ 28 | } 29 | j++ 30 | } 31 | return arr; 32 | } 33 | 34 | // console.log(sortBits([0, 1, 1, 1, 0, 0, 1])) 35 | 36 | // console.log(sortBitArray([0, 1, 0, 1, 1, 0])); 37 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/LargestPrimeFactorMemo.js: -------------------------------------------------------------------------------- 1 | function largestPrimeFactor(n) { 2 | 3 | //List of primes in the memo 4 | var memo = {2: 2}; 5 | 6 | //Limit of prime factors to test 7 | //Worst case scenario, n is p x p 8 | //Where p is prime 9 | var limit = Math.sqrt(n); 10 | 11 | //Thing we will return at the end 12 | var temp = 2; 13 | 14 | //Tests a number's primality 15 | //If prime, add to memo 16 | function isPrime(num){ 17 | for(var k in memo){ 18 | if(num % memo[k] === 0) return; 19 | } 20 | temp = num; 21 | memo[temp] = num; 22 | } 23 | 24 | 25 | var counter = temp; 26 | 27 | while(counter <= limit) { 28 | isPrime(counter); 29 | counter++; 30 | } 31 | 32 | return temp; 33 | } 34 | 35 | // largestPrimeFactor(600851475143); 36 | -------------------------------------------------------------------------------- /DataStructures/LinkedLists/Dequeue.js: -------------------------------------------------------------------------------- 1 | class Dequeue { 2 | constructor(){ 3 | this.head = new ListNode(Infinity) 4 | this.tail = new ListNode(-Infinity) 5 | this.head.next = this.tail 6 | this.tail.prev = this.head 7 | } 8 | removeFromHead() { 9 | this.head.next = this.head.next.next 10 | this.head.next.prev = this.head 11 | } 12 | 13 | removeFromTail() { 14 | this.tail.prev = this.tail.prev.prev 15 | this.tail.prev.next = this.tail 16 | } 17 | addToTail(val) { 18 | let newNode = new ListNode(val) 19 | newNode.prev = this.tail.prev 20 | this.tail.prev.next = newNode 21 | this.tail.prev = newNode 22 | } 23 | } 24 | 25 | class ListNode { 26 | constructor(val) { 27 | this.val = val 28 | this.next = null 29 | this.prev = null 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/KnapSack.js: -------------------------------------------------------------------------------- 1 | // K = capacity 2 | // N = values/weights.length 3 | 4 | function KnapSack(values, weights, capacity) { 5 | let finalMax = new Array(capacity + 1).fill(0); //O(K) Space and Time to Create 6 | 7 | for(let index = 0; index < weights.length; index++ ) { //O(N) Time 8 | let weight = weights[index]; 9 | let value = values[index]; 10 | let tempMax = finalMax.slice(); //O(K) Time and Space 11 | 12 | for(let i = 0; i <= capacity; i++){ //O(K) Time 13 | 14 | if(i - weight >= 0) { //Key check here 15 | tempMax[i] = Math.max(tempMax[i], (finalMax[i - weight] + value)) 16 | } 17 | } 18 | finalMax = tempMax; 19 | 20 | } 21 | 22 | return finalMax[capacity]; 23 | } 24 | 25 | 26 | 27 | // console.log(KnapSack([6, 10, 12], [1, 2, 3], 5)) 28 | 29 | 30 | // => 22 31 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/LongestPalindromeSubsequence.js: -------------------------------------------------------------------------------- 1 | function longest_palindromic_substring(str) { 2 | if(str.length <= 1){ 3 | return str.length; 4 | }; 5 | // var longest = 1; 6 | 7 | for(var i = str.length; i >= 2; i--){ 8 | for(var j = 0; j < str.length - i + 1; j++){ 9 | var substr = str.slice(j, j + i) 10 | if(isPalindrome(substr)){ 11 | // longest = substr.length; 12 | // return longest; 13 | return substr.length; 14 | } 15 | 16 | } 17 | }; 18 | // return longest; 19 | return 1; 20 | 21 | } 22 | 23 | function isPalindrome(str){ 24 | for(var i = 0; i < str.length; i++){ 25 | if(str[i] !== str[str.length - 1 - i]){ 26 | return false; 27 | } 28 | } 29 | return true; 30 | } 31 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/LimitingReagent.js: -------------------------------------------------------------------------------- 1 | // Ratios are given as quantities necessary to produce one unit of output 2 | // Quantities are given as units available 3 | 4 | function limitingReagent(ratios, quantities) { 5 | let maxOutput = Infinity; 6 | let limiting; 7 | 8 | for (let compound in ratios) { 9 | if(quantities[compound] === undefined) { 10 | return 0; 11 | } 12 | let maxOutputForGivenCompound = quantities[compound] / ratios[compound] 13 | if(maxOutputForGivenCompound < maxOutput) { 14 | maxOutput = maxOutputForGivenCompound; 15 | limiting = compound; 16 | } 17 | } 18 | console.log(limiting); 19 | return maxOutput; 20 | } 21 | 22 | let ratios = {'C':12, 'H':62, 'O':24, 'N': 1} 23 | 24 | let quantities = {'C':5000, 'H':3000, 'O':10000, 'N': 200} 25 | 26 | console.log(limitingReagent(ratios, quantities)) 27 | -------------------------------------------------------------------------------- /AlgorithmProblems/Sorting/SortDigits.js: -------------------------------------------------------------------------------- 1 | function sortDigits(num){ 2 | let nums = {} 3 | let power = 1; 4 | let result = 0; 5 | 6 | while(num > 0){ 7 | let numToSubtract = num % Math.pow(10, power); 8 | num -= numToSubtract; 9 | let digit = numToSubtract / Math.pow(10, power - 1); 10 | 11 | if(nums[digit] !== undefined) { 12 | nums[digit] += 1; 13 | } else { 14 | nums[digit] = 1; 15 | } 16 | 17 | power++ 18 | } 19 | 20 | power--; 21 | 22 | for(let i = 0; i < 10; i++){ 23 | while(nums[i] !== undefined && nums[i] > 0){ 24 | power--; 25 | result += Number(i) * Math.pow(10, power); 26 | nums[i] -= 1; 27 | } 28 | } 29 | return result; 30 | } 31 | 32 | // console.log(sortDigits(2975920661000001)) 33 | 34 | module.exports = sortDigits; 35 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/RatPath2.js: -------------------------------------------------------------------------------- 1 | // JavaScript Solution: 2 | // DOWN, RIGHT solution 3 | function ratPath(maze) { 4 | let result; 5 | let path = []; 6 | function findPath(x, y) { 7 | if(x >= maze.length || y >= maze[0].length || maze[x][y] === 1) { 8 | return; 9 | } 10 | path.push([x, y]); 11 | if(x === maze.length - 1 && y === maze[0].length - 1) { 12 | result = path.slice(); 13 | return; 14 | } 15 | findPath(x + 1, y) 16 | findPath(x, y + 1) 17 | path.pop(); 18 | } 19 | findPath(0, 0); 20 | return !result ? [-1, -1] : result; 21 | } 22 | 23 | 24 | let maze = [[0, 0, 0, 1], 25 | [0, 1, 0, 1], 26 | [0, 1, 0, 0], 27 | [0, 0, 1, 0]] 28 | 29 | 30 | console.log(ratPath(maze)) 31 | /* 32 | [ [ 0, 0 ], 33 | [ 0, 1 ], 34 | [ 0, 2 ], 35 | [ 1, 2 ], 36 | [ 2, 2 ], 37 | [ 2, 3 ], 38 | [ 3, 3 ] ] 39 | */ 40 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/ToeplitzMatrix.js: -------------------------------------------------------------------------------- 1 | function isToeplitz(matrix) { 2 | for(let i = 0; i < matrix.length; i++) { 3 | if(!checkDiagonal(matrix, i, 0)){ 4 | return false; 5 | } 6 | } 7 | 8 | for(let j = matrix.length; j > 0; j--) { 9 | if(!checkDiagonal(matrix, 0, j)) { 10 | return false; 11 | } 12 | } 13 | return true; 14 | } 15 | 16 | 17 | function checkDiagonal(matrix, col, row) { 18 | let element; 19 | while(col < matrix.length && row < matrix.length) { 20 | if (element !== undefined && matrix[row][col] !== element) { 21 | return false; 22 | } 23 | element = matrix[row][col]; 24 | col++; 25 | row++; 26 | } 27 | return true; 28 | } 29 | 30 | // let test = [[3, 2, 1], 31 | // [1, 3, 2], 32 | // [2, 1, 3]]; 33 | // 34 | // console.log(isToeplitz(test)); 35 | 36 | module.exports = isToeplitz; 37 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/Telephone.js: -------------------------------------------------------------------------------- 1 | function Telephone(num) { 2 | let result = []; 3 | let keys = {1: [" "], 4 | 2: ["A", "B", "C"], 5 | 3: ["D", "E", "F"], 6 | 4: ["G", "H", "I"], 7 | 5: ["J", "K", "L"], 8 | 6: ["M", "N", "O"], 9 | 7: ["P", "Q", "R", "S"], 10 | 8: ["T", "U", "V"], 11 | 9: ["W", "X", "Y", "Z"], 12 | 0: [" "]} 13 | 14 | let n = String(num); 15 | 16 | function recurse(substr, depth) { 17 | if(depth >= n.length) { 18 | result.push(substr); 19 | return; 20 | } 21 | for(let i = 0; i < keys[n[depth]].length; i++) { 22 | recurse(substr + keys[n[depth]][i], depth + 1); 23 | } 24 | 25 | } 26 | 27 | recurse("", 0); 28 | 29 | return result; 30 | } 31 | 32 | // console.log(Telephone(3646)); 33 | 34 | module.exports = Telephone; 35 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/RatPath.js: -------------------------------------------------------------------------------- 1 | function ratPath(matrix) { 2 | let path = []; 3 | 4 | function traverse(x, y) { 5 | if(x >= matrix[0].length || y >= matrix.length) { 6 | return; 7 | } 8 | if(x === matrix[0].length - 1 && y === matrix.length - 1) { 9 | path.push([x, y]); 10 | return true; 11 | } 12 | 13 | if(traverse(x + 1, y)) { 14 | path.push([x, y]); 15 | return true; 16 | } 17 | if(traverse(x, y + 1)) { 18 | path.push([x, y]); 19 | return true; 20 | } 21 | } 22 | traverse(0,0); 23 | 24 | return path.reverse(); 25 | } 26 | 27 | // let matrix = [[0, 0], [0, 0]] 28 | 29 | let matrix = [[0, 0, 0, 1], 30 | [0, 1, 0, 1], 31 | [0, 1, 0, 0], 32 | [0, 0, 1, 0]]; 33 | 34 | // Expect 35 | // [[0, 0], [0, 1], [0, 2], [1, 2], [2, 2], [2, 3], [3, 3]] 36 | 37 | 38 | console.log(ratPath(matrix)); 39 | 40 | 41 | module.exports = ratPath; 42 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/SubArraySumK.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subarray-sum-equals-k/submissions/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @param {number} k 6 | * @return {number} 7 | */ 8 | var subarraySum = function(nums, k) { 9 | let numWays = 0; 10 | let currentSum = 0; 11 | let sumsSeen = {}; 12 | 13 | for(let i = 0; i < nums.length; i++) { 14 | let n = nums[i]; 15 | currentSum += n; 16 | if(currentSum === k) { 17 | numWays += 1; 18 | } 19 | if((currentSum - k) in sumsSeen) { 20 | numWays += sumsSeen[currentSum - k]; 21 | } 22 | 23 | if(sumsSeen[currentSum] === undefined) { 24 | sumsSeen[currentSum] = 1; 25 | } else { 26 | sumsSeen[currentSum] += 1; 27 | } 28 | } 29 | return numWays 30 | }; 31 | 32 | // sum = 0; 33 | 34 | // [1, 1, 1] 35 | // f 36 | // s 37 | // 38 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/BooleanMatrix.js: -------------------------------------------------------------------------------- 1 | /* 2 | Find 0’s in Boolean Matrix 3 | Given a matrix with N rows and N columns where elements in the matrix can be either 1 or 0 and each row and column are sorted in ascending order, find the number of 0’s. 4 | 5 | Input: Matrix of elements with values either 0 or 1 6 | Output: An integer which is the count of all 0’s in the matrix 7 | */ 8 | 9 | 10 | function CountOnes(matrix) { 11 | let column = matrix[0].length - 1; 12 | let sum = 0; 13 | for(let row = 0; row < matrix.length; row++){ 14 | while(matrix[row][column] === 1){ 15 | sum += (matrix.length - row); 16 | column--; 17 | } 18 | } 19 | return sum; 20 | } 21 | 22 | // Tests 23 | console.log(CountOnes([[0,0,1],[0,1,1],[1,1,1]])); 24 | // 6 25 | console.log(CountOnes([[1,1,1],[1,1,1],[1,1,1]])); 26 | // 9 27 | console.log(CountOnes([[0,0,1],[0,0,1],[0,0,1]])); 28 | // 3 29 | 30 | module.exports = CountOnes; 31 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/NumberIslands.js: -------------------------------------------------------------------------------- 1 | let test = [[1, 1, 0, 0, 0, 1], 2 | [0, 1, 0, 0, 0, 0], 3 | [1, 1, 0, 0, 0, 1], 4 | [0, 0, 1, 0, 1, 1]] 5 | 6 | 7 | function numberOfIslands(matrix) { 8 | let seen = new Set(); 9 | let islands = 0; 10 | 11 | function recurse(x, y) { 12 | if(x >= matrix.length || y >= matrix[0].length || x < 0 || y < 0 || matrix[x][y] === 0 || seen.has(`${x}.${y}`)) { 13 | return; 14 | } 15 | seen.add(`${x}.${y}`); 16 | recurse(x + 1, y) 17 | recurse(x - 1, y) 18 | recurse(x, y + 1) 19 | recurse(x, y - 1) 20 | } 21 | 22 | for(let i = 0; i < matrix.length; i++) { 23 | for(let j = 0; j < matrix[0].length; j++) { 24 | if(matrix[i][j] === 1 && !seen.has(`${i}.${j}`)) { 25 | recurse(i, j); 26 | islands += 1; 27 | } 28 | } 29 | } 30 | 31 | return islands; 32 | } 33 | 34 | console.log(numberOfIslands(test)); 35 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/CoinChange.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that takes in an amount, and an array of integers 3 | representing the available denominations, return the possible combinations of coins, without repeats 4 | 5 | CoinChange(4, [1, 2, 3]) => 4 or [[1, 1, 1, 1], [1, 1, 2], [1, 3], [2, 2]] 6 | */ 7 | 8 | function CoinChange(target, coins) { 9 | let result = [] 10 | 11 | let change = []; 12 | 13 | function traverseCoins(amount, index){ 14 | if(amount === 0) { 15 | result.push(change.slice()); 16 | return; 17 | } 18 | if(amount < 0) { 19 | return; 20 | } 21 | for(let i = index; i < coins.length; i++){ 22 | change.push(coins[i]); 23 | traverseCoins(amount - coins[i], i); 24 | change.pop(); 25 | } 26 | } 27 | 28 | traverseCoins(target, 0); 29 | return result; 30 | } 31 | 32 | // Test 33 | console.log(CoinChange(4, [1, 2, 3])); 34 | 35 | module.exports = CoinChange; 36 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/Permutations.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/permutations/submissions/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @return {number[][]} 6 | */ 7 | var permute = function(nums) { 8 | let seen = new Set(); 9 | let result = []; 10 | 11 | function addInteger(permutation) { 12 | 13 | if(permutation.length === nums.length) { 14 | result.push(permutation); 15 | return; 16 | } 17 | 18 | for(let i = 0; i < nums.length; i++) { 19 | let currentNum = nums[i]; 20 | if(!seen.has(currentNum)) { 21 | seen.add(currentNum); 22 | let newPermutation = permutation.slice(); 23 | newPermutation.push(currentNum); 24 | addInteger(newPermutation); 25 | seen.delete(currentNum); 26 | } 27 | } 28 | } 29 | 30 | addInteger([]); 31 | return result; 32 | }; 33 | -------------------------------------------------------------------------------- /DataStructures/LinkedLists/DynamicArray.js: -------------------------------------------------------------------------------- 1 | class DynamicArray { 2 | 3 | constructor(){ 4 | this.storage = new Array(8); 5 | this.index = 0; 6 | } 7 | 8 | append(item) { 9 | if(this.index >= this.storage.length) { 10 | let temp = this.storage; 11 | this.index = 0; 12 | this.storage = new Array(this.storage.length * 2); 13 | 14 | while(this.index < temp.length) { 15 | this.storage[this.index] = temp[this.index]; 16 | this.index++; 17 | } 18 | } 19 | this.storage[this.index] = item; 20 | this.index++; 21 | } 22 | } 23 | 24 | // let d = new DynamicArray(); 25 | 26 | // d.append(10); 27 | // d.append(10); 28 | // d.append(10); 29 | // d.append(10); 30 | // d.append(10); 31 | // d.append(10); 32 | // d.append(10); 33 | // d.append(10); 34 | // d.append(10); 35 | // d.append(10); 36 | // d.append(10); 37 | 38 | 39 | // console.log(d.storage) 40 | 41 | module.exports = DynamicArray; 42 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/NumWays.js: -------------------------------------------------------------------------------- 1 | // function ways(total, k) { 2 | // // Write your code here 3 | // function compute(currentNum, subTotal) { 4 | // if(currentNum > k || subTotal < 0) { 5 | // return 0; 6 | // } 7 | // if(subTotal === 0) { 8 | // return 1; 9 | // } 10 | // let result = 0; 11 | // for(let i = currentNum; i <= k; i++) { 12 | // result += compute(i, subTotal - i); 13 | // } 14 | // return result % 1000000007; 15 | // } 16 | 17 | // return compute(1, total); 18 | // } 19 | 20 | function ways(total, k) { 21 | let table = new Array(total + 1).fill(0); 22 | table[0] = 1; 23 | for(let i = 1; i <= k; i++) { 24 | for(let j = i; j <= total; j++) { 25 | let result = (table[j] + table[j - i])%1000000007; 26 | table[j] = result; 27 | } 28 | } 29 | return table[total] 30 | } 31 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/LongestPalindrome.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var longestPalindrome = function(s) { 6 | let letterCounts = {}; 7 | for(let i = 0; i < s.length; i++) { 8 | let char = s[i] 9 | if(letterCounts[char] === undefined) { 10 | letterCounts[char] = 0; 11 | } 12 | letterCounts[char] += 1; 13 | } 14 | 15 | let totalEvens = 0; 16 | let maxOdd = 0; 17 | 18 | for(let c in letterCounts) { 19 | console.log(c) 20 | let charCount = letterCounts[c] 21 | if(charCount % 2 === 0) { 22 | totalEvens += charCount; 23 | } else if(maxOdd === 0 && charCount % 2 === 1){ 24 | maxOdd = charCount; 25 | } else { 26 | totalEvens += (Math.min(maxOdd, charCount) - 1); 27 | maxOdd = Math.max(maxOdd, charCount); 28 | } 29 | } 30 | return totalEvens + maxOdd; 31 | }; 32 | -------------------------------------------------------------------------------- /Other/Archive/OOPArchive/Elevator/Person.js: -------------------------------------------------------------------------------- 1 | class Person { 2 | constructor(name, weight){ 3 | this.name = name; 4 | this.weight = weight; 5 | this.currentfloor; 6 | this.desiredFloor; 7 | this.floorButtons = null; 8 | } 9 | 10 | setCurrentFloor(floorNumber) { 11 | this.currentfloor = floorNumber; 12 | } 13 | setDesiredFloor(floorNumber) { 14 | this.desiredFloor = floorNumber; 15 | } 16 | 17 | setFloorButtons(floorButtons) { 18 | this.floorButtons = floorButtons; 19 | } 20 | // Alternatively, give person access to their current floor, but larger coupling 21 | 22 | pressFloorButton() { 23 | if(!this.floorButtons) { //if they haven't entered the building 24 | return; 25 | } 26 | if(this.currentFloor < this.desiredFloor) { 27 | this.buttons.get('up').turnOnLight(); 28 | } else { 29 | this.buttons.get('down').turnOnLight(); 30 | } 31 | } 32 | } 33 | 34 | module.exports = Person 35 | -------------------------------------------------------------------------------- /DataStructures/N-aryTrees/Copy.js: -------------------------------------------------------------------------------- 1 | class Node { 2 | constructor(value) { 3 | this.value = value; 4 | this.children = {}; //{: } 5 | } 6 | } 7 | 8 | function copyTree(node) { 9 | let copy = new Node(node.value); 10 | for(let key in node.children) { 11 | copy.children[key] = copyTree(node.children[key]); 12 | } 13 | return copy; 14 | } 15 | 16 | let nodeA = new Node("A") 17 | let nodeB = new Node("B") 18 | let nodeC = new Node("C") 19 | let nodeD = new Node("D") 20 | let nodeE = new Node("E") 21 | let nodeF = new Node("F") 22 | let nodeG = new Node("G") 23 | let nodeH = new Node("H") 24 | let nodeI = new Node("I") 25 | 26 | nodeA.children["B"] = nodeB; 27 | nodeA.children["C"] = nodeC; 28 | nodeA.children["D"] = nodeD; 29 | 30 | nodeB.children["E"] = nodeE; 31 | nodeB.children["F"] = nodeF; 32 | 33 | nodeD.children["G"] = nodeG; 34 | nodeD.children["H"] = nodeH; 35 | nodeD.children["I"] = nodeI; 36 | 37 | 38 | console.log(copyTree(nodeA)) 39 | -------------------------------------------------------------------------------- /DataStructures/LinkedLists/Stack.js: -------------------------------------------------------------------------------- 1 | function Stack(size) { 2 | var maxSize = size || 10; 3 | var currentSize = 0; 4 | 5 | var storage = {}; 6 | 7 | //Get properties operations 8 | var operations = {}; 9 | 10 | operations.maxSize = function() { 11 | return maxSize; 12 | }; 13 | 14 | operations.currentSize = function() { 15 | return currentSize; 16 | }; 17 | 18 | operations.storage = function() { 19 | var result = []; 20 | 21 | for(var i = 0; i < currentSize; i++){ 22 | result.push(storage[i]); 23 | } 24 | return result; 25 | }; 26 | 27 | this.get = function(keyword) { 28 | return operations[keyword](); 29 | }; 30 | 31 | //Adding/Removing Items 32 | 33 | this.addItem = function(item){ 34 | storage[currentSize] = item; 35 | currentSize++; 36 | }; 37 | 38 | this.removeItem = function(){ 39 | if(currentSize <= 0) return "" 40 | 41 | delete(storage[currentSize - 1]); 42 | currentSize--; 43 | }; 44 | 45 | 46 | } 47 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/ReverseCoinChange.js: -------------------------------------------------------------------------------- 1 | // Repl: https://repl.it/repls/YearlyFearlessQbasic 2 | // Given a set of ways to break down values, return the valid set of coins 3 | // that can produce that result 4 | 5 | function reverseCoin(inputTable) { 6 | let rebuildTable = new Array(inputTable.length).fill(0); 7 | rebuildTable[0] = 1; 8 | let solutionCoins = []; 9 | 10 | for(let coin = 0; coin < rebuildTable.length; coin++) { 11 | if(inputTable[coin] > rebuildTable[coin]) { 12 | let copy = rebuildTable.slice(); 13 | for(let amountToBreak = coin; amountToBreak < rebuildTable.length; amountToBreak++) { 14 | rebuildTable[amountToBreak] += rebuildTable[amountToBreak - coin]; 15 | } 16 | solutionCoins.push(coin); 17 | } 18 | 19 | if(inputTable[coin] != rebuildTable[coin]) { 20 | return []; 21 | } 22 | } 23 | return solutionCoins; 24 | } 25 | 26 | console.log(reverseCoin([1, 1, 1, 2, 2, 1])); 27 | reverseCoin([1,0,1,0,1,1,2,1,2,1,3]); 28 | -------------------------------------------------------------------------------- /Other/Archive/staticNeuralNetwork/referenceTest.js: -------------------------------------------------------------------------------- 1 | //An experiment in JavaScript Assignment 2 | 3 | //Assigning b to an index of a 4 | var a = [1, 2, 3, 4]; 5 | var b = a[0]; 6 | console.log(b); //1 7 | a[0] = 9; 8 | console.log(b) //1 9 | 10 | //So 'b' does not update when 'a' is changed; 11 | 12 | //Assigning indices of a to variables b->d 13 | var b = 1; 14 | var c = 2; 15 | var d = 3; 16 | 17 | var a = []; 18 | 19 | a[0] = b; 20 | a[1] = c; 21 | a[2] = d; 22 | 23 | console.log(a[0]); 24 | b = 9; 25 | console.log(a[0]) 26 | 27 | //The reverse direction of assignment doesn't work either 28 | 29 | 30 | 31 | //Solution 32 | //Create an object that stores those values 33 | function createNode(n){ 34 | this.val = n; 35 | } 36 | 37 | 38 | 39 | var b = new createNode(1); 40 | var c = new createNode(2); 41 | var d = new createNode(3); 42 | 43 | var a = []; 44 | 45 | a[0] = b; 46 | a[1] = c; 47 | a[2] = d; 48 | 49 | console.log(a[0].val); 50 | 51 | b.val = 9; 52 | 53 | console.log(a[0].val) 54 | 55 | -------------------------------------------------------------------------------- /DataStructures/BinaryTrees/BinaryTree.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | class Node { 3 | constructor(val){ 4 | this.val = val; 5 | this.leftChild = null; 6 | this.rightChild = null; 7 | } 8 | } 9 | 10 | class BinarySearchTree { 11 | constructor(){ 12 | this.root = null; 13 | } 14 | 15 | addChild(val){ 16 | let tree = this; 17 | let newNode = new Node(val); 18 | 19 | function recurse(node){ 20 | if(tree.root === null){ 21 | tree.root = newNode; 22 | } else { 23 | if(val < node.val){ 24 | if(node.leftChild === null){ 25 | node.leftChild = newNode; 26 | } else { 27 | recurse(node.leftChild); 28 | } 29 | } else { 30 | if(node.rightChild === null){ 31 | node.rightChild = newNode; 32 | } else { 33 | recurse(node.rightChild); 34 | } 35 | } 36 | } 37 | } 38 | recurse(tree.root) 39 | } 40 | contains(val){ 41 | 42 | } 43 | } 44 | 45 | -------------------------------------------------------------------------------- /DataStructures/BinaryTrees/BinaryTreePaths.js: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/binary-tree-paths/submissions/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * function TreeNode(val) { 6 | * this.val = val; 7 | * this.left = this.right = null; 8 | * } 9 | */ 10 | /** 11 | * @param {TreeNode} root 12 | * @return {string[]} 13 | */ 14 | var binaryTreePaths = function(root) { 15 | let paths = []; 16 | let currentPath = []; 17 | 18 | function dfs(node) { 19 | if (node == null) { 20 | return; 21 | } 22 | currentPath.push(node.val) 23 | if(node.left === null && node.right === null) { 24 | paths.push(generatePath(currentPath)); 25 | } 26 | dfs(node.left); 27 | dfs(node.right); 28 | currentPath.pop(); 29 | } 30 | 31 | dfs(root); 32 | 33 | return paths; 34 | }; 35 | 36 | function generatePath(arr) { 37 | return arr.join("->") 38 | } 39 | 40 | // console.log(generatePath([1, 2, 3])) 41 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/LargestRectangleHistogramII.js: -------------------------------------------------------------------------------- 1 | function findLargestRectangle(hist) { 2 | var h, pos, tempH, tempPos, tempSize = 0, maxSize = 0 3 | var hStack = [], pStack = [] 4 | 5 | for(pos = 0; pos < hist.length; pos++) { 6 | h = hist[pos] 7 | if(hStack.length === 0 || h > hStack[hStack.length - 1]) { 8 | hStack.push(h); pStack.push(pos); 9 | } else if(h < hStack[hStack.length - 1]) { 10 | while(hStack.length && h < hStack[hStack.length - 1]) { 11 | tempH = hStack.pop(); 12 | tempPos = pStack.pop(); 13 | tempSize = tempH * (pos - tempPos) 14 | maxSize = Math.max(tempSize, maxSize); 15 | } 16 | hStack.push(h); 17 | pStack.push(tempPos) 18 | } 19 | } 20 | while(hStack.length) { 21 | tempH = hStack.pop(); 22 | tempPos = pStack.pop(); 23 | tempSize = tempH * (pos - tempPos) 24 | maxSize = Math.max(tempSize, maxSize); 25 | } 26 | return maxSize 27 | } 28 | 29 | console.log(findLargestRectangle([5, 2])) 30 | -------------------------------------------------------------------------------- /DataStructures/BinaryTrees/PureRecursionTrees.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.left = null; 5 | this.right = null; 6 | } 7 | } 8 | 9 | 10 | let root1 = new TreeNode(1) 11 | root1.left = new TreeNode(3) 12 | root1.right = new TreeNode(2) 13 | root1.left.left = new TreeNode(5) 14 | root1.left.left.right = new TreeNode(1) 15 | 16 | 17 | let root2 = new TreeNode(2) 18 | root2.left = new TreeNode(1) 19 | root2.right = new TreeNode(3) 20 | root2.left.right = new TreeNode(4) 21 | root2.right.right = new TreeNode(7) 22 | 23 | function traverseTree(node, callback) { 24 | if(node === null) { 25 | return null; 26 | } 27 | callback(node); 28 | traverseTree(node.left, callback) 29 | traverseTree(node.right, callback) 30 | return node; 31 | 32 | } 33 | 34 | function swap(node) { 35 | [node.left, node.right] = [node.right, node.left] 36 | } 37 | 38 | traverseTree(root3, swap) 39 | 40 | traverseTree(root3, function(node) { 41 | console.log(node.val) 42 | }) 43 | -------------------------------------------------------------------------------- /Other/assets/clean.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | prompt: (input) => { 5 | const rawInput = input.split('\n'); 6 | let write = true; 7 | let results = []; 8 | 9 | rawInput.forEach((line) => { 10 | if (line.indexOf('{{{') > -1) { 11 | write = false; 12 | } else if (line.indexOf('---') > -1 || line.indexOf('}}}') > -1 ){ 13 | write = true; 14 | } else if (write) { 15 | results.push(line); 16 | } 17 | }); 18 | 19 | return results.join('\n'); 20 | }, 21 | solution: (input) => { 22 | const rawInput = input.split('\n'); 23 | let write = true; 24 | let results = []; 25 | 26 | rawInput.forEach((line) => { 27 | if (line.indexOf('---') > -1) { 28 | write = false; 29 | } else if (line.indexOf('{{{') > -1 || line.indexOf('}}}') > -1 ){ 30 | write = true; 31 | } else if (write) { 32 | results.push(line); 33 | } 34 | }); 35 | 36 | return results.join('\n'); 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/MergeIntervals2.js: -------------------------------------------------------------------------------- 1 | function mergeInterval(intervals, rangeToAdd) { 2 | let result = []; 3 | 4 | for(let i = 0; i < intervals.length; i++) { 5 | if(overlap(intervals[i], rangeToAdd)) { 6 | rangeToAdd = merge(intervals[i], rangeToAdd); 7 | } else if(rangeToAdd[0] < intervals[i][0]) { 8 | result.push(rangeToAdd); 9 | result.concat(intervals.slice(i, intervals.length)); 10 | return result; 11 | } else { 12 | result.push(intervals[i]); 13 | } 14 | } 15 | 16 | result.push(rangeToAdd); 17 | return result; 18 | } 19 | 20 | function overlap(i1, i2) { 21 | if(i1[0] >= i2[0] && i1[0] <= i2[1]) { 22 | return true; 23 | } 24 | if(i2[0] >= i1[0] && i2[0] <= i1[1]) { 25 | return true; 26 | } 27 | return false; 28 | } 29 | 30 | function merge(i1, i2) { 31 | return [Math.min(i1[0], i2[0]), Math.max(i1[1], i2[1])] 32 | } 33 | 34 | 35 | console.log(mergeInterval([[0, 1], [2, 3], [4, 5]], [0, 4] )) 36 | 37 | // console.log(overlap([0, 1], [6, 7])) 38 | -------------------------------------------------------------------------------- /Other/MachineLearning/GoogleTutorial/iris.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from sklearn.datasets import load_iris 3 | from sklearn import tree 4 | iris = load_iris() 5 | test_idx = [0, 50, 100] 6 | 7 | # training data 8 | train_target = np.delete(iris.target, test_idx) 9 | train_data = np.delete(iris.data, test_idx, axis=0) 10 | 11 | # testing data 12 | test_target = iris.target[test_idx] 13 | test_data = iris.data[test_idx] 14 | 15 | clf = tree.DecisionTreeClassifier() 16 | clf.fit(train_data, train_target) 17 | 18 | 19 | print test_target 20 | print clf.predict(test_data) 21 | 22 | # viz code 23 | from sklearn.externals.six import StringIO 24 | import pydot 25 | dot_data = StringIO() 26 | tree.export_graphviz(clf, out_file=dot_data, 27 | feature_names=iris.feature_names, 28 | class_names=iris.target_names, 29 | filled=True, rounded=True, 30 | impurity=False) 31 | graph = pydot.graph_from_dot_data(dot_data.getvalue()) 32 | graph.write_pdf("iris.pdf") 33 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/NthSmallestMissing.js: -------------------------------------------------------------------------------- 1 | function nthSmallestMissing(arr, n) { 2 | let start = 0; 3 | let end = arr.length; 4 | let mid = Math.floor((end + start)/2); 5 | let numsMissingToLeft = (arr[mid] - arr[start]) - (mid - start);; 6 | 7 | while(start < end - 1) { 8 | if(numsMissingToLeft >= n) { 9 | end = mid; 10 | mid = Math.floor((end + start)/2) 11 | numsMissingToLeft -= (arr[end] - arr[mid]) - (end - mid); 12 | } else { 13 | start = mid; 14 | mid = Math.floor((end + start)/2) 15 | numsMissingToLeft += (arr[mid] - arr[start]) - (mid - start); 16 | } 17 | } 18 | 19 | return arr[mid] + (n - numsMissingToLeft); 20 | } 21 | 22 | /* 23 | numsMissingToLeft = 4 24 | start = 1 25 | end = 2 26 | mid = 1 27 | 28 | n = 5 29 | 30 | */ 31 | 32 | // nthSmallestMissing([3, 8, 9, 10, 12, 15], 5); 33 | // nthSmallestMissing([1, 2, 3, 4, 5, 6, 8, 12, 15], 4); 34 | nthSmallestMissing([100, 101, 103, 201], 90) 35 | 36 | 37 | 38 | // 4, 5, 6, 7, 9, 10, 11, 13, 14 39 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/LargestPrimeFactor.js: -------------------------------------------------------------------------------- 1 | //Largest Prime Factor 2 | //Find the largest prime factor of a given input 3 | 4 | //largestPrimeFactor(2) --> 2 5 | //largestPrimeFactor(20) --> 5 6 | //largestPrimeFactor(21) --> 7 7 | 8 | //Iterative Solution 9 | function largestPrimeFactor(num) { 10 | 11 | var subNum = num; 12 | var test = 2; 13 | 14 | while(subNum > 1){ 15 | subNum % test === 0? subNum = subNum/test : test++; 16 | } 17 | 18 | return test; 19 | } 20 | 21 | largestPrimeFactor(600851475143); 22 | 23 | //Recursive Solution 24 | //Note: May exceed maximum call stack size for large numbers 25 | 26 | // function largestPrimeFactor(num) { 27 | 28 | // function recurse(subNum, test){ 29 | // if(subNum === 1){ 30 | // return test; 31 | // } 32 | // if(subNum % test === 0){ 33 | // return recurse(subNum/test, test); 34 | // } 35 | // if(subNum % test !== 0){ 36 | // return recurse(subNum, test + 1); 37 | // } 38 | // } 39 | 40 | // return recurse(num, 2); 41 | // } 42 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/AnagramPalindrome.js: -------------------------------------------------------------------------------- 1 | var anagramPalindrome = function(word) { 2 | // you code here 3 | // Count number of occurrences of each letter 4 | // if they are all even number of occurrences 5 | // or if one letter has an odd number of occurrences 6 | //return true 7 | //else return false 8 | 9 | var dic = {}; 10 | var oddCount = 0; 11 | var letter; 12 | 13 | for(var i = 0; i < word.length; i++){ 14 | letter = word[i]; 15 | 16 | if(!dic[letter]){ 17 | dic[letter] = 1; 18 | } else { 19 | dic[letter] += 1; 20 | } 21 | } 22 | 23 | for(var letter in dic){ 24 | if(dic[letter] % 2 === 1){ 25 | oddCount++; 26 | } 27 | } 28 | 29 | if(oddCount > 1){ 30 | return false; 31 | } 32 | return true; 33 | 34 | 35 | }; 36 | 37 | console.log(anagramPalindrome("carrace")); // true 38 | console.log(anagramPalindrome("cutoo")); // false 39 | console.log(anagramPalindrome("dddaayyy")); // false 40 | console.log(anagramPalindrome("ddddaaayyyy")); // true 41 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/LongestNonRepeatingSubstringEfficient.js: -------------------------------------------------------------------------------- 1 | 2 | // Returns the max Length 3 | function longestNonRepeatingSubstring(str) { 4 | let maxLength = 0; 5 | let slow = 0; 6 | let chars = {}; 7 | 8 | for(let i = 0; i < str.length; i++) { 9 | if(str[i] in chars && slow <= chars[str[i]]) { 10 | slow = chars[str[i]] + 1 11 | } else { 12 | maxLength = Math.max(maxLength, i - slow + 1); 13 | } 14 | chars[str[i]] = i 15 | } 16 | return maxLength; 17 | } 18 | 19 | // Returns the actual slice of the string 20 | function longestNonRepeatingSubstring(str) { 21 | let window = [0, 0]; 22 | let slow = 0; 23 | let chars = {}; 24 | 25 | for(let fast = 0; fast <= str.length; fast++) { 26 | if(str[fast] in chars && slow <= chars[str[fast]]) { 27 | slow = chars[str[fast]] + 1 28 | } else if((fast - slow) > (window[1] - window[0])) { 29 | window = [slow, fast] 30 | } 31 | chars[str[fast]] = fast 32 | } 33 | return str.slice(window[0], window[1]); 34 | } 35 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/BinarySearch.js: -------------------------------------------------------------------------------- 1 | function binarySearch(arr, target) { 2 | let start = 0; 3 | let end = arr.length; 4 | let counter = 0; 5 | 6 | while(start <= end) { 7 | // console.log('entered the loop ' + counter + ' times' ) 8 | counter++ 9 | let mid = Math.floor((start + end) / 2); 10 | if (arr[mid] === target) return mid; 11 | if (target > arr[mid]) start = mid + 1; 12 | else end = mid - 1; 13 | } 14 | return -1; 15 | } 16 | 17 | 18 | // console.log(binarySearch([1, 3, 6, 7, 8, 10, 19, 23, 30, 32, 49, 50, 56, 60, 78, 85], 2)); 19 | // //List of tests 20 | // var tests = [ 21 | // binarySearch([1], 1) === 0, 22 | // binarySearch([1, 2, 3], 2) === 1, 23 | // binarySearch([1, 2, 3, 4, 5], 4) === 3, 24 | // binarySearch([4, 5, 7], 1) === -1, 25 | // binarySearch([], 10) === -1, 26 | // binarySearch([1, 2, 3, 4], 3) === 2 27 | // ]; 28 | // tests.forEach(function(item){ 29 | // console.log(item); 30 | // }); 31 | 32 | module.exports = binarySearch; 33 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/LargestRectangleHistogramI.js: -------------------------------------------------------------------------------- 1 | function largestHistogram(hist) { 2 | let stack = [] 3 | let maxArea = 0; 4 | let top; 5 | let areaWithTop; 6 | 7 | let i = 0; 8 | 9 | while(i < hist.length) { 10 | 11 | if(stack.length === 0 || hist[stack[stack.length - 1]] <= hist[i]) { 12 | stack.push(i); 13 | i = i + 1 14 | } 15 | else { 16 | 17 | top = stack[stack.length - 1] 18 | 19 | stack.pop(); 20 | 21 | areaWithTop = hist[top] * (stack.length === 0 ? i : i - stack[stack.length - 1] - 1) 22 | if(areaWithTop > maxArea) { 23 | maxArea = areaWithTop 24 | } 25 | } 26 | } 27 | 28 | while(stack.length !== 0) { 29 | top = stack[stack.length - 1] 30 | stack.pop(); 31 | areaWithTop = hist[top] * (stack.length === 0 ? i : i - stack[stack.length - 1] - 1) 32 | if(areaWithTop > maxArea) { 33 | maxArea = areaWithTop 34 | } 35 | } 36 | 37 | return maxArea 38 | } 39 | 40 | console.log(largestHistogram([6, 2, 5, 4, 5, 1, 6])) 41 | // => 12 42 | -------------------------------------------------------------------------------- /DataStructures/LinkedLists/ReverseLinkedListRecursive.js: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | constructor(value) { 3 | this.value = value; 4 | this.next = null; 5 | } 6 | } 7 | 8 | let a = new ListNode(1) 9 | let b = new ListNode(3) 10 | let c = new ListNode(5) 11 | let d = new ListNode(7) 12 | 13 | a.next = b 14 | b.next = c 15 | c.next = d 16 | 17 | function printForward(node) { 18 | let current = node; 19 | while(current) { 20 | console.log(current.value) 21 | current = current.next 22 | } 23 | } 24 | 25 | // printForward(a) 26 | 27 | function reverseLinkedList(node) { 28 | let newHead; 29 | 30 | function recurse(current) { 31 | if(current.next === null) { 32 | newHead = current; 33 | return current; 34 | } 35 | let prev = recurse(current.next); 36 | prev.next = current 37 | 38 | if(current === node) { 39 | current.next = null; 40 | } 41 | return current; 42 | } 43 | recurse(node) 44 | return newHead; 45 | } 46 | 47 | 48 | 49 | // let test = 50 | reverseLinkedList(a) 51 | 52 | console.log(d) 53 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/RainWater.js: -------------------------------------------------------------------------------- 1 | function rainWater(arr) { 2 | let result = 0; 3 | let globalMax = 0; 4 | let globalMaxIndex = 0; 5 | 6 | // Find the global Max and its index 7 | for(let i = 0; i < arr.length; i++) { 8 | if(arr[i] > globalMax) { 9 | globalMax = arr[i]; 10 | globalMaxIndex = i; 11 | } 12 | } 13 | 14 | // Loop from the left side to the global max 15 | let leftMax = arr[0]; 16 | for(let i = 0; i < globalMaxIndex; i++){ 17 | if(arr[i] >= leftMax) { 18 | leftMax = arr[i]; 19 | } else { 20 | result = result + (leftMax - arr[i]); 21 | } 22 | } 23 | 24 | // Loop from the right side to the global max 25 | let rightMax = arr[arr.length - 1]; 26 | for(let j = arr.length - 1; j > globalMaxIndex; j--) { 27 | if(arr[j] >= rightMax) { 28 | rightMax = arr[j]; 29 | } else { 30 | result = result + (rightMax - arr[j]); 31 | } 32 | } 33 | 34 | return result; 35 | } 36 | 37 | // console.log(rainWater([1, 5, 0, 5, 3, 0])) 38 | 39 | module.exports = rainWater; 40 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/NumberIslands2.js: -------------------------------------------------------------------------------- 1 | let test = [[1, 1, 0, 0, 0, 1], 2 | [0, 1, 0, 0, 0, 0], 3 | [1, 1, 0, 0, 0, 1], 4 | [0, 0, 1, 0, 1, 1]] 5 | 6 | function numberOfIslandsDiagonals(matrix) { 7 | let seen = new Set(); 8 | let islands = 0; 9 | 10 | function recurse(x, y) { 11 | if(x >= matrix.length || y >= matrix[0].length || x < 0 || y < 0 || matrix[x][y] === 0 || seen.has(`${x}.${y}`)) { 12 | return; 13 | } 14 | seen.add(`${x}.${y}`); 15 | recurse(x + 1, y) 16 | recurse(x - 1, y) 17 | recurse(x, y + 1) 18 | recurse(x, y - 1) 19 | recurse(x + 1, y + 1) 20 | recurse(x + 1, y - 1) 21 | recurse(x - 1, y + 1) 22 | recurse(x - 1, y - 1) 23 | } 24 | 25 | for(let i = 0; i < matrix.length; i++) { 26 | for(let j = 0; j < matrix[0].length; j++) { 27 | if(matrix[i][j] === 1 && !seen.has(`${i}.${j}`)) { 28 | recurse(i, j); 29 | islands += 1; 30 | } 31 | } 32 | } 33 | 34 | return islands; 35 | } 36 | 37 | console.log(numberOfIslandsDiagonals(test)); 38 | -------------------------------------------------------------------------------- /DataStructures/UnionFind/QuickFind.js: -------------------------------------------------------------------------------- 1 | 2 | class QuickFind { 3 | // Eager Approach 4 | constructor(size) { 5 | this.ids = []; 6 | for(let i = 0; i < size; i++) { 7 | this.ids.push(i); 8 | } 9 | } 10 | 11 | union(id1, id2) { 12 | let root1 = this.ids[id1] 13 | let root2 = this.ids[id2] 14 | for(let i = 0; i < this.ids.length; i++) { 15 | if(this.ids[i] === root1) { 16 | this.ids[i] = root2; 17 | } 18 | } 19 | } 20 | 21 | connected(id1, id2) { 22 | return this.ids[id1] === this.ids[id2] 23 | } 24 | } 25 | 26 | let u = new QuickFind(10); 27 | 28 | u.union(4, 3) 29 | u.union(3, 8) 30 | u.union(6, 5) 31 | u.union(5, 8) 32 | u.union(0, 1) 33 | u.union(1, 8) 34 | u.union(9, 2) 35 | u.union(2, 4) 36 | 37 | 38 | console.log(u) 39 | 40 | 41 | 42 | 43 | /* 44 | 45 | "Is Connected To" is an equivalence relation 46 | 47 | Reflexive: p is connected to p 48 | Symmetric: If p is connected to q, then q is connected to p 49 | Transitive: If p is connected to q, and q is connected to r, 50 | then p is connected to r 51 | */ 52 | -------------------------------------------------------------------------------- /AlgorithmProblems/Sorting/Quickselect.js: -------------------------------------------------------------------------------- 1 | /* 2 | wall = 0 3 | pivot = 5 4 | end = 5 5 | start = 0 6 | current = 0 7 | k = 1 8 | 9 | [3, 1, 6, 4, 9, 8] 10 | p 11 | c 12 | w 13 | */ 14 | 15 | 16 | function Quickselect(arr, k) { 17 | let kthLargest; 18 | 19 | function recurse(start, end) { 20 | if(start > end) return; 21 | 22 | let pivot = end; 23 | let wall = start; 24 | let current = start; 25 | 26 | for(current; current < end; current++) { 27 | if(arr[current] < arr[pivot]) { 28 | [arr[current], arr[wall]] = [arr[wall], arr[current]]; 29 | wall++; 30 | } 31 | } 32 | 33 | [arr[pivot], arr[wall]] = [arr[wall], arr[pivot]]; 34 | 35 | if(wall === (arr.length - k)) { 36 | kthLargest = arr[wall]; 37 | return; 38 | } 39 | 40 | if(wall > (arr.length - k)) { 41 | recurse(start, wall - 1); 42 | } else { 43 | recurse(wall + 1, end); 44 | } 45 | } 46 | 47 | recurse(0, arr.length - 1); 48 | return kthLargest; 49 | } 50 | 51 | console.log(Quickselect([3, 1, 6, 4, 9, 8], 5)) 52 | -------------------------------------------------------------------------------- /DataStructures/Graphs/GraphIsTree.js: -------------------------------------------------------------------------------- 1 | const Vertex = require('./DataStructures/Graphs/Vertex'); 2 | 3 | function graphIsTree(vertex) { 4 | let seen = new Set(); 5 | let queue = []; 6 | let count; 7 | 8 | seen.add(vertex.value); 9 | queue.push(vertex); 10 | 11 | while(queue.length > 0) { 12 | let current = queue.shift(); 13 | count = 0; 14 | 15 | for(let v in current.edges) { 16 | if(seen.has(v)) { 17 | count++; 18 | } 19 | if(count > 1) { 20 | return false; 21 | } 22 | if(!seen.has(v)) { 23 | seen.add(v); 24 | queue.push(current.edges[v]); 25 | } 26 | } 27 | } 28 | return true; 29 | } 30 | 31 | let a = new Vertex('a'); 32 | let b = new Vertex('b'); 33 | let c = new Vertex('c'); 34 | let d = new Vertex('d'); 35 | 36 | a.edges['b'] = b; 37 | a.edges['c'] = c; 38 | 39 | 40 | b.edges['a'] = a; 41 | // b.edges['c'] = c; 42 | // b.edges['d'] = d; 43 | 44 | c.edges['a'] = a; 45 | // c.edges['b'] = b; 46 | // c.edges['d'] = d; 47 | 48 | // d.edges['c'] = c; 49 | // d.edges['b'] = b; 50 | 51 | console.log(graphIsTree(a)); 52 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/URLTree.js: -------------------------------------------------------------------------------- 1 | let alist = ['/home/anti/xanax', 2 | '/home/heart/lipitor', 3 | '/home/heart/atova' 4 | ] 5 | 6 | function createTree(paths) { 7 | paths = paths.map(url => { 8 | return url.split("/"); 9 | }) 10 | 11 | let tree = {}; 12 | 13 | for(let i = 0; i < paths.length; i++) { 14 | let path = paths[i]; 15 | let subdirectory = tree; 16 | 17 | for(let j = 1; j < path.length; j++) { 18 | let nextFolder = path[j]; 19 | if(!(nextFolder in subdirectory)) { 20 | subdirectory[nextFolder] = {}; 21 | } 22 | subdirectory = subdirectory[nextFolder] 23 | } 24 | } 25 | 26 | return tree; 27 | } 28 | 29 | function printTree(root) { 30 | 31 | function printNode(node, depth) { 32 | for(let subdirectory in node) { 33 | let whitespace = " "; 34 | whitespace = whitespace.repeat(depth); 35 | console.log(`${whitespace}- ${subdirectory}`); 36 | printNode(node[subdirectory], depth + 2) 37 | } 38 | } 39 | 40 | printNode(root, 0); 41 | } 42 | 43 | printTree(createTree(alist)) 44 | -------------------------------------------------------------------------------- /DataStructures/UnionFind/WeightedQuickUnion.js: -------------------------------------------------------------------------------- 1 | class WQU { 2 | constructor(size) { 3 | this.ids = []; 4 | this.sizes = []; 5 | for(let i = 0; i < size; i++) { 6 | this.ids.push(i); 7 | this.sizes.push(1); 8 | } 9 | } 10 | 11 | root(id) { 12 | while(this.ids[id] !== id) { 13 | this.ids[id] = this.ids[this.ids[id]]; //Path Compression Piece 14 | id = this.ids[id]; 15 | } 16 | return id; 17 | } 18 | 19 | 20 | union(id1, id2) { 21 | let root1 = this.root(id1) 22 | let root2 = this.root(id2) 23 | if(root1 === root2) { 24 | return; 25 | } 26 | if(this.sizes[root1] < this.sizes[root2]) { 27 | this.ids[root1] = root2; 28 | this.sizes[root2] += this.sizes[root1]; 29 | } else { 30 | this.ids[root2] = root1; 31 | this.sizes[root1] += this.sizes[root2]; 32 | } 33 | } 34 | 35 | connected(id1, id2) { 36 | return this.root(id1) === this.root(id2); 37 | } 38 | 39 | } 40 | 41 | 42 | let wqu = new WQU(10); 43 | 44 | wqu.union(1, 2) 45 | wqu.union(3, 4) 46 | wqu.union(3, 5) 47 | wqu.union(2, 3) 48 | 49 | console.log(wqu) 50 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/AddLarge.js: -------------------------------------------------------------------------------- 1 | function addLarge(str1, str2) { 2 | let result = ""; 3 | let smallIndex = Math.min(str1.length, str2.length); 4 | let largeIndex = Math.max(str1.length, str2.length); 5 | 6 | let newStr1 = str1.split("").reverse().join("") 7 | let newStr2 = str2.split("").reverse().join("") 8 | 9 | let longString; 10 | 11 | if(newStr1 > newStr2) { 12 | longString = newStr1; 13 | } else { 14 | longString = newStr2; 15 | } 16 | 17 | let carry = 0; 18 | 19 | for(let i = 0; i < smallIndex; i++){ 20 | let sum = Number(newStr1[i]) + Number(newStr2[i]) + carry; 21 | if(sum >= 10) { 22 | carry = 1; 23 | } else { 24 | carry = 0; 25 | } 26 | result += sum % 10 27 | } 28 | 29 | for(let i = smallIndex; i < largeIndex; i++) { 30 | let sum = Number(longString[i]) + carry 31 | if(sum >= 10) { 32 | carry = 1; 33 | } else { 34 | carry = 0; 35 | } 36 | result += sum % 10 37 | } 38 | 39 | if(carry) { 40 | result += 1; 41 | } 42 | 43 | return result.split("").reverse().join("") 44 | } 45 | 46 | console.log(addLarge("99999999", "1000")) 47 | -------------------------------------------------------------------------------- /Other/Archive/OOPArchive/Elevator/Queue.js: -------------------------------------------------------------------------------- 1 | let ListNode = require("./ListNode"); 2 | 3 | class Queue { 4 | 5 | constructor() { 6 | this.head = new ListNode(-Infinity); 7 | this.tail = new ListNode(Infinity); // this way we always have nodes 8 | this.head.next = this.tail; 9 | this.tail.prev = this.head; 10 | } 11 | 12 | // Some Code Duplication here 13 | insertFromFront(floorNumber) { 14 | let current = this.head; 15 | while(current.val < floorNumber) { 16 | current = current.next; 17 | } 18 | if(current.val === floorNumber) { 19 | return false; 20 | } 21 | let newNode = new ListNode(floorNumber); 22 | current.prev.next = newNode; 23 | current.prev = newNode; 24 | } 25 | 26 | insertFromBack(floorNumber) { 27 | let current = this.tail; 28 | while(current.val > floorNumber) { 29 | current = current.prev; 30 | } 31 | if(current.val === floorNumber) { 32 | return false; 33 | } 34 | let newNode = new ListNode(floorNumber); 35 | current.next.prev = newNode; 36 | current.next = newNode; 37 | } 38 | } 39 | 40 | module.exports = Queue; 41 | -------------------------------------------------------------------------------- /DataStructures/BinaryTrees/IsBST.js: -------------------------------------------------------------------------------- 1 | // let test = require('./BSTNode') 2 | class TreeNode { 3 | constructor(val){ 4 | this.val = val; 5 | this.left = null; 6 | this.right = null; 7 | } 8 | } 9 | 10 | function isBST(root) { 11 | let result = true; 12 | 13 | function helper(node, min, max) { 14 | if(node === null) { 15 | return; 16 | } 17 | 18 | if(node.val <= min || node.val >= max) { 19 | result = false; 20 | return; 21 | } 22 | 23 | helper(node.left, min, node.val); 24 | helper(node.right, node.val, max); 25 | 26 | } 27 | 28 | helper(root, -Infinity, Infinity); 29 | 30 | return result; 31 | } 32 | 33 | 34 | let node4 = new TreeNode(4) 35 | let node2 = new TreeNode(2) 36 | let node6 = new TreeNode(6) 37 | let node1 = new TreeNode(1) 38 | let node3 = new TreeNode(3) 39 | let node5 = new TreeNode(5) 40 | let node7 = new TreeNode(7) 41 | 42 | node4.left = node2; 43 | node4.right = node6; 44 | node2.left = node1; 45 | node2.right = node3; 46 | node6.left = node5; 47 | node6.right = node7; 48 | 49 | // let node8 = new TreeNode(8); 50 | 51 | 52 | 53 | 54 | console.log(isBST(node4)); 55 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/SpiralMatrix.js: -------------------------------------------------------------------------------- 1 | function spiralMatrix(n) { 2 | let matrix = []; 3 | for(let i = 0; i < n; i++) { 4 | matrix.push(new Array(n).fill(0)); 5 | } 6 | 7 | let topRow = 0; 8 | let rightColumn = n - 1; 9 | let bottomRow = n - 1; 10 | let leftColumn = 0; 11 | 12 | let currentNumber = 1; 13 | 14 | while(topRow <= bottomRow && leftColumn <= rightColumn) { 15 | for(let i = leftColumn; i <= rightColumn; i++) { 16 | matrix[topRow][i] = currentNumber; 17 | currentNumber++; 18 | } 19 | topRow++; 20 | 21 | for(let i = topRow; i <= bottomRow; i++) { 22 | matrix[i][rightColumn] = currentNumber; 23 | currentNumber++; 24 | } 25 | 26 | rightColumn--; 27 | 28 | for(let i = rightColumn; i >= leftColumn; i--) { 29 | matrix[bottomRow][i] = currentNumber; 30 | currentNumber++; 31 | } 32 | 33 | bottomRow--; 34 | 35 | for(let i = bottomRow; i >= topRow; i--) { 36 | matrix[i][leftColumn] = currentNumber; 37 | currentNumber++; 38 | } 39 | 40 | leftColumn++; 41 | 42 | } 43 | 44 | return matrix; 45 | } 46 | 47 | console.log(spiralMatrix(3)) 48 | -------------------------------------------------------------------------------- /Other/Archive/Combinations.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | class nChooseK { 5 | 6 | public static ArrayList> combine(int n, int k) { 7 | ArrayList> result = new ArrayList>(); 8 | 9 | if (n <= 0 || n < k) 10 | return result; 11 | 12 | ArrayList item = new ArrayList(); 13 | dfs(n, k, 1, item, result); // because it need to begin from 1 14 | 15 | return result; 16 | } 17 | 18 | private static void dfs(int n, int k, int start, ArrayList item, 19 | ArrayList> result) { 20 | 21 | if (item.size() == k) { 22 | result.add(new ArrayList(item)); 23 | return; 24 | } 25 | 26 | if(start > n) { 27 | return; 28 | } 29 | 30 | 31 | dfs(n, k, start + 1, item, result); 32 | item.add(start); 33 | dfs(n, k, start + 1, item, result); 34 | item.remove(item.size() - 1); 35 | 36 | 37 | } 38 | 39 | } 40 | 41 | class Main { 42 | public static void main(String[] args) { 43 | System.out.println(nChooseK.combine(4,2)); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/LargestIslands.js: -------------------------------------------------------------------------------- 1 | function largestIslands(matrix) { 2 | let result = 0; 3 | let seen = new Set(); 4 | 5 | for(let i = 0; i < matrix.length; i++) { 6 | for(let j = 0; j < matrix[0].length; j++) { 7 | if(matrix[i][j] === 1 && !seen.has(`${i}.${j}`)) { 8 | dfs(i, j); 9 | } 10 | } 11 | } 12 | 13 | function dfs(x, y) { 14 | if(x < 0 || 15 | y < 0 || 16 | x >= matrix.length || 17 | y >= matrix[0].length || 18 | matrix[x][y] === 0 || 19 | seen.has(`${x}.${y}`)) { 20 | return 0; 21 | } 22 | let size = 0; 23 | seen.add(`${x}.${y}`); 24 | size += dfs(x + 1, y); 25 | // size += dfs(x + 1, y + 1); // diagonal 26 | // size += dfs(x + 1, y - 1); // diagonal 27 | size += dfs(x - 1, y); 28 | // size += dfs(x - 1, y - 1); // diagonal 29 | size += dfs(x, y + 1); 30 | // size += dfs(x - 1, y + 1); // diagonal 31 | size += dfs(x, y - 1); 32 | 33 | size += 1; 34 | result = Math.max(result, size); 35 | return size; 36 | } 37 | 38 | console.log(seen) 39 | 40 | return result; 41 | } 42 | 43 | console.log(largestIslands(matrix)) 44 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/ThreeSum.js: -------------------------------------------------------------------------------- 1 | function threeSum(arr) { 2 | arr.sort((a, b) => { 3 | return a - b 4 | }); // O(N * Log(N)) 5 | let resultSet = new Set(); 6 | 7 | console.log(arr) 8 | 9 | for(let i = 0; i < arr.length - 2; i++) { 10 | let current = arr[i]; 11 | let left = i + 1; 12 | let right = arr.length - 1; 13 | 14 | while(left < right) { 15 | let l = arr[left] 16 | let r = arr[right] 17 | let sum = current + l + r; 18 | if(sum === 0) { 19 | resultSet.add(`${current}.${l}.${r}`); 20 | } 21 | if(sum < 0) { 22 | left = left + 1; 23 | } else { 24 | right = right - 1; 25 | } 26 | } 27 | } 28 | 29 | let result = []; 30 | 31 | resultSet.forEach(item => { 32 | let validSum = item.split('.'); 33 | validSum.forEach((num, index) => { 34 | validSum[index] = Number(num); 35 | }) 36 | result.push(validSum); 37 | }) 38 | 39 | return result; 40 | } 41 | 42 | console.log(threeSum([-1,-2,-3,4,1,3,0,3,-2,1,-2,2,-1,1,-5,4,-3])) 43 | 44 | // https://www.geeksforgeeks.org/find-triplets-array-whose-sum-equal-zero/ 45 | // https://leetcode.com/problems/3sum/ 46 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/PermuteArray.js: -------------------------------------------------------------------------------- 1 | function permuteArray(arr){ 2 | var result = []; 3 | 4 | for(var i = 0; i < arr.length; i++){ 5 | if(result.length === 0){ 6 | // If there is nothing in the result array, just push in first element 7 | result.push([arr[i]]); 8 | } else { 9 | // Create a temporary array 10 | var temp = []; 11 | 12 | // Loop through each permuted array in the results array 13 | for(var j = 0; j < result.length; j++){ 14 | 15 | // Place the letter at index i in the original Array 16 | // at every location 17 | for(var k = 0; k <= result[j].length; k++){ 18 | 19 | // Creates a copy of the permuted array result[j] 20 | var newPermutation = result[j].slice() 21 | 22 | // Splice inserts character arr[i] at index k in the newPermutation array 23 | newPermutation.splice(k, 0, arr[i]); 24 | 25 | // Append newPermutation to temp 26 | temp.push(newPermutation); 27 | } 28 | } 29 | // Reset result to the temp array 30 | result = temp; 31 | } 32 | } 33 | return result; 34 | } 35 | 36 | console.log(permuteArray([1, 2, 3, 4])) 37 | -------------------------------------------------------------------------------- /Other/Archive/OOPArchive/Elevator/Script.md: -------------------------------------------------------------------------------- 1 | # 5 Principles of OOP 2 | 3 | What is OOP and why do we use it? 4 | 5 | It's a way of organizing our information, to make it modular, readable and maintanable. 6 | 7 | It reduces the amount of bugs and refactoring we need to do, and allows us to scale our projects better because it makes it easier to bring new people on and because the codebase will be designed with efficiency in mind 8 | 9 | ## Coupling 10 | 11 | Coupling refers to the level of interdependence between systems 12 | How much do they depend on one another? 13 | When two pieces of software interface, what assumptions do they have to make about each other? 14 | 15 | You want to minimize the amount of coupling between systems to make code more modular. 16 | 17 | ## 5) Inheritance 18 | 19 | ## 4) Polymorphism 20 | Ad Hoc Polymorphism vs Parametric Polymorphism 21 | 22 | ``` 23 | 2 + 2 => 4 24 | 25 | '2' + '2' => '22' 26 | ``` 27 | 28 | 29 | ## 3) Composition 30 | 31 | Bottom up vs top down 32 | 33 | Usually preferable to inheritance patterns 34 | 35 | 36 | ## 2) Encapsulation 37 | 38 | The tool with which we 39 | 40 | ## 1) Abstraction 41 | 42 | Dealing with ideas instead of concretions 43 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/TwoSum.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers and a target, 3 | return the two indices in that array that sum up to the target 4 | If none exist, return -1; 5 | */ 6 | 7 | function twoSum(arr, target) { 8 | let complements = {}; 9 | let result = [-1, -1] 10 | arr.forEach((item, index) => { 11 | if(complements[item] === undefined) { 12 | complements[target - item] = index; 13 | } else { 14 | result[0] = complements[item]; 15 | result[1] = index; 16 | } 17 | }); 18 | return result; 19 | } 20 | 21 | module.exports = twoSum; 22 | 23 | // console.log(twoSum([1, 2, 3, 5, 5], 60)); 24 | 25 | //https://leetcode.com/problems/two-sum/submissions/ 26 | /** 27 | * @param {number[]} nums 28 | * @param {number} target 29 | * @return {number[]} 30 | */ 31 | 32 | /* 33 | 34 | var twoSum = function(nums, target) { 35 | 36 | let complements = {}; 37 | nums.forEach((num, index) => { 38 | complements[target - num] = index; 39 | }) 40 | 41 | for(let i = 0; i < nums.length; i++) { 42 | if(nums[i] in complements && i != complements[nums[i]]) { 43 | return [i, complements[nums[i]]]; 44 | } 45 | } 46 | }; 47 | 48 | 49 | */ 50 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/RatPathGeneral.js: -------------------------------------------------------------------------------- 1 | // General Solution (UP, DOWN, LEFT, RIGHT) 2 | function ratPath2(maze) { 3 | let result; 4 | let path = []; 5 | function findPath(x, y) { 6 | if(x >= maze.length || y >= maze[0].length || x < 0 || y < 0 || maze[x][y] === 1) { 7 | return; 8 | } 9 | path.push([x, y]); 10 | maze[x][y] = 1; 11 | 12 | if(x === maze.length - 1 && y === maze[0].length - 1) { 13 | if(result === undefined || path.length < result.length) { 14 | result = path.slice(); 15 | } 16 | } 17 | findPath(x - 1, y) 18 | findPath(x + 1, y) 19 | findPath(x, y - 1) 20 | findPath(x, y + 1) 21 | path.pop(); 22 | maze[x][y] = 0; 23 | } 24 | findPath(0, 0); 25 | return !result ? [-1, -1] : result; 26 | } 27 | 28 | 29 | let maze2 =[[0, 1, 0, 0, 0], 30 | [0, 1, 0, 1, 0], 31 | [0, 1, 0, 1, 0], 32 | [0, 0, 0, 1, 0]] 33 | 34 | 35 | console.log(ratPath2(maze2)) 36 | /* 37 | [ [ 0, 0 ], 38 | [ 1, 0 ], 39 | [ 2, 0 ], 40 | [ 3, 0 ], 41 | [ 3, 1 ], 42 | [ 3, 2 ], 43 | [ 2, 2 ], 44 | [ 1, 2 ], 45 | [ 0, 2 ], 46 | [ 0, 3 ], 47 | [ 0, 4 ], 48 | [ 1, 4 ], 49 | [ 2, 4 ], 50 | [ 3, 4 ] ] 51 | */ 52 | -------------------------------------------------------------------------------- /Other/InterviewQuestions/InformationalInterviewQuestions.md: -------------------------------------------------------------------------------- 1 | # Informational Interview Questions 2 | 3 | ### Hiring Managers: 4 | 5 | 6 | What are your expectations for someone in this role after 30 days? 7 | Why are you growing your team? 8 | (basically,to know if they are hiring because of growth, or replacing someone who ran away from a bad situation) 9 | What do you see your role and responsibilities as a software engineer growing to one or two years from now? 10 | 11 | ### Founders: 12 | 13 | How they came up with the idea and what inspired them? 14 | When did you start your company? 15 | What are the biggest struggles your team is facing right now? 16 | What are some of the immediate plans of the company? 17 | 18 | ### Engineers: 19 | 20 | What are you working now? 21 | How has your experience been working here? 22 | How did you get into this field? 23 | How does a normal day look like at your company? 24 | If you could solve one major hurdle in your day what would it be? 25 | What does your tech stack look like and why did you choose that stack? 26 | What excites you about the company? 27 | How long have you been on the team and the best part that you like about being on this team? 28 | What motivated you to stay so long? 29 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/LongestNonRepeatingSubstring.js: -------------------------------------------------------------------------------- 1 | function longestSubstring(str) { 2 | let seen = {}; 3 | let range = [0,0]; 4 | let slow = 0; 5 | 6 | for (let i = 0; i < str.length; i++) { 7 | if(!seen[str[i]]) { 8 | seen[str[i]] = 1; 9 | } else if(seen[str[i]]) { 10 | seen[str[i]] += 1; 11 | } 12 | 13 | while(seen[str[i]] > 1) { 14 | seen[str[slow]] -= 1; 15 | slow += 1 16 | } 17 | if((i - slow) > range[1] - range[0]) { 18 | range = [slow, i]; 19 | } 20 | } 21 | 22 | return str.slice(range[0], range[1] + 1); 23 | } 24 | 25 | console.log(longestSubstring("aabcdeafg")); 26 | 27 | 28 | /* 29 | 30 | Python Solution 31 | 32 | def longest_substring(str): 33 | seen = {} 34 | range = [-1, -1] 35 | slow = 0 36 | 37 | for i in xrange(0, len(str)): 38 | if not str[i] in seen: 39 | seen[str[i]] = 1 40 | 41 | elif str[i] in seen: 42 | seen[str[i]] += 1 43 | 44 | 45 | while seen[str[i]] > 1: 46 | 47 | seen[str[slow]] -= 1 48 | slow += 1 49 | 50 | if (i - slow) > range[1] - range[0]: 51 | range = [slow, i] 52 | 53 | 54 | 55 | 56 | 57 | return str[range[0]: range[1] + 1] 58 | 59 | 60 | 61 | print longest_substring("") 62 | 63 | */ 64 | -------------------------------------------------------------------------------- /AlgorithmProblems/Sorting/Heapsort.js: -------------------------------------------------------------------------------- 1 | /* 2 | Heapsort in place 3 | Time Complexity: O(N log N) 4 | Space Complexity: O(1) 5 | */ 6 | 7 | function heapSort(arr) { 8 | let lastElement = arr.length; 9 | 10 | function getChild(parent) { 11 | let child1 = 2 * parent + 1; 12 | let child2 = 2 * parent + 2; 13 | 14 | if (child1 >= lastElement) { 15 | return child1; 16 | } else if (child2 >= lastElement) { 17 | return child1; 18 | } else if (arr[child1] > arr[child2]) { 19 | return child1; 20 | } else { 21 | return child2; 22 | } 23 | } 24 | 25 | function bubbleDown(parent) { 26 | let child = getChild(parent); 27 | 28 | while (child <= lastElement && arr[parent] < arr[child]) { 29 | [arr[child], arr[parent]] = [arr[parent], arr[child]]; 30 | parent = child; 31 | child = getChild(parent); 32 | } 33 | } 34 | 35 | let i = arr.length; 36 | while (i--) { 37 | bubbleDown(i); 38 | } 39 | 40 | lastElement--; 41 | while(lastElement >= 0) { 42 | [arr[0], arr[lastElement]] = [arr[lastElement], arr[0]]; //Swap 43 | lastElement--; 44 | bubbleDown(0); 45 | } 46 | return arr; 47 | } 48 | 49 | // console.log(heapSort([10, 4, 5, 1, 9, 6, 8, 9, 1])) 50 | 51 | module.exports = heapSort; 52 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/ReverseVowels.js: -------------------------------------------------------------------------------- 1 | var reverseVowels = function(word) { 2 | // your code here 3 | var forwardIndex = 0; 4 | var backwardIndex = word.length - 1; 5 | var vowels = {}; 6 | vowels.a = 'a'; 7 | vowels.e = 'e'; 8 | vowels.i = 'i'; 9 | vowels.o = 'o'; 10 | vowels.u = 'u'; 11 | 12 | var temp; 13 | 14 | while(forwardIndex < backwardIndex){ 15 | if(vowels[word[forwardIndex]] && vowels[word[backwardIndex]]){ 16 | temp = word[forwardIndex]; 17 | word[forwardIndex] = word[backwardIndex]; 18 | word[backwardIndex] = temp; 19 | forwardIndex++; 20 | backwardIndex--; 21 | } else{ 22 | if(!vowels[word[forwardIndex]]){ 23 | forwardIndex++; 24 | } 25 | if(!vowels[word[backwardIndex]]){ 26 | backwardIndex--; 27 | } 28 | } 29 | } 30 | 31 | return word; 32 | }; 33 | 34 | //Loop through the array simulatneously forward and backward 35 | //save any vowels that are found 36 | //once the loop encounters a vowel going forward and backward, swap 37 | //stop when forward and backward indices match 38 | //return word 39 | 40 | console.log(reverseVowels(["d","a","v","i","d","o"])); 41 | console.log(reverseVowels(["d","a","v","i","d","o", 'u'])); 42 | console.log(reverseVowels(["a", "e", "i","o","u"])); 43 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/FlipZeros.js: -------------------------------------------------------------------------------- 1 | function flipZeros(arr, m){ 2 | 3 | // Current Max Count 4 | var maxCount = 0; 5 | 6 | // Current Zero Count 7 | var currentCount = 0; 8 | 9 | // Keeps Track of Left and Rightmost zeros 10 | var left = 0; 11 | var right = 0; 12 | 13 | // Keeps Track 14 | var zeros = []; 15 | 16 | // First Loop to Create Zeros Array 17 | for(var i = 0; i < arr.length; i++){ 18 | if(arr[i] === 0){ 19 | zeros.push(i); 20 | } 21 | } 22 | 23 | // Second Loop To Flip Zeros 24 | while(right < arr.length){ 25 | 26 | // If there are no zeros left to flip 27 | if(m > 0){ 28 | if(arr[right] === 0){ 29 | m--; 30 | } 31 | currentCount++; 32 | right++; 33 | } 34 | // If there are 35 | else { 36 | if(arr[right] === 1){ 37 | currentCount++; 38 | right++; 39 | } else { 40 | // Subtract the flipped zero and any ones that were with it 41 | currentCount = right - zeros[left] - 1; 42 | left++; 43 | m++; 44 | } 45 | } 46 | // Update the max count 47 | if(currentCount > maxCount){ 48 | maxCount = currentCount; 49 | } 50 | } 51 | 52 | return maxCount; 53 | } 54 | 55 | console.log(flipZeros([0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1], 7)); 56 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/GroupAnagrams.js: -------------------------------------------------------------------------------- 1 | function groupAnagrams(words) { 2 | let result = []; 3 | let anagramMap = {}; 4 | let chars = assignCharsToPrimes(); 5 | 6 | function computeAnagramNumber(str) { 7 | let result = 1; 8 | for(let i = 0; i < str.length; i++){ 9 | result *= chars[str[i]]; 10 | } 11 | return result; 12 | } 13 | 14 | words.forEach(word => { 15 | let anagramNum = computeAnagramNumber(word); 16 | if(anagramMap[anagramNum] === undefined) { 17 | anagramMap[anagramNum] = [word] 18 | } else { 19 | anagramMap[anagramNum].push(word); 20 | } 21 | }) 22 | 23 | for (let num in anagramMap) { 24 | result.push(anagramMap[num]); 25 | } 26 | 27 | return result; 28 | } 29 | 30 | function assignCharsToPrimes(){ 31 | let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101] 32 | let chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 33 | let zip = {}; 34 | chars.forEach((char, index) => { 35 | zip[char] = primes[index] 36 | }) 37 | return zip; 38 | } 39 | 40 | console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])) 41 | 42 | // Leetcode: https://leetcode.com/problems/group-anagrams/description/ 43 | -------------------------------------------------------------------------------- /DataStructures/Tries/Scrabble.js: -------------------------------------------------------------------------------- 1 | const Trie = require("./Trie"); 2 | const fs = require("fs"); 3 | 4 | // const trie = require("./DictAsTrie"); 5 | 6 | Set.prototype.copy = function() { 7 | let result = new Set(); 8 | this.forEach((item) => { 9 | result.add(item); 10 | }); 11 | return result; 12 | } 13 | 14 | 15 | function Scrabble(dictionary, characters) { 16 | let trie = new Trie(); 17 | trie.addWords(dictionary); 18 | console.log(trie) 19 | 20 | //function Scrabble(characters) { 21 | 22 | let result = []; 23 | let currentWord = [] 24 | 25 | function dfs(current, available) { 26 | currentWord.push(current.char); 27 | if(current.isWord){ 28 | let word = currentWord.join(""); 29 | result.push(word); 30 | } 31 | 32 | available.forEach(char => { 33 | if(current.children[char] !== undefined) { 34 | let remaining = available.copy(); 35 | remaining.delete(char); 36 | dfs(current.children[char], remaining); 37 | } 38 | }); 39 | currentWord.pop(); 40 | } 41 | 42 | dfs(trie.root, new Set(characters)); 43 | 44 | return result; 45 | } 46 | 47 | const dictionary = fs.readFileSync("./dictionary.txt").toString().split("\n"); 48 | 49 | 50 | let chars = ["t", "h", "e", "e", "m", "a", "n", "s", "t"]; 51 | 52 | console.log(Scrabble(dictionary, chars)); 53 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/CapitalPermutations.js: -------------------------------------------------------------------------------- 1 | function capitalPermutationsAdvanced(S) { //Given a string of letters containing uppercase, lowercase and numbers 2 | let result = []; 3 | 4 | function recurse(substr, depth) { 5 | if(depth === S.length) { 6 | result.push(substr); 7 | return; 8 | } 9 | if(!isNaN(S[depth])) { 10 | recurse(substr + S[depth], depth + 1) 11 | } else if(S[depth] == S[depth].toUpperCase()) { 12 | recurse(substr + S[depth].toLowerCase(), depth + 1); 13 | recurse(substr + S[depth], depth + 1); 14 | } else { 15 | recurse(substr + S[depth].toUpperCase(), depth + 1); 16 | recurse(substr + S[depth], depth + 1); 17 | } 18 | } 19 | recurse("", 0) 20 | return result; 21 | }; 22 | 23 | 24 | 25 | function captialPermutationsBasic(str) { //Given a string of letters in lowercase 26 | let result = []; 27 | 28 | function permute(substr, depth) { 29 | if(depth === str.length) { 30 | result.push(substr); 31 | return; 32 | } 33 | permute(substr + str[depth], depth + 1); 34 | permute(substr + str[depth].toUpperCase(), depth + 1); 35 | } 36 | 37 | permute("", 0); 38 | 39 | return result; 40 | } 41 | 42 | console.log(capitalPermutationsAdvanced("abc")); 43 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/GroupAnagramsNaive.js: -------------------------------------------------------------------------------- 1 | function anagramGroups(words) { 2 | let wordSet = new Set(words); 3 | let result = []; 4 | 5 | wordSet.forEach(word => { 6 | let currentWord = word; 7 | let anagramsOfCurrentWord = []; 8 | wordSet.forEach(w => { 9 | if(areAnagrams(currentWord, w)){ 10 | anagramsOfCurrentWord.push(w); 11 | wordSet.delete(w); 12 | } 13 | }) 14 | result.push(anagramsOfCurrentWord); 15 | }) 16 | return result; 17 | } 18 | 19 | function areAnagrams(word1, word2) { 20 | if(word1.length !== word2.length) { 21 | return false; 22 | } 23 | let counts1 = countCharacters(word1); 24 | let counts2 = countCharacters(word2); 25 | 26 | if(Object.keys(counts1).length !== Object.keys(counts2).length) { 27 | return false; 28 | } 29 | for(let key in counts1) { 30 | if(!(key in counts2) || counts2[key] !== counts1[key]) { 31 | return false; 32 | } 33 | } 34 | return true; 35 | } 36 | 37 | function countCharacters(word) { 38 | let result = {}; 39 | for(let i = 0; i < word.length; i++) { 40 | let char = word[i] 41 | if(result[char] === undefined) { 42 | result[char] = 1; 43 | } else { 44 | result[char] += 1; 45 | } 46 | } 47 | return result; 48 | } 49 | 50 | console.log(anagramGroups(["eat", "tea", "tan", "ate", "nat", "bat"])) 51 | -------------------------------------------------------------------------------- /DataStructures/HashTables/HashTable.js: -------------------------------------------------------------------------------- 1 | //Hashing Function 2 | function makeHash(input, memory) { 3 | if(typeof input === 'number') return makeHash(String(input), memory); 4 | if (typeof input !== 'string') throw "Error, first argument must be a string or a number"; 5 | if(typeof memory !== 'number') throw "Error, second argument must be an integer"; 6 | 7 | var code = 0; 8 | var split = input.split(''); 9 | 10 | split.forEach(function(item){ 11 | code += item.charCodeAt(0); 12 | }) 13 | 14 | return code % memory; 15 | } 16 | 17 | //HashTable Generator Function 18 | function HashTable(size){ 19 | if(typeof size !== 'number' || size % 1 !== 0 || size >= 0) return "Error, first argument must be a positive integer"; 20 | var s = size; 21 | var storage = {}; 22 | 23 | this.get = function(key){ 24 | var result = makeHash(key, size); 25 | return storage[result]; 26 | }; 27 | 28 | this.put = function(key, value){ 29 | var result = makeHash(key, size); 30 | storage[result] = value; 31 | }; 32 | 33 | } 34 | 35 | HashTable.prototype.get = function(key){ 36 | 37 | } 38 | 39 | HashTable.prototype.hello = function() { 40 | console.log('Hello World') 41 | } 42 | 43 | var h = new HashTable(8); 44 | console.log(h.size) 45 | h.hello() 46 | 47 | 48 | console.log(makeHash('abcdefgh', 15)) 49 | 50 | var a = 'a' 51 | console.log() 52 | -------------------------------------------------------------------------------- /Other/assets/git-author-rewrite.sh: -------------------------------------------------------------------------------- 1 | 2 | 3 | #Changes the email and name in the repos commit history 4 | # Commit Info: https://help.github.com/articles/viewing-contributions-on-your-profile/ 5 | # Source: https://help.github.com/articles/changing-author-info/ 6 | # Article: https://code.bradymower.com/why-arent-my-commits-showing-up-on-my-contributions-graph-52141efa7542 7 | 8 | #!/bin/sh 9 | 10 | git filter-branch --env-filter ' 11 | OLD_EMAIL="your-old-email@example.com" 12 | CORRECT_NAME="Your Correct Name" 13 | CORRECT_EMAIL="your-correct-email@example.com" 14 | if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ] 15 | then 16 | export GIT_COMMITTER_NAME="$CORRECT_NAME" 17 | export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL" 18 | fi 19 | if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ] 20 | then 21 | export GIT_AUTHOR_NAME="$CORRECT_NAME" 22 | export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL" 23 | fi 24 | ' --tag-name-filter cat -- --branches --tags 25 | 26 | 27 | 28 | 29 | # Resources for changin multiple commits: 30 | # Stack Overflow: https://stackoverflow.com/questions/4981126/how-to-amend-several-commits-in-git-to-change-author 31 | # https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages 32 | # https://www.git-tower.com/learn/git/faq/change-author-name-email 33 | 34 | # https://www.git-tower.com/learn/git/faq/change-author-name-email 35 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/NumberOfOnes.js: -------------------------------------------------------------------------------- 1 | function numberOfOnes(arr) { 2 | let start = 0; 3 | let end = arr.length; 4 | let mid = Math.floor((start + end) / 2) 5 | 6 | while (start < end) { 7 | if(arr[mid] === 0) { 8 | start = mid + 1 9 | } else { 10 | end = mid 11 | } 12 | mid = Math.floor((start + end) /2) 13 | } 14 | return arr.length - mid; 15 | } 16 | 17 | 18 | 19 | 20 | 21 | // function NumberOfOnes(arr){ 22 | // 23 | // var minIndex = 0; 24 | // var maxIndex = arr.length - 1; 25 | // var currentIndex; 26 | // var currentElement; 27 | // 28 | // // Edge Case Checks 29 | // 30 | // if(arr[0] === 1){ 31 | // return arr.length; 32 | // } 33 | // if(arr[arr.length - 1] === 0){ 34 | // return 0; 35 | // } 36 | // 37 | // while(minIndex <= maxIndex) { 38 | // 39 | // currentIndex = Math.floor((minIndex + maxIndex) / 2) | 0; 40 | // currentElement = arr[currentIndex]; 41 | // 42 | // if(currentElement === 0){ 43 | // minIndex = currentIndex + 1; 44 | // } 45 | // else if (currentElement === 1){ 46 | // if(arr[currentIndex - 1] === 0){ 47 | // return arr.length - currentIndex 48 | // 49 | // } else { 50 | // maxIndex = currentIndex - 1 51 | // } 52 | // } 53 | // } 54 | // 55 | // return 0; 56 | // } 57 | 58 | console.log(NumberOfOnes([0, 0, 0, 1, 1, 1, 1])) 59 | -------------------------------------------------------------------------------- /DataStructures/BinaryTrees/MergeBinaryTrees.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.left = null; 5 | this.right = null; 6 | } 7 | } 8 | 9 | 10 | let root1 = new TreeNode(1) 11 | root1.left = new TreeNode(3) 12 | root1.right = new TreeNode(2) 13 | root1.left.left = new TreeNode(5) 14 | root1.left.left.right = new TreeNode(1) 15 | 16 | 17 | let root2 = new TreeNode(2) 18 | root2.left = new TreeNode(1) 19 | root2.right = new TreeNode(3) 20 | root2.left.right = new TreeNode(4) 21 | root2.right.right = new TreeNode(7) 22 | 23 | 24 | 25 | function mergeTrees(node1, node2) { 26 | // Case 1: Neither is null 27 | if(node1 !== null && node2 !== null) { 28 | let newNode = new TreeNode(node1.val + node2.val); 29 | newNode.left = mergeTrees(node1.left, node2.left); 30 | newNode.right = mergeTrees(node1.right, node2.right); 31 | return newNode; 32 | } 33 | // Case 2: 1 or more is null 34 | if(node1 === null) { 35 | return copyTree(node2) 36 | } 37 | if(node2 === null) { 38 | return copyTree(node1); 39 | } 40 | } 41 | 42 | function copyTree(node) { 43 | if(node === null) { 44 | return null; 45 | } 46 | let newNode = new TreeNode(node.val); 47 | newNode.left = copyTree(node.left); 48 | newNode.right = copyTree(node.right); 49 | return newNode; 50 | } 51 | 52 | let root3 = mergeTrees(root1, root2); 53 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/Multiply.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that given two matrices 3 | return the matrix that results from multiplying them together 4 | If the matrices are unable to be multipled throw an error 5 | 6 | ***Note*** 7 | The dimensions of the matrices need not be the same. 8 | And the dimensions of the result need not equal the dimensions 9 | of either input 10 | 11 | */ 12 | 13 | function Multiply(matrix1, matrix2){ 14 | if(matrix1[0].length !== matrix2.length){ 15 | throw "Cannot multiply matrices with given dimensions" 16 | } 17 | let result = [] 18 | for(let row = 0; row < matrix1.length; row++) { 19 | let newRow = []; 20 | for(let column = 0; column < matrix2[0].length; column++) { 21 | let num = 0; 22 | for(let i = 0; i < matrix1[0].length; i++) { 23 | num += matrix1[row][i] * matrix2[i][column] 24 | } 25 | newRow.push(num); 26 | } 27 | result.push(newRow); 28 | } 29 | return result; 30 | } 31 | 32 | module.exports = Multiply; 33 | 34 | // Tests 35 | // console.log(Multiply([[1,1],[1,1],[1,1]], [[1,1,1],[1,1,1]])); 36 | // console.log(Multiply([[1,1,1],[1,1,1]], [[1,1],[1,1],[1,1]])); 37 | // console.log(Multiply([[1,1,1],[1,1,1]], [[1],[1],[1]])); 38 | // console.log(Multiply([[1],[1],[1]], [[1,1,1]])); 39 | // console.log(Multiply([[1,1,1]], [[1],[1],[1]])); 40 | // console.log(Multiply([[1,1,1]], [[1],[1]])); 41 | -------------------------------------------------------------------------------- /AlgorithmProblems/Recursion/Combinations.js: -------------------------------------------------------------------------------- 1 | function combinations1(n, k) { 2 | let result= []; 3 | 4 | function recurse(start, combos) { 5 | if(combos.length === k) { 6 | return result.push(combos); 7 | } 8 | if(start > n) { 9 | return; 10 | } 11 | let temp = combos.slice(); 12 | recurse(start + 1, temp); 13 | temp.push(start); 14 | recurse(start + 1, temp); 15 | } 16 | 17 | recurse(1, []); 18 | return result; 19 | } 20 | 21 | // Optimizes space/time by only copying combos when ready to push into result 22 | // Also saves time by breaking out of recursion when the number of combos can't reach length k 23 | function combinations2(n, k) { 24 | let result= []; 25 | 26 | function recurse(start, combos) { 27 | if(combos.length === k) { 28 | return result.push(combos.slice()); 29 | } 30 | if(combos.length + (n - start + 1) < k){ 31 | return; 32 | } 33 | recurse(start + 1, combos); 34 | combos.push(start); 35 | recurse(start + 1, combos); 36 | combos.pop(); 37 | } 38 | 39 | recurse(1, []); 40 | return result; 41 | } 42 | 43 | 44 | // combinations(4, 2); 45 | 46 | console.time("combinations 1") 47 | combinations1(60, 4) 48 | console.timeEnd("combinations 1") 49 | 50 | console.time("combinations 2") 51 | combinations2(60, 4) 52 | console.timeEnd("combinations 2") 53 | 54 | // module.exports = combinations; 55 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/AllAnagrams.js: -------------------------------------------------------------------------------- 1 | function allAnagrams (string) { 2 | // Write your code here, and 3 | // return your final answer. 4 | var firstResult = [[]]; 5 | var finalResult = []; 6 | var split = string.split(''); 7 | 8 | 9 | var addLettertoSingleCombination = function(arr, letter){ 10 | var result = []; 11 | for(var i = 0; i < arr.length + 1; i++){ //length + 1 to add to the end of the array as well 12 | var copy = arr.slice(); 13 | copy.splice(i, 0, letter); 14 | result.push(copy); 15 | } 16 | return result; 17 | }; 18 | 19 | // console.log(addLettertoSingleCombination(['a'], 'c')) 20 | 21 | var addLettertoAllCombinations = function(combos, letter){ 22 | var results = []; 23 | for(var i = 0; i < combos.length; i++){ 24 | results = results.concat(addLettertoSingleCombination(combos[i], letter)) 25 | } 26 | return results 27 | } 28 | 29 | 30 | console.log(addLettertoAllCombinations([['a', 'b'], ['b', 'a']], 'd')) 31 | 32 | 33 | for(var j = 0; j < split.length; j++){ 34 | firstResult = addLettertoAllCombinations(firstResult, split[j]); 35 | } 36 | 37 | 38 | 39 | for(var i = 0; i < firstResult.length; i++){ 40 | finalResult.push(firstResult[i].join('')) 41 | }; 42 | 43 | 44 | return finalResult; 45 | return split; 46 | return finalResult 47 | return recurse(string); 48 | 49 | } 50 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/Steps.js: -------------------------------------------------------------------------------- 1 | function climbStairsMemo(steps){ 2 | var memo = {}; 3 | memo[-1] = 0; 4 | memo[0] = 1; 5 | memo[1] = 1; 6 | 7 | function helper(subSteps){ 8 | if(memo[subSteps] !== undefined){ 9 | return memo[subSteps] 10 | } else { 11 | var sum = helper(subSteps - 1) + helper(subSteps - 2) + helper(subSteps - 3); 12 | memo[subSteps] = sum; 13 | return sum 14 | } 15 | } 16 | 17 | helper(steps); 18 | 19 | return memo[steps]; 20 | } 21 | 22 | function climbStairsTab(steps){ 23 | var tab = [1, 1, 2]; 24 | 25 | for(var i = 3; i <= steps; i++){ 26 | tab.push(tab[i - 1] + tab[i - 2] + tab[i - 3]) 27 | } 28 | return tab[steps] 29 | } 30 | 31 | function constantTimeFib(n){ 32 | return round( (pow(goldenRatio(), n) - pow(- goldenRatio(), -n) )/sqrt5) 33 | } 34 | 35 | var pow = Math.pow 36 | var round = Math.round 37 | var sqrt5 = Math.sqrt(5); 38 | 39 | function goldenRatio(){ 40 | return (1 + Math.sqrt(5))/2 41 | } 42 | 43 | function tabFib(n){ 44 | var tab = [0, 1]; 45 | for(var i = 2; i <= n; i++){ 46 | tab[i] = tab[i - 1] + tab[i - 2] 47 | } 48 | return tab[n]; 49 | } 50 | 51 | // console.log(climbStairsMemo(1000)) 52 | // console.log(climbStairsTab(30)) 53 | console.time('tabFib'); 54 | console.log(tabFib(50)); 55 | console.timeEnd('tabFib'); 56 | console.time('constFib'); 57 | console.log(constantTimeFib(50)) 58 | console.timeEnd('constFib'); 59 | 60 | -------------------------------------------------------------------------------- /DataStructures/Graphs/StringChain2.js: -------------------------------------------------------------------------------- 1 | function stringChain2(words) { 2 | let setOfWords = new Set(words); //O(N) adds all words to a set for O(1) lookup 3 | let seen = new Set(); // To keep track of graph 4 | let chains = {}; 5 | let globalMax = 1; 6 | 7 | 8 | function dfs(word) { //O(N) 9 | if(word.length === 1) { 10 | chains[word] = 1; 11 | return 1; 12 | } 13 | if(chains[word] !== undefined) { 14 | return chains[word] 15 | } 16 | let maxChain = 1; 17 | let oneRemovals = generateAllOneRemovals(word); 18 | 19 | oneRemovals.forEach((w) => { 20 | if(setOfWords.has(w)) { 21 | maxChain = Math.max(dfs(w) + 1, maxChain); 22 | } 23 | }) 24 | chains[word] = maxChain; 25 | globalMax = Math.max(maxChain, globalMax); 26 | return maxChain; 27 | } 28 | 29 | words.forEach((w) => { 30 | if(!seen.has(w)) { 31 | seen.add(w); 32 | dfs(w); 33 | } 34 | }) 35 | 36 | // return chains; //Print to see all the chains for each word 37 | return globalMax; 38 | } 39 | 40 | let words = ["a", "b", "ba", "bca", "bda", "bdca", "xyzabc"]; 41 | 42 | function generateAllOneRemovals(word) { 43 | let result = []; 44 | for(let i = 0; i < word.length; i++) { 45 | let newWord = word.split("") 46 | newWord.splice(i, 1) 47 | newWord = newWord.join(""); 48 | result.push(newWord); 49 | } 50 | return result; 51 | } 52 | 53 | console.log(stringChain2(words)) 54 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/MinimumWindowSubstringWithRepeats.js: -------------------------------------------------------------------------------- 1 | function minimumSubstringWithRepeats(str, substr) { 2 | let lettersSeen = {}; 3 | let lettersNeeded = {}; 4 | let lettersMissing = 0; 5 | 6 | for(let i = 0; i < substr.length; i++) { 7 | if(substr[i] in lettersNeeded){ 8 | lettersNeeded[substr[i]] += 1; 9 | } else { 10 | lettersNeeded[substr[i]] = 1; 11 | lettersSeen[substr[i]] = 0; 12 | lettersMissing += 1; 13 | } 14 | } 15 | 16 | let fast = 0; 17 | let slow = 0; 18 | 19 | let result = [-Infinity, Infinity]; 20 | 21 | for(fast; fast < str.length; fast++) { 22 | 23 | if(str[fast] in lettersNeeded) { 24 | lettersSeen[str[fast]] += 1; 25 | if(lettersSeen[str[fast]] === lettersNeeded[str[fast]]) { 26 | lettersMissing -= 1; 27 | } 28 | } 29 | 30 | while(lettersMissing === 0) { 31 | if(fast - slow < result[1] - result[0]) { 32 | [result[0], result[1]] = [slow, fast]; 33 | // console.log(str.slice(result) 34 | } 35 | if(str[slow] in lettersNeeded) { 36 | lettersSeen[str[slow]] -= 1; 37 | if(lettersSeen[str[slow]] < lettersNeeded[str[slow]]) { 38 | lettersMissing += 1; 39 | } 40 | } 41 | slow++; 42 | } 43 | } 44 | 45 | return str.slice(result[0], result[1] + 1); 46 | } 47 | 48 | console.log(minimumSubstringWithRepeats('abbbbacbbacccbbbabaa', 'aabc')); 49 | // => 'acbba' 50 | -------------------------------------------------------------------------------- /DataStructures/BinaryTrees/MergeBinaryTrees.java: -------------------------------------------------------------------------------- 1 | class Main { 2 | public static void main(String[] args) { 3 | System.out.println("Hello world!"); 4 | TreeNode test1 = new TreeNode(1); 5 | TreeNode test2 = new TreeNode(2); 6 | TreeNode test3 = TreeMethods.mergeTrees(test1, test2); 7 | System.out.println(test3.val); 8 | } 9 | } 10 | 11 | class TreeNode { 12 | public TreeNode left = null; 13 | public TreeNode right = null; 14 | public Integer val; 15 | 16 | public TreeNode(int val) { 17 | this.val = val; 18 | } 19 | } 20 | 21 | class TreeMethods { 22 | public static TreeNode copyTree(TreeNode node) { 23 | if(node == null) { 24 | return null; 25 | } 26 | TreeNode newNode = new TreeNode(node.val); 27 | newNode.left = copyTree(node.left); 28 | newNode.right = copyTree(node.right); 29 | return newNode; 30 | } 31 | 32 | public static TreeNode mergeTrees(TreeNode node1, TreeNode node2) { 33 | // Case 1: Neither is null 34 | if(node1 != null && node2 != null) { 35 | TreeNode newNode = new TreeNode(node1.val + node2.val); 36 | newNode.left = mergeTrees(node1.left, node2.left); 37 | newNode.right = mergeTrees(node1.right, node2.right); 38 | return newNode; 39 | } 40 | // Case 2: 1 or more is null 41 | if(node1 == null) { 42 | return copyTree(node2); 43 | } 44 | if(node2 == null) { 45 | return copyTree(node1); 46 | } 47 | return node1; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Other/MachineLearning/GoogleTutorial/classifier.py: -------------------------------------------------------------------------------- 1 | from scipy.spatial import distance 2 | 3 | def euc(a, b): 4 | return distance.euclidean(a, b) 5 | 6 | class ScrappyKNN(): 7 | def fit(self, X_train, y_train): 8 | self.X_train = X_train 9 | self.y_train = y_train 10 | 11 | def predict(self, X_test): 12 | predictions = [] 13 | for row in X_test: 14 | label = self.closest(row) 15 | predictions.append(label) 16 | return predictions 17 | 18 | def closest(self, row): 19 | best_dist = euc(row, self.X_train[0]) 20 | best_index = 0 21 | for i in range(1, len(self.X_train)): 22 | dist = euc(row, self.X_train[i]) 23 | if dist < best_dist: 24 | best_dist = dist 25 | best_index = i 26 | return self.y_train[best_index] 27 | 28 | 29 | # import a dataset 30 | from sklearn import datasets 31 | iris = datasets.load_iris() 32 | 33 | X = iris.data 34 | y = iris.target 35 | 36 | from sklearn.cross_validation import train_test_split 37 | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5) 38 | 39 | my_classifier = ScrappyKNN() 40 | 41 | my_classifier.fit(X_train, y_train) 42 | 43 | predictions = my_classifier.predict(X_test) 44 | 45 | from sklearn.metrics import accuracy_score 46 | print accuracy_score(y_test, predictions) 47 | 48 | 49 | # Pros: 50 | # Simple Algorithm 51 | 52 | # Cons: 53 | # Slow and computationally expensive 54 | # Hard to show relationships between features 55 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | /* 3 | * ENVIRONMENTS 4 | * ================= 5 | */ 6 | 7 | // Define globals exposed by modern browsers. 8 | "browser": true, 9 | 10 | // Define globals exposed by jQuery. 11 | "jquery": true, 12 | 13 | // Define globals exposed by Node.js. 14 | "node": true, 15 | 16 | // Allow ES6. 17 | "esversion": 6, 18 | 19 | /* 20 | * ENFORCING OPTIONS 21 | * ================= 22 | */ 23 | 24 | // Force all variable names to use either camelCase style or UPPER_CASE 25 | // with underscores. 26 | "camelcase": true, 27 | 28 | // Prohibit use of == and != in favor of === and !==. 29 | "eqeqeq": true, 30 | 31 | // Enforce tab width of 2 spaces. 32 | "indent": 2, 33 | 34 | // Prohibit use of a variable before it is defined. 35 | "latedef": true, 36 | 37 | // Enforce line length to 100 characters 38 | "maxlen": 100, 39 | 40 | // Require capitalized names for constructor functions. 41 | "newcap": true, 42 | 43 | // Enforce use of single quotation marks for strings. 44 | "quotmark": "single", 45 | 46 | // Enforce placing 'use strict' at the top function scope 47 | "strict": true, 48 | 49 | // Prohibit use of explicitly undeclared variables. 50 | "undef": true, 51 | 52 | // Warn when variables are defined but never used. 53 | "unused": false, 54 | 55 | /* 56 | * RELAXING OPTIONS 57 | * ================= 58 | */ 59 | 60 | // Suppress warnings about == null comparisons. 61 | "eqnull": true 62 | } 63 | -------------------------------------------------------------------------------- /DataStructures/LinkedLists/AddTwoNums.js: -------------------------------------------------------------------------------- 1 | /** 2 | https://leetcode.com/problems/add-two-numbers/submissions/ 3 | * Definition for singly-linked list. 4 | * function ListNode(val) { 5 | * this.val = val; 6 | * this.next = null; 7 | * } 8 | */ 9 | /** 10 | * @param {ListNode} l1 11 | * @param {ListNode} l2 12 | * @return {ListNode} 13 | */ 14 | var addTwoNumbers = function(l1, l2) { 15 | if(l1 === null && l2 === null) { 16 | return null; 17 | } 18 | let head = new ListNode(0); 19 | let currentNode = head; 20 | let node1 = l1; 21 | let node2 = l2; 22 | let carry = 0; 23 | 24 | while(!(node1 === null && node2 === null)) { 25 | let node1Val = 0; 26 | let node2Val = 0; 27 | 28 | if(node1 !== null) { 29 | node1Val = node1.val; 30 | node1 = node1.next; 31 | } 32 | 33 | if(node2 !== null) { 34 | node2Val = node2.val; 35 | node2 = node2.next; 36 | } 37 | 38 | currentNode.val = (node1Val + node2Val + carry) % 10; 39 | 40 | if(node1Val + node2Val + carry >= 10) { 41 | carry = 1; 42 | } else { 43 | carry = 0; 44 | } 45 | if(!(node1 === null && node2 === null)) { 46 | currentNode.next = new ListNode(0); 47 | currentNode = currentNode.next; 48 | } 49 | } 50 | if(carry === 1) { 51 | currentNode.next = new ListNode(1); 52 | } 53 | 54 | return head; 55 | }; 56 | -------------------------------------------------------------------------------- /Other/Archive/staticNeuralNetwork/staticNeuralNetwork.js: -------------------------------------------------------------------------------- 1 | function createVectorNode(n){ 2 | this.val = n; 3 | } 4 | 5 | function createMatrixNode(n){ 6 | this.val = n; 7 | } 8 | 9 | function generateConnectivityMatrix(matrix){ 10 | return matrix.map((item) => 11 | item.map((index) => new createMatrixNode(index))); 12 | } 13 | 14 | function generateStateVector(lst){ 15 | return lst.map((item) => new createVectorNode(item)); 16 | } 17 | 18 | 19 | function updateStateVector(matrix, vector){ 20 | 21 | var columnIndex = 0, rowIndex = 0; 22 | var result = new Array(matrix.length).fill(0); 23 | 24 | vector.forEach((item) => { 25 | if(item.val) { 26 | for(rowIndex; rowIndex < matrix.length; rowIndex++){ 27 | if(matrix[rowIndex][columnIndex].val){ 28 | result[rowIndex] = 1; 29 | } 30 | } 31 | } 32 | rowIndex = 0; 33 | columnIndex++; 34 | }) 35 | 36 | return generateStateVector(result); 37 | } 38 | 39 | function resetStateVector(vector){ 40 | return vector.map((item) => item.val = 0) 41 | } 42 | 43 | //Tests 44 | var a = [ 45 | [0, 1, 0, 0], 46 | [0, 0, 1, 0], 47 | [1, 0, 0, 0], 48 | [0, 1, 0, 0] 49 | ]; 50 | 51 | a = generateConnectivityMatrix(a) 52 | 53 | var v = generateStateVector([1, 0, 0, 0]); 54 | console.log(v); 55 | var w = updateStateVector(a, v); 56 | console.log(w); 57 | var x = updateStateVector(a, w); 58 | console.log(x); 59 | var y = updateStateVector(a, x); 60 | console.log(y); 61 | var z = updateStateVector(a, y); 62 | console.log(z) 63 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/ShortestSequenceContainingSet.js: -------------------------------------------------------------------------------- 1 | function shortestSequenceContainingSet(set, arr) { 2 | let start = 0; 3 | let end = 0; 4 | 5 | let seen = {}; 6 | let seenSize = 0; 7 | 8 | let shortestSequence = Infinity; 9 | 10 | while(end < arr.length) { 11 | 12 | if(!set.has(arr[start])) { 13 | start++; 14 | } 15 | 16 | if(!set.has(arr[end])) { 17 | end++; 18 | } 19 | 20 | if(set.has(arr[start]) && seenSize < set.size) { 21 | 22 | let element = arr[end] 23 | 24 | if(set.has(element)) { 25 | if(seen[element]) { 26 | seen[element] += 1; 27 | } else { 28 | seen[element] = 1; 29 | seenSize++; 30 | } 31 | } 32 | end++; 33 | } 34 | 35 | 36 | if(seenSize === set.size) { 37 | if(end - start < shortestSequence ) { 38 | shortestSequence = end - start; 39 | } 40 | let element = arr[start]; 41 | 42 | if(seen[element] === 1) { 43 | delete seen[element]; 44 | seenSize--; 45 | } else { 46 | seen[element]--; 47 | } 48 | start++; 49 | } 50 | 51 | } 52 | return shortestSequence === Infinity ? -1 : shortestSequence; 53 | } 54 | 55 | // let set = new Set([1, 2, 3]); 56 | // let arr = [4, 1, 2, 6, 7, 1, 3, 2, 5]; 57 | 58 | // console.log(shortestSequenceContainingSet(set, arr)) 59 | // Time: O(n) where n = length of the array 60 | // Space: O(k) where k = size of the set 61 | 62 | module.exports = shortestSequenceContainingSet; 63 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/HouseRobber2.js: -------------------------------------------------------------------------------- 1 | let counter = 0; 2 | 3 | function houseRobberRecursive(arr) { 4 | function stealFromHouse(index) { 5 | if(index >= arr.length) { 6 | counter++; 7 | return 0; 8 | } 9 | return Math.max(arr[index] + stealFromHouse(index + 2), stealFromHouse(index + 1)); 10 | } 11 | return stealFromHouse(0); 12 | } 13 | 14 | // console.log(houseRobberRecursive([3, 1, 2, 5, 4, 2, 5])) 15 | // houseRobberRecursive([1, 2, 3, 4]) 16 | // console.log(counter) 17 | 18 | let results = {}; 19 | let array = []; 20 | 21 | for(let i = 0; i <= 20; i++) { 22 | houseRobberRecursive(array); 23 | results[i] = counter; 24 | counter = 0; 25 | array.push(i); 26 | } 27 | 28 | console.log(results); 29 | 30 | 31 | function houseRobber1(houses) { 32 | let max_gold = [] 33 | 34 | for(let i = 0; i < houses.length; i++) { 35 | let current = houses[i]; 36 | let prevMax = max_gold[i - 1] || 0; 37 | let twoBackMax = max_gold[i - 2] || 0; 38 | max_gold.push(Math.max(current + twoBackMax, prevMax)); 39 | } 40 | 41 | return max_gold[houses.length - 1]; 42 | } 43 | 44 | function houseRobber2(houses) { 45 | let currentMax = 0; 46 | let prevMax = 0; 47 | 48 | for(let i = 0; i < houses.length; i++) { 49 | let currentHouse = houses[i]; 50 | let newMax = Math.max(currentMax, prevMax + currentHouse) 51 | prevMax = currentMax; 52 | currentMax = newMax; 53 | } 54 | 55 | return currentMax 56 | } 57 | 58 | houseRobber2([3, 5, 1, 3, 4, 5, 1]) // => 13 59 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/PowerDigitSum.js: -------------------------------------------------------------------------------- 1 | /* 2 | PowerDigit Sum 3 | Find the sum of the digits of 2^1000 4 | This problem was challenging because JS has a hard time with very large numbers 5 | The solution I cam across was to use strings to store the large numbers, and loop through them one index at a time, converting the index to a Number, performing the multiplication, and turning it back into a string. 6 | */ 7 | 8 | //IFF Wrapper 9 | (function() { 10 | 11 | //Curried function 12 | //Performs all the string processing for large numbers 13 | function multiplyLarge(numSmall) { 14 | return function(numLarge){ 15 | var str = numLarge.toString(); 16 | var carryOver = 0; 17 | var result = ''; 18 | for(var i = str.length - 1; i >= 0; i--){ 19 | var n = Number(str[i]); 20 | var temp = n * numSmall + carryOver; 21 | result = temp % 10 + result; 22 | carryOver = ((temp % 100) - (temp % 10)) /10; 23 | } 24 | if(carryOver) return carryOver + result; 25 | return result; 26 | }; 27 | } 28 | 29 | //Iteratively generates 2^1000 30 | var multiplyLargeBy2 = multiplyLarge(2); 31 | var counter = 0; 32 | var product = 1; 33 | 34 | while(counter < 1000){ 35 | product = multiplyLargeBy2(product); 36 | counter++; 37 | } 38 | 39 | //Sums the digits of 2^1000 40 | function sumDigits(numStr){ 41 | var result = 0; 42 | for(var i = 0; i < numStr.length; i++){ 43 | result += Number(numStr[i]); 44 | } 45 | return result; 46 | } 47 | 48 | console.log(sumDigits(product)) 49 | 50 | })(); 51 | 52 | -------------------------------------------------------------------------------- /AlgorithmProblems/Math/LogicalOperators.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | function ID(p) { 4 | return p; 5 | } 6 | 7 | function TAUTOLOGY(p){ 8 | return true; 9 | } 10 | 11 | function CONTRADICTION(p){ 12 | return false; 13 | } 14 | 15 | function NOT(p) { 16 | if (p) { 17 | return true; 18 | } 19 | return false; 20 | } 21 | 22 | function OR(p, q) { 23 | if(p) { 24 | return true; 25 | } 26 | if(q) { 27 | return true; 28 | } 29 | return false; 30 | } 31 | 32 | function AND(p, q) { 33 | if(NOT(p)) { 34 | return false; 35 | } 36 | if(NOT(q)) { 37 | return false; 38 | } 39 | return true; 40 | } 41 | 42 | function NAND(p, q) { 43 | return NOT(AND(p, q)); 44 | } 45 | 46 | function NOR(p, q) { 47 | return NOT(OR(p, q)); 48 | } 49 | 50 | function IMPLIES(p, q) { 51 | return NOT(AND(p, NOT(q))); 52 | } 53 | 54 | function EQUALS(p, q) { 55 | return AND(IMPLIES(p, q), IMPLIES(q, p)); 56 | } 57 | 58 | function XOR(p, q) { 59 | return NOT(EQUALS(p, q)); 60 | } 61 | 62 | function XNOR(p, q) { 63 | return NOT(XOR(p, q)); 64 | } 65 | 66 | function HALFADDER(p, q) { 67 | return [XOR(p, q), AND(p, q)]; 68 | } 69 | 70 | function FULLADDER(p, q, c) { 71 | return [XOR(XOR(p, q), c), OR(AND(XOR(p, q), c), AND(p, q))] 72 | } 73 | 74 | console.log(FULLADDER(0, 0, 0)); 75 | console.log(FULLADDER(0, 0, 1)); 76 | console.log(FULLADDER(0, 1, 0)); 77 | console.log(FULLADDER(1, 0, 0)); 78 | console.log(FULLADDER(0, 1, 1)); 79 | console.log(FULLADDER(1, 0, 1)); 80 | console.log(FULLADDER(1, 1, 0)); 81 | console.log(FULLADDER(1, 1, 1)); 82 | -------------------------------------------------------------------------------- /DataStructures/QuadTrees/QuadTree.js: -------------------------------------------------------------------------------- 1 | const QuadNode = require('./QuadNode'); 2 | const Point = require('./Point'); 3 | 4 | class QuadTree { 5 | constructor(width, height, maxPointsPerNode) { 6 | this.maxPointsPerNode = maxPointsPerNode || 5; 7 | this.width = width; 8 | this.height = height; 9 | this.points = new Map(); 10 | this.root = new QuadNode(0, width, 0, height); 11 | this.currentPoint = 0; 12 | } 13 | 14 | addPoint(point) { 15 | this.points.set(point.name, point); 16 | this.root.addPoint(point); 17 | this.currentPoint++; 18 | } 19 | 20 | addPoints(num) { 21 | while(num > 0) { 22 | let randomX = Math.random() * this.width; 23 | let randomY = Math.random() * this.height; 24 | let p = new Point(randomX, randomY, `Point ${this.currentPoint}`); 25 | this.addPoint(p); 26 | num--; 27 | } 28 | } 29 | } 30 | 31 | function distance(point1, point2) { 32 | return Math.sqrt(Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2)) 33 | } 34 | 35 | function intersecting(point1, point2) { 36 | return distance(point1, point2) < point1.radius + point2.radius ? true : false; 37 | } 38 | 39 | let p1 = new Point(50, 50) 40 | let p2 = new Point(51, 49) 41 | let p3 = new Point(10, 10) 42 | 43 | // console.log(distance(p1, p2)) 44 | 45 | console.log(intersecting(p1, p2)) 46 | console.log(intersecting(p1, p3)) 47 | 48 | // console.log(qt) 49 | 50 | // let qt = new QuadTree(100, 100, 5) 51 | 52 | // qt.addPoints(10) 53 | 54 | // console.log(qt.points.get('Point 0')) 55 | // console.log(qt.points.get('Point 1')) 56 | -------------------------------------------------------------------------------- /DataStructures/Graphs/StringChain.js: -------------------------------------------------------------------------------- 1 | function stringChain(words) { 2 | let maxChain = 1; 3 | let setOfWords = new Set(); 4 | 5 | words.forEach((word) => { 6 | setOfWords.add(word); 7 | }); 8 | 9 | // Sort the words by length O(n * log(n)) Do it without sorting 10 | words.sort((a, b) => a.length < b.length) 11 | 12 | let seen = new Set(); 13 | let queue = []; 14 | 15 | // Perform BFS from every word in the array sorted by length 16 | for(let i = 0; i < words.length; i++) { 17 | 18 | if(!seen.has(words[i]) && words[i].length > maxChain) { 19 | 20 | queue.push([words[i], 1]) 21 | seen.add(words[i]); 22 | 23 | while(queue.length > 0) { 24 | let currentItem = queue.shift(); 25 | let [currentWord, distance] = [currentItem[0], currentItem[1]]; 26 | 27 | maxChain = Math.max(distance, maxChain); 28 | 29 | let oneRemovals = generateAllOneRemovals(currentWord); 30 | oneRemovals.forEach((word) => { 31 | if(!seen.has(word) && setOfWords.has(word)) { 32 | queue.push([word, distance + 1]); 33 | seen.add(word); 34 | } 35 | }) 36 | } 37 | } 38 | } 39 | return maxChain; 40 | } 41 | 42 | function generateAllOneRemovals(word) { 43 | let result = []; 44 | for(let i = 0; i < word.length; i++) { 45 | let newWord = word.split("") 46 | newWord.splice(i, 1) 47 | newWord = newWord.join(""); 48 | result.push(newWord); 49 | } 50 | return result; 51 | } 52 | 53 | 54 | stringChain(["a", "b", "ba", "bca", "bda", "bdca"]) 55 | 56 | // console.log(generateAllOneRemovals("bdca")) 57 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "toy-problems", 3 | "version": "1.0.0", 4 | "description": "A repo of toy problems and solutions", 5 | "main": "index.js", 6 | "scripts": { 7 | "build": "npm run destroy && npm run create", 8 | "create": "mkdir -p homework_prompts/$folder/{java,js,py,rb,swift} && mkdir -p homework_solutions/$folder/{java,js,py,rb,swift} && mkdir -p target_practice_prompts/$folder/{java,js,py,rb,swift} && mkdir -p target_practice_solutions/$folder/{java,js,py,rb,swift} && mkdir -p warm_up_prompts/$folder/{java,js,py,rb,swift} && mkdir -p warm_up_solutions/$folder/{java,js,py,rb,swift} && mkdir -p foundation_solutions_temp/$folder/{java,js,py,rb,swift} && mkdir -p foundation_prompts_temp/$folder/{java,js,py,rb,swift} && node assets/build/builder.js", 9 | "destroy": "rm -rf {homework_prompts,homework_solutions,target_practice_prompts,target_practice_solutions,warm_up_prompts,warm_up_solutions,foundation_solutions_temp,foundation_prompts_temp}", 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/spiterman/ToyProblems.git" 14 | }, 15 | "keywords": [ 16 | "toy", 17 | "problems", 18 | "algorithms", 19 | "data", 20 | "structures", 21 | "coding", 22 | "interview", 23 | "preparation" 24 | ], 25 | "author": "Sergey Piterman", 26 | "license": "ISC", 27 | "bugs": { 28 | "url": "https://github.com/spiterman/ToyProblems/issues" 29 | }, 30 | "homepage": "https://github.com/spiterman/ToyProblems#readme", 31 | "dependencies": { 32 | "express": "^4.16.2", 33 | "path": "^0.12.7", 34 | "request": "^2.88.0" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/CompareStringsConstantSpace.js: -------------------------------------------------------------------------------- 1 | // Python Solution 2 | // 3 | // def compare_strings(s1, s2): 4 | // 5 | // def edit_string(s): 6 | // i = 0 7 | // while i < len(s)-1: 8 | // if s[i] == '/': # we found a command 9 | // if s[i+1] == 'b': # backspace 10 | // if i < 2: # cant erase char if /b is first in string 11 | // s = s[2:] 12 | // else: 13 | // s = s[:i-1] + s[i+2:] 14 | // i -= 2 15 | // i += 1 16 | // return s 17 | // 18 | // s1 = edit_string(s1) 19 | // s2 = edit_string(s2) 20 | // 21 | // print s1, s2 22 | // c1 = "" 23 | // c2 = "" 24 | // i = 0 25 | // j = 0 26 | // s1upper = False 27 | // s2upper = False 28 | // while True: 29 | // # print i, len(s1), j, len(s2) 30 | // if i == len(s1) and j == len(s2): 31 | // return True 32 | // if i == len(s1): 33 | // for k in range(j, len(s2), 2): 34 | // if s2[k] != '/': 35 | // return False 36 | // return True 37 | // if j == len(s2): 38 | // for k in range(j, len(s1), 2): 39 | // if s1[k] != '/': 40 | // return False 41 | // return True 42 | // 43 | // if s1[i] == '/': 44 | // s1upper = not s1upper 45 | // i+=2 46 | // if s2[j] == '/': 47 | // s2upper = not s2upper 48 | // j+=2 49 | // 50 | // if s1upper: 51 | // c1 = s1[i].upper() 52 | // else: 53 | // c1 = s1[i] 54 | // if s2upper: 55 | // c2 = s2[j].upper() 56 | // else: 57 | // c2 = s2[j] 58 | // 59 | // # print c1, c2 60 | // if c1 != c2: 61 | // return False 62 | // j+=1 63 | // i+=1 64 | // 65 | // s1 = "abc/b/cae/b" 66 | // s2 = "ab/ca/c/c" 67 | // print compare_strings(s1, s2) 68 | -------------------------------------------------------------------------------- /DataStructures/Tries/Trie.js: -------------------------------------------------------------------------------- 1 | const TrieNode = require("./TrieNode"); 2 | 3 | class Trie { 4 | constructor() { 5 | this.root = new TrieNode(""); 6 | } 7 | addWord(str) { 8 | let current = this.root; 9 | for(let i = 0; i < str.length; i++) { 10 | if(current.children[str[i]] === undefined) { 11 | current.children[str[i]] = new TrieNode(str[i]); 12 | } 13 | current = current.children[str[i]]; 14 | } 15 | current.isWord = true; 16 | } 17 | 18 | addWords(arrOfWords) { 19 | let trie = this; 20 | arrOfWords.forEach(word => { 21 | trie.addWord(word); 22 | }) 23 | } 24 | 25 | search(prefix){ //returns a node, or null 26 | let result = null; 27 | function dfs(current, index) { 28 | if(!(prefix[index] in current.children)){ 29 | return; 30 | } 31 | if(index === prefix.length) { 32 | result = current; 33 | return; 34 | } 35 | dfs(current[prefix[index]], index + 1); 36 | } 37 | dfs(this.root, 0); 38 | return result; 39 | } 40 | 41 | getWords(prefix){ //returns an array of words 42 | let current = this.search(prefix); 43 | } 44 | 45 | isWord(str){ //returns true/false if word exists or not in trie 46 | 47 | } 48 | 49 | removeWord(str){ //removes the word from the trie 50 | 51 | function dfs(current, index) { 52 | if(!(str[index] in current.children)) { 53 | return; 54 | } 55 | if(index === str.length) { 56 | 57 | } 58 | dfs(current[str[index]], index + 1); 59 | if(current.children); 60 | } 61 | } 62 | 63 | } 64 | 65 | 66 | module.exports = Trie; 67 | -------------------------------------------------------------------------------- /Other/FunctionalProgramming/functionBind.js: -------------------------------------------------------------------------------- 1 | 2 | var bind = function(func, context){ 3 | //Your code here 4 | //var that = func; 5 | funContext = Array.prototype.slice.call(arguments, 1); 6 | 7 | for(var i = 0; i < funContext.length; i++){ 8 | if (!funContext[i]){ 9 | funContext.splice(i, 1); 10 | } 11 | } 12 | 13 | return function(){ 14 | return func.apply(context, 15 | funContext.concat(Array.prototype.slice.call(arguments))) 16 | } 17 | 18 | }; 19 | 20 | 21 | 22 | 23 | Function.prototype.bind = function(oThis) { 24 | 25 | var aArgs = Array.prototype.slice.call(arguments, 1), 26 | fToBind = this, 27 | fNOP = function () {}, 28 | fBound = function () { 29 | return fToBind.apply(this instanceof fNOP && oThis 30 | ? this 31 | : oThis, 32 | aArgs.concat(Array.prototype.slice.call(arguments))); 33 | }; 34 | 35 | fNOP.prototype = this.prototype; 36 | fBound.prototype = new fNOP(); 37 | 38 | return fBound; 39 | 40 | }; 41 | 42 | 43 | var bind = function(func, context) { 44 | var args = Array.prototype.slice.call(arguments, 2); 45 | return function() { 46 | var args1 = Array.prototype.slice.call(arguments); 47 | return func.apply(context, args.concat(args1)); 48 | }; 49 | }; 50 | 51 | 52 | Function.prototype.bind = function(context) { 53 | var args = Array.prototype.slice.call(arguments, 1); 54 | var that = this; 55 | return function() { 56 | var args1 = Array.prototype.slice.call(arguments); 57 | return that.apply(context, args.concat(args1)); 58 | }; 59 | }; 60 | -------------------------------------------------------------------------------- /Other/ComputationalFinance/Event Study/eventStudy.py: -------------------------------------------------------------------------------- 1 | 2 | import QSTK.qstkutil.qsdateutil as du 3 | import numpy as np 4 | import QSTK.qstkutil.tsutil as tsu 5 | import QSTK.qstkutil.DataAccess as da 6 | import datetime as dt 7 | import matplotlib.pyplot as plt 8 | import pandas as pd 9 | import math 10 | import copy 11 | import QSTK.qstkstudy.EventProfiler as ep 12 | 13 | def find_events(ls_symbols, d_data): 14 | ''' Finding the event dataframe ''' 15 | df_close = d_data['actual_close'] 16 | ts_market = df_close['SPY'] 17 | 18 | print "Finding Events" 19 | 20 | # Creating an empty dataframe 21 | df_events = copy.deepcopy(df_close) 22 | df_events = df_events * np.NAN 23 | 24 | # Time stamps for the event range 25 | ldt_timestamps = df_close.index 26 | 27 | for s_sym in ls_symbols: # for each symbol 28 | for i in range(1, len(ldt_timestamps)): # for each day 29 | # Calculating the returns for this timestamp 30 | f_symprice_today = df_close[s_sym].ix[ldt_timestamps[i]] 31 | f_symprice_yest = df_close[s_sym].ix[ldt_timestamps[i - 1]] 32 | f_marketprice_today = ts_market.ix[ldt_timestamps[i]] 33 | f_marketprice_yest = ts_market.ix[ldt_timestamps[i - 1]] 34 | f_symreturn_today = (f_symprice_today / f_symprice_yest) - 1 35 | f_marketreturn_today = (f_marketprice_today / f_marketprice_yest) - 1 36 | 37 | # Event is found if the symbol is down more then 3% while the 38 | # market is up more then 2% 39 | if f_symreturn_today <= -0.03 and f_marketreturn_today >= 0.02: 40 | df_events[s_sym].ix[ldt_timestamps[i]] = 1 41 | 42 | return df_events 43 | -------------------------------------------------------------------------------- /Other/FunctionalProgramming/StarWars.js: -------------------------------------------------------------------------------- 1 | const request = require('request'); 2 | 3 | let firstPage = "https://swapi.co/api/starships/" 4 | 5 | function getSingleURL(currentPage) { 6 | return new Promise((resolve, reject) => { 7 | request(currentPage, (error, response, body) => { 8 | if(error) { 9 | reject({error, response}); 10 | } 11 | let nextPage = JSON.parse(body).next; 12 | resolve({currentPage, nextPage}); 13 | }) 14 | }) 15 | } 16 | 17 | // getSingleURL(firstPage).then(console.log) 18 | 19 | function getAllURLs(firstPage, result) { 20 | return getSingleURL(firstPage).then(urls => { 21 | result.push(urls.currentPage); 22 | if(urls.nextPage === null) { 23 | return result; 24 | } 25 | return getAllURLs(urls.nextPage, result); 26 | }) 27 | } 28 | 29 | // getAllURLs(firstPage, []).then(console.log) 30 | 31 | function getShips(passengers, url){ 32 | return new Promise(function(resolve, reject){ 33 | request(url, function(error, repsonse, body){ 34 | if(error){ 35 | reject(error) 36 | } 37 | let starWarsData = JSON.parse(body); 38 | let results = starWarsData.results.filter(currentShip => { 39 | return currentShip.passengers > passengers && currentShip.pilots.length > 0; 40 | }); 41 | resolve(results) 42 | }) 43 | }) 44 | } 45 | 46 | // getShips(10, firstPage).then(console.log) 47 | 48 | // getAllURLs(firstPage, []).then(urls => { 49 | // return urls.map((url) => { 50 | // return getShips(10, url); 51 | // }) 52 | // }).then(promiseArray => { 53 | // return Promise.all(promiseArray); 54 | // }) 55 | // .then(console.log) 56 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/ShortestSubArray.js: -------------------------------------------------------------------------------- 1 | /* 2 | Find Shortest Sub Array 3 | 4 | Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. 5 | 6 | Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. 7 | 8 | Example 1: 9 | Input: [1, 2, 2, 3, 1] 10 | Output: 2 11 | 12 | Explanation: 13 | The input array has a degree of 2 because both elements 1 and 2 appear twice. 14 | Of the subarrays that have the same degree: 15 | [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] 16 | The shortest length is 2. So return 2. 17 | 18 | 19 | Example 2: 20 | Input: [1,2,2,3,1,4,2] 21 | Output: 6 22 | 23 | Note: 24 | nums.length will be between 1 and 50,000. 25 | nums[i] will be an integer between 0 and 49,999. 26 | */ 27 | 28 | 29 | function findShortestSubArray(nums) { 30 | let counts = {}; 31 | 32 | nums.forEach((element, index) => { 33 | counts[element] ? counts[element].push(index) : counts[element] = [index]; 34 | }); 35 | 36 | let degree = 0; 37 | let minRange = Infinity; 38 | 39 | for (let key in counts) { 40 | let newDegree = counts[key].length; 41 | let newRange = counts[key][newDegree - 1] - counts[key][0] + 1; 42 | if(newDegree > degree) { 43 | degree = newDegree; 44 | minRange = newRange; 45 | } else if(newDegree == degree) { 46 | minRange = Math.min(minRange, newRange); 47 | } 48 | } 49 | 50 | return minRange; 51 | } 52 | 53 | // findShortestSubArray([1, 2, 2, 3, 1, 4, 2, 3, 3, 3, 4, 4, 4, 4, 1, 1, 1, 2, 2, 2, 2]); 54 | // findShortestSubArray([1,2,2,3,1,4,2]); 55 | -------------------------------------------------------------------------------- /AlgorithmProblems/DynamicProgramming/SlidingWindowMaximum.js: -------------------------------------------------------------------------------- 1 | class Dequeue { 2 | constructor(){ 3 | this.head = new ListNode(Infinity) 4 | this.tail = new ListNode(-Infinity) 5 | this.head.next = this.tail 6 | this.tail.prev = this.head 7 | } 8 | removeFromHead() { 9 | this.head.next = this.head.next.next 10 | this.head.next.prev = this.head 11 | } 12 | 13 | removeFromTail() { 14 | this.tail.prev = this.tail.prev.prev 15 | this.tail.prev.next = this.tail 16 | } 17 | addToTail(val) { 18 | let newNode = new ListNode(val) 19 | newNode.prev = this.tail.prev 20 | this.tail.prev.next = newNode 21 | this.tail.prev = newNode 22 | } 23 | } 24 | 25 | class ListNode { 26 | constructor(val) { 27 | this.val = val 28 | this.next = null 29 | this.prev = null 30 | } 31 | } 32 | 33 | 34 | function slidingWindowMaximum(arr, k){ 35 | let deq = new Dequeue() 36 | 37 | let result = [] 38 | 39 | for(let i = 0; i < k; i++) { 40 | while(deq.tail.prev.val !== Infinity && arr[i] >= arr[deq.tail.prev.val]) { 41 | deq.removeFromTail() 42 | } 43 | deq.addToTail(i) 44 | } 45 | 46 | let slow = 0 47 | let fast = k 48 | 49 | for(fast; fast <= arr.length; fast++) { 50 | result.push(arr[deq.head.next.val]) 51 | 52 | if(arr[slow] >= arr[deq.head.next.val]) { 53 | deq.removeFromHead() 54 | } 55 | slow++ 56 | 57 | while(arr[fast] >= arr[deq.tail.prev.val]) { 58 | deq.removeFromTail() 59 | } 60 | deq.addToTail(fast) 61 | } 62 | 63 | return result 64 | } 65 | 66 | 67 | console.log(slidingWindowMaximum([1, 2, 3, 1, 4, 5, 2, 3, 6], 3)) 68 | 69 | console.log(slidingWindowMaximum([8, 5, 10, 7, 9, 4, 15, 12, 90, 13], 4)) 70 | -------------------------------------------------------------------------------- /DataStructures/Graphs/SocialNetwork.js: -------------------------------------------------------------------------------- 1 | // Suppose you are creating an internal networking site for your company. You have two data sets to work with. 2 | // The first data set is the employees at your company, and the second is all the pairs of employees who are virtually friends so far. 3 | // It does not matter which employee's ID is in which column, the friendships are bidirectional. 4 | // You want to know who’s friends with whom. 5 | // You need to implement a function that, given the employees and friendships as parameters, 6 | // returns this data in the form of an adjacency list representation. 7 | // This should associate each employee ID to his/her friends on the site. 8 | 9 | 10 | var employees_input = [ 11 | "1,Richard,Engineering", 12 | "2,Erlich,HR", 13 | "3,Monica,Business", 14 | "4,Dinesh,Engineering", 15 | "6,Carla,Engineering", 16 | "9,Laurie,Directors" 17 | ]; 18 | 19 | 20 | var friendships_input = [ 21 | "1,2", 22 | "1,3", 23 | "1,6", 24 | "2,4" 25 | ]; 26 | 27 | 28 | function findNetwork(employees_input, friendships_input) { 29 | let result = {}; 30 | 31 | for(let i = 0; i < employees_input.length; i++) { 32 | let employee = employees_input[i].split(","); 33 | result[employee[0]] = [] 34 | } 35 | 36 | for(let i = 0; i < friendships_input.length; i++) { 37 | let friendship = friendships_input[i].split(","); 38 | result[friendship[0]].push(Number(friendship[1])) 39 | result[friendship[1]].push(Number(friendship[0])) 40 | } 41 | 42 | return result; 43 | 44 | } 45 | 46 | console.log(findNetwork(employees_input, friendships_input)) 47 | // { 48 | // 1: [2, 3, 6], 49 | // 2: [1, 4], 50 | // 3: [1], 51 | // 4: [2], 52 | // 6: [1], 53 | // 9: [] 54 | // } 55 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/FindAnagrams.js: -------------------------------------------------------------------------------- 1 | function findAnagrams(s, p) { 2 | let result = []; 3 | let letterCount = {}; 4 | let start = 0; 5 | let end = 0; 6 | 7 | for(let i = 0; i < p.length; i++) { 8 | p[i] in letterCount ? letterCount[p[i]] ++: letterCount[p[i]] = 1; 9 | } 10 | 11 | let seen = {}; 12 | 13 | while(start < s.length) { 14 | 15 | let letter = s[end]; 16 | let oldLetter = s[start]; 17 | 18 | if(objShallowEqual(seen, letterCount)) { 19 | result.push(start); 20 | seen[oldLetter]--; 21 | start++; 22 | } 23 | 24 | if(letterCount[letter] === undefined) { 25 | end++; 26 | start = end; 27 | seen = {}; 28 | } 29 | 30 | if(letterCount[letter] !== undefined) { 31 | if(seen[letter] === undefined) { 32 | seen[letter] = 1; 33 | } 34 | else if(seen[letter] < letterCount[letter]) { 35 | seen[letter]++; 36 | } 37 | else { 38 | seen[letter]++; 39 | while(seen[letter] > letterCount[letter]) { 40 | let oldLetter = s[start]; 41 | if(seen[oldLetter] !== undefined ) { 42 | seen[oldLetter]--; 43 | } 44 | start++; 45 | } 46 | } 47 | end++; 48 | } 49 | } 50 | return result; 51 | } 52 | 53 | 54 | 55 | function objShallowEqual(obj1, obj2) { 56 | if(Object.keys(obj1).length !== Object.keys(obj2).length ) { 57 | return false; 58 | } 59 | for(let k in obj1) { 60 | if(!(k in obj2) || obj1[k] !== obj2[k]) { 61 | return false 62 | } 63 | } 64 | return true; 65 | } 66 | 67 | // console.log(findAnagrams("baa", "aa")) 68 | // console.log(findAnagrams("abab", "ab")); 69 | 70 | module.exports = findAnagrams; 71 | -------------------------------------------------------------------------------- /OOP/Cards.js: -------------------------------------------------------------------------------- 1 | class Card { 2 | constructor (suit, rank) { 3 | this.suit = suit; 4 | this.rank = rank; 5 | } 6 | value () { 7 | return `${this.rank}${this.suit}`; 8 | } 9 | } 10 | 11 | class Deck { 12 | constructor() { 13 | this.storage = []; 14 | 15 | const suits = ['C', 'D', 'H', 'S']; 16 | const ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']; 17 | 18 | ranks.forEach((rank) => { 19 | suits.forEach((suit) => { 20 | this.storage.push(new Card(suit, rank)); 21 | }); 22 | }); 23 | } 24 | 25 | dealCard(){ 26 | return this.storage.pop() 27 | } 28 | 29 | shuffleCards() { 30 | this.storage.forEach((card, index) => { 31 | let newIndex = Math.floor(Math.random() * this.storage.length); 32 | this.swapCards(index, newIndex); 33 | }); 34 | } 35 | 36 | swapCards(idx1, idx2) { 37 | const temp = this.storage[idx1] 38 | this.storage[idx1] = this.storage[idx2] 39 | this.storage[idx2] = temp 40 | } 41 | 42 | returnCard(card) { 43 | this.storage.push(card); 44 | } 45 | 46 | dealHands(players, cardsPerPlayer) { 47 | // Return an array of arrays of cards 48 | let hands = []; 49 | let i = 0; 50 | 51 | // Generate the array of arrays 52 | while (i < players) { 53 | hands.push([]); 54 | i++; 55 | } 56 | 57 | // Shuffle Cards First 58 | this.shuffleCards(); 59 | 60 | let j = 0; 61 | while(j < cardsPerPlayer) { 62 | hands.forEach((hand) => { 63 | let card = this.dealCard(); 64 | hand.push(card); 65 | }) 66 | j++; 67 | } 68 | return hands; 69 | } 70 | 71 | } 72 | 73 | let d = new Deck(); 74 | 75 | console.log(d.dealHands(4, 5)); 76 | 77 | console.log(d.storage); 78 | -------------------------------------------------------------------------------- /DataStructures/LinkedLists/Intersection.js: -------------------------------------------------------------------------------- 1 | // function getIntersectionNode (headA, headB) { 2 | // let lenA = length(headA); 3 | // let lenB = length(headB); 4 | // 5 | // // move headA and headB to the same start point 6 | // while (lenA > lenB) { 7 | // headA = headA.next; 8 | // lenA--; 9 | // } 10 | // while (lenA < lenB) { 11 | // headB = headB.next; 12 | // lenB--; 13 | // } 14 | // 15 | // // find the intersection until end 16 | // while(headA !== headB) { 17 | // headA = headA.next; 18 | // headB = headB.next; 19 | // } 20 | // return headA; 21 | // }; 22 | 23 | function getIntersectionNode(headA, headB) { 24 | let currentA = headA; 25 | let currentB = headB; 26 | 27 | while(currentA != currentB) { 28 | currentA = currentA ? currentA = currentA.next : headB 29 | currentB = currentB ? currentB = currentB.next : headA 30 | } 31 | return currentA; 32 | 33 | } 34 | 35 | 36 | function ListNode(val) { 37 | this.val = val; 38 | this.next = null; 39 | } 40 | 41 | function length (head) { 42 | let count = 0; 43 | while(head !== null) { 44 | head = head.next; 45 | count++; 46 | } 47 | return count; 48 | } 49 | 50 | // Test Cases 51 | let a1 = new ListNode('a1'); 52 | let a2 = new ListNode('a2'); 53 | let a3 = new ListNode('a3'); 54 | 55 | let b1 = new ListNode('b1'); 56 | let b2 = new ListNode('b2'); 57 | 58 | let c1 = new ListNode('c1'); 59 | let c2 = new ListNode('c2'); 60 | let c3 = new ListNode('c3'); 61 | 62 | a1.next = a2; 63 | a2.next = a3; 64 | a3.next = c1; 65 | 66 | b1.next = b2; 67 | b2.next = c1; 68 | 69 | c1.next = c2; 70 | c2.next = c3; 71 | 72 | let c4 = new ListNode('c4'); 73 | 74 | console.log(getIntersectionNode(a1, b1)); // => c1 75 | console.log(getIntersectionNode(a1, c4)); // => null 76 | -------------------------------------------------------------------------------- /DataStructures/BinaryTrees/TreeExpression.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a method to evaluate a binary expression tree. Include classes to represent the tree in your design. 3 | 4 | As an example, the binary tree representation of the expression 6 + ( 6 / 2 ) would be: 5 | + 6 | / \ 7 | 6 '/' 8 | / \ 9 | "6" "2" 10 | 11 | 12 | 13 | Assume input is valid 14 | 15 | Ints, all positives 16 | 17 | Only division and addition 18 | 19 | No divide by 0 20 | 21 | 22 | Define a binary tree node class 23 | 24 | Write a function that takes in the root node 25 | 26 | Treat numbers as a base case 27 | 28 | Otherwise there will be an evaluate sub expression 29 | 30 | If a node corresponds to a number, return an integer version of that number 31 | 32 | If it's an operator, return that operator applied to recursing left and right 33 | 34 | */ 35 | 36 | class Node { 37 | constructor(val) { 38 | this.val = val; 39 | this.left = null; 40 | this.right = null; 41 | } 42 | } 43 | 44 | 45 | function evaluateTree(node) { 46 | try { 47 | if(node === null) { 48 | throw "Error, invalid Tree" 49 | } 50 | 51 | if(node.val === "/") { 52 | return evaluateTree(node.left) / evaluateTree(node.right); 53 | } 54 | if(node.val === "+") { 55 | return evaluateTree(node.left) + evaluateTree(node.right); 56 | } 57 | return parseInt(node.val); 58 | 59 | } catch(e) { 60 | console.error(e) 61 | } 62 | } 63 | 64 | 65 | let node1 = new Node("+") 66 | let node2 = new Node("6") 67 | let node3 = new Node("/") 68 | let node4 = new Node("6") 69 | let node5 = new Node("2") 70 | 71 | node1.left = node2 72 | node1.right = node3 73 | node3.left = node4 74 | // node3.right = node5 75 | 76 | 77 | evaluateTree(node1) 78 | -------------------------------------------------------------------------------- /OOP/Drone.js: -------------------------------------------------------------------------------- 1 | class Drone { 2 | up(){ 3 | setTimeout(() => console.log("moved up"), 200); 4 | } 5 | left() { 6 | setTimeout(() => console.log("moved left"), 100); 7 | } 8 | spin() { 9 | setTimeout(() => console.log("spun"), 400); 10 | } 11 | } 12 | 13 | class SuperDrone extends Drone { 14 | up() { 15 | setTimeout(super.up, 0); 16 | return this; 17 | } 18 | left() { 19 | setTimeout(super.left, 0); 20 | return this; 21 | } 22 | spin() { 23 | setTimeout(super.spin, 0); 24 | return this; 25 | } 26 | } 27 | 28 | 29 | //Given a drone class with different timing for their moves. The moves are 30 | //async. 31 | 'use strict'; 32 | 33 | // Do not edit this drone class at all 34 | class Drone { 35 | 36 | up(callback){ 37 | setTimeout(() => { 38 | console.log('moved up'); 39 | callback(); 40 | }, 800); 41 | } 42 | 43 | down(callback){ 44 | setTimeout(() => { 45 | console.log('moved down'); 46 | callback(); 47 | }, 500); 48 | } 49 | 50 | forward(callback){ 51 | setTimeout(() => { 52 | console.log('moved forward'); 53 | callback(); 54 | }, 400); 55 | } 56 | 57 | backward(callback){ 58 | setTimeout(() => { 59 | console.log('moved down'); 60 | callback(); 61 | }, 700); 62 | } 63 | 64 | left(callback){ 65 | setTimeout(() => { 66 | console.log('moved left'); 67 | callback(); 68 | }, 200); 69 | } 70 | right(callback){ 71 | setTimeout(() => { 72 | console.log('moved right'); 73 | callback(); 74 | }, 250); 75 | } 76 | 77 | spin(callback){ 78 | setTimeout(() => { 79 | console.log('spun around 30 degrees'); 80 | callback(); 81 | }, 400); 82 | } 83 | } 84 | 85 | let drone = new SuperDrone(); 86 | 87 | drone.spin().up().left(); 88 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/PigLatin.js: -------------------------------------------------------------------------------- 1 | /* 2 | As a user I can enter a phrase "hello" and see it translated to Pig Latin "ellohay" X 3 | 4 | As a user I can enter a phrase "hello world" and see it translated to Pig Latin "ellohay orldway" X 5 | 6 | As a user I can enter a phrase "Hello World" and see it translated to Pig Latin "Ellohay Orldway" X 7 | 8 | As a user I can enter a phrase "Hello, world!" and see it translated to Pig Latin "Ellohay, orldway!" X 9 | 10 | As a user I can enter a phrase "eat apples" and see it translated to Pig Latin "eatay applesay" 11 | 12 | As a user I can enter a phrase "quick brown fox" and see it translated to Pig Latin "ickquay ownbray oxfay" 13 | */ 14 | 15 | function PigLatin(str){ 16 | var result = []; 17 | var arr = str.split(' '); 18 | 19 | arr.forEach((item) => { 20 | result.push(handleCapitals(item) + removePunctuation(item) + item[0].toLowerCase() + 'ay' + returnPunctuation(item)); 21 | }); 22 | 23 | return result.join(' '); 24 | } 25 | 26 | function handleCapitals(str){ 27 | if(str[0] === str[0].toUpperCase()){ 28 | return str[1].toUpperCase(); 29 | } else { 30 | return str[1]; 31 | } 32 | } 33 | 34 | function removePunctuation(str) { 35 | if(str.match(/\W/)){ 36 | return str.slice(2, str.length - 1) 37 | } else { 38 | return str.slice(2, str.length); 39 | } 40 | } 41 | 42 | function returnPunctuation(str){ 43 | if(str.match(/\W/)){ 44 | return str[str.length - 1]; 45 | } else { 46 | return ""; 47 | } 48 | } 49 | 50 | console.log(PigLatin('hello') === 'ellohay', PigLatin('hello')); 51 | console.log(PigLatin('hello world') === 'ellohay orldway', PigLatin('hello world')); 52 | console.log(PigLatin('Hello World') === 'Ellohay Orldway', PigLatin('Hello World')); 53 | console.log(PigLatin('Hello, World!') === 'Ellohay, Orldway!', PigLatin('Hello, World!')); 54 | -------------------------------------------------------------------------------- /DataStructures/LinkedLists/Queue.js: -------------------------------------------------------------------------------- 1 | var Queue = function() { 2 | 3 | var storage = {}; 4 | var size = 0; 5 | var currentIndex = 0; 6 | 7 | this.enqueue = function(item) { 8 | storage[currentIndex] = item; 9 | size++; 10 | currentIndex++; 11 | }; 12 | 13 | this.dequeue = function() { 14 | if(size > 0){ 15 | var result = storage[currentIndex - size]; 16 | delete storage[currentIndex - size]; 17 | size--; 18 | return result; 19 | } 20 | console.error('The queue is empty'); 21 | }; 22 | 23 | this.showQueueValues = function() { 24 | var result = []; 25 | var start = currentIndex - size; 26 | while(start < currentIndex){ 27 | result.push(storage[start]); 28 | start++; 29 | } 30 | 31 | return result; 32 | }; 33 | 34 | // This is so the size can't just be manipulated directly 35 | this.size = function() { 36 | return size; 37 | }; 38 | 39 | //Like dequeue, but doesn't remove the 40 | this.peek = function() { 41 | return storage[currentIndex - size]; 42 | }; 43 | 44 | this.findIndex = function(n) { 45 | if (n >= 0 && n < size) { 46 | return storage[currentIndex - (size - n)]; 47 | } 48 | 49 | return console.error('Index given is out of range'); 50 | }; 51 | 52 | this.containsValue = function(val) { 53 | for(var key in storage) { 54 | if (val === storage[key]) { 55 | return true; 56 | } 57 | } 58 | return false; 59 | }; 60 | 61 | this.containsKey = function(k) { 62 | if(typeof k !== 'string'){ 63 | return console.error('The argument given must be a string') 64 | } 65 | for (var key in storage) { 66 | console.log(key) 67 | console.log(k) 68 | if(k === key){ 69 | return true; 70 | } 71 | } 72 | return false; 73 | }; 74 | 75 | }; 76 | -------------------------------------------------------------------------------- /AlgorithmProblems/Matrices/IsValidSudoku.js: -------------------------------------------------------------------------------- 1 | 2 | function isValidSudoku(grid) { 3 | if(grid.length !== 9 || grid[0].length !== 9) { 4 | return false; 5 | } 6 | // Check Rows 7 | for(let i = 0; i < grid.length; i++) { 8 | let nums = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]) 9 | for(let j = 0; j < grid[i].length; j++) { 10 | if(nums.has(grid[i][j])) { 11 | nums.delete(grid[i][j]); 12 | } else if(grid[i][j] !== 0){ 13 | return false; 14 | } 15 | } 16 | } 17 | // Check Columns 18 | for(let i = 0; i < grid.length; i++) { 19 | let nums = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]) 20 | for(let j = 0; j < grid[i].length; j++) { 21 | if(nums.has(grid[j][i])) { 22 | nums.delete(grid[j][i]); 23 | } else if(grid[j][i] !== 0){ 24 | return false; 25 | } 26 | } 27 | } 28 | 29 | // Check Quadrants 30 | for(let q = 0; q < 3; q++) { 31 | for(let p = 0; p < 3; p++) { 32 | if(!checkQuadrant(grid, q, p)) { 33 | return false; 34 | } 35 | } 36 | } 37 | return true; 38 | } 39 | 40 | function checkQuadrant(grid, x, y) { 41 | let nums = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]); 42 | for(let i = 0; i < 3; i++) { 43 | for(let j = 0; j < 3; j++) { 44 | if(nums.has(grid[3 * x + i][3 * y + j])) { 45 | nums.delete(grid[3 * x + i][3 * y + j]); 46 | } else if(grid[3 * x + i][3 * y + j] !== 0){ 47 | return false; 48 | } 49 | } 50 | } 51 | return true; 52 | } 53 | 54 | 55 | let grid = 56 | [[5, 3, 0, 0, 7, 0, 0, 0, 0], 57 | [6, 0, 0, 1, 9, 5, 0, 0, 0], 58 | [0, 9, 8, 0, 0, 0, 0, 6, 0], 59 | [8, 0, 0, 0, 6, 0, 0, 0, 3], 60 | [4, 0, 0, 8, 0, 3, 0, 0, 1], 61 | [7, 0, 0, 0, 2, 0, 0, 0, 6], 62 | [0, 6, 0, 0, 0, 0, 2, 8, 0], 63 | [0, 0, 0, 4, 1, 9, 0, 0, 5], 64 | [0, 0, 0, 0, 8, 0, 0, 7, 9]]; 65 | 66 | isValidSudoku(grid) 67 | -------------------------------------------------------------------------------- /DataStructures/Graphs/WordLadderB.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | function createOneLetterDifferences(word) { 4 | let result = []; 5 | let letters = 'abcdefghijklmnopqrstuvwxyz'; 6 | for(let i = 0; i < word.length; i++) { 7 | for(let j = 0; j < letters.length; j++) { 8 | let temp = word.split(''); 9 | temp[i] = letters[j]; 10 | temp = temp.join(''); 11 | if(temp !== word) { 12 | result.push(temp); 13 | } 14 | } 15 | } 16 | return result; 17 | } 18 | 19 | function wordLadder(beginWord, endWord, wordList) { 20 | let map = {}; 21 | 22 | // Solution B: O(N * K * 26) time 23 | // Part 1: Create a set with all words for constant lookup; 24 | map[beginWord] = []; 25 | for(let i = 0; i < wordList.length; i++) { 26 | map[wordList[i]] = []; 27 | } 28 | // Part 2: Generate all one letter differences of a given word 29 | // Loop through those words and add any that exist in the word set to 30 | // the edge list in map 31 | 32 | for(let word in map) { 33 | let differences = createOneLetterDifferences(word); 34 | for(let i = 0; i < differences.length; i++) { 35 | if(differences[i] in map) { 36 | map[word].push(differences[i]); 37 | } 38 | } 39 | } 40 | 41 | // Step 2: Traverse the graph using BFS 42 | let queue = []; 43 | let seen = {}; 44 | 45 | queue.push([beginWord, 1]); 46 | seen[beginWord] = 1; 47 | 48 | while(queue.length > 0) { 49 | let current = queue.shift(); 50 | let word = current[0]; 51 | let count = current[1]; 52 | let connections = map[word]; 53 | for(let index = 0; index < connections.length; index++) { 54 | if(!seen[connections[index]]) { 55 | seen[connections[index]] = count + 1; 56 | queue.push([connections[index], count + 1]); 57 | } 58 | } 59 | } 60 | 61 | return seen[endWord] || 0; 62 | 63 | } 64 | 65 | console.log(wordLadder("hit", "cog", ["hot","dot","dog","lot","log","cog"])); 66 | -------------------------------------------------------------------------------- /DataStructures/BinaryTrees/TreeEach.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.left = null; 5 | this.right = null; 6 | } 7 | } 8 | 9 | function TreeEach(node, cb) { 10 | function recurse(current) { 11 | if(current === null) { 12 | return; 13 | } 14 | cb(current); 15 | recurse(current.left); 16 | recurse(current.right); 17 | return current; 18 | } 19 | return recurse(node); 20 | } 21 | 22 | function TreeMapValues(node, cb) { 23 | function recurse(current) { 24 | if(current === null) { 25 | return null; 26 | } 27 | let newNode = new TreeNode(cb(current.val)); 28 | newNode.left = recurse(current.left); 29 | newNode.right = recurse(current.right); 30 | return newNode; 31 | } 32 | return recurse(node); 33 | } 34 | 35 | 36 | // Helper Functions 37 | function print(node) { 38 | console.log(node.val) 39 | } 40 | 41 | function reverse(node) { 42 | [node.left, node.right] = [node.right, node.left] 43 | } 44 | 45 | function copy(val) { 46 | return val; 47 | } 48 | 49 | function square(val) { 50 | return val * val; 51 | } 52 | 53 | 54 | // Tests 55 | let node1 = new TreeNode(1) 56 | let node2 = new TreeNode(2) 57 | let node3 = new TreeNode(3) 58 | let node4 = new TreeNode(4) 59 | let node5 = new TreeNode(5) 60 | let node6 = new TreeNode(6) 61 | let node7 = new TreeNode(7) 62 | 63 | 64 | node4.left = node2 65 | node2.left = node1 66 | node2.right = node3 67 | node4.right = node6 68 | node6.left = node5 69 | node6.right = node7 70 | 71 | 72 | // console.log("Original Tree") 73 | // TreeEach(node4, print) 74 | // TreeEach(node4, reverse); 75 | // console.log("Reversed Tree") 76 | // TreeEach(node4, print) 77 | 78 | 79 | // console.log("Squared copy") 80 | // 81 | // TreeEach(TreeEach(TreeMapValues(node4, square), reverse), print) 82 | // 83 | // console.log("Original Tree") 84 | // TreeEach(node4, print) 85 | 86 | exports.TreeNode = TreeNode; 87 | exports.TreeEach = TreeEach; 88 | exports.TreeMapValues = TreeMapValues; 89 | -------------------------------------------------------------------------------- /Other/Archive/OOPArchive/Dates.js: -------------------------------------------------------------------------------- 1 | function sayHello() { 2 | console.log('Hello, World'); 3 | } 4 | 5 | sayHello(); 6 | 7 | //Time/Space: 8 | //In: 9 | //Out: Number of days 10 | // [1, 15, 2016][2, 15, 2016] 11 | 12 | function calculateDays(date1, date2){ 13 | //Start with years 14 | //if years differ, then add 365 to total for each year 15 | //in between 16 | //if the same, or once we're on the same year 17 | //Do the same for the months 18 | //Finally do the same for the days 19 | 20 | //Edge case: 21 | //if year divisible by 4, then total number of days is 366 22 | //and february has 29 days 23 | //Also need a check for which date is the one in the future 24 | var months = { 25 | 1: 31, 26 | 2: 28, 27 | 3: 31, 28 | 4: 30, 29 | 5: 31, 30 | 6: 30, 31 | 7: 31, 32 | 8: 31, 33 | 9: 30, 34 | 10: 31, 35 | 11: 30, 36 | 12: 31 37 | } 38 | 39 | var year1 = date1[2]; 40 | var year2 = date2[2]; 41 | 42 | var result = 0; 43 | 44 | while(year1 < year2){ 45 | if(year1 % 4 === 0){ 46 | result += 366; 47 | year1++; 48 | } else { 49 | result += 365; 50 | year1++; 51 | } 52 | } 53 | // console.log('check1'); 54 | // year1 = 2017 55 | // result = 366; 56 | console.log(result); 57 | 58 | if(year2 % 4 === 0){ 59 | months[2] = 29; 60 | } 61 | 62 | var month1 = date1[0]; 63 | var month2 = date2[0]; 64 | 65 | if(month2 > month1){ 66 | while(month1 < month2){ 67 | result += months[month1]; 68 | month1++; 69 | } 70 | } else { 71 | while(month1 > month2){ 72 | result -= months[month2]; 73 | month2++; 74 | } 75 | } 76 | //month1 = 2; 77 | //result 397; 78 | 79 | 80 | var day1 = date1[1]; 81 | var day2 = date2[1]; 82 | 83 | result += (day2 - day1); 84 | 85 | //result 398; 86 | return result; 87 | } 88 | 89 | // console.log(calculateDays([3, 15, 2016], [1, 15, 2017])); 90 | 91 | // 3/15/2016 -> 3/15/2017 92 | 93 | // 1/15/2017 -> 3/15/2017 94 | 95 | // 1/1/2016 -> 3/14/2016 96 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Toy Problems 2 | 3 | A repository full of 175+ data structures and algorithm problems designed to help software engineers pass their technical interviews. These problems are all in JavaScript, and are drawn from a variety of sources, including actual questions software engineers have gotten on interviews, [Leetcode](https://leetcode.com), [Geeks for Geeks](https://www.geeksforgeeks.org/), [Hackerrank](https://hackerrank.com) and many more. 4 | 5 | Also checkout some of the stuff I've written for [Outco](https://outco.io) on [Medium](https://medium.com/outco). We're a career accelerator for software engineers with new cohorts starting every month. 6 | 7 | This repo is meant for anyone interested in leveling up their problem-solving abilities, so feel free to fork it and look through it. Hopefully you'll find something that helps! 8 | 9 | ## Future Plans 10 | 11 | **More Advanced Problems** 12 | 13 | I'm always looking for new and challenging algorithms and data structures to implement so keep an eye out for new additions like Fibonacci Heaps, Quad Trees, Prim's Algorithm and many more! 14 | 15 | **Prompts** 16 | 17 | Currently what I mainly have are solutions, but I'm hoping to provide prompts, example inputs and outputs, and links to resources on how to solve the problem or where more of an explanation can be found. 18 | 19 | **Build Script** 20 | 21 | I'm working on incorporating a build script that will create a copy of the folder structure, with stubs for the problems, which you can use to solve the problems yourself! 22 | 23 | **General Clean Up** 24 | 25 | This repo is constantly evolving and because of that there are likely going to be typos and errors. I'm currently in the middle of restructuring how the files are organized so that it makes the most intuitive sense and keeps things as flat and searchable as possible. 26 | 27 | But if you have feedback or thoughts feel free to submit a Github Issue and I'll be more than happy to take a look. And I'm always looking for new problems to solve, so feel free to submit questions either as Issues or email me . 28 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/MergeArraysOrdered.js: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/insert-interval/submissions/ 2 | 3 | /** 4 | * @param {number[][]} intervals 5 | * @param {number[]} newInterval 6 | * @return {number[][]} 7 | */ 8 | var insert = function(intervals, newInterval) { 9 | let mergedInterval = newInterval; 10 | let addedMergedInterval = false; 11 | let result = []; 12 | if(intervals.length === 0) { 13 | result.push(newInterval); 14 | return result; 15 | } 16 | 17 | intervals.forEach((interval) => { 18 | if(intervalsOverlap(mergedInterval, interval)) { 19 | mergedInterval = mergeIntervals(mergedInterval, interval); 20 | } else { 21 | if(findLowerInterval(mergedInterval, interval) == mergedInterval && !addedMergedInterval) { 22 | result.push(mergedInterval); 23 | addedMergedInterval = true; 24 | } 25 | result.push(interval); 26 | } 27 | }) 28 | 29 | if(!addedMergedInterval) { 30 | result.push(mergedInterval); 31 | } 32 | return result; 33 | }; 34 | 35 | function findLowerInterval(firstInterval, secondInterval) { 36 | if(firstInterval[0] < secondInterval[0]) { 37 | return firstInterval 38 | } 39 | return secondInterval; 40 | } 41 | 42 | function intervalsOverlap(firstInterval, secondInterval) { 43 | let firstIntervalLowerBound = firstInterval[0] 44 | let firstIntervalUpperBound = firstInterval[1] 45 | let secondIntervalLowerBound = secondInterval [0] 46 | let secondIntervalUpperBound = secondInterval[1] 47 | if(firstIntervalLowerBound <= secondIntervalLowerBound && firstIntervalUpperBound >= secondIntervalLowerBound) { 48 | return true; 49 | } 50 | if(secondIntervalLowerBound <= firstIntervalLowerBound && secondIntervalUpperBound >= firstIntervalLowerBound) { 51 | return true; 52 | } 53 | return false; 54 | } 55 | 56 | function mergeIntervals(firstInterval, secondInterval) { 57 | return [Math.min(firstInterval[0], secondInterval[0]), Math.max(firstInterval[1], secondInterval[1])] 58 | } 59 | -------------------------------------------------------------------------------- /Other/Archive/graph.swift: -------------------------------------------------------------------------------- 1 | class NodeClass { 2 | var name: String 3 | var lon: Double 4 | var lat: Double 5 | var edges: [String: NodeClass] 6 | 7 | init(name: String, lon: Double, lat: Double) { 8 | self.name = name 9 | self.lon = lon 10 | self.lat = lat 11 | self.edges = [:] 12 | } 13 | } 14 | 15 | class GraphClass { 16 | var vertices: [String: NodeClass] 17 | 18 | init() { 19 | self.vertices = [:] 20 | } 21 | 22 | func addNode(name: String, lon: Double, lat: Double) { 23 | vertices[name] = NodeClass(name: name, lon: lon, lat: lat) 24 | } 25 | 26 | func removeNode(name: String) { 27 | vertices.removeValue(forKey: name) 28 | } 29 | 30 | func addEdge(node1: String, node2: String) { 31 | let n1 = vertices[node1] 32 | let n2 = vertices[node2] 33 | n1!.edges[node2] = n2 34 | n2!.edges[node1] = n1 35 | } 36 | 37 | func removeEdge(node1: String, node2: String) { 38 | let n1 = vertices[node1] 39 | let n2 = vertices[node2] 40 | n1!.edges.removeValue(forKey: node2) 41 | n2!.edges.removeValue(forKey: node1) 42 | } 43 | 44 | func shortestPath(node1: String, node2: String) -> Array { 45 | 46 | // func traverse(currentNode: NodeClass, path: Array) -> Array { 47 | 48 | // if currentNode!.name == node2 { 49 | // return path.append(node2) 50 | // } 51 | // // if(path.count) 52 | // print("hello") 53 | // let a = [1, 2, 3] 54 | // print(a.count) 55 | // return [] 56 | 57 | 58 | // } 59 | // traverse(currentNode: vertices[node1], path: []) 60 | 61 | return [] 62 | } 63 | } 64 | 65 | // let n = NodeClass(name: "twin peaks", long: 1.10, lat: 1.302) 66 | 67 | let g = GraphClass() 68 | g.addNode(name: "twin peaks", lon: 1.12, lat: 1.302) 69 | g.addNode(name: "abc", lon: 1.12, lat: 1.302) 70 | 71 | // g.removeNode(name: "twin peaks") 72 | // print(g.vertices) 73 | 74 | let a = g.vertices["twin peaks"] 75 | g.addEdge(node1: "twin peaks", node2: "abc") 76 | // g.removeEdge(node1: "twin peaks", node2: "abc") 77 | 78 | // print(a!.edges) 79 | -------------------------------------------------------------------------------- /Other/InterviewQuestions/JobListings.md: -------------------------------------------------------------------------------- 1 | # Job Search Portals 2 | 3 | | Site | 4 | |---| 5 | | [100offer] (https://www.100offer.com) | 6 | | [AngelList] (https://angel.co/) | 7 | | [Breakout List] (https://breakoutlist.com/)| 8 | | [Built in NYC] (http://www.builtinnyc.com/jobs)| 9 | | [CraigsList] (http://sfbay.craigslist.org/search/sof) | 10 | | [Dice] (http://www.dice.com) | 11 | | [Engineering Jobs] (http://engineerjobs.com) | 12 | | [Github Easy Apply] (https://github.com/j-delaney/easy-application) | 13 | | [Glassdoor] (https://glassdoor.com)| 14 | | [Google Jobs] (https://techcrunch.com/2017/06/20/google-launches-its-ai-powered-jobs-search-engine/?ncid%3Dmobilenavtrend)| 15 | | [Hacker News Who is Hiring] (https://news.ycombinator.com/item?id=15384262)| 16 | | [HackerRank Jobs] (https://www.hackerrank.com/jobs) | 17 | | [Handshake] (https://app.joinhandshake.com/login) | 18 | | [Hired] (https://hired.com/) | 19 | | [Indeed] (https://www.indeed.com/) | 20 | | [InterviewJet (NYC)] (https://www.interviewjet.com/#!) | 21 | | [Jobr] (http://jobr.jobrapp.com/) | 22 | | [Kholsa Ventures] (http://jobs.khoslaventures.com/) | 23 | | [LinkUp] (linkup.com) 24 | | [Looksharp/WayUp] (https://id.looksharp.com) | 25 | | [Mattermark Chrome Extension] (https://chrome.google.com/webstore/detail/mattermark/iedfcbkaanfabmfmndgnogeghbellanl?hl=en) | 26 | | [Mattermark Mobile] (https://mattermark.com/mobile/) | 27 | | [Simply Hired] (http://www.simplyhired.com/) | 28 | | [Stack Overflow] (stackoverflow.com/jobs) | 29 | | [The Muse] (https://www.themuse.com/jobs/q-Software-Engineer-jobs) 30 | | [TripleByte ] (https://triplebyte.com/) 31 | | [Underdog.io (NYC)] (https://underdog.io/) | 32 | | [VentureLoop] (https://www.ventureloop.com/ventureloop/job_search.php) | 33 | | [White Truffle] (https://www.whitetruffle.com/) | 34 | | [Who is Hiring?] (https://whoishiring.io/) | 35 | | [YC Careers] (http://jonathanzwhite.github.io/yc-careers/) | 36 | | [Albert's List] (https://www.facebook.com/groups/findyournextopportunity/) | 37 | | [HireClub] (https://www.facebook.com/groups/hireclub/) | 38 | | [ZipRecruiter] (https://www.ziprecruiter.com) | 39 | | [Yodas] (https://www.yodas.com) | 40 | -------------------------------------------------------------------------------- /Other/Archive/OOPArchive/Elevator/Floor.js: -------------------------------------------------------------------------------- 1 | const FloorButton = require("./FloorButton"); 2 | 3 | 4 | class Floor { 5 | // Knows how many people there 6 | // Knows how to add people to the floor 7 | // Knows how to remove people from the floor 8 | constructor(floorNumber, elevator) { 9 | this.people = new Set(); 10 | this.floorNumber = floorNumber; 11 | this.capacity = 0; 12 | // this.maxCapcity = 100; will implement later 13 | this.elevator = elevator; 14 | this.buttons = new Map(); 15 | this.buttons.set('up', new FloorButton('up')); 16 | this.buttons.set('down', new FloorButton('down')); 17 | } 18 | 19 | addPerson(person){ 20 | this.people.add(person); 21 | person.setFloorButtons(this.buttons); // 22 | this.capacity += 1; 23 | } 24 | 25 | addPeople(people) { 26 | people.forEach((person) => { 27 | this.people.add(person); 28 | }) 29 | } 30 | 31 | removePerson(person) { 32 | this.people.delete(person); 33 | person.setFloorButtons(null); //resets their floor buttons 34 | this.capacity -= 1; 35 | return person; 36 | } 37 | 38 | removePeople(elevatorDirection) { 39 | // Can do this with functional programming, filter based on some callback function 40 | // Returns people on the floor based on a given condition (all the ones going up oer down) 41 | let people = new Set(); 42 | this.people.forEach((person) => { 43 | // Removes a person if the direction is going up and the elevator is headed up 44 | if(person.desiredFloor > this.floorNumber && elevatorDirection === "up"){ 45 | people.add(this.removePerson(person)); 46 | //Removes a person if the direction is going down and the elevator is headed down 47 | } else if(person.desiredFloor < this.floorNumber && elevatorDirection === "down") { 48 | people.add(this.removePerson(person)); 49 | } 50 | }) 51 | 52 | this.buttons.get(elevatorDirection).turnOffLight(); //Resets button 53 | //Doesn't handle when elevator is at capacity 54 | // * (the people the elevator can't add need to stay on the floor, and re-request it, can't just be discarded) 55 | 56 | return people; 57 | } 58 | 59 | turnButtonLightOff(direction) { 60 | this.buttons.get(direction).turnOffLight(); 61 | } 62 | } 63 | 64 | module.exports = Floor; 65 | -------------------------------------------------------------------------------- /Other/assets/builder.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const clean = require('./clean'); 5 | 6 | function writeFile(destination, fileContents, message) { 7 | fs.writeFile(destination, fileContents, (err) => { 8 | if (err) { throw err; } 9 | console.log(message + destination); 10 | }); 11 | } 12 | 13 | function buildFile(type, filename, language) { 14 | fs.readFile(type + '/' + language + '/' + filename, 'utf8', (err, data) => { 15 | if (err) { throw err; } 16 | 17 | writeFile(type + '_prompts/' + language + '/' + filename, 18 | clean.prompt(data), type + ' prompt generated for: '); 19 | writeFile(type + '_solutions/' + language + '/' + filename, 20 | clean.solution(data), type + ' solution generated for: '); 21 | }); 22 | } 23 | 24 | function specialBuildFile(type, filename, language) { 25 | fs.readFile(type + '/' + language + '/' + filename, 'utf8', (err, data) => { 26 | if (err) { throw err; } 27 | 28 | writeFile(type + '_prompts_temp/' + language + '/' + filename, 29 | clean.prompt(data), type + ' prompt generated for: '); 30 | writeFile(type + '_solutions_temp/' + language + '/' + filename, 31 | clean.solution(data), type + ' solution generated for: '); 32 | }); 33 | } 34 | 35 | 36 | function run(languages) { 37 | languages.forEach((language) => { 38 | fs.readdir('homework/' + language, (err, files) => { 39 | if (err) { throw err; } 40 | console.log(files); 41 | files.forEach((file) => { 42 | buildFile('homework', file, language); 43 | }); 44 | }); 45 | fs.readdir('target_practice/' + language, (err, files) => { 46 | if (err) { throw err; } 47 | console.log(files); 48 | files.forEach((file) => { 49 | buildFile('target_practice', file, language); 50 | }); 51 | }); 52 | fs.readdir('warm_up/' + language, (err, files) => { 53 | if (err) { throw err; } 54 | console.log(files); 55 | files.forEach((file) => { 56 | buildFile('warm_up', file, language); 57 | }); 58 | }); 59 | fs.readdir('foundation/' + language, (err, files) => { 60 | if (err) { throw err; } 61 | console.log(files); 62 | files.forEach((file) => { 63 | specialBuildFile('foundation', file, language); 64 | }); 65 | }); 66 | }); 67 | } 68 | 69 | run(['java','js','rb','py','swift']); 70 | -------------------------------------------------------------------------------- /AlgorithmProblems/Strings/ParseExpression.js: -------------------------------------------------------------------------------- 1 | /* Given a mathematical expression as a string with prefix notation 2 | return what it would evaluate to. 3 | */ 4 | 5 | 6 | let test = "(+ (* 10 (+ 5 2) 2) 50)" 7 | 8 | function parseExpression(str) { 9 | let arr = str.split(""); //O(N) split into characters 10 | let currentNumber = ""; 11 | let newArr = []; 12 | 13 | for(let i = 0; i < arr.length; i++) { //O(N) joins numbers 14 | if(!isNaN(parseInt(arr[i]))) { 15 | currentNumber += arr[i]; 16 | } 17 | else { 18 | newArr.push(currentNumber); 19 | currentNumber = ""; 20 | newArr.push(arr[i]); 21 | } 22 | } 23 | 24 | let chars = newArr.filter(char => char != "" && char != " "); //O(N) Removes Whitespace 25 | 26 | let stack = [[]]; 27 | 28 | for(let i = 0; i < chars.length; i++) { 29 | if(chars[i] === "(") { 30 | stack.push([]); 31 | } else if(chars[i] === ")") { 32 | let top = stack.pop(); 33 | stack[stack.length - 1].push(top); 34 | } else { 35 | stack[stack.length - 1].push(chars[i]); 36 | } 37 | } 38 | 39 | return evaluateExpression(stack[0][0]) 40 | } 41 | 42 | // Takes in an array and evaluates it; 43 | function evaluateExpression(expr) { 44 | let accumulator; 45 | if(expr[0] === "*") { 46 | accumulator = 1; 47 | for(let i = 1; i < expr.length; i++) { 48 | if(Array.isArray(expr[i])) { 49 | accumulator *= evaluateExpression(expr[i]); 50 | } else { 51 | accumulator *= parseInt(expr[i]); 52 | } 53 | } 54 | 55 | } else if(expr[0] === "+") { 56 | accumulator = 0; 57 | for(let i = 1; i < expr.length; i++) { 58 | if(Array.isArray(expr[i])) { 59 | accumulator += evaluateExpression(expr[i]); 60 | } else { 61 | accumulator += parseInt(expr[i]); 62 | } 63 | } 64 | } 65 | return accumulator; 66 | } 67 | 68 | 69 | 70 | function parseExpression(str){
 71 | let res = [];
 72 | let cNum = '';
 73 | const isNum = c => '123456789.0'.includes(c);
 74 | 75 | for(let i = 0; i < str.length; i++){
 76 | if(isNum(str[i])){
 77 | cNum += str[i];
 78 | if(!isNum(str[i+1])){
 79 | res.push(Number(cNum));
 80 | cNum = '';
 81 | }
 82 | }
 83 | else if(str[i] !== ' '){ 84 | res.push(str[i]); 85 | }
 86 | }
 87 | 
 88 | return res;
 89 | } 90 | 91 | 92 | parseExpression(test) 93 | -------------------------------------------------------------------------------- /AlgorithmProblems/Arrays/MaxPopulation.js: -------------------------------------------------------------------------------- 1 | // Time: O(N + K) 2 | // Space: O(K) 3 | 4 | function maxPopulation(people) { 5 | let minBirthYear = Infinity 6 | let maxBirthYear = -Infinity 7 | 8 | people.forEach((person) => { 9 | minBirthYear = Math.min(person.born, minBirthYear); 10 | maxBirthYear = Math.max(person.born, maxBirthYear); 11 | }) 12 | 13 | let yearRange = new Array(maxBirthYear - minBirthYear + 1).fill(0); 14 | 15 | people.forEach((person) => { 16 | yearRange[person.born - minBirthYear] += 1; 17 | if(!(person.died - minBirthYear > yearRange.length)) { 18 | yearRange[person.died - minBirthYear] -= 1; 19 | } 20 | }) 21 | 22 | let currentPopulation = 0; 23 | let maxPopulation = 0; 24 | 25 | yearRange.forEach((peopleAliveThatYear) => { 26 | currentPopulation += peopleAliveThatYear; 27 | maxPopulation = Math.max(maxPopulation, currentPopulation); 28 | }) 29 | 30 | return maxPopulation; 31 | } 32 | 33 | 34 | // Time: O(N Log(N)) 35 | // Space: O(N) 36 | function maxPopulationAlternate(people) { 37 | let births = []; 38 | let deaths = []; 39 | 40 | people.forEach(person => { 41 | births.push({year: person.born, action: "born"}); 42 | deaths.push({year: person.died, action: "died"}); 43 | }) 44 | 45 | births.sort((a, b) =>{ 46 | return a.year- b.year; 47 | }) 48 | deaths.sort((a, b) =>{ 49 | return a.year- b.year; 50 | }) 51 | 52 | let i = 0; 53 | let j = 0; 54 | 55 | let currentPopulation = 0; 56 | let maxPopulation = 0; 57 | 58 | while(i < births.length && j < births.length) { 59 | if(births[i].year <= deaths[j].year) { 60 | currentPopulation += 1; 61 | maxPopulation = Math.max(maxPopulation, currentPopulation); 62 | i++; 63 | } else { 64 | currentPopulation -= 1; 65 | j++; 66 | } 67 | } 68 | return maxPopulation 69 | } 70 | 71 | 72 | 73 | let people = [ 74 | { 75 | name: "John", 76 | born: 1900, 77 | died: 1950 78 | }, 79 | { 80 | name: "John", 81 | born: 1940, 82 | died: 2000 83 | }, 84 | { 85 | name: "John", 86 | born: 1920, 87 | died: 1990 88 | }, 89 | { 90 | name: "John", 91 | born: 1960, 92 | died: 2010 93 | }, 94 | { 95 | name: "John", 96 | born: 1910, 97 | died: 1930 98 | } 99 | ] 100 | 101 | maxPopulation(people); 102 | maxPopulationAlternate(people); 103 | --------------------------------------------------------------------------------