├── java ├── .gitignore ├── tests │ ├── .gitignore │ └── DisjointSetTest.java ├── leetcode │ ├── kth-largest-element-in-an-array-215.java │ ├── power-of-two-231.java │ ├── max-subarray-53.java │ ├── palindrome-number-9.java │ ├── container-most-water-11.java │ ├── buy-sell-stock-121.java │ ├── kth-smallest-element-in-a-sorted-matrix.java │ ├── array-nesting-565.java │ ├── random-pick-index-398.java │ ├── move-zeroes-283.java │ ├── teemo-attacking-495.java │ ├── merge-sorted-array-88.java │ ├── trapping-rain-water-42.java │ ├── path-sum-112.java │ ├── missing-number-268.java │ ├── wiggle-sort-280.java │ ├── pascals-triangle-118.java │ ├── minimum-number-of-arrows-to-burst-balloons-452.java │ ├── generate-parenthesis-22.java │ ├── max-average-subarray-643.java │ ├── remove-duplicates-from-sorted-list-ii-82.java │ ├── longest-increasing-subsequence-300.java │ ├── 132-pattern-456.java │ ├── max-consecutive-ones-485.java │ ├── sum-of-square-numbers-633.java │ ├── subsets-78.java │ ├── group-anagrams-49.java │ ├── merge-sorted-linked-lists-21.java │ ├── range-sum-query-immutable-303.java │ ├── magical-strings-481.java │ ├── combination-sum-iii-216.java │ ├── longest-common-prefix-14.java │ ├── is-palindrome-125.java │ ├── count-number-with-unique-digits-357.java │ ├── target-sum-494.java │ ├── 3sum-smaller-259.java │ ├── path-sum-iii-437.java │ ├── product-of-array-except-self-238.java │ ├── shuffle-array-384.java │ ├── combination-sum-39.java │ ├── combinations-77.java │ ├── decode-ways-91.java │ ├── average-levels-of-binary-tree-637.java │ ├── is-subsequence-392.java │ ├── linked-list-random-node-382.java │ ├── plus-one-66.java │ ├── longest-substring-without-repeating-characters-3.java │ ├── path-sum-ii-113.java │ ├── path-sum-113.java │ ├── max-width-binary-tree-662.java │ ├── diagonal-traverse-498.java │ ├── intersection-of-two-linked-lists-160.java │ ├── zigzag-iterator-281.java │ ├── permutations-46.java │ ├── missing-ranges-163.java │ ├── binary-tree-level-order-traversal-ii-107.java │ ├── binary-search-tree-iterator-173.java │ ├── copy-list-with-random-pointer-138.java │ ├── next-greater-element-ii-503.java │ ├── non-overlapping-intervals-435.java │ ├── top-k-frequent-elements-347.java │ ├── phonenumber-combinations-17.java │ ├── reshape-matrix-566.java │ ├── moving-average-from-data-stream-346.java │ ├── merge-k-sorted-lists-23.java │ ├── binary-tree-inorder-traversal-94.java │ ├── flatten-nested-list-iterator-341.java │ ├── 3sum-closest-16.java │ ├── predict-the-winner-486.java │ ├── longest-absolute-file-path-388.java │ ├── number-of-islands-200.java │ ├── find-largest-val-in-each-tree-row-515.java │ ├── relative-ranks-506.java │ ├── trie-208.java │ ├── spiral-matrix-54.java │ ├── longest-substring-with-k-distinct-characters-340.java │ ├── sort-chars-by-freq-451.java │ ├── most-frequent-subtree-sum-508.java │ ├── course-schedule-iii-630.java │ ├── decode-string-394.java │ ├── next-greater-element-496.java │ ├── friend-circles-547.java │ └── unique-word-abbreviation-288.java ├── datastructures │ ├── GraphNode.java │ ├── GraphEdge.java │ └── DisjointSet.java ├── misc │ └── least-disruptive-subrange.java ├── epi │ ├── 9.6.java │ ├── 8.7-8.8.java │ ├── 9.4-9.5.java │ ├── 9.7.java │ └── 8.9-8.10.java ├── interview │ ├── column-layout.java │ └── bipartition-pattern-matching.java ├── programmingteam │ ├── Paren.java │ ├── Shuffle.java │ ├── GraphColoring.java │ ├── Polling.java │ └── Name.java ├── algorithms │ ├── DijkstraPathFinder.java │ ├── MatrixChainMultiplication.java │ ├── KruskalMST.java │ └── PrimMST.java └── test_runner.py ├── .babelrc ├── .coveralls.yml ├── .gitignore ├── spec ├── .jshintrc ├── support │ └── jasmine.json ├── math │ └── randomWeightSpec.js ├── tree │ ├── killProcessSpec.js │ ├── pathSumSpec.js │ └── columnSortSpec.js ├── string │ ├── flipParenthesisSpec.js │ ├── longestSubstringSpec.js │ ├── longestPalindromeSpec.js │ ├── palindromeSpec.js │ ├── kmpSpec.js │ └── balancedParenthesesSpec.js ├── recursion │ ├── knapsackSpec.js │ ├── numberOfPathsInMatrixSpec.js │ ├── permutationsSpec.js │ ├── pascalsTriangleSpec.js │ ├── depthFinderSpec.js │ └── staircaseSpec.js ├── array │ ├── peakSpec.js │ ├── minAdditionsSpec.js │ ├── leaderSpec.js │ ├── spiralGridSpec.js │ └── greatestSubarraySpec.js ├── sort │ └── mergesortSpec.js ├── grid │ ├── gridTraversalSpec.js │ ├── largestNeighborSpec.js │ └── largestRegionSpec.js ├── linkedlist │ ├── reverseListSpec.js │ ├── findIntersectionSpec.js │ ├── cyclicalSpec.js │ └── sumListsSpec.js ├── knn │ └── housing.json ├── search │ └── binarysearchSpec.js └── kmeans │ └── indexSpec.js ├── python └── dcp │ ├── README.md │ ├── problem5.py │ ├── problem7.py │ ├── problem9.py │ ├── problem8.py │ ├── problem1.py │ ├── problem3.py │ ├── problem4.py │ ├── problem2.py │ └── problem6.py ├── .travis.yml ├── .jshintrc ├── javascript ├── string │ ├── palindrome.js │ ├── flipParenthesis.js │ ├── longestPalindrome.js │ ├── longestSubstring.js │ ├── balancedParentheses.js │ └── longestSubsequence.js ├── trie │ ├── README.md │ └── TrieNode.js ├── tree │ ├── pathSum.js │ ├── killProcess.js │ └── TreeNode.js ├── linkedlist │ ├── reverseList.js │ ├── cyclical.js │ ├── mergeLists.js │ ├── DoublyListNode.js │ ├── sumLists.js │ └── findIntersection.js ├── array │ ├── minAdditions.js │ ├── leader.js │ ├── jumpingArray.js │ ├── peak.js │ └── spiralGrid.js ├── math │ └── randomWeight.js ├── grid │ ├── largestRegion.js │ ├── largestNeighbor.js │ └── gridTraversal.js ├── recursion │ ├── staircase.js │ ├── permutations.js │ ├── numberOfPathsInMatrix.js │ ├── pascalsTriangle.js │ ├── depthFinder.js │ └── knapsack.js ├── search │ ├── binarysearch.js │ └── README.md ├── genetic │ └── README.md ├── kmeans │ └── README.md ├── sort │ ├── README.md │ └── mergesort.js └── systemdesign │ └── README.md ├── package.json └── LICENSE /java/.gitignore: -------------------------------------------------------------------------------- 1 | input.in 2 | -------------------------------------------------------------------------------- /java/tests/.gitignore: -------------------------------------------------------------------------------- 1 | input.in 2 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["es2015"] 3 | } 4 | -------------------------------------------------------------------------------- /.coveralls.yml: -------------------------------------------------------------------------------- 1 | repo_token: 5tUaF98ljkPe9bMUT2WeyRYQhwXRcserC 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | *.class 4 | Solution.java 5 | -------------------------------------------------------------------------------- /spec/.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../.jshintrc", 3 | "jasmine": true 4 | } 5 | -------------------------------------------------------------------------------- /python/dcp/README.md: -------------------------------------------------------------------------------- 1 | ## [Daily Coding Problem](https://www.dailycodingproblem.com/) 2 | 3 | 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | node_js: 4 | - "6" 5 | 6 | sudo: false 7 | 8 | after_success: 9 | - npm run coveralls 10 | 11 | -------------------------------------------------------------------------------- /spec/support/jasmine.json: -------------------------------------------------------------------------------- 1 | { 2 | "spec_dir": "spec", 3 | "spec_files": [ 4 | "./**/*[sS]pec.js" 5 | ], 6 | "helpers": ["../node_modules/jasmine-expect/index.js"] 7 | } 8 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "node": true, 3 | 4 | "latedef": true, 5 | "quotmark": true, 6 | "undef": true, 7 | "unused": true, 8 | "trailing": true, 9 | "esnext": true 10 | } 11 | -------------------------------------------------------------------------------- /java/leetcode/kth-largest-element-in-an-array-215.java: -------------------------------------------------------------------------------- 1 | public int findKthLargest(int[] nums, int k) { 2 | // Make k 0 indexed. 3 | k --; 4 | if (k < 0 || k > nums.length) { 5 | return -1; 6 | } 7 | Arrays.sort(nums); 8 | return nums[nums.length - 1 - k]; 9 | } 10 | -------------------------------------------------------------------------------- /java/leetcode/power-of-two-231.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an integer, write a function to determine if it is a power of two. 3 | * Cute problem to do. 4 | * Complexity : O(1) time , O(1) space 5 | */ 6 | public class Solution { 7 | public boolean isPowerOfTwo(int n) { 8 | return n > 0 && Integer.bitCount(n) == 1; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /javascript/string/palindrome.js: -------------------------------------------------------------------------------- 1 | function isPalindrome(string) { 2 | if (!string.length) return false; 3 | 4 | var front = 0; 5 | var end = string.length - 1; 6 | 7 | while (front < end) { 8 | if (string.charAt(front++) != string.charAt(end--)) return false; 9 | } 10 | 11 | return true; 12 | } 13 | 14 | module.exports = isPalindrome; 15 | -------------------------------------------------------------------------------- /java/leetcode/max-subarray-53.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxSubArray(int[] nums) { 3 | int localMax = nums[0]; 4 | int globalMax = nums[0]; 5 | 6 | for (int i = 1; i < nums.length; i ++) { 7 | localMax = Math.max(nums[i], nums[i] + localMax); 8 | globalMax = Math.max(globalMax, localMax); 9 | } 10 | 11 | return globalMax; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/leetcode/palindrome-number-9.java: -------------------------------------------------------------------------------- 1 | public class Palindrome-Number-9 { 2 | public boolean isPalindrome(int x) { 3 | if (x < 10 && x > -1) return true; 4 | else if (x < 0) return false; 5 | 6 | int clone = x; 7 | int reverse = 0; 8 | while (x > 0) { 9 | reverse = (reverse * 10) + (x % 10); 10 | x /= 10; 11 | } 12 | 13 | return reverse == clone; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/datastructures/GraphNode.java: -------------------------------------------------------------------------------- 1 | package datastructures; 2 | public class GraphNode implements Comparable { 3 | int weight; 4 | int id; 5 | public GraphNode(int i, int w) { 6 | id = i; 7 | weight = w; 8 | } 9 | 10 | public int compareTo(GraphNode n) { 11 | return this.weight - n.weight; 12 | } 13 | 14 | public int index() { 15 | return id - 1; 16 | } 17 | } -------------------------------------------------------------------------------- /java/leetcode/container-most-water-11.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxArea(int[] height) { 3 | int left = 0, right = height.length - 1; 4 | int maxArea = 0; 5 | 6 | while (left < right) { 7 | maxArea = Math.max(maxArea, Math.min(height[left], height[right]) * (right - left)); 8 | if (height[left] < height[right]) left++; 9 | else right--; 10 | } 11 | 12 | return maxArea; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /javascript/trie/README.md: -------------------------------------------------------------------------------- 1 | ## Trie 2 | #### Problem 3 | A trie is similar to a tree, but the values that are stored are letters where each complete path is meant to store a word. This also goes by the name of prefix tree. The trie should have the following methods: 4 | 5 | - `insert(word)` - Add the `word` into the structure. 6 | - `match(prefix)` - Return all words that match the prefix. 7 | - `search(word)` - Return true if the word exists in the trie. 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "algorithms", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "test": "jasmine", 6 | "coverage": "istanbul cover jasmine", 7 | "coveralls": "npm run coverage && cat coverage/lcov.info | coveralls" 8 | }, 9 | "devDependencies": { 10 | "coveralls": "^2.11.15", 11 | "istanbul": "^0.4.5", 12 | "jasmine": "2.3.1", 13 | "jasmine-expect": "^3.0.1", 14 | "underscore": "1.8.3" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /spec/math/randomWeightSpec.js: -------------------------------------------------------------------------------- 1 | var randomWeight = require('../../javascript/math/randomWeight'); 2 | 3 | describe('randomWeight', () => { 4 | it('should work', () => { 5 | expect(randomWeight([1, 2, 3], [1, 1, 2])).toBeWithinRange(1, 3); 6 | expect(randomWeight([1, 2, 3], [0, 0, 1])).toEqual(3); 7 | expect(randomWeight([1, 2, 3], [0, 1, 0])).toEqual(2); 8 | expect(randomWeight([1, 2, 3], [1, 0, 0])).toEqual(1); 9 | }); 10 | }); 11 | -------------------------------------------------------------------------------- /spec/tree/killProcessSpec.js: -------------------------------------------------------------------------------- 1 | var killProcess = require('../../javascript/tree/killProcess'); 2 | 3 | describe('killProcess', () => { 4 | it('should return a list of all the connected pids', () => { 5 | expect(killProcess([1, 3, 10, 5], [3, 0, 5, 3], 5)).toEqual([5, 10]); 6 | expect(killProcess([1, 3, 10, 5], [10, 0, 5, 3], 5)).toEqual([5, 10, 1]); 7 | 8 | expect(killProcess([1, 2, 3], [0, 1, 1], 1)).toEqual([1, 2, 3]); 9 | }); 10 | }); 11 | -------------------------------------------------------------------------------- /spec/string/flipParenthesisSpec.js: -------------------------------------------------------------------------------- 1 | var flip = require('../../javascript/string/flipParenthesis'); 2 | 3 | 4 | describe('flip parenthesis', () => { 5 | it('should work', () => { 6 | expect(flip('(((())))')).toEqual(0); 7 | expect(flip('(()(((')).toEqual(2); 8 | expect(flip('))((')).toEqual(2); 9 | expect(flip('))(())((((')).toEqual(3); 10 | expect(flip('(())((')).toEqual(1); 11 | expect(flip(')))(()')).toEqual(2); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /javascript/tree/pathSum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a tree, return true if there exists a path where the sum equals k. 3 | * 4 | * @param {TreeNode} root 5 | * @param {Int} k 6 | * @return {Boolean} 7 | */ 8 | function pathSum(root, k) { 9 | if (!root) return false; 10 | else if (root.value === k && root.isLeaf()) return true; 11 | 12 | return pathSum(root.left, k - root.value) || pathSum(root.right, k - root.value); 13 | } 14 | 15 | module.exports = pathSum; 16 | -------------------------------------------------------------------------------- /java/leetcode/buy-sell-stock-121.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxProfit(int[] prices) { 3 | if (prices.length < 2) return 0; 4 | int max = 0; 5 | int s = 0; 6 | int e = 1; 7 | while (e < prices.length) { 8 | max = Math.max(max, prices[e] - prices[s]); 9 | if (prices[s] < prices[e]) { 10 | e ++; 11 | } else { 12 | s ++; 13 | e = s + 1; 14 | } 15 | } 16 | return max; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/leetcode/kth-smallest-element-in-a-sorted-matrix.java: -------------------------------------------------------------------------------- 1 | public int kthSmallest(int[][] grid, int k) { 2 | PriorityQueue q = new PriorityQueue<>(); 3 | for (int i = 0; i < grid.length; i ++) { 4 | for (int j = 0; j < grid[i].length; j ++) { 5 | q.add(grid[i][j]); 6 | } 7 | } 8 | 9 | // Subtract one from K to make it 0 indexed. 10 | k --; 11 | for (int i = 0; i < k; i ++) { 12 | q.poll(); 13 | } 14 | 15 | return q.poll(); 16 | } 17 | -------------------------------------------------------------------------------- /spec/string/longestSubstringSpec.js: -------------------------------------------------------------------------------- 1 | var longestSubstring = require('../../javascript/string/longestSubstring'); 2 | 3 | describe('longestSubstring', () => { 4 | it('should return the longest substring', () => { 5 | expect(longestSubstring('abcde')).toEqual(5); 6 | expect(longestSubstring('aabbc')).toEqual(2); 7 | expect(longestSubstring('aabcde')).toEqual(5); 8 | expect(longestSubstring('abcacder')).toEqual(5); 9 | expect(longestSubstring('abcabacade')).toEqual(4); 10 | }); 11 | }); -------------------------------------------------------------------------------- /spec/recursion/knapsackSpec.js: -------------------------------------------------------------------------------- 1 | var knapsack = require('../../javascript/recursion/knapsack'); 2 | 3 | describe('knapsack', () => { 4 | it('should return an array of indexes', () => { 5 | expect(knapsack([2, 2, 4, 5], [3, 7, 2, 9], 10)).toEqual([0, 1, 3]); 6 | }); 7 | 8 | it('should work for a lot of items', () => { 9 | expect(knapsack([2, 4, 1, 4, 5, 12, 3, 5, 3, 12, 31, 51], 10 | [1, 3, 12, 31, 4, 3, 1, 4, 9, 7, 4, 19], 20)).toEqual([0, 2, 3, 4, 7, 8]); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /java/datastructures/GraphEdge.java: -------------------------------------------------------------------------------- 1 | package datastructures; 2 | 3 | public class GraphEdge implements Comparable { 4 | int weight; 5 | int id1; 6 | int id2; 7 | 8 | public GraphEdge(int a, int b, int weight) { 9 | this.weight = weight; 10 | id1 = a; 11 | id2 = b; 12 | } 13 | 14 | public int getA() { return id1; } 15 | public int getB() { return id2; } 16 | 17 | public int compareTo(GraphEdge n) { 18 | return this.weight - n.weight; 19 | } 20 | } -------------------------------------------------------------------------------- /java/leetcode/array-nesting-565.java: -------------------------------------------------------------------------------- 1 | public int largestNest(int[] arr) { 2 | if (arr.length == 0) return 0; 3 | int max = 1; 4 | 5 | for (int i = 0; i < arr.length; i ++) { 6 | int j = arr[i]; 7 | int count = 1; 8 | 9 | // Follow the cycle and mark each value as -1 (visited) so we dont repeat values. 10 | while (j >= 0 && j != i) { 11 | int temp = arr[j]; 12 | arr[j] = -1; 13 | j = arr[j]; 14 | count ++; 15 | } 16 | max = Math.max(max, count); 17 | } 18 | 19 | return max; 20 | } -------------------------------------------------------------------------------- /javascript/linkedlist/reverseList.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('./ListNode'); 2 | 3 | /** 4 | * Given a linked list, return a linked list in reverse order. 5 | * 6 | * @param {ListNode} list 7 | * @return {ListNode} 8 | */ 9 | function reverseList(list) { 10 | var clone = new ListNode(-1); 11 | 12 | while(list) { 13 | var temp = new ListNode(list.value); 14 | temp.next = clone.next; 15 | clone.next = temp; 16 | list = list.next; 17 | } 18 | 19 | return clone.next; 20 | } 21 | 22 | module.exports = reverseList; 23 | -------------------------------------------------------------------------------- /spec/array/peakSpec.js: -------------------------------------------------------------------------------- 1 | var peak = require('../../javascript/array/peak'); 2 | 3 | describe('peak', () => { 4 | it('should find a peak element', () => { 5 | expect([4, 7]).toContain(peak([1, 4, 3, 6, 7, 5])); 6 | expect([4, 9]).toContain(peak([1, 4, 2, 3, 6, 7, 9])); 7 | }); 8 | 9 | it('should work for end elements', () => { 10 | expect([8]).toContain(peak([1, 2, 3, 4, 5, 6, 7, 8])); 11 | }); 12 | 13 | it('should work for start elements', () => { 14 | expect([5]).toContain(peak([5, 4, 3, 2, 1])); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /python/dcp/problem5.py: -------------------------------------------------------------------------------- 1 | # This problem was asked by Jane Street. 2 | # cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. 3 | # For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. 4 | # Given this implementation of cons: 5 | 6 | def cons(a, b): 7 | return lambda f : f(a, b) 8 | 9 | # Implement car and cdr. 10 | 11 | def car(fn): 12 | return fn(lambda a, b: a) 13 | 14 | def cdr(fn): 15 | return fn(lambda a, b: b) 16 | 17 | print(car(cons(3,4))) 18 | print(cdr(cons(3,4))) -------------------------------------------------------------------------------- /java/leetcode/random-pick-index-398.java: -------------------------------------------------------------------------------- 1 | // TODO: use reservoir sampling 2 | public class Solution { 3 | int[] nums; 4 | 5 | public Solution(int[] nums) { 6 | this.nums = nums; 7 | } 8 | 9 | public int pick(int target) { 10 | List list = new ArrayList(); 11 | for (int i = 0 ; i < nums.length; i ++ ) { 12 | if (this.nums[i] == target) { 13 | list.add(i); 14 | } 15 | } 16 | 17 | int length = list.size(); 18 | int random = (int)(Math.random() * length); 19 | return list.get(random); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/leetcode/move-zeroes-283.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 3 | */ 4 | public class Solution { 5 | public void moveZeroes(int[] nums) { 6 | int i = 0; 7 | int j = 0; 8 | if (nums.length == 0) return; 9 | while (j < nums.length) { 10 | if (nums[j] == 0) { 11 | j++; 12 | continue; 13 | } 14 | 15 | nums[i] = nums[j]; 16 | i ++; 17 | j ++; 18 | } 19 | for (;i < nums.length; i ++) nums[i] = 0; 20 | } 21 | } -------------------------------------------------------------------------------- /javascript/array/minAdditions.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Find the minimum number of operations to equalize all values in a unique array. 3 | * An operation is incrementing a value by 1. 4 | * 5 | * Ex. [1, 2, 3] requires 3 operations to make [3, 3, 3]. 6 | * 7 | * @param {Array} array 8 | * @return {Int} 9 | */ 10 | function minAdditions(array) { 11 | var min = Number.MAX_SAFE_INTEGER; 12 | var sum = 0; 13 | 14 | for (var i in array) { 15 | sum += array[i]; 16 | min = Math.min(min, array[i]); 17 | } 18 | 19 | return sum - (min * array.length); 20 | } 21 | 22 | module.exports = minAdditions; 23 | -------------------------------------------------------------------------------- /java/leetcode/teemo-attacking-495.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | // O(n) soultion, n being the size timeSeries. 3 | public int findPoisonedDuration(int[] timeSeries, int duration) { 4 | if (timeSeries.length == 0) { 5 | return 0; 6 | } 7 | int start = timeSeries[0]; 8 | int total = 0; 9 | 10 | for (int i = 0; i < timeSeries.length; i++) { 11 | if (timeSeries[i] < duration + start) { 12 | total += timeSeries[i] - start; 13 | } else { 14 | total += duration; 15 | } 16 | start = timeSeries[i]; 17 | } 18 | return total + duration; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/leetcode/merge-sorted-array-88.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void merge(int[] nums1, int m, int[] nums2, int n) { 3 | int p = m + n - 1; 4 | int a = m - 1; 5 | int b = n - 1; 6 | while (p >= 0) { 7 | if (a == -1) { 8 | nums1[p] = nums2[b--]; 9 | } else if (b == -1) { 10 | nums1[p] = nums1[a--]; 11 | } else if (nums1[a] > nums2[b]) { 12 | nums1[p] = nums1[a--]; 13 | } else if (nums1[a] < nums2[b]) { 14 | nums1[p] = nums2[b--]; 15 | } else { 16 | nums1[p] = nums1[a--]; 17 | } 18 | 19 | p --; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /javascript/math/randomWeight.js: -------------------------------------------------------------------------------- 1 | function randomWeight(array, weights) { 2 | var total = weights.reduce((a, b) => a + b, 0); 3 | var standard = 1 / total; 4 | var start = 0; 5 | var ranges = array.map((current, index) => { 6 | var weight = weights[index]; 7 | var range = [start, (standard * weight) + start]; 8 | start = (standard * weight) + start; 9 | return range; 10 | }); 11 | 12 | var random = Math.random(); 13 | for (var i in ranges) { 14 | var range = ranges[i]; 15 | if (range[0] <= random && range[1] >= random) return array[i]; 16 | } 17 | return -1; 18 | } 19 | 20 | module.exports = randomWeight; 21 | -------------------------------------------------------------------------------- /java/leetcode/trapping-rain-water-42.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int trap(int[] height) { 3 | int left = 0; 4 | int right = height.length - 1; 5 | int leftMax = 0; 6 | int rightMax = 0; 7 | int max = 0; 8 | 9 | while (left < right) { 10 | leftMax = Math.max(leftMax, height[left]); 11 | rightMax = Math.max(rightMax, height[right]); 12 | 13 | 14 | if (height[right] > height[left]) { 15 | max += leftMax - height[left]; 16 | left ++; 17 | } else { 18 | max += rightMax - height[right]; 19 | right --; 20 | 21 | } 22 | } 23 | return max; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /java/leetcode/path-sum-112.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given a binary tree and a sum, 4 | * determine if the tree has a root-to-leaf path such that adding up 5 | * all the values along the path equals the given sum. 6 | */ 7 | public class Solution { 8 | public boolean hasPathSum(TreeNode root, int sum) { 9 | if (root == null) return false; 10 | if (isLeaf(root)) { 11 | return sum == root.val; 12 | } 13 | 14 | return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); 15 | } 16 | 17 | public boolean isLeaf(TreeNode node) { 18 | return node != null && node.left == null && node.right == null; 19 | } 20 | } -------------------------------------------------------------------------------- /javascript/array/leader.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers, print the leaders in the array. 3 | * A leader is an element which is larger than all the elements in the array to its right. 4 | * 5 | * @param {Array} array 6 | * @return {Array} 7 | */ 8 | function leader(array) { 9 | if (!array.length) return array; 10 | 11 | var currentLeader = array[array.length - 1]; 12 | var leaders = [currentLeader]; 13 | for (var i = array.length - 2; i >= 0; i--) { 14 | if (array[i] > currentLeader) { 15 | leaders.push(array[i]); 16 | currentLeader = array[i]; 17 | } 18 | } 19 | 20 | return leaders; 21 | } 22 | 23 | module.exports = leader; 24 | -------------------------------------------------------------------------------- /spec/sort/mergesortSpec.js: -------------------------------------------------------------------------------- 1 | var mergesort = require('../../javascript/sort/mergesort'); 2 | 3 | describe('mergesort', () => { 4 | it('should sort an unsorted array', () => { 5 | var array = [1, 9, 2, 8, 3, 7, 4, 6, 5]; 6 | expect(mergesort(array)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]); 7 | }); 8 | 9 | it('should work for an empty array', () => { 10 | expect(mergesort([])).toEqual([]); 11 | }); 12 | 13 | it('should work for an array of a single value', () => { 14 | expect(mergesort([1])).toEqual([1]); 15 | }); 16 | 17 | it('should work for an already sorted array', () => { 18 | expect(mergesort([1, 2, 3])).toEqual([1, 2, 3]); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /spec/string/longestPalindromeSpec.js: -------------------------------------------------------------------------------- 1 | var longestPalindrome = require('../../javascript/string/longestPalindrome'); 2 | 3 | describe('longestPalindrome', () => { 4 | it('should return the longest palindrome', () => { 5 | expect(longestPalindrome('babad')).toEqual('bab'); 6 | expect(longestPalindrome('aslkdjlaksjdklasjdklracecarasjlkdjaslkdjskla')).toEqual('racecar'); 7 | expect(longestPalindrome('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbcccddddddddddd')) 8 | .toEqual('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'); 9 | expect(longestPalindrome('aaaabaaa')).toEqual('aaabaaa'); 10 | }); 11 | }); 12 | -------------------------------------------------------------------------------- /java/leetcode/missing-number-268.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, 3 | * find the one that is missing from the array. 4 | * 5 | * The trick is to find the ideal sum if the missing number is included. 6 | * This can be found in constant time because if the array contains all numbers from 0 - n, 7 | * then the sum is just n * (n + 1) / 2. 8 | * The missing number is then just the difference between the ideal sum and the actual sum. 9 | */ 10 | public class Solution { 11 | public int missingNumber(int[] nums) { 12 | int n = nums.length; 13 | int sum = ((n) * (n + 1))/ 2; 14 | int current = 0; 15 | for (int i : nums) current += i; 16 | return sum - current; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /python/dcp/problem7.py: -------------------------------------------------------------------------------- 1 | # This problem was asked by Facebook. 2 | # Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. 3 | # For example, the message '111' would give 3, since it could be decoded as 'aaa, 'ka', and 'ak'. 4 | 5 | def encoding(input): 6 | length = len(input) 7 | arr = [0] * (length + 1) 8 | arr[0] = 1 9 | 10 | for i in range(1, length + 1): 11 | if input[i - 1] != '0': 12 | arr[i] = arr[i - 1] 13 | 14 | double_digit = input[i - 2:i] 15 | if i > 1 and double_digit > '09' and double_digit < '27': 16 | arr[i] += arr[i - 2] 17 | 18 | return arr[length] 19 | 20 | assert(3 == encoding('111')) 21 | assert(2 == encoding('12')) -------------------------------------------------------------------------------- /java/leetcode/wiggle-sort-280.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... 3 | * For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. 4 | * pretty cute problem to do. Key for this is to draw the sort yourself, helps with writing the algo out. 5 | * Complexity : O(nlog(n)) time, O(1) space 6 | */ 7 | 8 | public class Solution { 9 | public void wiggleSort(int[] nums) { 10 | Arrays.sort(nums); 11 | for (int i = 1; i < nums.length; i+=2){ 12 | int swap = i + 1; 13 | if (i + 1 < nums.length) { 14 | int temp = nums[i]; 15 | nums[i] = nums[swap]; 16 | nums[swap] = temp; 17 | } 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /javascript/linkedlist/cyclical.js: -------------------------------------------------------------------------------- 1 | function cyclical(node) { 2 | if (!node) return false; 3 | 4 | var runner = node; 5 | 6 | while (runner.next && runner.next.next) { 7 | node = node.next; 8 | runner = runner.next.next; 9 | 10 | if (node === runner) return true; 11 | } 12 | 13 | // If the list ever reaches the end, then there can't be a cycle. 14 | return false; 15 | } 16 | 17 | // This requires the node object to be mutable. 18 | function mutatingCyclical(node) { 19 | while (node.next) { 20 | if (node.visited) return true; 21 | node.visited = true; 22 | node = node.next; 23 | } 24 | 25 | // If the list ever reaches the end, then there can't be a cycle. 26 | return false; 27 | } 28 | 29 | module.exports = cyclical; 30 | -------------------------------------------------------------------------------- /spec/array/minAdditionsSpec.js: -------------------------------------------------------------------------------- 1 | var minAdditions = require('../../javascript/array/minAdditions'); 2 | 3 | describe('minAdditions', () => { 4 | it('should find the minimum number of operations', () => { 5 | expect(minAdditions([1, 2, 3])).toEqual(3); 6 | }); 7 | 8 | it('should find the minimum number of operations', () => { 9 | expect(minAdditions([1, 2, 3, 4])).toEqual(6); 10 | }); 11 | 12 | it('should find the minimum number of operations', () => { 13 | expect(minAdditions([1, 10, 20, 30, 40, 50])).toEqual(145); 14 | expect(minAdditions([50, 40, 30, 20, 10, 1])).toEqual(145); 15 | }); 16 | 17 | it('should find the minimum number of operations', () => { 18 | expect(minAdditions([1, 2, 4, 5])).toEqual(8); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /java/leetcode/pascals-triangle-118.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Generate and return the first n rows of pascal's triangle 3 | */ 4 | public class Solution { 5 | public List> generate(int n) { 6 | List> list = new ArrayList>()); 7 | triangle(n, 0, list); 8 | return list; 9 | } 10 | 11 | public void triangle(int n, int index, List> list) { 12 | if (index == n) return; 13 | List cur = new ArrayList(); 14 | cur.add(1); 15 | for (int i = 1; i < index; i ++) { 16 | List above = list.get(index - 1); 17 | cur.add(above.get(i) + above.get(i - 1)); 18 | } 19 | if (index > 0) cur.add(1); 20 | list.add(cur); 21 | triangle(n, index + 1, list); 22 | } 23 | } -------------------------------------------------------------------------------- /javascript/tree/killProcess.js: -------------------------------------------------------------------------------- 1 | module.exports = function(pid, ppid, kill) { 2 | var table = {}; 3 | 4 | // Populate the hash table. 5 | for (var i = 0; i < ppid.length; i ++) { 6 | if (ppid[i] === 0) continue; 7 | var list = table[ppid[i]]; 8 | if (!list) list = []; 9 | list.push(pid[i]); 10 | table[ppid[i]] = list; 11 | } 12 | 13 | var results = []; 14 | var queue = []; 15 | queue.push(kill); 16 | 17 | // Use bfs to find all connected pids. 18 | while (queue.length > 0) { 19 | var elem = queue.shift(); 20 | results.push(elem); 21 | if (!table[elem]) continue; 22 | var l = table[elem]; 23 | 24 | for (var i = 0; i < l.length; i ++) 25 | queue.push(l[i]); 26 | } 27 | 28 | return results; 29 | } 30 | 31 | -------------------------------------------------------------------------------- /java/leetcode/minimum-number-of-arrows-to-burst-balloons-452.java: -------------------------------------------------------------------------------- 1 | public int findMinArrowShots(int[][] points) { 2 | if (points.length <= 1) { 3 | return points.length; 4 | } 5 | 6 | // Sort the list so that we can take a greedy approach. 7 | Arrays.sort(points, (a, b) -> a[1] - b[1]); 8 | 9 | // Keep track of the number of arrows. 10 | int count = 0; 11 | 12 | // The index of where the last arrow was shot. 13 | int index = 0; 14 | for (int i = 0; i < points.lenght; i ++) { 15 | // If the current point starts past the current index. 16 | // Then, we must shoot another arrow to hit the current balloon. 17 | if (points[i][0] > index) { 18 | count ++; 19 | index = points[i][1]; 20 | } 21 | } 22 | 23 | return count; 24 | } 25 | -------------------------------------------------------------------------------- /spec/grid/gridTraversalSpec.js: -------------------------------------------------------------------------------- 1 | var gridTraversal = require('../../javascript/grid/gridTraversal'); 2 | 3 | describe('gridTraversal', () => { 4 | beforeEach(() => { 5 | this.grid = [ 6 | [1,2,3], 7 | [4,5,6], 8 | [7,8,9] 9 | ]; 10 | }); 11 | 12 | it('should return the traversal path', () => { 13 | expect(gridTraversal(this.grid, 0, 0)).toEqual([1, 4, 7, 8, 9, 6, 5, 2, 3]); 14 | }); 15 | 16 | it('should skip neighbors with values less than 0', () => { 17 | this.grid[1][0] = 0; 18 | expect(gridTraversal(this.grid, 0, 0)).toEqual([1, 2, 5, 8, 9, 6, 3]); 19 | }); 20 | 21 | it('should return the path from any location', () => { 22 | expect(gridTraversal(this.grid, 1, 1)).toEqual([5, 8, 9, 6, 3, 2, 1, 4, 7]); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /spec/grid/largestNeighborSpec.js: -------------------------------------------------------------------------------- 1 | var largestNeighbor = require('../../javascript/grid/largestNeighbor'); 2 | 3 | describe('largestNeighbor', () => { 4 | beforeAll(() => { 5 | this.grid = [ 6 | [1,2,3], 7 | [4,5,6], 8 | [7,8,9] 9 | ]; 10 | }); 11 | 12 | it('should return the largest neighbor', () => { 13 | expect(largestNeighbor(this.grid, 1, 0)).toEqual({x: 1, y: 1}); 14 | }); 15 | 16 | it('should skip out of bounds neighbors', () => { 17 | expect(largestNeighbor(this.grid, 0, 0)).toEqual({x: 0, y: 1}); 18 | expect(largestNeighbor(this.grid, 2, 2)).toEqual({x: 1, y: 2}); 19 | }); 20 | 21 | it('should skip diagonal neighbors', () => { 22 | expect(largestNeighbor(this.grid, 1, 1)).toEqual({x: 1, y: 2}); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /java/leetcode/generate-parenthesis-22.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | */ 4 | public class Solution { 5 | public List generateParenthesis(int n) { 6 | List list = new ArrayList(); 7 | helper(n, 0, 0, "", list); 8 | return list; 9 | } 10 | 11 | void helper(int n, int i, int j, String s, List list) { 12 | if (i + j == 2 * n) { 13 | list.add(s); 14 | return; 15 | } 16 | 17 | // First, add all the opening parenthesis. 18 | if (i < n) helper(n, i + 1, j, s + "(", list); 19 | 20 | // If there is an unmatched parenthesis, then add a matching closing one. 21 | if (j != i) helper(n, i, j + 1, s + ")", list); 22 | } 23 | } -------------------------------------------------------------------------------- /java/misc/least-disruptive-subrange.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public static int[] findLeastDisruptiveSubrange(int[] arr, int[] replace) { 3 | if (arr.length == 0 || replace.length == 0 || arr.length < replace.length) { 4 | return new int[2]; 5 | } 6 | 7 | 8 | int minI = 0; 9 | int minJ = 0; 10 | int minDiff = Integer.MAX_VALUE;; 11 | for (int i = 0; i < arr.length - replace.length; i ++) { 12 | int cur = 0; 13 | for (int j = 0; j < replace.length; j ++) { 14 | cur += Math.abs(arr[i + j] - replace[j]); 15 | } 16 | 17 | if (cur < minDiff) { 18 | minI = i; 19 | minJ = i + replace.length - 1; 20 | minDiff = cur; 21 | } 22 | } 23 | 24 | return new int[] { minI, minJ }; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /javascript/linkedlist/mergeLists.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('./ListNode'); 2 | 3 | /** 4 | * Given two sorted lists, return a new list that contains 5 | * the nodes in each list in order. 6 | * 7 | * @param {ListNode} a 8 | * @param {ListNode} b 9 | * @return {ListNode} 10 | */ 11 | function mergeLists(a, b) { 12 | if (!a && !b) return null; 13 | var merged = new ListNode(-1); 14 | var clone = merged; 15 | 16 | while (a || b) { 17 | if ((a ? a.value : Number.MAX_VALUE) > (b ? b.value : Number.MAX_VALUE)) { 18 | merged.next = b; 19 | b = b ? b.next : b; 20 | } else { 21 | merged.next = a; 22 | a = a ? a.next : a; 23 | } 24 | 25 | merged = merged.next 26 | } 27 | 28 | return clone.next; 29 | } 30 | 31 | module.exports = mergeLists; 32 | -------------------------------------------------------------------------------- /python/dcp/problem9.py: -------------------------------------------------------------------------------- 1 | # This problem was asked by Airbnb. 2 | # Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. 3 | # For example, [2, 4, 6, 8] should return 12, since we pick 4 and 8. [5, 1, 1, 5] should return 10, since we pick 5 and 5. 4 | 5 | def maxNonAdjacentSum(arr): 6 | length = len(arr) 7 | if length == 0: 8 | return 0 9 | incl = arr[0] 10 | excl = 0 11 | 12 | for i in range(1, length): 13 | tmp = max(incl, excl) 14 | incl = arr[i] + excl 15 | excl = tmp 16 | 17 | return max(incl, excl) 18 | 19 | assert(maxNonAdjacentSum([2, 4, 6, 8]) == 12) 20 | assert(maxNonAdjacentSum([5, 1, 1, 5]) == 10) 21 | assert(maxNonAdjacentSum([5, 5, 10, 100, 10, 5]) == 110) -------------------------------------------------------------------------------- /java/epi/9.6.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a list of building heights, return a subset of building that can view the westward sun. 3 | * All buildings only have windows facing the west. 4 | * Therefore, if a building west of another building is taller, then the second building cannot see the sun. 5 | * Ex. [1, 2, 3, 4] => [1, 2, 3, 4] 6 | * [4, 3, 2, 1] => [] 7 | * [1, 3, 2, 5, 4, 7] => [1, 3, 5, 7] 8 | */ 9 | public List buildings(int[] heights) { 10 | List result = new ArrayList(); 11 | int index = 0; 12 | int currentMax = 0; 13 | 14 | while (index < heights.length) { 15 | if (heights[index] > currentMax) result.add(heights[index]); 16 | currentMax = Math.max(currentMax, heights[index]); 17 | index ++; 18 | } 19 | return result; 20 | } 21 | -------------------------------------------------------------------------------- /java/leetcode/max-average-subarray-643.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value. 3 | * 4 | * The solution is trivial as there are n - k + 1 subarrays. 5 | */ 6 | public class Solution { 7 | public double findMaxAverage(int[] nums, int k) { 8 | if (nums.length == 0) return Integer.MIN_VALUE; 9 | double sum = 0; 10 | for (int i = 0; i < k && i < nums.length; i ++) { 11 | sum += nums[i]; 12 | } 13 | double max = sum / k; 14 | int i = 0; 15 | int j = k; 16 | while (j < nums.length) { 17 | sum = sum - nums[i++] + nums[j++]; 18 | max = Math.max(max, sum / k); 19 | } 20 | 21 | return max; 22 | } 23 | } -------------------------------------------------------------------------------- /spec/string/palindromeSpec.js: -------------------------------------------------------------------------------- 1 | var isPalindrome = require('../../javascript/string/palindrome'); 2 | 3 | describe('isPalindrome', () => { 4 | it('should return true for valid palindromes', () => { 5 | expect(isPalindrome('cac')).toBeTruthy(); 6 | expect(isPalindrome('aba')).toBeTruthy(); 7 | expect(isPalindrome('abba')).toBeTruthy(); 8 | expect(isPalindrome('aaaa')).toBeTruthy(); 9 | expect(isPalindrome('aaa')).toBeTruthy(); 10 | expect(isPalindrome('abcba')).toBeTruthy(); 11 | expect(isPalindrome('c')).toBeTruthy(); 12 | }); 13 | 14 | it('should return false for invalid palindromes', () => { 15 | expect(isPalindrome('cat')).toBeFalsy(); 16 | expect(isPalindrome('')).toBeFalsy(); 17 | expect(isPalindrome('askdjsalkjdklasj')).toBeFalsy(); 18 | }); 19 | }); 20 | -------------------------------------------------------------------------------- /java/leetcode/remove-duplicates-from-sorted-list-ii-82.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 3 | */ 4 | public class Solution { 5 | public ListNode deleteDuplicates(ListNode head) { 6 | if (head == null) return head; 7 | ListNode temp = new ListNode(-1); 8 | temp.next = head; 9 | ListNode pre = temp; 10 | ListNode cur = head; 11 | while (cur != null) { 12 | while (cur.next != null && cur.val == cur.next.val) { 13 | cur = cur.next; 14 | } 15 | 16 | if(pre.next == cur) { 17 | pre = pre.next; 18 | } else { 19 | pre.next = cur.next; 20 | } 21 | cur = cur.next; 22 | } 23 | return temp.next; 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /javascript/string/flipParenthesis.js: -------------------------------------------------------------------------------- 1 | function flipParen(paren) { 2 | var list = []; 3 | for (var i = 0; i < paren.length; i ++) { 4 | if (paren.charAt(i) == '(') { 5 | list.push('('); 6 | } else if (paren.charAt(i) == ')' && list[list.length - 1] == '(') { 7 | list.pop(); 8 | } else { 9 | list.push(paren.charAt(i)); 10 | } 11 | } 12 | 13 | if (list.length == 0) return 0; 14 | 15 | // Count the number of open and close left. 16 | // The result will be the sum of half of each. 17 | var open = 0; 18 | var close = 0; 19 | for (var j = 0; j < list.length; j ++) { 20 | if (list[j] == '(') { 21 | open ++; 22 | } else { 23 | close ++; 24 | } 25 | } 26 | 27 | return (open / 2) + (close / 2); 28 | } 29 | 30 | module.exports = flipParen; 31 | -------------------------------------------------------------------------------- /java/leetcode/longest-increasing-subsequence-300.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an unsorted array of integers, find the length of longest increasing subsequence. 3 | */ 4 | public int longestSubsequence(int[] arr) { 5 | if (arr.length == 0) return 0; 6 | int[] dp = new int[arr.length]; 7 | 8 | // The subsequence at least contains itself. 9 | for (int i = 0; i < arr.length; i ++) 10 | dp[i] = 1; 11 | 12 | int j = 0; 13 | int k = 1; 14 | int max = 1; 15 | 16 | // For every arr[k], find all arr[j] < arr[k]. 17 | while (k < arr.length) { 18 | if (j == k) { 19 | max = Math.max(max, dp[k]); 20 | k ++; 21 | j = 0; 22 | continue; 23 | } 24 | if (arr[j] < arr[k]) { 25 | dp[k] = Math.max(dp[k], dp[j] + 1); 26 | } 27 | j ++; 28 | } 29 | 30 | return max; 31 | } -------------------------------------------------------------------------------- /spec/recursion/numberOfPathsInMatrixSpec.js: -------------------------------------------------------------------------------- 1 | var numberOfPathsInMatrix = require('../../javascript/recursion/numberOfPathsInMatrix'); 2 | 3 | describe('numberOfPathsInMatrix', () => { 4 | it('should return the number of paths in the matrix', () => { 5 | expect(numberOfPathsInMatrix([ 6 | [0, 1, 1], 7 | [0, 0, 1], 8 | [1, 0, 0] 9 | ])).toEqual(1); 10 | }); 11 | 12 | it('should return the number of paths in the matrix', () => { 13 | expect(numberOfPathsInMatrix([ 14 | [0, 0, 0], 15 | [0, 0, 0], 16 | [0, 0, 0] 17 | ])).toEqual(6); 18 | }); 19 | 20 | it('should return the number of paths in the matrix', () => { 21 | expect(numberOfPathsInMatrix([ 22 | [0, 1, 1], 23 | [1, 1, 1], 24 | [1, 1, 0] 25 | ])).toEqual(0); 26 | }); 27 | }); 28 | -------------------------------------------------------------------------------- /java/leetcode/132-pattern-456.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public boolean find132pattern(int[] nums) { 4 | // Keep track of the global minimum. 5 | // The global min will be the ai value. 6 | int min = Integer.MAX_VALUE; 7 | for (int j = 0; j < nums.length; j++) { 8 | min = Math.min(nums[j], min); 9 | 10 | // If the current value is the minimum, 11 | // then this is the ai value for this current iteration. 12 | if (min == nums[j]) continue; 13 | 14 | // Otherwise, it is not the minimum so let nums[j] be aj 15 | for (int k = nums.length - 1; k > j; k--) { 16 | 17 | // If there is a valid ak, after j then return true; 18 | if (min < nums[k] && nums[k] < nums[j]) return true; 19 | } 20 | } 21 | 22 | return false; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /java/interview/column-layout.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @Company Pinterest 3 | * 4 | * Given a number of columns and an array of pin objects, return an array containing the optimal height of each column. 5 | * A pin object is defined as: 6 | * 7 | * class Pin { 8 | * int height; 9 | * } 10 | * 11 | * The optimal heights for the column will minimize the height of the largest column. 12 | */ 13 | public int[] columnLayout(int k, Pin[] pins) { } 14 | 15 | 16 | /** 17 | * Part two will expand on the pin object to be: 18 | * 19 | * class Pin { 20 | * int height; 21 | * int width; 22 | * } 23 | * 24 | * You are also given the width of the column, so that any pin that does not equal the column's width 25 | * must be resized proportionally to fit the column. 26 | */ 27 | public int[] columnLayout(int k, int width, Pin[] pins) { } 28 | -------------------------------------------------------------------------------- /java/leetcode/max-consecutive-ones-485.java: -------------------------------------------------------------------------------- 1 | /** 2 | *Given a binary array, find the maximum number of consecutive 1s in this array. 3 | *Input: [1,1,0,1,1,1] 4 | *Output: 3 5 | *Complexity O(n) time , and O(1) space. 6 | *trick count the number of ones until you see a different number and record the Max value as you go along. 7 | *When you see if reset the count. 8 | */ 9 | public class Solution { 10 | public int findMaxConsecutiveOnes(int[] nums) { 11 | int numOfOnes = 0; 12 | int numOfConsecutiveOnes = Integer.MIN_VALUE; 13 | for (int i = 0; i < nums.length; i++) { 14 | if (nums[i] != 1) { 15 | numOfOnes = 0; 16 | } else { 17 | numOfOnes++; 18 | } 19 | numOfConsecutiveOnes = Math.max(numOfOnes, numOfConsecutiveOnes); 20 | } 21 | return numOfConsecutiveOnes; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /javascript/array/jumpingArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of non-negative integers, starting at the beginning of the array where each 3 | * element in the array represents your maximum jumping distance at that position. 4 | * Determine if reaching the end index is possible. 5 | * 6 | * @param {Array} array 7 | * @return {Boolean} 8 | */ 9 | function jumpingArray(array) { 10 | // Start the pointer at the end of the array. 11 | var pointer = array.length - 1; 12 | 13 | for (var i = array.length - 1; i >= 0; i --) { 14 | 15 | // If the current index is able to reach the pointer, then update the pointer 16 | if (i + array[i] >= pointer) pointer = i; 17 | } 18 | 19 | // The pointer must be at the start index if there is a viable path. 20 | return pointer === 0; 21 | } 22 | 23 | module.exports = jumpingArray; 24 | -------------------------------------------------------------------------------- /java/leetcode/sum-of-square-numbers-633.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a^2 + b^2 = c. 3 | * Input: 5 4 | * Output: True 5 | * Explanation: 1 * 1 + 2 * 2 = 5 6 | * Complexity : O(Sqrt(N)) time, O(Sqrt(N)) space 7 | */ 8 | public class Solution { 9 | public boolean judgeSquareSum(int c) { 10 | if (c <= 1) { 11 | return true; 12 | } 13 | 14 | Set set = new HashSet<>(); 15 | for (int a = 0; a < (int) Math.sqrt(c) + 1; a++) { 16 | int b = c - (a * a); // b^2 val; 17 | set.add(b); 18 | } 19 | 20 | // checking if the b^2 exits. 21 | for (int b = 0; b < (int) Math.sqrt(c) + 1; b++) { 22 | if (set.contains(b * b)) { 23 | return true; 24 | } 25 | } 26 | return false; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java/leetcode/subsets-78.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a set of distinct integers, nums, return all possible subsets. 3 | * Including the null set. 4 | */ 5 | public List> subsets(int[] nums) { 6 | List> list = new ArrayList>(); 7 | helper(nums, 0, list, new ArrayList()); 8 | return list; 9 | } 10 | 11 | public void helper(int[] nums, int index, List> list, List cur) { 12 | // The base case is to add the current set. 13 | list.add(new ArrayList(cur)); 14 | for (int i = index; i < nums.length; i ++) { 15 | // Add the next value. 16 | cur.add(nums[i]); 17 | // Find all potential subsets building off the current set. 18 | helper(nums, i + 1, list, cur); 19 | // Backtrack by removing the current value. 20 | cur.remove(cur.size() - 1); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /python/dcp/problem8.py: -------------------------------------------------------------------------------- 1 | # This problem was asked by Google. 2 | # A unival tree (which stands for "universal value") is a tree where all nodes have the same value. 3 | # Given the root to a binary tree, count the number of unival subtrees. 4 | 5 | class TreeNode(object): 6 | def __init__(self, x): 7 | self.val = x 8 | self.left = None 9 | self.right = None 10 | 11 | def unival(root): 12 | count = [0] 13 | helper(root, count) 14 | return count[0] 15 | 16 | def helper(node, count): 17 | if node is None: 18 | return True 19 | left = helper(node.left, count) 20 | right = helper(node.right, count) 21 | 22 | if left and right and node.left != None and node.right != None and node.left.val == node.val and node.right.val == node.val: 23 | count[0] += 1 24 | return True 25 | 26 | return False -------------------------------------------------------------------------------- /java/leetcode/group-anagrams-49.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> groupAnagrams(String[] strs) { 3 | HashMap> map = new HashMap>(); 4 | 5 | for (String s: strs) { 6 | char[] chars = s.toCharArray(); 7 | Arrays.sort(chars); 8 | String temp = new String(chars); 9 | if (map.containsKey(temp)) { 10 | List list = map.get(temp); 11 | list.add(s); 12 | map.put(temp, list); 13 | } else { 14 | List list = new ArrayList(); 15 | list.add(s); 16 | map.put(temp, list); 17 | } 18 | } 19 | 20 | List> result = new ArrayList>(); 21 | 22 | for (String key: map.keySet()) { 23 | result.add(map.get(key)); 24 | } 25 | 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java/leetcode/merge-sorted-linked-lists-21.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 11 | ListNode head = new ListNode(-1); 12 | ListNode clone = head; 13 | while (l1 != null || l2 != null) { 14 | if (l1 == null) { 15 | head.next = l2; 16 | l2 = l2.next; 17 | } else if (l2 == null) { 18 | head.next = l1; 19 | l1 = l1.next; 20 | } else if (l1.val > l2.val) { 21 | head.next = l2; 22 | l2 = l2.next; 23 | } else { 24 | head.next = l1; 25 | l1 = l1.next; 26 | } 27 | head = head.next; 28 | } 29 | 30 | return clone.next; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/programmingteam/Paren.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Stack; 3 | 4 | public class Paren { 5 | public static void main(String[] args) { 6 | Scanner s = new Scanner(System.in); 7 | String line = s.next(); 8 | Stack stack = new Stack(); 9 | 10 | for (int i = 0; i < line.length(); i++) { 11 | if (line.charAt(i) == '(') { 12 | stack.push(line.charAt(i)); 13 | } else if (line.charAt(i) == ')') { 14 | if (stack.empty()) { 15 | System.out.println("Unbalanced"); 16 | return; 17 | } 18 | stack.pop(); 19 | } else { 20 | System.out.println("Unbalanced"); 21 | return; 22 | } 23 | } 24 | 25 | if (stack.empty()) { 26 | System.out.println("Balanced"); 27 | } else { 28 | System.out.println("Unbalanced"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /python/dcp/problem1.py: -------------------------------------------------------------------------------- 1 | # Given an array of numbers, return whether any two sums to K. 2 | # For example, given [10, 15, 3, 7] and K of 17, return true since 10 + 7 is 17. 3 | 4 | def two_sum(arr, target): 5 | seen = set() 6 | for num in arr: 7 | complement = target - num 8 | if complement in seen: 9 | return True 10 | seen.add(num) 11 | return False 12 | 13 | print(two_sum([10, 15, 3, 7], 17)) 14 | print(two_sum([10, 15, 3, 7], 10)) 15 | print(two_sum([1, 2, -5, 5, -10, 20, -25], 0)) 16 | print(two_sum([1, 2, -5, 5, -10, 20, -25], 10)) 17 | print(two_sum([1, 2, -5, 5, -10, 20, -25], 15)) 18 | print(two_sum([1, 2, -5, 5, -10, 20, -25], 25)) 19 | print(two_sum([1, 2, -5, 5, -10, 20, -25], 1)) 20 | print(two_sum([1, 2, -5, 5, -10, 20, -25], 11)) 21 | print(two_sum([1, 2, -5, 5, -10, 20, -25], 16)) 22 | print(two_sum([1, 2, -5, 5, -10, 20, -25], 26)) 23 | -------------------------------------------------------------------------------- /spec/array/leaderSpec.js: -------------------------------------------------------------------------------- 1 | var leader = require('../../javascript/array/leader'); 2 | 3 | describe('leader', () => { 4 | it('should return all leaders in the array', () => { 5 | expect(leader([98, 23, 54, 12, 20, 7, 27])).toEqual([27, 54, 98]); 6 | expect(leader([1, 2, 3, 4, 5])).toEqual([5]); 7 | expect(leader([5, 4, 3, 2, 1])).toEqual([1, 2, 3, 4, 5]); 8 | expect(leader([5])).toEqual([5]); 9 | 10 | // This is me spamming a bunch of number keys 11 | expect(leader([243,14,124,124,124,12,412,412,4312,312,3,125,124,2543,51245,224531,425,12352,314,235564214,5651,3124,12,412,4123,5431435423,5,23453,54,12435,142,5423,56124,526,4235,234,235,235,234,243,565241345436,5124,526,5134,1235,245,2341,325,3])).toEqual([3, 325, 2341, 5134, 565241345436]); 12 | }); 13 | 14 | it('should work for empty arrays', () => { 15 | expect(leader([])).toEqual([]); 16 | }); 17 | 18 | }); 19 | -------------------------------------------------------------------------------- /javascript/grid/largestRegion.js: -------------------------------------------------------------------------------- 1 | function largestRegion(grid) { 2 | var score = 0; 3 | for (var row in grid) { 4 | for (var col in grid[row]) { 5 | if (grid[row][col] === 1) score = Math.max(score, findRegionSize(grid, row, col)); 6 | } 7 | } 8 | 9 | return score; 10 | } 11 | 12 | function findRegionSize(grid, row, col) { 13 | row = Number(row); 14 | col = Number(col); 15 | if (row < 0 || col < 0 || row >= grid.length || col >= grid[row].length) return 0; 16 | else if (grid[row][col] === 0) return 0; 17 | 18 | // Mark as visited by setting to 0. 19 | grid[row][col] = 0; 20 | var size = 1; 21 | 22 | for (var r = row - 1; r <= row + 1; r++) { 23 | for (var c = col - 1; c <= col + 1; c++) { 24 | if (r !== row || c !== col) size += findRegionSize(grid, r, c); 25 | } 26 | } 27 | 28 | return size; 29 | } 30 | 31 | module.exports = largestRegion; 32 | -------------------------------------------------------------------------------- /javascript/trie/TrieNode.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | 3 | /** 4 | * A single node that represents a letter in the trie structure. 5 | * 6 | * @param {String} letter 7 | */ 8 | function TrieNode(letter) { 9 | assert(letter.length === 1, 'letter must be a single character'); 10 | this.letter = letter; 11 | // Store each trie node's children using a table indexed by the letters. 12 | this.children = {}; 13 | // A boolean value to mark if the current partial string is a complete string. 14 | this.complete = false; 15 | // Keep track of the complete words that this node is a part of. 16 | this.matches = []; 17 | } 18 | 19 | TrieNode.prototype.toArray = function(array) { 20 | if (this.complete) array.push(...this.matches); 21 | for (var i in this.children) { 22 | this.children[i].toArray(array); 23 | } 24 | return array; 25 | } 26 | 27 | module.exports = TrieNode; 28 | -------------------------------------------------------------------------------- /java/leetcode/range-sum-query-immutable-303.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 3 | */ 4 | public class NumArray { 5 | 6 | int[] sums; 7 | public NumArray(int[] nums) { 8 | sums = new int[nums.length]; 9 | n = nums; 10 | 11 | // Make a running sum array. 12 | for (int i = 0; i < nums.length; i ++) { 13 | if (i == 0) { 14 | sums[i] = nums[i]; 15 | } else { 16 | sums[i] = nums[i] + sums[i - 1]; 17 | } 18 | } 19 | } 20 | 21 | public int sumRange(int i, int j) { 22 | if (i == 0) return sums[j]; 23 | if (i == j) return n[i]; 24 | 25 | // If the range does not start at 0, then subtract the difference of the sum leading up to the beginning of the range. 26 | int diff = sums[i]; 27 | return sums[j] - diff + n[i]; // Add back n[i] because the range is inclusive. 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /spec/recursion/permutationsSpec.js: -------------------------------------------------------------------------------- 1 | var permutations = require('../../javascript/recursion/permutations'); 2 | 3 | describe('permutations', () => { 4 | it('should return all permutations of arrays', () => { 5 | var result = permutations([[1, 2], [3, 4]]); 6 | expect(result).toContain([3, 2]); 7 | expect(result).toContain([3, 1]); 8 | expect(result).toContain([4, 2]); 9 | expect(result).toContain([4, 1]); 10 | }); 11 | 12 | it('should return all permutations of arrays', () => { 13 | var result = permutations([[1, 2], [3], [4, 5], [6, 7]]) 14 | expect(result).toEqual([ 15 | [ 6, 4, 3, 1 ], 16 | [ 6, 4, 3, 2 ], 17 | [ 6, 5, 3, 1 ], 18 | [ 6, 5, 3, 2 ], 19 | [ 7, 4, 3, 1 ], 20 | [ 7, 4, 3, 2 ], 21 | [ 7, 5, 3, 1 ], 22 | [ 7, 5, 3, 2 ] 23 | ]); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /java/leetcode/magical-strings-481.java: -------------------------------------------------------------------------------- 1 | public class magicalStrings-481 { 2 | public int magicalString(int n) { 3 | if (n == 0) { 4 | return 0; 5 | } else if(n <= 3) { 6 | return 1; 7 | } 8 | 9 | int[] seq = sequenceMaker(n); 10 | int counter = 0; 11 | for (int i = 0; i < n; i++) { 12 | counter += seq[i] == 1 ? 1 : 0; 13 | } 14 | return counter; 15 | } 16 | 17 | private int[] sequenceMaker(int n){ 18 | int[] sequence = new int[n + 1]; 19 | sequence[0] = 1; 20 | sequence[1] = 2; 21 | sequence[2] = 2; 22 | int tail = 3; 23 | int head = 2; 24 | while (tail < n) { 25 | int element = sequence[tail - 1] == 2 ? 1 : 2; 26 | int frequency = sequence[head]; 27 | for (int i = 0; i < frequency; i++) { 28 | sequence[tail] = element; 29 | tail++; 30 | } 31 | 32 | head++; 33 | } 34 | return sequence; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /java/leetcode/combination-sum-iii-216.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Find all possible combinations of k numbers that add up to a number n, 3 | * given that only numbers from 1 to 9 can be used and each combination 4 | * should be a unique set of numbers. 5 | */ 6 | public class Solution { 7 | public List> combinationSum3(int k, int n) { 8 | List> list = new ArrayList>(); 9 | helper(k, n, 1, list, new ArrayList()); 10 | return list; 11 | } 12 | 13 | void helper(int k, int n, int i, List> list, List cur) { 14 | if (n == 0 && cur.size() == k) { 15 | list.add(new ArrayList(cur)); 16 | return; 17 | } else if (n < 0) { 18 | return; 19 | } 20 | 21 | for (int index = i; index < 10; index ++) { 22 | cur.add(index); 23 | helper(k, n - index, index + 1, list, cur); 24 | cur.remove(cur.size() - 1); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /java/leetcode/longest-common-prefix-14.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String longestCommonPrefix(String[] strs) { 3 | if( strs.length == 0) return ""; 4 | StringBuilder res = new StringBuilder(); 5 | int i = 0; 6 | 7 | // get the length of the shortest string 8 | int shortestString = getShortestString(strs); 9 | 10 | while (i < shortestString) { 11 | char c = strs[0].charAt(i); 12 | for ( int j = 0; j < strs.length; j++) { 13 | if(c != strs[j].charAt(i)){ 14 | return res.toString(); 15 | } 16 | } 17 | i++; 18 | res.append(c); 19 | 20 | } 21 | return res.toString(); 22 | } 23 | 24 | 25 | public int getShortestString(String[] strings) { 26 | int minHeight = Integer.MAX_VALUE; 27 | for(int i = 0; i < strings.length; i++) { 28 | minHeight = Math.min(minHeight, strings[i].length()); 29 | } 30 | return minHeight; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/programmingteam/Shuffle.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Arrays; 3 | import java.util.Collections; 4 | 5 | public class Shuffle { 6 | public static void main(String[] args) { 7 | Scanner s = new Scanner(System.in); 8 | int count = Integer.parseInt(s.next()); 9 | String[] things = new String[count]; 10 | int half = count / 2; 11 | int counter = 1; 12 | if (count % 2 != 0) { 13 | half ++; 14 | counter ++; 15 | } 16 | for (int i = 0; i= 0 && !isValid(s.charAt(j))) j --; 22 | } 23 | return true; 24 | 25 | } 26 | 27 | public boolean isValid(Character c) { 28 | return Character.isLetter(c) || Character.isDigit(c); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /spec/linkedlist/reverseListSpec.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('../../javascript/linkedlist/ListNode'); 2 | var reverseList = require('../../javascript/linkedlist/reverseList'); 3 | 4 | describe('reverseList', () => { 5 | it('should reverse a linked list', () => { 6 | var a = new ListNode(1); 7 | a.append([2, 3, 4, 5, 6]); 8 | expect(reverseList(a).toArray()).toEqual([6, 5, 4, 3, 2, 1]); 9 | }); 10 | 11 | it('should reverse a linked list', () => { 12 | var a = new ListNode(1); 13 | expect(reverseList(a).toArray()).toEqual([1]); 14 | }); 15 | 16 | it('should reverse a linked list', () => { 17 | var a = new ListNode(1); 18 | a.append([123,12,312,3,123,4151,23,14,13,13,1,4215,34,6,67,4321,456,32,145,6321,4534,2,13,534,2421,36,523414,23,634,6521,412,532,53]); 19 | expect(reverseList(a).toArray()).toEqual([53,532,412,6521,634,23,523414,36,2421,534,13,2,4534,6321,145,32,456,4321,67,6,34,4215,1,13,13,14,23,4151,123,3,312,12,123,1]); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /javascript/string/longestPalindrome.js: -------------------------------------------------------------------------------- 1 | function longestPalindrome(string) { 2 | if (!string.length) return null; 3 | else if (string.length === 1) return string; 4 | 5 | var front = 0; 6 | var back = 0; 7 | var length = 1; 8 | 9 | for (var i = 0; i < string.length; i ++) { 10 | var odd = findMaxPalindrome(string, i, i); 11 | var even = findMaxPalindrome(string, i, i + 1); 12 | 13 | if (length < odd[0]) { 14 | length = odd[0]; 15 | front = odd[1]; 16 | back = odd[2]; 17 | } 18 | 19 | if (length < even[0]) { 20 | length = even[0]; 21 | front = even[1]; 22 | back = even[2]; 23 | } 24 | } 25 | 26 | return string.substring(front, back); 27 | } 28 | 29 | function findMaxPalindrome(string, i, j) { 30 | while (i > -1 && j < string.length && string.charAt(i) === string.charAt(j)) { 31 | i --; 32 | j ++; 33 | } 34 | 35 | return [j - i + 1, i + 1, j]; 36 | } 37 | 38 | module.exports = longestPalindrome; 39 | -------------------------------------------------------------------------------- /java/leetcode/count-number-with-unique-digits-357.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10^n. 3 | * 4 | * This is a simple counting problem and be solved using combinatorics. 5 | * For every additional digit, there is n - 1 remaining digits since one was just used. 6 | * Because there are only 10 total digits, all combinations where n > 10 is equal to n = 10. 7 | * The base case is where n = 0 and the answer is 1. 8 | */ 9 | public class Solution { 10 | public int countNumbersWithUniqueDigits(int n) { 11 | if (n > 10) n = 10; 12 | if (n == 0) return 1; 13 | 14 | int[] dp = new int[n + 1]; 15 | int sum = dp[0] = 1; 16 | 17 | for (int i = 1; i <= n; i ++) { 18 | if (i == 1) { 19 | dp[i] = sum = 9; 20 | continue; 21 | } 22 | 23 | int inverse = 10 - (i - 1); 24 | dp[i] = dp[i - 1] * inverse; 25 | sum += dp[i]; 26 | } 27 | 28 | return sum; 29 | } 30 | } -------------------------------------------------------------------------------- /java/leetcode/target-sum-494.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Problem: You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. 3 | * Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. 4 | * To approach this problem think of a recursion tree with different two different possibility where you can subtract or add 5 | * Complexity: O(2^n) time and O(n) space (recursion stack trace) where n is the length of nums. 6 | */ 7 | public class Solution { 8 | 9 | public int findTargetSumWays(int[] nums, int S) { 10 | if (nums.length == 0) return 0; 11 | 12 | return helper(nums, S, 0, 0 ); 13 | } 14 | 15 | private int helper(int[] nums, int sum, int index, int curr) { 16 | if (index == nums.length) return curr == sum ? 1 : 0; 17 | index ++; 18 | 19 | int plus = helper(nums, sum, index, curr + nums[index]); 20 | int minus = helper(nums, sum, index, curr - nums[index]); 21 | return plus + minus; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /javascript/recursion/permutations.js: -------------------------------------------------------------------------------- 1 | // Find all permutations of an array of arrays. 2 | function permutations(arrays) { 3 | return recursivePermutations(arrays, 0); 4 | } 5 | 6 | function recursivePermutations(arrays, index) { 7 | var temp; 8 | // Bottoms up approach. 9 | if (index < arrays.length - 1) { 10 | // Get the initial array from the end. 11 | temp = recursivePermutations(arrays, index + 1); 12 | } else { 13 | // Start with an array of a single empty array. 14 | temp = [ [ ] ] ; 15 | } 16 | 17 | var result = [] 18 | for (var i = 0; i < temp.length; i ++) { 19 | var current = temp[i]; 20 | 21 | for (var j = 0; j < arrays[index].length; j ++) { 22 | // Update the current array and add to result. 23 | current.push(arrays[index][j]); 24 | result.push(current.slice()); 25 | 26 | // Backtrack by removing the value. 27 | current.pop() 28 | } 29 | } 30 | 31 | return result; 32 | } 33 | 34 | module.exports = permutations; 35 | -------------------------------------------------------------------------------- /java/leetcode/3sum-smaller-259.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n 3 | * that satisfy the condition nums[i] + nums[j] + nums[k] < target. 4 | * For example, given nums = [-2, 0, 1, 3], and target = 2. 5 | * key for this problem is to elimaniate 3 unknowns to only having 2 unknowns to get the Complexity fron n^3 to n^2. 6 | * Complexity : O(N^2) time, O(1) space 7 | */ 8 | public class Solution { 9 | public int threeSumSmaller(int[] nums, int target) { 10 | Arrays.sort(nums); 11 | int result = 0; 12 | int j = 0; 13 | 14 | for (int i = 0; i < nums.length; i++) { 15 | int sum = target - nums[i]; 16 | j = i + 1; 17 | int k = nums.length - 1; 18 | while (j < k) { 19 | if (nums[j] + nums[k] >= sum) { 20 | k--; 21 | } else { 22 | result += k - j; 23 | j++; 24 | } 25 | } 26 | } 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java/leetcode/path-sum-iii-437.java: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given a binary tree in which each node contains an integer value. 3 | * Find the number of paths that sum to a given value. 4 | * The path does not need to start or end at the root or a leaf, 5 | * but it must go downwards (traveling only from parent nodes to child nodes). 6 | */ 7 | public class Solution { 8 | public int pathSum(TreeNode root, int sum) { 9 | if (root == null) return 0; 10 | return helper(root, sum, sum, 0); 11 | } 12 | 13 | public int helper(TreeNode node, int sum, int original, int count) { 14 | if (node == null) return count; 15 | if (sum == node.val) count ++; 16 | 17 | int left = helper(node.left, sum - node.val, original, count); 18 | int right = helper(node.right, sum - node.val, original, count); 19 | int startLeft = helper(node.left, original - node.val, original, count); 20 | int startRight = helper(node.right, original - node.val, original, count); 21 | return left + right; 22 | } 23 | } -------------------------------------------------------------------------------- /java/leetcode/product-of-array-except-self-238.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of n integers where n > 1, nums, 3 | * return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 4 | * 5 | * Solve it without division and in O(n). 6 | * 7 | * For example, given [1,2,3,4], return [24,12,8,6]. 8 | * This problem took me a while to do the optimal solution without timing out, but the trick is to split the problem by doing 9 | * left to right, and then right to left. 10 | * Complexity : O(n) time, O(N) space 11 | */ 12 | 13 | public class Solution { 14 | public int[] productExceptSelf(int[] nums) { 15 | int[] res = new int[nums.length]; 16 | Arrays.fill(res, 1); 17 | for (int i = 1; i < nums.length; i++) { 18 | res[i] = nums[i - 1] * res[i - 1]; 19 | } 20 | int down = 1; 21 | for (int j = nums.length - 1; j >= 0; j--) { 22 | res[j] *= down; 23 | down *= nums[j]; 24 | } 25 | return res; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /javascript/linkedlist/DoublyListNode.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('./ListNode'); 2 | 3 | function DoublyListNode(value) { 4 | if (value === undefined || value === null) throw new TypeError('Invalid DoublyListNode value'); 5 | else if (typeof value === 'number') value = [value]; 6 | 7 | this.value = value.shift(); 8 | this.prev = null; 9 | while (value.length) { 10 | var next = this.next = new DoublyListNode(value); 11 | next.prev = this; 12 | } 13 | } 14 | 15 | DoublyListNode.prototype = ListNode.prototype; 16 | DoublyListNode.prototype.constructor = DoublyListNode; 17 | 18 | /** 19 | * Remove the current node from its position in the list. 20 | * 21 | * @return {DoublyListNode} 22 | */ 23 | DoublyListNode.prototype.removeFromList = function() { 24 | var node = this; 25 | 26 | if (node.prev) node.prev.next = node.next; 27 | if (node.next) node.next.prev = node.prev; 28 | 29 | node.next = node.prev = null; 30 | return node; 31 | }; 32 | 33 | module.exports = DoublyListNode; 34 | -------------------------------------------------------------------------------- /javascript/linkedlist/sumLists.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('./ListNode'); 2 | /** 3 | * Given two linked lists, in reverse order, return a new list with the sum of the two lists. 4 | * 5 | * Example: 6 | * 1 -> 2 -> 3 (321) 7 | * 4 -> 5 -> 6 (654) 8 | * ------------------- 9 | * 5 -> 7 -> 9 (975) 10 | * 11 | * @param {ListNode} a 12 | * @param {ListNode} b 13 | * @return {ListNode} 14 | */ 15 | function sumLists(a, b) { 16 | var sum = new ListNode(-1); 17 | var clone = sum; 18 | var carry = 0; 19 | 20 | while (a || b) { 21 | var currentSum = (a ? a.value : 0) + (b ? b.value : 0) + carry; 22 | if (currentSum > 9) { 23 | carry = 1; 24 | currentSum = currentSum - 10; 25 | } else { 26 | carry = 0; 27 | } 28 | 29 | clone = clone.next = new ListNode(currentSum); 30 | a = a ? a.next : a; 31 | b = b ? b.next : b; 32 | } 33 | 34 | if (carry) clone.next = new ListNode(carry); 35 | 36 | return sum.next; 37 | } 38 | 39 | module.exports = sumLists; 40 | -------------------------------------------------------------------------------- /javascript/array/peak.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array, find a peak element in the array. 3 | * Peak element is the element which is greater than or equal to its neighbors. 4 | * 5 | * @param {Array} array 6 | * @return {Int} 7 | */ 8 | function peak(array) { 9 | return findPeak(array, 0, array.length - 1); 10 | } 11 | 12 | function findPeak(array, start, end) { 13 | var middle = parseInt((start + end) / 2); 14 | 15 | if (start > end) return null; 16 | else if (isPeak(array, middle)) return array[middle]; 17 | else if (array[middle] < array[middle - 1]) return findPeak(array, start, middle - 1); 18 | 19 | return findPeak(array, middle + 1, end); 20 | } 21 | 22 | function isPeak(array, index) { 23 | if (!array.length) return false; 24 | 25 | var right = array[index] > array[index + 1]; 26 | var left = array[index] > array[index - 1]; 27 | 28 | if (index === 0) return right; 29 | else if (index === array.length - 1) return left; 30 | 31 | return left && right; 32 | } 33 | 34 | module.exports = peak; 35 | -------------------------------------------------------------------------------- /java/leetcode/shuffle-array-384.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Shuffle a set of numbers without duplicates. 3 | * @return the random shuffling of the given array. 4 | */ 5 | public class Solution { 6 | 7 | int[] original; 8 | public Solution(int[] nums) { 9 | this.original = nums; 10 | } 11 | 12 | /** Resets the array to its original configuration and return it. */ 13 | public int[] reset() { 14 | return this.original; 15 | } 16 | 17 | /** Returns a random shuffling of the array. */ 18 | public int[] shuffle() { 19 | int[] clone = new int[original.length]; 20 | for (int i = 0; i < clone.length; i ++) { 21 | clone[i] = original[i]; 22 | } 23 | int[] arr = new int[clone.length]; 24 | int len = clone.length; 25 | 26 | for (int i = 0; i < clone.length; i ++) { 27 | int index = (int)(Math.random() * (len--)); 28 | arr[i] = clone[index]; 29 | clone[index] = clone[len]; 30 | } 31 | 32 | return arr; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /java/leetcode/combination-sum-39.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a set of candidate numbers (C) (without duplicates) and a target number (T), 3 | * find all unique combinations in C where the candidate numbers sums to T. 4 | * The same repeated number may be chosen from C unlimited number of times. 5 | */ 6 | public class Solution { 7 | public List> combinationSum(int[] candidates, int target) { 8 | Arrays.sort(candidates); 9 | List> list = new ArrayList>(); 10 | helper(candidates, target, list, new ArrayList(), 0); 11 | return list; 12 | } 13 | 14 | public void helper(int[] arr, int target, List> list, List cur, int index) { 15 | if (target == 0) { 16 | list.add(new ArrayList(cur)); 17 | return; 18 | } 19 | if (target < 0) return; 20 | for (int i = index; i < arr.length; i ++) { 21 | cur.add(arr[i]); 22 | helper(arr, target - arr[i], list, cur, i); 23 | cur.remove(cur.size() - 1); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /spec/knn/housing.json: -------------------------------------------------------------------------------- 1 | [{ "rooms": 1, "area": 350, "type": "apartment" },{ "rooms": 2, "area": 300, "type": "apartment" },{ "rooms": 3, "area": 300, "type": "apartment" },{ "rooms": 4, "area": 250, "type": "apartment" },{ "rooms": 4, "area": 500, "type": "apartment" },{ "rooms": 4, "area": 400, "type": "apartment" },{ "rooms": 5, "area": 450, "type": "apartment" },{ "rooms": 7, "area": 850, "type": "house" },{ "rooms": 7, "area": 900, "type": "house" },{ "rooms": 7, "area": 1200, "type": "house" },{ "rooms": 8, "area": 1500, "type": "house" },{ "rooms": 9, "area": 1300, "type": "house" },{ "rooms": 8, "area": 1240, "type": "house" },{ "rooms": 10, "area": 1700, "type": "house" },{ "rooms": 9, "area": 1000, "type": "house" },{ "rooms": 1, "area": 800, "type": "flat" },{ "rooms": 3, "area": 900, "type": "flat" },{ "rooms": 2, "area": 700, "type": "flat" },{ "rooms": 1, "area": 900, "type": "flat" },{ "rooms": 2, "area": 1150, "type": "flat" },{ "rooms": 1, "area": 1000, "type": "flat" },{ "rooms": 2, "area": 1200, "type": "flat" },{ "rooms": 1, "area": 1300, "type": "flat" }] 2 | -------------------------------------------------------------------------------- /java/leetcode/combinations-77.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 3 | */ 4 | public class Solution { 5 | public List> combine(int n, int k) { 6 | int[] arr = new int[n]; 7 | for (int i = 0; i < n; i ++) { 8 | arr[i] = i + 1; 9 | } 10 | 11 | List> list = new ArrayList>(); 12 | helper(arr, 0, list, new ArrayList(), k); 13 | return list; 14 | } 15 | 16 | public void helper(int[] nums, int index, List> list, List cur, int k) { 17 | // The base case is to add the current set. 18 | if (cur.size() == k) list.add(new ArrayList(cur)); 19 | for (int i = index; i < nums.length; i ++) { 20 | // Add the next value. 21 | cur.add(nums[i]); 22 | // Find all potential subsets building off the current set. 23 | helper(nums, i + 1, list, cur, k); 24 | // Backtrack by removing the current value. 25 | cur.remove(cur.size() - 1); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /java/leetcode/decode-ways-91.java: -------------------------------------------------------------------------------- 1 | /** 2 | * A message containing letters from A-Z is being encoded to numbers using the following mapping: 3 | * 'A' -> 1 4 | * 'B' -> 2 5 | * ... 6 | * 'Z' -> 26 7 | * Given an encoded message containing digits, determine the total number of ways to decode it. 8 | */ 9 | public class Solution { 10 | public int numDecodings(String s) { 11 | if (s.equals("0")) return 0; 12 | if (s.length() <= 1) return s.length(); 13 | return helper(s, 0, new int[s.length()]); 14 | } 15 | 16 | public int helper(String s, int i, int[] memo) { 17 | if (i >= s.length()) return 1; 18 | if (s.charAt(i) == '0') return 0; 19 | if (memo[i] > 0) return memo[i]; 20 | 21 | int count = helper(s, i + 1, memo); 22 | if (i == s.length() - 1) { 23 | memo[i] = count; 24 | return count; 25 | } 26 | 27 | int doubledigit = Integer.parseInt(s.substring(i, i + 2)); 28 | if (doubledigit <= 26) { 29 | count += helper(s, i + 2, memo); 30 | } 31 | memo[i] = count; 32 | return count; 33 | } 34 | } -------------------------------------------------------------------------------- /java/programmingteam/GraphColoring.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | import java.util.Scanner; 4 | 5 | public class GraphColoring { 6 | int numVertex; 7 | ArrayList adj[]; 8 | 9 | GraphColoring(int num) { 10 | adj = new ArrayList[num]; 11 | this.numVertex = num; 12 | } 13 | 14 | void addEdge(int a, int b) { 15 | if (a == b) return; 16 | adj[a].add(b); 17 | adj[b].add(a); 18 | } 19 | 20 | int color() { 21 | int colors = new int[numVertex]; 22 | 23 | return 1; 24 | } 25 | 26 | public static void main(String[] args) { 27 | Scanner s = new Scanner(System.in); 28 | int n = s.nextInt(); 29 | GraphColoring graph = new GraphColoring(n); 30 | for (int i = 0; i < n; i++) { 31 | graph.adj[i] = new ArrayList<>(); 32 | String line = s.nextLine(); 33 | String[] tokens = line.split("\\s"); 34 | for (String t: tokens) { 35 | graph.adj[i].add(Integer.parseInt(t)); 36 | } 37 | } 38 | System.out.println(graph.color()); 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /java/leetcode/average-levels-of-binary-tree-637.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a non-empty binary tree, return the average value of the nodes on each level 3 | * in the form of an array. 4 | */ 5 | public class Solution { 6 | public List averageOfLevels(TreeNode root) { 7 | 8 | Queue queue = new LinkedList(); 9 | List list = new ArrayList(); 10 | queue.add(root); 11 | 12 | int cur = 1; 13 | int count = 1; 14 | int next = 0; 15 | double sum = 0; 16 | 17 | while(!queue.isEmpty()) { 18 | TreeNode node = queue.poll(); 19 | cur --; 20 | sum += node.val; 21 | 22 | if (node.left != null) { 23 | next ++; 24 | queue.add(node.left); 25 | } 26 | 27 | if (node.right != null) { 28 | next ++; 29 | queue.add(node.right); 30 | } 31 | 32 | if (cur == 0) { 33 | cur = next; 34 | list.add(sum / count); 35 | count = next; 36 | next = 0; 37 | sum = 0; 38 | } 39 | } 40 | 41 | return list; 42 | } 43 | } -------------------------------------------------------------------------------- /javascript/string/longestSubstring.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a string, find the length of the longest substring without repeating characters. 3 | * @param {string} s 4 | * @return {number} 5 | */ 6 | function lengthOfLongestSubstring(s) { 7 | if (!s.length) return 0; 8 | 9 | // Convert to char array. 10 | var arr = s.split(''); 11 | var length = 0; 12 | 13 | // Mapping of character to its occuring index. 14 | var table = {}; 15 | var i = 0; 16 | 17 | // Iterate through the string. 18 | for (var j = 0;j < arr.length; j++) { 19 | 20 | // If the character has already exists, then move the start pointer. 21 | if (table[arr[j]] !== undefined) { 22 | // since character, arr[j], already exists then move i. 23 | // if i is already past that occurence, then leave it. 24 | // if i is behind the occurence, then move it in front of it. 25 | i = Math.max(i, table[arr[j]] + 1); 26 | } 27 | table[arr[j]] = j; 28 | length = Math.max(length, j - i + 1); 29 | } 30 | 31 | return length; 32 | } 33 | 34 | module.exports = lengthOfLongestSubstring; -------------------------------------------------------------------------------- /java/leetcode/is-subsequence-392.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a string s and a string t, check if s is subsequence of t. 3 | * You may assume that there is only lower case English letters in both s and t. 4 | * t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100). 5 | * A subsequence of a string is a new string which is formed from the original string by deleting some 6 | * (can be none) of the characters without disturbing the relative positions of the remaining characters. 7 | * (ie, "ace" is a subsequence of "abcde" while "aec" is not). 8 | */ 9 | public class Solution { 10 | public boolean isSubsequence(String s, String t) { 11 | // An empty string is a subsequence of everything. 12 | if (s.length() == 0) return true; 13 | // There are no subsequences of an empty string. 14 | if (t.length() == 0) return false; 15 | 16 | int k = 0; 17 | for (int i = 0; i < t.length(); i ++) { 18 | if (t.charAt(i) == s.charAt(k)) k ++; 19 | if (k >= s.length()) return true; 20 | } 21 | 22 | return k >= s.length(); 23 | } 24 | } -------------------------------------------------------------------------------- /javascript/search/binarysearch.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A binary search runs in o(logn) by decreasing the search boundaries by half for each iteration. 3 | * @param {Array} array The array to search in. 4 | * @param {Int} value The value to search for. 5 | * @return {Int} The index of the found value or -1 if not found. 6 | */ 7 | function binarysearch(array, value) { 8 | // Create the initial boundaries containing the entire array.. 9 | var left = 0; 10 | var right = array.length - 1; 11 | // Iterate through the array until the boundaries collide. 12 | while (left <= right) { 13 | // Calculate the midpoint. 14 | var midpoint = Math.floor((right + left) / 2); 15 | if (array[midpoint] === value) { 16 | return midpoint; 17 | // Upper half. 18 | } else if (array[midpoint] < value) { 19 | left = midpoint + 1; 20 | // Lower half. 21 | } else if (array[midpoint] > value) { 22 | right = midpoint - 1; 23 | } 24 | } 25 | // A collision has occured but the value was not found. 26 | return -1; 27 | } 28 | 29 | module.exports = binarysearch; 30 | -------------------------------------------------------------------------------- /java/leetcode/linked-list-random-node-382.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | 11 | /** @param head The linked list's head. 12 | Note that the head is guaranteed to be not null, so it contains at least one node. */ 13 | ListNode node = null; 14 | public Solution(ListNode head) { 15 | this.node = head; 16 | 17 | } 18 | 19 | /** Returns a random node's value. */ 20 | public int getRandom() { 21 | ListNode head = node; 22 | ListNode res = node; 23 | int size = 0; 24 | while(head != null){ 25 | size++; 26 | head = head.next; 27 | } 28 | int randomProb = (int)(Math.random() * size); 29 | for(int i = 0; i < randomProb; i++){ 30 | res = res.next; 31 | 32 | } 33 | return res.val; 34 | } 35 | } 36 | 37 | /** 38 | * Your Solution object will be instantiated and called as such: 39 | * Solution obj = new Solution(head); 40 | * int param_1 = obj.getRandom(); 41 | */ 42 | -------------------------------------------------------------------------------- /java/leetcode/plus-one-66.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. 3 | * You may assume the integer do not contain any leading zero, except the number 0 itself. 4 | * The digits are stored such that the most significant digit is at the head of the list. 5 | */ 6 | public class Solution { 7 | public int[] plusOne(int[] digits) { 8 | // Start as 1 so that we dont need to add extra code to truly add one. 9 | int carry = 1; 10 | for (int i = digits.length - 1; i >= 0; i --) { 11 | int cur = digits[i]; 12 | int sum = carry + cur; 13 | if (sum > 9) { 14 | digits[i] = sum - 10; 15 | carry = 1; 16 | } else { 17 | digits[i] = sum; 18 | carry = 0; 19 | } 20 | 21 | if (carry == 0) break; 22 | } 23 | 24 | if (carry > 0) { 25 | int[] temp = new int[digits.length + 1]; 26 | temp[0] = carry; 27 | for (int i = 0; i < digits.length; i ++) 28 | temp[i + 1] = digits[i]; 29 | return temp; 30 | } 31 | 32 | return digits; 33 | } 34 | } -------------------------------------------------------------------------------- /spec/array/spiralGridSpec.js: -------------------------------------------------------------------------------- 1 | var spiralGrid = require('../../javascript/array/spiralGrid'); 2 | 3 | describe('spiralGrid', () => { 4 | it('should return an array', () => { 5 | expect(spiralGrid([[1, 2, 3], [4, 5, 6], [7, 8, 9]])).toEqual([1, 2, 3, 6, 9, 8, 7, 4, 5]); 6 | }); 7 | 8 | it('should work for invalid inputs', () => { 9 | expect(spiralGrid([])).toEqual([]); 10 | expect(spiralGrid()).toEqual([]); 11 | expect(spiralGrid(undefined)).toEqual([]); 12 | expect(spiralGrid([[]])).toEqual([]); 13 | }); 14 | 15 | it('should work for rectangular grids', () => { 16 | expect(spiralGrid([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])).toEqual([1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]); 17 | expect(spiralGrid([[1, 2], 18 | [3, 9], 19 | [9, 0], 20 | [8, 1], 21 | [2, 2], 22 | [1, 7], 23 | [3, 4], 24 | [8, 4], 25 | [7, 6], 26 | [7, 2], 27 | [4, 6], 28 | [2, 1], 29 | [5, 6], 30 | [3, 4], 31 | [5, 6], 32 | [7, 8]])).toEqual([1,2,9,0,1,2,7,4,4,6,2,6,1,6,4,6,8,7,5,3,5,2,4,7,7,8,3,1,2,8,9,3]); 33 | }); 34 | }); 35 | -------------------------------------------------------------------------------- /java/leetcode/longest-substring-without-repeating-characters-3.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a string, find the length of the longest substring without repeating characters. 3 | * Given "abcabcbb", the answer is "abc", which the length is 3. 4 | * Complexity : O(n) time, O(n) space 5 | */ 6 | public class Solution { 7 | public int lengthOfLongestSubstring(String s) { 8 | int j = 0; // front pointer 9 | int i = 0; // back pointer 10 | int size = s.length(); 11 | HashSet set = new HashSet(); 12 | int result = 0; 13 | while ( i < size && j < size) { 14 | // adds only the unique values 15 | if (!set.contains(s.charAt(i))) { 16 | // Move the back pointer, increasing the substring length. 17 | i++; 18 | set.add(s.charAt(i - 1)); 19 | // i - j, since that will give use the length of the substring 20 | result = Math.max(result, i - j); 21 | } else { 22 | // Move the front pointer, decreasing the substring length. 23 | j++; 24 | set.remove(s.charAt(j - 1)); 25 | } 26 | } 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java/leetcode/path-sum-ii-113.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 3 | */ 4 | public class Solution { 5 | public List> pathSum(TreeNode root, int sum) { 6 | List> list = new ArrayList>(); 7 | if (root == null) return list; 8 | List cur = new ArrayList(); 9 | helper(root, sum, list, cur); 10 | return list; 11 | } 12 | 13 | public void helper(TreeNode node, int sum, List> list, List cur) { 14 | if (node == null) return; 15 | if (isLeaf(node)) { 16 | if (sum == node.val){ 17 | cur.add(node.val); 18 | list.add(new ArrayList(cur)); 19 | } 20 | 21 | return; 22 | } 23 | cur.add(node.val); 24 | 25 | helper(node.left, sum - node.val, list, new ArrayList(cur)); 26 | helper(node.right, sum - node.val, list, new ArrayList(cur)); 27 | } 28 | 29 | public boolean isLeaf(TreeNode node) { 30 | return node != null && node.left == null && node.right == null; 31 | } 32 | } -------------------------------------------------------------------------------- /javascript/string/balancedParentheses.js: -------------------------------------------------------------------------------- 1 | // The following hash tables are used for simpler character comparison. 2 | const OPENED_TO_CLOSED = { 3 | '{': '}', 4 | '[': ']', 5 | '(': ')' 6 | }; 7 | 8 | const CLOSED_TO_OPENED = { 9 | '}': '{', 10 | ']': '[', 11 | ')': '(', 12 | }; 13 | 14 | function balancedParentheses(expression) { 15 | if (!expression) return false; 16 | 17 | var stack = []; 18 | for (var i in expression) { 19 | var char = expression[i]; 20 | if (OPENED_TO_CLOSED[char]) { 21 | // If the character is an opening parentheses, then add it to the stack. 22 | stack.push(char); 23 | } else if (CLOSED_TO_OPENED[char]) { 24 | // If the character is a closing parentheses, then compare it to the end of the stack. 25 | if (CLOSED_TO_OPENED[char] !== stack[stack.length - 1]) return false; 26 | stack.pop(); 27 | } else { 28 | // This is an invalid character. 29 | return false; 30 | } 31 | } 32 | 33 | // The expression is balanced if the stack is empty in the end. 34 | return !stack.length; 35 | } 36 | 37 | module.exports = balancedParentheses; 38 | -------------------------------------------------------------------------------- /spec/tree/pathSumSpec.js: -------------------------------------------------------------------------------- 1 | var TreeNode = require('../../javascript/tree/TreeNode'); 2 | var pathSum = require('../../javascript/tree/pathSum'); 3 | 4 | describe('pathSum', () => { 5 | beforeEach(() => { 6 | this.node = new TreeNode([1, 2, 3, 4, 5]); 7 | }); 8 | 9 | it('should return true if there is a valid path', () => { 10 | expect(pathSum(this.node, 6)).toEqual(true); 11 | expect(pathSum(this.node, 12)).toEqual(true); 12 | }); 13 | 14 | it('should return false if there is not a valid path', () => { 15 | expect(pathSum(this.node, 1)).toEqual(false); 16 | expect(pathSum(this.node, 2)).toEqual(false); 17 | expect(pathSum(this.node, 3)).toEqual(false); 18 | expect(pathSum(this.node, 4)).toEqual(false); 19 | expect(pathSum(this.node, 5)).toEqual(false); 20 | expect(pathSum(this.node, 7)).toEqual(false); 21 | expect(pathSum(this.node, 8)).toEqual(false); 22 | expect(pathSum(this.node, 9)).toEqual(false); 23 | expect(pathSum(this.node, 10)).toEqual(false); 24 | expect(pathSum(this.node, 11)).toEqual(false); 25 | expect(pathSum(this.node, 13)).toEqual(false); 26 | }); 27 | }); 28 | -------------------------------------------------------------------------------- /java/leetcode/path-sum-113.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 3 | */ 4 | public class Solution { 5 | public List> hasPathSum(TreeNode root, int sum) { 6 | List> list = new ArrayList>(); 7 | if (root == null) return list; 8 | List cur = new ArrayList(); 9 | hasPathSum(root, sum, list, cur); 10 | return list; 11 | } 12 | 13 | public void helper(TreeNode node, int sum, List> list, List cur) { 14 | if (node == null) return; 15 | if (isLeaf(node)) { 16 | if (sum == node.val) { 17 | cur.add(node.val); 18 | list.add(new ArrayList(cur)); 19 | } 20 | 21 | return; 22 | } 23 | 24 | cur.add(node.val); 25 | 26 | hasPathSum(root.left, sum - root.val, list, new ArrayList(cur)); 27 | hasPathSum(root.right, sum - root.val, list, new ArrayList(cur)); 28 | } 29 | 30 | public boolean isLeaf(TreeNode node) { 31 | return node != null && node.left == null && node.right == null; 32 | } 33 | } -------------------------------------------------------------------------------- /javascript/genetic/README.md: -------------------------------------------------------------------------------- 1 | ## Genetic Algorithms 2 | 3 | I find genetic algorithms to be super cool and interesting that it is based off natural evolution. The idea is that given a gene, which represents a single object such as a person, has a specific trait or attribute that makes it unique. The algorithm would have a gene with an ideal trait, this will be the target gene which is the end goal of the algorithm. 4 | 5 | It works by grouping together multiple genes to *mate* and produce offspring which have certain traits from its parents but can also contain mutation which is random. The initial genes in the group or pool are completely random and from there only the best fitting genes are allowed to mate. This is to mock the natural selection or survival of the fittest. Over a period of time, the pools become closer and closer to the target gene. 6 | 7 | The developer has to define the ideal trait as well as how to calculate the best fitting genes. These functions are called cost functions which calculate the closeness to the trait. There are also fitness functions which are similar to cost functions but it calculates the score so the higher the better. 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Vincent Le 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /java/leetcode/max-width-binary-tree-662.java: -------------------------------------------------------------------------------- 1 | public int widthOfBinaryTree(TreeNode root) { 2 | if (root == null) { 3 | return 0; 4 | } 5 | 6 | Queue q = new LinkedList<>(); 7 | Queue indices = new LinkedList<>(); 8 | q.add(root); 9 | indices.add(1); 10 | int cur = 1; 11 | int next = 0; 12 | int left = 0; 13 | int max = 0; 14 | boolean firstLeft = true; 15 | 16 | while (!q.isEmpty()) { 17 | TreeNode node = q.poll(); 18 | int index = indices.poll(); 19 | cur --; 20 | 21 | // First left node. 22 | if (firstLeft) { 23 | left = index; 24 | firstLeft = false; 25 | } 26 | 27 | if (node.left != null) { 28 | q.add(node.left); 29 | columns.add(col * 2); 30 | next ++; 31 | } 32 | 33 | if (node.right != null) { 34 | q.add(node.right); 35 | columns.add(col * 2 + 1); 36 | next ++; 37 | } 38 | 39 | // Last right node. 40 | if (cur == 0) { 41 | cur = next; 42 | next = 0; 43 | max = Math.max(max, index + 1 - left); 44 | left = 0; 45 | firstLeft = true; 46 | } 47 | } 48 | 49 | return max; 50 | } 51 | -------------------------------------------------------------------------------- /java/leetcode/diagonal-traverse-498.java: -------------------------------------------------------------------------------- 1 | public static int[] diagonalTraverse(int[][] grid) { 2 | if (grid.length == 0 || grid[0].length == 0) { 3 | return new int[0]; 4 | } 5 | int count = grid.length * grid[0].length; 6 | int cur = 0; 7 | int col = 0; 8 | int[] arr = new int[count]; 9 | boolean dir = false; 10 | while (cur < count) { 11 | int i = dir ? 0 : col; 12 | int j = dir ? col : 0; 13 | 14 | if (dir) { 15 | // Traverse diagonally upwards 16 | while (j >= 0 || i < grid.length) { 17 | if (isValid(grid, i, j)) { 18 | arr[cur ++] = grid[i][j]; 19 | } 20 | i ++; 21 | j --; 22 | } 23 | } else { 24 | // Traverse diagonally downwards 25 | while (i >= 0 && j < grid[0].length) { 26 | if (isValid(grid, i, j)) { 27 | arr[cur ++] = grid[i][j]; 28 | } 29 | i --; 30 | j ++; 31 | } 32 | } 33 | 34 | dir = !dir; 35 | col ++; 36 | } 37 | 38 | return arr; 39 | } 40 | 41 | public static boolean isValid(int[][] grid, int i, int j) { 42 | return i < grid.length && j < grid[0].length && i >= 0 && j >= 0; 43 | } 44 | -------------------------------------------------------------------------------- /java/leetcode/intersection-of-two-linked-lists-160.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a program to find the node at which the intersection of two singly linked lists begins. 3 | */ 4 | public class Solution { 5 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 6 | if (headA == null || headB == null) return null; 7 | int countA = 1; 8 | int countB = 1; 9 | ListNode cloneA = headA; 10 | ListNode cloneB = headB; 11 | 12 | while (cloneA.next != null || cloneB.next != null) { 13 | if (cloneA.next != null) { 14 | cloneA = cloneA.next; 15 | countA ++; 16 | } 17 | 18 | if (cloneB.next != null) { 19 | cloneB = cloneB.next; 20 | countB ++; 21 | } 22 | } 23 | 24 | if (cloneA != cloneB) return null; 25 | 26 | ListNode longer = countA > countB ? headA : headB; 27 | ListNode shorter = countA > countB ? headB : headA; 28 | for (int i = 0; i < Math.abs(countA - countB); i ++) { 29 | longer = longer.next; 30 | } 31 | 32 | while (longer != shorter) { 33 | longer = longer.next; 34 | shorter = shorter.next; 35 | } 36 | return longer; 37 | } 38 | } -------------------------------------------------------------------------------- /javascript/search/README.md: -------------------------------------------------------------------------------- 1 | ## Table of Contents 2 | - [Binary Search](#binary-search) 3 | 4 | ## Binary Search 5 | #### Problem 6 | Given an array and a value, return the index of the value in the array or -1 if it does not exist. 7 | 8 | #### Input/Output 9 | ``` 10 | Input: [1, 2, 3, 4, 5, 6, 7, 8, 9], 8 11 | Output: 7 12 | ``` 13 | #### Explanation 14 | Binary search relies on the given array to be sorted. The binary search works by dividing the array in half for every check where the check occurs in the midpoint of the current array. 15 | 16 | For example, when searching for *8* in the given array, we first look at the midpoint value *5*. In this case, our value is larger so we will next look at the right half of the array. This is why a sorted array is necessary. The divide and check keeps occurring until the value is found. When the current becomes empty, then the value does not exist and return *-1*. 17 | 18 | The time and space complexities for this is O(logn) and O(1) respectively. If the array isn't sorted then the runtime complexity would then be O(nlogn). 19 | 20 | [Implementation](https://github.com/vinnyoodles/algorithms/blob/master/src/search/binarySearch.js) 21 | -------------------------------------------------------------------------------- /javascript/recursion/numberOfPathsInMatrix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a two dimensional array with values of 0s or 1s (where 1 represents a blocked wall). 3 | * Return the total number of paths to traverse from the origin (0, 0) to the bottom right corner (x - 1, y - 1). 4 | * The only direction to move is either to the right or down. 5 | * 6 | * @param {Array} two dimensional array of 0s and 1s. 7 | * @return {Integer} number of paths. 8 | */ 9 | 10 | function numberOfPathsInMatrix(array) { 11 | if (!array.length || !array[0].length) return 0; 12 | return findNumberOfPaths(array, 0, 0, 0); 13 | } 14 | 15 | function findNumberOfPaths(array, n, m, paths) { // jshint ignore:line 16 | // Check if the coordinates are out of bounds. 17 | if (m >= array.length || n >= array[0].length) return paths; 18 | // Check if the coordinates point to a wall. 19 | else if (array[m][n] === 1) return paths; 20 | // Check if the coordinates point to the goal. 21 | else if (m === array.length - 1 && n === array[0].length - 1) return paths + 1; 22 | return findNumberOfPaths(array, n + 1, m, paths) + findNumberOfPaths(array, n, m + 1, paths); 23 | } 24 | 25 | module.exports = numberOfPathsInMatrix; 26 | -------------------------------------------------------------------------------- /java/leetcode/zigzag-iterator-281.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given two 1d vectors, implement an iterator to return their elements alternately. 3 | * Input 4 | * v1 = [1, 2] 5 | * v2 = [3, 4, 5, 6] 6 | * Output 7 | * By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6]. 8 | * Complexity : O(N) time, O(m + n) m and n are the two list sizes : space 9 | */ 10 | public class ZigzagIterator { 11 | LinkedList list; 12 | public ZigzagIterator(List v1, List v2) { 13 | list = new LinkedList(); 14 | if (!v1.isEmpty()) { 15 | list.add(v1.iterator()); 16 | } 17 | if (!v2.isEmpty()){ 18 | list.add(v2.iterator()); 19 | } 20 | } 21 | public int next() { 22 | Iterator it = list.remove(); 23 | int res = (int)it.next(); 24 | if (it.hasNext()) { 25 | list.add(it); 26 | } 27 | return res; 28 | } 29 | public boolean hasNext() { 30 | return !list.isEmpty(); 31 | } 32 | } 33 | /** 34 | * Your ZigzagIterator object will be instantiated and called as such: 35 | * ZigzagIterator i = new ZigzagIterator(v1, v2); 36 | * while (i.hasNext()) v[f()] = i.next(); 37 | */ 38 | -------------------------------------------------------------------------------- /spec/linkedlist/findIntersectionSpec.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('../../javascript/linkedlist/ListNode'); 2 | var findIntersection = require('../../javascript/linkedlist/findIntersection'); 3 | 4 | describe('findIntersection', () => { 5 | it('should find the intersecting node', () => { 6 | var a = new ListNode(1); 7 | a.append([2, 3, 4, 5, 6]); 8 | var third = a.next.next; 9 | var b = new ListNode(10); 10 | b.next = third; 11 | expect(findIntersection(a, b)).toEqual(third); 12 | expect(findIntersection(a, b).toArray()).toEqual([3, 4, 5, 6]); 13 | }); 14 | 15 | it('should return null if it does not exist', () => { 16 | var a = new ListNode(1); 17 | a.append([2, 3, 4, 5, 6]); 18 | var third = a.next.next; 19 | var b = new ListNode(10); 20 | expect(findIntersection(a, b)).toEqual(null); 21 | }); 22 | 23 | it('should work if b is longer', () => { 24 | var a = new ListNode(1); 25 | a.append([2, 3, 4, 5, 6]); 26 | var third = a.next.next; 27 | var b = new ListNode(10); 28 | b.next = third; 29 | expect(findIntersection(b, a)).toEqual(third); 30 | expect(findIntersection(b, a).toArray()).toEqual([3, 4, 5, 6]); 31 | }); 32 | }); 33 | -------------------------------------------------------------------------------- /java/leetcode/permutations-46.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a list of distinct numbers, return all possible permutations. 3 | */ 4 | public class Solution { 5 | public List> permute(int[] nums) { 6 | List> permutations = new ArrayList>(); 7 | helper(nums, 0, permutations, new ArrayList()); 8 | return permutations; 9 | } 10 | 11 | public void helper(int[] nums, int index, List> list, List cur) { 12 | // Permutations are same size of nums, just different ordering. 13 | if (nums.length == cur.size()) list.add(new ArrayList(cur)); 14 | 15 | for (int i = index; i < nums.length; i ++) { 16 | cur.add(nums[i]); 17 | // Move the one that was just added out of the potential options to prevent duplicates. 18 | if (i != index) swap(nums, i, index); 19 | helper(nums, index + 1, list, cur); 20 | 21 | // Move back to find different unique orderings. 22 | if (i != index) swap(nums, i, index); 23 | cur.remove(cur.size() - 1); 24 | } 25 | } 26 | 27 | public void swap(int[] arr, int i, int j) { 28 | int temp = arr[i]; 29 | arr[i] = arr[j]; 30 | arr[j] = temp; 31 | } 32 | } -------------------------------------------------------------------------------- /java/leetcode/missing-ranges-163.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges. 3 | * For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"]. 4 | * Note when doing this problem be careful with overflow since input could be a Integer.MaxValue. 5 | * Complexity : O(N) time, O(N) space (the solution list) 6 | */ 7 | public class Solution { 8 | public List findMissingRanges(int[] nums, int lower, int upper) { 9 | List res = new ArrayList(); 10 | int range = lower; 11 | for (int i = 0; i < nums.length; i++) { 12 | if (nums[i] > range) { 13 | res.add(getValidRange(range, nums[i] - 1)); 14 | } 15 | if (upper == nums[i]) { // avoid the overflow so return the result; 16 | return res; 17 | } 18 | range = nums[i] + 1; 19 | } 20 | if (range <= upper) { 21 | res.add(getValidRange(range, upper)); 22 | } 23 | return res; 24 | } 25 | 26 | private String getValidRange(int lower, int upper) { 27 | return upper > lower ? String.format("%d->%d", lower, upper) : lower + ""; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java/leetcode/binary-tree-level-order-traversal-ii-107.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a binary tree, return the bottom-up level order traversal of its nodes' values. 3 | * (ie, from left to right, level by level from leaf to root). 4 | */ 5 | public class Solution { 6 | public List> levelOrderBottom(TreeNode root) { 7 | Queue q = new LinkedList(); 8 | List> list = new ArrayList>(); 9 | if (root == null) return list; 10 | 11 | List temp = new ArrayList(); 12 | int cur = 1; 13 | int next = 0; 14 | q.add(root); 15 | 16 | while (!q.isEmpty()) { 17 | TreeNode node = q.poll(); 18 | temp.add(node.val); 19 | cur --; 20 | 21 | if (cur == 0 && !temp.isEmpty()) { 22 | list.add(0, temp); 23 | temp = new ArrayList(); 24 | } 25 | 26 | if (node.left != null) { 27 | q.add(node.left); 28 | next ++; 29 | } 30 | 31 | if (node.right != null) { 32 | q.add(node.right); 33 | next ++; 34 | } 35 | 36 | if (cur == 0) { 37 | cur = next; 38 | next = 0; 39 | } 40 | } 41 | 42 | return list; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /javascript/linkedlist/findIntersection.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given two linked lists, find the intersecting node. 3 | * An intersecting node is a node that is apparent in both lists. 4 | * If no node exists, then return null. 5 | * 6 | * @param {ListNode} a 7 | * @param {ListNode} b 8 | */ 9 | function findIntersection(a, b) { 10 | var temp1 = a; 11 | var temp2 = b; 12 | var length1 = 0; 13 | var length2 = 0; 14 | 15 | while (temp1 || temp2) { 16 | if (temp1) { 17 | length1 ++; 18 | temp1 = temp1.next 19 | } 20 | 21 | if (temp2) { 22 | length2 ++; 23 | temp2 = temp2.next; 24 | } 25 | } 26 | 27 | // No intersecting node exists. 28 | if (temp1 !== temp2) return null; 29 | 30 | var longer = length1 > length2 ? a : b; 31 | var shorter = length1 > length2 ? b : a; 32 | var difference = Math.abs(length1 - length2); 33 | 34 | for (var i = 0; i < difference; i++) { 35 | longer = longer.next; 36 | } 37 | 38 | while(longer) { 39 | // Found the intersecting node. 40 | if (longer === shorter) return longer; 41 | 42 | longer = longer.next; 43 | shorter = shorter.next; 44 | } 45 | 46 | 47 | return null; 48 | } 49 | 50 | module.exports = findIntersection; 51 | -------------------------------------------------------------------------------- /python/dcp/problem3.py: -------------------------------------------------------------------------------- 1 | # This problem was asked by Google. 2 | # Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, 3 | # and deserialize(s), which deserializes the string back into the tree. 4 | 5 | class TreeNode(object): 6 | def __init__(self, x): 7 | self.val = x 8 | self.left = None 9 | self.right = None 10 | 11 | def serialize(root): 12 | if root: 13 | string = '{0},'.format(root.val) 14 | string = string + serialize(root.left) 15 | string = string + serialize(root.right) 16 | return string 17 | else: 18 | return 'X,' 19 | 20 | 21 | def deserialize(data): 22 | if len(data) < 1: 23 | return None 24 | queue = [x.strip() for x in data.split(',')] 25 | return helper(queue) 26 | 27 | def helper(queue): 28 | if len(queue) < 1: 29 | return None 30 | val = queue.pop(0) 31 | if val == 'X': 32 | return None 33 | else: 34 | node = TreeNode(int(val)) 35 | node.left = helper(queue) 36 | node.right = helper(queue) 37 | return node 38 | 39 | data = '1,2,X,X,3,4,X,X,5,X,X,' 40 | assert(data == serialize(deserialize('1,2,X,X,3,4,X,X,5,X,X,'))) -------------------------------------------------------------------------------- /java/leetcode/binary-search-tree-iterator-173.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | 11 | public class BSTIterator { 12 | 13 | // Use an array list to prevent having to count the # of nodes beforehand. 14 | List list; 15 | int current; 16 | public BSTIterator(TreeNode root) { 17 | this.list = traverse(root, new ArrayList()); 18 | this.current = 0; 19 | } 20 | 21 | /** @return whether we have a next smallest number */ 22 | public boolean hasNext() { 23 | return this.current < this.list.size(); 24 | } 25 | 26 | /** @return the next smallest number */ 27 | public int next() { 28 | if (this.hasNext()) return this.list.get(this.current++); 29 | return -1; 30 | } 31 | 32 | /** 33 | * Simple in order traversal to populate the array list in sorted order. 34 | */ 35 | private List traverse(TreeNode node, List list) { 36 | if (node == null) return list; 37 | traverse(node.left, list); 38 | list.add(node.val); 39 | traverse(node.right, list); 40 | return list; 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /java/leetcode/copy-list-with-random-pointer-138.java: -------------------------------------------------------------------------------- 1 | /** 2 | * A linked list is given such that each node contains an additional random pointer 3 | * which could point to any node in the list or null. 4 | * Return a deep copy of the list. 5 | */ 6 | public class Solution { 7 | public RandomListNode copyRandomList(RandomListNode head) { 8 | if (head == null) return null; 9 | 10 | HashMap map = new HashMap(); 11 | RandomListNode temp = head; 12 | 13 | // Populate the map and instantiate all new nodes. 14 | while (temp != null) { 15 | map.put(temp, new RandomListNode(temp.label)); 16 | temp = temp.next; 17 | } 18 | 19 | temp = head; 20 | RandomListNode newHead = new RandomListNode(-1); 21 | RandomListNode anotherNode = newHead; 22 | while (temp != null) { 23 | RandomListNode clone = map.get(temp); 24 | newHead.next = clone; 25 | RandomListNode random = temp.random; 26 | 27 | // Assign the random pointer, if it exists. 28 | if (random != null) newHead.next.random = map.get(random); 29 | temp = temp.next; 30 | newHead = newHead.next; 31 | } 32 | 33 | return anotherNode.next; 34 | } 35 | } -------------------------------------------------------------------------------- /javascript/grid/largestNeighbor.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Find the neighbor of the current node with the greatest value. 3 | * If no neighbor with a value greater than 0 exists, then return an empty object. 4 | * 5 | * A node is defined with a (x, y) coordinate to find its value in the grid. 6 | * var node = { 7 | * x: x, 8 | * y: y 9 | * } 10 | * 11 | * @param {2D Array} grid 12 | * @param {Integer} x 13 | * @param {Integer} y 14 | */ 15 | function largestNeighbor(grid, x, y) { 16 | var value = Number.MIN_VALUE; 17 | var target = {}; 18 | // Iterate through each adjacent grid. 19 | for (var n = x - 1; n <= x + 1; n++) { 20 | for (var m = y - 1; m <= y + 1; m++) { 21 | // Check if the coordinates are within the grid. 22 | if (n < 0 || m < 0 || n >= grid[0].length || m >= grid.length) continue; 23 | // Check if the coordinate is a diagonal. 24 | else if ((n === x || m !== y) && (n !== x || m === y)) continue; 25 | 26 | // Update the selected grid if it is greater. 27 | if (grid[m][n] > 0 && grid[m][n] > value) { 28 | value = grid[m][n]; 29 | target.x = n; 30 | target.y = m; 31 | } 32 | } 33 | } 34 | return target; 35 | } 36 | 37 | module.exports = largestNeighbor; 38 | -------------------------------------------------------------------------------- /spec/linkedlist/cyclicalSpec.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('../../javascript/linkedlist/ListNode'); 2 | var cyclical = require('../../javascript/linkedlist/cyclical'); 3 | 4 | describe('cyclical', () => { 5 | it('should return false for normal lists', () => { 6 | var a = new ListNode([1, 2, 3, 4, 5, 6]); 7 | expect(cyclical(a)).toBeFalsy(); 8 | expect(cyclical(new ListNode(1))).toBeFalsy(); 9 | }); 10 | 11 | it('should return true if the list has a cycle', () => { 12 | var a = new ListNode([1, 2, 3]); 13 | var lastNode = a.next.next; 14 | // Point the last node to the middle node; 15 | lastNode.next = a.next; 16 | expect(cyclical(a)).toBeTruthy(); 17 | }); 18 | 19 | it('should work', () => { 20 | var a = new ListNode(1); 21 | a.next = a; 22 | expect(cyclical(a)).toBeTruthy(); 23 | }); 24 | 25 | it('should work pt2', () => { 26 | var a = new ListNode([1, 2, 3, 4, 5]); 27 | var last = a.next.next.next.next; 28 | last.next = a; 29 | expect(cyclical(a)).toBeTruthy(); 30 | }); 31 | 32 | it('should work pt2', () => { 33 | var a = new ListNode([1, 2, 3, 4, 5]); 34 | var last = a.next.next; 35 | last.next = a; 36 | expect(cyclical(a)).toBeTruthy(); 37 | }); 38 | }); 39 | -------------------------------------------------------------------------------- /javascript/kmeans/README.md: -------------------------------------------------------------------------------- 1 | ## Kth Means 2 | #### Problem 3 | Kth means is a machine learning algorithms, more specifically it is a clustering algorithm. Clustering algorithms group together similar nodes to form a single cluster. Similar to knn, *k* represents the number of clusters. A good use case for a clustering algorithm such as kmeans is tagging clothing styles. For example, we can determine if a given shirt is a specific style if it has similar features to a certain cluster. 4 | 5 | #### Explanation 6 | kmeans works by first creating *k* clusters and randomly assigning them to a certain location in the grid. Once the clusters are assigned a coordinate, we iterate through each node and assign that node to the closest cluster. When all nodes have been assigned, the cluster are then moved to the center of all of its assigned nodes. These steps will keep looping until no more clusters are moving. This will happen when all the clusters are in the correct center location. 7 | 8 | In order to use kmeans you either need to know how many clusters you're looking for in the dataset or you have to use a second algorithm to also guess the number of clusters. kmeans just organizes your points into clusters; you need to do something else to figure out the right number of clusters. 9 | -------------------------------------------------------------------------------- /java/leetcode/next-greater-element-ii-503.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a circular array (the next element of the last element is the first element of the array), 3 | * print the Next Greater Number for every element. The Next Greater Number of a number x is the 4 | * first greater number to its traversing-order next in the array, which means you could search 5 | * circularly to find its next greater number. If it doesn't exist, output -1 for this number. 6 | */ 7 | public class Solution { 8 | public int[] nextGreaterElements(int[] nums) { 9 | int[] arr = new int[nums.length]; 10 | 11 | // Iterate through to find each greater element. 12 | for (int i = 0; i < arr.length; i ++) { 13 | int j = i + 1; 14 | int val = -1; 15 | 16 | // For every element find the closest greater element from the front. 17 | while (j != i) { 18 | // For circular arrays. 19 | if (j >= arr.length) j = 0; 20 | // If a cycle has been completed then break. 21 | if (j == i) break; 22 | // The greater element has been found. 23 | if (nums[j] > nums[i]) { 24 | val = nums[j]; 25 | break; 26 | } 27 | 28 | j ++; 29 | } 30 | arr[i] = val; 31 | } 32 | 33 | return arr; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /java/leetcode/non-overlapping-intervals-435.java: -------------------------------------------------------------------------------- 1 | /** 2 | * public class Interval { 3 | * int start; 4 | * int end; 5 | * Interval() { start = 0; end = 0; } 6 | * Interval(int s, int e) { start = s; end = e; } 7 | * } 8 | */ 9 | public int eraseOverlapIntervals(Interval[] intervals) { 10 | if (intervals.length == 0) { 11 | return 0; 12 | } 13 | // Sort by the end interval. 14 | Arrays.sort(intervls, (a, b) -> a.end - b.end); 15 | int count = 0; 16 | 17 | // This pointer represents the current ending index of the current interval. 18 | int index = intervals[0].end; 19 | for (int i = 1; i < intervals.length; i ++) { 20 | 21 | // If the current interval's start index is greater than the ending index, 22 | // then we can update the ending index to be the current end because 23 | // these two are not overlapping. 24 | if (intervals[i].start >= index) { 25 | cur = temp.end; 26 | } else { 27 | // Otherwise, the two intervals are intersecting. Therefore, update the counter 28 | // and take the smallest end index between the two in order to minimize the number 29 | // of overlapping intervals. 30 | count ++; 31 | cur = Math.min(cur, intervals[i].end; 32 | } 33 | } 34 | 35 | return count; 36 | } 37 | -------------------------------------------------------------------------------- /java/leetcode/top-k-frequent-elements-347.java: -------------------------------------------------------------------------------- 1 | public List topKFrequent(int[] nums, int k) { 2 | HashMap map = new HashMap<>(); 3 | 4 | // Make a frequency map. 5 | for (int i : nums) { 6 | map.put(i, map.getOrDefault(i, 0) + 1); 7 | } 8 | 9 | // Reverse the map so that the frequency is the index. 10 | // Store in some sort of data structure where the indices are sorted 11 | // so that we can iterate from most frequent to least frequent. 12 | List> list = new ArrayList<>(); 13 | 14 | // Populate the entire list. 15 | for (int i = 0; i <= nums.length; i ++) { 16 | list.add(new HashSet()); 17 | } 18 | 19 | for (int key : map.keySet()) { 20 | int frequency = map.get(key); 21 | 22 | // Add the value into the hash set, indexed by the frequency. 23 | list.get(frequency).add(key); 24 | } 25 | 26 | // Now iterate and grab the k most frequenct elements. 27 | List result = new ArrayList<>(); 28 | for (int i = list.size() - 1; i >= 0 && k > 0; i --) { 29 | HashSet set = list.get(i); 30 | 31 | for (int value : set) { 32 | if (k <= 0) { 33 | break; 34 | } 35 | 36 | result.add(value); 37 | k --; 38 | } 39 | } 40 | 41 | return result; 42 | } 43 | -------------------------------------------------------------------------------- /javascript/array/spiralGrid.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a grid (two dimensional array), return an array of its value in spiral order. 3 | * 4 | * @param {Array} grid 5 | * @return {Array} 6 | */ 7 | function spiralGrid(grid) { 8 | if (!grid || !grid.length || !grid[0].length) return []; 9 | 10 | var maxY = grid.length; 11 | var maxX = grid[0].length; 12 | var minY = 0; 13 | var minX = 0; 14 | var array = []; 15 | var size = grid.length * grid[0].length; 16 | 17 | var x = 0; 18 | var y = 0; 19 | while(array.length < size) { 20 | for (x = minX; x < maxX; x++) { 21 | array.push(grid[y][x]); 22 | } 23 | if (array.length === size) return array; 24 | minY++; 25 | x--; 26 | 27 | for (y = minY; y < maxY; y++) { 28 | array.push(grid[y][x]); 29 | } 30 | if (array.length === size) return array; 31 | maxX--; 32 | y--; 33 | 34 | for (x = maxX - 1; x >= minX; x--) { 35 | array.push(grid[y][x]); 36 | } 37 | if (array.length === size) return array; 38 | maxY--; 39 | x++; 40 | 41 | for (y = maxY - 1; y >= minY; y--) { 42 | array.push(grid[y][x]); 43 | } 44 | if (array.length === size) return array; 45 | minX++; 46 | y++; 47 | } 48 | 49 | return array; 50 | } 51 | 52 | module.exports = spiralGrid; 53 | -------------------------------------------------------------------------------- /java/leetcode/phonenumber-combinations-17.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | 4 | public class Solution { 5 | public List letterCombinations(String digits) { 6 | String[] map = new String[10]; 7 | if (digits.length() == 0) return new ArrayList(); 8 | map[0] = ""; 9 | map[1] = ""; 10 | map[2] = "abc"; 11 | map[3] = "def"; 12 | map[4] = "ghi"; 13 | map[5] = "jkl"; 14 | map[6] = "mno"; 15 | map[7] = "pqrs"; 16 | map[8] = "tuv"; 17 | map[9] = "wxyz"; 18 | 19 | return permutation(digits, 0, map); 20 | } 21 | 22 | private List permutation(String digits, int index, String[] map) { 23 | List result; 24 | if (index < digits.length() - 1) { 25 | result = permutation(digits, index + 1, map); 26 | } else { 27 | result = new ArrayList(); 28 | result.add(new String("")); 29 | } 30 | 31 | List newResult = new ArrayList(); 32 | for (int i = 0; i < result.size(); i ++) { 33 | String c = result.get(i); 34 | String mapped = map[digits.charAt(index) - '0']; 35 | 36 | for (int j = 0; j < mapped.length(); j ++) { 37 | newResult.add(mapped.charAt(j) + "" + c); 38 | } 39 | } 40 | 41 | return newResult; 42 | } 43 | } -------------------------------------------------------------------------------- /javascript/grid/gridTraversal.js: -------------------------------------------------------------------------------- 1 | var largestNeighbor = require('./largestNeighbor'); 2 | 3 | /** 4 | * Use depth first search to traverse a 2D array. 5 | * 6 | * A node is defined with a (x, y) coordinate to find its value in the grid. 7 | * var node = { 8 | * x: x, 9 | * y: y 10 | * } 11 | * 12 | * A node's neighbor is confined to only the cardinal directions (north, south, east and west). 13 | * When traversing, prioritize neighbors with greatest value. 14 | * The traversal ends when the node no longer has an neighbors with a value greater than 0. 15 | * 16 | * @param {2D Array} grid where each node contains an integer. 17 | * @param {Integer} x start location. 18 | * @param {Integer} y start location. 19 | * @return {Array} path in order of traversal. 20 | */ 21 | function gridTraversal(grid, x, y) { 22 | if (!grid.length || !grid[0].length) return []; 23 | var stack = [{x: x, y: y}]; 24 | var path = []; 25 | while (stack.length) { 26 | var node = stack.pop(); 27 | // Mark as visited. 28 | path.push(grid[node.y][node.x]); 29 | grid[node.y][node.x] = 0; 30 | var neighbor = largestNeighbor(grid, node.x, node.y); 31 | if (neighbor.x !== undefined && neighbor.y !== undefined) stack.push(neighbor); 32 | } 33 | return path; 34 | } 35 | 36 | module.exports = gridTraversal; 37 | -------------------------------------------------------------------------------- /spec/grid/largestRegionSpec.js: -------------------------------------------------------------------------------- 1 | var largestRegion = require('../../javascript/grid/largestRegion'); 2 | 3 | describe('largestRegion', () => { 4 | it('should find the largest region', () => { 5 | expect(largestRegion([ 6 | [1,0,0,0,0,0,0], 7 | [1,0,0,0,1,0,0], 8 | [1,0,0,1,1,1,1], 9 | [0,1,0,1,0,1,1], 10 | [0,0,1,1,1,1,1] 11 | ])).toEqual(17); 12 | 13 | expect(largestRegion([ 14 | [0,1,1,1,1,0,0], 15 | [0,0,1,1,1,1,0], 16 | [0,1,1,0,0,1,0], 17 | [0,1,1,0,0,0,0], 18 | [0,1,1,0,0,1,0], 19 | [0,1,1,1,1,0,0] 20 | ])).toEqual(20); 21 | 22 | expect(largestRegion([ 23 | [1,1,1,1,1,011], 24 | [1,0,1,1,1,1,1], 25 | [1,1,1,0,0,1,1], 26 | [1,1,1,0,0,0,1], 27 | [1,1,1,0,0,1,1], 28 | [1,1,1,1,1,1,1] 29 | ])).toEqual(33); 30 | }); 31 | 32 | it('should count diagonals', () => { 33 | expect(largestRegion([ 34 | [1,0,0,0,0,0,0], 35 | [0,1,0,0,1,0,0], 36 | [0,0,1,0,0,0,1], 37 | [0,0,0,1,0,0,1], 38 | [0,0,0,0,1,0,0] 39 | ])).toEqual(5); 40 | 41 | expect(largestRegion([ 42 | [0,0,0,0,0,0,0], 43 | [0,0,0,0,0,0,0], 44 | [0,0,0,0,0,0,0], 45 | [0,0,0,0,0,0,0], 46 | [0,0,0,0,0,0,0], 47 | [0,0,0,0,0,0,0] 48 | ])).toEqual(0); 49 | }); 50 | }); 51 | -------------------------------------------------------------------------------- /spec/linkedlist/sumListsSpec.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('../../javascript/linkedlist/ListNode'); 2 | var sumLists = require('../../javascript/linkedlist/sumLists'); 3 | 4 | describe('sumLists', () => { 5 | it('should sum up two linked lists', () => { 6 | var a = new ListNode(1); 7 | var b = new ListNode(4); 8 | a.append([2, 3]); 9 | b.append([5, 6]); 10 | 11 | var c = sumLists(a, b); 12 | expect(c.toArray()).toEqual([5, 7, 9]); 13 | }); 14 | 15 | it('should sum up two uneven linked lists', () => { 16 | var a = new ListNode(1); 17 | var b = new ListNode(4); 18 | a.append([2, 3, 5]); 19 | b.append([5, 6]); 20 | 21 | var c = sumLists(a, b); 22 | expect(c.toArray()).toEqual([5, 7, 9, 5]); 23 | }); 24 | 25 | it('should take into account carries', () => { 26 | var a = new ListNode(9); 27 | var b = new ListNode(9); 28 | a.append([9, 9, 9]); 29 | b.append([9, 9]); 30 | 31 | var c = sumLists(a, b); 32 | expect(c.toArray()).toEqual([8, 9, 9, 0, 1]); 33 | }); 34 | 35 | it('should work for a much longer lists', () => { 36 | var a = new ListNode(1); 37 | var b = new ListNode(4); 38 | a.append([2, 3]); 39 | b.append([5, 6, 7, 8, 9]); 40 | 41 | var c = sumLists(a, b); 42 | expect(c.toArray()).toEqual([5, 7, 9, 7, 8, 9]); 43 | }); 44 | }); 45 | -------------------------------------------------------------------------------- /spec/tree/columnSortSpec.js: -------------------------------------------------------------------------------- 1 | var TreeNode = require('../../javascript/tree/TreeNode'); 2 | var columnSort = require('../../javascript/tree/columnSort'); 3 | 4 | describe('columnSort', () => { 5 | it('should return an array of the nodes\' value in column sorted order', () => { 6 | var node = new TreeNode([1, 2, 3, 4, 5, 6]); 7 | expect(columnSort(node)).toEqual([1, 2, 4, 3, 5, 6]); 8 | }); 9 | 10 | it('should work for an empty tree', () => { 11 | var node = new TreeNode([]); 12 | expect(columnSort(node)).toEqual([]); 13 | }); 14 | 15 | /** 16 | * Test with the following tree. 17 | * 5 18 | * / \ 19 | * 4 8 20 | * / / \ 21 | * 9 6 4 22 | * / \ / \ 23 | * 7 2 5 1 24 | */ 25 | it('should work for this tree', () => { 26 | var node = new TreeNode(5); 27 | node.left = new TreeNode(4); 28 | node.right = new TreeNode(8); 29 | node.left.left = new TreeNode([7, 9, 2]); 30 | node.right.left = new TreeNode(6); 31 | node.right.right = new TreeNode([5, 4, 1]); 32 | expect(columnSort(node)).toEqual([7, 9, 4, 2, 5, 6, 8, 5, 4, 1]); 33 | }); 34 | 35 | it('should work for that tree', () => { 36 | var node = new TreeNode([7, 9, 2, 4, 5, 6, 8, 5, 4, 1]); 37 | expect(columnSort(node)).toEqual([7, 9, 2, 4, 8, 6, 5, 5, 4, 1]); 38 | }); 39 | }); 40 | -------------------------------------------------------------------------------- /java/leetcode/reshape-matrix-566.java: -------------------------------------------------------------------------------- 1 | /** 2 | * You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively. 3 | * The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were. 4 | * If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. 5 | * 6 | * Complexity: O(N * M) runtime and O(R * C) space where N and M are the length and height of the orignal array and R and C are the length and height of the new array. 7 | */ 8 | public class Solution { 9 | public int[][] matrixReshape(int[][] nums, int r, int c) { 10 | // No possible way to reshape. 11 | if (nums.length == 0 || nums[0].length == 0) return nums; 12 | if (r * c != nums.length * nums[0].length) return nums; 13 | 14 | int[][] arr = new int[r][c]; 15 | int x = 0; 16 | int y = 0; 17 | 18 | for (int i = 0; i < r; i ++) { 19 | for (int j = 0; j < c; j ++) { 20 | arr[i][j] = nums[x][y]; 21 | 22 | if (y < nums[0].length) y ++; 23 | 24 | if (y >= nums[0].length) { 25 | y = 0; 26 | x ++; 27 | } 28 | } 29 | } 30 | 31 | return arr; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /java/algorithms/DijkstraPathFinder.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | import datastructures.PriorityQueue; 3 | import datastructures.GraphNode; 4 | 5 | public class DijkstraPathFinder { 6 | public int[] find(int[][] matrix, int start) { 7 | int length = matrix.length; 8 | int[] dist = new int[length]; 9 | PriorityQueue queue = new PriorityQueue<>(); 10 | boolean[] visited = new boolean[length]; 11 | 12 | for (int i = 0; i < length; i ++) { 13 | // Every node but the source has an initial distance of infinity. 14 | dist[i] = (i + 1) == start ? 0 : Integer.MAX_VALUE; 15 | } 16 | 17 | queue.add(new GraphNode(start, 0)); 18 | while (!queue.isEmpty()) { 19 | GraphNode curr = queue.poll(); 20 | int[] neighbors = matrix[curr.index()]; 21 | visited[curr.index()] = true; 22 | 23 | for (int i = 0; i < neighbors.length; i ++) { 24 | // Skip self node or non connected node. 25 | if (i == curr.index() || neighbors[i] == 0) continue; 26 | 27 | dist[i] = Math.min(dist[i], dist[curr.index()] + neighbors[i]); 28 | if (!visited[i]) { 29 | queue.add(new GraphNode(i + 1, dist[i])); 30 | } 31 | } 32 | } 33 | return dist; 34 | } 35 | } -------------------------------------------------------------------------------- /spec/recursion/pascalsTriangleSpec.js: -------------------------------------------------------------------------------- 1 | var { pascalsTriangle, _iterative } = require('../../javascript/recursion/pascalsTriangle'); 2 | 3 | describe('pascalsTriangle', () => { 4 | it('should return pascal\'s triangle', () => { 5 | expect(pascalsTriangle(1)).toEqual([[1]]); 6 | expect(_iterative(1)).toEqual([[1]]); 7 | }); 8 | 9 | it('should return pascal\'s triangle with 3 levels', () => { 10 | expect(pascalsTriangle(3)).toEqual([ 11 | [1], 12 | [1, 1], 13 | [1, 2, 1] 14 | ]); 15 | 16 | expect(pascalsTriangle(3)).toEqual(_iterative(3)); 17 | }); 18 | 19 | it('should return pascal\'s triangle with 5 levels', () => { 20 | expect(pascalsTriangle(5)).toEqual([ 21 | [1], 22 | [1, 1], 23 | [1, 2, 1], 24 | [1, 3, 3, 1], 25 | [1, 4, 6, 4, 1] 26 | ]); 27 | expect(pascalsTriangle(5)).toEqual(_iterative(5)); 28 | }); 29 | 30 | it('should return pascal\'s triangle with 10 levels', () => { 31 | expect(pascalsTriangle(10)).toEqual([ 32 | [1], 33 | [1, 1], 34 | [1, 2, 1], 35 | [1, 3, 3, 1], 36 | [1, 4, 6, 4, 1], 37 | [1, 5, 10, 10, 5, 1], 38 | [1, 6, 15, 20, 15, 6, 1], 39 | [1, 7, 21, 35, 35, 21, 7, 1], 40 | [1, 8, 28, 56, 70, 56, 28, 8, 1], 41 | [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] 42 | ]); 43 | 44 | expect(pascalsTriangle(5)).toEqual(_iterative(5)); 45 | }); 46 | }); 47 | -------------------------------------------------------------------------------- /java/leetcode/moving-average-from-data-stream-346.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. 3 | * For example, 4 | * MovingAverage m = new MovingAverage(3); 5 | * m.next(1) = 1 6 | * m.next(10) = (1 + 10) / 2 7 | * m.next(3) = (1 + 10 + 3) / 3 8 | * m.next(5) = (10 + 3 + 5) / 3 9 | * Input : ["MovingAverage","next","next","next","next"] 10 | * [[3],[1],[10],[3],[5]] 11 | * 12 | * Output : [null,1.00000,5.50000,4.66667,6.00000] 13 | * Complexity: O(1) time, space O(n) where is the given size of the array. 14 | */ 15 | public class MovingAverage { 16 | /** Initialize your data structure here. */ 17 | int[] arr; 18 | int index; 19 | double res; 20 | int start; 21 | 22 | public MovingAverage(int size) { 23 | arr = new int[size]; 24 | index = 0; 25 | res = 0; 26 | start = 0; 27 | } 28 | 29 | public double next(int val) { 30 | // keep a constant size to divide once we reach length - 1 31 | if (start < arr.length) { 32 | start++; 33 | } 34 | res -= arr[index]; 35 | res += val; 36 | arr[index] = val; 37 | index = (index + 1) % arr.length; 38 | return res / start; 39 | } 40 | } 41 | /** 42 | * Your MovingAverage object will be instantiated and called as such: 43 | * MovingAverage obj = new MovingAverage(size); 44 | * double param_1 = obj.next(val); 45 | */ 46 | -------------------------------------------------------------------------------- /spec/recursion/depthFinderSpec.js: -------------------------------------------------------------------------------- 1 | var depthFinder = require('../../javascript/recursion/depthFinder'); 2 | 3 | describe('depthFinder', () => { 4 | it('should return the object with each value\'s path', () => { 5 | expect(depthFinder([1, 2, 3])).toEqual({ 6 | 1: [0], 7 | 2: [1], 8 | 3: [2] 9 | }); 10 | }); 11 | 12 | it('should return the object with each value\'s path', () => { 13 | expect(depthFinder([1, 2, [3]])).toEqual({ 14 | 1: [0], 15 | 2: [1], 16 | 3: [2, 0] 17 | }); 18 | }); 19 | 20 | it('should return the object with each value\'s path', () => { 21 | expect(depthFinder([1, 2, [3, [4]]])).toEqual({ 22 | 1: [0], 23 | 2: [1], 24 | 3: [2, 0], 25 | 4: [2, 1, 0] 26 | }); 27 | }); 28 | 29 | it('should return the object with each value\'s path', () => { 30 | expect(depthFinder([1, 2, [3, [4, [[5]]]]])).toEqual({ 31 | 1: [0], 32 | 2: [1], 33 | 3: [2, 0], 34 | 4: [2, 1, 0], 35 | 5: [2, 1, 1, 0, 0] 36 | }); 37 | }); 38 | 39 | it('should return the object with each value\'s path', () => { 40 | expect(depthFinder([[[1]]])).toEqual({ 41 | 1: [0, 0, 0] 42 | }); 43 | }); 44 | 45 | it('should return the object with each value\'s path', () => { 46 | expect(depthFinder([[[1], [[[2]]]]])).toEqual({ 47 | 1: [0, 0, 0], 48 | 2: [0, 1, 0, 0, 0] 49 | }); 50 | }); 51 | }); 52 | -------------------------------------------------------------------------------- /java/interview/bipartition-pattern-matching.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @Company Facebook 3 | * 4 | * Given two strings, str and pattern, return true if the str has a valid mapping between the words in str and the characters in the pattern. 5 | * The str will be whitespace separated and the pattern will be depicted using characters. 6 | * 7 | * Problem Ex. 8 | * Input: 'cat dog dog cat', 'abba' 9 | * Output: true because cat = a and dog = b. 10 | * 11 | * Input: 'cat dog dog foo', 'abba' 12 | * Output: false because cat = a so foo cannot == a 13 | */ 14 | public boolean wordPattern(String str, String pattern) { 15 | // map each letter to a string. 16 | String[] strs = str.split("\\s"); 17 | // character -> string mapping 18 | String[] map = new String[26]; 19 | HashSet set = new HashSet(); 20 | 21 | // Must be equal in length. 22 | if (strs.length != pattern.length()) return false; 23 | 24 | for (int i = 0; i < strs.length; i ++) { 25 | String string = strs[i]; 26 | char c = pattern.charAt(i); 27 | int index = c - 'a'; 28 | 29 | // First occurence of the character. 30 | if (map[index] == null && !set.contains(string)) { 31 | map[index] = string; 32 | set.add(string); 33 | 34 | // Valid pattern match 35 | } else if (map[index] != null && map[index].equals(string)) { 36 | continue; 37 | } else { 38 | return false; 39 | } 40 | } 41 | 42 | return true; 43 | } 44 | -------------------------------------------------------------------------------- /java/leetcode/merge-k-sorted-lists-23.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Use merge sort to combine the k sorted lists. 3 | * The dividing part is already completed, so just perform the merge. 4 | */ 5 | public class Solution { 6 | public ListNode mergeKLists(ListNode[] lists) { 7 | if (lists.length == 0 ) return null; 8 | int length = lists.length; 9 | int index = 0; 10 | 11 | while (length > 1) { 12 | if (index >= length - 1) index = 0; 13 | ListNode a = lists[index]; 14 | ListNode b = lists[index + 1]; 15 | 16 | lists[index] = mergeTwoLists(a, b); 17 | lists[index + 1] = lists[length - 1]; 18 | index += 2; 19 | length --; 20 | } 21 | 22 | return lists[0]; 23 | } 24 | 25 | public ListNode mergeTwoLists(ListNode a, ListNode b) { 26 | ListNode temp = new ListNode(-1); 27 | ListNode clone = temp; 28 | 29 | while (a != null || b != null) { 30 | if (a == null) { 31 | temp.next = b; 32 | return clone.next; 33 | } else if (b == null) { 34 | temp.next = a; 35 | return clone.next; 36 | } 37 | int aVal = a == null ? Integer.MAX_VALUE : a.val; 38 | int bVal = b == null ? Integer.MAX_VALUE : b.val; 39 | temp.next = aVal >= bVal ? b : a; 40 | temp = temp.next; 41 | 42 | if (aVal < bVal) a = a == null ? a : a.next; 43 | else b = b == null ? b : b.next; 44 | } 45 | 46 | return clone.next; 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /java/leetcode/binary-tree-inorder-traversal-94.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a binary tree, return the inorder traversal of its nodes' values. 3 | */ 4 | 5 | /** Iterative version **/ 6 | public List inorderTraversal(TreeNode root) { 7 | Stack stack = new Stack<>(); 8 | HashSet set = new HashSet<>(); 9 | List list = new ArrayList<>(); 10 | stack.push(root); 11 | set.add(root); 12 | if (root == null) return list; 13 | 14 | while (!stack.isEmpty()) { 15 | TreeNode node = stack.pop(); 16 | if (node == null) { 17 | continue; 18 | } 19 | 20 | TreeNode left = node.left; 21 | TreeNode right = node.right; 22 | boolean hasLeft = false; 23 | if (left != null && !set.contains(left)) { 24 | // Push the current node back into the stack because if left exists then 25 | // it will not be added in this current iteration 26 | stack.push(node); 27 | hasLeft = true; 28 | } 29 | 30 | while (left != null) { 31 | if (!set.contains(left)) { 32 | stack.push(left); 33 | set.add(left); 34 | } 35 | left = left.left; 36 | } 37 | 38 | if (hasLeft) { 39 | // We have to stop the current iteration to add all the left nodes first. 40 | continue; 41 | } 42 | 43 | list.add(node.val); 44 | 45 | if (node.right != null) { 46 | stack.push(node.right); 47 | } 48 | } 49 | 50 | return list; 51 | } 52 | -------------------------------------------------------------------------------- /java/algorithms/MatrixChainMultiplication.java: -------------------------------------------------------------------------------- 1 | public class MatrixChainMultiplication { 2 | public static void main(String[] args) { 3 | System.out.println(solve(new int[] { 6, 4, 30, 2, 10, 5 })); 4 | } 5 | 6 | public static int solve(int[] matrices) { 7 | int length = matrices.length; 8 | int[][] dp = new int[length][length]; 9 | 10 | for (int i = 0; i < length; i ++) { 11 | for (int j = 0; j < length; j ++) { 12 | dp[i][j] = i == j ? 0 : Integer.MAX_VALUE; 13 | } 14 | } 15 | 16 | for (int jump = 1; jump < length - 1; jump ++) { 17 | for (int i = 1; i + jump < length; i ++) { 18 | int j = i + jump; 19 | int product = matrices[i - 1] * matrices[j]; 20 | for (int k = i; k < j; k ++) { 21 | dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + (product * matrices[k])); 22 | } 23 | } 24 | } 25 | 26 | for (int i = 0; i < length; i ++) { 27 | for (int j = 0; j < length; j ++) { 28 | if (dp[i][j] == Integer.MAX_VALUE) { 29 | System.out.print("-\t"); 30 | } else { 31 | System.out.print(dp[i][j] + "\t"); 32 | } 33 | } 34 | System.out.println(""); 35 | } 36 | 37 | return dp[1][length - 1]; 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /spec/search/binarysearchSpec.js: -------------------------------------------------------------------------------- 1 | var binarysearch = require('../../javascript/search/binarysearch'); 2 | 3 | describe('binarysearch', () => { 4 | it('should return the index of the value', () => { 5 | var array = [1, 3, 5, 7, 9, 11, 13, 15]; 6 | expect(binarysearch(array, 1)).toEqual(0); 7 | expect(binarysearch(array, 3)).toEqual(1); 8 | expect(binarysearch(array, 5)).toEqual(2); 9 | expect(binarysearch(array, 7)).toEqual(3); 10 | expect(binarysearch(array, 9)).toEqual(4); 11 | expect(binarysearch(array, 11)).toEqual(5); 12 | expect(binarysearch(array, 13)).toEqual(6); 13 | expect(binarysearch(array, 15)).toEqual(7); 14 | }); 15 | 16 | it('should work with even number of values in the array', () => { 17 | var array = [1, 3, 5, 7, 9, 11, 13, 15, 17]; 18 | var value = 13; 19 | expect(binarysearch(array, value)).toEqual(6); 20 | }); 21 | 22 | it('should return -1 if not found', () => { 23 | var array = [1, 2, 3]; 24 | var value = 4; 25 | expect(binarysearch(array, value)).toEqual(-1); 26 | }); 27 | 28 | it('should work with an empty array', () => { 29 | var array = []; 30 | var value = 1; 31 | expect(binarysearch(array, value)).toEqual(-1); 32 | }); 33 | 34 | it('should work with an array with a single value', () => { 35 | var array = [1]; 36 | var value = 1; 37 | expect(binarysearch(array, value)).toEqual(0); 38 | expect(binarysearch(array, 2)).toEqual(-1); 39 | }); 40 | }); 41 | -------------------------------------------------------------------------------- /java/leetcode/flatten-nested-list-iterator-341.java: -------------------------------------------------------------------------------- 1 | /** 2 | * // This is the interface that allows for creating nested lists. 3 | * // You should not implement it, or speculate about its implementation 4 | * public interface NestedInteger { 5 | * 6 | * // @return true if this NestedInteger holds a single integer, rather than a nested list. 7 | * public boolean isInteger(); 8 | * 9 | * // @return the single integer that this NestedInteger holds, if it holds a single integer 10 | * // Return null if this NestedInteger holds a nested list 11 | * public Integer getInteger(); 12 | * 13 | * // @return the nested list that this NestedInteger holds, if it holds a nested list 14 | * // Return null if this NestedInteger holds a single integer 15 | * public List getList(); 16 | * } 17 | */ 18 | public class NestedIterator implements Iterator { 19 | 20 | Queue q; 21 | public NestedIterator(List nestedList) { 22 | q = new LinkedList<>(); 23 | append(nestedList); 24 | } 25 | 26 | private void append(List list) { 27 | for (NestedInteger cur : list) { 28 | if (cur.isInteger()) { 29 | q.add(cur.getInteger()); 30 | } else { 31 | append(cur.getList()); 32 | } 33 | } 34 | } 35 | 36 | public Integer next() { 37 | return q.poll(); 38 | } 39 | 40 | public boolean hasNext() { 41 | return !q.isEmpty(); 42 | } 43 | } 44 | 45 | -------------------------------------------------------------------------------- /java/leetcode/3sum-closest-16.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array S of n integers, 3 | * find three integers in S such that the sum is closest to a given number, target. 4 | * Return the sum of the three integers. You may assume that each input would have exactly one solution. 5 | */ 6 | public class Solution { 7 | public int threeSumClosest(int[] nums, int target) { 8 | // Sort the array to make it run in O(N^2) time. 9 | Arrays.sort(nums); 10 | 11 | // No index out of bounds error due to a guaranteed sum. 12 | int closestSum = nums[0] + nums[1] + nums[2]; 13 | 14 | for (int i = 0; i < nums.length; i ++) { 15 | int currentTarget = target - nums[i]; 16 | int j = i + 1; 17 | int k = nums.length - 1; 18 | 19 | // Find the target relative to index i. 20 | while (j < k) { 21 | int currentSum = nums[j] + nums[k]; 22 | 23 | // If the sum is actually found, then just return this as it is as close as can be. 24 | if (currentSum == currentTarget) return target; 25 | 26 | // Update the closest sum to whichever is closer. 27 | int prevDiff = Math.abs(closestSum - target); 28 | int currDiff = Math.abs(currentSum + nums[i] - target); 29 | closestSum = prevDiff > currDiff ? currentSum + nums[i] : closestSum; 30 | if (currentSum > currentTarget) { 31 | k --; 32 | } else { 33 | j ++; 34 | } 35 | 36 | } 37 | } 38 | 39 | return closestSum; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /java/leetcode/predict-the-winner-486.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of scores that are non-negative integers. 3 | * Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. 4 | * Each time a player picks a number, that number will not be available for the next player. 5 | * This continues until all the scores have been chosen. 6 | * The player with the maximum score wins. 7 | * Given an array of scores, predict whether player 1 is the winner. 8 | * You can assume each player plays to maximize his score. 9 | */ 10 | public class Solution { 11 | public boolean PredictTheWinner(int[] nums) { 12 | if (nums.length <= 2) return true; 13 | return predict(nums, 0, nums.length - 1, 0, 0, true /* player 1 goes first */); 14 | } 15 | 16 | public boolean predict(int[] nums, int i, int j, int p1, int p2, boolean turn) { 17 | if (i > j) { 18 | // Return true if the player that made the last move has won. 19 | // If p1 made the last move, then p1 >= p2. 20 | // If p2 made the last move, then p1 < p2. 21 | return turn ? p1 >= p2 : p2 > p1; 22 | } 23 | 24 | if (turn) { 25 | return !predict(nums, i + 1, j, p1 + nums[i], p2, !turn) || 26 | !predict(nums, i, j - 1, p1 + nums[j], p2, !turn); 27 | } else { 28 | return !predict(nums, i + 1, j, p1, p2 + nums[i], !turn) || 29 | !predict(nums, i, j - 1, p1, p2 + nums[j], !turn); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /java/leetcode/longest-absolute-file-path-388.java: -------------------------------------------------------------------------------- 1 | /** 2 | * We are interested in finding the longest (number of characters) absolute path to a file within our file system. 3 | * For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext" 4 | * its length is 32 (not including the double quotes). 5 | * 6 | * Given a string representing the file system in the above format, return the length of the longest absolute path to 7 | * file in the abstracted file system. If there is no file in the system, return 0. 8 | * 9 | * Note: 10 | * The name of a file contains at least a . and an extension. 11 | * The name of a directory or sub-directory will not contain a .. 12 | * Time complexity required: O(n) where n is the size of the input string. 13 | * Notice that a/aa/aaa/file1.txt is not the longest file path, if there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png. 14 | * Complexity : O(N) time, O(N) space 15 | */ 16 | public class Solution { 17 | public int lengthLongestPath(String input) { 18 | int[] level = new int[input.length()]; 19 | int max = 0; 20 | 21 | for (String s : input.split("\n")) { 22 | int depth = s.lastIndexOf("\t") + 1; 23 | // stores the depth as an index 24 | level[depth] = s.length() - depth + 1; 25 | if (depth - 1 >= 0) { 26 | level[depth] += level[depth - 1]; 27 | } 28 | if (s.contains(".")) { 29 | max = Math.max(max, level[depth] - 1); 30 | } 31 | } 32 | return max; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /java/programmingteam/Polling.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Hashtable; 3 | import java.util.Set; 4 | import java.util.Arrays; 5 | import java.util.ArrayList; 6 | 7 | public class Polling { 8 | public static void main(String[] args) { 9 | Scanner s = new Scanner(System.in); 10 | int count = Integer.parseInt(s.nextLine()); 11 | Hashtable table = new Hashtable(count); 12 | int score = 0; 13 | for (int i = 0; i < count; i++) { 14 | String name = s.nextLine().trim(); 15 | if (name.length() == 0) { 16 | continue; 17 | } 18 | if (table.get(name) == null) { 19 | table.put(name, 1); 20 | score = Math.max(score, 1); 21 | } else { 22 | int currentScore = table.get(name) + 1; 23 | table.put(name, table.get(name) + 1); 24 | score = Math.max(currentScore, score); 25 | } 26 | } 27 | 28 | Set keys = table.keySet(); 29 | ArrayList names = new ArrayList(count); 30 | for (String key: keys) { 31 | if (table.get(key) == score){ 32 | names.add(key); 33 | } 34 | } 35 | String[] foo = new String[names.size()]; 36 | 37 | for (int i = 0; i < names.size(); i ++) { 38 | foo[i] = names.get(i); 39 | } 40 | 41 | Arrays.sort(foo); 42 | for (String name: foo) { 43 | if (name.length() == 0) { 44 | continue; 45 | } 46 | System.out.println(name.trim()); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /java/leetcode/number-of-islands-200.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. 4 | * An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. 5 | * You may assume all four edges of the grid are all surrounded by water. 6 | */ 7 | 8 | public class Solution { 9 | public int numIslands(char[][] grid) { 10 | if (grid.length == 0 || grid[0].length == 0) return 0; 11 | Stack stack = new Stack(); 12 | 13 | int count = 0; 14 | for (int i = 0; i < grid.length; i ++) { 15 | for (int j = 0; j < grid[0].length; j ++) { 16 | 17 | // Hit land which can be AT MOST 1 island. 18 | // Therefore increment by only 1 and convert all nearby land into water. 19 | if (grid[i][j] == '1') { 20 | count++; 21 | stack.clear(); 22 | stack.push(new int[] { i, j }); 23 | while (!stack.isEmpty()) { 24 | int[] pair = stack.pop(); 25 | int x = pair[0]; 26 | int y = pair[1]; 27 | if (x >= grid.length || x < 0 || y >= grid[0].length || y < 0 || grid[x][y] == '0') continue; 28 | grid[x][y] = '0'; 29 | stack.push(new int[] { x + 1, y }); 30 | stack.push(new int[] { x - 1, y }); 31 | stack.push(new int[] { x, y + 1 }); 32 | stack.push(new int[] { x, y - 1 }); 33 | 34 | } 35 | } 36 | } 37 | } 38 | return count; 39 | } 40 | } -------------------------------------------------------------------------------- /python/dcp/problem4.py: -------------------------------------------------------------------------------- 1 | # This problem was asked by Stripe. 2 | # Given an array of integers, find the first missing positive integer in linear time and constant space. 3 | # In other words, find the lowest positive integer that does not exist in the array. 4 | # The array can contain duplicates and negative numbers as well. 5 | # For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. 6 | # You can modify the input array in-place. 7 | ########################################### 8 | # Explanation 9 | # First, the answer must lie in the range 1 - len(arr). 10 | # This is because we want the smallest increasing number so we have to think of 11 | # the worst case (answer would be the largest in the array). 12 | # Knowing that the answer must be in a specific range, we can use the arr as a lookup table. 13 | # First, place all valid numbers where they belong. 14 | # Then, find the first number that does not belong. 15 | def findingFirstMissingPositive(arr): 16 | length = len(arr) 17 | if length == 0: 18 | return 1 19 | for index in range(length): 20 | value = arr[index] 21 | while value <= length and value > 0 and arr[value - 1] != value: 22 | new_value = arr[value - 1] 23 | arr[value - 1] = value 24 | value = new_value 25 | 26 | for index in range(length): 27 | if arr[index] != (index + 1): 28 | return index + 1 29 | 30 | return length + 1 -------------------------------------------------------------------------------- /spec/string/kmpSpec.js: -------------------------------------------------------------------------------- 1 | var { kmp, createTable } = require('../../javascript/string/kmp'); 2 | 3 | describe('kmp', () => { 4 | describe('main', () => { 5 | it('should return the start index if found', () => { 6 | expect(kmp('abc abcdab abcdabcdabde','abcdabd')).toEqual(15); 7 | expect(kmp('participate in parachute','abcdabd')).toEqual(-1); 8 | expect(kmp('participate in parachute','para')).toEqual(15); 9 | expect(kmp('participate in parachute','par')).toEqual(0); 10 | }); 11 | }); 12 | 13 | describe('createTable', () => { 14 | it('should create a fail table given a target string', () => { 15 | expect(createTable('abcdabd')).toEqual([-1, 0, 0, 0, 0, 1, 2, 0]); 16 | expect(createTable('abcdefg')).toEqual([-1, 0, 0, 0, 0, 0, 0, 0]); 17 | expect(createTable('abcdeab')).toEqual([-1, 0, 0, 0, 0, 0, 1, 2]); 18 | expect(createTable('abcdeabc')).toEqual([-1, 0, 0, 0, 0, 0, 1, 2, 3]); 19 | expect(createTable('abcdeabce')).toEqual([-1, 0, 0, 0, 0, 0, 1, 2, 3, 0]); 20 | expect(createTable('abcdeabczxc')).toEqual([-1, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0]); 21 | expect(createTable('123')).toEqual([-1, 0, 0, 0]); 22 | expect(createTable('abcakjdasdkjakjdklajabcajkldajsdkljaslj')).toEqual([-1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 2, 3, 4, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]); 23 | expect(createTable('participate in parachute')).toEqual([-1,0,0,0,0,0,0,0,1,2,0,0,0,0,0,0,1,2,3,0,0,0,0,0,0]); 24 | }); 25 | }); 26 | }); 27 | -------------------------------------------------------------------------------- /java/leetcode/find-largest-val-in-each-tree-row-515.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | * Complexity: O(N) time and space 10 | */ 11 | public class Solution { 12 | public List largestValues(TreeNode root) { 13 | List list = new ArrayList(); 14 | if (root == null) return list; 15 | 16 | // Using BFS 17 | Queue queue = new LinkedList(); 18 | queue.add(root); 19 | 20 | // Counters for keeping track of depth. 21 | int cur = 1; 22 | int next = 0; 23 | 24 | // The current max for the current depth. 25 | int max = Integer.MIN_VALUE; 26 | 27 | while (!queue.isEmpty()) { 28 | TreeNode node = queue.poll(); 29 | // Always update the max. 30 | max = Math.max(max, node.val); 31 | cur --; 32 | 33 | if (node.left != null) { 34 | queue.add(node.left); 35 | next ++; 36 | } 37 | 38 | if (node.right != null) { 39 | queue.add(node.right); 40 | next ++; 41 | } 42 | 43 | // The end of the level/depth has been reached 44 | // so update all counters and add the current max as well as resetting the max. 45 | if (cur == 0) { 46 | list.add(max); 47 | max = Integer.MIN_VALUE; 48 | cur = next; 49 | next = 0; 50 | } 51 | } 52 | 53 | return list; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /java/test_runner.py: -------------------------------------------------------------------------------- 1 | import subprocess, os, sys 2 | 3 | TESTS = ['MSTTest', 'DijkstraTest', 'PriorityQueueTest', 'SkipListTest', 'DisjointSetTest'] 4 | DATASTRUCTURES = ['PriorityQueue', 'GraphNode', 'GraphEdge', 'SkipList', 'DisjointSet'] 5 | ALGORITHMS = ['PrimMST', 'KruskalMST', 'DijkstraPathFinder'] 6 | DEPENDENCIES = ['GraphMaker', 'Utilities'] 7 | BIN_DIR = 'bin' 8 | 9 | try: 10 | subprocess.check_output(['javac', '-version']) 11 | except: 12 | print('Unable to find java compiler') 13 | exit(1) 14 | 15 | # Make a bin directory to store Java class files. 16 | if not os.path.isdir('bin'): 17 | os.makedirs('bin') 18 | 19 | try: 20 | dependencies = list(map((lambda name: 'tools/%s.java' % name), DEPENDENCIES)) 21 | datastructures = list(map((lambda name: 'datastructures/%s.java' % name), DATASTRUCTURES)) 22 | algorithms = list(map((lambda name: 'algorithms/%s.java' % name), ALGORITHMS)) 23 | tests = list(map((lambda name: 'tests/%s.java' % name), TESTS)) 24 | files = dependencies + datastructures + algorithms + tests 25 | print('Compiling the following files:\n\t%s\n' % '\n\t'.join(files)) 26 | subprocess.check_output(['javac', '-d', BIN_DIR] + files) 27 | 28 | except: 29 | print('Failed to compile java test code') 30 | exit(1) 31 | 32 | for test in TESTS: 33 | print('Running %s:' % test) 34 | sys.stdout.flush() 35 | try: 36 | subprocess.run(['java', '-cp', BIN_DIR, test], check=True) 37 | except: 38 | print('Test crashed: %s' % test) 39 | exit(1) 40 | -------------------------------------------------------------------------------- /java/algorithms/KruskalMST.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.*; 4 | import datastructures.GraphEdge; 5 | import datastructures.DisjointSet; 6 | 7 | public class KruskalMST { 8 | public int[][] findMST(int[][] matrix) throws Exception { 9 | int length = matrix.length; 10 | int[][] mst = new int[length][length]; 11 | // Edges to be sorted. 12 | List edges = new ArrayList<>(); 13 | 14 | // DisjointSet of nodes. 15 | DisjointSet set = new DisjointSet(length); 16 | 17 | for (int i = 0; i < length; i ++) { 18 | for (int j = i + 1; j < length; j ++) { 19 | if (matrix[i][j] > 0) { 20 | edges.add(new GraphEdge(i + 1, j + 1, matrix[i][j])); 21 | } 22 | } 23 | } 24 | 25 | if (edges.size() < length) throw new Exception("Not enough edges"); 26 | 27 | // Sort edges by weight. 28 | Collections.sort(edges); 29 | 30 | int nodeCount = length; 31 | int edgeIndex = 0; 32 | while (nodeCount > 1) { 33 | GraphEdge edge = edges.get(edgeIndex++); 34 | int node1 = edge.getA(); 35 | int node2 = edge.getB(); 36 | if (set.find(node1) != set.find(node2)) { 37 | mst[node1 - 1][node2 - 1] = 1; 38 | mst[node2 - 1][node1 - 1] = 1; 39 | nodeCount --; 40 | set.union(node1, node2); 41 | } 42 | } 43 | 44 | return mst; 45 | } 46 | } -------------------------------------------------------------------------------- /java/leetcode/relative-ranks-506.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given scores of N athletes, find their relative ranks and the people with the top three highest scores 3 | * who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal". 4 | * Input: [5, 4, 3, 2, 1] 5 | * Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"] 6 | * Explanation: The first three athletes got the top three highest scores 7 | * so they got "Gold Medal", "Silver Medal" and "Bronze Medal". 8 | * For the left two athletes, you just need to output their relative ranks according to their scores. 9 | * Key: sort the poings from highest points to lowest points to give them their rankings. 10 | * Complexity : O(N) time , O(N) space 11 | */ 12 | public class Solution { 13 | public String[] findRelativeRanks(int[] nums) { 14 | String[] res = new String[nums.length]; 15 | Integer[] ranking = new Integer[nums.length]; 16 | for (int i = 0; i < nums.length; i++) { 17 | ranking[i] = i; 18 | } 19 | Arrays.sort(ranking, (a, b) -> (nums[b] - nums[a])); 20 | 21 | for (int i = 0; i < ranking.length; i++) { 22 | // check the rankings and give the top there medals. 23 | if (i == 0) { 24 | res[ranking[i]] = "Gold Medal"; 25 | } else if (i == 1) { 26 | res[ranking[i]] = "Silver Medal"; 27 | } else if (i == 2) { 28 | res[ranking[i]] = "Bronze Medal"; 29 | } else { 30 | res[ranking[i]] = (i + 1) + ""; // Convert int to string. 31 | } 32 | } 33 | return res; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /python/dcp/problem2.py: -------------------------------------------------------------------------------- 1 | # This problem was asked by Uber. 2 | # Given an array of integers, return a new array such that each element at index i of the new array 3 | # is the product of all the numbers in the original array except the one at i. 4 | # Solve it without using division and in O(n) time. 5 | # For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. 6 | # If our input was [3, 2, 1], the expected output would be [2, 3, 6]. 7 | 8 | def product_array(arr): 9 | length = len(arr) 10 | left = [1] * length 11 | right = [1] * length 12 | result = [1] * length 13 | left_index = 0 14 | while left_index < length: 15 | right_index = length - left_index - 1 16 | 17 | if left_index - 1 >= 0: 18 | left[left_index] = arr[left_index] * left[left_index - 1] 19 | else: 20 | left[left_index] = arr[left_index] 21 | 22 | if right_index + 1 < length: 23 | right[right_index] = arr[right_index] * right[right_index + 1] 24 | else: 25 | right[right_index] = arr[right_index] 26 | 27 | left_index += 1 28 | 29 | 30 | for i in range(length): 31 | left_val = 1 32 | right_val = 1 33 | 34 | if i > 0: 35 | left_val = left[i - 1] 36 | 37 | if i < length - 1: 38 | right_val = right[i + 1] 39 | result[i] = left_val * right_val 40 | 41 | return result 42 | 43 | 44 | print(product_array([1, 2, 3, 4, 5])) 45 | print(product_array([3, 2, 1])) 46 | 47 | -------------------------------------------------------------------------------- /java/leetcode/trie-208.java: -------------------------------------------------------------------------------- 1 | public class Trie { 2 | 3 | class Node { 4 | char letter; 5 | HashMap map; 6 | boolean complete; 7 | 8 | public Node(char letter) { 9 | this.letter = letter; 10 | map = new HashMap(); 11 | complete = false; 12 | } 13 | } 14 | 15 | Node root; 16 | 17 | public Trie() { 18 | this.root = new Node('*'); 19 | } 20 | 21 | public void insert(String word) { 22 | Node node = this.root; 23 | int count = 0; 24 | 25 | for (char c : word.toCharArray()) { 26 | if (!node.map.containsKey(c)) { 27 | node.map.put(c, new Node(c)); 28 | } 29 | 30 | node = node.map.get(c); 31 | if (count == word.length() - 1) { 32 | node.complete = true; 33 | } 34 | count ++; 35 | } 36 | } 37 | 38 | public boolean search(String word) { 39 | Node node = this.root; 40 | int count = 0; 41 | while (count < word.length()) { 42 | char letter = word.charAt(count); 43 | if (!node.map.containsKey(letter)) { 44 | return false; 45 | } 46 | node = node.map.get(letter); 47 | count++; 48 | } 49 | 50 | return node.complete; 51 | } 52 | 53 | public boolean startsWith(String prefix) { 54 | Node node = this.root; 55 | int count = 0; 56 | while (count < prefix.length()) { 57 | char letter = prefix.charAt(count); 58 | if (!node.map.containsKey(letter)) { 59 | return false; 60 | } 61 | node = node.map.get(letter); 62 | count++; 63 | } 64 | return true; 65 | } 66 | } -------------------------------------------------------------------------------- /java/datastructures/DisjointSet.java: -------------------------------------------------------------------------------- 1 | package datastructures; 2 | 3 | public class DisjointSet { 4 | int[] parent; 5 | int[] rank; 6 | 7 | public DisjointSet(int length) { 8 | parent = new int[length + 1]; 9 | rank = new int[length + 1]; 10 | for (int i = 1; i <= length; i ++) { 11 | make(i); 12 | } 13 | } 14 | 15 | public void make(int i) { 16 | // Place element i in a set by itself. 17 | parent[i] = i; 18 | rank[i] = 0; 19 | } 20 | 21 | public int find(int i) { 22 | int direct = parent[i]; 23 | if (direct == i) 24 | return direct; 25 | 26 | int indirect = find(direct); 27 | 28 | // Update parent using path compression. 29 | parent[i] = indirect; 30 | return indirect; 31 | } 32 | 33 | public void union(int i, int j) throws Exception { 34 | if (i <= 0 || i >= parent.length || j <= 0 || j >= parent.length) 35 | throw new Exception("Invalid elements"); 36 | int ip = find(i); 37 | int jp = find(j); 38 | 39 | // They are already in the same set. 40 | if (ip == jp) 41 | return; 42 | 43 | int irank = rank[ip]; 44 | int jrank = rank[jp]; 45 | 46 | if (irank == jrank) { 47 | parent[ip] = jp; 48 | // Update the rank of the representative. 49 | rank[jp] = rank[ip] + 1; 50 | } else if (irank < jrank) { 51 | parent[ip] = jp; 52 | } else if (jrank < irank) { 53 | parent[jp] = ip; 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /java/leetcode/spiral-matrix-54.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 3 | * Input 4 | * [ 5 | * [ 1, 2, 3 ], 6 | * [ 4, 5, 6 ], 7 | * [ 7, 8, 9 ] 8 | * ] 9 | * Output : [1,2,3,6,9,8,7,4,5] 10 | * Note for this problem make sure you don't repeat elements. That was the issue that took me a while to figure out 11 | * Complexity : O(N^2) time , O(m * n) space 12 | */ 13 | public class Solution { 14 | public List spiralOrder(int[][] matrix) { 15 | List list = new ArrayList(); 16 | int rowStart = 0; 17 | int rowEnd = matrix.length - 1; 18 | if (matrix.length == 0) return list; 19 | int colEnd = matrix[0].length - 1; 20 | int colStart = 0; 21 | 22 | while (rowStart <= rowEnd && colStart <= colEnd) { 23 | //left to right 24 | for (int i = colStart; i <= colEnd; i++) { 25 | list.add(matrix[rowStart][i]); 26 | } 27 | rowStart++; 28 | //right to down 29 | for (int i = rowStart; i <= rowEnd; i++) { 30 | list.add(matrix[i][colEnd]); 31 | } 32 | colEnd--; 33 | //right to left 34 | if (rowStart <= rowEnd) { 35 | for (int i = colEnd; i >= colStart; i--) { 36 | list.add(matrix[rowEnd][i]); 37 | } 38 | } 39 | rowEnd--; 40 | //down to top 41 | if (colStart <= colEnd) { 42 | for (int i = rowEnd; i >= rowStart; i--) { 43 | list.add(matrix[i][colStart]); 44 | } 45 | } 46 | colStart++; 47 | } 48 | return list; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /java/epi/8.7-8.8.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 8.7 3 | * remove the kth to the last node 4 | * 1 -> 2-> 3 -> 4 -> 5 k th 2 5 | * 1 -> 2 -> 3 -> 5 6 | * O(2n) worst case, best case O(n+1) 7 | */ 8 | public Node removeKLastNode(Node node, int k){ 9 | int size = 1; 10 | Node sizeNode = node; 11 | // gets the length of the linked list 12 | while(sizeNode.next !=null){ 13 | size++; 14 | sizeNode = sizeNode.next 15 | } 16 | // index to remove the node 17 | int removeNodeIndex = size - k; 18 | int counter = 1; 19 | while( node.next != null){ 20 | // change the pointer to skip over the k node 21 | if(counter == removeNodeIndex - 1){ 22 | node.next = node.next.next; 23 | return node; 24 | } 25 | counter++; 26 | node = node.next; 27 | } 28 | } 29 | 30 | /** 31 | * 8.8 32 | * 1 - > 2 - > 3 -> 3 -> 3 - > 4 - > 5 33 | * 1 -> 2 -> 3 -> 4 -> 5 34 | * remove duplicates from a sorted linked list, returns a sorted linked list 35 | * O(N) soltution 36 | */ 37 | public Node removeDuplicates(Node node){ 38 | 39 | if(node.next == null){ 40 | return node; 41 | } 42 | Node fastPointer = node.next 43 | Node slowPointer = node; 44 | while( fastPointer.next != null){ 45 | if(slowPointer.element < fastPointer.element){ 46 | slowPointer.next = fastPointer; 47 | slowPointer = slowPointer.next; 48 | fastPointer = fastPointer.next; 49 | } 50 | else if( slowPointer.element == fastPointer.element){ 51 | fastPointer = fastPointer.next; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /java/leetcode/longest-substring-with-k-distinct-characters-340.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a string, find the length of the longest substring T that contains at most k distinct characters. 3 | * For example, given s = "eceba" and k = 2, 4 | * T is "ece" which has a length of 3 and 2 distinct characters. 5 | */ 6 | public class Solution { 7 | public static int lengthOfLongestSubstringKDistinct(String s, int k) { 8 | if (k == 0) return 0; 9 | if (s.length() == 0 || s.length() == 1) return s.length(); 10 | 11 | int i = 0; 12 | int j = 0; 13 | HashMap map = new HashMap(); 14 | int distinct = 0; 15 | int maxLength = 0; 16 | 17 | while (j < s.length()) { 18 | char next = s.charAt(j); 19 | int count = map.get(next) != null && map.get(next) > 0 ? map.get(next) : 0; 20 | map.put(next, count + 1); 21 | if (count == 0) distinct ++; 22 | 23 | // The number of distinct character is equal to K so we must remove the a distinct character and all of its occurences. 24 | if (distinct > k) { 25 | char start = s.charAt(i); 26 | 27 | // Keep moving the beginning pointer until a character frequency is 0 28 | while (i < j && map.get(s.charAt(i)) != null && map.get(s.charAt(i)) - 1 > 0) { 29 | map.put(s.charAt(i), map.get(s.charAt(i++)) - 1); 30 | } 31 | 32 | // Remove the last character. 33 | map.put(s.charAt((++i) - 1), 0); 34 | distinct --; 35 | } 36 | 37 | maxLength = Math.max(maxLength, j - i + 1); 38 | j ++; 39 | } 40 | 41 | return maxLength; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /java/leetcode/sort-chars-by-freq-451.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a string, sort it in decreasing order based on the frequency of characters. 3 | * Complexity: O(N) time and space. 4 | * Note: there is a nested loop, but it is still O(N) time because 5 | * the sum of all the counts is equal to the length of the initial string. 6 | */ 7 | public class Solution { 8 | public String frequencySort(String s) { 9 | HashMap map = new HashMap(); 10 | 11 | // Get the count of each character. 12 | for (char c: s.toCharArray()) { 13 | if (map.containsKey(c)) { 14 | map.put(c, map.get(c) + 1) ; 15 | } else { 16 | map.put(c, 1); 17 | } 18 | } 19 | 20 | // An array of stringbuilders where the index is equal to the count/frequence of those characters. 21 | StringBuilder[] arr = new StringBuilder[s.length()]; 22 | 23 | // Prepopulate all the stringbuilders. 24 | for (int i = 0; i < s.length(); i ++) arr[i] = new StringBuilder(); 25 | 26 | // Iterate through the map of character counts 27 | for (char key: map.keySet()) { 28 | int count = map.get(key); 29 | 30 | // Append the character, count times, into the corresponding stringbuilder. 31 | for (int i = 0; i < count; i ++) { 32 | arr[count - 1].append(key); 33 | } 34 | } 35 | 36 | // Create the final stringbuilder 37 | StringBuilder b = new StringBuilder(); 38 | for (StringBuilder temp: arr) { 39 | b.append(temp.toString()); 40 | } 41 | 42 | // Reverse because of decreasing order. 43 | return b.reverse().toString(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /spec/kmeans/indexSpec.js: -------------------------------------------------------------------------------- 1 | var kmeans = require('../../javascript/kmeans'); 2 | 3 | describe('kmeans', () => { 4 | describe('dataset1', () => { 5 | beforeEach(() => { 6 | this.data = [[1,2],[2,1],[2,4],[1,3],[2,2],[3,1],[1,1],[7,3],[8,2],[6,4],[7,4],[8,1],[9,2],[10,8],[9,10],[7,8],[7,9],[8,10],[9,9]]; 7 | 8 | this.factors = [0, 1]; 9 | this.clusterSize = 3; 10 | this.list = new kmeans.NodeList(this.clusterSize, this.data); 11 | }); 12 | 13 | it('should cluster the data', () => { 14 | var clusters = this.list.cluster(this.factors); 15 | expect(this.list.normalizeAxis(this.factors)).toEqual({ 0: { min: 1, max: 10, label: 0, range: 9 }, 1: { min: 1, max: 10, label: 1, range: 9 } }); 16 | expect(clusters.length).toEqual(this.clusterSize); 17 | clusters.forEach((cluster) => { 18 | cluster.forEach((point) => { 19 | expect(point).toBeWithinRange(1, 10); 20 | }); 21 | }); 22 | }); 23 | 24 | it('should make the assignments', () => { 25 | var assignments = this.list.assign(this.factors); 26 | expect(assignments.length).toEqual(this.data.length); 27 | assignments.forEach((assignment) => { 28 | expect(assignment).toBeWithinRange(0, this.clusterSize - 1); 29 | }); 30 | }); 31 | 32 | it('should keep clustering and assigning until complete', () => { 33 | var results = this.list.run(this.factors, [[9,9], [1,1], [5,2]]); 34 | expect(this.list.nodes).toEqual(this.data); 35 | var clusters = [[8,9], [1,2], [7,2]]; 36 | results.forEach(r => expect(clusters).toContain(r)); 37 | }); 38 | }); 39 | }); 40 | -------------------------------------------------------------------------------- /java/epi/9.4-9.5.java: -------------------------------------------------------------------------------- 1 | /** 2 | * EPI 9.4: Given a string representing a valid filepath, 3 | * return the shortest equivalent filepath. 4 | * Complexity: O(n) runtime and space. 5 | */ 6 | public String resolveFilepath(String filepath) { 7 | 8 | Stack stack = new Stack(); 9 | String delimiter = "/"; 10 | String[] file = filpath.split(delimiter); 11 | for (int i = 0; i < file.length(); i++) { 12 | // Ignore single periods 13 | if (file[i].equals("") || file[i].equals(".") ) { 14 | continue; 15 | } else if (file[i].equals("..") && !stack.isEmpty()) { 16 | stack.pop(); 17 | } else { 18 | stack.push(file[i]); 19 | } 20 | 21 | } 22 | return String.join("/", stack.toArray()); 23 | } 24 | 25 | /** 26 | * EPI 9.5: Given a linked list with a next pointer and a jump pointer, 27 | * Return the jump first traversal of the linked list. 28 | * The jump pointer can point to any node in the list except for itself. 29 | * Jump first traversal can be defined as prioritizing the jump pointer over the next pointer. 30 | * O(n) time and space 31 | */ 32 | public List jumpOrderList(Node node) { 33 | 34 | HashSet visited = new HashSet(); 35 | Stack stack = new Stack(); 36 | stack.push(node); 37 | while (!stack.isEmpty()) { 38 | Node temp = stack.pop(); 39 | 40 | if (!visited.contains(temp)) { 41 | visited.add(temp); 42 | if (temp.next != null) stack.push(temp.next); 43 | stack.push(temp.jump); 44 | } 45 | } 46 | 47 | return visited.toArray(); 48 | } 49 | -------------------------------------------------------------------------------- /spec/array/greatestSubarraySpec.js: -------------------------------------------------------------------------------- 1 | var greatestSubarray = require('../../javascript/array/greatestSubarray'); 2 | 3 | describe('greatestSubarray', () => { 4 | it('should return the greatest subarray whose sum is less than k', () => { 5 | var array = [1, 3, 5, 7, 9, 11, 13, 15]; 6 | var k = 15; 7 | expect(greatestSubarray(array, k)).toEqual(3); 8 | }); 9 | 10 | it('should work if the whole array is the greatest subarray', () => { 11 | var array = [74,659,931,273,545,879,924]; 12 | var k = 22337; 13 | expect(greatestSubarray(array, k)).toEqual(7); 14 | }); 15 | 16 | it('should work if no subaray exists', () => { 17 | var array = [74,659,931,273,545,879,924]; 18 | var k = 5; 19 | expect(greatestSubarray(array, k)).toEqual(0); 20 | }); 21 | 22 | it('should return the greatest subarray near the end', () => { 23 | var array = [1, 1, 100, 1, 1, 5]; 24 | var k = 10; 25 | expect(greatestSubarray(array, k)).toEqual(3); 26 | }); 27 | 28 | it('should return the greatest subarray near the beginning', () => { 29 | var array = [1, 2, 1, 2, 3, 4, 30, 1, 5, 2, 4, 20]; 30 | var k = 10; 31 | expect(greatestSubarray(array, k)).toEqual(5); 32 | }); 33 | 34 | it('should return the greatest subarray near the middle', () => { 35 | var array = [20, 25, 1, 2, 3, 2, 3, 1, 2, 3, 50, 100]; 36 | var k = 15; 37 | expect(greatestSubarray(array, k)).toEqual(7); 38 | }); 39 | 40 | it('should test all cases', () => { 41 | expect(greatestSubarray([], 1)).toEqual(0); 42 | expect(greatestSubarray([5], 1)).toEqual(0); 43 | expect(greatestSubarray([5], 5)).toEqual(1); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /java/leetcode/most-frequent-subtree-sum-508.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the root of a tree, you are asked to find the most frequent subtree sum. 3 | * The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). 4 | * So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order. 5 | * 6 | * Solution: Use DFS + recursion and hashmap to maintain frequency 7 | * Complexity: O(N) time and space. 8 | */ 9 | public class Solution { 10 | public int[] findFrequentTreeSum(TreeNode root) { 11 | if (root == null) return new int[0]; 12 | HashMap map = new HashMap(); 13 | populateMap(root, map); 14 | int max = 0; 15 | for (int i : map.keySet()) { 16 | max = Math.max(max, map.get(i)); 17 | } 18 | 19 | List list = new ArrayList(); 20 | for (int i : map.keySet()) { 21 | if (map.get(i) == max) list.add(i); 22 | } 23 | 24 | int[] res = new int[list.size()]; 25 | for (int i = 0; i < list.size(); i ++) res[i] = list.get(i); 26 | return res; 27 | } 28 | 29 | public int populateMap(TreeNode node, HashMap map) { 30 | if (node == null) return 0; 31 | if (node.left == null && node.right == null) { 32 | map.put(node.val, map.getOrDefault(node.val, 0) + 1); 33 | return node.val; 34 | } 35 | int left = populateMap(node.left, map); 36 | int right = populateMap(node.right, map); 37 | int sum = left + right + node.val; 38 | map.put(sum, map.getOrDefault(sum, 0) + 1); 39 | return sum; 40 | } 41 | } -------------------------------------------------------------------------------- /javascript/sort/README.md: -------------------------------------------------------------------------------- 1 | ## Table of Contents 2 | - [Merge Sort](#merge-sort) 3 | 4 | ## Merge Sort 5 | #### Problem 6 | Given an unsorted array, return the sorted array using a merge sort. 7 | 8 | #### Input/Output 9 | ``` 10 | Input: [1, 5, 2, 4, 3, 6] 11 | Output: [1, 2, 3, 4, 5, 6] 12 | ``` 13 | 14 | #### Explanation 15 | The merge sort uses a divide and conquer method. It first divides the given array until subarrays of length 1. It then merges each subarray with each other. The sort portion occurs during the merge. 16 | 17 | When dividing the array, split the array in half similar to a binary search. The trick for the merge is to not iterate through both subarrays but rather just compare the first two values. This is because the subarray will *always* be sorted. The subarray of 1 value will be sorted since it is by itself. When merging two subarrays, the outcome will be a sorted array twice the size of the initial subarray. 18 | 19 | The merge sort can be visualized as. 20 | ``` 21 | Divide: 22 | [1, 5, 2, 4, 3, 6] 23 | [1, 5, 2], [4, 3, 6] 24 | [1, 5], [2], [4, 3], [6] 25 | [1], [5], [2], [4], [3], [6] 26 | 27 | Merge: 28 | [1], [5], [2], [4], [3], [6] 29 | [1, 5], [2, 4], [3, 6] 30 | [1, 2, 4, 5], [3, 6] 31 | [1, 2, 3, 4, 5, 6] 32 | ``` 33 | 34 | The divide and merge portions can be done separately or one after the other. As in they can all be divided first and then merged or the first half can be divided which will then be merged before dividing the second half. 35 | 36 | The time complexity is O(nlogn) and the space complexity is O(n) where n is the length of the array. 37 | 38 | [Implementation](https://github.com/vinnyoodles/algorithms/blob/master/src/sort/mergesort.js) 39 | -------------------------------------------------------------------------------- /python/dcp/problem6.py: -------------------------------------------------------------------------------- 1 | # This problem was asked by Google. 2 | # An XOR linked list is a more memory efficient doubly linked list. 3 | # Instead of each node holding next and prev fields, it holds a field named both, which is a XOR of the next node and the previous node. 4 | # Implement a XOR linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at index. 5 | # If using a language that has no pointers (such as Python), 6 | # assume you have access to get_pointer and dereference_pointer functions that converts between nodes and memory addresses. 7 | 8 | class ListNode(object): 9 | def __init__(self, element): 10 | self.element = element 11 | self.both = None 12 | 13 | class XORLinkedList(object): 14 | def __init__(self): 15 | self.head = None 16 | self.size = 0 17 | 18 | def add(self, element): 19 | if self.head == None: 20 | self.head = ListNode(element) 21 | self.size += 1 22 | return 23 | 24 | # Get the tail node first 25 | tail = get(size - 1) 26 | node = ListNode(element) 27 | node.both = get_pointer(node) 28 | tail.both = tail.both ^ get_pointer(tail) 29 | self.size += 1 30 | 31 | 32 | def get(self, index): 33 | if index < 0 or index >= size 34 | return None 35 | 36 | node = self.head 37 | prev_p = 0 38 | for i in range(index): 39 | next_p = prev_p ^ node.both 40 | next_node = dereference_pointer(next_p) 41 | prev_p = next_node.both ^ get_pointer(node) 42 | node = next_node 43 | 44 | return node -------------------------------------------------------------------------------- /javascript/recursion/pascalsTriangle.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Pascal's triangle is defined as the rth column of the nth row is n! / ( r! x (n - r)!) 3 | * 4 | * @param {Integer} n 5 | * @return {Array} int array where each value represents a level in the triangle. 6 | */ 7 | function pascalsTriangle(n) { 8 | // Check if the triangle is empty. 9 | if (!n) return []; 10 | 11 | return pascalsTriangleRecursive(n, [[1]]); 12 | } 13 | 14 | function pascalsTriangleRecursive(n, triangle) { // jshint ignore:line 15 | if (n <= 1) return triangle; 16 | 17 | // Each level starts with 1; 18 | var level = [1]; 19 | var above = triangle[triangle.length - 1]; 20 | 21 | // A direct child level has exactly one more value. 22 | for (var i = 1; i < above.length; i ++) { 23 | level[i] = above[i] + above[i - 1]; 24 | } 25 | 26 | // Each level ends with 1. 27 | level.push(1); 28 | triangle.push(level); 29 | 30 | return pascalsTriangleRecursive(n - 1, triangle); 31 | } 32 | 33 | function pascalsTriangleIterative(n) { // jshint ignore:line 34 | // Check if n is 0. 35 | if (!n) return []; 36 | 37 | // Start with the first level already made. 38 | var triangle = [[1]]; 39 | 40 | // Add each level after the first. 41 | for (var i = 0; i < n - 1; i++) { 42 | // Each level starts with 1. 43 | var level = [1]; 44 | 45 | for (var j = 1; j < triangle[i].length; j++) { 46 | level[j] = triangle[i][j] + triangle[i][j - 1]; 47 | } 48 | 49 | // Each level ends with 1. 50 | level.push(1); 51 | triangle.push(level); 52 | } 53 | 54 | return triangle; 55 | } 56 | 57 | module.exports = { 58 | pascalsTriangle, 59 | // For testing. 60 | _iterative: pascalsTriangleIterative 61 | }; 62 | -------------------------------------------------------------------------------- /javascript/systemdesign/README.md: -------------------------------------------------------------------------------- 1 | ## Least Recently Used Cache 2 | #### Problem 3 | Design and implement a data structure for Least Recently Used cache. It should support the following operations: get and set. 4 | 5 | `get(key)` - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. 6 | `set(key, value)` - Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem, when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted. 7 | 8 | #### Input/Output 9 | ``` 10 | Input: 5 11 | Output: Cache of max size 5 12 | ``` 13 | 14 | #### Explanation 15 | There are many ways to design a least recently used cache. The optimal complexity for this cache is O(1) runtime and O(n) space. 16 | 17 | My implementation is currently O(n) for both time and space. It uses a hash table for constant lookup as well as a linked list for quick eviction. The head of the linked list represents the most recently used and the head of the list represents the least recently used. When evicting a node, it would just remove the tail. When updating a node (marking as most 18 | recent), it would move the node to the head of the list. 19 | 20 | The reason why I wasn't able to achieve O(1) runtime is because when it is updating the linked list, it has to iterate through the list to find the previous node in order to move the node to the head of the list. A solution for constant update and eviction would be to use a doubly linked list so that it would not have to iterate through the list in order to find the previous node. 21 | -------------------------------------------------------------------------------- /spec/string/balancedParenthesesSpec.js: -------------------------------------------------------------------------------- 1 | var balanced = require('../../javascript/string/balancedParentheses'); 2 | 3 | describe('balancedParentheses', () => { 4 | it('should return true for a valid expression', () => { 5 | expect(balanced('[{()}]')).toBeTruthy(); 6 | expect(balanced('{}[]()')).toBeTruthy(); 7 | expect(balanced('{{{{{{{{{{}}}}}}}}}}')).toBeTruthy(); 8 | expect(balanced('(((((((((((((((((())))))))))))))))))')).toBeTruthy(); 9 | expect(balanced('[[[[[[[[[[[[[[[[[[[[[[[[{{{{{{{}}}}}}}[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]')).toBeTruthy(); 10 | expect(balanced('[[[[[[[[[[[[[[[[[[[[[[[[{{{{{{{}}}}}}}[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]](((((((((())))))))))]]]]]]]]]]]]]]]]]')).toBeTruthy(); 11 | expect(balanced('{}()[{}]')).toBeTruthy(); 12 | expect(balanced('{}({{{{((((([[[[]]]])))))}}}})[{}]')).toBeTruthy(); 13 | }); 14 | 15 | it('should return false for an invalid expression', () => { 16 | expect(balanced('[[[[[[]]]]]')).toBeFalsy(); 17 | expect(balanced('{{{{{)}}}}')).toBeFalsy(); 18 | expect(balanced('abc')).toBeFalsy(); 19 | expect(balanced('d')).toBeFalsy(); 20 | expect(balanced()).toBeFalsy(); 21 | expect(balanced(null)).toBeFalsy(); 22 | expect(balanced('[]{}(')).toBeFalsy(); 23 | expect(balanced('{{{{{(}((([[[]]])))))}}}}}')).toBeFalsy(); 24 | expect(balanced('[[[[[[[[[[[[[[[[[[[[[[[[{{{{{{{}}}}}}}[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]')).toBeFalsy(); 25 | expect(balanced('}{}')).toBeFalsy(); 26 | expect(balanced('{{}')).toBeFalsy(); 27 | expect(balanced('{()})')).toBeFalsy(); 28 | expect(balanced('{(})')).toBeFalsy(); 29 | expect(balanced('[]{(})')).toBeFalsy(); 30 | expect(balanced('[{(})')).toBeFalsy(); 31 | }); 32 | }); 33 | -------------------------------------------------------------------------------- /javascript/recursion/depthFinder.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an arbitrary array, return a table with each value in the array pointing to its path using its indexes. 3 | * An arbitrary array is defined as an array with values as either integers or a nested arbitrary array. 4 | * 5 | * Examples: 6 | * [1, 2, 3] => { 1: [0], 2: [1], 3: [2] } 7 | * [1, 2, [3]] => { 1: [0], 2: [1], 3: [2, 0] } 8 | * [1, 2, [3, [4]]] => { 1: [0], 2: [1], 3: [2, 0], 4: [2, 1, 0] } 9 | * 10 | * Explanations: 11 | * The first test case is a simple integer array so the return object is just the value pointing to its index. 12 | * The second case has a nested array of [3] for the 3rd value so its path is equal to [2, 0] since its the 2nd index in the first array and the 0th index in the nested array. 13 | * The third case is the same as above where the value 4 is the 2nd index in the first array, 1st index in the nested array, and the 0th index in the nested nested array. 14 | * 15 | * @param {Array} arr 16 | * @return {Object} 17 | */ 18 | function depthFinder(arr) { 19 | return depthFinderRecursive(arr, {} /* Empty table to start */, [] /* Empty path to start */); 20 | } 21 | 22 | function depthFinderRecursive(arr, table, path) { // jshint ignore:line 23 | for (var i in arr) { 24 | // Add the current index into the path. 25 | path.push(Number(i)); 26 | 27 | if (typeof arr[i] === 'number') { 28 | // Set the value as a clone of the path since it will be mutating. 29 | table[arr[i]] = path.slice(); 30 | } else { // Nested array 31 | depthFinderRecursive(arr[i], table, path); 32 | } 33 | 34 | // Take the current index out of the path. 35 | path.pop(); 36 | } 37 | 38 | return table; 39 | } 40 | 41 | module.exports = depthFinder; 42 | -------------------------------------------------------------------------------- /spec/recursion/staircaseSpec.js: -------------------------------------------------------------------------------- 1 | var { staircase, _recursive } = require('../../javascript/recursion/staircase'); 2 | 3 | describe('staircase', () => { 4 | it('should return the number of steps', () => { 5 | expect(staircase(0)).toEqual(1); 6 | expect(staircase(1)).toEqual(1); 7 | expect(staircase(2)).toEqual(2); 8 | expect(staircase(3)).toEqual(4); 9 | expect(staircase(4)).toEqual(7); 10 | expect(staircase(5)).toEqual(13); 11 | expect(staircase(6)).toEqual(24); 12 | expect(staircase(7)).toEqual(44); 13 | expect(staircase(10)).toEqual(274); 14 | expect(staircase(15)).toEqual(5768); 15 | expect(staircase(20)).toEqual(121415); 16 | expect(staircase(50)).toEqual(10562230626642); 17 | expect(staircase(75)).toEqual(43650752323191775000); 18 | expect(staircase(100)).toEqual(1.803963808151009e+26); 19 | expect(staircase(150)).toEqual(3.081058855986474e+39); 20 | expect(staircase(500)).toEqual(1.3061865697021874e+132); 21 | expect(staircase(1000)).toEqual(2.7588428077664853e+264); 22 | }); 23 | 24 | it('should return 0 for negatives', () => { 25 | expect(staircase(-5)).toEqual(0); 26 | }); 27 | 28 | it('should also work using only recursion', () => { 29 | expect(staircase(0)).toEqual(_recursive(0)); 30 | expect(staircase(1)).toEqual(_recursive(1)); 31 | expect(staircase(2)).toEqual(_recursive(2)); 32 | expect(staircase(3)).toEqual(_recursive(3)); 33 | expect(staircase(4)).toEqual(_recursive(4)); 34 | expect(staircase(5)).toEqual(_recursive(5)); 35 | expect(staircase(6)).toEqual(_recursive(6)); 36 | expect(staircase(7)).toEqual(_recursive(7)); 37 | expect(staircase(10)).toEqual(_recursive(10)); 38 | expect(staircase(15)).toEqual(_recursive(15)); 39 | }); 40 | }); 41 | -------------------------------------------------------------------------------- /javascript/sort/mergesort.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A divide and conquer implementation for sorting an array. 3 | * Divide the original array into subarrays of length 2. 4 | * Conquer by sorting each subarray. 5 | * Merge all subarray back into a single, sorted array. 6 | * @param {[type]} array [description] 7 | * @return {[type]} [description] 8 | */ 9 | function mergesort(array) { 10 | // Base case where the array contains, at most, a single element. 11 | if (array.length < 2) return array; 12 | 13 | // Divide the arrays into subarrays. 14 | var midpoint = Math.round(array.length / 2); 15 | var left = array.slice(0, midpoint); 16 | var right = array.slice(midpoint, array.length); 17 | 18 | // Conquer each individual subarray. 19 | left = mergesort(left); 20 | right = mergesort(right); 21 | 22 | // Merge the sorted arrays back together. 23 | return merge(left, right); 24 | } 25 | 26 | /** 27 | * Merge two unsorted arrays into a single sorted array. 28 | * @param {Array} left 29 | * @param {Array} right 30 | * @return {Array} 31 | */ 32 | function merge(left, right) { 33 | var sorted = []; 34 | // Iterate both arrays together and push the lower value into the new array. 35 | while (left.length && right.length) { 36 | var leftValue = left[0]; 37 | var rightValue = right[0]; 38 | if (leftValue > rightValue) { 39 | sorted.push(right.shift()); 40 | } else { 41 | sorted.push(left.shift()); 42 | } 43 | } 44 | 45 | // If the two arrays are unbalanced, then push whatever is left in the longer array. 46 | while (left.length) { 47 | sorted.push(left.shift()); 48 | } 49 | 50 | while (right.length) { 51 | sorted.push(right.shift()); 52 | } 53 | 54 | return sorted; 55 | } 56 | 57 | module.exports = mergesort; 58 | -------------------------------------------------------------------------------- /java/leetcode/course-schedule-iii-630.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int scheduleCourse(int[][] courses) { 3 | Arrays.sort(courses, (a, b) -> a[1] - b[1]); 4 | int time = 0; 5 | int count = 0; 6 | for (int i = 0; i < courses.length; i++) { 7 | 8 | // If possible to add the time, then add it. 9 | if (time + courses[i][0] <= courses[i][1]) { 10 | time += courses[i][0]; 11 | courses[count++] = courses[i]; 12 | continue; 13 | } 14 | 15 | // Not possible to add the current time. 16 | int max = i; 17 | 18 | // Iterate through all the past courses to find the max course duration 19 | // out of the possible courses. 20 | for (int j = 0; j < count; j++) 21 | if (courses[j][0] > courses[max][0]) max = j; 22 | 23 | // If the max value has changed, then update the time to be the difference of the old max and the new max. 24 | // In other words, remove the biggest course from the schedule and update the time. 25 | if (courses[max][0] != courses[i][0]) { 26 | time += courses[i][0] - courses[max][0]; 27 | courses[max] = courses[i]; 28 | } 29 | } 30 | 31 | return count; 32 | } 33 | 34 | // Recursive implementation 35 | public int scheduleCourse(int[][] courses) { 36 | Arrays.sort(courses, (a, b) -> a[1] - b[1]); 37 | return helper(courses, 0, 0, 0); 38 | } 39 | 40 | public int helper(int[][] courses, int cur, int i, int day) { 41 | if (i >= courses.length) return cur; 42 | 43 | int without = helper(courses, cur, i + 1, day); 44 | int with = 0; 45 | if (courses[i][0] + day <= courses[i][1]) 46 | with = helper(courses, cur + 1, i + 1, day + courses[i][0]); 47 | 48 | return Math.max(with, without); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /java/leetcode/decode-string-394.java: -------------------------------------------------------------------------------- 1 | /** 2 | * The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. 3 | * Note that k is guaranteed to be a positive integer. 4 | * You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. 5 | * Input/Output 6 | * s = "3[a]2[bc]", return "aaabcbc". 7 | * s = "3[a2[c]]", return "accaccacc". 8 | * s = "2[abc]3[cd]ef", return "abcabccdcdcdef". 9 | * Complexity: O(N) time, N is the length of the decoded string 10 | * O(N) space, N is the length of the decoded string 11 | */ 12 | public class Solution { 13 | public String decodeString(String s) { 14 | Stack repeatValue = new Stack(); 15 | Stack str = new Stack(); 16 | int index = 0; 17 | String res = ""; 18 | while (index < s.length()) { 19 | char c = s.charAt(index); 20 | if (Character.isDigit(c)) { 21 | int start = index; 22 | while (Character.isDigit(c)) { 23 | index++; 24 | c = s.charAt(index); 25 | } 26 | int val = Integer.parseInt(s.substring(start, index)); 27 | repeatValue.push(val); 28 | c = s.charAt(index); 29 | } 30 | if (c == '[') { 31 | // want to push our string we made 32 | str.push(res); 33 | res = ""; 34 | } else if (c == ']') { 35 | int repeat = repeatValue.pop(); 36 | // get our resultString 37 | StringBuilder b = new StringBuilder(str.pop()); 38 | for (int i = 0; i < repeat; i++) { 39 | b.append(res); 40 | } 41 | res = b.toString(); 42 | } else { 43 | res += c; 44 | } 45 | index++; 46 | } 47 | return res; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /java/programmingteam/Name.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Arrays; 3 | import java.util.Collections; 4 | 5 | public class Name { 6 | public static void main(String[] args) { 7 | Scanner s = new Scanner(System.in); 8 | int count = Integer.parseInt(s.next()); 9 | String[] names = new String[count]; 10 | int[] hashed = new int[count]; 11 | 12 | for (int i = 0; i < count; i++) { 13 | names[i] = s.next(); 14 | String name = names[i]; 15 | if (shouldReverse(name)) { 16 | names[i] = reverseString(name); 17 | } 18 | } 19 | 20 | Arrays.sort(names, Collections.reverseOrder()); 21 | 22 | String outcome = append(names); 23 | String[] foos = new String[2]; 24 | foos[0] = outcome; 25 | foos[1] = "acorn"; 26 | 27 | Arrays.sort(foos, Collections.reverseOrder()); 28 | 29 | System.out.println(capitalize(foos[0])); 30 | } 31 | 32 | private static String reverseString(String name) { 33 | String foo = ""; 34 | for (int i = name.length() - 1; i >=0; i--) { 35 | foo += name.charAt(i); 36 | } 37 | return foo; 38 | } 39 | 40 | private static String append(String[] names) { 41 | String foo = ""; 42 | for (int i = 0 ;i < names.length;i ++) { 43 | foo += names[i]; 44 | } 45 | return foo; 46 | } 47 | 48 | private static String capitalize(String input) { 49 | return input.substring(0, 1).toUpperCase() + input.substring(1); 50 | } 51 | 52 | private static Boolean shouldReverse(String name) { 53 | int i = 0; 54 | int j = name.length() - 1; 55 | Boolean foo = false; 56 | while (i < j) { 57 | if (name.charAt(i) != name.charAt(j)) { 58 | return name.charAt(i) < name.charAt(j); 59 | } 60 | i ++ ; 61 | j --; 62 | } 63 | 64 | return foo; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /javascript/recursion/knapsack.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a set of items, each with weight and benefit, determine the items 3 | * to include in the knapsack so that the total weight is less than or 4 | * equal to a given weight limit and the total benefit is maximized. 5 | * 6 | * @param {Array} weights 7 | * @param {Array} benefits 8 | * @param {Int} maxWeight 9 | * @return {Array} of indexes of the items 10 | */ 11 | function knapsack(weights, benefits, maxWeight) { 12 | if (maxWeight < 1 || !weights.length || benefits.length !== weights.length) return []; 13 | return knapsackRecurse(weights, benefits, maxWeight, [], 0, 0, 0); 14 | } 15 | 16 | function knapsackRecurse(weights, benefits, maxWeight, indexes, currentIndex, currentWeight, currentBenefit) { 17 | if (currentWeight >= maxWeight || currentIndex >= weights.length) return indexes; 18 | 19 | var weight = weights[currentIndex]; 20 | var benefit = benefits[currentIndex]; 21 | 22 | if (weight > maxWeight || weight + currentWeight > maxWeight) return knapsackRecurse(weights, benefits, maxWeight, indexes, currentIndex + 1, currentWeight, currentBenefit); 23 | 24 | var withSack = knapsackRecurse(weights, benefits, maxWeight, indexes.concat(currentIndex), currentIndex + 1, currentWeight + weight, currentBenefit + benefit); 25 | var without = knapsackRecurse(weights, benefits, maxWeight, indexes, currentIndex + 1, currentWeight, currentBenefit); 26 | 27 | var a = sumBenefit(benefits, withSack); 28 | var b = sumBenefit(benefits, without); 29 | return (a > b) ? withSack : without; 30 | } 31 | 32 | function sumBenefit(benefits, indexes) { 33 | var sum = 0; 34 | indexes = indexes.slice(); 35 | for (var i in benefits) { 36 | if (!indexes.length) return sum; 37 | else if (indexes[0] == i) { 38 | sum += benefits[i]; 39 | indexes.shift(); 40 | } 41 | } 42 | return sum; 43 | } 44 | 45 | module.exports = knapsack; 46 | -------------------------------------------------------------------------------- /java/leetcode/next-greater-element-496.java: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. 3 | * Find all the next greater numbers for nums1's elements in the corresponding places of nums2. 4 | * The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. 5 | * If it does not exist, output -1 for this number. 6 | * 7 | * Solution: 8 | * For every number in nums1, we will call it num for simplicity, find the next greater element in nums2 by traversing from the back. 9 | * We iterate from the back because as soon as we find num, we break since we only want the next element AKA the element to the right. 10 | * Keep a variable that tracks the greatest element and initialize it to -1 so we do not have to check if one was found or not. 11 | * Because we iterate from the back, we never have to find the index of num in nums2 since that is when we break the loop. 12 | * 13 | * Complexity: O(n * m) time and O(n) space 14 | * where n is the length of nums1 and m is the length of nums2 15 | * 16 | */ 17 | public class Solution { 18 | public int[] nextGreaterElement(int[] findNums, int[] nums) { 19 | int[] res = new int[findNums.length]; 20 | 21 | for (int i = 0; i < findNums.length; i ++) { 22 | int num = findNums[i]; 23 | int greater = -1; 24 | 25 | // Iterate from back. 26 | for (int j = nums.length - 1; j >= 0; j --) { 27 | 28 | // Case where we found num in nums2. 29 | if (nums[j] == num) break; 30 | 31 | // Case where we update greater. 32 | // NOTE: we do not care what the previous value of greater is 33 | // since we only want a value that is greater than num and not the absolute maximum. 34 | if (nums[j] > num) greater = nums[j]; 35 | } 36 | res[i] = greater; 37 | } 38 | 39 | return res; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /java/tests/DisjointSetTest.java: -------------------------------------------------------------------------------- 1 | import datastructures.DisjointSet; 2 | public class DisjointSetTest { 3 | public static void main(String[] args) throws Exception { 4 | for (int i = 0; i < 10; i ++) { 5 | testSingleSet((int) (Math.random() * 100) + 100); 6 | testDoubleSet((int) (Math.random() * 100) + 100); 7 | } 8 | } 9 | 10 | private static void testSingleSet(int n) throws Exception { 11 | System.out.printf("\tTestSingleSet (n = %d)\n", n); 12 | DisjointSet set = new DisjointSet(n); 13 | 14 | // Place all the elements in the same set. 15 | for (int i = 2; i <= n; i ++) 16 | set.union(1, i); 17 | 18 | for (int i = 1; i <= n; i ++) { 19 | for (int j = 1; j <= n; j ++) { 20 | if (set.find(i) != set.find(j)) throw new Exception("Elements should be in the same set"); 21 | } 22 | } 23 | } 24 | 25 | private static void testDoubleSet(int n) throws Exception { 26 | System.out.printf("\tTestDoubleSet (n = %d)\n", n); 27 | DisjointSet set = new DisjointSet(n); 28 | int[] arr = new int[n + 1]; 29 | arr[1] = 1; 30 | arr[2] = 2; 31 | 32 | // Place the elements in two exclusive sets. 33 | for (int i = 3; i <= n; i ++) { 34 | int parent = Math.random() < 0.5 ? 1 : 2; 35 | set.union(parent, i); 36 | arr[i] = parent; 37 | } 38 | 39 | for (int i = 1; i <= n; i ++) { 40 | for (int j = 1; j <= n; j ++) { 41 | if (arr[i] == arr[j] && set.find(i) != set.find(j)) 42 | throw new Exception("Elements should be in the same set"); 43 | else if (arr[i] != arr[j] && set.find(i) == set.find(j)) 44 | throw new Exception("Elements should not be in the same set"); 45 | } 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /javascript/tree/TreeNode.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Creates a binary tree node. 3 | * Supports creating an entire tree if the parameter is an array. 4 | * The tree will be created using an in order traversal. 5 | * 6 | * @param {Int/Array} values 7 | * @return {TreeNode} root node. 8 | */ 9 | function TreeNode(values) { 10 | if (typeof values === 'number') values = [values]; 11 | 12 | // Return if there are no values. 13 | else if (!values.length) return; 14 | 15 | var midpoint = Math.floor(values.length / 2); 16 | var nodeValue = values[midpoint]; 17 | this.value = nodeValue; 18 | this.left = new TreeNode(values.slice(0, midpoint)); 19 | this.right = new TreeNode(values.slice(midpoint + 1)); 20 | } 21 | 22 | TreeNode.prototype.preOrder = function(array) { 23 | if (!this) return []; 24 | 25 | array = array || []; 26 | 27 | if (this.value) array.push(this.value); 28 | if (this.left) array.concat(this.left.preOrder(array)); 29 | if (this.right) array.concat(this.right.preOrder(array)); 30 | 31 | return array; 32 | }; 33 | 34 | TreeNode.prototype.inOrder = function(array) { 35 | if (!this) return []; 36 | 37 | array = array || []; 38 | 39 | if (this.left) array.concat(this.left.inOrder(array)); 40 | if (this.value) array.push(this.value); 41 | if (this.right) array.concat(this.right.inOrder(array)); 42 | 43 | return array; 44 | }; 45 | 46 | TreeNode.prototype.postOrder = function(array) { 47 | if (!this) return []; 48 | 49 | array = array || []; 50 | 51 | if (this.left) array.concat(this.left.postOrder(array)); 52 | if (this.right) array.concat(this.right.postOrder(array)); 53 | if (this.value) array.push(this.value); 54 | 55 | return array; 56 | }; 57 | 58 | TreeNode.prototype.isLeaf = function() { 59 | if (!this || !this.value) return false; 60 | return !((this.left && this.left.value) || (this.right && this.right.value)); 61 | }; 62 | 63 | module.exports = TreeNode; 64 | -------------------------------------------------------------------------------- /java/algorithms/PrimMST.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | import datastructures.PriorityQueue; 3 | import datastructures.GraphEdge; 4 | 5 | import tools.Utilities; 6 | 7 | public class PrimMST { 8 | public int[][] findMST(int[][] matrix) { 9 | PriorityQueue queue = new PriorityQueue<>(); 10 | boolean[] visited = new boolean[matrix.length]; 11 | boolean[][] inQueue = new boolean[matrix.length][matrix.length]; 12 | 13 | // A tree with n nodes will have n - 1 edges. 14 | int count = matrix.length - 1; 15 | 16 | // Pick a random starting node. 17 | int node = Utilities.getRandomNumber(1, matrix.length + 1); 18 | 19 | // Resultant matrix. 20 | int[][] mst = new int[matrix.length][matrix.length]; 21 | 22 | while (count > 0) { 23 | int[] neighbors = matrix[node - 1]; 24 | visited[node - 1] = true; 25 | for (int i = 0; i < neighbors.length; i ++) { 26 | // Skip visited nodes and edges of 0 weight. 27 | if (i == node - 1 || inQueue[i][node - 1] || neighbors[i] == 0) continue; 28 | 29 | inQueue[i][node - 1] = true; 30 | inQueue[node - 1][i] = true; 31 | queue.add(new GraphEdge(node, i + 1, neighbors[i])); 32 | } 33 | 34 | GraphEdge minEdge = queue.poll(); 35 | 36 | // If both nodes of the edge have been visited, then skip this edge. 37 | if (visited[minEdge.getA() - 1] && visited[minEdge.getB() - 1]) continue; 38 | mst[minEdge.getA() - 1][minEdge.getB() - 1] = 1; 39 | mst[minEdge.getB() - 1][minEdge.getA() - 1] = 1; 40 | 41 | // The next node will be the one that has not been visited yet. 42 | node = visited[minEdge.getA() - 1] ? minEdge.getB() : minEdge.getA(); 43 | count --; 44 | } 45 | 46 | return mst; 47 | } 48 | } -------------------------------------------------------------------------------- /javascript/string/longestSubsequence.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Find the longest subsequence that appear in both given strings and return the length of the subsequence. 3 | * A subsequence is a subset of a string that may or may not be continuous but is in the same order. 4 | * 5 | * Ex. abc is a subsequence of abcdef 6 | * abc is a subsequence of akbdec 7 | * abc is NOT a subsequence of acb or adcfb 8 | * 9 | * @param {String} x 10 | * @param {Sting} y 11 | * @return {Int} 12 | */ 13 | function longestSubsequence(x, y) { 14 | var a = x.length; 15 | var b = y.length; 16 | var grid = []; 17 | 18 | // Create the 2D array of length x times length y. 19 | // The 2D array will store the length of the current subsequence for that specific subproblem. 20 | for (var i = 0; i < a + 1; i ++) { 21 | grid.push(new Array(b + 1)); 22 | } 23 | 24 | // Break the problem into subproblems where we compare all of string Y with a subset of X. 25 | // Each iteration, we know more about the longest subsequence for that subset of X. 26 | for (var i = 0; i <= a; i ++) { 27 | for (var j = 0; j <= b; j ++ ) { 28 | // The first row and the first column are used to compare the string with the null set. 29 | if(i == 0 || j == 0){ 30 | grid[i][j] = 0; 31 | 32 | // If the characters are equal, then include it in the current subsequence. 33 | } else if(x.charAt(i - 1) === y.charAt(j - 1)) { 34 | 35 | // Update the grid by incrementing the length of the subsequence. 36 | grid[i][j] = grid[i - 1][j - 1] + 1; 37 | 38 | // If the characters do not match, then assign the length of the subsequence of the subproblem before it or the length of the subsequence excluding this character. 39 | } else { 40 | grid[i][j] = Math.max(grid[i - 1][j], grid[i][j - 1]); 41 | } 42 | } 43 | } 44 | 45 | return grid[a][b]; 46 | }; 47 | 48 | module.exports = longestSubsequence; 49 | -------------------------------------------------------------------------------- /java/leetcode/friend-circles-547.java: -------------------------------------------------------------------------------- 1 | /** 2 | * There are N students in a class. Some of them are friends, while some are not. 3 | * Their friendship is transitive in nature. 4 | * For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. 5 | * And we defined a friend circle is a group of students who are direct or indirect friends. 6 | * Given a N*N matrix M representing the friend relationship between students in the class. 7 | * If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. 8 | * And you have to output the total number of friend circles among all the students. 9 | */ 10 | public int findCircleNum(int[][] friends) { 11 | /** 12 | * For every `1` seen, increment the count by 1 and then change all direct and indirect relationships to 0 13 | * because they are all in the same friend group. 14 | * The runtime is N^2 and the space complexity is N where N is the number of friends. 15 | */ 16 | 17 | int count = 0; 18 | Stack stack = new Stack(); 19 | int[] visited = new int[friends.length]; 20 | 21 | for (int i = 0; i < friends.length; i ++) { 22 | for (int j = 0; j < friends[i].length; j ++) { 23 | if (friends[i][j] == 1) { 24 | count ++; 25 | stack.clear(); 26 | stack.push(i); 27 | stack.push(j); 28 | while (!stack.isEmpty()) { 29 | int index = stack.pop(); 30 | // If out of bounds or if we have marked the entire row already. 31 | if (index < 0 || index >= friends.length || visited[index] == 1) continue; 32 | visited[index] = 1; 33 | for (int k = 0; k < friends[index].length; k ++) { 34 | if (friends[index][k] == 1) { 35 | friends[index][k] = 0; 36 | stack.push(k); 37 | } 38 | } 39 | } 40 | } 41 | } 42 | } 43 | 44 | return count; 45 | } -------------------------------------------------------------------------------- /java/epi/9.7.java: -------------------------------------------------------------------------------- 1 | /** 2 | * class TreeNode { 3 | * TreeNode left; 4 | * TreeNode right; 5 | * int element; 6 | * } 7 | * 8 | * Given a tree with the structure above, create a list for every depth of the tree 9 | * and return all the lists. 10 | */ 11 | public List> binaryTreeDepthList(TreeNode root) { 12 | // Safety check. 13 | if (root == null) return null; 14 | 15 | Queue queue = new Queue(); 16 | // Nested list in the resultant list. 17 | List current = new ArrayList(); 18 | // The resultant list. 19 | List> result = new ArrayList>(); 20 | 21 | // Keep track of the number of nodes we have currently visited 22 | // that are in the same depth/level. 23 | int currentNodes = 1; 24 | // Keep track of the number of nodes in the same depth/level. 25 | int nextNodes = 0; 26 | 27 | queue.enqueue(root); 28 | while (!queue.isEmpty()) { 29 | TreeNode node = queue.dequeue(); 30 | current.add(node.element); 31 | currentNodes --; 32 | 33 | if (node.left != null) { 34 | queue.enqueue(node.left); 35 | nextNodes ++; 36 | } 37 | 38 | if (node.right != null) { 39 | queue.enqueue(node.right); 40 | nextNodes ++; 41 | } 42 | 43 | // All the nodes in that current level have been visited so reset the counters. 44 | if (currentNodes == 0) { 45 | // Transfer the count of the next depth to the current count since 46 | // we are now moving to the next depth. 47 | currentNodes = nextNodes; 48 | 49 | // There is a count of 0 nodes in the next next depth as we have not touched that level yet. 50 | nextNodes = 0; 51 | 52 | // Add the current list to the resultant and reset the current list. 53 | result.add(current); 54 | // Reinitialize a new list so we do not mutate the old ones. 55 | current = new ArrayList(); 56 | } 57 | } 58 | 59 | return result; 60 | } -------------------------------------------------------------------------------- /java/leetcode/unique-word-abbreviation-288.java: -------------------------------------------------------------------------------- 1 | /** 2 | * An abbreviation of a word follows the form . Below are some examples of word abbreviations: 3 | * Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary. 4 | * A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. 5 | * 6 | * Input : Given dictionary = [ "deer", "door", "cake", "card" ] 7 | * 8 | * isUnique("dear") -> 9 | * false 10 | * isUnique("cart") -> 11 | * true 12 | * isUnique("cane") -> 13 | * false 14 | * isUnique("make") -> 15 | * true 16 | * 17 | * this problem can be hard if you don't think about the edge cases. The key part is to know what makes the word true or false and 18 | * read the problem carefully when writing the code. Becauuse I had to restart since I didn't read it carefully. 19 | * Complexity : O(N) time, O(N) space 20 | */ 21 | 22 | public class ValidWordAbbr { 23 | HashMap map; 24 | public ValidWordAbbr(String[] dictionary) { 25 | map = new HashMap(); 26 | for (String s : dictionary) { 27 | if (!s.isEmpty()){ 28 | String key = s.charAt(0) +""+ (s.length() - 2) +""+ s.charAt(s.length() - 1) +""; 29 | if (!map.containsKey(key)) { 30 | map.put(key, s); 31 | } else { 32 | if (!map.get(key).equals(s)) { 33 | map.put(key, ""); 34 | } 35 | } 36 | } 37 | } 38 | } 39 | public boolean isUnique(String word) { 40 | if (word.isEmpty()) return true; 41 | String key = word.charAt(0) +""+ (word.length() - 2) +""+ word.charAt(word.length() - 1) +""; 42 | return !map.containsKey(key)|| map.get(key).equals(word); 43 | } 44 | } 45 | 46 | /** 47 | * Your ValidWordAbbr object will be instantiated and called as such: 48 | * ValidWordAbbr obj = new ValidWordAbbr(dictionary); 49 | * boolean param_1 = obj.isUnique(word); 50 | */ 51 | -------------------------------------------------------------------------------- /java/epi/8.9-8.10.java: -------------------------------------------------------------------------------- 1 | // 2 -> 3 -> 5 -> 3 -> 2 K = 3 2 | // 2 -> 2 -> 3 -> 5 -> 3 1 cycle 3 | // 3 -> 2 -> 2 -> 3 -> 5 2 cycle 4 | // 5 -> 3 -> 2 -> 2 -> 3 3 cycle result LinkedList 5 | /** 6 | * Implement a right cyclic shift 7 | * Runs in O(n) time with no extra space 8 | */ 9 | public Node cyclicRightShift(Node node, int k){ 10 | 11 | Node kMinusNode = node; 12 | Node kNode = new Node(); 13 | Node head = node; 14 | int counter = 1; 15 | 16 | // Find the kth - 1 node 17 | while (counter < k - 1) { 18 | kMinusNode = kMinusNode.next; 19 | counter++; 20 | } 21 | 22 | // Remove the kth - 1 node's pointer to make it the new tail. 23 | kNode = kMinusNode.next; 24 | Node resultNode = kNode; 25 | kMinusNode.next = null; 26 | 27 | // Find the original tail and point it to the original head to keep the list whole. 28 | while (kNode.next != null) { 29 | kNode = kNode.next; 30 | } 31 | kNode.next = head; 32 | 33 | return resultNode; 34 | 35 | } 36 | 37 | // l0 - > l1 -> l2 -> l3 -> l4 -> l5 38 | // odd = l1 -> l3 -> l5 39 | // even = l0 -> l2 -> l4 40 | // result = l0 - > l2 -> l4 -> l1 -> l3 -> l5 41 | // runs in O(n) time with of O(1) space 42 | public evenOddMerge(Node node){ 43 | 44 | Node even = node; 45 | Node result = even; 46 | 47 | if (node.next == null) { 48 | return node; 49 | } 50 | 51 | Node odd = node.next; 52 | Node headOdd = odd; 53 | int counter = 1; 54 | 55 | if (node.next.next != null) { 56 | node = node.next.next; 57 | } 58 | 59 | while (node.next != null) { 60 | counter++; 61 | int modVal = counter%2; 62 | if (modVal == 0) { 63 | even.next = node; 64 | even = even.next; 65 | } else { 66 | odd.next = node; 67 | odd = odd.next; 68 | } 69 | node = node.next; 70 | } 71 | even.next = headOdd; 72 | return result; 73 | } 74 | --------------------------------------------------------------------------------