├── .travis.yml ├── .gitignore ├── problems ├── 112-path-sum │ ├── testcases.js │ └── index.js ├── 231-power-of-two │ ├── testcases.js │ └── index.js ├── 322-coin-change │ ├── testcases.js │ └── index.js ├── 118-pascals-triangle │ ├── testcases.js │ └── index.js ├── 125-valid-palindrome │ ├── testcases.js │ └── index.js ├── 141-linked-list-cycle │ ├── testcases.js │ └── index.js ├── 228-summary-ranges │ ├── testcases.js │ └── index.js ├── 278-first-bad-version │ ├── testcases.js │ └── index.js ├── 319-bulb-switcher │ ├── testcases.js │ └── index.js ├── 326-power-of-three │ ├── testcases.js │ └── index.js ├── 119-pascals-triangle-ii │ ├── testcases.js │ └── index.js ├── 303-range-sum-query-immutable │ ├── testcases.js │ └── index.js ├── 304-range-sum-query-2d-immutable │ ├── testcases.js │ └── index.js ├── 297-serialize-and-deserialize-binary-tree │ ├── testcases.js │ └── index.js ├── 016-3sum-closest │ ├── testcases.js │ └── index.js ├── 048-rotate-image │ ├── testcases.js │ └── index.js ├── 006-zigzag-conversion │ ├── testcases.js │ └── index.js ├── 025-reverse-nodes-in-k-group │ ├── testcases.js │ └── index.js ├── 017-letter-combinations-of-a-phone-number │ ├── testcases.js │ └── index.js ├── 027-remove-element │ ├── testcases.js │ └── index.js ├── 001-two-sum │ ├── testcases.js │ └── index.js ├── 206-reverse-linked-list │ ├── testcases.js │ └── index.js ├── 021-merge-two-sorted-lists │ ├── testcases.js │ └── index.js ├── 019-remove-nth-node-from-end-of-list │ ├── testcases.js │ └── index.js ├── 023-merge-k-sorted-lists │ ├── testcases.js │ └── index.js ├── 026-remove-duplicates-from-sorted-array │ ├── testcases.js │ └── index.js ├── 003-longest-substring-without-repeating-characters │ ├── testcases.js │ └── index.js ├── 005-longest-palindromic-substring │ ├── testcases.js │ └── index.js ├── 004-median-of-two-sorted-arrays │ ├── testcases.js │ └── index.js ├── 009-palindrome-number │ ├── testcases.js │ └── index.js ├── 011-container-with-most-water │ ├── testcases.js │ └── index.js ├── 007-reverse-integer │ ├── testcases.js │ └── index.js ├── 020-valid-parentheses │ ├── testcases.js │ └── index.js ├── 242-valid-anagram │ ├── testcases.js │ └── index.js ├── 024-swap-nodes-in-pairs │ ├── testcases.js │ └── index.js ├── 008-string-to-integer-atoi │ ├── testcases.js │ └── index.js ├── 028-implement-strstr │ ├── testcases.js │ └── index.js ├── 022-generate-parentheses │ ├── testcases.js │ └── index.js ├── 010-regular-expression-matching │ ├── testcases.js │ └── index.js ├── 002-add-two-numbers │ ├── testcases.js │ └── index.js ├── 029-divide-two-integers │ ├── testcases.js │ └── index.js ├── 014-longest-common-prefix │ ├── testcases.js │ └── index.js ├── 124-binary-tree-maximum-path-sum │ ├── testcases.js │ └── index.js ├── 030-substring-with-concatenation-of-all-words │ ├── testcases.js │ └── index.js ├── 015-3sum │ ├── testcases.js │ └── index.js ├── 012-integer-to-roman │ ├── testcases.js │ └── index.js ├── 013-roman-to-integer │ ├── testcases.js │ └── index.js └── 018-4sum │ ├── index.js │ ├── index1.js │ └── testcases.js ├── README.md ├── .eslintrc ├── package.json ├── structures ├── TreeNode.js └── ListNode.js └── test └── index.js /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "4" 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | npm-debug.log 3 | .DS_Store 4 | -------------------------------------------------------------------------------- /problems/112-path-sum/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/231-power-of-two/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/322-coin-change/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/118-pascals-triangle/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/125-valid-palindrome/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/141-linked-list-cycle/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/228-summary-ranges/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/278-first-bad-version/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/319-bulb-switcher/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/326-power-of-three/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/119-pascals-triangle-ii/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/303-range-sum-query-immutable/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/304-range-sum-query-2d-immutable/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/297-serialize-and-deserialize-binary-tree/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | ]; 3 | -------------------------------------------------------------------------------- /problems/016-3sum-closest/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [[-1, 2, 1, -4], 1], 4 | output: 2, 5 | }, 6 | ]; 7 | -------------------------------------------------------------------------------- /problems/048-rotate-image/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [[[0, 1], [0, 1]]], 4 | output: undefined, 5 | }, 6 | ]; 7 | -------------------------------------------------------------------------------- /problems/006-zigzag-conversion/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: ['PAYPALISHIRING', 3], 4 | output: 'PAHNAPLSIIGYIR', 5 | }, 6 | { 7 | input: ['AB', 1], 8 | output: 'AB', 9 | }, 10 | ]; 11 | -------------------------------------------------------------------------------- /problems/025-reverse-nodes-in-k-group/testcases.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('../../structures/ListNode'); 2 | 3 | module.exports = [ 4 | { 5 | input: [ListNode.generateList(531), 2], 6 | output: ListNode.generateList(513), 7 | }, 8 | ]; 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | 3 | [![Build Status](https://travis-ci.org/xcatliu/leetcode.svg?branch=master)](https://travis-ci.org/xcatliu/leetcode) 4 | 5 | My LeetCode Solutions. 6 | 7 | # Test 8 | 9 | ``` 10 | npm i 11 | npm test 12 | ``` 13 | -------------------------------------------------------------------------------- /problems/017-letter-combinations-of-a-phone-number/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: ['23'], 4 | output: ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf'], 5 | }, 6 | { 7 | input: [''], 8 | output: [], 9 | }, 10 | ]; 11 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb/legacy", 3 | "rules": { 4 | "no-unused-vars": 0, 5 | "func-names": 0, 6 | "no-console": 0, 7 | "vars-on-top": 0, 8 | "no-use-before-define": 0 9 | }, 10 | "env": { 11 | "mocha": true 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /problems/027-remove-element/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [[1, 1, 2], 2], 4 | output: 2, 5 | }, 6 | { 7 | input: [[1, 2, 3], 4], 8 | output: 3, 9 | }, 10 | { 11 | input: [[], 0], 12 | output: 0, 13 | }, 14 | ]; 15 | -------------------------------------------------------------------------------- /problems/001-two-sum/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [[2, 7, 11, 15], 9], 4 | output: [1, 2], 5 | }, 6 | { 7 | input: [[3, 2, 4], 6], 8 | output: [2, 3], 9 | }, 10 | { 11 | input: [[0, 4, 3, 0], 0], 12 | output: [1, 4], 13 | }, 14 | ]; 15 | -------------------------------------------------------------------------------- /problems/206-reverse-linked-list/testcases.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('../../structures/ListNode'); 2 | 3 | module.exports = [ 4 | { 5 | input: [ListNode.generateList(342)], 6 | output: ListNode.generateList(243), 7 | }, 8 | { 9 | input: [null], 10 | output: null, 11 | }, 12 | ]; 13 | -------------------------------------------------------------------------------- /problems/021-merge-two-sorted-lists/testcases.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('../../structures/ListNode'); 2 | 3 | module.exports = [ 4 | { 5 | input: [ListNode.generateList(531), ListNode.generateList(421)], 6 | output: ListNode.generateList(543211), 7 | }, 8 | { 9 | input: [null, null], 10 | output: null, 11 | }, 12 | ]; 13 | -------------------------------------------------------------------------------- /problems/019-remove-nth-node-from-end-of-list/testcases.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('../../structures/ListNode'); 2 | 3 | module.exports = [ 4 | { 5 | input: [ListNode.generateList(54321), 2], 6 | output: ListNode.generateList(5321), 7 | }, 8 | { 9 | input: [ListNode.generateList(1), 1], 10 | output: null, 11 | }, 12 | ]; 13 | -------------------------------------------------------------------------------- /problems/023-merge-k-sorted-lists/testcases.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('../../structures/ListNode'); 2 | 3 | module.exports = [ 4 | { 5 | input: [[ListNode.generateList(531), ListNode.generateList(421)]], 6 | output: ListNode.generateList(543211), 7 | }, 8 | { 9 | input: [[null, null]], 10 | output: null, 11 | }, 12 | ]; 13 | -------------------------------------------------------------------------------- /problems/026-remove-duplicates-from-sorted-array/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [[1, 1, 2]], 4 | output: 2, 5 | }, 6 | { 7 | input: [[1, 2]], 8 | output: 2, 9 | }, 10 | { 11 | input: [[]], 12 | output: 0, 13 | }, 14 | { 15 | input: [[1, 1, 1, 2]], 16 | output: 2, 17 | }, 18 | ]; 19 | -------------------------------------------------------------------------------- /problems/003-longest-substring-without-repeating-characters/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: ['abcabcbb'], 4 | output: 3, 5 | }, 6 | { 7 | input: ['bbbbb'], 8 | output: 1, 9 | }, 10 | { 11 | input: ['c'], 12 | output: 1, 13 | }, 14 | { 15 | input: ['au'], 16 | output: 2, 17 | }, 18 | ]; 19 | -------------------------------------------------------------------------------- /problems/005-longest-palindromic-substring/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: ['banana'], 4 | output: 'anana', 5 | }, 6 | { 7 | input: ['a'], 8 | output: 'a', 9 | }, 10 | { 11 | input: ['aaa'], 12 | output: 'aaa', 13 | }, 14 | { 15 | input: ['ceabadabac'], 16 | output: 'abadaba', 17 | }, 18 | ]; 19 | -------------------------------------------------------------------------------- /problems/004-median-of-two-sorted-arrays/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]], 4 | output: 3, 5 | }, 6 | { 7 | input: [[], [1]], 8 | output: 1, 9 | }, 10 | { 11 | input: [[], [2, 3]], 12 | output: 2.5, 13 | }, 14 | { 15 | input: [[1, 2], [1, 2]], 16 | output: 1.5, 17 | }, 18 | ]; 19 | -------------------------------------------------------------------------------- /problems/009-palindrome-number/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [1], 4 | output: true, 5 | }, 6 | { 7 | input: [-1], 8 | output: false, 9 | }, 10 | { 11 | input: [0], 12 | output: true, 13 | }, 14 | { 15 | input: [121], 16 | output: true, 17 | }, 18 | { 19 | input: [1001], 20 | output: true, 21 | }, 22 | ]; 23 | -------------------------------------------------------------------------------- /problems/011-container-with-most-water/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [[0, 1]], 4 | output: 0, 5 | }, 6 | { 7 | input: [[1, 1]], 8 | output: 1, 9 | }, 10 | { 11 | input: [[1, 2]], 12 | output: 1, 13 | }, 14 | { 15 | input: [[1, 2, 4, 3]], 16 | output: 4, 17 | }, 18 | { 19 | input: [[5, 2, 12, 1, 5, 3, 4, 11, 9, 4]], 20 | output: 55, 21 | }, 22 | ]; 23 | -------------------------------------------------------------------------------- /problems/007-reverse-integer/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [123], 4 | output: 321, 5 | }, 6 | { 7 | input: [-123], 8 | output: -321, 9 | }, 10 | { 11 | input: [100], 12 | output: 1, 13 | }, 14 | { 15 | input: [1534236469], 16 | output: 0, 17 | }, 18 | { 19 | input: [-2147483648], 20 | output: 0, 21 | }, 22 | { 23 | input: [1463847412], 24 | output: 2147483641, 25 | }, 26 | ]; 27 | -------------------------------------------------------------------------------- /problems/020-valid-parentheses/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: ['()'], 4 | output: true, 5 | }, 6 | { 7 | input: ['()[]{}'], 8 | output: true, 9 | }, 10 | { 11 | input: ['([)]'], 12 | output: false, 13 | }, 14 | { 15 | input: ['()]'], 16 | output: false, 17 | }, 18 | { 19 | input: ['([])'], 20 | output: true, 21 | }, 22 | { 23 | input: ['(])'], 24 | output: false, 25 | }, 26 | ]; 27 | -------------------------------------------------------------------------------- /problems/242-valid-anagram/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: ['anagram', 'nagaram'], 4 | output: true, 5 | }, 6 | { 7 | input: ['', 'a'], 8 | output: false, 9 | }, 10 | { 11 | input: ['cat', 'let'], 12 | output: false, 13 | }, 14 | { 15 | input: ['', ''], 16 | output: true, 17 | }, 18 | { 19 | input: ['b', ''], 20 | output: false, 21 | }, 22 | { 23 | input: ['a', 'a'], 24 | output: true, 25 | }, 26 | ]; 27 | -------------------------------------------------------------------------------- /problems/326-power-of-three/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/power-of-three/ 3 | * 4 | * Given an integer, write a function to determine if it is a power of three. 5 | * 6 | * Follow up: 7 | * Could you do it without using any loop / recursion? 8 | */ 9 | 10 | /** 11 | * @param {number} n 12 | * @return {boolean} 13 | */ 14 | var isPowerOfThree = module.exports = function (n) { 15 | if (n === 0) return false; 16 | return Math.pow(3, n.toString(3).length - 1) === n; 17 | }; 18 | -------------------------------------------------------------------------------- /problems/024-swap-nodes-in-pairs/testcases.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('../../structures/ListNode'); 2 | 3 | module.exports = [ 4 | { 5 | input: [ListNode.generateList(531)], 6 | output: ListNode.generateList(513), 7 | }, 8 | { 9 | input: [ListNode.generateList(1)], 10 | output: ListNode.generateList(1), 11 | }, 12 | { 13 | input: [null], 14 | output: null, 15 | }, 16 | { 17 | input: [ListNode.generateList(4321)], 18 | output: ListNode.generateList(3412), 19 | }, 20 | ]; 21 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "leetcode-js", 3 | "version": "0.0.0", 4 | "description": "My LeetCode solutions using JavaScript.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "npm run lint && mocha", 8 | "lint": "eslint . && echo 'ESLint Passed.\\n'" 9 | }, 10 | "author": "xcatliu ", 11 | "license": "MIT", 12 | "devDependencies": { 13 | "eslint": "^1.10.3", 14 | "eslint-config-airbnb": "^3.1.0", 15 | "glob": "^5.0.5", 16 | "mocha": "^2.2.4" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /problems/008-string-to-integer-atoi/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: ['1'], 4 | output: 1, 5 | }, 6 | { 7 | input: ['0'], 8 | output: 0, 9 | }, 10 | { 11 | input: ['+'], 12 | output: 0, 13 | }, 14 | { 15 | input: ['+1'], 16 | output: 1, 17 | }, 18 | { 19 | input: ['+-2'], 20 | output: 0, 21 | }, 22 | { 23 | input: ['2147483648'], 24 | output: 2147483647, 25 | }, 26 | { 27 | input: [' b11228552307'], 28 | output: 0, 29 | }, 30 | ]; 31 | -------------------------------------------------------------------------------- /problems/231-power-of-two/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/power-of-two/ 3 | * 4 | * Given an integer, write a function to determine if it is a power of two. 5 | */ 6 | 7 | /** 8 | * @param {number} n 9 | * @return {boolean} 10 | */ 11 | var isPowerOfTwo = module.exports = function (n) { 12 | if (n <= 0) return false; 13 | var nString = n.toString(2); 14 | for (var i = 1; i < nString.length; i++) { 15 | if (nString[i] === '1') { 16 | return false; 17 | } 18 | } 19 | return true; 20 | }; 21 | -------------------------------------------------------------------------------- /structures/TreeNode.js: -------------------------------------------------------------------------------- 1 | // Definition for a binary tree node. 2 | 3 | function TreeNode(val) { 4 | this.val = val; 5 | this.left = this.right = null; 6 | } 7 | 8 | TreeNode.deserialize = function (data) { 9 | if (typeof data === 'string') { 10 | return deser(JSON.parse(data)); 11 | } 12 | return deser(data); 13 | 14 | function deser(d) { 15 | if (d === null) return null; 16 | var root = new TreeNode(d[0]); 17 | root.left = deser(d[1]); 18 | root.right = deser(d[2]); 19 | return root; 20 | } 21 | }; 22 | 23 | module.exports = TreeNode; 24 | -------------------------------------------------------------------------------- /structures/ListNode.js: -------------------------------------------------------------------------------- 1 | // Definition for singly-linked list. 2 | 3 | function ListNode(val) { 4 | this.val = val; 5 | this.next = null; 6 | } 7 | 8 | ListNode.generateList = function (num) { 9 | var numbers = num.toString().split('').map(Number); 10 | var result; 11 | var tmp; 12 | numbers.forEach(function (number, index) { 13 | if (index === 0) { 14 | result = new ListNode(number); 15 | return; 16 | } 17 | tmp = new ListNode(number); 18 | tmp.next = result; 19 | result = tmp; 20 | }); 21 | return result; 22 | }; 23 | 24 | module.exports = ListNode; 25 | -------------------------------------------------------------------------------- /problems/028-implement-strstr/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: ['', ''], 4 | output: 0, 5 | }, 6 | { 7 | input: ['a', ''], 8 | output: 0, 9 | }, 10 | { 11 | input: ['abc', 'ababac'], 12 | output: -1, 13 | }, 14 | { 15 | input: ['abc', 'a'], 16 | output: 0, 17 | }, 18 | { 19 | input: ['', 'a'], 20 | output: -1, 21 | }, 22 | { 23 | input: ['abcabc', 'cd'], 24 | output: -1, 25 | }, 26 | { 27 | input: ['abcabc', 'ca'], 28 | output: 2, 29 | }, 30 | { 31 | input: ['bananab', 'nab'], 32 | output: 4, 33 | }, 34 | ]; 35 | -------------------------------------------------------------------------------- /problems/022-generate-parentheses/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [0], 4 | output: [], 5 | }, 6 | { 7 | input: [1], 8 | output: ['()'], 9 | }, 10 | { 11 | input: [2], 12 | output: ['()()', '(())'], 13 | }, 14 | { 15 | input: [3], 16 | output: ['()()()', '(())()', '()(())', '(()())', '((()))'], 17 | }, 18 | { 19 | input: [4], 20 | output: [ 21 | '()()()()', '(())()()', '()(())()', '(()())()', '((()))()', 22 | '()()(())', '(())(())', '()(()())', '(()()())', '((())())', 23 | '()((()))', '(()(()))', '((()()))', '(((())))', 24 | ], 25 | }, 26 | ]; 27 | -------------------------------------------------------------------------------- /problems/010-regular-expression-matching/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: ['aa', 'a'], 4 | output: false, 5 | }, 6 | { 7 | input: ['aa', 'aa'], 8 | output: true, 9 | }, 10 | { 11 | input: ['aaa', 'aa'], 12 | output: false, 13 | }, 14 | { 15 | input: ['aa', 'a*'], 16 | output: true, 17 | }, 18 | { 19 | input: ['aa', '.*'], 20 | output: true, 21 | }, 22 | { 23 | input: ['ab', '.*'], 24 | output: true, 25 | }, 26 | { 27 | input: ['aab', 'c*a*b'], 28 | output: true, 29 | }, 30 | { 31 | input: ['bbba', '.*a*a'], 32 | output: true, 33 | }, 34 | ]; 35 | -------------------------------------------------------------------------------- /problems/002-add-two-numbers/testcases.js: -------------------------------------------------------------------------------- 1 | var ListNode = require('../../structures/ListNode'); 2 | 3 | module.exports = [ 4 | { 5 | input: [ListNode.generateList(342), ListNode.generateList(465)], 6 | output: ListNode.generateList(807), 7 | }, 8 | { 9 | input: [ListNode.generateList(999), ListNode.generateList(888)], 10 | output: ListNode.generateList(1887), 11 | }, 12 | { 13 | input: [ListNode.generateList(81), ListNode.generateList(0)], 14 | output: ListNode.generateList(81), 15 | }, 16 | { 17 | input: [ListNode.generateList(0), ListNode.generateList(0)], 18 | output: ListNode.generateList(0), 19 | }, 20 | ]; 21 | -------------------------------------------------------------------------------- /problems/029-divide-two-integers/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [0, 0], 4 | output: 0, 5 | }, 6 | { 7 | input: [1, 0], 8 | output: 0, 9 | }, 10 | { 11 | input: [0, 1], 12 | output: 0, 13 | }, 14 | { 15 | input: [4, 2], 16 | output: 2, 17 | }, 18 | { 19 | input: [5, 2], 20 | output: 2, 21 | }, 22 | { 23 | input: [5, -2], 24 | output: -2, 25 | }, 26 | { 27 | input: [-2147483648, -1], 28 | output: 2147483647, 29 | }, 30 | { 31 | input: [7, 3], 32 | output: 2, 33 | }, 34 | { 35 | input: [2147483647, 3], 36 | output: 715827882, 37 | }, 38 | ]; 39 | -------------------------------------------------------------------------------- /problems/027-remove-element/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/remove-element/ 3 | * 4 | * Given an array and a value, 5 | * remove all instances of that value in place and return the new length. 6 | * 7 | * The order of elements can be changed. 8 | * It doesn't matter what you leave beyond the new length. 9 | */ 10 | 11 | /** 12 | * @param {number[]} nums 13 | * @param {number} val 14 | * @return {number} 15 | */ 16 | var removeElement = module.exports = function (nums, val) { 17 | for (var i = 0; i < nums.length; i++) { 18 | if (nums[i] === val) { 19 | nums.splice(i, 1); 20 | i--; 21 | } 22 | } 23 | return nums.length; 24 | }; 25 | -------------------------------------------------------------------------------- /problems/014-longest-common-prefix/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [[]], 4 | output: '', 5 | }, 6 | { 7 | input: [['a']], 8 | output: 'a', 9 | }, 10 | { 11 | input: [['']], 12 | output: '', 13 | }, 14 | { 15 | input: [['a', 'a']], 16 | output: 'a', 17 | }, 18 | { 19 | input: [['ab', 'ac']], 20 | output: 'a', 21 | }, 22 | { 23 | input: [['aa', 'ab', 'aab']], 24 | output: 'a', 25 | }, 26 | { 27 | input: [['abc', 'abd', 'abcd']], 28 | output: 'ab', 29 | }, 30 | { 31 | input: [['a b', 'a ']], 32 | output: 'a ', 33 | }, 34 | { 35 | input: [['a', '']], 36 | output: '', 37 | }, 38 | ]; 39 | -------------------------------------------------------------------------------- /problems/124-binary-tree-maximum-path-sum/testcases.js: -------------------------------------------------------------------------------- 1 | var TreeNode = require('../../structures/TreeNode'); 2 | 3 | module.exports = [ 4 | { 5 | input: [TreeNode.deserialize(null)], 6 | output: 0, 7 | }, 8 | { 9 | input: [TreeNode.deserialize([1, null, null])], 10 | output: 1, 11 | }, 12 | { 13 | input: [TreeNode.deserialize([1, [2, null, null], [3, null, null]])], 14 | output: 6, 15 | }, 16 | { 17 | input: [TreeNode.deserialize([-3, null, null])], 18 | output: -3, 19 | }, 20 | { 21 | input: [TreeNode.deserialize([2, [-1, null, null], null])], 22 | output: 2, 23 | }, 24 | { 25 | input: [TreeNode.deserialize([1, [-2, null, null], [3, null, null]])], 26 | output: 4, 27 | }, 28 | ]; 29 | -------------------------------------------------------------------------------- /problems/030-substring-with-concatenation-of-all-words/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | // { 3 | // input: [0, 0], 4 | // output: 0, 5 | // }, 6 | // { 7 | // input: [1, 0], 8 | // output: 0, 9 | // }, 10 | // { 11 | // input: [0, 1], 12 | // output: 0, 13 | // }, 14 | // { 15 | // input: [4, 2], 16 | // output: 2, 17 | // }, 18 | // { 19 | // input: [5, 2], 20 | // output: 2, 21 | // }, 22 | // { 23 | // input: [5, -2], 24 | // output: -2, 25 | // }, 26 | // { 27 | // input: [-2147483648, -1], 28 | // output: 2147483647, 29 | // }, 30 | // { 31 | // input: [7, 3], 32 | // output: 2, 33 | // }, 34 | // { 35 | // input: [2147483647, 3], 36 | // output: 715827882, 37 | // }, 38 | ]; 39 | -------------------------------------------------------------------------------- /problems/030-substring-with-concatenation-of-all-words/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/substring-with-concatenation-of-all-words/ 3 | * 4 | * You are given a string, s, and a list of words, words, 5 | * that are all of the same length. 6 | * 7 | * Find all starting indices of substring(s) in s that is a concatenation of 8 | * each word in words exactly once and without any intervening characters. 9 | * 10 | * For example, given: 11 | * 12 | * s: "barfoothefoobarman" 13 | * words: ["foo", "bar"] 14 | * 15 | * You should return the indices: [0,9]. 16 | * (order does not matter). 17 | */ 18 | 19 | /** 20 | * @param {string} s 21 | * @param {string[]} words 22 | * @return {number[]} 23 | */ 24 | var findSubstring = module.exports = function (s, words) { 25 | }; 26 | -------------------------------------------------------------------------------- /problems/119-pascals-triangle-ii/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/pascals-triangle-ii/ 3 | * 4 | * Given an index k, return the kth row of the Pascal's triangle. 5 | * 6 | * For example, given k = 3, 7 | * Return [1,3,3,1]. 8 | * 9 | * Note: 10 | * Could you optimize your algorithm to use only O(k) extra space? 11 | */ 12 | 13 | /** 14 | * @param {number} rowIndex 15 | * @return {number[]} 16 | */ 17 | var getRow = module.exports = function (rowIndex) { 18 | if (rowIndex === 0) return [1]; 19 | var result = [1, 1]; 20 | var i; 21 | var j; 22 | for (i = 0; i < rowIndex - 1; i++) { 23 | for (j = 0; j < result.length - 1; j++) { 24 | result[j] = result[j] + result[j + 1]; 25 | } 26 | result.unshift(1); 27 | } 28 | return result; 29 | }; 30 | -------------------------------------------------------------------------------- /problems/015-3sum/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [[]], 4 | output: [], 5 | }, 6 | { 7 | input: [[1, 2]], 8 | output: [], 9 | }, 10 | { 11 | input: [[1, 2, 3]], 12 | output: [], 13 | }, 14 | { 15 | input: [[0, 0, 0]], 16 | output: [[0, 0, 0]], 17 | }, 18 | { 19 | input: [[0, 0, 1]], 20 | output: [], 21 | }, 22 | { 23 | input: [[-3, 2, 1]], 24 | output: [[-3, 1, 2]], 25 | }, 26 | { 27 | input: [[2, -4]], 28 | output: [], 29 | }, 30 | { 31 | input: [[-1, 0, 1, 2, -1, -4]], 32 | output: [[-1, 0, 1], [-1, -1, 2]], 33 | }, 34 | { 35 | input: [[1, 2, -2, -1]], 36 | output: [], 37 | }, 38 | { 39 | input: [[3, 0, -2, -1, 1, 2]], 40 | output: [[-1, 0, 1], [-2, 0, 2], [-2, -1, 3]], 41 | }, 42 | ]; 43 | -------------------------------------------------------------------------------- /problems/141-linked-list-cycle/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/linked-list-cycle/ 3 | * 4 | * Given a linked list, determine if it has a cycle in it. 5 | * 6 | * Follow up: 7 | * Can you solve it without using extra space? 8 | */ 9 | 10 | /** 11 | * Definition for singly-linked list. 12 | * function ListNode(val) { 13 | * this.val = val; 14 | * this.next = null; 15 | * } 16 | */ 17 | 18 | /** 19 | * @param {ListNode} head 20 | * @return {boolean} 21 | */ 22 | var hasCycle = module.exports = function (head) { 23 | if (head === null) return false; 24 | var slow = head; 25 | var fast = head.next; 26 | while (fast !== null && fast.next !== null && fast !== slow) { 27 | fast = fast.next.next; 28 | slow = slow.next; 29 | } 30 | if (fast === null || fast.next === null) return false; 31 | return true; 32 | }; 33 | -------------------------------------------------------------------------------- /problems/118-pascals-triangle/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/pascals-triangle/ 3 | * 4 | * Given numRows, generate the first numRows of Pascal's triangle. 5 | * 6 | * For example, given numRows = 5, 7 | * Return 8 | * 9 | * [ 10 | * [1], 11 | * [1,1], 12 | * [1,2,1], 13 | * [1,3,3,1], 14 | * [1,4,6,4,1] 15 | * ] 16 | * 17 | */ 18 | 19 | /** 20 | * @param {number} numRows 21 | * @return {number[][]} 22 | */ 23 | var generate = module.exports = function (numRows) { 24 | if (numRows === 0) return []; 25 | if (numRows === 1) return [[1]]; 26 | var result = [[1], [1, 1]]; 27 | var i; 28 | var j; 29 | for (i = 2; i < numRows; i++) { 30 | result[i] = [1]; 31 | for (j = 1; j < i; j++) { 32 | result[i][j] = result[i - 1][j - 1] + result[i - 1][j]; 33 | } 34 | result[i][i] = 1; 35 | } 36 | return result; 37 | }; 38 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var glob = require('glob'); 3 | var path = require('path'); 4 | var exec = require('child_process').exec; 5 | var fs = require('fs'); 6 | 7 | var problems = glob.sync(path.resolve(__dirname, '../problems/*')); 8 | 9 | problems.forEach(function (dirPath) { 10 | var dirName = path.relative(path.resolve(dirPath, '..'), dirPath); 11 | var testcasesPath = path.join(dirPath, 'testcases.js'); 12 | var programPath = path.join(dirPath, 'index.js'); 13 | var program = require(programPath); 14 | var testcases = require(testcasesPath); 15 | // if (dirName.indexOf('002') !== 0) return; 16 | describe(dirName, function () { 17 | it('testcases should passed', function () { 18 | testcases.forEach(function (testcase) { 19 | assert.deepEqual(program.apply(null, testcase.input), testcase.output); 20 | }); 21 | }); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /problems/012-integer-to-roman/testcases.js: -------------------------------------------------------------------------------- 1 | // http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm 2 | 3 | module.exports = [ 4 | { 5 | input: [1], 6 | output: 'I', 7 | }, 8 | { 9 | input: [2], 10 | output: 'II', 11 | }, 12 | { 13 | input: [3], 14 | output: 'III', 15 | }, 16 | { 17 | input: [4], 18 | output: 'IV', 19 | }, 20 | { 21 | input: [5], 22 | output: 'V', 23 | }, 24 | { 25 | input: [6], 26 | output: 'VI', 27 | }, 28 | { 29 | input: [9], 30 | output: 'IX', 31 | }, 32 | { 33 | input: [14], 34 | output: 'XIV', 35 | }, 36 | { 37 | input: [40], 38 | output: 'XL', 39 | }, 40 | { 41 | input: [90], 42 | output: 'XC', 43 | }, 44 | { 45 | input: [550], 46 | output: 'DL', 47 | }, 48 | { 49 | input: [1500], 50 | output: 'MD', 51 | }, 52 | { 53 | input: [3999], 54 | output: 'MMMCMXCIX', 55 | }, 56 | ]; 57 | -------------------------------------------------------------------------------- /problems/013-roman-to-integer/testcases.js: -------------------------------------------------------------------------------- 1 | // http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm 2 | 3 | module.exports = [ 4 | { 5 | input: ['I'], 6 | output: 1, 7 | }, 8 | { 9 | input: ['II'], 10 | output: 2, 11 | }, 12 | { 13 | input: ['III'], 14 | output: 3, 15 | }, 16 | { 17 | input: ['IV'], 18 | output: 4, 19 | }, 20 | { 21 | input: ['V'], 22 | output: 5, 23 | }, 24 | { 25 | input: ['VI'], 26 | output: 6, 27 | }, 28 | { 29 | input: ['IX'], 30 | output: 9, 31 | }, 32 | { 33 | input: ['XIV'], 34 | output: 14, 35 | }, 36 | { 37 | input: ['XL'], 38 | output: 40, 39 | }, 40 | { 41 | input: ['XC'], 42 | output: 90, 43 | }, 44 | { 45 | input: ['DL'], 46 | output: 550, 47 | }, 48 | { 49 | input: ['MD'], 50 | output: 1500, 51 | }, 52 | { 53 | input: ['MMMCMXCIX'], 54 | output: 3999, 55 | }, 56 | ]; 57 | -------------------------------------------------------------------------------- /problems/022-generate-parentheses/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/generate-parentheses/ 3 | * 4 | * Given n pairs of parentheses, 5 | * write a function to generate all combinations of well-formed parentheses. 6 | * 7 | * For example, given n = 3, a solution set is: 8 | * 9 | * "((()))", "(()())", "(())()", "()(())", "()()()" 10 | */ 11 | 12 | /** 13 | * @param {number} n 14 | * @return {string[]} 15 | */ 16 | var generateParenthesis = module.exports = function (n) { 17 | if (n === 0) return []; 18 | if (n === 1) return ['()']; 19 | var minus1Result = generateParenthesis(n - 1); 20 | var result = []; 21 | var existsHash = {}; 22 | var tempStr; 23 | minus1Result.forEach(function (str) { 24 | for (var i = 0; i < n; i++) { 25 | tempStr = str.slice(0, i) + '()' + str.slice(i); 26 | if (existsHash[tempStr]) continue; 27 | existsHash[tempStr] = true; 28 | result.push(tempStr); 29 | } 30 | }); 31 | return result; 32 | }; 33 | -------------------------------------------------------------------------------- /problems/319-bulb-switcher/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/bulb-switcher/ 3 | * 4 | * There are n bulbs that are initially off. 5 | * You first turn on all the bulbs. Then, you turn off every second bulb. 6 | * On the third round, 7 | * you toggle every third bulb (turning on if it's off or turning off if it's on). 8 | * For the nth round, you only toggle the last bulb. 9 | * Find how many bulbs are on after n rounds. 10 | * 11 | * Example: 12 | * 13 | * Given n = 3. 14 | * 15 | * At first, the three bulbs are [off, off, off]. 16 | * After first round, the three bulbs are [on, on, on]. 17 | * After second round, the three bulbs are [on, off, on]. 18 | * After third round, the three bulbs are [on, off, off]. 19 | * 20 | * So you should return 1, because there is only one bulb is on. 21 | */ 22 | 23 | /** 24 | * @param {number} n 25 | * @return {number} 26 | */ 27 | var bulbSwitch = module.exports = function (n) { 28 | return Math.floor(Math.sqrt(n)); 29 | }; 30 | -------------------------------------------------------------------------------- /problems/013-roman-to-integer/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/roman-to-integer/ 3 | * 4 | * Given a roman numeral, convert it to an integer. 5 | * 6 | * Input is guaranteed to be within the range from 1 to 3999. 7 | */ 8 | 9 | var roman = { 10 | I: 1, 11 | V: 5, 12 | X: 10, 13 | L: 50, 14 | C: 100, 15 | D: 500, 16 | M: 1000, 17 | }; 18 | 19 | /** 20 | * @param {string} s 21 | * @return {number} 22 | */ 23 | var romanToInt = module.exports = function (s) { 24 | var sLength = s.length; 25 | var result = 0; 26 | var sub = false; 27 | for (var i = 0; i < sLength; i++) { 28 | if ( 29 | (s[i] === 'I' && (s[i + 1] === 'V' || s[i + 1] === 'X')) || 30 | (s[i] === 'X' && (s[i + 1] === 'L' || s[i + 1] === 'C')) || 31 | (s[i] === 'C' && (s[i + 1] === 'D' || s[i + 1] === 'M')) 32 | ) { 33 | result += roman[s[i + 1]] - roman[s[i]]; 34 | i++; 35 | continue; 36 | } 37 | result += roman[s[i]]; 38 | } 39 | return result; 40 | }; 41 | -------------------------------------------------------------------------------- /problems/003-longest-substring-without-repeating-characters/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/longest-substring-without-repeating-characters/ 3 | * 4 | * Given a string, find the length of the longest substring without repeating 5 | * characters. 6 | * For example, the longest substring without repeating letters for "abcabcbb" 7 | * is "abc", which the length is 3. For "bbbbb" the longest substring is "b", 8 | * with the length of 1. 9 | */ 10 | 11 | /** 12 | * @param {string} s 13 | * @return {number} 14 | */ 15 | var lengthOfLongestSubstring = module.exports = function (s) { 16 | if (s.length === 0) { 17 | return 0; 18 | } 19 | var result = 1; 20 | var j; 21 | var k; 22 | var i = 0; 23 | for (j = i + 1; j < s.length; j++) { 24 | for (k = i; k < j; k++) { 25 | if (s[k] === s[j]) { 26 | result = Math.max(result, j - i); 27 | i = k + 1; 28 | break; 29 | } 30 | } 31 | } 32 | result = Math.max(result, j - i); 33 | return result; 34 | }; 35 | -------------------------------------------------------------------------------- /problems/125-valid-palindrome/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/valid-palindrome/ 3 | * 4 | * Given a string, determine if it is a palindrome, 5 | * considering only alphanumeric characters and ignoring cases. 6 | * 7 | * For example, 8 | * "A man, a plan, a canal: Panama" is a palindrome. 9 | * "race a car" is not a palindrome. 10 | * 11 | * Note: 12 | * Have you consider that the string might be empty? 13 | * This is a good question to ask during an interview. 14 | * 15 | * For the purpose of this problem, we define empty string as valid palindrome. 16 | */ 17 | 18 | /** 19 | * @param {string} s 20 | * @return {boolean} 21 | */ 22 | var isPalindrome = module.exports = function (s) { 23 | var replacedS = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); 24 | if (replacedS.length === 0) return true; 25 | var i = 0; 26 | var j = replacedS.length - 1; 27 | while (i < j) { 28 | if (replacedS[i] === replacedS[j]) { 29 | i++; 30 | j--; 31 | } else { 32 | return false; 33 | } 34 | } 35 | return true; 36 | }; 37 | -------------------------------------------------------------------------------- /problems/026-remove-duplicates-from-sorted-array/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 3 | * 4 | * Given a sorted array, 5 | * remove the duplicates in place such that each element appear only once and 6 | * return the new length. 7 | * 8 | * Do not allocate extra space for another array, 9 | * you must do this in place with constant memory. 10 | * 11 | * For example, 12 | * Given input array nums = [1,1,2], 13 | * 14 | * Your function should return length = 2, 15 | * with the first two elements of nums being 1 and 2 respectively. 16 | * It doesn't matter what you leave beyond the new length. 17 | */ 18 | 19 | /** 20 | * @param {number[]} nums 21 | * @return {number} 22 | */ 23 | var removeDuplicates = module.exports = function (nums) { 24 | if (nums.length === 0) return 0; 25 | var hash = {}; 26 | for (var i = 0; i < nums.length; i++) { 27 | if (hash[nums[i]]) { 28 | nums.splice(i, 1); 29 | i--; 30 | } else { 31 | hash[nums[i]] = true; 32 | } 33 | } 34 | return Object.keys(hash).length; 35 | }; 36 | -------------------------------------------------------------------------------- /problems/228-summary-ranges/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/summary-ranges/ 3 | * 4 | * Given a sorted integer array without duplicates, 5 | * return the summary of its ranges. 6 | * 7 | * For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. 8 | */ 9 | 10 | /** 11 | * @param {number[]} nums 12 | * @return {string[]} 13 | */ 14 | var summaryRanges = module.exports = function (nums) { 15 | if (nums.length === 0) { 16 | return []; 17 | } 18 | var result = []; 19 | var lastStart = nums[0]; 20 | var temp = nums[0]; 21 | var i; 22 | for (i = 1; i < nums.length; i++) { 23 | if (nums[i] === temp + 1) { 24 | temp++; 25 | } else { 26 | if (lastStart === nums[i - 1]) { 27 | result.push(lastStart.toString()); 28 | } else { 29 | result.push(lastStart + '->' + nums[i - 1]); 30 | } 31 | lastStart = nums[i]; 32 | temp = nums[i]; 33 | } 34 | } 35 | if (lastStart === nums[i - 1]) { 36 | result.push(lastStart.toString()); 37 | } else { 38 | result.push(lastStart + '->' + nums[i - 1]); 39 | } 40 | return result; 41 | }; 42 | -------------------------------------------------------------------------------- /problems/112-path-sum/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/path-sum/ 3 | * 4 | * Given a binary tree and a sum, 5 | * determine if the tree has a root-to-leaf path such that adding up all the 6 | * values along the path equals the given sum. 7 | * 8 | * For example: 9 | * Given the below binary tree and sum = 22, 10 | * 5 11 | * / \ 12 | * 4 8 13 | * / / \ 14 | * 11 13 4 15 | * / \ \ 16 | * 7 2 1 17 | * return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 18 | */ 19 | 20 | /** 21 | * Definition for a binary tree node. 22 | * function TreeNode(val) { 23 | * this.val = val; 24 | * this.left = this.right = null; 25 | * } 26 | */ 27 | /** 28 | * @param {TreeNode} root 29 | * @param {number} sum 30 | * @return {boolean} 31 | */ 32 | var hasPathSum = module.exports = function (root, sum) { 33 | if (root === null) return false; 34 | if (root.val === sum && root.left === null && root.right === null) return true; 35 | return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); 36 | }; 37 | -------------------------------------------------------------------------------- /problems/020-valid-parentheses/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/valid-parentheses/ 3 | * 4 | * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', 5 | * determine if the input string is valid. 6 | * 7 | * The brackets must close in the correct order, "()" and "()[]{}" are all valid 8 | * but "(]" and "([)]" are not. 9 | */ 10 | 11 | /** 12 | * @param {string} s 13 | * @return {boolean} 14 | */ 15 | var isValid = module.exports = function (s) { 16 | var stack = []; 17 | var result = true; 18 | for (var i = 0; i < s.length; i++) { 19 | if (s[i] === '(' || s[i] === '[' || s[i] === '{') { 20 | stack.push(s[i]); 21 | } else if (s[i] === ')' || s[i] === ']' || s[i] === '}') { 22 | if (stack.length === 0) return false; 23 | if ( 24 | (stack[stack.length - 1] === '(' && s[i] === ')') || 25 | (stack[stack.length - 1] === '[' && s[i] === ']') || 26 | (stack[stack.length - 1] === '{' && s[i] === '}') 27 | ) { 28 | stack.pop(); 29 | } else { 30 | return false; 31 | } 32 | } 33 | } 34 | if (stack.length !== 0) return false; 35 | return result; 36 | }; 37 | -------------------------------------------------------------------------------- /problems/014-longest-common-prefix/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/longest-common-prefix/ 3 | * 4 | * Write a function to find the longest common prefix string amongst an array 5 | * of strings. 6 | */ 7 | 8 | /** 9 | * @param {string[]} strs 10 | * @return {string} 11 | */ 12 | var longestCommonPrefix = module.exports = function (strs) { 13 | var strsLength = strs.length; 14 | if (strsLength === 0) return ''; 15 | if (strsLength === 1) return strs[0]; 16 | 17 | // calculate minimal string length 18 | var minStrLength = strs[0].length; 19 | var i; 20 | for (i = 1; i < strsLength; i++) { 21 | minStrLength = Math.min(strs[i].length, minStrLength); 22 | } 23 | if (minStrLength === 0) return ''; 24 | 25 | for (i = 0; i < minStrLength; i++) { 26 | if (!strsIndexEqual(strs, i)) { 27 | return strs[0].slice(0, i); 28 | } 29 | } 30 | return strs[0].slice(0, i); 31 | }; 32 | 33 | function strsIndexEqual(strs, index) { 34 | var strsLength = strs.length; 35 | if (strsLength <= 1) return true; 36 | for (var i = 1; i < strsLength; i++) { 37 | if (strs[i][index] !== strs[0][index]) return false; 38 | } 39 | return true; 40 | } 41 | -------------------------------------------------------------------------------- /problems/303-range-sum-query-immutable/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/range-sum-query-immutable/ 3 | * 4 | * Given an integer array nums, 5 | * find the sum of the elements between indices i and j (i ≤ j), inclusive. 6 | * 7 | * Example: 8 | * Given nums = [-2, 0, 3, -5, 2, -1] 9 | * 10 | * sumRange(0, 2) -> 1 11 | * sumRange(2, 5) -> -1 12 | * sumRange(0, 5) -> -3 13 | * 14 | * Note: 15 | * You may assume that the array does not change. 16 | * There are many calls to sumRange function. 17 | */ 18 | 19 | /** 20 | * @constructor 21 | * @param {number[]} nums 22 | */ 23 | var NumArray = module.exports = function (nums) { 24 | this.dp = [0]; 25 | for (var i = 0; i < nums.length; i++) { 26 | this.dp[i + 1] = this.dp[i] + nums[i]; 27 | } 28 | }; 29 | 30 | /** 31 | * @param {number} i 32 | * @param {number} j 33 | * @return {number} 34 | */ 35 | NumArray.prototype.sumRange = function (i, j) { 36 | return this.dp[j + 1] - this.dp[i]; 37 | }; 38 | 39 | 40 | /** 41 | * Your NumArray object will be instantiated and called as such: 42 | * var numArray = new NumArray(nums); 43 | * numArray.sumRange(0, 1); 44 | * numArray.sumRange(0, 2); 45 | */ 46 | -------------------------------------------------------------------------------- /problems/019-remove-nth-node-from-end-of-list/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 3 | * 4 | * Given a linked list, 5 | * remove the nth node from the end of list and return its head. 6 | * 7 | * For example, 8 | * 9 | * Given linked list: 1->2->3->4->5, and n = 2. 10 | * 11 | * After removing the second node from the end, the linked list becomes 12 | * 1->2->3->5. 13 | * 14 | * Note: 15 | * 16 | * Given n will always be valid. 17 | * Try to do this in one pass. 18 | */ 19 | 20 | /** 21 | * Definition for singly-linked list. 22 | * function ListNode(val) { 23 | * this.val = val; 24 | * this.next = null; 25 | * } 26 | */ 27 | /** 28 | * @param {ListNode} head 29 | * @param {number} n 30 | * @return {ListNode} 31 | */ 32 | var removeNthFromEnd = module.exports = function (head, n) { 33 | if (n === 0) return head; 34 | var stack = []; 35 | var node = head; 36 | while (node !== null) { 37 | stack.push(node); 38 | node = node.next; 39 | } 40 | if (stack.length - n - 1 === -1) { 41 | return head.next; 42 | } 43 | stack[stack.length - n - 1].next = stack[stack.length - n + 1]; 44 | return head; 45 | }; 46 | -------------------------------------------------------------------------------- /problems/005-longest-palindromic-substring/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/longest-palindromic-substring/ 3 | * 4 | * Given a string S, find the longest palindromic substring in S. 5 | * You may assume that the maximum length of S is 1000, 6 | * and there exists one unique longest palindromic substring. 7 | */ 8 | 9 | /** 10 | * @param {string} s 11 | * @return {string} 12 | */ 13 | var longestPalindrome = module.exports = function (s) { 14 | if (s.length === 0) return ''; 15 | /** 16 | * 将 s 字符之间插入 # 17 | * banana => #b#a#n#a#n#a# 18 | * abba => #a#b#b#a# 19 | * abcd => #a#b#c#d# 20 | * 这样处理的好处是 aba 和 abba 的两种情况可以一起处理 21 | */ 22 | var insertedS = '#' + s.split('').join('#') + '#'; 23 | var length = insertedS.length; 24 | var result = ''; 25 | for (var i = 1; i < length - 1; i++) { 26 | // j 表示往左走和往右走的长度 27 | var j = 1; 28 | // 当两边的字符相同 j++ 29 | while (i - j >= 0 && i + j <= length - 1 && insertedS[i - j] === insertedS[i + j]) { 30 | j++; 31 | } 32 | // j - 1 正好就是回文字符串的长度 33 | if (j - 1 > result.length) { 34 | result = insertedS.substr(i - j + 1, j * 2 - 1).replace(/#/g, ''); 35 | } 36 | } 37 | return result; 38 | }; 39 | -------------------------------------------------------------------------------- /problems/242-valid-anagram/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/valid-anagram/ 3 | * 4 | * Given two strings s and t, write a function to determine if t is an anagram of s. 5 | * 6 | * For example, 7 | * s = "anagram", t = "nagaram", return true. 8 | * s = "rat", t = "car", return false. 9 | * 10 | * Note: 11 | * You may assume the string contains only lowercase alphabets. 12 | * 13 | * Follow up: 14 | * What if the inputs contain unicode characters? 15 | * How would you adapt your solution to such case? 16 | */ 17 | 18 | /** 19 | * @param {string} s 20 | * @param {string} t 21 | * @return {boolean} 22 | */ 23 | var isAnagram = module.exports = function (s, t) { 24 | if (s === '' && t === '') return true; 25 | if (s.length !== t.length) return false; 26 | var hash = {}; 27 | for (var i = 0; i < s.length; i++) { 28 | if (hash[s[i]] === undefined) { 29 | hash[s[i]] = 1; 30 | } else { 31 | hash[s[i]]++; 32 | } 33 | if (hash[t[i]] === undefined) { 34 | hash[t[i]] = -1; 35 | } else { 36 | hash[t[i]]--; 37 | } 38 | } 39 | return Object.keys(hash).filter(function (key) { 40 | return hash[key] !== 0; 41 | }).length === 0; 42 | }; 43 | -------------------------------------------------------------------------------- /problems/206-reverse-linked-list/index.js: -------------------------------------------------------------------------------- 1 | /* eslint no-param-reassign:0 */ 2 | 3 | /** 4 | * https://leetcode.com/problems/reverse-linked-list/ 5 | * 6 | * Reverse a singly linked list. 7 | * 8 | * Hint: 9 | * A linked list can be reversed either iteratively or recursively. 10 | * Could you implement both? 11 | */ 12 | 13 | /** 14 | * You should comment the following function to pass the leetcode tests. 15 | * Definition for singly-linked list. 16 | */ 17 | // var ListNode = require('../../structures/ListNode'); 18 | 19 | /** 20 | * Definition for singly-linked list. 21 | * function ListNode(val) { 22 | * this.val = val; 23 | * this.next = null; 24 | * } 25 | */ 26 | /** 27 | * @param {ListNode} head 28 | * @return {ListNode} 29 | */ 30 | var reverseList = module.exports = function (head) { 31 | if (head === null) return null; 32 | if (head.next === null) return head; 33 | var reverseOthers = reverseList(head.next); 34 | head.next.next = head; 35 | head.next = null; 36 | return reverseOthers; 37 | }; 38 | 39 | function getLastNode(head) { 40 | if (head === null) return null; 41 | var result = head; 42 | while (result.next !== null) { 43 | result = result.next; 44 | } 45 | return result; 46 | } 47 | -------------------------------------------------------------------------------- /problems/007-reverse-integer/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/reverse-integer/ 3 | * 4 | * Reverse digits of an integer. 5 | * 6 | * Example1: x = 123, return 321 7 | * Example2: x = -123, return -321 8 | * 9 | * Have you thought about this? 10 | * 11 | * Here are some good questions to ask before coding. Bonus points for you if 12 | * you have already thought through this! 13 | * 14 | * If the integer's last digit is 0, what should the output be? ie, cases such 15 | * as 10, 100. 16 | * 17 | * Did you notice that the reversed integer might overflow? Assume the input is 18 | * a 32-bit integer, then the reverse of 1000000003 overflows. How should you 19 | * handle such cases? 20 | * 21 | * For the purpose of this problem, assume that your function returns 0 when the 22 | * reversed integer overflows. 23 | */ 24 | 25 | /** 26 | * @param {number} x 27 | * @return {number} 28 | */ 29 | var reverse = module.exports = function (x) { 30 | var pn = x >= 0 ? '' : '-'; 31 | var num = Math.abs(x); 32 | var result = Number(pn + num.toString().split('').reverse().join('')); 33 | if (result > Math.pow(2, 31)) { 34 | return 0; 35 | } 36 | if (result < 1 - Math.pow(2, 31)) { 37 | return 0; 38 | } 39 | return result; 40 | }; 41 | -------------------------------------------------------------------------------- /problems/028-implement-strstr/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/implement-strstr/ 3 | * 4 | * Implement strStr(). 5 | * 6 | * Returns the index of the first occurrence of needle in haystack, 7 | * or -1 if needle is not part of haystack. 8 | */ 9 | 10 | /** 11 | * @param {string} haystack 12 | * @param {string} needle 13 | * @return {number} 14 | */ 15 | var strStr = module.exports = function (haystack, needle) { 16 | if (needle === '') return 0; 17 | var needleBacktrackPosition = generateNeedleBacktrackPosition(needle); 18 | var j = -1; 19 | for (var i = 0; i < haystack.length; i++) { 20 | while (j > -1 && needle[j + 1] !== haystack[i]) { 21 | j = needleBacktrackPosition[j]; 22 | } 23 | if (needle[j + 1] === haystack[i]) { 24 | j++; 25 | } 26 | if (j === needle.length - 1) return (i - needle.length + 1); 27 | } 28 | return -1; 29 | }; 30 | 31 | function generateNeedleBacktrackPosition(needle) { 32 | var result = [-1]; 33 | var j = -1; 34 | for (var i = 1; i < needle.length; i++) { 35 | while (j > -1 && needle[j + 1] !== needle[i]) { 36 | j = result[j]; 37 | } 38 | if (needle[j + 1] === needle[i]) { 39 | j++; 40 | } 41 | result[i] = j; 42 | } 43 | return result; 44 | } 45 | -------------------------------------------------------------------------------- /problems/016-3sum-closest/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/3sum-closest/ 3 | * 4 | * Given an array S of n integers, 5 | * find three integers in S such that the sum is closest to a given number, 6 | * target. Return the sum of the three integers. 7 | * You may assume that each input would have exactly one solution. 8 | * 9 | * For example, given array S = {-1 2 1 -4}, and target = 1. 10 | * 11 | * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 12 | */ 13 | 14 | /** 15 | * @param {number[]} nums 16 | * @param {number} target 17 | * @return {number} 18 | */ 19 | var threeSumClosest = module.exports = function (nums, target) { 20 | nums.sort(function (a, b) { return a - b; }); 21 | var numsLength = nums.length; 22 | var left; 23 | var right; 24 | var tempMinDiff = Infinity; 25 | var diff; 26 | for (var i = 0; i < numsLength - 2; i++) { 27 | left = i + 1; 28 | right = numsLength - 1; 29 | while (left < right) { 30 | diff = nums[i] + nums[left] + nums[right] - target; 31 | tempMinDiff = Math.abs(diff) < Math.abs(tempMinDiff) ? diff : tempMinDiff; 32 | if (diff === 0) { 33 | break; 34 | } else if (diff > 0) { 35 | right--; 36 | } else if (diff < 0) { 37 | left++; 38 | } 39 | } 40 | if (diff === 0) break; 41 | } 42 | return target + tempMinDiff; 43 | }; 44 | -------------------------------------------------------------------------------- /problems/017-letter-combinations-of-a-phone-number/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/letter-combinations-of-a-phone-number/ 3 | * 4 | * Given a digit string, return all possible letter combinations that the number 5 | * could represent. 6 | * 7 | * A mapping of digit to letters (just like on the telephone buttons) is given below. 8 | * 9 | * Input:Digit string "23" 10 | * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 11 | * 12 | * Note: 13 | * 14 | * Although the above answer is in lexicographical order, 15 | * your answer could be in any order you want. 16 | */ 17 | 18 | var digitMap = { 19 | 2: ['a', 'b', 'c'], 20 | 3: ['d', 'e', 'f'], 21 | 4: ['g', 'h', 'i'], 22 | 5: ['j', 'k', 'l'], 23 | 6: ['m', 'n', 'o'], 24 | 7: ['p', 'q', 'r', 's'], 25 | 8: ['t', 'u', 'v'], 26 | 9: ['w', 'x', 'y', 'z'], 27 | }; 28 | 29 | /** 30 | * @param {string} digits 31 | * @return {string[]} 32 | */ 33 | var letterCombinations = module.exports = function (digits) { 34 | if (digits.length === 0) return []; 35 | if (digits.length === 1) return digitMap[digits[0]]; 36 | var result = []; 37 | var restResult = letterCombinations(digits.slice(1)); 38 | digitMap[digits[0]].forEach(function (letter) { 39 | result = result.concat(restResult.map(function (item) { 40 | return letter + item; 41 | })); 42 | }); 43 | return result; 44 | }; 45 | -------------------------------------------------------------------------------- /problems/012-integer-to-roman/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/integer-to-roman/ 3 | * 4 | * Given an integer, convert it to a roman numeral. 5 | * 6 | * Input is guaranteed to be within the range from 1 to 3999. 7 | */ 8 | 9 | var roman = { 10 | 1: 'I', 11 | 5: 'V', 12 | 10: 'X', 13 | 50: 'L', 14 | 100: 'C', 15 | 500: 'D', 16 | 1000: 'M', 17 | }; 18 | 19 | /** 20 | * @param {number} num 21 | * @return {string} 22 | */ 23 | var intToRoman = module.exports = function (num) { 24 | var roman1000 = generateRoman(Math.floor(num / 1000), roman[1000]); 25 | var roman100 = generateRoman(Math.floor((num % 1000) / 100), roman[100], roman[500], roman[1000]); 26 | var roman10 = generateRoman(Math.floor((num % 100) / 10), roman[10], roman[50], roman[100]); 27 | var roman1 = generateRoman(Math.floor(num % 10), roman[1], roman[5], roman[10]); 28 | return roman1000 + roman100 + roman10 + roman1; 29 | }; 30 | 31 | function generateRoman(num, s1, s5, s10) { 32 | if (num === 0) return ''; 33 | if (num <= 3) return repeat(s1, num); 34 | if (num === 4) return s1 + s5; 35 | if (num === 5) return s5; 36 | if (num <= 8) return s5 + repeat(s1, num - 5); 37 | if (num === 9) return s1 + s10; 38 | return ''; 39 | } 40 | 41 | function repeat(str, count) { 42 | if ((count) === 0) return ''; 43 | var result = ''; 44 | for (var i = 0; i < count; i++) { 45 | result += str; 46 | } 47 | return result; 48 | } 49 | -------------------------------------------------------------------------------- /problems/024-swap-nodes-in-pairs/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/swap-nodes-in-pairs/ 3 | * 4 | * Given a linked list, swap every two adjacent nodes and return its head. 5 | * 6 | * For example, 7 | * 8 | * Given 1->2->3->4, you should return the list as 2->1->4->3. 9 | * 10 | * Your algorithm should use only constant space. 11 | * You may not modify the values in the list, only nodes itself can be changed. 12 | */ 13 | 14 | /** 15 | * You should comment the following function to pass the leetcode tests. 16 | * Definition for singly-linked list. 17 | */ 18 | var ListNode = require('../../structures/ListNode'); 19 | 20 | /** 21 | * Definition for singly-linked list. 22 | * function ListNode(val) { 23 | * this.val = val; 24 | * this.next = null; 25 | * } 26 | */ 27 | /** 28 | * @param {ListNode} head 29 | * @return {ListNode} 30 | */ 31 | var swapPairs = module.exports = function (head) { 32 | if (head === null) return null; 33 | if (head.next === null) return head; 34 | var result = head.next; 35 | var tempNode; 36 | var currentNode = head; 37 | var lastNode = null; 38 | while (currentNode !== null && currentNode.next !== null) { 39 | tempNode = currentNode.next; 40 | currentNode.next = currentNode.next.next; 41 | tempNode.next = currentNode; 42 | if (lastNode !== null) { 43 | lastNode.next = tempNode; 44 | } 45 | lastNode = currentNode; 46 | currentNode = currentNode.next; 47 | } 48 | return result; 49 | }; 50 | -------------------------------------------------------------------------------- /problems/322-coin-change/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/coin-change/ 3 | * 4 | * You are given coins of different denominations and a total amount of money amount. 5 | * Write a function to compute the fewest number of coins that you need to make up that amount. 6 | * If that amount of money cannot be made up by any combination of the coins, return -1. 7 | * 8 | * Example 1: 9 | * coins = [1, 2, 5], amount = 11 10 | * return 3 (11 = 5 + 5 + 1) 11 | * 12 | * Example 2: 13 | * coins = [2], amount = 3 14 | * return -1. 15 | * 16 | * Note: 17 | * You may assume that you have an infinite number of each kind of coin. 18 | */ 19 | 20 | /** 21 | * @param {number[]} coins 22 | * @param {number} amount 23 | * @return {number} 24 | */ 25 | var coinChange = module.exports = function (coins, amount) { 26 | if (coins.length === 0) return -1; 27 | if (amount === 0) return 0; 28 | coins.sort(function (a, b) { return a - b; }); 29 | var dp = []; 30 | var i; 31 | var j; 32 | for (i = 0; i <= coins.length; i++) { 33 | dp[coins[i]] = 1; 34 | } 35 | for (i = coins[0] + 1; i <= amount; i++) { 36 | for (j = coins.length - 1; j >= 0; j--) { 37 | if (dp[i - coins[j]] > 0) { 38 | if (typeof dp[i] === 'undefined') { 39 | dp[i] = dp[i - coins[j]] + 1; 40 | } else { 41 | dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1); 42 | } 43 | } 44 | } 45 | } 46 | if (typeof dp[amount] === 'undefined') return -1; 47 | return dp[amount]; 48 | }; 49 | -------------------------------------------------------------------------------- /problems/124-binary-tree-maximum-path-sum/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/binary-tree-maximum-path-sum/ 3 | * 4 | * Given a binary tree, find the maximum path sum. 5 | * 6 | * For this problem, 7 | * a path is defined as any sequence of nodes from some starting node to any 8 | * node in the tree along the parent-child connections. 9 | * The path does not need to go through the root. 10 | * 11 | * For example: 12 | * Given the below binary tree, 13 | * 14 | * 1 15 | * / \ 16 | * 2 3 17 | * Return 6. 18 | */ 19 | 20 | var TreeNode = require('../../structures/TreeNode'); 21 | 22 | /** 23 | * Definition for a binary tree node. 24 | * function TreeNode(val) { 25 | * this.val = val; 26 | * this.left = this.right = null; 27 | * } 28 | */ 29 | 30 | /** 31 | * @param {TreeNode} root 32 | * @return {number} 33 | */ 34 | var maxPathSum = module.exports = function (root) { 35 | if (root === null) return 0; 36 | return sub(root).max; 37 | function sub(r) { 38 | if (r === null) { 39 | return { 40 | max: -Infinity, 41 | childMax: -Infinity, 42 | }; 43 | } 44 | var leftSub = sub(r.left); 45 | var rightSub = sub(r.right); 46 | return { 47 | max: Math.max( 48 | leftSub.max, 49 | rightSub.max, 50 | leftSub.childMax + rightSub.childMax + r.val, 51 | leftSub.childMax + r.val, 52 | rightSub.childMax + r.val, 53 | r.val 54 | ), 55 | childMax: Math.max(leftSub.childMax, rightSub.childMax, 0) + r.val, 56 | }; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /problems/010-regular-expression-matching/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/regular-expression-matching/ 3 | * 4 | * Implement regular expression matching with support for '.' and '*'. 5 | * 6 | * '.' Matches any single character. 7 | * '*' Matches zero or more of the preceding element. 8 | * 9 | * The matching should cover the entire input string (not partial). 10 | * 11 | * The function prototype should be: 12 | * bool isMatch(const char *s, const char *p) 13 | * 14 | * Some examples: 15 | * isMatch("aa","a") → false 16 | * isMatch("aa","aa") → true 17 | * isMatch("aaa","aa") → false 18 | * isMatch("aa", "a*") → true 19 | * isMatch("aa", ".*") → true 20 | * isMatch("ab", ".*") → true 21 | * isMatch("aab", "c*a*b") → true 22 | */ 23 | 24 | /** 25 | * @param {string} s 26 | * @param {string} p 27 | * @return {boolean} 28 | */ 29 | var isMatch = module.exports = function (s, p) { 30 | var sLength = s.length; 31 | var pLength = p.length; 32 | if (pLength === 0) return sLength === 0; 33 | if (pLength === 1) { 34 | if (sLength !== 1) return false; 35 | if (p === '.') return true; 36 | return s === p; 37 | } 38 | if (p[1] !== '*') { 39 | if (sLength === 0) return false; 40 | if (s[0] !== p[0] && p[0] !== '.') return false; 41 | return isMatch(s.slice(1), p.slice(1)); 42 | } 43 | if (isMatch(s, p.slice(2))) return true; 44 | for (var i = 0; i < sLength; i++) { 45 | if (s[i] !== p[0] && p[0] !== '.') return false; 46 | if (isMatch(s.slice(i + 1), p.slice(2))) return true; 47 | } 48 | return false; 49 | }; 50 | -------------------------------------------------------------------------------- /problems/004-median-of-two-sorted-arrays/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/median-of-two-sorted-arrays/ 3 | * 4 | * There are two sorted arrays nums1 and nums2 of size m and n respectively. 5 | * Find the median of the two sorted arrays. 6 | * The overall run time complexity should be O(log (m+n)). 7 | */ 8 | 9 | /** 10 | * @param {number[]} nums1 11 | * @param {number[]} nums2 12 | * @return {number} 13 | */ 14 | var findMedianSortedArrays = module.exports = function (nums1, nums2) { 15 | return findMedian(merge(nums1, nums2)); 16 | }; 17 | 18 | function merge(nums1, nums2) { 19 | var i = 0; 20 | var j = 0; 21 | var result = []; 22 | var nums1Length = nums1.length; 23 | var nums2Length = nums2.length; 24 | if (nums1Length === 0) { 25 | return nums2; 26 | } 27 | if (nums2Length === 0) { 28 | return nums1; 29 | } 30 | while (i !== nums1Length && j !== nums2Length) { 31 | if (nums1[i] < nums2[j]) { 32 | result.push(nums1[i]); 33 | i = i + 1; 34 | } else { 35 | result.push(nums2[j]); 36 | j = j + 1; 37 | } 38 | } 39 | if (i === nums1Length) { 40 | result = result.concat(nums2.slice(j)); 41 | } else if (j === nums2Length) { 42 | result = result.concat(nums1.slice(i)); 43 | } 44 | return result; 45 | } 46 | 47 | function findMedian(array) { 48 | var arrayLength = array.length; 49 | var medianIndex = (arrayLength - 1) / 2; 50 | var floor = Math.floor(medianIndex); 51 | if (floor === medianIndex) { 52 | return array[medianIndex]; 53 | } 54 | return (array[floor] + array[floor + 1]) / 2; 55 | } 56 | -------------------------------------------------------------------------------- /problems/009-palindrome-number/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/palindrome-number/ 3 | * 4 | * Determine whether an integer is a palindrome. Do this without extra space. 5 | * 6 | * Some hints: 7 | * 8 | * Could negative integers be palindromes? (ie, -1) 9 | * 10 | * If you are thinking of converting the integer to string, 11 | * note the restriction of using extra space. 12 | * 13 | * You could also try reversing an integer. 14 | * However, if you have solved the problem "Reverse Integer", 15 | * you know that the reversed integer might overflow. 16 | * How would you handle such case? 17 | * 18 | * There is a more generic way of solving this problem. 19 | */ 20 | 21 | /** 22 | * @param {number} x 23 | * @return {boolean} 24 | */ 25 | var isPalindrome = module.exports = function (x) { 26 | if (x < 0) return false; 27 | if (x < 10) return true; 28 | // get the length of the number 29 | var numLength = Math.floor(Math.log10(x)) + 1; 30 | // compare halfNumLength times 31 | var halfNumLength = Math.floor(numLength / 2); 32 | var highDigital; 33 | var lowDigital; 34 | for (var i = 0; i < halfNumLength; i++) { 35 | // get the low ist digital 36 | // TODO Math.pow runs too many times, it can be optimized 37 | lowDigital = (Math.floor(x / Math.pow(10, i))) % 10; 38 | // get the high ist digital 39 | highDigital = Math.floor((x % Math.pow(10, numLength - i)) / Math.pow(10, numLength - i - 1)); 40 | // if they are equal, them x is not a palindrome number 41 | if (lowDigital !== highDigital) { 42 | return false; 43 | } 44 | } 45 | return true; 46 | }; 47 | -------------------------------------------------------------------------------- /problems/029-divide-two-integers/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/divide-two-integers/ 3 | * 4 | * Divide two integers without using multiplication, division and mod operator. 5 | * 6 | * If it is overflow, return MAX_INT. 7 | */ 8 | 9 | var MAX_INT = 2147483647; 10 | var MIN_INT = -2147483648; 11 | 12 | /** 13 | * @param {number} dividend 14 | * @param {number} divisor 15 | * @return {number} 16 | */ 17 | var divide = module.exports = function (dividend, divisor) { 18 | if (dividend === 0 || divisor === 0) return 0; 19 | var sign = (dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0); 20 | var absDividend = Math.abs(dividend); 21 | var absDivisor = Math.abs(divisor); 22 | var result = 1; 23 | var current = absDivisor; 24 | var tempResult = 1; 25 | var tempCurrent = absDivisor; 26 | while (current <= absDividend) { 27 | if (current + tempCurrent > absDividend) { 28 | tempResult = 1; 29 | tempCurrent = absDivisor; 30 | result += tempResult; 31 | current += tempCurrent; 32 | } else { 33 | result += tempResult; 34 | current += tempCurrent; 35 | tempResult += tempResult; 36 | tempCurrent += tempCurrent; 37 | } 38 | // console.log('tempResult ', tempResult); 39 | // console.log('tempCurrent', tempCurrent); 40 | // console.log('result', result); 41 | // console.log('current ', current); 42 | // console.log(''); 43 | } 44 | if (sign) { 45 | result = result - 1; 46 | } else { 47 | result = 1 - result; 48 | } 49 | if (result > MAX_INT || result < MIN_INT) return MAX_INT; 50 | return result; 51 | }; 52 | -------------------------------------------------------------------------------- /problems/048-rotate-image/index.js: -------------------------------------------------------------------------------- 1 | /* eslint no-param-reassign:0 */ 2 | 3 | /** 4 | * https://leetcode.com/problems/rotate-image/ 5 | * 6 | * You are given an n x n 2D matrix representing an image. 7 | * 8 | * Rotate the image by 90 degrees (clockwise). 9 | * 10 | * Follow up: 11 | * Could you do this in-place? 12 | */ 13 | 14 | /** 15 | * @param {number[][]} matrix 16 | * @return {void} Do not return anything, modify matrix in-place instead. 17 | */ 18 | var rotate = module.exports = function (matrix) { 19 | if (!Array.isArray(matrix)) return; 20 | var matrixLength = matrix.length; 21 | if (matrixLength <= 1) return; 22 | var i; 23 | var j; 24 | var halfMatrixLength = Math.floor(matrixLength / 2); 25 | var temp; 26 | for (i = 0; i < halfMatrixLength; i++) { 27 | for (j = 0; j < halfMatrixLength; j++) { 28 | temp = matrix[i][j]; 29 | matrix[i][j] = matrix[matrixLength - j - 1][i]; 30 | matrix[matrixLength - j - 1][i] = matrix[matrixLength - i - 1][matrixLength - j - 1]; 31 | matrix[matrixLength - i - 1][matrixLength - j - 1] = matrix[j][matrixLength - i - 1]; 32 | matrix[j][matrixLength - i - 1] = temp; 33 | } 34 | } 35 | console.log(matrix); 36 | if (matrix.length % 2 === 0) return; 37 | j = halfMatrixLength; 38 | for (i = 0; i < halfMatrixLength; i++) { 39 | temp = matrix[i][j]; 40 | matrix[i][j] = matrix[matrixLength - j - 1][i]; 41 | matrix[matrixLength - j - 1][i] = matrix[matrixLength - i - 1][matrixLength - j - 1]; 42 | matrix[matrixLength - i - 1][matrixLength - j - 1] = matrix[j][matrixLength - i - 1]; 43 | matrix[j][matrixLength - i - 1] = temp; 44 | } 45 | return; 46 | }; 47 | -------------------------------------------------------------------------------- /problems/018-4sum/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/4sum/ 3 | * 4 | * Given an array S of n integers, are there elements a, b, c, 5 | * and d in S such that a + b + c + d = target? 6 | * Find all unique quadruplets in the array which gives the sum of target. 7 | * 8 | * Note: 9 | * 10 | * - Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d) 11 | * - The solution set must not contain duplicate quadruplets. 12 | * 13 | * For example, given array S = {1 0 -1 0 -2 2}, and target = 0. 14 | * 15 | * A solution set is: 16 | * (-1, 0, 0, 1) 17 | * (-2, -1, 1, 2) 18 | * (-2, 0, 0, 2) 19 | */ 20 | 21 | /** 22 | * @param {number[]} nums 23 | * @param {number} target 24 | * @return {number[][]} 25 | */ 26 | var fourSum = module.exports = function (nums, target) { 27 | nums.sort(function (a, b) { return a - b; }); 28 | var left; 29 | var right; 30 | var tempSum; 31 | var result = []; 32 | var existsHash = {}; 33 | var tempArr; 34 | for (var i = 0; i < nums.length - 3; i++) { 35 | for (var j = i + 1; j < nums.length - 2; j++) { 36 | left = j + 1; 37 | right = nums.length - 1; 38 | while (left < right) { 39 | tempSum = nums[i] + nums[j] + nums[left] + nums[right]; 40 | if (tempSum > target) { 41 | right--; 42 | } else if (tempSum < target) { 43 | left++; 44 | } else { 45 | tempArr = [nums[i], nums[j], nums[left], nums[right]]; 46 | if (!existsHash[tempArr]) { 47 | existsHash[tempArr] = true; 48 | result.push(tempArr); 49 | } 50 | left++; 51 | right--; 52 | } 53 | } 54 | } 55 | } 56 | return result; 57 | }; 58 | -------------------------------------------------------------------------------- /problems/006-zigzag-conversion/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/zigzag-conversion/ 3 | * 4 | * The string `"PAYPALISHIRING"` is written in a zigzag pattern on a given number 5 | * of rows like this: (you may want to display this pattern in a fixed font for 6 | * better legibility) 7 | * 8 | * ``` 9 | * P A H N 10 | * A P L S I I G 11 | * Y I R 12 | * ``` 13 | * 14 | * And then read line by line: `"PAHNAPLSIIGYIR"` 15 | * 16 | * Write the code that will take a string and make this conversion given a 17 | * number of rows: 18 | * 19 | * ``` 20 | * string convert(string text, int nRows); 21 | * ``` 22 | * 23 | * `convert("PAYPALISHIRING", 3)` should return `"PAHNAPLSIIGYIR"`. 24 | */ 25 | 26 | /** 27 | * @param {string} s 28 | * @param {number} numRows 29 | * @return {string} 30 | */ 31 | var convert = module.exports = function (s, numRows) { 32 | if (s.length <= 2) return s; 33 | if (numRows === 1) return s; 34 | var sMatrix = []; 35 | var i; 36 | for (i = 0; i < numRows; i++) { 37 | sMatrix[i] = []; 38 | } 39 | var sLength = s.length; 40 | i = 0; 41 | var j = 0; 42 | // downward 43 | var downward = true; 44 | for (var k = 0; k < sLength; k++) { 45 | sMatrix[i][j] = s[k]; 46 | if (downward) { 47 | i++; 48 | // touched bottom 49 | if (i === numRows - 1) { 50 | downward = false; 51 | } 52 | } else { 53 | i--; 54 | j++; 55 | // touched top 56 | if (i === 0) { 57 | downward = true; 58 | } 59 | } 60 | } 61 | var result = sMatrix.map(function (row) { 62 | return row.filter(function (item) { 63 | return !!item; 64 | }).join(''); 65 | }).join(''); 66 | return result; 67 | }; 68 | -------------------------------------------------------------------------------- /problems/278-first-bad-version/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/first-bad-version/ 3 | * 4 | * You are a product manager and currently leading a team to develop a new product. 5 | * Unfortunately, the latest version of your product fails the quality check. 6 | * Since each version is developed based on the previous version, 7 | * all the versions after a bad version are also bad. 8 | * 9 | * Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, 10 | * which causes all the following ones to be bad. 11 | * 12 | * You are given an API bool isBadVersion(version) which will return whether version is bad. 13 | * Implement a function to find the first bad version. 14 | * You should minimize the number of calls to the API. 15 | * 16 | * Credits: 17 | * Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 18 | */ 19 | 20 | /** 21 | * Definition for isBadVersion() 22 | * 23 | * @param {integer} version number 24 | * @return {boolean} whether the version is bad 25 | * isBadVersion = function(version) { 26 | * ... 27 | * }; 28 | */ 29 | 30 | /** 31 | * @param {function} isBadVersion() 32 | * @return {function} 33 | */ 34 | var solution = module.exports = function (isBadVersion) { 35 | /** 36 | * @param {integer} n Total versions 37 | * @return {integer} The first bad version 38 | */ 39 | return function (n) { 40 | var min = 1; 41 | var max = n; 42 | var mid = Math.floor((min + max) / 2); 43 | while (max > min) { 44 | if (isBadVersion(mid)) { 45 | max = mid; 46 | } else { 47 | min = mid + 1; 48 | } 49 | mid = Math.floor((min + max) / 2); 50 | } 51 | return mid; 52 | }; 53 | }; 54 | -------------------------------------------------------------------------------- /problems/021-merge-two-sorted-lists/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/merge-two-sorted-lists/ 3 | * 4 | * Merge two sorted linked lists and return it as a new list. 5 | * The new list should be made by splicing together the nodes of the first two 6 | * lists. 7 | */ 8 | 9 | /** 10 | * You should comment the following function to pass the leetcode tests. 11 | * Definition for singly-linked list. 12 | */ 13 | var ListNode = require('../../structures/ListNode'); 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * function ListNode(val) { 18 | * this.val = val; 19 | * this.next = null; 20 | * } 21 | */ 22 | /** 23 | * @param {ListNode} l1 24 | * @param {ListNode} l2 25 | * @return {ListNode} 26 | */ 27 | var mergeTwoLists = module.exports = function (l1, l2) { 28 | if (l1 === null) return l2; 29 | if (l2 === null) return l1; 30 | var l1Node = l1; 31 | var l2Node = l2; 32 | var firstNode = null; 33 | var lastNode = null; 34 | var tempNode; 35 | while (l1Node !== null && l2Node !== null) { 36 | if (l1Node.val < l2Node.val) { 37 | tempNode = new ListNode(l1Node.val); 38 | if (firstNode === null) { 39 | firstNode = lastNode = tempNode; 40 | } else { 41 | lastNode.next = tempNode; 42 | lastNode = tempNode; 43 | } 44 | l1Node = l1Node.next; 45 | } else { 46 | tempNode = new ListNode(l2Node.val); 47 | if (firstNode === null) { 48 | firstNode = lastNode = tempNode; 49 | } else { 50 | lastNode.next = tempNode; 51 | lastNode = tempNode; 52 | } 53 | l2Node = l2Node.next; 54 | } 55 | } 56 | if (l1Node !== null) { 57 | lastNode.next = l1Node; 58 | } 59 | if (l2Node !== null) { 60 | lastNode.next = l2Node; 61 | } 62 | return firstNode; 63 | }; 64 | -------------------------------------------------------------------------------- /problems/002-add-two-numbers/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/add-two-numbers/ 3 | * 4 | * You are given two linked lists representing two non-negative numbers. 5 | * The digits are stored in reverse order and each of their nodes contain a 6 | * single digit. 7 | * Add the two numbers and return it as a linked list. 8 | * 9 | * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 10 | * Output: 7 -> 0 -> 8 11 | */ 12 | 13 | /** 14 | * You should comment the following function to pass the leetcode tests. 15 | * Definition for singly-linked list. 16 | */ 17 | var ListNode = require('../../structures/ListNode'); 18 | 19 | /** 20 | * Definition for singly-linked list. 21 | * function ListNode(val) { 22 | * this.val = val; 23 | * this.next = null; 24 | * } 25 | */ 26 | /** 27 | * @param {ListNode} l1 28 | * @param {ListNode} l2 29 | * @return {ListNode} 30 | */ 31 | var addTwoNumbers = module.exports = function (listA, listB) { 32 | var tmpA = listA; 33 | var tmpB = listB; 34 | var result; 35 | var tmpNode; 36 | var sum; 37 | /** 38 | * A carry is a digit that is transferred from one column of digits to 39 | * another column of more significant digits. 40 | */ 41 | var carry; 42 | carry = 0; 43 | while (tmpA !== null || tmpB !== null) { 44 | sum = (tmpA === null ? 0 : tmpA.val) + (tmpB === null ? 0 : tmpB.val) + carry; 45 | if (!tmpNode) { 46 | tmpNode = result = new ListNode(sum % 10); 47 | } else { 48 | tmpNode.next = new ListNode(sum % 10); 49 | tmpNode = tmpNode.next; 50 | } 51 | carry = sum > 9 ? 1 : 0; 52 | if (tmpA !== null) { 53 | tmpA = tmpA.next; 54 | } 55 | if (tmpB !== null) { 56 | tmpB = tmpB.next; 57 | } 58 | } 59 | if (carry === 1) { 60 | tmpNode.next = new ListNode(1); 61 | } 62 | return result; 63 | }; 64 | -------------------------------------------------------------------------------- /problems/001-two-sum/index.js: -------------------------------------------------------------------------------- 1 | /* eslint no-param-reassign:0 */ 2 | 3 | /** 4 | * https://leetcode.com/problems/two-sum/ 5 | * 6 | * Given an array of integers, find two numbers such that they add up to a 7 | * specific target number. 8 | * 9 | * The function twoSum should return indices of the two numbers such that they 10 | * add up to the target, where index1 must be less than index2. 11 | * Please note that your returned answers (both index1 and index2) are not 12 | * zero-based. 13 | * 14 | * You may assume that each input would have exactly one solution. 15 | * 16 | * Input: numbers={2, 7, 11, 15}, target=9 17 | * Output: index1=1, index2=2 18 | */ 19 | 20 | /** 21 | * @param {number[]} nums 22 | * @param {number} target 23 | * @return {number[]} 24 | */ 25 | var twoSum = module.exports = function (nums, target) { 26 | // Use a hash to store value-to-index pairs 27 | var hash = nums.reduce(function (prev, item, index) { 28 | if (prev[item] === undefined) { 29 | prev[item] = index; 30 | return prev; 31 | } 32 | /** 33 | * Maybe there are two same numbers, for example: 34 | * Input: numbers={2, 5, 5, 7}, target = 10 35 | * Output: index1=1, index2=2 36 | * So we save the index array 37 | */ 38 | prev[item] = [prev[item], index]; 39 | return prev; 40 | }, {}); 41 | var i; 42 | // Loop over hash 43 | for (i in hash) { 44 | // If hash[i] is an array, then check if i * 2 equals to target 45 | if (hash[i] instanceof Array && i * 2 === target) { 46 | return [hash[i][0] + 1, hash[i][1] + 1].sort(function (a, b) { 47 | return a - b; 48 | }); 49 | // Check if hash[target - 1] is undefined, only take O(1) time complexity 50 | } else if (hash[target - i] !== undefined) { 51 | return [hash[i] + 1, hash[target - i] + 1].sort(function (a, b) { 52 | return a - b; 53 | }); 54 | } 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /problems/304-range-sum-query-2d-immutable/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/range-sum-query-2d-immutable/ 3 | * 4 | * Given a 2D matrix matrix, 5 | * find the sum of the elements inside the rectangle defined by its upper left 6 | * corner (row1, col1) and lower right corner (row2, col2). 7 | * 8 | * Example: 9 | * Given matrix = [ 10 | * [3, 0, 1, 4, 2], 11 | * [5, 6, 3, 2, 1], 12 | * [1, 2, 0, 1, 5], 13 | * [4, 1, 0, 1, 7], 14 | * [1, 0, 3, 0, 5] 15 | * ] 16 | * 17 | * sumRegion(2, 1, 4, 3) -> 8 18 | * sumRegion(1, 1, 2, 2) -> 11 19 | * sumRegion(1, 2, 2, 4) -> 12 20 | * 21 | * Note: 22 | * 23 | * 1. You may assume that the matrix does not change. 24 | * 2. There are many calls to sumRegion function. 25 | * 3. You may assume that row1 ≤ row2 and col1 ≤ col2. 26 | */ 27 | 28 | /** 29 | * @constructor 30 | * @param {number[][]} matrix 31 | */ 32 | var NumMatrix = module.exports = function (matrix) { 33 | if (matrix.length === 0 || matrix[0].length === 0) return; 34 | this.dp = []; 35 | var i; 36 | var j; 37 | for (i = 0; i < matrix.length + 1; i++) { 38 | this.dp[i] = [0]; 39 | } 40 | for (j = 1; j < matrix[0].length + 1; j++) { 41 | this.dp[0][j] = 0; 42 | } 43 | for (i = 0; i < matrix.length; i++) { 44 | for (j = 0; j < matrix[0].length; j++) { 45 | this.dp[i + 1][j + 1] = 46 | this.dp[i][j + 1] + this.dp[i + 1][j] - 47 | this.dp[i][j] + matrix[i][j]; 48 | } 49 | } 50 | }; 51 | 52 | /** 53 | * @param {number} row1 54 | * @param {number} col1 55 | * @param {number} row2 56 | * @param {number} col2 57 | * @return {number} 58 | */ 59 | NumMatrix.prototype.sumRegion = function (row1, col1, row2, col2) { 60 | return this.dp[row2 + 1][col2 + 1] - this.dp[row2 + 1][col1] - 61 | this.dp[row1][col2 + 1] + this.dp[row1][col1]; 62 | }; 63 | 64 | 65 | /** 66 | * Your NumMatrix object will be instantiated and called as such: 67 | * var numMatrix = new NumMatrix(matrix); 68 | * numMatrix.sumRegion(0, 1, 2, 3); 69 | * numMatrix.sumRegion(1, 2, 3, 4); 70 | */ 71 | -------------------------------------------------------------------------------- /problems/011-container-with-most-water/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/container-with-most-water/ 3 | * 4 | * Given n non-negative integers a1, a2, ..., an, 5 | * where each represents a point at coordinate (i, ai). 6 | * n vertical lines are drawn such that the two endpoints of line i is 7 | * at (i, ai) and (i, 0). 8 | * Find two lines, which together with x-axis forms a container, 9 | * such that the container contains the most water. 10 | * 11 | * Note: You may not slant the container. 12 | */ 13 | 14 | /** 15 | * @param {number[]} height 16 | * @return {number} 17 | */ 18 | var maxArea = module.exports = function (height) { 19 | var heightLength = height.length; 20 | if (heightLength < 2) return 0; 21 | var maxHeight = -1; 22 | var ltr = []; 23 | var rtl = []; 24 | var i; 25 | var j; 26 | for (i = 0; i < heightLength; i++) { 27 | if (height[i] > maxHeight) { 28 | maxHeight = height[i]; 29 | ltr.push({ 30 | x: i, 31 | height: maxHeight, 32 | }); 33 | } 34 | } 35 | maxHeight = -1; 36 | for (i = heightLength - 1; i >= 0; i--) { 37 | if (height[i] > maxHeight) { 38 | maxHeight = height[i]; 39 | rtl.push({ 40 | x: i, 41 | height: maxHeight, 42 | }); 43 | } 44 | } 45 | var ltrLength = ltr.length; 46 | var rtlLength = rtl.length; 47 | var canBreak = false; 48 | i = 0; 49 | j = 0; 50 | var result = 0; 51 | while (i < ltrLength) { 52 | while (j < rtlLength - 1 && rtl[j].height < ltr[i].height) { 53 | j++; 54 | } 55 | result = Math.max(result, calculate(i, j)); 56 | j = 0; 57 | i++; 58 | } 59 | i = 0; 60 | j = 0; 61 | while (j < rtlLength) { 62 | while (i < ltrLength - 1 && ltr[i].height < rtl[j].height) { 63 | i++; 64 | } 65 | result = Math.max(result, calculate(i, j)); 66 | i = 0; 67 | j++; 68 | } 69 | 70 | return result; 71 | 72 | function calculate(ltrIndex, rtlIndex) { 73 | return Math.abs(ltr[ltrIndex].x - rtl[rtlIndex].x) 74 | * Math.min(ltr[ltrIndex].height, rtl[rtlIndex].height); 75 | } 76 | }; 77 | -------------------------------------------------------------------------------- /problems/023-merge-k-sorted-lists/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/merge-k-sorted-lists/ 3 | * 4 | * Merge k sorted linked lists and return it as one sorted list. 5 | * Analyze and describe its complexity. 6 | */ 7 | 8 | /** 9 | * You should comment the following function to pass the leetcode tests. 10 | * Definition for singly-linked list. 11 | */ 12 | var ListNode = require('../../structures/ListNode'); 13 | 14 | /** 15 | * Definition for singly-linked list. 16 | * function ListNode(val) { 17 | * this.val = val; 18 | * this.next = null; 19 | * } 20 | */ 21 | /** 22 | * @param {ListNode[]} lists 23 | * @return {ListNode} 24 | */ 25 | var mergeKLists = module.exports = function (lists) { 26 | if (lists.length === 0) return null; 27 | if (lists.length === 1) return lists[0]; 28 | if (lists.length === 2) return mergeTwoLists(lists[0], lists[1]); 29 | var middle = Math.floor(lists.length / 2); 30 | return mergeTwoLists(mergeKLists(lists.slice(0, middle)), mergeKLists(lists.slice(middle))); 31 | }; 32 | 33 | /** 34 | * @param {ListNode} l1 35 | * @param {ListNode} l2 36 | * @return {ListNode} 37 | */ 38 | var mergeTwoLists = function (l1, l2) { 39 | // console.log(l1, l2); 40 | if (l1 === null) return l2; 41 | if (l2 === null) return l1; 42 | var l1Node = l1; 43 | var l2Node = l2; 44 | var firstNode = null; 45 | var lastNode = null; 46 | var tempNode; 47 | while (l1Node !== null && l2Node !== null) { 48 | if (l1Node.val < l2Node.val) { 49 | tempNode = new ListNode(l1Node.val); 50 | if (firstNode === null) { 51 | firstNode = lastNode = tempNode; 52 | } else { 53 | lastNode.next = tempNode; 54 | lastNode = tempNode; 55 | } 56 | l1Node = l1Node.next; 57 | } else { 58 | tempNode = new ListNode(l2Node.val); 59 | if (firstNode === null) { 60 | firstNode = lastNode = tempNode; 61 | } else { 62 | lastNode.next = tempNode; 63 | lastNode = tempNode; 64 | } 65 | l2Node = l2Node.next; 66 | } 67 | } 68 | if (l1Node !== null) { 69 | lastNode.next = l1Node; 70 | } 71 | if (l2Node !== null) { 72 | lastNode.next = l2Node; 73 | } 74 | return firstNode; 75 | }; 76 | -------------------------------------------------------------------------------- /problems/025-reverse-nodes-in-k-group/index.js: -------------------------------------------------------------------------------- 1 | /* eslint no-constant-condition:0 */ 2 | 3 | /** 4 | * https://leetcode.com/problems/reverse-nodes-in-k-group/ 5 | * 6 | * Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 7 | * 8 | * If the number of nodes is not a multiple of k then left-out nodes in the end 9 | * should remain as it is. 10 | * 11 | * You may not alter the values in the nodes, only nodes itself may be changed. 12 | * 13 | * Only constant memory is allowed. 14 | * 15 | * For example, 16 | * 17 | * Given this linked list: 1->2->3->4->5 18 | * 19 | * For k = 2, you should return: 2->1->4->3->5 20 | * 21 | * For k = 3, you should return: 3->2->1->4->5 22 | */ 23 | 24 | /** 25 | * You should comment the following function to pass the leetcode tests. 26 | * Definition for singly-linked list. 27 | */ 28 | var ListNode = require('../../structures/ListNode'); 29 | 30 | /** 31 | * Definition for singly-linked list. 32 | * function ListNode(val) { 33 | * this.val = val; 34 | * this.next = null; 35 | * } 36 | */ 37 | /** 38 | * @param {ListNode} head 39 | * @param {number} k 40 | * @return {ListNode} 41 | */ 42 | var reverseKGroup = module.exports = function (head, k) { 43 | if (k === 0) return head; 44 | if (k === 1) return head; 45 | var kMinusOneNext = getKNext(head, k - 1); 46 | if (kMinusOneNext === null) return head; 47 | var result = kMinusOneNext; 48 | 49 | var currentNode = head; 50 | var k2; 51 | var kNext; 52 | while (true) { 53 | kMinusOneNext = getKNext(currentNode, k - 1); 54 | if (kMinusOneNext === null) break; 55 | k2 = getKNext(currentNode, 2 * k - 1); 56 | kNext = getKNext(currentNode, k); 57 | reverseNodes(currentNode, k - 1); 58 | if (k2 === null) { 59 | currentNode.next = kNext; 60 | } else { 61 | currentNode.next = k2; 62 | } 63 | currentNode = kNext; 64 | } 65 | return result; 66 | }; 67 | 68 | function getKNext(head, k) { 69 | if (k === 0) return head; 70 | var tempNode = head; 71 | for (var i = 0; i < k; i++) { 72 | if (tempNode === null) return null; 73 | tempNode = tempNode.next; 74 | } 75 | return tempNode; 76 | } 77 | 78 | function reverseNodes(head, k) { 79 | var tempNode1 = head; 80 | var tempNode2 = head.next; 81 | var tempNode3; 82 | for (var i = 0; i < k; i++) { 83 | tempNode3 = tempNode2.next; 84 | tempNode2.next = tempNode1; 85 | tempNode1 = tempNode2; 86 | tempNode2 = tempNode3; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /problems/015-3sum/index.js: -------------------------------------------------------------------------------- 1 | /* eslint no-param-reassign:0 */ 2 | 3 | /** 4 | * https://leetcode.com/problems/3sum/ 5 | * 6 | * Given an array S of n integers, are there elements a, b, c in S such that 7 | * a + b + c = 0? 8 | * Find all unique triplets in the array which gives the sum of zero. 9 | * 10 | * Note: 11 | * 12 | * - Elements in a triplet (a,b,c) must be in non-descending order. 13 | * (ie, a ≤ b ≤ c) 14 | * - The solution set must not contain duplicate triplets. 15 | * 16 | * For example, given array S = {-1 0 1 2 -1 -4}, 17 | * 18 | * A solution set is: 19 | * (-1, 0, 1) 20 | * (-1, -1, 2) 21 | */ 22 | 23 | /** 24 | * @param {number[]} nums 25 | * @return {number[][]} 26 | */ 27 | var threeSum = module.exports = function (nums) { 28 | // Use a hash to store value-to-count pairs 29 | var hash = nums.reduce(function (prev, item, index) { 30 | if (prev[item] === undefined) { 31 | prev[item] = 1; 32 | return prev; 33 | } 34 | prev[item]++; 35 | return prev; 36 | }, {}); 37 | 38 | var result = []; 39 | Object.keys(hash).forEach(function (key) { 40 | var numberKey = Number(key); 41 | result = result.concat(twoSum(-numberKey).map(function (twoNumArray) { 42 | twoNumArray.push(numberKey); 43 | return twoNumArray.sort(function (a, b) { 44 | return (a - b); 45 | }); 46 | })); 47 | }); 48 | 49 | // remove duplicate 50 | var duplicateHash = {}; 51 | result = result.filter(function (threeNumArray) { 52 | var threeNumArrayString = threeNumArray.toString(); 53 | if (duplicateHash[threeNumArrayString]) return false; 54 | duplicateHash[threeNumArrayString] = true; 55 | return true; 56 | }); 57 | return result; 58 | 59 | function twoSum(target) { 60 | var twoSumResult = []; 61 | hash[-target]--; 62 | // console.log(hash); 63 | Object.keys(hash).forEach(function (key) { 64 | var numberKey = Number(key); 65 | var count = hash[numberKey]; 66 | // console.log(numberKey, target, count); 67 | if (count === 0) return; 68 | if (numberKey * 2 === target) { 69 | if (count >= 2) { 70 | twoSumResult.push([numberKey, numberKey]); 71 | } 72 | // undefined or 0 73 | } else if (hash[target - numberKey]) { 74 | if (target === 0 && count < 2) return; 75 | twoSumResult.push([numberKey, target - numberKey]); 76 | } 77 | // console.log(twoSumResult); 78 | }); 79 | hash[-target]++; 80 | // console.log(twoSumResult); 81 | return twoSumResult; 82 | } 83 | }; 84 | -------------------------------------------------------------------------------- /problems/297-serialize-and-deserialize-binary-tree/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ 3 | * 4 | * Serialization is the process of converting a data structure or object into a 5 | * sequence of bits so that it can be stored in a file or memory buffer, 6 | * or transmitted across a network connection link to be reconstructed later in 7 | * the same or another computer environment. 8 | * 9 | * Design an algorithm to serialize and deserialize a binary tree. 10 | * There is no restriction on how your serialization/deserialization algorithm 11 | * should work. 12 | * You just need to ensure that a binary tree can be serialized to a string and 13 | * this string can be deserialized to the original tree structure. 14 | * 15 | * For example, you may serialize the following tree 16 | * 17 | * 1 18 | * / \ 19 | * 2 3 20 | * / \ 21 | * 4 5 22 | * as "[1,2,3,null,null,4,5]", 23 | * just the same as how LeetCode OJ serializes a binary tree. 24 | * You do not necessarily need to follow this format, 25 | * so please be creative and come up with different approaches yourself. 26 | * 27 | * Note: Do not use class member/global/static variables to store states. 28 | * Your serialize and deserialize algorithms should be stateless. 29 | */ 30 | 31 | /** 32 | * You should comment the following function to pass the leetcode tests. 33 | * Definition for a binary tree node. 34 | */ 35 | var TreeNode = require('../../structures/TreeNode'); 36 | 37 | /** 38 | * Definition for a binary tree node. 39 | * function TreeNode(val) { 40 | * this.val = val; 41 | * this.left = this.right = null; 42 | * } 43 | */ 44 | 45 | /** 46 | * Encodes a tree to a single string. 47 | * 48 | * @param {TreeNode} root 49 | * @return {string} 50 | */ 51 | var serialize = exports.serialize = function (root) { 52 | return JSON.stringify(ser(root)); 53 | 54 | function ser(r) { 55 | if (r === null) return null; 56 | return [r.val, ser(r.left), ser(r.right)]; 57 | } 58 | }; 59 | 60 | /** 61 | * Decodes your encoded data to tree. 62 | * 63 | * @param {string} data 64 | * @return {TreeNode} 65 | */ 66 | var deserialize = exports.deserialize = function (data) { 67 | return deser(JSON.parse(data)); 68 | 69 | function deser(d) { 70 | if (d === null) return null; 71 | var root = new TreeNode(d[0]); 72 | root.left = deser(d[1]); 73 | root.right = deser(d[2]); 74 | return root; 75 | } 76 | }; 77 | 78 | /** 79 | * Your functions will be called as such: 80 | * deserialize(serialize(root)); 81 | */ 82 | -------------------------------------------------------------------------------- /problems/018-4sum/index1.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/4sum/ 3 | * 4 | * Given an array S of n integers, are there elements a, b, c, 5 | * and d in S such that a + b + c + d = target? 6 | * Find all unique quadruplets in the array which gives the sum of target. 7 | * 8 | * Note: 9 | * 10 | * - Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d) 11 | * - The solution set must not contain duplicate quadruplets. 12 | * 13 | * For example, given array S = {1 0 -1 0 -2 2}, and target = 0. 14 | * 15 | * A solution set is: 16 | * (-1, 0, 0, 1) 17 | * (-2, -1, 1, 2) 18 | * (-2, 0, 0, 2) 19 | */ 20 | 21 | /** 22 | * @param {number[]} nums 23 | * @param {number} target 24 | * @return {number[][]} 25 | */ 26 | var fourSum = module.exports = function (nums, target) { 27 | var hash = {}; 28 | var i; 29 | var j; 30 | var numsLength = nums.length; 31 | var value; 32 | for (i = 0; i < numsLength; i++) { 33 | for (j = i + 1; j < numsLength; j++) { 34 | value = nums[i] + nums[j]; 35 | if (hash[value] === undefined) { 36 | hash[value] = [[i, j]]; 37 | } else { 38 | hash[value].push([i, j]); 39 | } 40 | } 41 | } 42 | 43 | // console.log(hash); 44 | var result = []; 45 | Object.keys(hash).forEach(function (key) { 46 | if (key * 2 < target) { 47 | return; 48 | } 49 | if (key * 2 === target) { 50 | for (i = 0; i < hash[key].length; i++) { 51 | for (j = i + 1; j < hash[key].length; j++) { 52 | if (notRepeat(hash[key][i], hash[target - key][j])) { 53 | result[result.length] = hash[key][i].concat(hash[target - key][j]); 54 | } 55 | } 56 | } 57 | } else if (hash[target - key] !== undefined) { 58 | for (i = 0; i < hash[key].length; i++) { 59 | for (j = 0; j < hash[target - key].length; j++) { 60 | if (notRepeat(hash[key][i], hash[target - key][j])) { 61 | result[result.length] = hash[key][i].concat(hash[target - key][j]); 62 | } 63 | } 64 | } 65 | } 66 | }); 67 | return deduplicate(result.map(function (indexs) { 68 | return indexs.map(function (index) { 69 | return nums[index]; 70 | }).sort(function (a, b) { return a - b; }); 71 | })); 72 | 73 | function notRepeat(arr1, arr2) { 74 | if ( 75 | arr1[0] !== arr2[0] && 76 | arr1[0] !== arr2[1] && 77 | arr1[1] !== arr2[0] && 78 | arr1[1] !== arr2[1] 79 | ) { 80 | return true; 81 | } 82 | return false; 83 | } 84 | 85 | function deduplicate(arr) { 86 | var existsHash = {}; 87 | return arr.filter(function (insideArr) { 88 | var key = insideArr.toString(); 89 | if (existsHash[key]) { 90 | return false; 91 | } 92 | existsHash[key] = true; 93 | return true; 94 | }); 95 | } 96 | }; 97 | -------------------------------------------------------------------------------- /problems/008-string-to-integer-atoi/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/string-to-integer-atoi/ 3 | * 4 | * Implement atoi to convert a string to an integer. 5 | * 6 | * Hint: Carefully consider all possible input cases. If you want a challenge, 7 | * please do not see below and ask yourself what are the possible input cases. 8 | * 9 | * Notes: It is intended for this problem to be specified vaguely 10 | * (ie, no given input specs). 11 | * You are responsible to gather all the input requirements up front. 12 | * 13 | * Update (2015-02-10): 14 | * The signature of the C++ function had been updated. 15 | * If you still see your function signature accepts a const char * argument, 16 | * please click the reload button to reset your code definition. 17 | * 18 | * Requirements for atoi: 19 | * The function first discards as many whitespace characters as necessary 20 | * until the first non-whitespace character is found. 21 | * Then, starting from this character, takes an optional initial plus or minus 22 | * sign followed by as many numerical digits as possible, 23 | * and interprets them as a numerical value. 24 | * 25 | * The string can contain additional characters after those that form the 26 | * integral number, 27 | * which are ignored and have no effect on the behavior of this function. 28 | * 29 | * If the first sequence of non-whitespace characters in str is not a valid 30 | * integral number, 31 | * or if no such sequence exists because either str is empty or it contains 32 | * only whitespace characters, no conversion is performed. 33 | * 34 | * If no valid conversion could be performed, a zero value is returned. 35 | * If the correct value is out of the range of representable values, 36 | * INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. 37 | */ 38 | 39 | /** 40 | * @param {string} str 41 | * @return {number} 42 | */ 43 | 44 | var REGEXP_NUM = /[0-9\.]/; 45 | var MAX = 2147483647; 46 | var MIN = -2147483648; 47 | 48 | var myAtoi = module.exports = function (str) { 49 | var strLength = str.length; 50 | if (strLength === 0) return 0; 51 | var touchFirstLetter = false; 52 | var pn = '+'; 53 | var startPosition = 0; 54 | var endPosition = strLength; 55 | for (var i = 0; i < strLength; i++) { 56 | if (!touchFirstLetter) { 57 | if (str[i] === ' ') continue; 58 | if (str[i] === '+' || str[i] === '-') { 59 | pn = str[i]; 60 | touchFirstLetter = true; 61 | startPosition = i + 1; 62 | continue; 63 | } 64 | if (REGEXP_NUM.test(str[i])) { 65 | touchFirstLetter = true; 66 | startPosition = i; 67 | continue; 68 | } else { 69 | startPosition = i; 70 | endPosition = i; 71 | break; 72 | } 73 | } else { 74 | if (!REGEXP_NUM.test(str[i])) { 75 | endPosition = i; 76 | break; 77 | } 78 | } 79 | } 80 | var result = Number(pn + str.substring(startPosition, endPosition)); 81 | if (isNaN(result)) return 0; 82 | if (result > MAX) return MAX; 83 | if (result < MIN) return MIN; 84 | return result; 85 | }; 86 | -------------------------------------------------------------------------------- /problems/018-4sum/testcases.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | input: [[1, 0, -1, 0, -2, 2], 0], 4 | output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]], 5 | }, 6 | { 7 | input: [[], 0], 8 | output: [], 9 | }, 10 | { 11 | input: [[1, -1, 8, 9, 10], 0], 12 | output: [], 13 | }, 14 | { 15 | input: [[1, 1, 1, 1, 2], 4], 16 | output: [[1, 1, 1, 1]], 17 | }, 18 | { 19 | input: [[ 20 | 91277418, 66271374, 38763793, 4092006, 11415077, 60468277, 1122637, 72398035, 21 | -62267800, 22082642, 60359529, -16540633, 92671879, -64462734, -55855043, 22 | -40899846, 88007957, -57387813, -49552230, -96789394, 18318594, -3246760, 23 | -44346548, -21370279, 42493875, 25185969, 83216261, -70078020, -53687927, 24 | -76072023, -65863359, -61708176, -29175835, 85675811, -80575807, -92211746, 25 | 44755622, -23368379, 23619674, -749263, -40707953, -68966953, 72694581, 26 | -52328726, -78618474, 40958224, -2921736, -55902268, -74278762, 63342010, 27 | 29076029, 58781716, 56045007, -67966567, -79405127, -45778231, -47167435, 28 | 1586413, -58822903, -51277270, 87348634, -86955956, -47418266, 74884315, 29 | -36952674, -29067969, -98812826, -44893101, -22516153, -34522513, 34091871, 30 | -79583480, 47562301, 6154068, 87601405, -48859327, -2183204, 17736781, 31 | 31189878, -23814871, -35880166, 39204002, 93248899, -42067196, -49473145, 32 | -75235452, -61923200, 64824322, -88505198, 20903451, -80926102, 56089387, 33 | -58094433, 37743524, -71480010, -14975982, 19473982, 47085913, -90793462, 34 | -33520678, 70775566, -76347995, -16091435, 94700640, 17183454, 85735982, 35 | 90399615, -86251609, -68167910, -95327478, 90586275, -99524469, 16999817, 36 | 27815883, -88279865, 53092631, 75125438, 44270568, -23129316, -846252, 37 | -59608044, 90938699, 80923976, 3534451, 6218186, 41256179, -9165388, 38 | -11897463, 92423776, -38991231, -6082654, 92275443, 74040861, 77457712, 39 | -80549965, -42515693, 69918944, -95198414, 15677446, -52451179, -50111167, 40 | -23732840, 39520751, -90474508, -27860023, 65164540, 26582346, -20183515, 41 | 99018741, -2826130, -28461563, -24759460, -83828963, -1739800, 71207113, 42 | 26434787, 52931083, -33111208, 38314304, -29429107, -5567826, -5149750, 43 | 9582750, 85289753, 75490866, -93202942, -85974081, 7365682, -42953023, 44 | 21825824, 68329208, -87994788, 3460985, 18744871, -49724457, -12982362, 45 | -47800372, 39958829, -95981751, -71017359, -18397211, 27941418, -34699076, 46 | 74174334, 96928957, 44328607, 49293516, -39034828, 5945763, -47046163, 47 | 10986423, 63478877, 30677010, -21202664, -86235407, 3164123, 8956697, 48 | -9003909, -18929014, -73824245], -236727523], 49 | output: [ 50 | [-79583480, -70078020, -65863359, -21202664], 51 | [-76072023, -59608044, -58094433, -42953023], 52 | ], 53 | }, 54 | { 55 | input: [[-3, -2, -1, 0, 0, 1, 2, 3], 0], 56 | output: [[-3, -2, 2, 3], [-3, -1, 1, 3], [-3, 0, 0, 3], [-3, 0, 1, 2], 57 | [-2, -1, 0, 3], [-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]], 58 | }, 59 | ]; 60 | --------------------------------------------------------------------------------