├── .gitignore ├── 001-two-sum └── two-sum.js ├── 002-add-two-numbers └── add-two-numbers.js ├── 003-longest-substring-without-repeating-characters └── longest-substring-without-repeating-characters.js ├── 004-median-of-two-sorted-arrays └── median-of-two-sorted-arrays.js ├── 005-longest-palindromic-substring └── longest-palindromic-substring.js ├── 006-zigzag-conversion └── zigzag-conversion.js ├── 007-reverse-integer └── reverse-integer.js ├── 008-string-to-integer-atoi └── string-to-integer-atoi.js ├── 009-palindrome-number └── palindrome-number.js ├── 010-regular-expression-matching └── regular-expression-matching.js ├── 011-container-with-most-water └── container-with-most-water.js ├── 012-integer-to-roman └── integer-to-roman.js ├── 013-roman-to-integer └── roman-to-integer.js ├── 014-longest-common-prefix └── longest-common-prefix.js ├── 015-3sum └── 3sum.js ├── 016-3sum-closest └── 3sum-closest.js ├── 017-letter-combinations-of-a-phone-number └── letter-combinations-of-a-phone-number.js ├── 018-4sum └── 4sum.js ├── 019-remove-nth-node-from-end-of-list └── remove-nth-node-from-end-of-list.js ├── 020-valid-parentheses └── valid-parentheses.js ├── 021-merge-two-sorted-lists └── merge-two-sorted-lists.js ├── 022-generate-parentheses └── generate-parentheses.js ├── 023-merge-k-sorted-lists └── merge-k-sorted-lists.js ├── 024-swap-nodes-in-pairs └── swap-nodes-in-pairs.js ├── 025-reverse-nodes-in-k-group └── reverse-nodes-in-k-group.js ├── 026-remove-duplicates-from-sorted-array └── remove-duplicates-from-sorted-array.js ├── 027-remove-element └── remove-element.js ├── 028-implement-strstr ├── implement-strstr.cpp └── implement-strstr.js ├── 029-divide-two-integers └── divide-two-integers.js ├── 030-substring-with-concatenation-of-all-words └── substring-with-concatenation-of-all-words.js ├── 031-next-permutation └── next-permutation.js ├── 032-longest-valid-parentheses └── longest-valid-parentheses.js ├── 033-search-in-rotated-sorted-array └── search-in-rotated-sorted-array.js ├── 034-find-first-and-last-position-of-element-in-sorted-array └── find-first-and-last-position-of-element-in-sorted-array.js ├── 035-search-insert-position └── search-insert-position.js ├── 036-valid-sudoku └── valid-sudoku.js ├── 037-sudoku-solver └── sudoku-solver.js ├── 038-count-and-say └── count-and-say.js ├── 039-combination-sum └── combination-sum.js ├── 040-combination-sum-ii └── combination-sum-ii.js ├── 041-first-missing-positive └── first-missing-positive.js ├── 042-trapping-rain-water └── trapping-rain-water.js ├── 043-multiply-strings └── multiply-strings.js ├── 044-wildcard-matching └── wildcard-matching.js ├── 045-jump-game-ii └── jump-game-ii.js ├── 046-permutations └── permutations.js ├── 047-permutations-ii └── permutations-ii.js ├── 048-rotate-image ├── rotate-image.js └── rotate-image.py ├── 049-group-anagrams └── group-anagrams.js ├── 050-powx-n └── powx-n.js ├── 051-n-queens └── n-queens.js ├── 052-n-queens-ii └── n-queens-ii.js ├── 053-maximum-subarray └── maximum-subarray.js ├── 054-spiral-matrix └── spiral-matrix.js ├── 055-jump-game └── jump-game.js ├── 056-merge-intervals └── merge-intervals.js ├── 057-insert-interval └── insert-interval.js ├── 058-length-of-last-word └── length-of-last-word.js ├── 059-spiral-matrix-ii └── spiral-matrix-ii.js ├── 060-permutation-sequence └── permutation-sequence.js ├── 061-rotate-list └── rotate-list.js ├── 062-unique-paths └── unique-paths.js ├── 063-unique-paths-ii └── unique-paths-ii.js ├── 064-minimum-path-sum └── minimum-path-sum.js ├── 065-valid-number └── valid-number.js ├── 066-plus-one └── plus-one.js ├── 067-add-binary └── add-binary.js ├── 068-text-justification └── text-justification.js ├── 069-sqrtx └── sqrtx.js ├── 070-climbing-stairs └── climbing-stairs.js ├── 071-simplify-path └── simplify-path.js ├── 072-edit-distance └── edit-distance.js ├── 073-set-matrix-zeroes └── set-matrix-zeroes.js ├── 074-search-a-2d-matrix └── search-a-2d-matrix.js ├── 075-sort-colors └── sort-colors.js ├── 076-minimum-window-substring └── minimum-window-substring.js ├── 077-combinations └── combinations.js ├── 078-subsets └── subsets.js ├── 079-word-search └── word-search.js ├── 080-remove-duplicates-from-sorted-array-ii └── remove-duplicates-from-sorted-array-ii.js ├── 081-search-in-rotated-sorted-array-ii └── search-in-rotated-sorted-array-ii.js ├── 082-remove-duplicates-from-sorted-list-ii └── remove-duplicates-from-sorted-list-ii.js ├── 083-remove-duplicates-from-sorted-list └── remove-duplicates-from-sorted-list.js ├── 084-largest-rectangle-in-histogram └── largest-rectangle-in-histogram.js ├── 085-maximal-rectangle └── maximal-rectangle.js ├── 086-partition-list └── partition-list.js ├── 087-scramble-string └── scramble-string.js ├── 088-merge-sorted-array └── merge-sorted-array.js ├── 089-gray-code └── gray-code.js ├── 090-subsets-ii └── subsets-ii.js ├── 091-decode-ways └── decode-ways.js ├── 092-reverse-linked-list-ii └── reverse-linked-list-ii.js ├── 093-restore-ip-addresses └── restore-ip-addresses.js ├── 094-binary-tree-inorder-traversal └── binary-tree-inorder-traversal.js ├── 095-unique-binary-search-trees-ii └── unique-binary-search-trees-ii.js ├── 096-unique-binary-search-trees └── unique-binary-search-trees.js ├── 097-interleaving-string └── interleaving-string.js ├── 098-validate-binary-search-tree └── validate-binary-search-tree.js ├── 099-recover-binary-search-tree └── recover-binary-search-tree.js ├── 100-same-tree └── same-tree.js ├── 101-symmetric-tree └── symmetric-tree.js ├── 102-binary-tree-level-order-traversal └── binary-tree-level-order-traversal.js ├── 103-binary-tree-zigzag-level-order-traversal └── binary-tree-zigzag-level-order-traversal.js ├── 104-maximum-depth-of-binary-tree └── maximum-depth-of-binary-tree.js ├── 105-construct-binary-tree-from-preorder-and-inorder-traversal └── construct-binary-tree-from-preorder-and-inorder-traversal.js ├── 106-construct-binary-tree-from-inorder-and-postorder-traversal └── construct-binary-tree-from-inorder-and-postorder-traversal.js ├── 107-binary-tree-level-order-traversal-ii └── binary-tree-level-order-traversal-ii.js ├── 108-convert-sorted-array-to-binary-search-tree └── convert-sorted-array-to-binary-search-tree.js ├── 109-convert-sorted-list-to-binary-search-tree └── convert-sorted-list-to-binary-search-tree.js ├── 110-balanced-binary-tree └── balanced-binary-tree.js ├── 111-minimum-depth-of-binary-tree └── minimum-depth-of-binary-tree.js ├── 112-path-sum └── path-sum.js ├── 113-path-sum-ii └── path-sum-ii.js ├── 114-flatten-binary-tree-to-linked-list └── flatten-binary-tree-to-linked-list.js ├── 115-distinct-subsequences └── distinct-subsequences.cpp ├── 116-populating-next-right-pointers-in-each-node └── populating-next-right-pointers-in-each-node.cpp ├── 117-populating-next-right-pointers-in-each-node-ii └── populating-next-right-pointers-in-each-node-ii.cpp ├── 118-pascals-triangle └── pascals-triangle.cpp ├── 119-pascals-triangle-ii └── pascals-triangle-ii.cpp ├── 120-triangle └── triangle.cpp ├── 121-best-time-to-buy-and-sell-stock ├── best-time-to-buy-and-sell-stock.cpp └── best-time-to-buy-and-sell-stock.js ├── 122-best-time-to-buy-and-sell-stock-ii └── best-time-to-buy-and-sell-stock-ii.cpp ├── 123-best-time-to-buy-and-sell-stock-iii └── best-time-to-buy-and-sell-stock-iii.cpp ├── 124-binary-tree-maximum-path-sum └── binary-tree-maximum-path-sum.cpp ├── 125-valid-palindrome └── valid-palindrome.cpp ├── 126-word-ladder-ii └── word-ladder-ii.cpp ├── 127-word-ladder └── word-ladder.cpp ├── 128-longest-consecutive-sequence └── longest-consecutive-sequence.cpp ├── 129-sum-root-to-leaf-numbers └── sum-root-to-leaf-numbers.cpp ├── 130-surrounded-regions └── surrounded-regions.cpp ├── 131-palindrome-partitioning └── palindrome-partitioning.cpp ├── 132-palindrome-partitioning-ii └── palindrome-partitioning-ii.cpp ├── 133-clone-graph └── clone-graph.cpp ├── 134-gas-station └── gas-station.cpp ├── 135-candy └── candy.cpp ├── 136-single-number └── single-number.cpp ├── 137-single-number-ii └── single-number-ii.cpp ├── 138-copy-list-with-random-pointer └── copy-list-with-random-pointer.cpp ├── 139-word-break └── word-break.cpp ├── 140-word-break-ii └── word-break-ii.cpp ├── 141-linked-list-cycle └── linked-list-cycle.cpp ├── 142-linked-list-cycle-ii └── linked-list-cycle-ii.cpp ├── 143-reorder-list └── reorder-list.cpp ├── 144-binary-tree-preorder-traversal └── binary-tree-preorder-traversal.cpp ├── 145-binary-tree-postorder-traversal └── binary-tree-postorder-traversal.cpp ├── 146-lru-cache └── lru-cache.cpp ├── 147-insertion-sort-list └── insertion-sort-list.cpp ├── 148-sort-list └── sort-list.cpp ├── 149-max-points-on-a-line └── max-points-on-a-line.cpp ├── 150-evaluate-reverse-polish-notation └── evaluate-reverse-polish-notation.cpp ├── 151-reverse-words-in-a-string └── reverse-words-in-a-string.cpp ├── 152-maximum-product-subarray └── maximum-product-subarray.cpp ├── 153-find-minimum-in-rotated-sorted-array └── find-minimum-in-rotated-sorted-array.cpp ├── 154-find-minimum-in-rotated-sorted-array-ii └── find-minimum-in-rotated-sorted-array-ii.cpp ├── 155-min-stack └── min-stack.cpp ├── 160-intersection-of-two-linked-lists └── intersection-of-two-linked-lists.cpp ├── 162-find-peak-element └── find-peak-element.cpp ├── 164-maximum-gap └── maximum-gap.cpp ├── 165-compare-version-numbers ├── compare-version-numbers.cpp └── compare-version-numbers.js ├── 166-fraction-to-recurring-decimal └── fraction-to-recurring-decimal.cpp ├── 167-two-sum-ii-input-array-is-sorted └── two-sum-ii-input-array-is-sorted.cpp ├── 168-excel-sheet-column-title └── excel-sheet-column-title.cpp ├── 169-majority-element ├── majority-element.cpp └── majority-element.js ├── 171-excel-sheet-column-number └── excel-sheet-column-number.cpp ├── 172-factorial-trailing-zeroes └── factorial-trailing-zeroes.cpp ├── 173-binary-search-tree-iterator └── binary-search-tree-iterator.cpp ├── 174-dungeon-game └── dungeon-game.cpp ├── 179-largest-number └── largest-number.cpp ├── 187-repeated-dna-sequences └── repeated-dna-sequences.cpp ├── 188-best-time-to-buy-and-sell-stock-iv └── best-time-to-buy-and-sell-stock-iv.cpp ├── 189-rotate-array ├── rotate-array.cpp └── rotate-array.js ├── 190-reverse-bits ├── reverse-bits.cpp └── reverse-bits.js ├── 191-number-of-1-bits ├── number-of-1-bits.cpp └── number-of-1-bits.js ├── 198-house-robber └── house-robber.cpp ├── 199-binary-tree-right-side-view └── binary-tree-right-side-view.cpp ├── 200-number-of-islands └── number-of-islands.cpp ├── 201-bitwise-and-of-numbers-range └── bitwise-and-of-numbers-range.cpp ├── 202-happy-number └── happy-number.cpp ├── 203-remove-linked-list-elements └── remove-linked-list-elements.cpp ├── 204-count-primes └── count-primes.cpp ├── 205-isomorphic-strings ├── isomorphic-strings.cpp └── isomorphic-strings.js ├── 206-reverse-linked-list └── reverse-linked-list.cpp ├── 207-course-schedule └── course-schedule.cpp ├── 208-implement-trie-prefix-tree └── implement-trie-prefix-tree.cpp ├── 209-minimum-size-subarray-sum └── minimum-size-subarray-sum.cpp ├── 210-course-schedule-ii └── course-schedule-ii.cpp ├── 211-add-and-search-word-data-structure-design └── add-and-search-word-data-structure-design.cpp ├── 212-word-search-ii └── word-search-ii.cpp ├── 213-house-robber-ii └── house-robber-ii.cpp ├── 214-shortest-palindrome └── shortest-palindrome.cpp ├── 215-kth-largest-element-in-an-array └── kth-largest-element-in-an-array.cpp ├── 216-combination-sum-iii └── combination-sum-iii.cpp ├── 217-contains-duplicate ├── contains-duplicate.cpp └── contains-duplicate.js ├── 218-the-skyline-problem └── the-skyline-problem.cpp ├── 219-contains-duplicate-ii ├── contains-duplicate-ii.cpp └── contains-duplicate-ii.js ├── 220-contains-duplicate-iii └── contains-duplicate-iii.cpp ├── 221-maximal-square └── maximal-square.cpp ├── 222-count-complete-tree-nodes └── count-complete-tree-nodes.cpp ├── 223-rectangle-area └── rectangle-area.cpp ├── 224-basic-calculator └── basic-calculator.cpp ├── 225-implement-stack-using-queues └── implement-stack-using-queues.js ├── 371-sum-of-two-integers └── sum-of-two-integers.cpp ├── 374-guess-number-higher-or-lower └── guess-number-higher-or-lower.cpp ├── README.md ├── cookies.json └── leetcode_generate.py /.gitignore: -------------------------------------------------------------------------------- 1 | config.cfg 2 | -------------------------------------------------------------------------------- /001-two-sum/two-sum.js: -------------------------------------------------------------------------------- 1 | // Given an array of integers, return indices of the two numbers such that they add up to a specific target. 2 | // 3 | // You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | // 5 | // Example: 6 | // 7 | // 8 | // Given nums = [2, 7, 11, 15], target = 9, 9 | // 10 | // Because nums[0] + nums[1] = 2 + 7 = 9, 11 | // return [0, 1]. 12 | // 13 | // 14 | //   15 | // 16 | 17 | 18 | /** 19 | * @param {number[]} nums 20 | * @param {number} target 21 | * @return {number[]} 22 | */ 23 | var twoSum = function(nums, target) { 24 | var hash = {}; 25 | for (var i = 0, len = nums.length; i < len; ++i) { 26 | if (hash[target - nums[i]] !== undefined) { 27 | return [hash[target - nums[i]], i + 1]; 28 | } 29 | hash[nums[i]] = hash[nums[i]] || i + 1; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /002-add-two-numbers/add-two-numbers.js: -------------------------------------------------------------------------------- 1 | // You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 2 | // 3 | // You may assume the two numbers do not contain any leading zero, except the number 0 itself. 4 | // 5 | // Example: 6 | // 7 | // 8 | // Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 9 | // Output: 7 -> 0 -> 8 10 | // Explanation: 342 + 465 = 807. 11 | // 12 | // 13 | 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 addTwoNumbers = function(l1, l2) { 28 | var result = new ListNode(-1), 29 | r = result, 30 | cur; 31 | while (l1 !== null || l2 !== null) { 32 | cur = r.next || new ListNode(0); 33 | r.next = cur; 34 | cur.val += (l1 && l1.val || 0); 35 | cur.val += (l2 && l2.val || 0); 36 | if (cur.val > 9) { 37 | cur.next = new ListNode(1); 38 | cur.val -= 10; 39 | } 40 | r = cur; 41 | l1 = l1 && l1.next; 42 | l2 = l2 && l2.next; 43 | } 44 | r = result.next; 45 | result.next = null; 46 | return r; 47 | }; 48 | 49 | -------------------------------------------------------------------------------- /003-longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.js: -------------------------------------------------------------------------------- 1 | // Given a string, find the length of the longest substring without repeating characters. 2 | // 3 | // 4 | // Example 1: 5 | // 6 | // 7 | // Input: "abcabcbb" 8 | // Output: 3 9 | // Explanation: The answer is "abc", with the length of 3. 10 | // 11 | // 12 | // 13 | // Example 2: 14 | // 15 | // 16 | // Input: "bbbbb" 17 | // Output: 1 18 | // Explanation: The answer is "b", with the length of 1. 19 | // 20 | // 21 | // 22 | // Example 3: 23 | // 24 | // 25 | // Input: "pwwkew" 26 | // Output: 3 27 | // Explanation: The answer is "wke", with the length of 3. 28 | // Note that the answer must be a substring, "pwke" is a subsequence and not a substring. 29 | // 30 | // 31 | // 32 | // 33 | // 34 | 35 | 36 | /** 37 | * @param {string} s 38 | * @return {number} 39 | */ 40 | var lengthOfLongestSubstring = function(s) { 41 | var hash = {}, maxLen = 0, 42 | cur = 0, start = 0; 43 | for (var i = 0, len = s.length; i < len;++i) { 44 | if (hash[s[i]] === undefined || hash[s[i]] < start) { 45 | ++cur; 46 | hash[s[i]] = i; 47 | } else { 48 | start = hash[s[i]]; 49 | hash[s[i]] = i; 50 | cur = i - start; 51 | } 52 | 53 | if (cur > maxLen) maxLen = cur; 54 | } 55 | return maxLen; 56 | }; 57 | 58 | -------------------------------------------------------------------------------- /005-longest-palindromic-substring/longest-palindromic-substring.js: -------------------------------------------------------------------------------- 1 | // Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: "babad" 7 | // Output: "bab" 8 | // Note: "aba" is also a valid answer. 9 | // 10 | // 11 | // Example 2: 12 | // 13 | // 14 | // Input: "cbbd" 15 | // Output: "bb" 16 | // 17 | // 18 | 19 | 20 | var isPalindrome = function(s,begin,end) { 21 | if (begin < 0) { 22 | return false; 23 | } 24 | while (begin < end && s[begin] === s[end]) { 25 | ++begin; --end; 26 | } 27 | return begin - end === 1 || 28 | begin === end; 29 | }; 30 | /** 31 | * @param {string} s 32 | * @return {string} 33 | */ 34 | var longestPalindrome = function(s) { 35 | var len = s.length, 36 | maxLen = 0, 37 | from = -1; 38 | if (len < 2) { 39 | return s; 40 | } 41 | for (var i = 0;i < len;++i) { 42 | if (isPalindrome(s,i - maxLen - 1,i)) { 43 | from = i - maxLen - 1; 44 | maxLen += 2; 45 | } else if (isPalindrome(s,i - maxLen,i)) { 46 | from = i - maxLen; 47 | ++maxLen; 48 | } 49 | } 50 | return s.substr(from,maxLen); 51 | }; 52 | 53 | -------------------------------------------------------------------------------- /006-zigzag-conversion/zigzag-conversion.js: -------------------------------------------------------------------------------- 1 | // The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 2 | // 3 | // 4 | // P A H N 5 | // A P L S I I G 6 | // Y I R 7 | // 8 | // 9 | // And then read line by line: "PAHNAPLSIIGYIR" 10 | // 11 | // Write the code that will take a string and make this conversion given a number of rows: 12 | // 13 | // 14 | // string convert(string s, int numRows); 15 | // 16 | // Example 1: 17 | // 18 | // 19 | // Input: s = "PAYPALISHIRING", numRows = 3 20 | // Output: "PAHNAPLSIIGYIR" 21 | // 22 | // 23 | // Example 2: 24 | // 25 | // 26 | // Input: s = "PAYPALISHIRING", numRows = 4 27 | // Output: "PINALSIGYAHRPI" 28 | // Explanation: 29 | // 30 | // P I N 31 | // A L S I G 32 | // Y A H R 33 | // P I 34 | // 35 | 36 | 37 | /** 38 | * @param {string} s 39 | * @param {number} numRows 40 | * @return {string} 41 | */ 42 | var convert = function(s, numRows) { 43 | var len = s.length, 44 | result = '', 45 | loop = 2 *numRows - 2, 46 | i,j; 47 | if (len <= numRows || numRows === 1) { 48 | return s; 49 | } 50 | for (i = 0;i < len;i += loop) { 51 | result += s[i]; 52 | } 53 | for (i = 1;i < numRows - 1;++i) { 54 | for (j = i;j < len;j += loop) { 55 | result += s[j]; 56 | if (j + loop - 2 * i = Math.pow(2,31)) { 38 | return 0; 39 | } else { 40 | return reverse * sign; 41 | } 42 | }; 43 | 44 | -------------------------------------------------------------------------------- /009-palindrome-number/palindrome-number.js: -------------------------------------------------------------------------------- 1 | // Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: 121 7 | // Output: true 8 | // 9 | // 10 | // Example 2: 11 | // 12 | // 13 | // Input: -121 14 | // Output: false 15 | // Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 16 | // 17 | // 18 | // Example 3: 19 | // 20 | // 21 | // Input: 10 22 | // Output: false 23 | // Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 24 | // 25 | // 26 | // Follow up: 27 | // 28 | // Coud you solve it without converting the integer to a string? 29 | // 30 | 31 | 32 | /** 33 | * @param {number} x 34 | * @return {boolean} 35 | */ 36 | var isPalindrome = function(x) { 37 | return (x+'') == (x+'').split('').reverse().join(''); 38 | }; 39 | -------------------------------------------------------------------------------- /010-regular-expression-matching/regular-expression-matching.js: -------------------------------------------------------------------------------- 1 | // Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. 2 | // 3 | // 4 | // '.' Matches any single character. 5 | // '*' Matches zero or more of the preceding element. 6 | // 7 | // 8 | // The matching should cover the entire input string (not partial). 9 | // 10 | // Note: 11 | // 12 | // 13 | // s could be empty and contains only lowercase letters a-z. 14 | // p could be empty and contains only lowercase letters a-z, and characters like . or *. 15 | // 16 | // 17 | // Example 1: 18 | // 19 | // 20 | // Input: 21 | // s = "aa" 22 | // p = "a" 23 | // Output: false 24 | // Explanation: "a" does not match the entire string "aa". 25 | // 26 | // 27 | // Example 2: 28 | // 29 | // 30 | // Input: 31 | // s = "aa" 32 | // p = "a*" 33 | // Output: true 34 | // Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". 35 | // 36 | // 37 | // Example 3: 38 | // 39 | // 40 | // Input: 41 | // s = "ab" 42 | // p = ".*" 43 | // Output: true 44 | // Explanation: ".*" means "zero or more (*) of any character (.)". 45 | // 46 | // 47 | // Example 4: 48 | // 49 | // 50 | // Input: 51 | // s = "aab" 52 | // p = "c*a*b" 53 | // Output: true 54 | // Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab". 55 | // 56 | // 57 | // Example 5: 58 | // 59 | // 60 | // Input: 61 | // s = "mississippi" 62 | // p = "mis*is*p*." 63 | // Output: false 64 | // 65 | // 66 | 67 | 68 | /** 69 | * @param {string} s 70 | * @param {string} p 71 | * @return {boolean} 72 | */ 73 | var isMatch = function(s, p) { 74 | var r = s.match(new RegExp(p)); 75 | if (r === null) return false; 76 | if (r[0] === s) return true; 77 | return false; 78 | }; 79 | -------------------------------------------------------------------------------- /011-container-with-most-water/container-with-most-water.js: -------------------------------------------------------------------------------- 1 | // Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 2 | // 3 | // Note: You may not slant the container and n is at least 2. 4 | // 5 | //   6 | // 7 | // 8 | // 9 | // The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. 10 | // 11 | //   12 | // 13 | // Example: 14 | // 15 | // 16 | // Input: [1,8,6,2,5,4,8,3,7] 17 | // Output: 49 18 | // 19 | 20 | 21 | /** 22 | * @param {number[]} height 23 | * @return {number} 24 | */ 25 | var maxArea = function(height) { 26 | var max = 0,i = 0,j = height.length - 1,temp; 27 | while (i < j) { 28 | if (height[i] < height[j]) { 29 | max = Math.max(max,height[i]*(j-i)); 30 | temp = height[i++]; 31 | while (i < j && height[i] <= temp) { 32 | ++i; 33 | } 34 | } else { 35 | max = Math.max(max,height[j]*(j-i)); 36 | temp = height[j--]; 37 | while (i < j && height[j] <= temp) { 38 | --j; 39 | } 40 | } 41 | } 42 | return max; 43 | }; 44 | 45 | -------------------------------------------------------------------------------- /014-longest-common-prefix/longest-common-prefix.js: -------------------------------------------------------------------------------- 1 | // Write a function to find the longest common prefix string amongst an array of strings. 2 | // 3 | // If there is no common prefix, return an empty string "". 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: ["flower","flow","flight"] 9 | // Output: "fl" 10 | // 11 | // 12 | // Example 2: 13 | // 14 | // 15 | // Input: ["dog","racecar","car"] 16 | // Output: "" 17 | // Explanation: There is no common prefix among the input strings. 18 | // 19 | // 20 | // Note: 21 | // 22 | // All given inputs are in lowercase letters a-z. 23 | // 24 | 25 | 26 | /** 27 | * @param {string[]} strs 28 | * @return {string} 29 | */ 30 | var longestCommonPrefix = function(strs) { 31 | var count = strs.length, 32 | minS = strs[0], 33 | minLen; 34 | if (minS === undefined) { 35 | return ''; 36 | } 37 | minLen = minS.length; 38 | for (var i = 1;i < count;++i) { 39 | if (minLen < strs[i].length) { 40 | minS = strs[i]; 41 | minLen = minS.length; 42 | } 43 | } 44 | for (i = 0;i < count;++i) { 45 | for (var j = 0;j < minLen;++j) { 46 | if (minS[j] != strs[i][j]) { 47 | minLen = j; 48 | break; 49 | } 50 | } 51 | } 52 | return minS.slice(0,minLen); 53 | }; 54 | 55 | -------------------------------------------------------------------------------- /015-3sum/3sum.js: -------------------------------------------------------------------------------- 1 | // Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 2 | // 3 | // Note: 4 | // 5 | // The solution set must not contain duplicate triplets. 6 | // 7 | // Example: 8 | // 9 | // 10 | // Given array nums = [-1, 0, 1, 2, -1, -4], 11 | // 12 | // A solution set is: 13 | // [ 14 | // [-1, 0, 1], 15 | // [-1, -1, 2] 16 | // ] 17 | // 18 | // 19 | 20 | 21 | /** 22 | * @param {number[]} nums 23 | * @return {number[][]} 24 | */ 25 | var threeSum = function(nums) { 26 | nums.sort(function(a,b) { 27 | return a - b; 28 | }); 29 | var i = 0, len = nums.length, 30 | result = [], 31 | low,high; 32 | for (;i < len - 2;++i) { 33 | low = i + 1; 34 | high = len - 1; 35 | while (low < high) { 36 | if (nums[low] + nums[high] + nums[i] === 0) { 37 | result.push([nums[i],nums[low],nums[high]]); 38 | while (low < len - 1 39 | && nums[low] === nums[low+1]) { 40 | ++low; 41 | } 42 | ++low; 43 | } else { 44 | if (nums[low] + nums[high] + nums[i] < 0) { 45 | ++low; 46 | } else { 47 | --high; 48 | } 49 | } 50 | } 51 | while (i < len - 3 && nums[i] === nums[i+1]) { 52 | ++i; 53 | } 54 | } 55 | return result; 56 | }; 57 | 58 | -------------------------------------------------------------------------------- /016-3sum-closest/3sum-closest.js: -------------------------------------------------------------------------------- 1 | // Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Given array nums = [-1, 2, 1, -4], and target = 1. 7 | // 8 | // The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 9 | // 10 | // 11 | 12 | 13 | /** 14 | * @param {number[]} nums 15 | * @param {number} target 16 | * @return {number} 17 | */ 18 | var threeSumClosest = function(nums, target) { 19 | nums.sort(function(a,b) { 20 | return a - b; 21 | }); 22 | var len = nums.length, 23 | minDis = Number.MAX_VALUE, 24 | result = 0, 25 | i,low,high; 26 | for (i = 0;i < len;++i) { 27 | if (i > 0 && nums[i] === nums[i-1]) { 28 | continue; 29 | } 30 | low = i + 1; 31 | high = len - 1; 32 | while (low < high) { 33 | var curSum = nums[i] + nums[low] + nums[high]; 34 | var curDis = Math.abs(curSum - target); 35 | if (curDis < minDis) { 36 | minDis = curDis; 37 | result = curSum; 38 | } 39 | 40 | if (curSum === target) { 41 | return target; 42 | } else if (curSum > target){ 43 | while (low < --high 44 | && nums[high] === nums[high + 1]); 45 | } else { 46 | while (++low < high 47 | && nums[low] === nums[low - 1]); 48 | } 49 | } 50 | } 51 | return result; 52 | }; 53 | 54 | -------------------------------------------------------------------------------- /017-letter-combinations-of-a-phone-number/letter-combinations-of-a-phone-number.js: -------------------------------------------------------------------------------- 1 | // Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. 2 | // 3 | // A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. 4 | // 5 | // 6 | // 7 | // Example: 8 | // 9 | // 10 | // Input: "23" 11 | // Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 12 | // 13 | // 14 | // Note: 15 | // 16 | // Although the above answer is in lexicographical order, your answer could be in any order you want. 17 | // 18 | 19 | 20 | var map = { 21 | "0": [], 22 | "1": [], 23 | "2": "abc".split(""), 24 | "3": "def".split(""), 25 | "4": "ghi".split(""), 26 | "5": "jkl".split(""), 27 | "6": "mno".split(""), 28 | "7": "pqrs".split(""), 29 | "8": "tuv".split(""), 30 | "9": "wxyz".split("") 31 | }; 32 | 33 | /** 34 | * @param {string[]} result 35 | * @param {string} currentStr 36 | * @param {string} digits 37 | * @param {number} index 38 | * @param {number} length 39 | */ 40 | var procedure = function(result,currentStr,digits,index,length) { 41 | if (index === length) { 42 | currentStr && result.push(currentStr); 43 | return; 44 | } 45 | var i,len = map[digits[index]].length; 46 | for (i = 0;i < len;++i) { 47 | procedure(result,currentStr + map[digits[index]][i], 48 | digits,index + 1,length); 49 | } 50 | }; 51 | 52 | /** 53 | * @param {string} digits 54 | * @return {string[]} 55 | */ 56 | var letterCombinations = function(digits) { 57 | var result = []; 58 | procedure(result,'',digits,0,digits.length); 59 | return result; 60 | }; 61 | 62 | -------------------------------------------------------------------------------- /019-remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.js: -------------------------------------------------------------------------------- 1 | // Given a linked list, remove the n-th node from the end of list and return its head. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Given linked list: 1->2->3->4->5, and n = 2. 7 | // 8 | // After removing the second node from the end, the linked list becomes 1->2->3->5. 9 | // 10 | // 11 | // Note: 12 | // 13 | // Given n will always be valid. 14 | // 15 | // Follow up: 16 | // 17 | // Could you do this in one pass? 18 | // 19 | 20 | 21 | /** 22 | * Definition for singly-linked list. 23 | * function ListNode(val) { 24 | * this.val = val; 25 | * this.next = null; 26 | * } 27 | */ 28 | /** 29 | * @param {ListNode} head 30 | * @param {number} n 31 | * @return {ListNode} 32 | */ 33 | var removeNthFromEnd = function(head, n) { 34 | var beforeHead = new ListNode(0); 35 | beforeHead.next = head; 36 | var target = beforeHead, 37 | current = beforeHead; 38 | 39 | while (n-- > 0) { 40 | current = current.next; 41 | } 42 | while (current.next) { 43 | current = current.next; 44 | target = target.next; 45 | } 46 | target.next = target.next.next; 47 | return beforeHead.next; 48 | }; 49 | 50 | -------------------------------------------------------------------------------- /020-valid-parentheses/valid-parentheses.js: -------------------------------------------------------------------------------- 1 | // Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 2 | // 3 | // An input string is valid if: 4 | // 5 | // 6 | // Open brackets must be closed by the same type of brackets. 7 | // Open brackets must be closed in the correct order. 8 | // 9 | // 10 | // Note that an empty string is also considered valid. 11 | // 12 | // Example 1: 13 | // 14 | // 15 | // Input: "()" 16 | // Output: true 17 | // 18 | // 19 | // Example 2: 20 | // 21 | // 22 | // Input: "()[]{}" 23 | // Output: true 24 | // 25 | // 26 | // Example 3: 27 | // 28 | // 29 | // Input: "(]" 30 | // Output: false 31 | // 32 | // 33 | // Example 4: 34 | // 35 | // 36 | // Input: "([)]" 37 | // Output: false 38 | // 39 | // 40 | // Example 5: 41 | // 42 | // 43 | // Input: "{[]}" 44 | // Output: true 45 | // 46 | // 47 | 48 | 49 | /** 50 | * @param {string} s 51 | * @return {boolean} 52 | */ 53 | var isValid = function(s) { 54 | var r = []; 55 | var i = 0; 56 | while (i < s.length) { 57 | if (s[i] === '(' || s[i] === '{' || s[i] === '[') { 58 | r.push(s[i]); 59 | } else if (s[i] === ')') { 60 | if (r[r.length - 1] === '(') r.pop(); 61 | else return false; 62 | } else if (s[i] === '}') { 63 | if (r[r.length - 1] === '{') r.pop(); 64 | else return false; 65 | } else if (s[i] === ']') { 66 | if (r[r.length - 1] === '[') r.pop(); 67 | else return false; 68 | } 69 | ++i; 70 | } 71 | return r.length > 0 ? false : true; 72 | }; 73 | -------------------------------------------------------------------------------- /021-merge-two-sorted-lists/merge-two-sorted-lists.js: -------------------------------------------------------------------------------- 1 | // Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 2 | // 3 | // Example: 4 | // 5 | // Input: 1->2->4, 1->3->4 6 | // Output: 1->1->2->3->4->4 7 | // 8 | // 9 | 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * function ListNode(val) { 14 | * this.val = val; 15 | * this.next = null; 16 | * } 17 | */ 18 | /** 19 | * @param {ListNode} l1 20 | * @param {ListNode} l2 21 | * @return {ListNode} 22 | */ 23 | var mergeTwoLists = function(l1, l2) { 24 | if (l1 === null) { 25 | return l2; 26 | } else if (l2 === null) { 27 | return l1; 28 | } 29 | 30 | var current = new ListNode(Math.min(l1.val,l2.val)), 31 | beforeHead = new ListNode(0), 32 | temp; 33 | beforeHead.next = current; 34 | if (l1.val < l2.val) { 35 | l1 = l1.next; 36 | } else { 37 | l2 = l2.next; 38 | } 39 | while (l1 && l2) { 40 | if (l1.val < l2.val) { 41 | temp = new ListNode(l1.val); 42 | l1 = l1.next; 43 | } else { 44 | temp = new ListNode(l2.val); 45 | l2 = l2.next; 46 | } 47 | current.next = temp; 48 | current = current.next; 49 | } 50 | current.next = l1 || l2 || null; 51 | return beforeHead.next; 52 | }; 53 | 54 | -------------------------------------------------------------------------------- /024-swap-nodes-in-pairs/swap-nodes-in-pairs.js: -------------------------------------------------------------------------------- 1 | // Given a linked list, swap every two adjacent nodes and return its head. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Given 1->2->3->4, you should return the list as 2->1->4->3. 7 | // 8 | // Note: 9 | // 10 | // 11 | // Your algorithm should use only constant extra space. 12 | // You may not modify the values in the list's nodes, only nodes itself may be changed. 13 | // 14 | // 15 | 16 | 17 | /** 18 | * Definition for singly-linked list. 19 | * function ListNode(val) { 20 | * this.val = val; 21 | * this.next = null; 22 | * } 23 | */ 24 | /** 25 | * @param {ListNode} head 26 | * @return {ListNode} 27 | */ 28 | var swapPairs = function(head) { 29 | if (head === null || head.next === null) { 30 | return head; 31 | } 32 | 33 | var h = new ListNode(0), 34 | p = h; 35 | 36 | while (head !== null && head.next !== null) { 37 | var temp = head.next; 38 | p.next = temp.next; 39 | temp.next = head; 40 | head.next = p.next; 41 | p.next = temp; 42 | p = head; 43 | head = head.next; 44 | } 45 | return h.next; 46 | }; 47 | 48 | -------------------------------------------------------------------------------- /025-reverse-nodes-in-k-group/reverse-nodes-in-k-group.js: -------------------------------------------------------------------------------- 1 | // Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 2 | // 3 | // k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. 4 | // 5 | // 6 | // 7 | // 8 | // Example: 9 | // 10 | // Given this linked list: 1->2->3->4->5 11 | // 12 | // For k = 2, you should return: 2->1->4->3->5 13 | // 14 | // For k = 3, you should return: 3->2->1->4->5 15 | // 16 | // Note: 17 | // 18 | // 19 | // Only constant extra memory is allowed. 20 | // You may not alter the values in the list's nodes, only nodes itself may be changed. 21 | // 22 | // 23 | 24 | 25 | /** 26 | * Definition for singly-linked list. 27 | * function ListNode(val) { 28 | * this.val = val; 29 | * this.next = null; 30 | * } 31 | */ 32 | /** 33 | * @param {ListNode} head 34 | * @param {number} k 35 | * @return {ListNode} 36 | */ 37 | var reverseKGroup = function(head, k) { 38 | var len = 0, p = head; 39 | while (p !== null) { 40 | p = p.next; 41 | ++len; 42 | } 43 | 44 | if (len < k) { 45 | return head; 46 | } 47 | 48 | var h = new ListNode(0), 49 | c = head, 50 | group = Math.floor(len / k); 51 | 52 | p = h; 53 | h.next = head; 54 | 55 | for (var j = 0;j < group;++j) { 56 | for (var i = 0;i < k - 1; ++i) { 57 | var temp = p.next; 58 | p.next = c.next; 59 | c.next = c.next.next; 60 | p.next.next = temp; 61 | } 62 | p = c; 63 | c = c.next; 64 | } 65 | return h.next; 66 | }; 67 | 68 | -------------------------------------------------------------------------------- /028-implement-strstr/implement-strstr.cpp: -------------------------------------------------------------------------------- 1 | // Implement strStr(). 2 | // 3 | // Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: haystack = "hello", needle = "ll" 9 | // Output: 2 10 | // 11 | // 12 | // Example 2: 13 | // 14 | // 15 | // Input: haystack = "aaaaa", needle = "bba" 16 | // Output: -1 17 | // 18 | // 19 | // Clarification: 20 | // 21 | // What should we return when needle is an empty string? This is a great question to ask during an interview. 22 | // 23 | // For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). 24 | // 25 | 26 | 27 | class Solution { 28 | public: 29 | int strStr(string haystack, string needle) { 30 | int lh = haystack.size(); 31 | int ln = needle.size(); 32 | if (ln == 0) return 0; 33 | if (lh < ln) return -1; 34 | int *next = new int[ln]; 35 | next[0] = -1; 36 | int k = - 1; 37 | int j = 0; 38 | while (j < ln-1) { 39 | if (k==-1 || needle[k] == needle[j]) { 40 | ++k; 41 | ++j; 42 | next[j] = k; 43 | } else { 44 | k = next[k]; 45 | } 46 | } 47 | 48 | k = 0; j = 0; 49 | while (k < lh && j < ln) { 50 | if (j == -1 || haystack[k] == needle[j]) { 51 | ++j; ++k; 52 | } else { 53 | j = next[j]; 54 | } 55 | } 56 | if (j == ln) return k-j; 57 | return -1; 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /028-implement-strstr/implement-strstr.js: -------------------------------------------------------------------------------- 1 | // Implement strStr(). 2 | // 3 | // Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: haystack = "hello", needle = "ll" 9 | // Output: 2 10 | // 11 | // 12 | // Example 2: 13 | // 14 | // 15 | // Input: haystack = "aaaaa", needle = "bba" 16 | // Output: -1 17 | // 18 | // 19 | // Clarification: 20 | // 21 | // What should we return when needle is an empty string? This is a great question to ask during an interview. 22 | // 23 | // For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). 24 | // 25 | 26 | 27 | /** 28 | * @param {string} haystack 29 | * @param {string} needle 30 | * @return {number} 31 | */ 32 | var strStr = function(haystack, needle) { 33 | var len1 = haystack.length, 34 | len2 = needle.length, 35 | next = new Array(len2), 36 | i = 0, j = -1; 37 | next[0] = -1; 38 | 39 | while (i <= len2 - 1) { 40 | if (j === -1 || needle[i] === needle[j]) { 41 | ++i; ++j; 42 | next[i] = j; 43 | } else { 44 | j = next[j]; 45 | } 46 | } 47 | 48 | i = 0; j = 0; 49 | while (i < len1 && j < len2) { 50 | if (j === -1 || haystack[i] === needle[j]) { 51 | ++i; ++j; 52 | } else { 53 | j = next[j]; 54 | } 55 | } 56 | return j === len2 ? i - j : -1; 57 | }; 58 | 59 | -------------------------------------------------------------------------------- /030-substring-with-concatenation-of-all-words/substring-with-concatenation-of-all-words.js: -------------------------------------------------------------------------------- 1 | // You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: 7 | // s = "barfoothefoobarman", 8 | // words = ["foo","bar"] 9 | // Output: [0,9] 10 | // Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively. 11 | // The output order does not matter, returning [9,0] is fine too. 12 | // 13 | // 14 | // Example 2: 15 | // 16 | // 17 | // Input: 18 | // s = "wordgoodstudentgoodword", 19 | // words = ["word","student"] 20 | // Output: [] 21 | // 22 | // 23 | 24 | 25 | /** 26 | * @param {string} s 27 | * @param {string[]} words 28 | * @return {number[]} 29 | */ 30 | var findSubstring = function(s, words) { 31 | var w = {}, result = []; 32 | words.forEach(function(v) { 33 | w[v] = w[v] + 1 || 1; 34 | //++w[v]; 35 | }); 36 | for (var i = 0, len = s.length, 37 | count = words.length, wLen = words[0].length; 38 | i < len - count * wLen + 1; 39 | ++i) { 40 | var temp = {}, j = 0; 41 | for (;j < count;++j) { 42 | var word = s.substr(i + j * wLen,wLen); 43 | if (w[word]) { 44 | temp[word] = temp[word] + 1 || 1; 45 | //++temp[word]; 46 | if (temp[word] > w[word]) { 47 | break; 48 | } 49 | } else { 50 | break; 51 | } 52 | } 53 | if (j >= count) { 54 | result.push(i); 55 | } 56 | } 57 | return result; 58 | }; 59 | 60 | -------------------------------------------------------------------------------- /031-next-permutation/next-permutation.js: -------------------------------------------------------------------------------- 1 | // Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 2 | // 3 | // If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 4 | // 5 | // The replacement must be in-place and use only constant extra memory. 6 | // 7 | // Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 8 | // 9 | // 1,2,3 → 1,3,2 10 | // 3,2,1 → 1,2,3 11 | // 1,1,5 → 1,5,1 12 | // 13 | 14 | 15 | /** 16 | * @param {number[]} nums 17 | * @return {void} Do not return anything, modify nums in-place instead. 18 | */ 19 | var nextPermutation = function(nums) { 20 | var index = 0, len = nums.length, 21 | i = len - 1, temp; 22 | if (i <= 0) { 23 | return ; 24 | } 25 | while (i > 0) { 26 | if (nums[i - 1] < nums[i]) { 27 | index = i; 28 | break; 29 | } 30 | --i; 31 | } 32 | if (index > 0) { 33 | i = len - 1; 34 | while (i >= index && nums[index - 1] >= nums[i]) { 35 | --i; 36 | } 37 | temp = nums[index - 1]; 38 | nums[index - 1] = nums[i]; 39 | nums[i] = temp; 40 | } 41 | for (i = 0;i < (len - index) / 2;++i) { 42 | temp = nums[index + i]; 43 | nums[index + i] = nums[len - i - 1]; 44 | nums[len - i - 1] = temp; 45 | } 46 | }; 47 | 48 | -------------------------------------------------------------------------------- /032-longest-valid-parentheses/longest-valid-parentheses.js: -------------------------------------------------------------------------------- 1 | // Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: "(()" 7 | // Output: 2 8 | // Explanation: The longest valid parentheses substring is "()" 9 | // 10 | // 11 | // Example 2: 12 | // 13 | // 14 | // Input: ")()())" 15 | // Output: 4 16 | // Explanation: The longest valid parentheses substring is "()()" 17 | // 18 | // 19 | 20 | 21 | /** 22 | * @param {string} s 23 | * @return {number} 24 | */ 25 | var longestValidParentheses = function(s) { 26 | var dp = new Array(s.length), 27 | max = 0, l; 28 | dp.fill(0); 29 | for (var i = 0,len = s.length;i < len; ++i) { 30 | if (s[i] === ')' && i > 0 31 | && (l = i - 1 - dp[i - 1]) >= 0 32 | && s[l] === '(') { 33 | dp[i] = 2 + dp[i - 1] + (l > 0 ? dp[l - 1] : 0); 34 | } 35 | max = Math.max(max, dp[i]); 36 | } 37 | return max; 38 | }; 39 | 40 | -------------------------------------------------------------------------------- /033-search-in-rotated-sorted-array/search-in-rotated-sorted-array.js: -------------------------------------------------------------------------------- 1 | // Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 2 | // 3 | // (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 4 | // 5 | // You are given a target value to search. If found in the array return its index, otherwise return -1. 6 | // 7 | // You may assume no duplicate exists in the array. 8 | // 9 | // Your algorithm's runtime complexity must be in the order of O(log n). 10 | // 11 | // Example 1: 12 | // 13 | // 14 | // Input: nums = [4,5,6,7,0,1,2], target = 0 15 | // Output: 4 16 | // 17 | // 18 | // Example 2: 19 | // 20 | // 21 | // Input: nums = [4,5,6,7,0,1,2], target = 3 22 | // Output: -1 23 | // 24 | 25 | 26 | /** 27 | * @param {number[]} nums 28 | * @param {number} target 29 | * @return {number} 30 | */ 31 | var search = function(nums, target) { 32 | var l = 0, h = nums.length - 1, m; 33 | while (l <= h) { 34 | m = ~~((l + h) / 2); 35 | if (target < nums[m]) { 36 | if (nums[l] < nums[h] || nums[m] < nums[l] || target > nums[h]) { 37 | h = m - 1; 38 | } else { 39 | l = m + 1; 40 | } 41 | } else if (target > nums[m]) { 42 | if (nums[l] < nums[h] || nums[m] > nums[l] || target < nums[l]) { 43 | l = m + 1; 44 | } else { 45 | h = m - 1; 46 | } 47 | 48 | } else { 49 | return m; 50 | } 51 | } 52 | return -1; 53 | }; 54 | 55 | -------------------------------------------------------------------------------- /034-find-first-and-last-position-of-element-in-sorted-array/find-first-and-last-position-of-element-in-sorted-array.js: -------------------------------------------------------------------------------- 1 | // Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. 2 | // 3 | // Your algorithm's runtime complexity must be in the order of O(log n). 4 | // 5 | // If the target is not found in the array, return [-1, -1]. 6 | // 7 | // Example 1: 8 | // 9 | // 10 | // Input: nums = [5,7,7,8,8,10], target = 8 11 | // Output: [3,4] 12 | // 13 | // Example 2: 14 | // 15 | // 16 | // Input: nums = [5,7,7,8,8,10], target = 6 17 | // Output: [-1,-1] 18 | // 19 | 20 | 21 | /** 22 | * @param {number[]} nums 23 | * @param {number} target 24 | * @return {number[]} 25 | */ 26 | var searchRange = function(nums, target) { 27 | var result = [-1,-1], 28 | l, h, m; 29 | l = 0; h = nums.length - 1; 30 | while (l <= h) { 31 | m = ~~((l + h) / 2); 32 | if (nums[m] >= target) { 33 | h = m - 1; 34 | } else { 35 | l = m + 1; 36 | } 37 | if (nums[m] === target) { 38 | result[0] = m; 39 | } 40 | } 41 | 42 | l = 0; h = nums.length - 1; 43 | while (l <= h) { 44 | m = ~~((l + h) / 2); 45 | if (nums[m] <= target) { 46 | l = m + 1; 47 | } else { 48 | h = m - 1; 49 | } 50 | if (nums[m] === target) { 51 | result[1] = m; 52 | } 53 | } 54 | 55 | return result; 56 | }; 57 | 58 | -------------------------------------------------------------------------------- /035-search-insert-position/search-insert-position.js: -------------------------------------------------------------------------------- 1 | // Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 2 | // 3 | // You may assume no duplicates in the array. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: [1,3,5,6], 5 9 | // Output: 2 10 | // 11 | // 12 | // Example 2: 13 | // 14 | // 15 | // Input: [1,3,5,6], 2 16 | // Output: 1 17 | // 18 | // 19 | // Example 3: 20 | // 21 | // 22 | // Input: [1,3,5,6], 7 23 | // Output: 4 24 | // 25 | // 26 | // Example 4: 27 | // 28 | // 29 | // Input: [1,3,5,6], 0 30 | // Output: 0 31 | // 32 | // 33 | 34 | 35 | /** 36 | * @param {number[]} nums 37 | * @param {number} target 38 | * @return {number} 39 | */ 40 | var searchInsert = function(nums, target) { 41 | var l = 0, h = nums.length - 1, m; 42 | while (l <= h) { 43 | m = ~~((l + h) / 2); 44 | if (target < nums[m]) { 45 | h = m - 1; 46 | } else if (target > nums[m]) { 47 | l = m + 1; 48 | } else { 49 | return m; 50 | } 51 | } 52 | return l; 53 | }; 54 | 55 | -------------------------------------------------------------------------------- /038-count-and-say/count-and-say.js: -------------------------------------------------------------------------------- 1 | // The count-and-say sequence is the sequence of integers with the first five terms as following: 2 | // 3 | // 4 | // 1. 1 5 | // 2. 11 6 | // 3. 21 7 | // 4. 1211 8 | // 5. 111221 9 | // 10 | // 11 | // 1 is read off as "one 1" or 11. 12 | // 11 is read off as "two 1s" or 21. 13 | // 21 is read off as "one 2, then one 1" or 1211. 14 | // 15 | // Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. 16 | // 17 | // Note: Each term of the sequence of integers will be represented as a string. 18 | // 19 | //   20 | // 21 | // Example 1: 22 | // 23 | // 24 | // Input: 1 25 | // Output: "1" 26 | // 27 | // 28 | // Example 2: 29 | // 30 | // 31 | // Input: 4 32 | // Output: "1211" 33 | // 34 | 35 | 36 | /** 37 | * @param {number} n 38 | * @return {string} 39 | */ 40 | var countAndSay = function(n) { 41 | var say = function(str) { 42 | var s = '', 43 | count = 1; 44 | for (var i = 1, len = str.length;i < len;++i) { 45 | if (str[i] === str[i - 1]) { 46 | ++count; 47 | } else { 48 | s += (String(count) + str[i - 1]); 49 | count = 1; 50 | } 51 | } 52 | s += (String(count) + str[len - 1]); 53 | return s; 54 | }; 55 | 56 | var s = '1'; 57 | for (var i = 1;i < n;++i) { 58 | s = say(s); 59 | } 60 | return s; 61 | }; 62 | 63 | -------------------------------------------------------------------------------- /039-combination-sum/combination-sum.js: -------------------------------------------------------------------------------- 1 | // Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. 2 | // 3 | // The same repeated number may be chosen from candidates unlimited number of times. 4 | // 5 | // Note: 6 | // 7 | // 8 | // All numbers (including target) will be positive integers. 9 | // The solution set must not contain duplicate combinations. 10 | // 11 | // 12 | // Example 1: 13 | // 14 | // 15 | // Input: candidates = [2,3,6,7], target = 7, 16 | // A solution set is: 17 | // [ 18 | // [7], 19 | // [2,2,3] 20 | // ] 21 | // 22 | // 23 | // Example 2: 24 | // 25 | // 26 | // Input: candidates = [2,3,5], target = 8, 27 | // A solution set is: 28 | // [ 29 | //   [2,2,2,2], 30 | //   [2,3,3], 31 | //   [3,5] 32 | // ] 33 | // 34 | // 35 | 36 | 37 | /** 38 | * @param {number[]} candidates 39 | * @param {number} target 40 | * @return {number[][]} 41 | */ 42 | var combinationSum = function(candidates, target) { 43 | var result = [], len = candidates.length; 44 | candidates.sort(function(a,b) { return a - b; }); 45 | 46 | var dfs = function(target, index, path) { 47 | for (var i = index; i < len;++i) { 48 | var temp = target - candidates[i]; 49 | if (temp < 0) { 50 | continue; 51 | } else if (temp === 0) { 52 | result.push(path.concat([candidates[i]])); 53 | } else { 54 | dfs(target - candidates[i], i, path.concat([candidates[i]])); 55 | } 56 | } 57 | }; 58 | dfs(target, 0, []); 59 | 60 | return result; 61 | 62 | }; 63 | 64 | -------------------------------------------------------------------------------- /041-first-missing-positive/first-missing-positive.js: -------------------------------------------------------------------------------- 1 | // Given an unsorted integer array, find the smallest missing positive integer. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: [1,2,0] 7 | // Output: 3 8 | // 9 | // 10 | // Example 2: 11 | // 12 | // 13 | // Input: [3,4,-1,1] 14 | // Output: 2 15 | // 16 | // 17 | // Example 3: 18 | // 19 | // 20 | // Input: [7,8,9,11,12] 21 | // Output: 1 22 | // 23 | // 24 | // Note: 25 | // 26 | // Your algorithm should run in O(n) time and uses constant extra space. 27 | // 28 | 29 | 30 | /** 31 | * @param {number[]} nums 32 | * @return {number} 33 | */ 34 | var firstMissingPositive = function(nums) { 35 | var len = nums.length, 36 | i; 37 | for (i = 0;i < len;) { 38 | if (nums[i] > 0 && nums[i] <= len && nums[i] !== nums[nums[i] - 1]) { 39 | var temp = nums[i]; 40 | nums[i] = nums[nums[i] - 1]; 41 | nums[temp - 1] = temp; 42 | } else { 43 | ++i; 44 | } 45 | } 46 | for (i = 0;i < len;++i) { 47 | if (nums[i] !== i + 1) { 48 | return i + 1; 49 | } 50 | } 51 | return len + 1; 52 | }; 53 | 54 | -------------------------------------------------------------------------------- /042-trapping-rain-water/trapping-rain-water.js: -------------------------------------------------------------------------------- 1 | // Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. 2 | // 3 | // 4 | // The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! 5 | // 6 | // Example: 7 | // 8 | // 9 | // Input: [0,1,0,2,1,0,1,3,2,1,2,1] 10 | // Output: 6 11 | 12 | 13 | /** 14 | * @param {number[]} height 15 | * @return {number} 16 | */ 17 | var trap = function(height) { 18 | var l = 0, h = height.length - 1, 19 | area = 0, secHeight = 0; 20 | while (l < h) { 21 | if (height[l] < height[h]) { 22 | secHeight = Math.max(height[l], secHeight); 23 | area += secHeight - height[l]; 24 | ++l; 25 | } else { 26 | secHeight = Math.max(height[h], secHeight); 27 | area += secHeight - height[h]; 28 | --h; 29 | } 30 | } 31 | return area; 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /043-multiply-strings/multiply-strings.js: -------------------------------------------------------------------------------- 1 | // Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: num1 = "2", num2 = "3" 7 | // Output: "6" 8 | // 9 | // Example 2: 10 | // 11 | // 12 | // Input: num1 = "123", num2 = "456" 13 | // Output: "56088" 14 | // 15 | // 16 | // Note: 17 | // 18 | // 19 | // The length of both num1 and num2 is < 110. 20 | // Both num1 and num2 contain only digits 0-9. 21 | // Both num1 and num2 do not contain any leading zero, except the number 0 itself. 22 | // You must not use any built-in BigInteger library or convert the inputs to integer directly. 23 | // 24 | // 25 | 26 | 27 | /** 28 | * @param {string} num1 29 | * @param {string} num2 30 | * @return {string} 31 | */ 32 | var multiply = function(num1, num2) { 33 | var len1 = num1.length, 34 | len2 = num2.length, 35 | res = new Array(len1 + len2); 36 | res.fill(0); 37 | for (var i = len1 - 1;i >= 0; --i) { 38 | for (var j = len2 - 1;j >= 0; --j) { 39 | var temp = num1[i] * num2[j] + res[i+j+1]; 40 | res[i+j+1] = (temp % 10); 41 | res[i+j] += ~~(temp / 10); 42 | } 43 | } 44 | for (i = 0;i < len1 + len2; ++i) { 45 | if (res[i] !== 0) { 46 | break; 47 | } 48 | } 49 | if (i >= len1 + len2) { 50 | return '0'; 51 | } else { 52 | return res.slice(i).join(''); 53 | } 54 | }; 55 | 56 | -------------------------------------------------------------------------------- /045-jump-game-ii/jump-game-ii.js: -------------------------------------------------------------------------------- 1 | // Given an array of non-negative integers, you are initially positioned at the first index of the array. 2 | // 3 | // Each element in the array represents your maximum jump length at that position. 4 | // 5 | // Your goal is to reach the last index in the minimum number of jumps. 6 | // 7 | // Example: 8 | // 9 | // 10 | // Input: [2,3,1,1,4] 11 | // Output: 2 12 | // Explanation: The minimum number of jumps to reach the last index is 2. 13 | // Jump 1 step from index 0 to 1, then 3 steps to the last index. 14 | // 15 | // Note: 16 | // 17 | // You can assume that you can always reach the last index. 18 | 19 | 20 | /** 21 | * @param {number[]} nums 22 | * @return {number} 23 | */ 24 | var jump = function(nums) { 25 | var result = 0; 26 | for (var i = 0, c = 0, len = nums.length - 1; c < len; ++result) { 27 | var max = 0; 28 | for (var j = i;j <= c; ++j) { 29 | max = Math.max(max, j + nums[j]); 30 | } 31 | i = c + 1; 32 | c = max; 33 | } 34 | return result; 35 | }; 36 | 37 | -------------------------------------------------------------------------------- /046-permutations/permutations.js: -------------------------------------------------------------------------------- 1 | // Given a collection of distinct integers, return all possible permutations. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: [1,2,3] 7 | // Output: 8 | // [ 9 | // [1,2,3], 10 | // [1,3,2], 11 | // [2,1,3], 12 | // [2,3,1], 13 | // [3,1,2], 14 | // [3,2,1] 15 | // ] 16 | // 17 | // 18 | 19 | 20 | /** 21 | * @param {number[]} nums 22 | * @return {number[][]} 23 | */ 24 | var permute = function(nums) { 25 | var len = nums.length, 26 | result = [], 27 | used = new Array(len), 28 | temp = new Array(len); 29 | 30 | var _permute = function(i) { 31 | if (i >= len) { 32 | result.push([].concat(temp)); 33 | return ; 34 | } 35 | for (var j = 0;j < len;++j) { 36 | if (used[j]) { 37 | continue; 38 | } 39 | used[j] = true; 40 | temp[i] = nums[j]; 41 | _permute(i + 1); 42 | used[j] = 0; 43 | } 44 | }; 45 | 46 | _permute(0); 47 | return result; 48 | }; 49 | 50 | -------------------------------------------------------------------------------- /047-permutations-ii/permutations-ii.js: -------------------------------------------------------------------------------- 1 | // Given a collection of numbers that might contain duplicates, return all possible unique permutations. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: [1,1,2] 7 | // Output: 8 | // [ 9 | // [1,1,2], 10 | // [1,2,1], 11 | // [2,1,1] 12 | // ] 13 | // 14 | // 15 | 16 | 17 | /** 18 | * @param {number[]} nums 19 | * @return {number[][]} 20 | */ 21 | var permuteUnique = function(nums) { 22 | var len = nums.length, 23 | result = [], 24 | used = new Array(len), 25 | temp = new Array(len); 26 | 27 | var _permuteUnique = function(i) { 28 | if (i >= len) { 29 | var r = [].concat(temp); 30 | result.push(r); 31 | return ; 32 | } 33 | var map = {}; 34 | for (var j = 0;j < len;++j) { 35 | if (used[j]) { 36 | continue; 37 | } 38 | if (!map[nums[j]]) { 39 | used[j] = true; 40 | temp[i] = nums[j]; 41 | _permuteUnique(i + 1); 42 | used[j] = 0; 43 | map[nums[j]] = 1; 44 | } 45 | } 46 | }; 47 | 48 | _permuteUnique(0); 49 | return result; 50 | }; 51 | 52 | -------------------------------------------------------------------------------- /048-rotate-image/rotate-image.js: -------------------------------------------------------------------------------- 1 | // You are given an n x n 2D matrix representing an image. 2 | // 3 | // Rotate the image by 90 degrees (clockwise). 4 | // 5 | // Note: 6 | // 7 | // You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. 8 | // 9 | // Example 1: 10 | // 11 | // 12 | // Given input matrix = 13 | // [ 14 | // [1,2,3], 15 | // [4,5,6], 16 | // [7,8,9] 17 | // ], 18 | // 19 | // rotate the input matrix in-place such that it becomes: 20 | // [ 21 | // [7,4,1], 22 | // [8,5,2], 23 | // [9,6,3] 24 | // ] 25 | // 26 | // 27 | // Example 2: 28 | // 29 | // 30 | // Given input matrix = 31 | // [ 32 | // [ 5, 1, 9,11], 33 | // [ 2, 4, 8,10], 34 | // [13, 3, 6, 7], 35 | // [15,14,12,16] 36 | // ], 37 | // 38 | // rotate the input matrix in-place such that it becomes: 39 | // [ 40 | // [15,13, 2, 5], 41 | // [14, 3, 4, 1], 42 | // [12, 6, 8, 9], 43 | // [16, 7,10,11] 44 | // ] 45 | // 46 | // 47 | 48 | 49 | /** 50 | * @param {number[][]} matrix 51 | * @return {void} Do not return anything, modify matrix in-place instead. 52 | */ 53 | var rotate = function(matrix) { 54 | matrix = matrix.reverse() 55 | len = matrix.length 56 | for (var i = 1;i < len;++i) { 57 | for (var j = 0;j max) { 27 | max = cur; 28 | } 29 | if (cur < 0) { 30 | cur = 0; 31 | } 32 | } 33 | return max; 34 | }; 35 | -------------------------------------------------------------------------------- /055-jump-game/jump-game.js: -------------------------------------------------------------------------------- 1 | // Given an array of non-negative integers, you are initially positioned at the first index of the array. 2 | // 3 | // Each element in the array represents your maximum jump length at that position. 4 | // 5 | // Determine if you are able to reach the last index. 6 | // 7 | // Example 1: 8 | // 9 | // 10 | // Input: [2,3,1,1,4] 11 | // Output: true 12 | // Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 13 | // 14 | // 15 | // Example 2: 16 | // 17 | // 18 | // Input: [3,2,1,0,4] 19 | // Output: false 20 | // Explanation: You will always arrive at index 3 no matter what. Its maximum 21 | //   jump length is 0, which makes it impossible to reach the last index. 22 | // 23 | // 24 | 25 | 26 | /** 27 | * @param {number[]} nums 28 | * @return {boolean} 29 | */ 30 | var canJump = function(nums) { 31 | var max = 0; 32 | for (var i = 0, len = nums.length; i < len;++i) { 33 | if (max < i) { 34 | return false; 35 | } 36 | max = Math.max(max, i + nums[i]); 37 | } 38 | return true; 39 | }; 40 | -------------------------------------------------------------------------------- /056-merge-intervals/merge-intervals.js: -------------------------------------------------------------------------------- 1 | // Given a collection of intervals, merge all overlapping intervals. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: [[1,3],[2,6],[8,10],[15,18]] 7 | // Output: [[1,6],[8,10],[15,18]] 8 | // Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 9 | // 10 | // 11 | // Example 2: 12 | // 13 | // 14 | // Input: [[1,4],[4,5]] 15 | // Output: [[1,5]] 16 | // Explanation: Intervals [1,4] and [4,5] are considerred overlapping. 17 | // 18 | 19 | 20 | /** 21 | * Definition for an interval. 22 | * function Interval(start, end) { 23 | * this.start = start; 24 | * this.end = end; 25 | * } 26 | */ 27 | /** 28 | * @param {Interval[]} intervals 29 | * @return {Interval[]} 30 | */ 31 | var merge = function(intervals) { 32 | if (intervals.length <= 0) { 33 | return []; 34 | } 35 | intervals.sort(function(a, b) { return a.start - b.start;}); 36 | var result = []; 37 | var current = new Interval(intervals[0].start, intervals[0].end); 38 | for (var i = 1, len = intervals.length; i < len; ++i) { 39 | if (current.end >= intervals[i].start) { 40 | current.end = Math.max(intervals[i].end, current.end); 41 | } else { 42 | result.push(new Interval(current.start, current.end)); 43 | current.start = intervals[i].start; 44 | current.end = intervals[i].end; 45 | } 46 | } 47 | result.push(current); 48 | return result; 49 | }; 50 | -------------------------------------------------------------------------------- /057-insert-interval/insert-interval.js: -------------------------------------------------------------------------------- 1 | // Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). 2 | // 3 | // You may assume that the intervals were initially sorted according to their start times. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: intervals = [[1,3],[6,9]], newInterval = [2,5] 9 | // Output: [[1,5],[6,9]] 10 | // 11 | // 12 | // Example 2: 13 | // 14 | // 15 | // Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] 16 | // Output: [[1,2],[3,10],[12,16]] 17 | // Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. 18 | // 19 | 20 | 21 | /** 22 | * Definition for an interval. 23 | * function Interval(start, end) { 24 | * this.start = start; 25 | * this.end = end; 26 | * } 27 | */ 28 | /** 29 | * @param {Interval[]} intervals 30 | * @param {Interval} newInterval 31 | * @return {Interval[]} 32 | */ 33 | var insert = function(intervals, newInterval) { 34 | var result = []; 35 | var isInserted = false; 36 | var overlap = function(a, b) { 37 | return !(a.end < b.start || a.start > b.end); 38 | } 39 | for (var i = 0, len = intervals.length;i < len;++i) { 40 | if (! overlap(intervals[i], newInterval)) { 41 | if (!isInserted && intervals[i].start > newInterval.end) { 42 | result.push(newInterval); 43 | isInserted = true; 44 | } 45 | result.push(intervals[i]); 46 | } else { 47 | newInterval.start = Math.min(newInterval.start, intervals[i].start); 48 | newInterval.end = Math.max(newInterval.end, intervals[i].end); 49 | } 50 | } 51 | if (!isInserted) { 52 | result.push(newInterval); 53 | } 54 | return result; 55 | }; 56 | -------------------------------------------------------------------------------- /058-length-of-last-word/length-of-last-word.js: -------------------------------------------------------------------------------- 1 | // Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 2 | // 3 | // If the last word does not exist, return 0. 4 | // 5 | // Note: A word is defined as a character sequence consists of non-space characters only. 6 | // 7 | // Example: 8 | // 9 | // Input: "Hello World" 10 | // Output: 5 11 | // 12 | // 13 | 14 | 15 | /** 16 | * @param {string} s 17 | * @return {number} 18 | */ 19 | var lengthOfLastWord = function(s) { 20 | var right = s.length - 1; 21 | while (right >= 0) { 22 | if (s[right] === ' ') { 23 | --right; 24 | } else { 25 | break; 26 | } 27 | } 28 | if (right < 0) { 29 | return 0; 30 | } 31 | var left = right - 1; 32 | while (left >= 0) { 33 | if (s[left] !== ' ') { 34 | --left; 35 | } else { 36 | break; 37 | } 38 | } 39 | return right - Math.max(left, -1); 40 | }; 41 | -------------------------------------------------------------------------------- /059-spiral-matrix-ii/spiral-matrix-ii.js: -------------------------------------------------------------------------------- 1 | // Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: 3 7 | // Output: 8 | // [ 9 | // [ 1, 2, 3 ], 10 | // [ 8, 9, 4 ], 11 | // [ 7, 6, 5 ] 12 | // ] 13 | // 14 | // 15 | 16 | 17 | /** 18 | * @param {number} n 19 | * @return {number[][]} 20 | */ 21 | var generateMatrix = function(n) { 22 | var result = new Array(n); 23 | for (var i = 0;i < n;++i) { 24 | result[i] = new Array(n); 25 | } 26 | i = 1; 27 | var x = 0, y = 0, dir = 0; 28 | var nextPos = function(x, y) { 29 | while (true) { 30 | var newX = x, newY = y; 31 | switch (dir) { 32 | case 0: //right 33 | ++newX; break; 34 | case 1: //down 35 | ++newY; break; 36 | case 2: //left 37 | --newX; break; 38 | case 3: //up 39 | --newY; break; 40 | } 41 | if (newX < 0 || newX >= n || newY < 0 || newY >= n || result[newY][newX]) { 42 | dir = (dir + 1) % 4; 43 | } else { 44 | return [newX, newY]; 45 | } 46 | } 47 | }; 48 | while (i <= n * n) { 49 | result[y][x] = i; 50 | if (i < n * n) { 51 | var pos = nextPos(x, y); 52 | x = pos[0]; 53 | y = pos[1]; 54 | } 55 | ++i; 56 | } 57 | return result; 58 | }; 59 | -------------------------------------------------------------------------------- /061-rotate-list/rotate-list.js: -------------------------------------------------------------------------------- 1 | // Given a linked list, rotate the list to the right by k places, where k is non-negative. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: 1->2->3->4->5->NULL, k = 2 7 | // Output: 4->5->1->2->3->NULL 8 | // Explanation: 9 | // rotate 1 steps to the right: 5->1->2->3->4->NULL 10 | // rotate 2 steps to the right: 4->5->1->2->3->NULL 11 | // 12 | // 13 | // Example 2: 14 | // 15 | // 16 | // Input: 0->1->2->NULL, k = 4 17 | // Output: 2->0->1->NULL 18 | // Explanation: 19 | // rotate 1 steps to the right: 2->0->1->NULL 20 | // rotate 2 steps to the right: 1->2->0->NULL 21 | // rotate 3 steps to the right: 0->1->2->NULL 22 | // rotate 4 steps to the right: 2->0->1->NULL 23 | // 24 | 25 | 26 | /** 27 | * Definition for singly-linked list. 28 | * function ListNode(val) { 29 | * this.val = val; 30 | * this.next = null; 31 | * } 32 | */ 33 | /** 34 | * @param {ListNode} head 35 | * @param {number} k 36 | * @return {ListNode} 37 | */ 38 | var rotateRight = function(head, k) { 39 | var length = 0, tempNode = head; 40 | while (tempNode) { 41 | ++length; 42 | tempNode = tempNode.next; 43 | } 44 | if (length <= 0) { 45 | return head; 46 | } 47 | k %= length; 48 | length -= (k + 1); 49 | if (length < 0) { 50 | return head; 51 | } 52 | tempNode = head; 53 | while (tempNode.next) { 54 | tempNode = tempNode.next; 55 | } 56 | tempNode.next = head; 57 | var shouldBeLastNode = head; 58 | while (length-- > 0) { 59 | shouldBeLastNode = shouldBeLastNode.next; 60 | } 61 | var newHead = shouldBeLastNode.next; 62 | shouldBeLastNode.next = null; 63 | return newHead; 64 | }; 65 | -------------------------------------------------------------------------------- /062-unique-paths/unique-paths.js: -------------------------------------------------------------------------------- 1 | // A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 2 | // 3 | // The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 4 | // 5 | // How many possible unique paths are there? 6 | // 7 | // 8 | // Above is a 7 x 3 grid. How many possible unique paths are there? 9 | // 10 | // Note: m and n will be at most 100. 11 | // 12 | // Example 1: 13 | // 14 | // 15 | // Input: m = 3, n = 2 16 | // Output: 3 17 | // Explanation: 18 | // From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 19 | // 1. Right -> Right -> Down 20 | // 2. Right -> Down -> Right 21 | // 3. Down -> Right -> Right 22 | // 23 | // 24 | // Example 2: 25 | // 26 | // 27 | // Input: m = 7, n = 3 28 | // Output: 28 29 | // 30 | 31 | 32 | /** 33 | * @param {number} m 34 | * @param {number} n 35 | * @return {number} 36 | */ 37 | var uniquePaths = function(m, n) { 38 | var paths = new Array(m); 39 | for (var i = 0;i < m;++i) { 40 | paths[i] = new Array(n); 41 | } 42 | for (i = 0;i < n;++i) { 43 | paths[0][i] = 1; 44 | } 45 | for (i = 1;i < m;++i) { 46 | paths[i][0] = 1; 47 | } 48 | var j; 49 | for (i = 1;i < m;++i) { 50 | for (j = 1;j < n;++j) { 51 | paths[i][j] = paths[i-1][j] + paths[i][j-1]; 52 | } 53 | } 54 | return paths[m-1][n-1]; 55 | }; 56 | -------------------------------------------------------------------------------- /064-minimum-path-sum/minimum-path-sum.js: -------------------------------------------------------------------------------- 1 | // Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 2 | // 3 | // Note: You can only move either down or right at any point in time. 4 | // 5 | // Example: 6 | // 7 | // 8 | // Input: 9 | // [ 10 | //   [1,3,1], 11 | // [1,5,1], 12 | // [4,2,1] 13 | // ] 14 | // Output: 7 15 | // Explanation: Because the path 1→3→1→1→1 minimizes the sum. 16 | // 17 | // 18 | 19 | 20 | /** 21 | * @param {number[][]} grid 22 | * @return {number} 23 | */ 24 | var minPathSum = function(grid) { 25 | var m = grid.length, 26 | n = grid[0].length; 27 | 28 | var paths = new Array(m); 29 | for (var i = 0;i < m;++i) { 30 | paths[i] = new Array(n); 31 | } 32 | paths[0][0] = grid[0][0]; 33 | for (i = 1;i < n;++i) { 34 | paths[0][i] = grid[0][i] + paths[0][i - 1]; 35 | } 36 | for (i = 1;i < m;++i) { 37 | paths[i][0] = grid[i][0] + paths[i-1][0]; 38 | } 39 | var j; 40 | for (i = 1;i < m;++i) { 41 | for (j = 1;j < n;++j) { 42 | paths[i][j] = Math.min(paths[i-1][j], paths[i][j-1]) + grid[i][j]; 43 | } 44 | } 45 | return paths[m-1][n-1]; 46 | }; 47 | -------------------------------------------------------------------------------- /066-plus-one/plus-one.js: -------------------------------------------------------------------------------- 1 | // Given a non-empty array of digits representing a non-negative integer, plus one to the integer. 2 | // 3 | // The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. 4 | // 5 | // You may assume the integer does not contain any leading zero, except the number 0 itself. 6 | // 7 | // Example 1: 8 | // 9 | // 10 | // Input: [1,2,3] 11 | // Output: [1,2,4] 12 | // Explanation: The array represents the integer 123. 13 | // 14 | // 15 | // Example 2: 16 | // 17 | // 18 | // Input: [4,3,2,1] 19 | // Output: [4,3,2,2] 20 | // Explanation: The array represents the integer 4321. 21 | // 22 | // 23 | 24 | 25 | /** 26 | * @param {number[]} digits 27 | * @return {number[]} 28 | */ 29 | var plusOne = function(digits) { 30 | var i = digits.length - 1; 31 | while(i >= 0) 32 | { 33 | if(digits[i] == 9) 34 | { 35 | digits[i] = 0; 36 | i--; 37 | // continue loop because we had to "carry" the 1 38 | } 39 | else 40 | { 41 | digits[i] = digits[i] + 1; 42 | i--; 43 | break; // stop the while loop because no "carry" needed 44 | } 45 | } 46 | if(digits[0] === 0) { 47 | digits.unshift(1); 48 | } 49 | return digits; 50 | }; 51 | -------------------------------------------------------------------------------- /067-add-binary/add-binary.js: -------------------------------------------------------------------------------- 1 | // Given two binary strings, return their sum (also a binary string). 2 | // 3 | // The input strings are both non-empty and contains only characters 1 or 0. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: a = "11", b = "1" 9 | // Output: "100" 10 | // 11 | // Example 2: 12 | // 13 | // 14 | // Input: a = "1010", b = "1011" 15 | // Output: "10101" 16 | // 17 | 18 | 19 | /** 20 | * @param {string} a 21 | * @param {string} b 22 | * @return {string} 23 | */ 24 | var addBinary = function(a, b) { 25 | var aLen = a.length, 26 | bLen = b.length, 27 | len = Math.max(aLen, bLen), 28 | results = new Array(len), 29 | c = 0; 30 | --aLen, --bLen, --len; 31 | var i, j; 32 | while (aLen >= 0 || bLen >= 0) { 33 | i = aLen >= 0 ? +a[aLen] : 0; 34 | j = bLen >= 0 ? +b[bLen] : 0; 35 | results[len] = i ^ j ^ c; 36 | c = i & j | c & (i ^ j); 37 | --aLen, --bLen, --len; 38 | } 39 | if (c) { 40 | results.unshift(1); 41 | } 42 | return results.join(''); 43 | }; 44 | -------------------------------------------------------------------------------- /069-sqrtx/sqrtx.js: -------------------------------------------------------------------------------- 1 | // Implement int sqrt(int x). 2 | // 3 | // Compute and return the square root of x, where x is guaranteed to be a non-negative integer. 4 | // 5 | // Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. 6 | // 7 | // Example 1: 8 | // 9 | // 10 | // Input: 4 11 | // Output: 2 12 | // 13 | // 14 | // Example 2: 15 | // 16 | // 17 | // Input: 8 18 | // Output: 2 19 | // Explanation: The square root of 8 is 2.82842..., and since 20 | //   the decimal part is truncated, 2 is returned. 21 | // 22 | // 23 | 24 | 25 | /** 26 | * @param {number} x 27 | * @return {number} 28 | */ 29 | var mySqrt = function(x) { 30 | var _is = function(_x) { 31 | return ((_x * _x) <= x && (_x + 1) * (_x + 1) > x); 32 | }; 33 | 34 | var low = 0, high = x; 35 | while (low <= high) { 36 | var mid = Math.floor((low + high) / 2); 37 | if (_is(mid)) { 38 | return mid; 39 | } else if (mid * mid < x) { 40 | low = mid + 1; 41 | } else { 42 | high = mid - 1; 43 | } 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /070-climbing-stairs/climbing-stairs.js: -------------------------------------------------------------------------------- 1 | // You are climbing a stair case. It takes n steps to reach to the top. 2 | // 3 | // Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 4 | // 5 | // Note: Given n will be a positive integer. 6 | // 7 | // Example 1: 8 | // 9 | // 10 | // Input: 2 11 | // Output: 2 12 | // Explanation: There are two ways to climb to the top. 13 | // 1. 1 step + 1 step 14 | // 2. 2 steps 15 | // 16 | // 17 | // Example 2: 18 | // 19 | // 20 | // Input: 3 21 | // Output: 3 22 | // Explanation: There are three ways to climb to the top. 23 | // 1. 1 step + 1 step + 1 step 24 | // 2. 1 step + 2 steps 25 | // 3. 2 steps + 1 step 26 | // 27 | // 28 | 29 | 30 | /** 31 | * @param {number} n 32 | * @return {number} 33 | */ 34 | var climbStairs = function(n) { 35 | var a = 1, b = 1; 36 | for (var i = 1;i < n; ++i) { 37 | b = a + b; 38 | a = b - a; 39 | } 40 | return b; 41 | }; 42 | -------------------------------------------------------------------------------- /071-simplify-path/simplify-path.js: -------------------------------------------------------------------------------- 1 | // Given an absolute path for a file (Unix-style), simplify it. 2 | // 3 | // For example, 4 | // path = "/home/", => "/home" 5 | // path = "/a/./b/../../c/", => "/c" 6 | // 7 | // Corner Cases: 8 | // 9 | // 10 | // Did you consider the case where path = "/../"? 11 | // In this case, you should return "/". 12 | // Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". 13 | // In this case, you should ignore redundant slashes and return "/home/foo". 14 | // 15 | // 16 | 17 | 18 | /** 19 | * @param {string} path 20 | * @return {string} 21 | */ 22 | var simplifyPath = function(path) { 23 | var pathArr = path.split('/'), 24 | stack = [], 25 | len = pathArr.length; 26 | 27 | for (var i = 0;i < len; ++i) { 28 | if (!pathArr[i] || pathArr[i] === '.') { 29 | continue; 30 | } 31 | if (pathArr[i] === '..') { 32 | if (stack.length) { 33 | stack.pop(); 34 | } 35 | } else { 36 | stack.push(pathArr[i]); 37 | } 38 | } 39 | return '/' + stack.join('/'); 40 | }; 41 | -------------------------------------------------------------------------------- /072-edit-distance/edit-distance.js: -------------------------------------------------------------------------------- 1 | // Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. 2 | // 3 | // You have the following 3 operations permitted on a word: 4 | // 5 | // 6 | // Insert a character 7 | // Delete a character 8 | // Replace a character 9 | // 10 | // 11 | // Example 1: 12 | // 13 | // 14 | // Input: word1 = "horse", word2 = "ros" 15 | // Output: 3 16 | // Explanation: 17 | // horse -> rorse (replace 'h' with 'r') 18 | // rorse -> rose (remove 'r') 19 | // rose -> ros (remove 'e') 20 | // 21 | // 22 | // Example 2: 23 | // 24 | // 25 | // Input: word1 = "intention", word2 = "execution" 26 | // Output: 5 27 | // Explanation: 28 | // intention -> inention (remove 't') 29 | // inention -> enention (replace 'i' with 'e') 30 | // enention -> exention (replace 'n' with 'x') 31 | // exention -> exection (replace 'n' with 'c') 32 | // exection -> execution (insert 'u') 33 | // 34 | // 35 | 36 | 37 | /** 38 | * @param {string} word1 39 | * @param {string} word2 40 | * @return {number} 41 | */ 42 | var minDistance = function(word1, word2) { 43 | var len1 = word1.length, len2 = word2.length, 44 | dp = new Array(len1 + 1); 45 | for (var i = 0;i < len1 + 1; ++i) { 46 | dp[i] = new Array(len2 + 1); 47 | dp[i][0] = i; 48 | } 49 | for (i = 0;i < len2 + 1;++i) { 50 | dp[0][i] = i; 51 | } 52 | var j; 53 | for (i = 1;i < len1 + 1; ++i) { 54 | for (j = 1;j < len2 + 1; ++j) { 55 | if (word1[i-1] === word2[j-1]) { 56 | dp[i][j] = dp[i-1][j-1]; 57 | } else { 58 | dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) + 1; 59 | } 60 | } 61 | } 62 | return dp[len1][len2]; 63 | }; 64 | -------------------------------------------------------------------------------- /074-search-a-2d-matrix/search-a-2d-matrix.js: -------------------------------------------------------------------------------- 1 | // Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 2 | // 3 | // 4 | // Integers in each row are sorted from left to right. 5 | // The first integer of each row is greater than the last integer of the previous row. 6 | // 7 | // 8 | // Example 1: 9 | // 10 | // 11 | // Input: 12 | // matrix = [ 13 | // [1, 3, 5, 7], 14 | // [10, 11, 16, 20], 15 | // [23, 30, 34, 50] 16 | // ] 17 | // target = 3 18 | // Output: true 19 | // 20 | // 21 | // Example 2: 22 | // 23 | // 24 | // Input: 25 | // matrix = [ 26 | // [1, 3, 5, 7], 27 | // [10, 11, 16, 20], 28 | // [23, 30, 34, 50] 29 | // ] 30 | // target = 13 31 | // Output: false 32 | // 33 | 34 | 35 | /** 36 | * @param {number[][]} matrix 37 | * @param {number} target 38 | * @return {boolean} 39 | */ 40 | var searchMatrix = function(matrix, target) { 41 | var m = matrix.length, n = matrix[0].length, 42 | len = m * n; 43 | var _get = function(index) { 44 | var x = index % n, y = Math.floor(index / n); 45 | return matrix[y][x]; 46 | }; 47 | 48 | var low = 0, high = len - 1; 49 | while (low <= high) { 50 | var mid = ~~((low + high) / 2), 51 | value = _get(mid); 52 | if (value === target) { 53 | return true; 54 | } else if (value < target) { 55 | low = mid + 1; 56 | } else { 57 | high = mid - 1; 58 | } 59 | } 60 | return false; 61 | }; 62 | -------------------------------------------------------------------------------- /075-sort-colors/sort-colors.js: -------------------------------------------------------------------------------- 1 | // Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. 2 | // 3 | // Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 4 | // 5 | // Note: You are not suppose to use the library's sort function for this problem. 6 | // 7 | // Example: 8 | // 9 | // 10 | // Input: [2,0,2,1,1,0] 11 | // Output: [0,0,1,1,2,2] 12 | // 13 | // Follow up: 14 | // 15 | // 16 | // A rather straight forward solution is a two-pass algorithm using counting sort. 17 | // First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. 18 | // Could you come up with a one-pass algorithm using only constant space? 19 | // 20 | // 21 | 22 | 23 | /** 24 | * @param {number[]} nums 25 | * @return {void} Do not return anything, modify nums in-place instead. 26 | */ 27 | var sortColors = function(nums) { 28 | var colors = [0, 0, 0], 29 | len = nums.length; 30 | nums.forEach(function(v) { 31 | colors[v]++; 32 | }); 33 | var i = 0, j = 0; 34 | for (;i < len; ++i) { 35 | var c = 0; 36 | while (colors[j] <= 0) { 37 | ++j; 38 | } 39 | c = j; 40 | --colors[j]; 41 | nums[i] = c; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /076-minimum-window-substring/minimum-window-substring.js: -------------------------------------------------------------------------------- 1 | // Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: S = "ADOBECODEBANC", T = "ABC" 7 | // Output: "BANC" 8 | // 9 | // 10 | // Note: 11 | // 12 | // 13 | // If there is no such window in S that covers all characters in T, return the empty string "". 14 | // If there is such window, you are guaranteed that there will always be only one unique minimum window in S. 15 | // 16 | // 17 | 18 | 19 | //Can't figure out by myself 20 | //Learnt from the url below: 21 | //https://leetcode.com/discuss/72701/here-10-line-template-that-can-solve-most-substring-problems 22 | /** 23 | * @param {string} s 24 | * @param {string} t 25 | * @return {string} 26 | */ 27 | var minWindow = function(s, t) { 28 | var map = new Array(128), 29 | counter = t.length, 30 | begin = 0, 31 | end = 0, 32 | d = Number.MAX_SAFE_INTEGER, 33 | head = 0; 34 | [].forEach.call(t, function(v) { 35 | var code = v.charCodeAt(0); 36 | map[code] = map[code] ? map[code] + 1 : 1; 37 | }); 38 | while (end < s.length) { 39 | if (map[s.charCodeAt(end++)]-- > 0) { 40 | counter--; 41 | } 42 | while (counter === 0) { 43 | if (end - begin < d) { 44 | d = end - (head=begin); 45 | } 46 | if (map[s.charCodeAt(begin++)]++ === 0) { 47 | counter++; 48 | } 49 | } 50 | } 51 | return d === Number.MAX_SAFE_INTEGER ? '' : s.substr(head, d); 52 | }; 53 | -------------------------------------------------------------------------------- /077-combinations/combinations.js: -------------------------------------------------------------------------------- 1 | // Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: n = 4, k = 2 7 | // Output: 8 | // [ 9 | // [2,4], 10 | // [3,4], 11 | // [2,3], 12 | // [1,2], 13 | // [1,3], 14 | // [1,4], 15 | // ] 16 | // 17 | // 18 | 19 | 20 | /** 21 | * @param {number} n 22 | * @param {number} k 23 | * @return {number[][]} 24 | */ 25 | var combine = function(n, k) { 26 | var result = [], 27 | current = [], 28 | used = []; 29 | 30 | var _r = function(dep, len) { 31 | if (len >= k) { 32 | result.push([].concat(current)); 33 | return ; 34 | } 35 | for (var i = dep;i <= n;++i) { 36 | if (!used[i]) { 37 | used[i] = true; 38 | current.push(i); 39 | _r(i+1, len+1); 40 | current.pop(); 41 | used[i] = false; 42 | } 43 | } 44 | }; 45 | _r(1, 0); 46 | return result; 47 | }; 48 | -------------------------------------------------------------------------------- /078-subsets/subsets.js: -------------------------------------------------------------------------------- 1 | // Given a set of distinct integers, nums, return all possible subsets (the power set). 2 | // 3 | // Note: The solution set must not contain duplicate subsets. 4 | // 5 | // Example: 6 | // 7 | // 8 | // Input: nums = [1,2,3] 9 | // Output: 10 | // [ 11 | // [3], 12 | //   [1], 13 | //   [2], 14 | //   [1,2,3], 15 | //   [1,3], 16 | //   [2,3], 17 | //   [1,2], 18 | //   [] 19 | // ] 20 | // 21 | 22 | 23 | /** 24 | * @param {number[]} nums 25 | * @return {number[][]} 26 | */ 27 | var subsets = function(nums) { 28 | var result = [], 29 | numsLen = nums.length; 30 | nums.sort(function(a, b) { 31 | return a - b; 32 | }); 33 | var combine = function(n, k) { 34 | var current = [], 35 | used = []; 36 | 37 | var _r = function(dep, len) { 38 | if (len >= k) { 39 | result.push([].concat(current)); 40 | return ; 41 | } 42 | for (var i = dep;i < numsLen;++i) { 43 | if (!used[i]) { 44 | used[i] = true; 45 | current.push(nums[i]); 46 | _r(i+1, len+1); 47 | current.pop(); 48 | used[i] = false; 49 | } 50 | } 51 | }; 52 | _r(0, 0); 53 | }; 54 | for (var i = 0, len = nums.length;i <= len;++i) { 55 | combine(1, i); 56 | } 57 | return result; 58 | }; 59 | -------------------------------------------------------------------------------- /079-word-search/word-search.js: -------------------------------------------------------------------------------- 1 | // Given a 2D board and a word, find if the word exists in the grid. 2 | // 3 | // The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. 4 | // 5 | // Example: 6 | // 7 | // 8 | // board = 9 | // [ 10 | // ['A','B','C','E'], 11 | // ['S','F','C','S'], 12 | // ['A','D','E','E'] 13 | // ] 14 | // 15 | // Given word = "ABCCED", return true. 16 | // Given word = "SEE", return true. 17 | // Given word = "ABCB", return false. 18 | // 19 | // 20 | 21 | 22 | /** 23 | * @param {character[][]} board 24 | * @param {string} word 25 | * @return {boolean} 26 | */ 27 | var exist = function(board, word) { 28 | var m = board.length, 29 | n = board[0].length, 30 | len = word.length; 31 | if (len <= 0) { 32 | return false; 33 | } 34 | var isVisit = new Array(m * n); 35 | var search = function(i, j, index) { 36 | if (i < 0 || i >= m || j < 0 || j >= n || isVisit[i*n+j] || 37 | board[i][j] !== word[index]) { 38 | return false; 39 | } 40 | if (index === len - 1) { 41 | return true; 42 | } 43 | isVisit[i*n+j] = true; 44 | var r = search(i-1, j, index+1) || search(i+1, j, index+1) || search(i, j-1, index+1) || search(i, j+1, index+1); 45 | isVisit[i*n+j] = false; 46 | return r; 47 | }; 48 | for (var i = 0;i < m;++i) { 49 | for (var j = 0;j < n;++j) { 50 | if (search(i, j, 0)) { 51 | return true; 52 | } 53 | } 54 | } 55 | return false; 56 | }; 57 | -------------------------------------------------------------------------------- /081-search-in-rotated-sorted-array-ii/search-in-rotated-sorted-array-ii.js: -------------------------------------------------------------------------------- 1 | // Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 2 | // 3 | // (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). 4 | // 5 | // You are given a target value to search. If found in the array return true, otherwise return false. 6 | // 7 | // Example 1: 8 | // 9 | // 10 | // Input: nums = [2,5,6,0,0,1,2], target = 0 11 | // Output: true 12 | // 13 | // 14 | // Example 2: 15 | // 16 | // 17 | // Input: nums = [2,5,6,0,0,1,2], target = 3 18 | // Output: false 19 | // 20 | // Follow up: 21 | // 22 | // 23 | // This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates. 24 | // Would this affect the run-time complexity? How and why? 25 | // 26 | // 27 | 28 | 29 | /** 30 | * @param {number[]} nums 31 | * @param {number} target 32 | * @return {boolean} 33 | */ 34 | var search = function(nums, target) { 35 | var l = 0, h = nums.length - 1, m; 36 | while (l <= h) { 37 | m = ~~((l + h) / 2); 38 | if(nums[m] === target) { 39 | return true; 40 | } 41 | if(nums[l] < nums[m]){ 42 | if(target < nums[l] || target > nums[m]){ 43 | l = m + 1; 44 | }else{ 45 | h = m - 1; 46 | } 47 | } else if(nums[l] > nums[m]){ 48 | if(target < nums[m] || target > nums[h]){ 49 | h = m -1; 50 | }else{ 51 | l = m + 1; 52 | } 53 | }else{ 54 | ++l; 55 | } 56 | } 57 | return false; 58 | }; 59 | -------------------------------------------------------------------------------- /082-remove-duplicates-from-sorted-list-ii/remove-duplicates-from-sorted-list-ii.js: -------------------------------------------------------------------------------- 1 | // Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: 1->2->3->3->4->4->5 7 | // Output: 1->2->5 8 | // 9 | // 10 | // Example 2: 11 | // 12 | // 13 | // Input: 1->1->1->2->3 14 | // Output: 2->3 15 | // 16 | // 17 | 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 deleteDuplicates = function(head) { 31 | if (!head) { 32 | return head; 33 | } 34 | var node = new ListNode(); 35 | node.next = head; 36 | var newHead = node, i = node.next, j = i.next; 37 | 38 | while (i && j) { 39 | while (j && i.val === j.val) { 40 | j = j.next; 41 | } 42 | if (j !== i.next) { 43 | i = j; 44 | node.next = i; 45 | } else { 46 | i = i.next; 47 | node = node.next; 48 | } 49 | j = i ? i.next : null; 50 | } 51 | return newHead.next; 52 | }; 53 | -------------------------------------------------------------------------------- /083-remove-duplicates-from-sorted-list/remove-duplicates-from-sorted-list.js: -------------------------------------------------------------------------------- 1 | // Given a sorted linked list, delete all duplicates such that each element appear only once. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: 1->1->2 7 | // Output: 1->2 8 | // 9 | // 10 | // Example 2: 11 | // 12 | // 13 | // Input: 1->1->2->3->3 14 | // Output: 1->2->3 15 | // 16 | 17 | 18 | /** 19 | * Definition for singly-linked list. 20 | * function ListNode(val) { 21 | * this.val = val; 22 | * this.next = null; 23 | * } 24 | */ 25 | /** 26 | * @param {ListNode} head 27 | * @return {ListNode} 28 | */ 29 | var deleteDuplicates = function(head) { 30 | if (!head) { 31 | return head; 32 | } 33 | var node = head.next, last = head; 34 | while (node) { 35 | if (node.val === last.val) { 36 | last.next = node.next; 37 | } else { 38 | last = node; 39 | } 40 | node = node.next; 41 | } 42 | return head; 43 | }; 44 | -------------------------------------------------------------------------------- /084-largest-rectangle-in-histogram/largest-rectangle-in-histogram.js: -------------------------------------------------------------------------------- 1 | // Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. 2 | // 3 | // 4 | // Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. 5 | // 6 | //   7 | // 8 | // 9 | // The largest rectangle is shown in the shaded area, which has area = 10 unit. 10 | // 11 | //   12 | // 13 | // Example: 14 | // 15 | // 16 | // Input: [2,1,5,6,2,3] 17 | // Output: 10 18 | // 19 | // 20 | 21 | 22 | /** 23 | * @param {number[]} heights 24 | * @return {number} 25 | */ 26 | var largestRectangleArea = function(heights) { 27 | var len = heights.length; 28 | if (len <= 0) { 29 | return 0; 30 | } 31 | heights.push(0); 32 | ++len; 33 | 34 | var max = heights[0]; 35 | for (var i = 1;i < len;++i) { 36 | if (heights[i-1] > heights[i]) { 37 | var j = i - 1, width = 0; 38 | while (j >= 0 && heights[j] > heights[i]) { 39 | ++width; 40 | max = Math.max(max, width * heights[j]); 41 | heights[j--] = heights[i]; 42 | } 43 | } 44 | } 45 | return max; 46 | }; 47 | -------------------------------------------------------------------------------- /085-maximal-rectangle/maximal-rectangle.js: -------------------------------------------------------------------------------- 1 | // Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: 7 | // [ 8 | // ["1","0","1","0","0"], 9 | // ["1","0","1","1","1"], 10 | // ["1","1","1","1","1"], 11 | // ["1","0","0","1","0"] 12 | // ] 13 | // Output: 6 14 | // 15 | // 16 | 17 | 18 | /** 19 | * @param {character[][]} matrix 20 | * @return {number} 21 | */ 22 | var maximalRectangle = function(matrix) { 23 | if (!matrix || !matrix[0]) { 24 | return 0; 25 | } 26 | var n = matrix[0].length; 27 | var height = new Array(n+1); 28 | for (var i = 0;i < n+1;++i) { 29 | height[i] = 0; 30 | } 31 | var ans = 0; 32 | for (i = 0;i < matrix.length;++i) { 33 | for (var j = 0;j < n;++j) { 34 | height[j] = matrix[i][j] === '1' ? height[j]+1 : 0; 35 | } 36 | var stack = [-1]; 37 | for (j = 0;j < n+1; ++j) { 38 | while (height[j] < height[stack[stack.length-1] + (stack[stack.length-1] >= 0 ? 0 : height.length)]) { 39 | var h = height[stack.pop()]; 40 | var w = j - 1 - stack[stack.length-1]; 41 | ans = Math.max(ans, h * w); 42 | } 43 | stack.push(j); 44 | } 45 | } 46 | return ans; 47 | }; 48 | 49 | -------------------------------------------------------------------------------- /086-partition-list/partition-list.js: -------------------------------------------------------------------------------- 1 | // Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 2 | // 3 | // You should preserve the original relative order of the nodes in each of the two partitions. 4 | // 5 | // Example: 6 | // 7 | // 8 | // Input: head = 1->4->3->2->5->2, x = 3 9 | // Output: 1->2->2->4->3->5 10 | // 11 | // 12 | 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} head 23 | * @param {number} x 24 | * @return {ListNode} 25 | */ 26 | var partition = function(head, x) { 27 | var newHead = new ListNode(-1); 28 | newHead.next = head; 29 | var node = newHead; 30 | while (node && node.next && node.next.val < x) { 31 | node = node.next; 32 | } 33 | if (!node || !node.next) { 34 | return newHead.next; 35 | } 36 | var flag = node; 37 | while (node && node.next) { 38 | if (node.next.val < x) { 39 | var temp = node.next; 40 | node.next = temp.next; 41 | temp.next = flag.next; 42 | flag.next = temp; 43 | flag = flag.next; 44 | } else { 45 | node = node.next; 46 | } 47 | } 48 | return newHead.next; 49 | }; 50 | -------------------------------------------------------------------------------- /088-merge-sorted-array/merge-sorted-array.js: -------------------------------------------------------------------------------- 1 | // Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 2 | // 3 | // Note: 4 | // 5 | // 6 | // The number of elements initialized in nums1 and nums2 are m and n respectively. 7 | // You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. 8 | // 9 | // 10 | // Example: 11 | // 12 | // 13 | // Input: 14 | // nums1 = [1,2,3,0,0,0], m = 3 15 | // nums2 = [2,5,6], n = 3 16 | // 17 | // Output: [1,2,2,3,5,6] 18 | // 19 | // 20 | 21 | 22 | /** 23 | * @param {number[]} nums1 24 | * @param {number} m 25 | * @param {number[]} nums2 26 | * @param {number} n 27 | * @return {void} Do not return anything, modify nums1 in-place instead. 28 | */ 29 | 30 | var merge = function(nums1, m, nums2, n) { 31 | var i = m - 1, j = n -1, k = m + n - 1 32 | while (i >= 0 && j >= 0) { 33 | nums1[k--] = nums1[i] < nums2[j] ? nums2[j--] : nums1[i--] 34 | } 35 | while (j >= 0) { 36 | nums1[k--] = nums2[j--] 37 | } 38 | }; 39 | 40 | -------------------------------------------------------------------------------- /089-gray-code/gray-code.js: -------------------------------------------------------------------------------- 1 | // The gray code is a binary numeral system where two successive values differ in only one bit. 2 | // 3 | // Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: 2 9 | // Output: [0,1,3,2] 10 | // Explanation: 11 | // 00 - 0 12 | // 01 - 1 13 | // 11 - 3 14 | // 10 - 2 15 | // 16 | // For a given n, a gray code sequence may not be uniquely defined. 17 | // For example, [0,2,3,1] is also a valid gray code sequence. 18 | // 19 | // 00 - 0 20 | // 10 - 2 21 | // 11 - 3 22 | // 01 - 1 23 | // 24 | // 25 | // Example 2: 26 | // 27 | // 28 | // Input: 0 29 | // Output: [0] 30 | // Explanation: We define the gray code sequence to begin with 0. 31 | //   A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1. 32 | //   Therefore, for n = 0 the gray code sequence is [0]. 33 | // 34 | // 35 | 36 | 37 | 38 | /** 39 | * @param {number} n 40 | * @return {number[]} 41 | */ 42 | 43 | var grayCode = function(n) { 44 | var showup = new Array(1 << n) 45 | var result = [0] 46 | showup[0] = 1 47 | var current = 0 48 | while (result.length < (1 << n)) { 49 | for (var i = 0;i < n;++i) { 50 | var mask = 1 << i 51 | var new_value = current ^ mask 52 | if (!showup[new_value]) { 53 | result.push(new_value) 54 | showup[new_value] = 1 55 | current = new_value 56 | break 57 | } 58 | } 59 | } 60 | return result 61 | } 62 | -------------------------------------------------------------------------------- /090-subsets-ii/subsets-ii.js: -------------------------------------------------------------------------------- 1 | // Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). 2 | // 3 | // Note: The solution set must not contain duplicate subsets. 4 | // 5 | // Example: 6 | // 7 | // 8 | // Input: [1,2,2] 9 | // Output: 10 | // [ 11 | // [2], 12 | // [1], 13 | // [1,2,2], 14 | // [2,2], 15 | // [1,2], 16 | // [] 17 | // ] 18 | // 19 | 20 | 21 | 22 | /** 23 | * @param {number[]} nums 24 | * @return {number[][]} 25 | */ 26 | 27 | var subsetsWithDup = function(nums) { 28 | nums.sort() 29 | var result = [] 30 | var map = {} 31 | var current = [] 32 | var backtrack = function(n) { 33 | debugger 34 | if (n === nums.length) { 35 | if (!map[current.toString()]) { 36 | map[current.toString()] = 1 37 | result.push(Array.prototype.slice.call(current)) 38 | } 39 | return 40 | } 41 | backtrack(n+1) 42 | current.push(nums[n]) 43 | backtrack(n+1) 44 | current.pop() 45 | } 46 | backtrack(0) 47 | return result 48 | } 49 | -------------------------------------------------------------------------------- /091-decode-ways/decode-ways.js: -------------------------------------------------------------------------------- 1 | // A message containing letters from A-Z is being encoded to numbers using the following mapping: 2 | // 3 | // 4 | // 'A' -> 1 5 | // 'B' -> 2 6 | // ... 7 | // 'Z' -> 26 8 | // 9 | // 10 | // Given a non-empty string containing only digits, determine the total number of ways to decode it. 11 | // 12 | // Example 1: 13 | // 14 | // 15 | // Input: "12" 16 | // Output: 2 17 | // Explanation: It could be decoded as "AB" (1 2) or "L" (12). 18 | // 19 | // 20 | // Example 2: 21 | // 22 | // 23 | // Input: "226" 24 | // Output: 3 25 | // Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). 26 | // 27 | 28 | 29 | 30 | /** 31 | * @param {string} s 32 | * @return {number} 33 | */ 34 | 35 | var numDecodings = function(s) { 36 | if (s === '' || s[0] === '0') return 0 37 | var pre = 0, old = 0, n = 1 38 | for (var i = 0;i < s.length;++i) { 39 | var current = ~~s[i] 40 | var cur = current !== 0 ? n : 0 41 | if (pre !== 0 && pre*10+current < 27) { 42 | cur += old 43 | } 44 | old = n 45 | n = cur 46 | pre = current 47 | } 48 | return n 49 | } 50 | -------------------------------------------------------------------------------- /092-reverse-linked-list-ii/reverse-linked-list-ii.js: -------------------------------------------------------------------------------- 1 | // Reverse a linked list from position m to n. Do it in one-pass. 2 | // 3 | // Note: 1 ≤ m ≤ n ≤ length of list. 4 | // 5 | // Example: 6 | // 7 | // 8 | // Input: 1->2->3->4->5->NULL, m = 2, n = 4 9 | // Output: 1->4->3->2->5->NULL 10 | // 11 | // 12 | 13 | 14 | /** 15 | * Definition for singly-linked list. 16 | * function ListNode(val) { 17 | * this.val = val; 18 | * this.next = null; 19 | * } 20 | */ 21 | 22 | /** 23 | * @param {ListNode} head 24 | * @param {number} m 25 | * @param {number} n 26 | * @return {ListNode} 27 | */ 28 | 29 | var reverseBetween = function(head, m, n) { 30 | var first = new ListNode() 31 | first.next = head 32 | var cur = first 33 | for (var i = 1;i < m;++i) { 34 | cur = cur.next 35 | } 36 | var temp = cur.next 37 | for (var i = 0;i < n-m;++i) { 38 | var temp_next = temp.next 39 | temp.next = temp_next.next 40 | temp_next.next = cur.next 41 | cur.next = temp_next 42 | } 43 | return first.next 44 | }; 45 | 46 | -------------------------------------------------------------------------------- /093-restore-ip-addresses/restore-ip-addresses.js: -------------------------------------------------------------------------------- 1 | // Given a string containing only digits, restore it by returning all possible valid IP address combinations. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: "25525511135" 7 | // Output: ["255.255.11.135", "255.255.111.35"] 8 | // 9 | // 10 | 11 | 12 | /** 13 | * @param {string} s 14 | * @return {string[]} 15 | */ 16 | var restoreIpAddresses = function(s) { 17 | var result = [] 18 | var cur = [] 19 | var func = function(s, count) { 20 | if (s.length >= count) { 21 | var substr = s.substr(0, count) 22 | if ((substr.length > 1 && substr[0] === '0') || ~~substr > 255) { 23 | return 24 | } 25 | cur.push(substr) 26 | backtrack(s.substr(count)) 27 | cur.pop() 28 | } 29 | } 30 | var backtrack = function(s) { 31 | if (cur.length === 4) { 32 | if (s.length === 0) { 33 | result.push(cur.join('.')) 34 | } 35 | return 36 | } 37 | func(s,1) 38 | func(s,2) 39 | func(s,3) 40 | } 41 | backtrack(s) 42 | return result 43 | }; 44 | 45 | -------------------------------------------------------------------------------- /094-binary-tree-inorder-traversal/binary-tree-inorder-traversal.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, return the inorder traversal of its nodes' values. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: [1,null,2,3] 7 | // 1 8 | // \ 9 | // 2 10 | // / 11 | // 3 12 | // 13 | // Output: [1,3,2] 14 | // 15 | // Follow up: Recursive solution is trivial, could you do it iteratively? 16 | // 17 | 18 | 19 | /** 20 | * Definition for a binary tree node. 21 | * function TreeNode(val) { 22 | * this.val = val; 23 | * this.left = this.right = null; 24 | * } 25 | */ 26 | /** 27 | * @param {TreeNode} root 28 | * @return {number[]} 29 | */ 30 | var inorderTraversal = function(root) { 31 | if (!root) return [] 32 | var stack = [] 33 | var result = [] 34 | stack.push(root) 35 | while (stack.length) { 36 | var top = stack.pop() 37 | if (top.val === undefined) { 38 | result.push(top) 39 | } else { 40 | if (top.right) { 41 | stack.push(top.right) 42 | } 43 | stack.push(top.val) 44 | if (top.left) { 45 | stack.push(top.left) 46 | } 47 | } 48 | } 49 | return result 50 | }; 51 | 52 | -------------------------------------------------------------------------------- /095-unique-binary-search-trees-ii/unique-binary-search-trees-ii.js: -------------------------------------------------------------------------------- 1 | // Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: 3 7 | // Output: 8 | // [ 9 | //   [1,null,3,2], 10 | //   [3,2,null,1], 11 | //   [3,1,null,null,2], 12 | //   [2,1,3], 13 | //   [1,null,2,null,3] 14 | // ] 15 | // Explanation: 16 | // The above output corresponds to the 5 unique BST's shown below: 17 | // 18 | // 1 3 3 2 1 19 | // \ / / / \ \ 20 | // 3 2 1 1 3 2 21 | // / / \ \ 22 | // 2 1 2 3 23 | // 24 | // 25 | 26 | 27 | /** 28 | * Definition for a binary tree node. 29 | * function TreeNode(val) { 30 | * this.val = val; 31 | * this.left = this.right = null; 32 | * } 33 | */ 34 | /** 35 | * @param {number} n 36 | * @return {TreeNode[]} 37 | */ 38 | var generateTrees = function(n) { 39 | if (n === 0) return [] 40 | 41 | var _generateTrees = function(l, h) { 42 | if (l > h) return [null] 43 | var r = [] 44 | for (var i = l;i <= h;++i) { 45 | var left = _generateTrees(l, i-1) 46 | var right = _generateTrees(i+1, h) 47 | for (var j = 0;j < left.length;++j) { 48 | for (var k = 0;k < right.length;++k) { 49 | var mid = new TreeNode(i) 50 | mid.left = left[j] 51 | mid.right = right[k] 52 | r.push(mid) 53 | } 54 | } 55 | } 56 | return r 57 | } 58 | return _generateTrees(1, n) 59 | }; 60 | 61 | -------------------------------------------------------------------------------- /096-unique-binary-search-trees/unique-binary-search-trees.js: -------------------------------------------------------------------------------- 1 | // Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: 3 7 | // Output: 5 8 | // Explanation: 9 | // Given n = 3, there are a total of 5 unique BST's: 10 | // 11 | // 1 3 3 2 1 12 | // \ / / / \ \ 13 | // 3 2 1 1 3 2 14 | // / / \ \ 15 | // 2 1 2 3 16 | // 17 | // 18 | 19 | 20 | /** 21 | * @param {number} n 22 | * @return {number} 23 | */ 24 | var numTrees = function(n) { 25 | var result = new Array(n) 26 | var _numTrees = function(l, n) { 27 | var del = n - l 28 | if (del <= 0) return 1 29 | if (result[del] !== undefined) return result[del] 30 | var sum = 0 31 | for (var i = l;i <= n;++i) { 32 | var left = _numTrees(l, i-1) 33 | var right = _numTrees(i+1, n) 34 | sum += left*right 35 | } 36 | result[del] = sum 37 | return sum 38 | } 39 | return _numTrees(1, n) 40 | }; 41 | 42 | -------------------------------------------------------------------------------- /097-interleaving-string/interleaving-string.js: -------------------------------------------------------------------------------- 1 | // Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" 7 | // Output: true 8 | // 9 | // 10 | // Example 2: 11 | // 12 | // 13 | // Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" 14 | // Output: false 15 | // 16 | // 17 | 18 | 19 | /** 20 | * @param {string} s1 21 | * @param {string} s2 22 | * @param {string} s3 23 | * @return {boolean} 24 | */ 25 | var isInterleave = function(s1, s2, s3) { 26 | if (s1.length + s2.length !== s3.length) return false 27 | 28 | var dp = {} 29 | var _isInterleave = function(s1, s2, s3) { 30 | if (s1.length === 0) return s2 === s3 31 | if (s2.length === 0) return s1 === s3 32 | var key = s1.length + '_' + s2.length 33 | if (dp[key] !== undefined) return dp[key] 34 | dp[key] = (s1[0] === s3[0] && _isInterleave(s1.substr(1), s2, s3.substr(1))) || 35 | (s2[0] === s3[0] && _isInterleave(s1, s2.substr(1), s3.substr(1))) 36 | return dp[key] 37 | } 38 | return _isInterleave(s1, s2, s3) 39 | }; 40 | 41 | -------------------------------------------------------------------------------- /098-validate-binary-search-tree/validate-binary-search-tree.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, determine if it is a valid binary search tree (BST). 2 | // 3 | // Assume a BST is defined as follows: 4 | // 5 | // 6 | // The left subtree of a node contains only nodes with keys less than the node's key. 7 | // The right subtree of a node contains only nodes with keys greater than the node's key. 8 | // Both the left and right subtrees must also be binary search trees. 9 | // 10 | // 11 | // Example 1: 12 | // 13 | // 14 | // Input: 15 | // 2 16 | // / \ 17 | // 1 3 18 | // Output: true 19 | // 20 | // 21 | // Example 2: 22 | // 23 | // 24 | // 5 25 | // / \ 26 | // 1 4 27 | //   / \ 28 | //   3 6 29 | // Output: false 30 | // Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value 31 | //   is 5 but its right child's value is 4. 32 | // 33 | // 34 | 35 | 36 | /** 37 | * Definition for a binary tree node. 38 | * function TreeNode(val) { 39 | * this.val = val; 40 | * this.left = this.right = null; 41 | * } 42 | */ 43 | /** 44 | * @param {TreeNode} root 45 | * @return {boolean} 46 | */ 47 | var isValidBST = function(root) { 48 | if (!root) return true 49 | if (!isValidBST(root.left) || !isValidBST(root.right)) return false 50 | var max = root.left || new TreeNode(-Number.MAX_VALUE) 51 | while (max.right) max = max.right 52 | var min = root.right || new TreeNode(Number.MAX_VALUE) 53 | while (min.left) min = min.left 54 | if (root.val > max.val && root.val < min.val) return true 55 | return false 56 | }; 57 | 58 | -------------------------------------------------------------------------------- /100-same-tree/same-tree.js: -------------------------------------------------------------------------------- 1 | // Given two binary trees, write a function to check if they are the same or not. 2 | // 3 | // Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: 1 1 9 | // / \ / \ 10 | // 2 3 2 3 11 | // 12 | // [1,2,3], [1,2,3] 13 | // 14 | // Output: true 15 | // 16 | // 17 | // Example 2: 18 | // 19 | // 20 | // Input: 1 1 21 | // / \ 22 | // 2 2 23 | // 24 | // [1,2], [1,null,2] 25 | // 26 | // Output: false 27 | // 28 | // 29 | // Example 3: 30 | // 31 | // 32 | // Input: 1 1 33 | // / \ / \ 34 | // 2 1 1 2 35 | // 36 | // [1,2,1], [1,1,2] 37 | // 38 | // Output: false 39 | // 40 | // 41 | 42 | 43 | /** 44 | * Definition for a binary tree node. 45 | * function TreeNode(val) { 46 | * this.val = val; 47 | * this.left = this.right = null; 48 | * } 49 | */ 50 | /** 51 | * @param {TreeNode} p 52 | * @param {TreeNode} q 53 | * @return {boolean} 54 | */ 55 | var isSameTree = function(p, q) { 56 | if (p === null || q === null) { 57 | return p === q 58 | } 59 | if (p.val !== q.val) { 60 | return false 61 | } 62 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right) 63 | }; 64 | 65 | -------------------------------------------------------------------------------- /101-symmetric-tree/symmetric-tree.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 2 | // 3 | // 4 | // For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 5 | // 6 | // 1 7 | // / \ 8 | // 2 2 9 | // / \ / \ 10 | // 3 4 4 3 11 | // 12 | // 13 | // 14 | // But the following [1,2,2,null,3,null,3] is not: 15 | // 16 | // 1 17 | // / \ 18 | // 2 2 19 | // \ \ 20 | // 3 3 21 | // 22 | // 23 | // 24 | // 25 | // Note: 26 | // Bonus points if you could solve it both recursively and iteratively. 27 | // 28 | 29 | 30 | /** 31 | * Definition for a binary tree node. 32 | * function TreeNode(val) { 33 | * this.val = val; 34 | * this.left = this.right = null; 35 | * } 36 | */ 37 | /** 38 | * @param {TreeNode} root 39 | * @return {boolean} 40 | */ 41 | var isSymmetric = function(root) { 42 | if (!root) return true 43 | var _isSymmetric = function(l, r) { 44 | if (!l || !r) { 45 | return l == r 46 | } 47 | if (l.val !== r.val) return false 48 | return _isSymmetric(l.left, r.right) && _isSymmetric(l.right, r.left) 49 | } 50 | 51 | return _isSymmetric(root.left, root.right) 52 | }; 53 | 54 | -------------------------------------------------------------------------------- /102-binary-tree-level-order-traversal/binary-tree-level-order-traversal.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 2 | // 3 | // 4 | // For example: 5 | // Given binary tree [3,9,20,null,null,15,7], 6 | // 7 | // 3 8 | // / \ 9 | // 9 20 10 | // / \ 11 | // 15 7 12 | // 13 | // 14 | // 15 | // return its level order traversal as: 16 | // 17 | // [ 18 | // [3], 19 | // [9,20], 20 | // [15,7] 21 | // ] 22 | // 23 | // 24 | 25 | 26 | /** 27 | * Definition for a binary tree node. 28 | * function TreeNode(val) { 29 | * this.val = val; 30 | * this.left = this.right = null; 31 | * } 32 | */ 33 | /** 34 | * @param {TreeNode} root 35 | * @return {number[][]} 36 | */ 37 | var levelOrder = function(root) { 38 | if (!root) return [] 39 | var result = [] 40 | var queue = [] 41 | queue.push([root, 0]) 42 | while (queue.length) { 43 | var top = queue.shift() 44 | result[top[1]] = result[top[1]] || [] 45 | result[top[1]].push(top[0].val) 46 | 47 | if (top[0].left) { 48 | queue.push([top[0].left, top[1]+1]) 49 | } 50 | if (top[0].right) { 51 | queue.push([top[0].right, top[1]+1]) 52 | } 53 | } 54 | return result 55 | }; 56 | 57 | -------------------------------------------------------------------------------- /103-binary-tree-zigzag-level-order-traversal/binary-tree-zigzag-level-order-traversal.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). 2 | // 3 | // 4 | // For example: 5 | // Given binary tree [3,9,20,null,null,15,7], 6 | // 7 | // 3 8 | // / \ 9 | // 9 20 10 | // / \ 11 | // 15 7 12 | // 13 | // 14 | // 15 | // return its zigzag level order traversal as: 16 | // 17 | // [ 18 | // [3], 19 | // [20,9], 20 | // [15,7] 21 | // ] 22 | // 23 | // 24 | 25 | 26 | /** 27 | * Definition for a binary tree node. 28 | * function TreeNode(val) { 29 | * this.val = val; 30 | * this.left = this.right = null; 31 | * } 32 | */ 33 | /** 34 | * @param {TreeNode} root 35 | * @return {number[][]} 36 | */ 37 | var zigzagLevelOrder = function(root) { 38 | if (!root) return [] 39 | var result = [] 40 | var queue = [] 41 | queue.push([root, 0]) 42 | while (queue.length) { 43 | var top = queue.shift() 44 | result[top[1]] = result[top[1]] || [] 45 | result[top[1]].push(top[0].val) 46 | 47 | if (top[0].left) { 48 | queue.push([top[0].left, top[1]+1]) 49 | } 50 | if (top[0].right) { 51 | queue.push([top[0].right, top[1]+1]) 52 | } 53 | } 54 | for (var i = 1;i < result.length;i += 2) { 55 | result[i].reverse() 56 | } 57 | return result 58 | }; 59 | 60 | -------------------------------------------------------------------------------- /104-maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its maximum depth. 2 | // 3 | // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 4 | // 5 | // Note: A leaf is a node with no children. 6 | // 7 | // Example: 8 | // 9 | // Given binary tree [3,9,20,null,null,15,7], 10 | // 11 | // 12 | // 3 13 | // / \ 14 | // 9 20 15 | // / \ 16 | // 15 7 17 | // 18 | // return its depth = 3. 19 | // 20 | 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 | * @param {TreeNode} root 31 | * @return {number} 32 | */ 33 | var maxDepth = function(root) { 34 | if (!root) return 0 35 | var queue = [] 36 | var result = 0 37 | queue.push(root) 38 | while (queue.length) { 39 | ++result 40 | for (var i = 0, l = queue.length; i < l;++i) { 41 | var top = queue.shift() 42 | if (top.left) queue.push(top.left) 43 | if (top.right) queue.push(top.right) 44 | } 45 | } 46 | return result 47 | }; 48 | 49 | -------------------------------------------------------------------------------- /105-construct-binary-tree-from-preorder-and-inorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal.js: -------------------------------------------------------------------------------- 1 | // Given preorder and inorder traversal of a tree, construct the binary tree. 2 | // 3 | // Note: 4 | // You may assume that duplicates do not exist in the tree. 5 | // 6 | // For example, given 7 | // 8 | // 9 | // preorder = [3,9,20,15,7] 10 | // inorder = [9,3,15,20,7] 11 | // 12 | // Return the following binary tree: 13 | // 14 | // 15 | // 3 16 | // / \ 17 | // 9 20 18 | // / \ 19 | // 15 7 20 | // 21 | 22 | 23 | /** 24 | * Definition for a binary tree node. 25 | * function TreeNode(val) { 26 | * this.val = val; 27 | * this.left = this.right = null; 28 | * } 29 | */ 30 | /** 31 | * @param {number[]} preorder 32 | * @param {number[]} inorder 33 | * @return {TreeNode} 34 | */ 35 | var buildTree = function(preorder, inorder) { 36 | if (preorder.length !== inorder.length || preorder.length === 0) return null 37 | 38 | var _buildTree = function(p_b, p_e, i_b, i_e) { 39 | if (p_b > p_e || i_b > i_e) return null 40 | var root = new TreeNode(preorder[p_b]) 41 | var i = inorder.indexOf(root.val, i_b) 42 | root.left = _buildTree(p_b+1, p_b+i-i_b, i_b, i-1) 43 | root.right = _buildTree(p_b+i-i_b+1, p_e, i+1, i_e) 44 | return root 45 | } 46 | return _buildTree(0, preorder.length-1, 0, inorder.length-1) 47 | }; 48 | 49 | -------------------------------------------------------------------------------- /106-construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.js: -------------------------------------------------------------------------------- 1 | // Given inorder and postorder traversal of a tree, construct the binary tree. 2 | // 3 | // Note: 4 | // You may assume that duplicates do not exist in the tree. 5 | // 6 | // For example, given 7 | // 8 | // 9 | // inorder = [9,3,15,20,7] 10 | // postorder = [9,15,7,20,3] 11 | // 12 | // Return the following binary tree: 13 | // 14 | // 15 | // 3 16 | // / \ 17 | // 9 20 18 | // / \ 19 | // 15 7 20 | // 21 | // 22 | 23 | 24 | /** 25 | * Definition for a binary tree node. 26 | * function TreeNode(val) { 27 | * this.val = val; 28 | * this.left = this.right = null; 29 | * } 30 | */ 31 | /** 32 | * @param {number[]} inorder 33 | * @param {number[]} postorder 34 | * @return {TreeNode} 35 | */ 36 | var buildTree = function(inorder, postorder) { 37 | if (postorder.length !== inorder.length || postorder.length === 0) return null 38 | 39 | var _buildTree = function(p_b, p_e, i_b, i_e) { 40 | if (p_b > p_e || i_b > i_e) return null 41 | var root = new TreeNode(postorder[p_e]) 42 | var i = i_e 43 | while (inorder[i] !== root.val) { 44 | --i 45 | } 46 | root.left = _buildTree(p_b, p_b+i-i_b-1, i_b, i-1) 47 | root.right = _buildTree(p_b+i-i_b, p_e-1, i+1, i_e) 48 | return root 49 | } 50 | return _buildTree(0, postorder.length-1, 0, inorder.length-1) 51 | }; 52 | 53 | -------------------------------------------------------------------------------- /107-binary-tree-level-order-traversal-ii/binary-tree-level-order-traversal-ii.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 2 | // 3 | // 4 | // For example: 5 | // Given binary tree [3,9,20,null,null,15,7], 6 | // 7 | // 3 8 | // / \ 9 | // 9 20 10 | // / \ 11 | // 15 7 12 | // 13 | // 14 | // 15 | // return its bottom-up level order traversal as: 16 | // 17 | // [ 18 | // [15,7], 19 | // [9,20], 20 | // [3] 21 | // ] 22 | // 23 | // 24 | 25 | 26 | /** 27 | * Definition for a binary tree node. 28 | * function TreeNode(val) { 29 | * this.val = val; 30 | * this.left = this.right = null; 31 | * } 32 | */ 33 | /** 34 | * @param {TreeNode} root 35 | * @return {number[][]} 36 | */ 37 | var levelOrderBottom = function(root) { 38 | if (!root) return [] 39 | var result = [] 40 | var queue = [] 41 | queue.push([root, 0]) 42 | while (queue.length) { 43 | var top = queue.shift() 44 | result[top[1]] = result[top[1]] || [] 45 | result[top[1]].push(top[0].val) 46 | 47 | if (top[0].left) { 48 | queue.push([top[0].left, top[1]+1]) 49 | } 50 | if (top[0].right) { 51 | queue.push([top[0].right, top[1]+1]) 52 | } 53 | } 54 | return result.reverse() 55 | }; 56 | 57 | -------------------------------------------------------------------------------- /108-convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.js: -------------------------------------------------------------------------------- 1 | // Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 2 | // 3 | // For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 4 | // 5 | // Example: 6 | // 7 | // 8 | // Given the sorted array: [-10,-3,0,5,9], 9 | // 10 | // One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 11 | // 12 | // 0 13 | // / \ 14 | // -3 9 15 | // / / 16 | // -10 5 17 | // 18 | // 19 | 20 | 21 | /** 22 | * Definition for a binary tree node. 23 | * function TreeNode(val) { 24 | * this.val = val; 25 | * this.left = this.right = null; 26 | * } 27 | */ 28 | /** 29 | * @param {number[]} nums 30 | * @return {TreeNode} 31 | */ 32 | var sortedArrayToBST = function(nums) { 33 | if (nums.length === 0) return null 34 | var index = ~~(nums.length/2) 35 | var root = new TreeNode(nums[index]) 36 | root.left = sortedArrayToBST(nums.slice(0, index)) 37 | root.right = sortedArrayToBST(nums.slice(index+1)) 38 | return root 39 | }; 40 | 41 | -------------------------------------------------------------------------------- /109-convert-sorted-list-to-binary-search-tree/convert-sorted-list-to-binary-search-tree.js: -------------------------------------------------------------------------------- 1 | // Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 2 | // 3 | // For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 4 | // 5 | // Example: 6 | // 7 | // 8 | // Given the sorted linked list: [-10,-3,0,5,9], 9 | // 10 | // One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 11 | // 12 | // 0 13 | // / \ 14 | // -3 9 15 | // / / 16 | // -10 5 17 | // 18 | // 19 | 20 | 21 | /** 22 | * Definition for singly-linked list. 23 | * function ListNode(val) { 24 | * this.val = val; 25 | * this.next = null; 26 | * } 27 | */ 28 | /** 29 | * Definition for a binary tree node. 30 | * function TreeNode(val) { 31 | * this.val = val; 32 | * this.left = this.right = null; 33 | * } 34 | */ 35 | /** 36 | * @param {ListNode} head 37 | * @return {TreeNode} 38 | */ 39 | var sortedListToBST = function(head) { 40 | var sortedArrayToBST = function(nums) { 41 | if (nums.length === 0) return null 42 | var index = ~~(nums.length/2) 43 | var root = new TreeNode(nums[index]) 44 | root.left = sortedArrayToBST(nums.slice(0, index)) 45 | root.right = sortedArrayToBST(nums.slice(index+1)) 46 | return root 47 | }; 48 | var arr = [] 49 | while (head) { 50 | arr.push(head.val) 51 | head = head.next 52 | } 53 | return sortedArrayToBST(arr) 54 | }; 55 | 56 | -------------------------------------------------------------------------------- /110-balanced-binary-tree/balanced-binary-tree.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, determine if it is height-balanced. 2 | // 3 | // For this problem, a height-balanced binary tree is defined as: 4 | // 5 | // 6 | // a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 7 | // 8 | // 9 | // Example 1: 10 | // 11 | // Given the following tree [3,9,20,null,null,15,7]: 12 | // 13 | // 14 | // 3 15 | // / \ 16 | // 9 20 17 | // / \ 18 | // 15 7 19 | // 20 | // Return true. 21 | // 22 | // Example 2: 23 | // 24 | // Given the following tree [1,2,2,3,3,null,null,4,4]: 25 | // 26 | // 27 | // 1 28 | // / \ 29 | // 2 2 30 | // / \ 31 | // 3 3 32 | // / \ 33 | // 4 4 34 | // 35 | // 36 | // Return false. 37 | // 38 | 39 | 40 | /** 41 | * Definition for a binary tree node. 42 | * function TreeNode(val) { 43 | * this.val = val; 44 | * this.left = this.right = null; 45 | * } 46 | */ 47 | /** 48 | * @param {TreeNode} root 49 | * @return {boolean} 50 | */ 51 | var isBalanced = function(root) { 52 | var getHeight = function(root) { 53 | if (!root) { 54 | return 0 55 | } 56 | var left_height = getHeight(root.left) 57 | if (left_height === -1) { 58 | return -1 59 | } 60 | var right_height = getHeight(root.right) 61 | if (right_height === -1) { 62 | return -1 63 | } 64 | if (Math.abs(left_height-right_height) > 1) { 65 | return -1 66 | } 67 | return Math.max(left_height, right_height) + 1 68 | } 69 | return getHeight(root) !== -1 70 | }; 71 | 72 | -------------------------------------------------------------------------------- /111-minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its minimum depth. 2 | // 3 | // The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 4 | // 5 | // Note: A leaf is a node with no children. 6 | // 7 | // Example: 8 | // 9 | // Given binary tree [3,9,20,null,null,15,7], 10 | // 11 | // 12 | // 3 13 | // / \ 14 | // 9 20 15 | // / \ 16 | // 15 7 17 | // 18 | // return its minimum depth = 2. 19 | // 20 | 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 | * @param {TreeNode} root 31 | * @return {number} 32 | */ 33 | var minDepth = function(root) { 34 | if (!root) return 0 35 | var queue = [] 36 | var result = 0 37 | queue.push(root) 38 | while (queue.length) { 39 | ++result 40 | for (var i = 0, l = queue.length; i < l;++i) { 41 | var top = queue.shift() 42 | if (!top.left && !top.right) return result 43 | if (top.left) queue.push(top.left) 44 | if (top.right) queue.push(top.right) 45 | } 46 | } 47 | return result 48 | }; 49 | 50 | -------------------------------------------------------------------------------- /112-path-sum/path-sum.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 2 | // 3 | // Note: A leaf is a node with no children. 4 | // 5 | // Example: 6 | // 7 | // Given the below binary tree and sum = 22, 8 | // 9 | // 10 | // 5 11 | // / \ 12 | // 4 8 13 | // / / \ 14 | // 11 13 4 15 | // / \ \ 16 | // 7 2 1 17 | // 18 | // 19 | // return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 20 | // 21 | 22 | 23 | /** 24 | * Definition for a binary tree node. 25 | * function TreeNode(val) { 26 | * this.val = val; 27 | * this.left = this.right = null; 28 | * } 29 | */ 30 | /** 31 | * @param {TreeNode} root 32 | * @param {number} sum 33 | * @return {boolean} 34 | */ 35 | var hasPathSum = function(root, sum) { 36 | if (!root) return false 37 | if (!root.left && !root.right) { 38 | return root.val === sum 39 | } 40 | return (!!root.left && hasPathSum(root.left, sum-root.val)) || 41 | (!!root.right && hasPathSum(root.right, sum-root.val)) 42 | }; 43 | 44 | 45 | -------------------------------------------------------------------------------- /113-path-sum-ii/path-sum-ii.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 2 | // 3 | // Note: A leaf is a node with no children. 4 | // 5 | // Example: 6 | // 7 | // Given the below binary tree and sum = 22, 8 | // 9 | // 10 | // 5 11 | // / \ 12 | // 4 8 13 | // / / \ 14 | // 11 13 4 15 | // / \ / \ 16 | // 7 2 5 1 17 | // 18 | // 19 | // Return: 20 | // 21 | // 22 | // [ 23 | // [5,4,11,2], 24 | // [5,8,4,5] 25 | // ] 26 | // 27 | // 28 | 29 | 30 | /** 31 | * Definition for a binary tree node. 32 | * function TreeNode(val) { 33 | * this.val = val; 34 | * this.left = this.right = null; 35 | * } 36 | */ 37 | /** 38 | * @param {TreeNode} root 39 | * @param {number} sum 40 | * @return {number[][]} 41 | */ 42 | var pathSum = function(root, sum) { 43 | if (!root) return [] 44 | 45 | if (root.left===root.right) { 46 | if (root.val === sum) { 47 | return [[root.val]] 48 | } 49 | return [] 50 | } 51 | 52 | return pathSum(root.left, sum-root.val) 53 | .concat(pathSum(root.right, sum-root.val)) 54 | .map(function(v) { 55 | v.unshift(root.val) 56 | return v 57 | }) 58 | }; 59 | 60 | -------------------------------------------------------------------------------- /114-flatten-binary-tree-to-linked-list/flatten-binary-tree-to-linked-list.js: -------------------------------------------------------------------------------- 1 | // Given a binary tree, flatten it to a linked list in-place. 2 | // 3 | // For example, given the following tree: 4 | // 5 | // 6 | // 1 7 | // / \ 8 | // 2 5 9 | // / \ \ 10 | // 3 4 6 11 | // 12 | // 13 | // The flattened tree should look like: 14 | // 15 | // 16 | // 1 17 | // \ 18 | // 2 19 | // \ 20 | // 3 21 | // \ 22 | // 4 23 | // \ 24 | // 5 25 | // \ 26 | // 6 27 | // 28 | // 29 | 30 | 31 | /** 32 | * Definition for a binary tree node. 33 | * function TreeNode(val) { 34 | * this.val = val; 35 | * this.left = this.right = null; 36 | * } 37 | */ 38 | /** 39 | * @param {TreeNode} root 40 | * @return {void} Do not return anything, modify root in-place instead. 41 | */ 42 | var flatten = function(root) { 43 | if (!root) return 44 | if (root.right) { 45 | flatten(root.right) 46 | } 47 | if (!root.left) return 48 | flatten(root.left) 49 | r = root.left 50 | while (r.right) { 51 | r = r.right 52 | } 53 | r.right = root.right 54 | root.right = root.left 55 | root.left = null 56 | }; 57 | 58 | -------------------------------------------------------------------------------- /115-distinct-subsequences/distinct-subsequences.cpp: -------------------------------------------------------------------------------- 1 | // Given a string S and a string T, count the number of distinct subsequences of S which equals T. 2 | // 3 | // A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: S = "rabbbit", T = "rabbit" 9 | // Output: 3 10 | // Explanation: 11 | // 12 | // As shown below, there are 3 ways you can generate "rabbit" from S. 13 | // (The caret symbol ^ means the chosen letters) 14 | // 15 | // rabbbit 16 | // ^^^^ ^^ 17 | // rabbbit 18 | // ^^ ^^^^ 19 | // rabbbit 20 | // ^^^ ^^^ 21 | // 22 | // 23 | // Example 2: 24 | // 25 | // 26 | // Input: S = "babgbag", T = "bag" 27 | // Output: 5 28 | // Explanation: 29 | // 30 | // As shown below, there are 5 ways you can generate "bag" from S. 31 | // (The caret symbol ^ means the chosen letters) 32 | // 33 | // babgbag 34 | // ^^ ^ 35 | // babgbag 36 | // ^^ ^ 37 | // babgbag 38 | // ^ ^^ 39 | // babgbag 40 | // ^ ^^ 41 | // babgbag 42 | // ^^^ 43 | // 44 | // 45 | 46 | 47 | class Solution { 48 | public: 49 | int numDistinct(string s, string t) { 50 | int sl = s.length(), tl = t.length(); 51 | vector dp(tl+1,0); 52 | dp[0] = 1; 53 | for (int i = 1; i<=sl; ++i) { 54 | int pre = 1; 55 | for (int j = 1; j<=tl;++j) { 56 | int temp = dp[j]; 57 | if (s[i-1] == t[j-1]) { 58 | dp[j] += pre; 59 | } 60 | pre = temp; 61 | } 62 | } 63 | return dp[tl]; 64 | } 65 | }; 66 | 67 | -------------------------------------------------------------------------------- /118-pascals-triangle/pascals-triangle.cpp: -------------------------------------------------------------------------------- 1 | // Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. 2 | // 3 | // 4 | // In Pascal's triangle, each number is the sum of the two numbers directly above it. 5 | // 6 | // Example: 7 | // 8 | // 9 | // Input: 5 10 | // Output: 11 | // [ 12 | // [1], 13 | // [1,1], 14 | // [1,2,1], 15 | // [1,3,3,1], 16 | // [1,4,6,4,1] 17 | // ] 18 | // 19 | // 20 | 21 | 22 | class Solution { 23 | public: 24 | vector> generate(int numRows) { 25 | vector> result(numRows, vector(0)); 26 | if (numRows <= 0) return result; 27 | for (int i = 0;i < numRows;++i) { 28 | for (int j = 0;j <= i;++j) { 29 | if (j == 0 || j == i) { 30 | result[i].push_back(1); 31 | continue; 32 | } 33 | result[i].push_back(result[i-1][j-1]+result[i-1][j]); 34 | } 35 | } 36 | return result; 37 | } 38 | }; 39 | 40 | -------------------------------------------------------------------------------- /119-pascals-triangle-ii/pascals-triangle-ii.cpp: -------------------------------------------------------------------------------- 1 | // Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. 2 | // 3 | // Note that the row index starts from 0. 4 | // 5 | // 6 | // In Pascal's triangle, each number is the sum of the two numbers directly above it. 7 | // 8 | // Example: 9 | // 10 | // 11 | // Input: 3 12 | // Output: [1,3,3,1] 13 | // 14 | // 15 | // Follow up: 16 | // 17 | // Could you optimize your algorithm to use only O(k) extra space? 18 | // 19 | 20 | 21 | class Solution { 22 | public: 23 | vector getRow(int rowIndex) { 24 | vector result(rowIndex+1, 1); 25 | for (int i = 1;i <= rowIndex;++i) { 26 | for (int j = i-1;j >= 1;--j) { 27 | result[j] = result[j] + result[j-1]; 28 | } 29 | } 30 | return result; 31 | } 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /120-triangle/triangle.cpp: -------------------------------------------------------------------------------- 1 | // Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 2 | // 3 | // For example, given the following triangle 4 | // 5 | // 6 | // [ 7 | // [2], 8 | // [3,4], 9 | // [6,5,7], 10 | // [4,1,8,3] 11 | // ] 12 | // 13 | // 14 | // The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 15 | // 16 | // Note: 17 | // 18 | // Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. 19 | // 20 | 21 | 22 | class Solution { 23 | public: 24 | int minimumTotal(vector>& triangle) { 25 | int row = 0; 26 | int col = 0; 27 | int current = 0; 28 | vector Min(triangle.size()+1, 0); 29 | for (row = triangle.size()-1; row >= 0;--row) { 30 | for (col = 0; col <= row; ++col) { 31 | current = triangle[row][col]; 32 | Min[col] = std::min(Min[col], Min[col+1]) + current; 33 | } 34 | } 35 | return Min[0]; 36 | } 37 | }; 38 | 39 | -------------------------------------------------------------------------------- /121-best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | // Say you have an array for which the ith element is the price of a given stock on day i. 2 | // 3 | // If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. 4 | // 5 | // Note that you cannot sell a stock before you buy one. 6 | // 7 | // Example 1: 8 | // 9 | // 10 | // Input: [7,1,5,3,6,4] 11 | // Output: 5 12 | // Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 13 | //   Not 7-1 = 6, as selling price needs to be larger than buying price. 14 | // 15 | // 16 | // Example 2: 17 | // 18 | // 19 | // Input: [7,6,4,3,1] 20 | // Output: 0 21 | // Explanation: In this case, no transaction is done, i.e. max profit = 0. 22 | // 23 | // 24 | 25 | 26 | class Solution { 27 | public: 28 | int maxProfit(vector& prices) { 29 | if (prices.size() == 0) { 30 | return 0; 31 | } 32 | int minVal = prices[0]; 33 | int best_profit = 0; 34 | for (auto price : prices) { 35 | best_profit = std::max(best_profit, price - minVal); 36 | minVal = std::min(minVal, price); 37 | } 38 | return best_profit; 39 | } 40 | }; 41 | 42 | -------------------------------------------------------------------------------- /121-best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.js: -------------------------------------------------------------------------------- 1 | // Say you have an array for which the ith element is the price of a given stock on day i. 2 | // 3 | // If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. 4 | // 5 | // Note that you cannot sell a stock before you buy one. 6 | // 7 | // Example 1: 8 | // 9 | // 10 | // Input: [7,1,5,3,6,4] 11 | // Output: 5 12 | // Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 13 | //   Not 7-1 = 6, as selling price needs to be larger than buying price. 14 | // 15 | // 16 | // Example 2: 17 | // 18 | // 19 | // Input: [7,6,4,3,1] 20 | // Output: 0 21 | // Explanation: In this case, no transaction is done, i.e. max profit = 0. 22 | // 23 | // 24 | 25 | 26 | /** 27 | * @param {number[]} prices 28 | * @return {number} 29 | */ 30 | var maxProfit = function(prices) { 31 | var min = prices[0]; 32 | var curr = 0; 33 | for (var i = 1;i < prices.length;++i) { 34 | curr = Math.max(curr, prices[i] - min); 35 | min = Math.min(min, prices[i]); 36 | } 37 | return curr; 38 | }; 39 | 40 | -------------------------------------------------------------------------------- /123-best-time-to-buy-and-sell-stock-iii/best-time-to-buy-and-sell-stock-iii.cpp: -------------------------------------------------------------------------------- 1 | // Say you have an array for which the ith element is the price of a given stock on day i. 2 | // 3 | // Design an algorithm to find the maximum profit. You may complete at most two transactions. 4 | // 5 | // Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). 6 | // 7 | // Example 1: 8 | // 9 | // 10 | // Input: [3,3,5,0,0,3,1,4] 11 | // Output: 6 12 | // Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. 13 | //   Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. 14 | // 15 | // Example 2: 16 | // 17 | // 18 | // Input: [1,2,3,4,5] 19 | // Output: 4 20 | // Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. 21 | //   Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are 22 | //   engaging multiple transactions at the same time. You must sell before buying again. 23 | // 24 | // 25 | // Example 3: 26 | // 27 | // 28 | // Input: [7,6,4,3,1] 29 | // Output: 0 30 | // Explanation: In this case, no transaction is done, i.e. max profit = 0. 31 | // 32 | 33 | 34 | class Solution { 35 | public: 36 | int maxProfit(vector& prices) { 37 | int s1 = 0, 38 | s2 = 0, 39 | b1 = -1<<31, 40 | b2 = -1<<31; 41 | for (auto i : prices) { 42 | b1 = std::max(b1, -i); 43 | s1 = std::max(s1, b1+i); 44 | b2 = std::max(b2, s1-i); 45 | s2 = std::max(s2, b2+i); 46 | } 47 | return s2; 48 | } 49 | }; 50 | 51 | -------------------------------------------------------------------------------- /124-binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | // Given a non-empty binary tree, find the maximum path sum. 2 | // 3 | // For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: [1,2,3] 9 | // 10 | // 1 11 | // / \ 12 | // 2 3 13 | // 14 | // Output: 6 15 | // 16 | // 17 | // Example 2: 18 | // 19 | // 20 | // Input: [-10,9,20,null,null,15,7] 21 | // 22 | //   -10 23 | //    / \ 24 | //   9  20 25 | //     /  \ 26 | //    15   7 27 | // 28 | // Output: 42 29 | // 30 | // 31 | 32 | 33 | /** 34 | * Definition for a binary tree node. 35 | * struct TreeNode { 36 | * int val; 37 | * TreeNode *left; 38 | * TreeNode *right; 39 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 40 | * }; 41 | */ 42 | class Solution { 43 | public: 44 | int max = -1<<31; 45 | int maxPathSum(TreeNode* root) { 46 | if (!root) return 0; 47 | dfs(root); 48 | return max; 49 | } 50 | int dfs(TreeNode* root) { 51 | if (!root) return 0; 52 | 53 | int l = dfs(root->left); 54 | int r = dfs(root->right); 55 | int s = root->val + std::max(l,0) + std::max(r,0); 56 | max = std::max(s, max); 57 | return std::max(root->val, root->val+std::max(l,r)); 58 | } 59 | }; 60 | 61 | -------------------------------------------------------------------------------- /125-valid-palindrome/valid-palindrome.cpp: -------------------------------------------------------------------------------- 1 | // Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 2 | // 3 | // Note: For the purpose of this problem, we define empty string as valid palindrome. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: "A man, a plan, a canal: Panama" 9 | // Output: true 10 | // 11 | // 12 | // Example 2: 13 | // 14 | // 15 | // Input: "race a car" 16 | // Output: false 17 | // 18 | // 19 | 20 | 21 | class Solution { 22 | public: 23 | bool isPalindrome(string s) { 24 | if (s.size() == 0) return true; 25 | 26 | int l = 0, r = s.size()-1; 27 | while (l < r) { 28 | if (!std::isalnum(s[l])) { 29 | ++l; 30 | continue; 31 | } 32 | if (!std::isalnum(s[r])) { 33 | --r; 34 | continue; 35 | } 36 | if (std::tolower(s[l]) != std::tolower(s[r])) return false; 37 | 38 | ++l; --r; 39 | } 40 | return true; 41 | } 42 | }; 43 | 44 | -------------------------------------------------------------------------------- /128-longest-consecutive-sequence/longest-consecutive-sequence.cpp: -------------------------------------------------------------------------------- 1 | // Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 2 | // 3 | // Your algorithm should run in O(n) complexity. 4 | // 5 | // Example: 6 | // 7 | // 8 | // Input: [100, 4, 200, 1, 3, 2] 9 | // Output: 4 10 | // Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. 11 | // 12 | // 13 | 14 | 15 | class Solution { 16 | public: 17 | int longestConsecutive(vector& nums) { 18 | unordered_set set(nums.begin(), nums.end()); 19 | int ans = 0; 20 | int current = 0; 21 | while (!set.empty()) { 22 | int x = (*set.begin()); 23 | current += 1; 24 | set.erase(x); 25 | int temp = x-1; 26 | while (set.find(temp) != set.end()) { 27 | ++current; 28 | set.erase(temp); 29 | --temp; 30 | } 31 | temp = x+1; 32 | while (set.find(temp) != set.end()) { 33 | ++current; 34 | set.erase(temp); 35 | ++temp; 36 | } 37 | ans = std::max(ans, current); 38 | current = 0; 39 | } 40 | 41 | return ans; 42 | } 43 | }; 44 | 45 | -------------------------------------------------------------------------------- /131-palindrome-partitioning/palindrome-partitioning.cpp: -------------------------------------------------------------------------------- 1 | // Given a string s, partition s such that every substring of the partition is a palindrome. 2 | // 3 | // Return all possible palindrome partitioning of s. 4 | // 5 | // Example: 6 | // 7 | // 8 | // Input: "aab" 9 | // Output: 10 | // [ 11 | // ["aa","b"], 12 | // ["a","a","b"] 13 | // ] 14 | // 15 | // 16 | 17 | 18 | class Solution { 19 | public: 20 | bool isPalindrome(string s) { 21 | for (int i = 0, len = s.size(); i < len/2; ++i) { 22 | if (s[i] != s[len-1-i]) return false; 23 | } 24 | return true; 25 | } 26 | vector> partition(string s) { 27 | vector> ans; 28 | for (int i = 1;i <= s.size();++i) { 29 | string substring = s.substr(0, i); 30 | if (!isPalindrome(substring)) continue; 31 | vector> subAns = partition(s.substr(i)); 32 | for (int j = 0; j < subAns.size(); ++j) { 33 | subAns[j].insert(subAns[j].begin(), substring); 34 | ans.push_back(subAns[j]); 35 | } 36 | if (subAns.size() == 0) { 37 | ans.push_back(vector(1,substring)); 38 | } 39 | } 40 | return ans; 41 | } 42 | }; 43 | 44 | -------------------------------------------------------------------------------- /132-palindrome-partitioning-ii/palindrome-partitioning-ii.cpp: -------------------------------------------------------------------------------- 1 | // Given a string s, partition s such that every substring of the partition is a palindrome. 2 | // 3 | // Return the minimum cuts needed for a palindrome partitioning of s. 4 | // 5 | // Example: 6 | // 7 | // 8 | // Input: "aab" 9 | // Output: 1 10 | // Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. 11 | // 12 | // 13 | 14 | 15 | class Solution { 16 | public: 17 | int minCut(string s) { 18 | int size = s.size(); 19 | vector min_cut(size+1, 0); 20 | for (int i = 0; i <= size; ++i) { 21 | min_cut[i] = i-1; 22 | } 23 | for (int i = 0; i < size; ++i) { 24 | for (int j = 0; i-j>=0&&i+j=0&&i+j& ratings) { 34 | int n = ratings.size(); 35 | vector candies(n, 1); 36 | for (int i = 1; i < n; ++i) { 37 | if (ratings[i] > ratings[i-1]) { 38 | candies[i] = candies[i-1]+1; 39 | } 40 | } 41 | for (int i = n-2; i >= 0; --i) { 42 | if (ratings[i] > ratings[i+1]) { 43 | candies[i] = max(candies[i], candies[i+1]+1); 44 | } 45 | } 46 | int ans = 0; 47 | for (auto c : candies) { 48 | ans += c; 49 | } 50 | return ans; 51 | } 52 | }; 53 | 54 | -------------------------------------------------------------------------------- /136-single-number/single-number.cpp: -------------------------------------------------------------------------------- 1 | // Given a non-empty array of integers, every element appears twice except for one. Find that single one. 2 | // 3 | // Note: 4 | // 5 | // Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | // 7 | // Example 1: 8 | // 9 | // 10 | // Input: [2,2,1] 11 | // Output: 1 12 | // 13 | // 14 | // Example 2: 15 | // 16 | // 17 | // Input: [4,1,2,1,2] 18 | // Output: 4 19 | // 20 | 21 | 22 | class Solution { 23 | public: 24 | int singleNumber(vector& nums) { 25 | int ans=0; 26 | for (int i = 0, size=nums.size();i& nums) { 26 | int one = 0, two = 0; 27 | for (auto i : nums) { 28 | one = (one ^ i) & (~two); 29 | two = (two ^ i) & (~one); 30 | } 31 | return one; 32 | } 33 | }; 34 | 35 | -------------------------------------------------------------------------------- /138-copy-list-with-random-pointer/copy-list-with-random-pointer.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 3 | // 4 | // 5 | // 6 | // Return a deep copy of the list. 7 | // 8 | 9 | 10 | /** 11 | * Definition for singly-linked list with a random pointer. 12 | * struct RandomListNode { 13 | * int label; 14 | * RandomListNode *next, *random; 15 | * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | map nodeMap; 21 | 22 | RandomListNode *copyRandomList(RandomListNode *head) { 23 | if (!head) return nullptr; 24 | if (nodeMap.find(head) != nodeMap.end()) return nodeMap[head]; 25 | RandomListNode *n = new RandomListNode(head->label); 26 | nodeMap[head] = n; 27 | if (!head->random) { 28 | n->random = nullptr; 29 | } else { 30 | n->random = copyRandomList(head->random); 31 | } 32 | if (!head->next) { 33 | n->next = nullptr; 34 | } else { 35 | n->next = copyRandomList(head->next); 36 | } 37 | return n; 38 | } 39 | }; 40 | 41 | -------------------------------------------------------------------------------- /139-word-break/word-break.cpp: -------------------------------------------------------------------------------- 1 | // Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. 2 | // 3 | // Note: 4 | // 5 | // 6 | // The same word in the dictionary may be reused multiple times in the segmentation. 7 | // You may assume the dictionary does not contain duplicate words. 8 | // 9 | // 10 | // Example 1: 11 | // 12 | // 13 | // Input: s = "leetcode", wordDict = ["leet", "code"] 14 | // Output: true 15 | // Explanation: Return true because "leetcode" can be segmented as "leet code". 16 | // 17 | // 18 | // Example 2: 19 | // 20 | // 21 | // Input: s = "applepenapple", wordDict = ["apple", "pen"] 22 | // Output: true 23 | // Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". 24 | //   Note that you are allowed to reuse a dictionary word. 25 | // 26 | // 27 | // Example 3: 28 | // 29 | // 30 | // Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] 31 | // Output: false 32 | // 33 | // 34 | 35 | 36 | class Solution { 37 | public: 38 | bool wordBreak(string s, unordered_set& wordDict) { 39 | int size = s.size(); 40 | if (!size) return true; 41 | vector dp(size+1, false); 42 | dp[0] = true; 43 | 44 | for (int i = 1; i <= size; ++i) { 45 | for (int j = i-1; j >= 0; --j) { 46 | if (!dp[j]) continue; 47 | if (wordDict.find(s.substr(j, i-j)) != wordDict.end()) { 48 | dp[i] = true; 49 | break; 50 | } 51 | } 52 | } 53 | return dp[size]; 54 | } 55 | }; 56 | 57 | -------------------------------------------------------------------------------- /141-linked-list-cycle/linked-list-cycle.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Given a linked list, determine if it has a cycle in it. 3 | // 4 | // 5 | // 6 | // Follow up: 7 | // Can you solve it without using extra space? 8 | // 9 | 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * struct ListNode { 14 | * int val; 15 | * ListNode *next; 16 | * ListNode(int x) : val(x), next(NULL) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | bool hasCycle(ListNode *head) { 22 | if (!head || !head->next) return false; 23 | ListNode *p = head, *q = head->next; 24 | while (p != q) { 25 | p = p->next; 26 | if (q->next && q->next->next) { 27 | q = q->next->next; 28 | } else { 29 | return false; 30 | } 31 | } 32 | return true; 33 | } 34 | }; 35 | 36 | -------------------------------------------------------------------------------- /142-linked-list-cycle-ii/linked-list-cycle-ii.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 3 | // 4 | // 5 | // 6 | // Note: Do not modify the linked list. 7 | // 8 | // 9 | // Follow up: 10 | // Can you solve it without using extra space? 11 | // 12 | 13 | 14 | /** 15 | * Definition for singly-linked list. 16 | * struct ListNode { 17 | * int val; 18 | * ListNode *next; 19 | * ListNode(int x) : val(x), next(NULL) {} 20 | * }; 21 | */ 22 | class Solution { 23 | public: 24 | ListNode *detectCycle(ListNode *head) { 25 | if (!head || !head->next) return nullptr; 26 | ListNode *p = head, *q = head->next; 27 | int step = 0; 28 | while (p != q) { 29 | p = p->next; 30 | ++step; 31 | if (q->next && q->next->next) { 32 | q = q->next->next; 33 | } else { 34 | return nullptr; 35 | } 36 | } 37 | p = head; 38 | q = q->next; 39 | while (p != q) { 40 | p = p->next; 41 | q = q->next; 42 | } 43 | return p; 44 | } 45 | }; 46 | 47 | -------------------------------------------------------------------------------- /143-reorder-list/reorder-list.cpp: -------------------------------------------------------------------------------- 1 | // Given a singly linked list L: L0→L1→…→Ln-1→Ln, 2 | // reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… 3 | // 4 | // You may not modify the values in the list's nodes, only nodes itself may be changed. 5 | // 6 | // Example 1: 7 | // 8 | // 9 | // Given 1->2->3->4, reorder it to 1->4->2->3. 10 | // 11 | // Example 2: 12 | // 13 | // 14 | // Given 1->2->3->4->5, reorder it to 1->5->2->4->3. 15 | // 16 | // 17 | 18 | 19 | /** 20 | * Definition for singly-linked list. 21 | * struct ListNode { 22 | * int val; 23 | * ListNode *next; 24 | * ListNode(int x) : val(x), next(NULL) {} 25 | * }; 26 | */ 27 | class Solution { 28 | public: 29 | void reorderList(ListNode* head) { 30 | if (!head || !head->next) return; 31 | int len = 0; 32 | ListNode *node = head; 33 | while (node) { 34 | ++len; 35 | node = node->next; 36 | } 37 | node = head; 38 | for (int i = 0; i < ((len+1)>>1)-1; ++i) { 39 | node = node->next; 40 | } 41 | ListNode *end = node->next; 42 | while (end->next) { 43 | ListNode *n = end->next; 44 | end->next = n->next; 45 | n->next = node->next; 46 | node->next = n; 47 | } 48 | ListNode *p = head; 49 | while (p != node) { 50 | ListNode *n = node->next; 51 | node->next = n->next; 52 | n->next = p->next; 53 | p->next = n; 54 | p = n->next; 55 | } 56 | } 57 | }; 58 | 59 | -------------------------------------------------------------------------------- /144-binary-tree-preorder-traversal/binary-tree-preorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | // Given a binary tree, return the preorder traversal of its nodes' values. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: [1,null,2,3] 7 | // 1 8 | // \ 9 | // 2 10 | // / 11 | // 3 12 | // 13 | // Output: [1,2,3] 14 | // 15 | // 16 | // Follow up: Recursive solution is trivial, could you do it iteratively? 17 | // 18 | 19 | 20 | /** 21 | * Definition for a binary tree node. 22 | * struct TreeNode { 23 | * int val; 24 | * TreeNode *left; 25 | * TreeNode *right; 26 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 27 | * }; 28 | */ 29 | class Solution { 30 | public: 31 | vector preorderTraversal(TreeNode* root) { 32 | vector ans; 33 | if (!root) return ans; 34 | stack s; 35 | s.push(root); 36 | while (!s.empty()) { 37 | TreeNode *top = s.top(); 38 | s.pop(); 39 | ans.push_back(top->val); 40 | if (top->right) s.push(top->right); 41 | if (top->left) s.push(top->left); 42 | } 43 | return ans; 44 | } 45 | }; 46 | 47 | -------------------------------------------------------------------------------- /145-binary-tree-postorder-traversal/binary-tree-postorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | // Given a binary tree, return the postorder traversal of its nodes' values. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: [1,null,2,3] 7 | // 1 8 | // \ 9 | // 2 10 | // / 11 | // 3 12 | // 13 | // Output: [3,2,1] 14 | // 15 | // 16 | // Follow up: Recursive solution is trivial, could you do it iteratively? 17 | // 18 | 19 | 20 | /** 21 | * Definition for a binary tree node. 22 | * struct TreeNode { 23 | * int val; 24 | * TreeNode *left; 25 | * TreeNode *right; 26 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 27 | * }; 28 | */ 29 | class Solution { 30 | public: 31 | vector postorderTraversal(TreeNode* root) { 32 | vector ans; 33 | if (!root) return ans; 34 | stack s; 35 | s.push(root); 36 | while (!s.empty()) { 37 | TreeNode *top = s.top(); 38 | s.pop(); 39 | ans.push_back(top->val); 40 | if (top->left) s.push(top->left); 41 | if (top->right) s.push(top->right); 42 | } 43 | reverse(ans.begin(), ans.end()); 44 | return ans; 45 | } 46 | }; 47 | 48 | -------------------------------------------------------------------------------- /148-sort-list/sort-list.cpp: -------------------------------------------------------------------------------- 1 | // Sort a linked list in O(n log n) time using constant space complexity. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: 4->2->1->3 7 | // Output: 1->2->3->4 8 | // 9 | // 10 | // Example 2: 11 | // 12 | // 13 | // Input: -1->5->3->4->0 14 | // Output: -1->0->3->4->5 15 | // 16 | 17 | 18 | /** 19 | * Definition for singly-linked list. 20 | * struct ListNode { 21 | * int val; 22 | * ListNode *next; 23 | * ListNode(int x) : val(x), next(NULL) {} 24 | * }; 25 | */ 26 | class Solution { 27 | public: 28 | ListNode* sortList(ListNode* head) { 29 | if (!head || !head->next) return head; 30 | ListNode *pre = head; 31 | ListNode *p1 = head; 32 | ListNode *p2 = head; 33 | while (p2 && p2->next) { 34 | pre = p1; 35 | p1 = p1->next; 36 | p2 = p2->next->next; 37 | } 38 | pre->next = nullptr; 39 | ListNode *r1 = sortList(head); 40 | ListNode *r2 = sortList(p1); 41 | return merge(r1, r2); 42 | } 43 | 44 | ListNode* merge(ListNode *h1, ListNode *h2) { 45 | if (!h2) return h1; 46 | if (!h1) return h2; 47 | ListNode *h = nullptr; 48 | if (h1->val < h2->val) { 49 | h = h1; 50 | h1 = h1->next; 51 | } else { 52 | h = h2; 53 | h2 = h2->next; 54 | } 55 | ListNode *p = h; 56 | while (h1 && h2) { 57 | if (h1->val < h2->val) { 58 | p->next = h1; 59 | h1 = h1->next; 60 | } else { 61 | p->next = h2; 62 | h2 = h2->next; 63 | } 64 | p = p->next; 65 | } 66 | if (h1) p->next = h1; 67 | if (h2) p->next = h2; 68 | return h; 69 | } 70 | }; 71 | 72 | -------------------------------------------------------------------------------- /151-reverse-words-in-a-string/reverse-words-in-a-string.cpp: -------------------------------------------------------------------------------- 1 | // Given an input string, reverse the string word by word. 2 | // 3 | // Example:   4 | // 5 | // 6 | // Input: "the sky is blue", 7 | // Output: "blue is sky the". 8 | // 9 | // 10 | // Note: 11 | // 12 | // 13 | // A word is defined as a sequence of non-space characters. 14 | // Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. 15 | // You need to reduce multiple spaces between two words to a single space in the reversed string. 16 | // 17 | // 18 | // Follow up: For C programmers, try to solve it in-place in O(1) space. 19 | // 20 | 21 | 22 | class Solution { 23 | public: 24 | void reverseWords(string &s) { 25 | auto b = s.begin(); 26 | while ((*b) == ' ') ++b; 27 | s.erase(s.begin(), b); 28 | b = s.end(); --b; 29 | while ((*b) == ' ') --b; 30 | s.erase(++b, s.end()); 31 | int i, j, k; 32 | for (i = 1; i < s.size();) { 33 | if (s[i] == ' ' && s[i-1] == ' ') { 34 | s.erase(i, 1); 35 | } else { 36 | ++i; 37 | } 38 | } 39 | reverse(s.begin(), s.end()); 40 | for (i = 0; i < s.size(); ++i) { 41 | if (s[i] == ' ') continue; 42 | for (j = i+1; j < s.size(); ++j) { 43 | if (s[j] == ' ') break; 44 | } 45 | for (int k = 0; k < (j-i)/2; ++k) { 46 | char c = s[i+k]; 47 | s[i+k] = s[j-k-1]; 48 | s[j-k-1] = c; 49 | } 50 | i = j-1; 51 | } 52 | } 53 | }; 54 | 55 | -------------------------------------------------------------------------------- /152-maximum-product-subarray/maximum-product-subarray.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: [2,3,-2,4] 7 | // Output: 6 8 | // Explanation: [2,3] has the largest product 6. 9 | // 10 | // 11 | // Example 2: 12 | // 13 | // 14 | // Input: [-2,0,-1] 15 | // Output: 0 16 | // Explanation: The result cannot be 2, because [-2,-1] is not a subarray. 17 | // 18 | 19 | 20 | class Solution { 21 | public: 22 | int maxProduct(vector& nums) { 23 | if (!nums.size()) return 0; 24 | int ans = nums[0]; 25 | int _max = ans, _min = ans; 26 | for (int i = 1; i < nums.size(); ++i) { 27 | if (nums[i] < 0) { 28 | swap(_max, _min); 29 | } 30 | _max = max(nums[i], nums[i]*_max); 31 | _min = min(nums[i], nums[i]*_min); 32 | ans = max(_max, ans); 33 | } 34 | return ans; 35 | } 36 | }; 37 | 38 | -------------------------------------------------------------------------------- /153-find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | // Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 2 | // 3 | // (i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]). 4 | // 5 | // Find the minimum element. 6 | // 7 | // You may assume no duplicate exists in the array. 8 | // 9 | // Example 1: 10 | // 11 | // 12 | // Input: [3,4,5,1,2] 13 | // Output: 1 14 | // 15 | // 16 | // Example 2: 17 | // 18 | // 19 | // Input: [4,5,6,7,0,1,2] 20 | // Output: 0 21 | // 22 | // 23 | 24 | 25 | class Solution { 26 | public: 27 | int findMin(vector& nums) { 28 | int len = nums.size(); 29 | if (len == 0) return 0; 30 | if (len == 1) return nums[0]; 31 | if (len == 2) return min(nums[0], nums[1]); 32 | if (nums[0] < nums[len-1]) return nums[0]; 33 | int mid = (len-1) / 2; 34 | if (nums[0] < nums[mid]) { 35 | vector temp(nums.begin()+mid, nums.end()); 36 | return findMin(temp); 37 | } 38 | vector temp(nums.begin(), nums.begin()+mid+1); 39 | return findMin(temp); 40 | } 41 | }; 42 | 43 | -------------------------------------------------------------------------------- /155-min-stack/min-stack.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 3 | // 4 | // 5 | // push(x) -- Push element x onto stack. 6 | // 7 | // 8 | // pop() -- Removes the element on top of the stack. 9 | // 10 | // 11 | // top() -- Get the top element. 12 | // 13 | // 14 | // getMin() -- Retrieve the minimum element in the stack. 15 | // 16 | // 17 | // 18 | // 19 | // Example: 20 | // 21 | // MinStack minStack = new MinStack(); 22 | // minStack.push(-2); 23 | // minStack.push(0); 24 | // minStack.push(-3); 25 | // minStack.getMin(); --> Returns -3. 26 | // minStack.pop(); 27 | // minStack.top(); --> Returns 0. 28 | // minStack.getMin(); --> Returns -2. 29 | // 30 | // 31 | 32 | 33 | class MinStack { 34 | public: 35 | MinStack() { 36 | } 37 | 38 | void push(int x) { 39 | m_stack.push(x); 40 | if (m_minStack.empty() || m_minStack.top() >= x) m_minStack.push(x); 41 | } 42 | 43 | void pop() { 44 | int t = m_stack.top(); 45 | m_stack.pop(); 46 | if (t == m_minStack.top()) m_minStack.pop(); 47 | } 48 | 49 | int top() { 50 | return m_stack.top(); 51 | } 52 | 53 | int getMin() { 54 | return m_minStack.top(); 55 | } 56 | 57 | private: 58 | stack m_stack; 59 | stack m_minStack; 60 | }; 61 | 62 | -------------------------------------------------------------------------------- /162-find-peak-element/find-peak-element.cpp: -------------------------------------------------------------------------------- 1 | // A peak element is an element that is greater than its neighbors. 2 | // 3 | // Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. 4 | // 5 | // The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 6 | // 7 | // You may imagine that nums[-1] = nums[n] = -∞. 8 | // 9 | // Example 1: 10 | // 11 | // 12 | // Input: nums = [1,2,3,1] 13 | // Output: 2 14 | // Explanation: 3 is a peak element and your function should return the index number 2. 15 | // 16 | // Example 2: 17 | // 18 | // 19 | // Input: nums = [1,2,1,3,5,6,4] 20 | // Output: 1 or 5 21 | // Explanation: Your function can return either index number 1 where the peak element is 2, 22 | //   or index number 5 where the peak element is 6. 23 | // 24 | // 25 | // Note: 26 | // 27 | // Your solution should be in logarithmic complexity. 28 | // 29 | 30 | 31 | class Solution { 32 | public: 33 | int findPeakElement(vector& nums) { 34 | int len = nums.size(); 35 | if (len < 2) return len-1; 36 | int low = 0, high = len-1; 37 | while (low < high) { 38 | int mid1 = (low+high)/2; 39 | int mid2 = mid1 + 1; 40 | if (nums[mid1] > nums[mid2]) { 41 | high = mid1; 42 | } else { 43 | low = mid2; 44 | } 45 | } 46 | return low; 47 | } 48 | }; 49 | 50 | -------------------------------------------------------------------------------- /165-compare-version-numbers/compare-version-numbers.cpp: -------------------------------------------------------------------------------- 1 | // Compare two version numbers version1 and version2. 2 | // If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0. 3 | // 4 | // You may assume that the version strings are non-empty and contain only digits and the . character. 5 | // The . character does not represent a decimal point and is used to separate number sequences. 6 | // For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. 7 | // 8 | // Example 1: 9 | // 10 | // 11 | // Input: version1 = "0.1", version2 = "1.1" 12 | // Output: -1 13 | // 14 | // Example 2: 15 | // 16 | // 17 | // Input: version1 = "1.0.1", version2 = "1" 18 | // Output: 1 19 | // 20 | // Example 3: 21 | // 22 | // 23 | // Input: version1 = "7.5.2.4", version2 = "7.5.3" 24 | // Output: -1 25 | // 26 | 27 | 28 | class Solution { 29 | public: 30 | int compareVersion(string version1, string version2) { 31 | int i = 0, j = 0; 32 | int l1 = version1.size(); 33 | int l2 = version2.size(); 34 | if (!l1) return -1; 35 | if (!l2) return 1; 36 | 37 | int v1 = 0, v2 = 0; 38 | while (i < l1 || j < l2) { 39 | v1 = 0; v2 = 0; 40 | 41 | while (i < l1 && version1[i] != '.') v1 = v1*10 + version1[i++]-'0'; 42 | while (j < l2 && version2[j] != '.') v2 = v2*10 + version2[j++]-'0'; 43 | 44 | if (v1 > v2) return 1; 45 | if (v1 < v2) return -1; 46 | ++i; ++j; 47 | } 48 | return 0; 49 | } 50 | }; 51 | 52 | -------------------------------------------------------------------------------- /165-compare-version-numbers/compare-version-numbers.js: -------------------------------------------------------------------------------- 1 | // Compare two version numbers version1 and version2. 2 | // If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0. 3 | // 4 | // You may assume that the version strings are non-empty and contain only digits and the . character. 5 | // The . character does not represent a decimal point and is used to separate number sequences. 6 | // For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. 7 | // 8 | // Example 1: 9 | // 10 | // 11 | // Input: version1 = "0.1", version2 = "1.1" 12 | // Output: -1 13 | // 14 | // Example 2: 15 | // 16 | // 17 | // Input: version1 = "1.0.1", version2 = "1" 18 | // Output: 1 19 | // 20 | // Example 3: 21 | // 22 | // 23 | // Input: version1 = "7.5.2.4", version2 = "7.5.3" 24 | // Output: -1 25 | // 26 | 27 | 28 | /** 29 | * @param {string} version1 30 | * @param {string} version2 31 | * @return {number} 32 | */ 33 | var compareVersion = function(version1, version2) { 34 | v1 = version1.split('.'); 35 | v2 = version2.split('.'); 36 | var l = Math.max(v1.length,v2.length); 37 | for (var i = 0;i < l;++i) { 38 | v1[i] = v1[i] || 0; 39 | v2[i] = v2[i] || 0; 40 | if (+v1[i] > +v2[i]) return 1; 41 | if (+v1[i] < +v2[i]) return -1; 42 | } 43 | return 0; 44 | }; 45 | 46 | 47 | -------------------------------------------------------------------------------- /166-fraction-to-recurring-decimal/fraction-to-recurring-decimal.cpp: -------------------------------------------------------------------------------- 1 | // Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. 2 | // 3 | // If the fractional part is repeating, enclose the repeating part in parentheses. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: numerator = 1, denominator = 2 9 | // Output: "0.5" 10 | // 11 | // 12 | // Example 2: 13 | // 14 | // 15 | // Input: numerator = 2, denominator = 1 16 | // Output: "2" 17 | // 18 | // Example 3: 19 | // 20 | // 21 | // Input: numerator = 2, denominator = 3 22 | // Output: "0.(6)" 23 | // 24 | // 25 | 26 | 27 | class Solution { 28 | public: 29 | string fractionToDecimal(int numerator, int denominator) { 30 | string ans; 31 | long long n = numerator; 32 | long long d = denominator; 33 | if (n * d < 0) ans += '-'; 34 | n = abs(n); 35 | d = abs(d); 36 | ans += to_string(n/d); 37 | if (n % d == 0) return ans; 38 | 39 | ans += '.'; 40 | unordered_map map; 41 | for (long long r = n%d; r ; r %= d) { 42 | if (map[r] > 0) { 43 | ans.insert(map[r], 1, '('); 44 | ans += ')'; 45 | return ans; 46 | } 47 | map[r] = ans.size(); 48 | r *= 10; 49 | 50 | ans += to_string(r / d); 51 | } 52 | return ans; 53 | } 54 | }; 55 | 56 | -------------------------------------------------------------------------------- /167-two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 2 | // 3 | // The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. 4 | // 5 | // Note: 6 | // 7 | // 8 | // Your returned answers (both index1 and index2) are not zero-based. 9 | // You may assume that each input would have exactly one solution and you may not use the same element twice. 10 | // 11 | // 12 | // Example: 13 | // 14 | // 15 | // Input: numbers = [2,7,11,15], target = 9 16 | // Output: [1,2] 17 | // Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. 18 | // 19 | 20 | 21 | class Solution { 22 | public: 23 | vector twoSum(vector& numbers, int target) { 24 | int len = numbers.size(); 25 | int l = 0, r = len-1; 26 | while (l<=r) { 27 | int t = numbers[l]+numbers[r]; 28 | if (t == target) { 29 | return vector{l+1, r+1}; 30 | } 31 | if (t < target) { 32 | ++l; 33 | } else { 34 | --r; 35 | } 36 | } 37 | return vector{-1,-1}; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /168-excel-sheet-column-title/excel-sheet-column-title.cpp: -------------------------------------------------------------------------------- 1 | // Given a positive integer, return its corresponding column title as appear in an Excel sheet. 2 | // 3 | // For example: 4 | // 5 | // 6 | // 1 -> A 7 | // 2 -> B 8 | // 3 -> C 9 | // ... 10 | // 26 -> Z 11 | // 27 -> AA 12 | // 28 -> AB 13 | // ... 14 | // 15 | // 16 | // Example 1: 17 | // 18 | // 19 | // Input: 1 20 | // Output: "A" 21 | // 22 | // 23 | // Example 2: 24 | // 25 | // 26 | // Input: 28 27 | // Output: "AB" 28 | // 29 | // 30 | // Example 3: 31 | // 32 | // 33 | // Input: 701 34 | // Output: "ZY" 35 | // 36 | // 37 | 38 | 39 | class Solution { 40 | public: 41 | string convertToTitle(int n) { 42 | string ans; 43 | while(n) { 44 | ans += (--n)%26+'A'; 45 | n /= 26; 46 | } 47 | reverse(ans.begin(), ans.end()); 48 | return ans; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /169-majority-element/majority-element.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 2 | // 3 | // You may assume that the array is non-empty and the majority element always exist in the array. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: [3,2,3] 9 | // Output: 3 10 | // 11 | // Example 2: 12 | // 13 | // 14 | // Input: [2,2,1,1,1,2,2] 15 | // Output: 2 16 | // 17 | // 18 | 19 | 20 | class Solution { 21 | public: 22 | int majorityElement(vector& nums) { 23 | sort(nums.begin(), nums.end()); 24 | return nums[nums.size()/2]; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /169-majority-element/majority-element.js: -------------------------------------------------------------------------------- 1 | // Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 2 | // 3 | // You may assume that the array is non-empty and the majority element always exist in the array. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: [3,2,3] 9 | // Output: 3 10 | // 11 | // Example 2: 12 | // 13 | // 14 | // Input: [2,2,1,1,1,2,2] 15 | // Output: 2 16 | // 17 | // 18 | 19 | 20 | /** 21 | * @param {number[]} nums 22 | * @return {number} 23 | */ 24 | var majorityElement = function(nums) { 25 | return nums.sort()[Math.floor(nums.length / 2)]; 26 | }; 27 | -------------------------------------------------------------------------------- /171-excel-sheet-column-number/excel-sheet-column-number.cpp: -------------------------------------------------------------------------------- 1 | // Given a column title as appear in an Excel sheet, return its corresponding column number. 2 | // 3 | // For example: 4 | // 5 | // 6 | // A -> 1 7 | // B -> 2 8 | // C -> 3 9 | // ... 10 | // Z -> 26 11 | // AA -> 27 12 | // AB -> 28 13 | // ... 14 | // 15 | // 16 | // Example 1: 17 | // 18 | // 19 | // Input: "A" 20 | // Output: 1 21 | // 22 | // 23 | // Example 2: 24 | // 25 | // 26 | // Input: "AB" 27 | // Output: 28 28 | // 29 | // 30 | // Example 3: 31 | // 32 | // 33 | // Input: "ZY" 34 | // Output: 701 35 | // 36 | // 37 | 38 | 39 | class Solution { 40 | public: 41 | int titleToNumber(string s) { 42 | int ans = 0; 43 | for (auto& i : s) { 44 | ans = ans*26 + i-'A'+1; 45 | } 46 | return ans; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /172-factorial-trailing-zeroes/factorial-trailing-zeroes.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer n, return the number of trailing zeroes in n!. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: 3 7 | // Output: 0 8 | // Explanation: 3! = 6, no trailing zero. 9 | // 10 | // Example 2: 11 | // 12 | // 13 | // Input: 5 14 | // Output: 1 15 | // Explanation: 5! = 120, one trailing zero. 16 | // 17 | // Note: Your solution should be in logarithmic time complexity. 18 | // 19 | 20 | 21 | class Solution { 22 | public: 23 | int trailingZeroes(int n) { 24 | int ans = 0; 25 | while (n) { 26 | ans += n/5; 27 | n /= 5; 28 | } 29 | return ans; 30 | } 31 | }; 32 | 33 | -------------------------------------------------------------------------------- /173-binary-search-tree-iterator/binary-search-tree-iterator.cpp: -------------------------------------------------------------------------------- 1 | // Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. 2 | // 3 | // Calling next() will return the next smallest number in the BST. 4 | // 5 | // Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. 6 | // 7 | // Credits:Special thanks to @ts for adding this problem and creating all test cases. 8 | 9 | 10 | /** 11 | * Definition for binary tree 12 | * struct TreeNode { 13 | * int val; 14 | * TreeNode *left; 15 | * TreeNode *right; 16 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 17 | * }; 18 | */ 19 | class BSTIterator { 20 | public: 21 | BSTIterator(TreeNode *root) { 22 | while (root) { 23 | s.push(root); 24 | root = root->left; 25 | } 26 | } 27 | 28 | /** @return whether we have a next smallest number */ 29 | bool hasNext() { 30 | return !s.empty(); 31 | } 32 | 33 | /** @return the next smallest number */ 34 | int next() { 35 | TreeNode *t = s.top(); 36 | s.pop(); 37 | int val = t->val; 38 | t = t->right; 39 | while (t) { 40 | s.push(t); 41 | t = t->left; 42 | } 43 | return val; 44 | } 45 | 46 | private: 47 | stack s; 48 | }; 49 | 50 | /** 51 | * Your BSTIterator will be called like this: 52 | * BSTIterator i = BSTIterator(root); 53 | * while (i.hasNext()) cout << i.next(); 54 | */ 55 | 56 | -------------------------------------------------------------------------------- /179-largest-number/largest-number.cpp: -------------------------------------------------------------------------------- 1 | // Given a list of non negative integers, arrange them such that they form the largest number. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: [10,2] 7 | // Output: "210" 8 | // 9 | // Example 2: 10 | // 11 | // 12 | // Input: [3,30,34,5,9] 13 | // Output: "9534330" 14 | // 15 | // 16 | // Note: The result may be very large, so you need to return a string instead of an integer. 17 | // 18 | 19 | 20 | class Solution { 21 | public: 22 | string largestNumber(vector& nums) { 23 | auto cmp = [](int a, int b) { 24 | string sa = to_string(a); 25 | string sb = to_string(b); 26 | return sa+sb > sb+sa; 27 | }; 28 | sort(nums.begin(), nums.end(), cmp); 29 | stringstream ss; 30 | for (auto&& i : nums) { 31 | ss << i; 32 | } 33 | string ans = ss.str(); 34 | size_t i = 0; 35 | while (ans[i] == '0' && i < ans.size()-1) { 36 | ++i; 37 | } 38 | return ans.substr(i); 39 | } 40 | }; 41 | 42 | -------------------------------------------------------------------------------- /187-repeated-dna-sequences/repeated-dna-sequences.cpp: -------------------------------------------------------------------------------- 1 | // All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. 2 | // 3 | // Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. 4 | // 5 | // Example: 6 | // 7 | // 8 | // Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" 9 | // 10 | // Output: ["AAAAACCCCC", "CCCCCAAAAA"] 11 | // 12 | // 13 | 14 | 15 | class Solution { 16 | public: 17 | vector findRepeatedDnaSequences(string s) { 18 | vector ans; 19 | unordered_map m; 20 | for (int i = 0; i+9 < s.size(); ++i) { 21 | string sub = s.substr(i, 10); 22 | ++m[sub]; 23 | } 24 | for (auto&& p : m) { 25 | if (p.second > 1) { 26 | ans.push_back(p.first); 27 | } 28 | } 29 | return ans; 30 | } 31 | }; 32 | 33 | -------------------------------------------------------------------------------- /188-best-time-to-buy-and-sell-stock-iv/best-time-to-buy-and-sell-stock-iv.cpp: -------------------------------------------------------------------------------- 1 | // Say you have an array for which the ith element is the price of a given stock on day i. 2 | // 3 | // Design an algorithm to find the maximum profit. You may complete at most k transactions. 4 | // 5 | // Note: 6 | // You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 7 | // 8 | // Example 1: 9 | // 10 | // 11 | // Input: [2,4,1], k = 2 12 | // Output: 2 13 | // Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. 14 | // 15 | // 16 | // Example 2: 17 | // 18 | // 19 | // Input: [3,2,6,5,0,3], k = 2 20 | // Output: 7 21 | // Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. 22 | //   Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. 23 | // 24 | // 25 | 26 | 27 | //https://discuss.leetcode.com/topic/8984/a-concise-dp-solution-in-java 28 | class Solution { 29 | public: 30 | int maxProfit(int k, vector& prices) { 31 | int len = prices.size(); 32 | if (k > len/2) { 33 | int ans = 0; 34 | for (int i = 1; i < len; ++i) { 35 | ans += max(0, prices[i]-prices[i-1]); 36 | } 37 | return ans; 38 | } 39 | 40 | vector> dp(k+1, vector(len, 0)); 41 | for (int i = 1; i <= k; ++i) { 42 | int tmpMax = -prices[0]; 43 | for (int j = 1; j < len; ++j) { 44 | dp[i][j] = max(dp[i][j-1], prices[j]+tmpMax); 45 | tmpMax = max(tmpMax, dp[i-1][j-1] - prices[j]); 46 | } 47 | } 48 | return dp[k][len-1]; 49 | } 50 | }; 51 | 52 | -------------------------------------------------------------------------------- /189-rotate-array/rotate-array.cpp: -------------------------------------------------------------------------------- 1 | // Given an array, rotate the array to the right by k steps, where k is non-negative. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: [1,2,3,4,5,6,7] and k = 3 7 | // Output: [5,6,7,1,2,3,4] 8 | // Explanation: 9 | // rotate 1 steps to the right: [7,1,2,3,4,5,6] 10 | // rotate 2 steps to the right: [6,7,1,2,3,4,5] 11 | // rotate 3 steps to the right: [5,6,7,1,2,3,4] 12 | // 13 | // 14 | // Example 2: 15 | // 16 | // 17 | // Input: [-1,-100,3,99] and k = 2 18 | // Output: [3,99,-1,-100] 19 | // Explanation: 20 | // rotate 1 steps to the right: [99,-1,-100,3] 21 | // rotate 2 steps to the right: [3,99,-1,-100] 22 | // 23 | // 24 | // Note: 25 | // 26 | // 27 | // Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 28 | // Could you do it in-place with O(1) extra space? 29 | // 30 | // 31 | 32 | 33 | class Solution { 34 | public: 35 | void rotate(vector& nums, int k) { 36 | int len = nums.size(); 37 | k %= len; 38 | reverse(nums.begin(), nums.begin()+len-k); 39 | reverse(nums.begin()+len-k, nums.end()); 40 | reverse(nums.begin(), nums.end()); 41 | } 42 | }; 43 | 44 | -------------------------------------------------------------------------------- /189-rotate-array/rotate-array.js: -------------------------------------------------------------------------------- 1 | // Given an array, rotate the array to the right by k steps, where k is non-negative. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: [1,2,3,4,5,6,7] and k = 3 7 | // Output: [5,6,7,1,2,3,4] 8 | // Explanation: 9 | // rotate 1 steps to the right: [7,1,2,3,4,5,6] 10 | // rotate 2 steps to the right: [6,7,1,2,3,4,5] 11 | // rotate 3 steps to the right: [5,6,7,1,2,3,4] 12 | // 13 | // 14 | // Example 2: 15 | // 16 | // 17 | // Input: [-1,-100,3,99] and k = 2 18 | // Output: [3,99,-1,-100] 19 | // Explanation: 20 | // rotate 1 steps to the right: [99,-1,-100,3] 21 | // rotate 2 steps to the right: [3,99,-1,-100] 22 | // 23 | // 24 | // Note: 25 | // 26 | // 27 | // Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 28 | // Could you do it in-place with O(1) extra space? 29 | // 30 | // 31 | 32 | 33 | /** 34 | * @param {number[]} nums 35 | * @param {number} k 36 | * @return {void} Do not return anything, modify nums in-place instead. 37 | */ 38 | var rotate = function(nums, k) { 39 | var reverse = function(n) { 40 | for (var i = 0;i < n.length / 2;++i) { 41 | var t = n[i]; 42 | n[i] = n[n.length - i - 1]; 43 | n[n.length - i - 1] = t; 44 | } 45 | return n; 46 | } 47 | var t = reverse(reverse(nums.slice(0,nums.length - k)).concat(reverse(nums.slice(nums.length - k,nums.length)))); 48 | for (var i = 0;i < nums.length;++i) 49 | nums[i] = t[i]; 50 | }; 51 | -------------------------------------------------------------------------------- /190-reverse-bits/reverse-bits.cpp: -------------------------------------------------------------------------------- 1 | // Reverse bits of a given 32 bits unsigned integer. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: 43261596 7 | // Output: 964176192 8 | // Explanation: 43261596 represented in binary as 00000010100101000001111010011100, 9 | //   return 964176192 represented in binary as 00111001011110000010100101000000. 10 | // 11 | // 12 | // Follow up: 13 | // If this function is called many times, how would you optimize it? 14 | 15 | 16 | class Solution { 17 | public: 18 | uint32_t reverseBits(uint32_t n) { 19 | uint32_t ans = 0; 20 | for (int i = 0; i < 32; ++i) { 21 | ans = (ans << 1) | (n & 1); 22 | n >>= 1; 23 | } 24 | return ans; 25 | } 26 | }; 27 | 28 | -------------------------------------------------------------------------------- /190-reverse-bits/reverse-bits.js: -------------------------------------------------------------------------------- 1 | // Reverse bits of a given 32 bits unsigned integer. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: 43261596 7 | // Output: 964176192 8 | // Explanation: 43261596 represented in binary as 00000010100101000001111010011100, 9 | //   return 964176192 represented in binary as 00111001011110000010100101000000. 10 | // 11 | // 12 | // Follow up: 13 | // If this function is called many times, how would you optimize it? 14 | 15 | 16 | /** 17 | * @param {number} n - a positive integer 18 | * @return {number} - a positive integer 19 | */ 20 | var reverseBits = function(n) { 21 | if (n === 0) return 0; 22 | var r = 0; 23 | for (var i = 0;i < 32;++i) { 24 | r *= 2; 25 | r += (n&1); 26 | n >>= 1; 27 | } 28 | return r; 29 | }; 30 | -------------------------------------------------------------------------------- /191-number-of-1-bits/number-of-1-bits.cpp: -------------------------------------------------------------------------------- 1 | // Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: 11 7 | // Output: 3 8 | // Explanation: Integer 11 has binary representation 00000000000000000000000000001011 9 | // 10 | // 11 | // Example 2: 12 | // 13 | // 14 | // Input: 128 15 | // Output: 1 16 | // Explanation: Integer 128 has binary representation 00000000000000000000000010000000 17 | // 18 | // 19 | 20 | 21 | class Solution { 22 | public: 23 | int hammingWeight(uint32_t n) { 24 | int ans = 0; 25 | while (n) { 26 | n &= (n-1); 27 | ++ans; 28 | } 29 | return ans; 30 | } 31 | }; 32 | 33 | -------------------------------------------------------------------------------- /191-number-of-1-bits/number-of-1-bits.js: -------------------------------------------------------------------------------- 1 | // Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: 11 7 | // Output: 3 8 | // Explanation: Integer 11 has binary representation 00000000000000000000000000001011 9 | // 10 | // 11 | // Example 2: 12 | // 13 | // 14 | // Input: 128 15 | // Output: 1 16 | // Explanation: Integer 128 has binary representation 00000000000000000000000010000000 17 | // 18 | // 19 | 20 | 21 | /** 22 | * @param {number} n - a positive integer 23 | * @return {number} 24 | */ 25 | var hammingWeight = function(n) { 26 | if (n === 0) return 0; 27 | var c = 0; 28 | while (n !== 0) { 29 | ++c; 30 | n &= (n-1); 31 | } 32 | return c; 33 | }; 34 | -------------------------------------------------------------------------------- /198-house-robber/house-robber.cpp: -------------------------------------------------------------------------------- 1 | // You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. 2 | // 3 | // Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: [1,2,3,1] 9 | // Output: 4 10 | // Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). 11 | //   Total amount you can rob = 1 + 3 = 4. 12 | // 13 | // Example 2: 14 | // 15 | // 16 | // Input: [2,7,9,3,1] 17 | // Output: 12 18 | // Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). 19 | //   Total amount you can rob = 2 + 9 + 1 = 12. 20 | // 21 | // 22 | 23 | 24 | class Solution { 25 | public: 26 | int rob(vector& nums) { 27 | int n = 0, y = 0; 28 | for (auto&& num : nums) { 29 | int t = n; 30 | n = max(n, y); 31 | y = num + t; 32 | } 33 | return max(n,y); 34 | } 35 | }; 36 | 37 | -------------------------------------------------------------------------------- /199-binary-tree-right-side-view/binary-tree-right-side-view.cpp: -------------------------------------------------------------------------------- 1 | // Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: [1,2,3,null,5,null,4] 7 | // Output: [1, 3, 4] 8 | // Explanation: 9 | // 10 | // 1 <--- 11 | // / \ 12 | // 2 3 <--- 13 | // \ \ 14 | // 5 4 <--- 15 | // 16 | // 17 | 18 | 19 | /** 20 | * Definition for a binary tree node. 21 | * struct TreeNode { 22 | * int val; 23 | * TreeNode *left; 24 | * TreeNode *right; 25 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 26 | * }; 27 | */ 28 | class Solution { 29 | public: 30 | vector rightSideView(TreeNode* root) { 31 | queue q[2]; 32 | vector res; 33 | if (!root) return res; 34 | 35 | int l = 0; 36 | q[0].push(root); 37 | while (!q[0].empty() || !q[1].empty()) { 38 | while (!q[l].empty()) { 39 | TreeNode *temp = q[l].front(); 40 | q[l].pop(); 41 | if (temp->left) q[1-l].push(temp->left); 42 | if (temp->right) q[1-l].push(temp->right); 43 | if (q[l].empty()) res.push_back(temp->val); 44 | } 45 | l = 1-l; 46 | } 47 | return res; 48 | } 49 | }; 50 | 51 | -------------------------------------------------------------------------------- /200-number-of-islands/number-of-islands.cpp: -------------------------------------------------------------------------------- 1 | // Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: 7 | // 11110 8 | // 11010 9 | // 11000 10 | // 00000 11 | // 12 | // Output: 1 13 | // 14 | // 15 | // Example 2: 16 | // 17 | // 18 | // Input: 19 | // 11000 20 | // 11000 21 | // 00100 22 | // 00011 23 | // 24 | // Output: 3 25 | // 26 | // 27 | 28 | 29 | class Solution { 30 | public: 31 | int numIslands(vector>& grid) { 32 | int ans = 0; 33 | int m = grid.size(); 34 | if (m == 0) return ans; 35 | int n = grid[0].size(); 36 | function change = [&](int i, int j)-> void { 37 | if (i >= 0 && i < m && j >=0 && j < n && grid[i][j] == '1') { 38 | grid[i][j] = '0'; 39 | change(i-1,j); 40 | change(i+1,j); 41 | change(i,j-1); 42 | change(i,j+1); 43 | } 44 | }; 45 | for (int i = 0; i < m; ++i) { 46 | for (int j = 0; j < n; ++j) { 47 | if (grid[i][j] == '1') { 48 | ++ans; 49 | change(i, j); 50 | } 51 | } 52 | } 53 | return ans; 54 | } 55 | }; 56 | 57 | 58 | -------------------------------------------------------------------------------- /201-bitwise-and-of-numbers-range/bitwise-and-of-numbers-range.cpp: -------------------------------------------------------------------------------- 1 | // Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: [5,7] 7 | // Output: 4 8 | // 9 | // 10 | // Example 2: 11 | // 12 | // 13 | // Input: [0,1] 14 | // Output: 0 15 | // 16 | 17 | 18 | class Solution { 19 | public: 20 | int rangeBitwiseAnd(int m, int n) { 21 | int ans = 0; 22 | while (m != n) { 23 | m >>= 1; 24 | n >>= 1; 25 | ++ans; 26 | } 27 | return n << ans; 28 | } 29 | }; 30 | 31 | -------------------------------------------------------------------------------- /202-happy-number/happy-number.cpp: -------------------------------------------------------------------------------- 1 | // Write an algorithm to determine if a number is "happy". 2 | // 3 | // A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 4 | // 5 | // Example:  6 | // 7 | // 8 | // Input: 19 9 | // Output: true 10 | // Explanation: 11 | // 12 + 92 = 82 12 | // 82 + 22 = 68 13 | // 62 + 82 = 100 14 | // 12 + 02 + 02 = 1 15 | // 16 | // 17 | 18 | 19 | class Solution { 20 | public: 21 | unordered_map m; 22 | 23 | bool isHappy(int n) { 24 | if (m.find(n) != m.end()) return m[n]; 25 | int sum = 0; 26 | int save_n = n; 27 | while (n) { 28 | int t = n % 10; 29 | sum += t*t; 30 | n /= 10; 31 | } 32 | if (sum == 1) { 33 | return m[save_n] = true; 34 | } 35 | m[save_n] = false; 36 | return isHappy(sum); 37 | } 38 | }; 39 | 40 | -------------------------------------------------------------------------------- /203-remove-linked-list-elements/remove-linked-list-elements.cpp: -------------------------------------------------------------------------------- 1 | // Remove all elements from a linked list of integers that have value val. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: 1->2->6->3->4->5->6, val = 6 7 | // Output: 1->2->3->4->5 8 | // 9 | // 10 | 11 | 12 | /** 13 | * Definition for singly-linked list. 14 | * struct ListNode { 15 | * int val; 16 | * ListNode *next; 17 | * ListNode(int x) : val(x), next(NULL) {} 18 | * }; 19 | */ 20 | class Solution { 21 | public: 22 | ListNode* removeElements(ListNode* head, int val) { 23 | ListNode *newHead = new ListNode(-1); 24 | newHead->next = head; 25 | ListNode *p = newHead; 26 | while (p->next) { 27 | if (p->next->val == val) { 28 | ListNode *temp = p->next; 29 | p->next = temp->next; 30 | delete temp; 31 | } else { 32 | p = p->next; 33 | } 34 | } 35 | ListNode *ans = newHead->next; 36 | delete newHead; 37 | return ans; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /204-count-primes/count-primes.cpp: -------------------------------------------------------------------------------- 1 | // Count the number of prime numbers less than a non-negative number, n. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: 10 7 | // Output: 4 8 | // Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 9 | // 10 | // 11 | 12 | 13 | class Solution { 14 | public: 15 | int countPrimes(int n) { 16 | vector isPrime(n, true); 17 | for (int i = 2; i*i < n; ++i) { 18 | if (!isPrime[i]) continue; 19 | for (int j = i*i; j < n; j+=i) { 20 | isPrime[j] = false; 21 | } 22 | } 23 | int ans = 0; 24 | for (int i = 2; i < n; ++i) { 25 | if (isPrime[i]) ++ans; 26 | } 27 | return ans; 28 | } 29 | }; 30 | 31 | -------------------------------------------------------------------------------- /205-isomorphic-strings/isomorphic-strings.cpp: -------------------------------------------------------------------------------- 1 | // Given two strings s and t, determine if they are isomorphic. 2 | // 3 | // Two strings are isomorphic if the characters in s can be replaced to get t. 4 | // 5 | // All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. 6 | // 7 | // Example 1: 8 | // 9 | // 10 | // Input: s = "egg", t = "add" 11 | // Output: true 12 | // 13 | // 14 | // Example 2: 15 | // 16 | // 17 | // Input: s = "foo", t = "bar" 18 | // Output: false 19 | // 20 | // Example 3: 21 | // 22 | // 23 | // Input: s = "paper", t = "title" 24 | // Output: true 25 | // 26 | // Note: 27 | // You may assume both s and t have the same length. 28 | // 29 | 30 | 31 | class Solution { 32 | public: 33 | bool isIsomorphic(string s, string t) { 34 | vector s2t(256, -1); 35 | vector t2s(256, -1); 36 | 37 | for (int i = 0; i < s.length(); ++i) { 38 | if (s2t[s[i]] != -1 && s2t[s[i]] != t[i]) { 39 | return false; 40 | } 41 | if (t2s[t[i]] != -1 && t2s[t[i]] != s[i]) { 42 | return false; 43 | } 44 | s2t[s[i]] = t[i]; 45 | t2s[t[i]] = s[i]; 46 | } 47 | return true; 48 | } 49 | }; 50 | 51 | -------------------------------------------------------------------------------- /205-isomorphic-strings/isomorphic-strings.js: -------------------------------------------------------------------------------- 1 | // Given two strings s and t, determine if they are isomorphic. 2 | // 3 | // Two strings are isomorphic if the characters in s can be replaced to get t. 4 | // 5 | // All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. 6 | // 7 | // Example 1: 8 | // 9 | // 10 | // Input: s = "egg", t = "add" 11 | // Output: true 12 | // 13 | // 14 | // Example 2: 15 | // 16 | // 17 | // Input: s = "foo", t = "bar" 18 | // Output: false 19 | // 20 | // Example 3: 21 | // 22 | // 23 | // Input: s = "paper", t = "title" 24 | // Output: true 25 | // 26 | // Note: 27 | // You may assume both s and t have the same length. 28 | // 29 | 30 | 31 | /** 32 | * @param {string} s 33 | * @param {string} t 34 | * @return {boolean} 35 | */ 36 | var isIsomorphic = function(s, t) { 37 | var normal = function(str) { 38 | var hash = {}; 39 | var arr = []; 40 | var index = 0; 41 | for (var i = 0;i < str.length;++i) { 42 | if (hash[str[i]] !== undefined) { 43 | arr[arr.length] = hash[str[i]]; 44 | } else { 45 | arr[arr.length] = index; 46 | hash[str[i]] = index++; 47 | } 48 | } 49 | return arr; 50 | } 51 | 52 | var as = normal(s); 53 | var at = normal(t); 54 | for (var i = 0;i < as.length;++i) { 55 | if (as[i] !== at[i]) return false; 56 | } 57 | return true; 58 | }; 59 | -------------------------------------------------------------------------------- /206-reverse-linked-list/reverse-linked-list.cpp: -------------------------------------------------------------------------------- 1 | // Reverse a singly linked list. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: 1->2->3->4->5->NULL 7 | // Output: 5->4->3->2->1->NULL 8 | // 9 | // 10 | // Follow up: 11 | // 12 | // A linked list can be reversed either iteratively or recursively. Could you implement both? 13 | // 14 | 15 | 16 | /** 17 | * Definition for singly-linked list. 18 | * struct ListNode { 19 | * int val; 20 | * ListNode *next; 21 | * ListNode(int x) : val(x), next(NULL) {} 22 | * }; 23 | */ 24 | class Solution { 25 | public: 26 | ListNode* reverseList(ListNode* head) { 27 | ListNode *newHead = new ListNode(-1); 28 | ListNode *p = head; 29 | while (p) { 30 | ListNode *n = newHead->next; 31 | newHead->next = p; 32 | p = p->next; 33 | newHead->next->next = n; 34 | } 35 | p = newHead->next; 36 | delete newHead; 37 | return p; 38 | } 39 | }; 40 | 41 | -------------------------------------------------------------------------------- /209-minimum-size-subarray-sum/minimum-size-subarray-sum.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. 2 | // 3 | // Example:  4 | // 5 | // 6 | // Input: s = 7, nums = [2,3,1,2,4,3] 7 | // Output: 2 8 | // Explanation: the subarray [4,3] has the minimal length under the problem constraint. 9 | // 10 | // Follow up: 11 | // 12 | // If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).  13 | // 14 | 15 | 16 | class Solution { 17 | public: 18 | int minSubArrayLen(int s, vector& nums) { 19 | int start = 0, current = 0, sum = 0, ans = INT_MAX; 20 | while (current < nums.size()) { 21 | sum += nums[current++]; 22 | 23 | while (sum >= s) { 24 | ans = min(ans, current-start); 25 | sum -= nums[start++]; 26 | } 27 | } 28 | return ans==INT_MAX ? 0 : ans; 29 | } 30 | }; 31 | 32 | -------------------------------------------------------------------------------- /213-house-robber-ii/house-robber-ii.cpp: -------------------------------------------------------------------------------- 1 | // You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. 2 | // 3 | // Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: [2,3,2] 9 | // Output: 3 10 | // Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), 11 | //   because they are adjacent houses. 12 | // 13 | // 14 | // Example 2: 15 | // 16 | // 17 | // Input: [1,2,3,1] 18 | // Output: 4 19 | // Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). 20 | //   Total amount you can rob = 1 + 3 = 4. 21 | // 22 | 23 | 24 | class Solution { 25 | public: 26 | int rob1(vector& nums, int begin, int end) { 27 | int n = 0, y = 0; 28 | for (int i = begin;i < end;++i) { 29 | int num = nums[i]; 30 | int t = n; 31 | n = max(n, y); 32 | y = num + t; 33 | } 34 | return max(n,y); 35 | } 36 | 37 | int rob(vector& nums) { 38 | int size = nums.size(); 39 | if (size == 0) return 0; 40 | if (size == 1) return nums[0]; 41 | return max(rob1(nums, 0, size-1), rob1(nums, 1, size)); 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /214-shortest-palindrome/shortest-palindrome.cpp: -------------------------------------------------------------------------------- 1 | // Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: "aacecaaa" 7 | // Output: "aaacecaaa" 8 | // 9 | // 10 | // Example 2: 11 | // 12 | // 13 | // Input: "abcd" 14 | // Output: "dcbabcd" 15 | // 16 | 17 | 18 | class Solution { 19 | public: 20 | string shortestPalindrome(string s) { 21 | string res(s); 22 | reverse(res.begin(), res.end()); 23 | for (int i = 0;i < res.length();++i) { 24 | if (res.substr(i) == s.substr(0,s.length()-i)) { 25 | return res.substr(0,i) + s; 26 | } 27 | } 28 | return res + s; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /215-kth-largest-element-in-an-array/kth-largest-element-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | // Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 2 | // 3 | // Example 1: 4 | // 5 | // 6 | // Input: [3,2,1,5,6,4] and k = 2 7 | // Output: 5 8 | // 9 | // 10 | // Example 2: 11 | // 12 | // 13 | // Input: [3,2,3,1,2,4,5,5,6] and k = 4 14 | // Output: 4 15 | // 16 | // Note: 17 | // You may assume k is always valid, 1 ≤ k ≤ array's length. 18 | // 19 | 20 | 21 | class Solution { 22 | public: 23 | int findKthLargest(vector& nums, int k) { 24 | priority_queue, greater > q; 25 | int i = 0; 26 | for (;i < k;++i) q.push(nums[i]); 27 | for (;i < nums.size();++i) { 28 | if (nums[i] > q.top()) { 29 | q.pop(); 30 | q.push(nums[i]); 31 | } 32 | } 33 | return q.top(); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /216-combination-sum-iii/combination-sum-iii.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. 3 | // 4 | // Note: 5 | // 6 | // 7 | // All numbers will be positive integers. 8 | // The solution set must not contain duplicate combinations. 9 | // 10 | // 11 | // Example 1: 12 | // 13 | // 14 | // Input: k = 3, n = 7 15 | // Output: [[1,2,4]] 16 | // 17 | // 18 | // Example 2: 19 | // 20 | // 21 | // Input: k = 3, n = 9 22 | // Output: [[1,2,6], [1,3,5], [2,3,4]] 23 | // 24 | // 25 | // 26 | 27 | 28 | class Solution { 29 | public: 30 | vector > res; 31 | vector current; 32 | int sum(vector c) { 33 | int s = 0; 34 | for (auto &n : c) s += n; 35 | return s; 36 | } 37 | void dfs(int i, int k, int n) { 38 | /* 39 | cout << i << endl; 40 | for (auto &nn : current) cout << nn << ","; 41 | cout << endl; 42 | */ 43 | if (i > 9 || current.size() == k) { 44 | if (current.size() !=k) return; 45 | if (sum(current) == n) res.push_back(current); 46 | return; 47 | } 48 | if (sum(current) >= n) return; 49 | for (int j = i;j <= 9;++j) { 50 | current.push_back(j); 51 | dfs(j+1, k, n); 52 | current.pop_back(); 53 | 54 | //dfs(j+1, k, n); 55 | } 56 | } 57 | vector> combinationSum3(int k, int n) { 58 | dfs(1, k, n); 59 | return res; 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /217-contains-duplicate/contains-duplicate.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of integers, find if the array contains any duplicates. 2 | // 3 | // Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: [1,2,3,1] 9 | // Output: true 10 | // 11 | // Example 2: 12 | // 13 | // 14 | // Input: [1,2,3,4] 15 | // Output: false 16 | // 17 | // Example 3: 18 | // 19 | // 20 | // Input: [1,1,1,3,3,4,3,2,4,2] 21 | // Output: true 22 | 23 | 24 | class Solution { 25 | public: 26 | bool containsDuplicate(vector& nums) { 27 | unordered_set s; 28 | for (auto &n : nums) { 29 | if (s.find(n) == s.end()) { 30 | s.insert(n); 31 | } else { 32 | return true; 33 | } 34 | } 35 | return false; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /217-contains-duplicate/contains-duplicate.js: -------------------------------------------------------------------------------- 1 | // Given an array of integers, find if the array contains any duplicates. 2 | // 3 | // Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 4 | // 5 | // Example 1: 6 | // 7 | // 8 | // Input: [1,2,3,1] 9 | // Output: true 10 | // 11 | // Example 2: 12 | // 13 | // 14 | // Input: [1,2,3,4] 15 | // Output: false 16 | // 17 | // Example 3: 18 | // 19 | // 20 | // Input: [1,1,1,3,3,4,3,2,4,2] 21 | // Output: true 22 | 23 | 24 | /** 25 | * @param {number[]} nums 26 | * @return {boolean} 27 | */ 28 | var containsDuplicate = function(nums) { 29 | var hash = {}; 30 | for (var i = 0;i < nums.length;++i) { 31 | if (hash[nums[i]] !== undefined) return true; 32 | hash[nums[i]] = i; 33 | } 34 | return false; 35 | }; 36 | -------------------------------------------------------------------------------- /219-contains-duplicate-ii/contains-duplicate-ii.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 2 | // 3 | // 4 | // Example 1: 5 | // 6 | // 7 | // Input: nums = [1,2,3,1], k = 3 8 | // Output: true 9 | // 10 | // 11 | // 12 | // Example 2: 13 | // 14 | // 15 | // Input: nums = [1,0,1,1], k = 1 16 | // Output: true 17 | // 18 | // 19 | // 20 | // Example 3: 21 | // 22 | // 23 | // Input: nums = [1,2,3,1,2,3], k = 2 24 | // Output: false 25 | // 26 | // 27 | // 28 | // 29 | 30 | 31 | class Solution { 32 | public: 33 | bool containsNearbyDuplicate(vector& nums, int k) { 34 | map m; 35 | for (int i = 0; i < nums.size(); ++i) { 36 | if (m.find(nums[i]) != m.end()) { 37 | if (i - m[nums[i]] <= k) return true; 38 | m[nums[i]] = i; 39 | } else { 40 | m[nums[i]] = i; 41 | } 42 | } 43 | return false; 44 | } 45 | }; 46 | 47 | -------------------------------------------------------------------------------- /219-contains-duplicate-ii/contains-duplicate-ii.js: -------------------------------------------------------------------------------- 1 | // Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 2 | // 3 | // 4 | // Example 1: 5 | // 6 | // 7 | // Input: nums = [1,2,3,1], k = 3 8 | // Output: true 9 | // 10 | // 11 | // 12 | // Example 2: 13 | // 14 | // 15 | // Input: nums = [1,0,1,1], k = 1 16 | // Output: true 17 | // 18 | // 19 | // 20 | // Example 3: 21 | // 22 | // 23 | // Input: nums = [1,2,3,1,2,3], k = 2 24 | // Output: false 25 | // 26 | // 27 | // 28 | // 29 | 30 | 31 | /** 32 | * @param {number[]} nums 33 | * @param {number} k 34 | * @return {boolean} 35 | */ 36 | var containsNearbyDuplicate = function(nums, k) { 37 | var hash = {}; 38 | for (var i = 0;i < nums.length;++i) { 39 | if (hash[nums[i]] !== undefined) { 40 | if (Math.abs(i - hash[nums[i]]) <= k) 41 | return true; 42 | } 43 | hash[nums[i]] = i; 44 | } 45 | return false; 46 | }; 47 | -------------------------------------------------------------------------------- /220-contains-duplicate-iii/contains-duplicate-iii.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k. 2 | // 3 | // 4 | // Example 1: 5 | // 6 | // 7 | // Input: nums = [1,2,3,1], k = 3, t = 0 8 | // Output: true 9 | // 10 | // 11 | // 12 | // Example 2: 13 | // 14 | // 15 | // Input: nums = [1,0,1,1], k = 1, t = 2 16 | // Output: true 17 | // 18 | // 19 | // 20 | // Example 3: 21 | // 22 | // 23 | // Input: nums = [1,5,9,1,5,9], k = 2, t = 3 24 | // Output: false 25 | // 26 | // 27 | // 28 | // 29 | 30 | 31 | class Solution { 32 | public: 33 | bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { 34 | if (t < 0) return false; 35 | unordered_map m; 36 | #define BIN(i, t) (i < 0 ? (i+1)/(t+1)-1 : i/(t+1)) 37 | for (int i = 0; i < nums.size(); ++i) { 38 | int b = BIN(nums[i], t); 39 | if (m.find(b) != m.end()) { 40 | return true; 41 | } 42 | if (m.find(b-1) != m.end() && abs(nums[i] - m[b-1]) <= t) { 43 | return true; 44 | } 45 | if (m.find(b+1) != m.end() && abs(nums[i] - m[b+1]) <= t) { 46 | return true; 47 | } 48 | m[b] = nums[i]; 49 | 50 | if (i >= k) { 51 | m.erase(BIN(nums[i-k], t)); 52 | } 53 | } 54 | return false; 55 | } 56 | }; 57 | 58 | -------------------------------------------------------------------------------- /221-maximal-square/maximal-square.cpp: -------------------------------------------------------------------------------- 1 | // Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 2 | // 3 | // Example: 4 | // 5 | // 6 | // Input: 7 | // 8 | // 1 0 1 0 0 9 | // 1 0 1 1 1 10 | // 1 1 1 1 1 11 | // 1 0 0 1 0 12 | // 13 | // Output: 4 14 | // 15 | // 16 | 17 | 18 | class Solution { 19 | public: 20 | int maximalSquare(vector>& matrix) { 21 | int m = matrix.size(); 22 | if (m == 0) return 0; 23 | int n = matrix[0].size(); 24 | 25 | vector > p(m, vector(n,0)); 26 | int res = 0; 27 | for (int i = 0; i < n; ++i) { 28 | p[0][i] = matrix[0][i] - '0'; 29 | res = max(res, p[0][i]); 30 | } 31 | for (int i = 1; i < m; ++i) { 32 | p[i][0] = matrix[i][0] - '0'; 33 | res = max(res, p[i][0]); 34 | } 35 | for (int i = 1; i < m; ++i) { 36 | for (int j = 1; j < n; ++j) { 37 | if (matrix[i][j] == '1') { 38 | p[i][j] = min(min(p[i-1][j], p[i-1][j-1]), p[i][j-1])+1; 39 | res = max(res, p[i][j]); 40 | } 41 | } 42 | } 43 | return res*res; 44 | } 45 | }; 46 | 47 | -------------------------------------------------------------------------------- /222-count-complete-tree-nodes/count-complete-tree-nodes.cpp: -------------------------------------------------------------------------------- 1 | // Given a complete binary tree, count the number of nodes. 2 | // 3 | // Note: 4 | // 5 | // Definition of a complete binary tree from Wikipedia: 6 | // In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. 7 | // 8 | // Example: 9 | // 10 | // 11 | // Input: 12 | // 1 13 | // / \ 14 | // 2 3 15 | // / \ / 16 | // 4 5 6 17 | // 18 | // Output: 6 19 | // 20 | 21 | 22 | /** 23 | * Definition for a binary tree node. 24 | * struct TreeNode { 25 | * int val; 26 | * TreeNode *left; 27 | * TreeNode *right; 28 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 29 | * }; 30 | */ 31 | class Solution { 32 | public: 33 | int countNodes(TreeNode* root) { 34 | if (root == nullptr) return 0; 35 | int rh = 0; 36 | TreeNode *p = root->right; 37 | while (p) {p=p->right; ++rh;} 38 | int lh = 0; 39 | p = root->left; 40 | while (p) {p=p->left; ++lh;} 41 | if (lh == rh) return pow(2, lh+1)-1; 42 | return 1 + countNodes(root->left) + countNodes(root->right); 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /223-rectangle-area/rectangle-area.cpp: -------------------------------------------------------------------------------- 1 | // Find the total area covered by two rectilinear rectangles in a 2D plane. 2 | // 3 | // Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. 4 | // 5 | // 6 | // 7 | // Example: 8 | // 9 | // 10 | // Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2 11 | // Output: 45 12 | // 13 | // Note: 14 | // 15 | // Assume that the total area is never beyond the maximum possible value of int. 16 | // 17 | 18 | 19 | class Solution { 20 | public: 21 | int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 22 | int left = max(A,E), right = max(min(C,G), left); 23 | int bottom = max(B,F), top = max(min(D,H), bottom); 24 | return (C-A)*(D-B) - (right-left)*(top-bottom) + (G-E)*(H-F); 25 | } 26 | }; 27 | 28 | -------------------------------------------------------------------------------- /371-sum-of-two-integers/sum-of-two-integers.cpp: -------------------------------------------------------------------------------- 1 | // Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 2 | // 3 | // 4 | // Example 1: 5 | // 6 | // 7 | // Input: a = 1, b = 2 8 | // Output: 3 9 | // 10 | // 11 | // 12 | // Example 2: 13 | // 14 | // 15 | // Input: a = -2, b = 3 16 | // Output: 1 17 | // 18 | // 19 | // 20 | // 21 | 22 | 23 | class Solution { 24 | public: 25 | int getSum(int a, int b) { 26 | if (a == 0) return b; 27 | if (b == 0) return a; 28 | int s = a ^ b; 29 | int c = (a&b) << 1; 30 | while (c) { 31 | int t = s ^ c; 32 | c = (s&c) << 1; 33 | s = t; 34 | } 35 | return s; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /374-guess-number-higher-or-lower/guess-number-higher-or-lower.cpp: -------------------------------------------------------------------------------- 1 | // We are playing the Guess Game. The game is as follows: 2 | // 3 | // I pick a number from 1 to n. You have to guess which number I picked. 4 | // 5 | // Every time you guess wrong, I'll tell you whether the number is higher or lower. 6 | // 7 | // You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): 8 | // 9 | // 10 | // -1 : My number is lower 11 | // 1 : My number is higher 12 | // 0 : Congrats! You got it! 13 | // 14 | // 15 | // Example : 16 | // 17 | // 18 | // 19 | // Input: n = 10, pick = 6 20 | // Output: 6 21 | // 22 | // 23 | // 24 | 25 | 26 | // Forward declaration of guess API. 27 | // @param num, your guess 28 | // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 29 | int guess(int num); 30 | 31 | class Solution { 32 | public: 33 | int guessNumber(int n) { 34 | if (n < 2) return n; 35 | 36 | long left = 1, right = n; 37 | int ans = 0; 38 | while (left <= right) { 39 | ans = (left+right)>>1; 40 | int g = guess(ans); 41 | if (g==0) return ans; 42 | if (g==1) left = ans+1; 43 | if (g==-1) right = ans-1; 44 | } 45 | return ans; 46 | } 47 | }; 48 | --------------------------------------------------------------------------------