├── 050.powx-n ├── question.md └── powx-n.cpp ├── 147.insertion-sort-list └── question.md ├── 148.sort-list └── question.md ├── 069.sqrtx ├── question.md └── sqrtx.cpp ├── 014.longest-common-prefix ├── question.md └── longest-common-prefix.cpp ├── 149.max-points-on-a-line └── question.md ├── 023.merge-k-sorted-lists └── question.md ├── 292.nim-game ├── nim-game.cpp └── question.md ├── 013.roman-to-integer ├── question.md └── roman-to-integer.cpp ├── 258.add-digits ├── add-digits.cpp └── question.md ├── 275.h-index-ii ├── question.md └── h-index-ii.cpp ├── 012.integer-to-roman ├── question.md └── integer-to-roman.cpp ├── 108.convert-sorted-array-to-binary-search-tree ├── question.md └── convert-sorted-array-to-binary-search-tree.cpp ├── 109.convert-sorted-list-to-binary-search-tree └── question.md ├── 231.power-of-two ├── power-of-two.cpp └── question.md ├── 234.palindrome-linked-list └── question.md ├── 029.divide-two-integers └── question.md ├── 052.n-queens-ii └── question.md ├── 021.merge-two-sorted-lists └── question.md ├── 048.rotate-image ├── question.md └── rotate-image.cpp ├── 141.linked-list-cycle ├── question.md └── linked-list-cycle.cpp ├── 028.implement-strstr └── question.md ├── 067.add-binary ├── question.md └── add-binary.cpp ├── 229.majority-element-ii ├── question.md └── majority-element-ii.cpp ├── 056.merge-intervals └── question.md ├── 061.rotate-list └── question.md ├── 104.maximum-depth-of-binary-tree ├── question.md └── maximum-depth-of-binary-tree.cpp ├── 111.minimum-depth-of-binary-tree ├── question.md └── minimum-depth-of-binary-tree.cpp ├── 204.count-primes ├── question.md └── count-primes.cpp ├── 208.implement-trie-prefix-tree └── question.md ├── 206.reverse-linked-list ├── question.md └── reverse-linked-list.cpp ├── 105.construct-binary-tree-from-preorder-and-inorder-traversal └── question.md ├── 100.same-tree ├── question.md └── same-tree.cpp ├── 106.construct-binary-tree-from-inorder-and-postorder-traversal └── question.md ├── 035.search-insert-position ├── search-insert-position.cpp └── question.md ├── 138.copy-list-with-random-pointer └── question.md ├── 136.single-number ├── single-number.cpp └── question.md ├── 219.contains-duplicate-ii ├── question.md └── contains-duplicate-ii.cpp ├── 083.remove-duplicates-from-sorted-list ├── question.md └── remove-duplicates-from-sorted-list.cpp ├── 217.contains-duplicate ├── question.md └── contains-duplicate.cpp ├── 064.minimum-path-sum ├── question.md └── minimum-path-sum.cpp ├── 268.missing-number ├── missing-number.cpp └── question.md ├── 070.climbing-stairs ├── question.md └── climbing-stairs.cpp ├── 172.factorial-trailing-zeroes ├── question.md └── factorial-trailing-zeroes.cpp ├── 020.valid-parentheses ├── question.md └── valid-parentheses.cpp ├── 119.pascals-triangle-ii ├── question.md └── pascals-triangle-ii.cpp ├── 110.balanced-binary-tree ├── question.md └── balanced-binary-tree.cpp ├── 220.contains-duplicate-iii ├── question.md └── contains-duplicate-iii.cpp ├── 118.pascals-triangle ├── question.md └── pascals-triangle.cpp ├── 152.maximum-product-subarray ├── question.md └── maximum-product-subarray.cpp ├── 093.restore-ip-addresses └── question.md ├── 142.linked-list-cycle-ii └── question.md ├── 233.number-of-digit-one ├── question.md └── number-of-digit-one.cpp ├── 263.ugly-number ├── ugly-number.cpp └── question.md ├── 143.reorder-list └── question.md ├── 099.recover-binary-search-tree └── question.md ├── 153.find-minimum-in-rotated-sorted-array ├── question.md └── find-minimum-in-rotated-sorted-array.cpp ├── 082.remove-duplicates-from-sorted-list-ii └── question.md ├── 137.single-number-ii ├── question.md └── single-number-ii.cpp ├── 041.first-missing-positive ├── question.md └── first-missing-positive.cpp ├── 066.plus-one ├── question.md └── plus-one.cpp ├── 228.summary-ranges ├── question.md └── summary-ranges.cpp ├── 047.permutations-ii ├── question.md └── permutations-ii.cpp ├── 049.anagrams ├── question.md └── anagrams.cpp ├── 059.spiral-matrix-ii ├── question.md └── spiral-matrix-ii.cpp ├── 085.maximal-rectangle └── question.md ├── 097.interleaving-string ├── question.md └── interleaving-string.cpp ├── 077.combinations ├── question.md └── combinations.cpp ├── 046.permutations ├── question.md └── permutations.cpp ├── 191.number-of-1-bits ├── number-of-1-bits.cpp └── question.md ├── 203.remove-linked-list-elements ├── question.md └── remove-linked-list-elements.cpp ├── 201.bitwise-and-of-numbers-range ├── question.md └── bitwise-and-of-numbers-range.cpp ├── 022.generate-parentheses ├── question.md └── generate-parentheses.cpp ├── 237.delete-node-in-a-linked-list ├── question.md └── delete-node-in-a-linked-list.cpp ├── 088.merge-sorted-array ├── question.md └── merge-sorted-array.cpp ├── 131.palindrome-partitioning └── question.md ├── README.md ├── 037.sudoku-solver └── question.md ├── 054.spiral-matrix ├── question.md └── spiral-matrix.cpp ├── 075.sort-colors ├── sort-colors.cpp └── question.md ├── 189.rotate-array ├── rotate-array.cpp └── question.md ├── 033.search-in-rotated-sorted-array ├── question.md └── search-in-rotated-sorted-array.cpp ├── 169.majority-element ├── question.md └── majority-element.cpp ├── 171.excel-sheet-column-number ├── excel-sheet-column-number.cpp └── question.md ├── 024.swap-nodes-in-pairs ├── question.md └── swap-nodes-in-pairs.cpp ├── 072.edit-distance ├── question.md └── edit-distance.cpp ├── 092.reverse-linked-list-ii ├── question.md └── reverse-linked-list-ii.cpp ├── 123.best-time-to-buy-and-sell-stock-iii ├── question.md └── best-time-to-buy-and-sell-stock-iii.cpp ├── 132.palindrome-partitioning-ii ├── question.md └── palindrome-partitioning-ii.cpp ├── 086.partition-list └── question.md ├── 094.binary-tree-inorder-traversal └── question.md ├── 128.longest-consecutive-sequence └── question.md ├── 144.binary-tree-preorder-traversal ├── question.md └── binary-tree-preorder-traversal.cpp ├── 222.count-complete-tree-nodes └── question.md ├── 145.binary-tree-postorder-traversal ├── question.md └── binary-tree-postorder-traversal.cpp ├── 273.integer-to-english-words └── question.md ├── 005.longest-palindromic-substring └── question.md ├── 168.excel-sheet-column-title ├── question.md └── excel-sheet-column-title.cpp ├── 032.longest-valid-parentheses ├── question.md └── longest-valid-parentheses.cpp ├── 062.unique-paths ├── unique-paths.cpp └── question.md ├── 078.subsets ├── question.md └── subsets.cpp ├── 090.subsets-ii ├── question.md └── subsets-ii.cpp ├── 121.best-time-to-buy-and-sell-stock ├── best-time-to-buy-and-sell-stock.cpp └── question.md ├── 179.largest-number ├── question.md └── largest-number.cpp ├── 279.perfect-squares ├── question.md └── perfect-squares.cpp ├── 016.3sum-closest └── question.md ├── 027.remove-element ├── remove-element.cpp └── question.md ├── 053.maximum-subarray ├── maximum-subarray.cpp └── question.md ├── 058.length-of-last-word ├── question.md └── length-of-last-word.cpp ├── 080.remove-duplicates-from-sorted-array-ii ├── question.md └── remove-duplicates-from-sorted-array-ii.cpp ├── 011.container-with-most-water ├── question.md └── container-with-most-water.cpp ├── 015.3sum └── question.md ├── 034.search-for-a-range ├── question.md └── search-for-a-range.cpp ├── 135.candy ├── question.md └── candy.cpp ├── 221.maximal-square └── question.md ├── 242.valid-anagram ├── valid-anagram.cpp └── question.md ├── 001.two-sum ├── question.md └── two-sum.cpp ├── 150.evaluate-reverse-polish-notation └── question.md ├── 002.add-two-numbers └── question.md ├── 036.valid-sudoku └── question.md ├── 122.best-time-to-buy-and-sell-stock-ii ├── question.md └── best-time-to-buy-and-sell-stock-ii.cpp ├── 043.multiply-strings └── question.md ├── 198.house-robber ├── house-robber.cpp └── question.md ├── 215.kth-largest-element-in-an-array ├── kth-largest-element-in-an-array.cpp └── question.md ├── 257.binary-tree-paths └── question.md ├── 019.remove-nth-node-from-end-of-list ├── question.md └── remove-nth-node-from-end-of-list.cpp ├── 055.jump-game ├── question.md └── jump-game.cpp ├── 223.rectangle-area ├── question.md └── rectangle-area.cpp ├── 060.permutation-sequence ├── question.md └── permutation-sequence.cpp ├── 173.binary-search-tree-iterator └── question.md ├── 226.invert-binary-tree ├── question.md └── invert-binary-tree.cpp ├── 300.longest-increasing-subsequence ├── longest-increasing-subsequence.cpp └── question.md ├── 003.longest-substring-without-repeating-characters ├── question.md └── longest-substring-without-repeating-characters.cpp ├── 096.unique-binary-search-trees ├── question.md └── unique-binary-search-trees.cpp ├── 164.maximum-gap └── question.md ├── 004.median-of-two-sorted-arrays └── question.md ├── 038.count-and-say ├── question.md └── count-and-say.cpp ├── 073.set-matrix-zeroes ├── question.md └── set-matrix-zeroes.cpp ├── 102.binary-tree-level-order-traversal └── question.md ├── 188.best-time-to-buy-and-sell-stock-iv ├── question.md └── best-time-to-buy-and-sell-stock-iv.cpp ├── 190.reverse-bits ├── reverse-bits.cpp └── question.md ├── 162.find-peak-element ├── find-peak-element.cpp └── question.md ├── 278.first-bad-version ├── first-bad-version.cpp └── question.md ├── 009.palindrome-number ├── palindrome-number.cpp └── question.md ├── 154.find-minimum-in-rotated-sorted-array-ii ├── question.md └── find-minimum-in-rotated-sorted-array-ii.cpp ├── 214.shortest-palindrome ├── question.md └── shortest-palindrome.cpp ├── 018.4sum └── question.md ├── 130.surrounded-regions └── question.md ├── 238.product-of-array-except-self ├── question.md └── product-of-array-except-self.cpp ├── 264.ugly-number-ii ├── question.md └── ugly-number-ii.cpp ├── 030.substring-with-concatenation-of-all-words └── question.md ├── 042.trapping-rain-water ├── question.md └── trapping-rain-water.cpp ├── 095.unique-binary-search-trees-ii └── question.md ├── 125.valid-palindrome ├── valid-palindrome.cpp └── question.md ├── 230.kth-smallest-element-in-a-bst ├── question.md └── kth-smallest-element-in-a-bst.cpp ├── 107.binary-tree-level-order-traversal-ii └── question.md ├── 113.path-sum-ii └── question.md ├── 124.binary-tree-maximum-path-sum ├── question.md └── binary-tree-maximum-path-sum.cpp ├── 174.dungeon-game └── dungeon-game.cpp ├── 081.search-in-rotated-sorted-array-ii └── question.md ├── 200.number-of-islands └── question.md ├── 240.search-a-2d-matrix-ii ├── search-a-2d-matrix-ii.cpp └── question.md ├── 017.letter-combinations-of-a-phone-number └── question.md ├── 089.gray-code ├── gray-code.cpp └── question.md ├── 091.decode-ways ├── question.md └── decode-ways.cpp ├── 187.repeated-dna-sequences ├── question.md └── repeated-dna-sequences.cpp ├── 224.basic-calculator └── question.md ├── 063.unique-paths-ii ├── question.md └── unique-paths-ii.cpp ├── 084.largest-rectangle-in-histogram ├── question.md └── largest-rectangle-in-histogram.cpp ├── 103.binary-tree-zigzag-level-order-traversal └── question.md ├── 115.distinct-subsequences ├── question.md └── distinct-subsequences.cpp ├── 199.binary-tree-right-side-view ├── question.md └── binary-tree-right-side-view.cpp ├── 202.happy-number ├── happy-number.cpp └── question.md ├── 134.gas-station ├── gas-station.cpp └── question.md ├── 112.path-sum ├── question.md └── path-sum.cpp ├── 101.symmetric-tree ├── question.md └── symmetric-tree.cpp ├── 129.sum-root-to-leaf-numbers ├── question.md └── sum-root-to-leaf-numbers.cpp ├── 216.combination-sum-iii ├── question.md └── combination-sum-iii.cpp ├── 026.remove-duplicates-from-sorted-array ├── question.md └── remove-duplicates-from-sorted-array.cpp ├── 282.expression-add-operators └── question.md ├── 074.search-a-2d-matrix ├── question.md └── search-a-2d-matrix.cpp ├── 120.triangle ├── question.md └── triangle.cpp ├── 076.minimum-window-substring └── question.md ├── 166.fraction-to-recurring-decimal └── question.md ├── 006.zigzag-conversion └── question.md ├── 071.simplify-path └── question.md ├── 057.insert-interval └── question.md ├── 239.sliding-window-maximum └── sliding-window-maximum.cpp ├── 274.h-index └── h-index.cpp ├── 283.move-zeroes ├── question.md └── move-zeroes.cpp ├── 031.next-permutation ├── question.md └── next-permutation.cpp ├── 065.valid-number └── question.md ├── 079.word-search └── question.md ├── 227.basic-calculator-ii └── question.md ├── 260.single-number-iii ├── single-number-iii.cpp └── question.md ├── 287.find-the-duplicate-number ├── find-the-duplicate-number.cpp └── question.md ├── 205.isomorphic-strings ├── question.md └── isomorphic-strings.cpp ├── 039.combination-sum └── question.md ├── 045.jump-game-ii ├── question.md └── jump-game-ii.cpp ├── 167.two-sum-ii-input-array-is-sorted ├── question.md └── two-sum-ii-input-array-is-sorted.cpp ├── 040.combination-sum-ii └── question.md ├── 241.different-ways-to-add-parentheses └── question.md ├── 010.regular-expression-matching └── question.md ├── 044.wildcard-matching └── question.md ├── 139.word-break ├── word-break.cpp └── question.md ├── 117.populating-next-right-pointers-in-each-node-ii └── question.md ├── 209.minimum-size-subarray-sum ├── question.md └── minimum-size-subarray-sum.cpp ├── 299.bulls-and-cows └── bulls-and-cows.cpp ├── 235.lowest-common-ancestor-of-a-binary-search-tree ├── lowest-common-ancestor-of-a-binary-search-tree.cpp └── question.md ├── 051.n-queens └── question.md ├── 098.validate-binary-search-tree ├── question.md └── validate-binary-search-tree.cpp ├── 114.flatten-binary-tree-to-linked-list └── question.md ├── 155.min-stack ├── question.md └── min-stack.cpp ├── 025.reverse-nodes-in-k-group └── question.md ├── 007.reverse-integer └── reverse-integer.cpp ├── 213.house-robber-ii ├── question.md └── house-robber-ii.cpp ├── 140.word-break-ii └── question.md ├── 165.compare-version-numbers └── question.md ├── 087.scramble-string └── scramble-string.cpp ├── 151.reverse-words-in-a-string └── question.md ├── 116.populating-next-right-pointers-in-each-node └── populating-next-right-pointers-in-each-node.cpp ├── 290.word-pattern └── question.md ├── 236.lowest-common-ancestor-of-a-binary-tree ├── lowest-common-ancestor-of-a-binary-tree.cpp └── question.md ├── 295.find-median-from-data-stream └── question.md ├── 160.intersection-of-two-linked-lists └── question.md └── 211.add-and-search-word-data-structure-design └── question.md /050.powx-n/question.md: -------------------------------------------------------------------------------- 1 | Implement pow(x, n). 2 | -------------------------------------------------------------------------------- /147.insertion-sort-list/question.md: -------------------------------------------------------------------------------- 1 | Sort a linked list using insertion sort. -------------------------------------------------------------------------------- /148.sort-list/question.md: -------------------------------------------------------------------------------- 1 | Sort a linked list in O(n log n) time using constant space complexity. -------------------------------------------------------------------------------- /069.sqrtx/question.md: -------------------------------------------------------------------------------- 1 | Implement int sqrt(int x). 2 | 3 | Compute and return the square root of x. -------------------------------------------------------------------------------- /014.longest-common-prefix/question.md: -------------------------------------------------------------------------------- 1 | Write a function to find the longest common prefix string amongst an array of strings. 2 | -------------------------------------------------------------------------------- /149.max-points-on-a-line/question.md: -------------------------------------------------------------------------------- 1 | Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. -------------------------------------------------------------------------------- /023.merge-k-sorted-lists/question.md: -------------------------------------------------------------------------------- 1 | 2 | Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 3 | -------------------------------------------------------------------------------- /292.nim-game/nim-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canWinNim(int n) { 4 | return n % 4 ? true : false; 5 | } 6 | }; -------------------------------------------------------------------------------- /013.roman-to-integer/question.md: -------------------------------------------------------------------------------- 1 | Given a roman numeral, convert it to an integer. 2 | 3 | Input is guaranteed to be within the range from 1 to 3999. -------------------------------------------------------------------------------- /258.add-digits/add-digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int addDigits(int num) { 4 | return 1 + (num - 1) % 9; 5 | } 6 | }; -------------------------------------------------------------------------------- /275.h-index-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm? 3 | -------------------------------------------------------------------------------- /012.integer-to-roman/question.md: -------------------------------------------------------------------------------- 1 | Given an integer, convert it to a roman numeral. 2 | 3 | 4 | Input is guaranteed to be within the range from 1 to 3999. -------------------------------------------------------------------------------- /108.convert-sorted-array-to-binary-search-tree/question.md: -------------------------------------------------------------------------------- 1 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. -------------------------------------------------------------------------------- /109.convert-sorted-list-to-binary-search-tree/question.md: -------------------------------------------------------------------------------- 1 | Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. -------------------------------------------------------------------------------- /231.power-of-two/power-of-two.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | return n <= 0 ? false : !(n & (n - 1)); 5 | } 6 | }; -------------------------------------------------------------------------------- /234.palindrome-linked-list/question.md: -------------------------------------------------------------------------------- 1 | Given a singly linked list, determine if it is a palindrome. 2 | 3 | Follow up: 4 | Could you do it in O(n) time and O(1) space? -------------------------------------------------------------------------------- /029.divide-two-integers/question.md: -------------------------------------------------------------------------------- 1 | 2 | Divide two integers without using multiplication, division and mod operator. 3 | 4 | 5 | If it is overflow, return MAX_INT. 6 | -------------------------------------------------------------------------------- /052.n-queens-ii/question.md: -------------------------------------------------------------------------------- 1 | Follow up for N-Queens problem. 2 | 3 | Now, instead outputting board configurations, return the total number of distinct solutions. 4 | 5 | -------------------------------------------------------------------------------- /021.merge-two-sorted-lists/question.md: -------------------------------------------------------------------------------- 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. -------------------------------------------------------------------------------- /048.rotate-image/question.md: -------------------------------------------------------------------------------- 1 | You are given an n x n 2D matrix representing an image. 2 | Rotate the image by 90 degrees (clockwise). 3 | Follow up: 4 | Could you do this in-place? -------------------------------------------------------------------------------- /141.linked-list-cycle/question.md: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /028.implement-strstr/question.md: -------------------------------------------------------------------------------- 1 | 2 | Implement strStr(). 3 | 4 | 5 | Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 6 | -------------------------------------------------------------------------------- /067.add-binary/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given two binary strings, return their sum (also a binary string). 3 | 4 | 5 | 6 | For example, 7 | a = "11" 8 | b = "1" 9 | Return "100". 10 | -------------------------------------------------------------------------------- /229.majority-element-ii/question.md: -------------------------------------------------------------------------------- 1 | Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space. -------------------------------------------------------------------------------- /056.merge-intervals/question.md: -------------------------------------------------------------------------------- 1 | Given a collection of intervals, merge all overlapping intervals. 2 | 3 | 4 | For example, 5 | Given [1,3],[2,6],[8,10],[15,18], 6 | return [1,6],[8,10],[15,18]. 7 | -------------------------------------------------------------------------------- /061.rotate-list/question.md: -------------------------------------------------------------------------------- 1 | Given a list, rotate the list to the right by k places, where k is non-negative. 2 | 3 | For example: 4 | Given 1->2->3->4->5->NULL and k = 2, 5 | return 4->5->1->2->3->NULL. -------------------------------------------------------------------------------- /104.maximum-depth-of-binary-tree/question.md: -------------------------------------------------------------------------------- 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. -------------------------------------------------------------------------------- /111.minimum-depth-of-binary-tree/question.md: -------------------------------------------------------------------------------- 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. -------------------------------------------------------------------------------- /204.count-primes/question.md: -------------------------------------------------------------------------------- 1 | Description: 2 | Count the number of prime numbers less than a non-negative number, n. 3 | 4 | Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /208.implement-trie-prefix-tree/question.md: -------------------------------------------------------------------------------- 1 | 2 | Implement a trie with insert, search, and startsWith methods. 3 | 4 | 5 | 6 | Note: 7 | You may assume that all inputs are consist of lowercase letters a-z. 8 | -------------------------------------------------------------------------------- /206.reverse-linked-list/question.md: -------------------------------------------------------------------------------- 1 | Reverse a singly linked list. 2 | 3 | click to show more hints. 4 | 5 | Hint: 6 | A linked list can be reversed either iteratively or recursively. Could you implement both? 7 | -------------------------------------------------------------------------------- /231.power-of-two/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an integer, write a function to determine if it is a power of two. 3 | 4 | 5 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /105.construct-binary-tree-from-preorder-and-inorder-traversal/question.md: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /100.same-tree/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given two binary trees, write a function to check if they are equal or not. 3 | 4 | 5 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 6 | -------------------------------------------------------------------------------- /106.construct-binary-tree-from-inorder-and-postorder-traversal/question.md: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /035.search-insert-position/search-insert-position.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | return lower_bound(nums.begin(),nums.end(),target)-nums.begin();; 5 | } 6 | }; -------------------------------------------------------------------------------- /138.copy-list-with-random-pointer/question.md: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /136.single-number/single-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int res = 0; 5 | for(int i = 0; i < nums.size(); i++) res ^= nums[i]; 6 | return res; 7 | } 8 | }; -------------------------------------------------------------------------------- /219.contains-duplicate-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | 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. 3 | -------------------------------------------------------------------------------- /083.remove-duplicates-from-sorted-list/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a sorted linked list, delete all duplicates such that each element appear only once. 3 | 4 | 5 | For example, 6 | Given 1->1->2, return 1->2. 7 | Given 1->1->2->3->3, return 1->2->3. 8 | -------------------------------------------------------------------------------- /217.contains-duplicate/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an array of integers, find if the array contains any duplicates. 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. 3 | -------------------------------------------------------------------------------- /064.minimum-path-sum/question.md: -------------------------------------------------------------------------------- 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. -------------------------------------------------------------------------------- /136.single-number/question.md: -------------------------------------------------------------------------------- 1 | Given an array of integers, every element appears twice except for one. Find that single one. 2 | 3 | 4 | Note: 5 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | -------------------------------------------------------------------------------- /268.missing-number/missing-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | int sum = (nums.size() + 1) * nums.size() / 2; 5 | for(auto a : nums) sum -= a; 6 | return sum; 7 | } 8 | }; -------------------------------------------------------------------------------- /070.climbing-stairs/question.md: -------------------------------------------------------------------------------- 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 | 6 | Note: Given n will be a positive integer. 7 | -------------------------------------------------------------------------------- /172.factorial-trailing-zeroes/question.md: -------------------------------------------------------------------------------- 1 | Given an integer n, return the number of trailing zeroes in n!. 2 | 3 | Note: Your solution should be in logarithmic time complexity. 4 | 5 | Credits:Special thanks to @ts for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /020.valid-parentheses/question.md: -------------------------------------------------------------------------------- 1 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 2 | 3 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 4 | -------------------------------------------------------------------------------- /119.pascals-triangle-ii/question.md: -------------------------------------------------------------------------------- 1 | Given an index k, return the kth row of the Pascal's triangle. 2 | 3 | 4 | For example, given k = 3, 5 | Return [1,3,3,1]. 6 | 7 | 8 | 9 | Note: 10 | Could you optimize your algorithm to use only O(k) extra space? 11 | -------------------------------------------------------------------------------- /110.balanced-binary-tree/question.md: -------------------------------------------------------------------------------- 1 | Given a binary tree, determine if it is height-balanced. 2 | 3 | 4 | 5 | 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. 6 | -------------------------------------------------------------------------------- /220.contains-duplicate-iii/question.md: -------------------------------------------------------------------------------- 1 | 2 | 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. 3 | -------------------------------------------------------------------------------- /118.pascals-triangle/question.md: -------------------------------------------------------------------------------- 1 | Given numRows, generate the first numRows of Pascal's triangle. 2 | 3 | 4 | For example, given numRows = 5, 5 | Return 6 | 7 | [ 8 | [1], 9 | [1,1], 10 | [1,2,1], 11 | [1,3,3,1], 12 | [1,4,6,4,1] 13 | ] 14 | 15 | -------------------------------------------------------------------------------- /152.maximum-product-subarray/question.md: -------------------------------------------------------------------------------- 1 | 2 | Find the contiguous subarray within an array (containing at least one number) which has the largest product. 3 | 4 | 5 | 6 | For example, given the array [2,3,-2,4], 7 | the contiguous subarray [2,3] has the largest product = 6. 8 | -------------------------------------------------------------------------------- /093.restore-ip-addresses/question.md: -------------------------------------------------------------------------------- 1 | Given a string containing only digits, restore it by returning all possible valid IP address combinations. 2 | 3 | 4 | For example: 5 | Given "25525511135", 6 | 7 | 8 | return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 9 | -------------------------------------------------------------------------------- /142.linked-list-cycle-ii/question.md: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /233.number-of-digit-one/question.md: -------------------------------------------------------------------------------- 1 | Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. 2 | 3 | 4 | For example: 5 | Given n = 13, 6 | Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. 7 | -------------------------------------------------------------------------------- /263.ugly-number/ugly-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isUgly(int num) { 4 | if (num <= 0) return false; 5 | int divisors[3] = {2, 3, 5}; 6 | for(int d : divisors) while (num % d == 0) num /= d; 7 | return num == 1; 8 | } 9 | }; -------------------------------------------------------------------------------- /143.reorder-list/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a singly linked list L: L0→L1→…→Ln-1→Ln, 3 | reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… 4 | 5 | 6 | You must do this in-place without altering the nodes' values. 7 | 8 | 9 | For example, 10 | Given {1,2,3,4}, reorder it to {1,4,2,3}. 11 | -------------------------------------------------------------------------------- /099.recover-binary-search-tree/question.md: -------------------------------------------------------------------------------- 1 | 2 | Two elements of a binary search tree (BST) are swapped by mistake. 3 | 4 | Recover the tree without changing its structure. 5 | 6 | 7 | Note: 8 | A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 9 | -------------------------------------------------------------------------------- /153.find-minimum-in-rotated-sorted-array/question.md: -------------------------------------------------------------------------------- 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. -------------------------------------------------------------------------------- /082.remove-duplicates-from-sorted-list-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 3 | 4 | 5 | For example, 6 | Given 1->2->3->3->4->4->5, return 1->2->5. 7 | Given 1->1->1->2->3, return 2->3. 8 | -------------------------------------------------------------------------------- /137.single-number-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one. 3 | 4 | 5 | 6 | Note: 7 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 8 | -------------------------------------------------------------------------------- /172.factorial-trailing-zeroes/factorial-trailing-zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trailingZeroes(int n) { 4 | int res = 0; 5 | while(n) 6 | { 7 | res += n/5; 8 | n/=5; 9 | } 10 | return res; 11 | } 12 | }; -------------------------------------------------------------------------------- /041.first-missing-positive/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an unsorted integer array, find the first missing positive integer. 3 | 4 | 5 | 6 | For example, 7 | Given [1,2,0] return 3, 8 | and [3,4,-1,1] return 2. 9 | 10 | 11 | 12 | Your algorithm should run in O(n) time and uses constant space. 13 | -------------------------------------------------------------------------------- /066.plus-one/question.md: -------------------------------------------------------------------------------- 1 | Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. 2 | 3 | You may assume the integer do not contain any leading zero, except the number 0 itself. 4 | 5 | The digits are stored such that the most significant digit is at the head of the list. -------------------------------------------------------------------------------- /228.summary-ranges/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a sorted integer array without duplicates, return the summary of its ranges. 3 | 4 | 5 | For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. 6 | 7 | 8 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /047.permutations-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 3 | 4 | 5 | 6 | For example, 7 | [1,1,2] have the following unique permutations: 8 | 9 | [ 10 | [1,1,2], 11 | [1,2,1], 12 | [2,1,1] 13 | ] 14 | 15 | -------------------------------------------------------------------------------- /049.anagrams/question.md: -------------------------------------------------------------------------------- 1 | Given an array of strings, group anagrams together. 2 | 3 | 4 | For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], 5 | Return: 6 | 7 | [ 8 | ["ate", "eat","tea"], 9 | ["nat","tan"], 10 | ["bat"] 11 | ] 12 | 13 | Note: All inputs will be in lower-case. -------------------------------------------------------------------------------- /059.spiral-matrix-ii/question.md: -------------------------------------------------------------------------------- 1 | Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 2 | 3 | 4 | For example, 5 | Given n = 3, 6 | 7 | You should return the following matrix: 8 | 9 | [ 10 | [ 1, 2, 3 ], 11 | [ 8, 9, 4 ], 12 | [ 7, 6, 5 ] 13 | ] 14 | -------------------------------------------------------------------------------- /085.maximal-rectangle/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. 3 | 4 | 5 | For example, given the following matrix: 6 | 7 | 1 0 1 0 0 8 | 1 0 1 1 1 9 | 1 1 1 1 1 10 | 1 0 0 1 0 11 | 12 | Return 6. 13 | -------------------------------------------------------------------------------- /097.interleaving-string/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. 3 | 4 | 5 | 6 | For example, 7 | Given: 8 | s1 = "aabcc", 9 | s2 = "dbbca", 10 | 11 | 12 | When s3 = "aadbbcbcac", return true. 13 | When s3 = "aadbbbaccc", return false. 14 | -------------------------------------------------------------------------------- /077.combinations/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 3 | 4 | 5 | For example, 6 | If n = 4 and k = 2, a solution is: 7 | 8 | 9 | 10 | [ 11 | [2,4], 12 | [3,4], 13 | [2,3], 14 | [1,2], 15 | [1,3], 16 | [1,4], 17 | ] 18 | -------------------------------------------------------------------------------- /046.permutations/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a collection of distinct numbers, return all possible permutations. 3 | 4 | 5 | 6 | For example, 7 | [1,2,3] have the following permutations: 8 | 9 | [ 10 | [1,2,3], 11 | [1,3,2], 12 | [2,1,3], 13 | [2,3,1], 14 | [3,1,2], 15 | [3,2,1] 16 | ] 17 | 18 | -------------------------------------------------------------------------------- /191.number-of-1-bits/number-of-1-bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingWeight(uint32_t n) { 4 | int res = 0; 5 | while(n) 6 | { 7 | res += n&1; 8 | //cout<>1; 10 | } 11 | return res; 12 | } 13 | }; -------------------------------------------------------------------------------- /203.remove-linked-list-elements/question.md: -------------------------------------------------------------------------------- 1 | Remove all elements from a linked list of integers that have value val. 2 | 3 | Example 4 | Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 5 | Return: 1 --> 2 --> 3 --> 4 --> 5 6 | 7 | 8 | Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /201.bitwise-and-of-numbers-range/question.md: -------------------------------------------------------------------------------- 1 | Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 2 | 3 | 4 | For example, given the range [5, 7], you should return 4. 5 | 6 | 7 | Credits:Special thanks to @amrsaqr for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /022.generate-parentheses/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | 4 | 5 | 6 | For example, given n = 3, a solution set is: 7 | 8 | 9 | [ 10 | "((()))", 11 | "(()())", 12 | "(())()", 13 | "()(())", 14 | "()()()" 15 | ] 16 | -------------------------------------------------------------------------------- /237.delete-node-in-a-linked-list/question.md: -------------------------------------------------------------------------------- 1 | 2 | Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 3 | 4 | 5 | 6 | Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 7 | -------------------------------------------------------------------------------- /088.merge-sorted-array/question.md: -------------------------------------------------------------------------------- 1 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 2 | 3 | 4 | Note: 5 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. -------------------------------------------------------------------------------- /131.palindrome-partitioning/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | 4 | 5 | Return all possible palindrome partitioning of s. 6 | 7 | 8 | For example, given s = "aab", 9 | 10 | Return 11 | 12 | [ 13 | ["aa","b"], 14 | ["a","a","b"] 15 | ] 16 | 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Leetcode 2 | Leetcode题解(C++版),代码 + 详细博客说明 ! 3 | 4 | 所有内容见博客专栏:小题大做——Leetcode算法 5 | 6 | [http://blog.csdn.net/column/details/12689.html](http://blog.csdn.net/column/details/12689.html) 7 | 8 | 欢迎提出任何问题和建议! 9 | 10 | 本人博客:[http://blog.csdn.net/accepthjp](http://blog.csdn.net/accepthjp) 11 | 12 | 邮 箱  :huangjipengnju@gmail.com 13 | -------------------------------------------------------------------------------- /037.sudoku-solver/question.md: -------------------------------------------------------------------------------- 1 | Write a program to solve a Sudoku puzzle by filling the empty cells. 2 | 3 | Empty cells are indicated by the character '.'. 4 | 5 | You may assume that there will be only one unique solution. 6 | 7 | 8 | 9 | A sudoku puzzle... 10 | 11 | 12 | 13 | 14 | ...and its solution numbers marked in red. 15 | -------------------------------------------------------------------------------- /054.spiral-matrix/question.md: -------------------------------------------------------------------------------- 1 | Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 2 | 3 | 4 | 5 | For example, 6 | Given the following matrix: 7 | 8 | 9 | [ 10 | [ 1, 2, 3 ], 11 | [ 4, 5, 6 ], 12 | [ 7, 8, 9 ] 13 | ] 14 | 15 | 16 | You should return [1,2,3,6,9,8,7,4,5]. 17 | -------------------------------------------------------------------------------- /075.sort-colors/sort-colors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(vector& nums) { 4 | int a[3]={0}; 5 | for(int i=0;i& nums, int k) { 4 | k = k % nums.size(); 5 | reverse(nums.begin(), nums.begin()+nums.size()-k); 6 | reverse(nums.begin()+nums.size()-k, nums.begin()+nums.size()); 7 | reverse(nums.begin(), nums.begin()+nums.size()); 8 | } 9 | }; -------------------------------------------------------------------------------- /033.search-in-rotated-sorted-array/question.md: -------------------------------------------------------------------------------- 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. -------------------------------------------------------------------------------- /070.climbing-stairs/climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int climbStairs(int n) { 4 | vector dp(n+1,0); 5 | dp[0]=1; 6 | for(int i=0;i<=n;i++) 7 | { 8 | if(i+1<=n) dp[i+1]+=dp[i]; 9 | if(i+2<=n) dp[i+2]+=dp[i]; 10 | } 11 | return dp[n]; 12 | } 13 | }; -------------------------------------------------------------------------------- /169.majority-element/question.md: -------------------------------------------------------------------------------- 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 | Credits:Special thanks to @ts for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /171.excel-sheet-column-number/excel-sheet-column-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int titleToNumber(string s) { 4 | int res = 0 , base = 1; 5 | for(int i = s.size()-1; i >= 0; i--) 6 | { 7 | res += base*(s[i]+1-'A'); 8 | base*=26; 9 | } 10 | return res; 11 | } 12 | }; -------------------------------------------------------------------------------- /024.swap-nodes-in-pairs/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a linked list, swap every two adjacent nodes and return its head. 3 | 4 | 5 | 6 | For example, 7 | Given 1->2->3->4, you should return the list as 2->1->4->3. 8 | 9 | 10 | 11 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 12 | -------------------------------------------------------------------------------- /072.edit-distance/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) 3 | 4 | 5 | 6 | You have the following 3 operations permitted on a word: 7 | 8 | 9 | 10 | a) Insert a character 11 | b) Delete a character 12 | c) Replace a character 13 | -------------------------------------------------------------------------------- /092.reverse-linked-list-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 3 | 4 | 5 | 6 | For example: 7 | Given 1->2->3->4->5->NULL, m = 2 and n = 4, 8 | 9 | 10 | return 1->4->3->2->5->NULL. 11 | 12 | 13 | Note: 14 | Given m, n satisfy the following condition: 15 | 1 ≤ m ≤ n ≤ length of list. 16 | -------------------------------------------------------------------------------- /123.best-time-to-buy-and-sell-stock-iii/question.md: -------------------------------------------------------------------------------- 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: 6 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). -------------------------------------------------------------------------------- /132.palindrome-partitioning-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | 4 | 5 | Return the minimum cuts needed for a palindrome partitioning of s. 6 | 7 | 8 | For example, given s = "aab", 9 | Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. 10 | -------------------------------------------------------------------------------- /086.partition-list/question.md: -------------------------------------------------------------------------------- 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 | 4 | You should preserve the original relative order of the nodes in each of the two partitions. 5 | 6 | 7 | For example, 8 | Given 1->4->3->2->5->2 and x = 3, 9 | return 1->2->2->4->3->5. 10 | -------------------------------------------------------------------------------- /094.binary-tree-inorder-traversal/question.md: -------------------------------------------------------------------------------- 1 | Given a binary tree, return the inorder traversal of its nodes' values. 2 | 3 | 4 | For example: 5 | Given binary tree [1,null,2,3], 6 | 7 | 1 8 | \ 9 | 2 10 | / 11 | 3 12 | 13 | 14 | 15 | return [1,3,2]. 16 | 17 | 18 | Note: Recursive solution is trivial, could you do it iteratively? -------------------------------------------------------------------------------- /128.longest-consecutive-sequence/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 3 | 4 | 5 | For example, 6 | Given [100, 4, 200, 1, 3, 2], 7 | The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. 8 | 9 | 10 | Your algorithm should run in O(n) complexity. 11 | -------------------------------------------------------------------------------- /144.binary-tree-preorder-traversal/question.md: -------------------------------------------------------------------------------- 1 | Given a binary tree, return the preorder traversal of its nodes' values. 2 | 3 | 4 | For example: 5 | Given binary tree {1,#,2,3}, 6 | 7 | 1 8 | \ 9 | 2 10 | / 11 | 3 12 | 13 | 14 | 15 | return [1,2,3]. 16 | 17 | 18 | Note: Recursive solution is trivial, could you do it iteratively? -------------------------------------------------------------------------------- /169.majority-element/majority-element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | unordered_map counts; 5 | int n = nums.size(); 6 | for (int i = 0; i < n; i++) 7 | if (++counts[nums[i]] > n / 2) 8 | return nums[i]; 9 | return 0; 10 | } 11 | }; -------------------------------------------------------------------------------- /222.count-complete-tree-nodes/question.md: -------------------------------------------------------------------------------- 1 | Given a complete binary tree, count the number of nodes. 2 | 3 | Definition of a complete binary tree from Wikipedia: 4 | 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. -------------------------------------------------------------------------------- /145.binary-tree-postorder-traversal/question.md: -------------------------------------------------------------------------------- 1 | Given a binary tree, return the postorder traversal of its nodes' values. 2 | 3 | 4 | For example: 5 | Given binary tree {1,#,2,3}, 6 | 7 | 1 8 | \ 9 | 2 10 | / 11 | 3 12 | 13 | 14 | 15 | return [3,2,1]. 16 | 17 | 18 | Note: Recursive solution is trivial, could you do it iteratively? -------------------------------------------------------------------------------- /217.contains-duplicate/contains-duplicate.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool containsDuplicate(vector& nums) { 4 | unordered_map mp; 5 | for(int i = 0; i < nums.size(); i++) 6 | { 7 | mp[nums[i]]++; 8 | if(mp[nums[i]] > 1) return true; 9 | } 10 | return false; 11 | } 12 | }; -------------------------------------------------------------------------------- /273.integer-to-english-words/question.md: -------------------------------------------------------------------------------- 1 | 2 | Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1. 3 | 4 | 5 | For example, 6 | 7 | 123 -> "One Hundred Twenty Three" 8 | 12345 -> "Twelve Thousand Three Hundred Forty Five" 9 | 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" -------------------------------------------------------------------------------- /005.longest-palindromic-substring/question.md: -------------------------------------------------------------------------------- 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: 4 | 5 | Input: "babad" 6 | 7 | Output: "bab" 8 | 9 | Note: "aba" is also a valid answer. 10 | 11 | 12 | 13 | Example: 14 | 15 | Input: "cbbd" 16 | 17 | Output: "bb" 18 | 19 | -------------------------------------------------------------------------------- /168.excel-sheet-column-title/question.md: -------------------------------------------------------------------------------- 1 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 2 | 3 | For example: 4 | 5 | 1 -> A 6 | 2 -> B 7 | 3 -> C 8 | ... 9 | 26 -> Z 10 | 27 -> AA 11 | 28 -> AB 12 | 13 | Credits:Special thanks to @ifanchu for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /191.number-of-1-bits/question.md: -------------------------------------------------------------------------------- 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 | For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 4 | 5 | Credits:Special thanks to @ts for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /201.bitwise-and-of-numbers-range/bitwise-and-of-numbers-range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rangeBitwiseAnd(int m, int n) { 4 | if(m == 0) return 0; 5 | int res = 1; 6 | while(m != n) 7 | { 8 | m >>= 1; 9 | n >>= 1; 10 | res <<= 1; 11 | } 12 | return m * res; 13 | } 14 | }; -------------------------------------------------------------------------------- /032.longest-valid-parentheses/question.md: -------------------------------------------------------------------------------- 1 | Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. 2 | 3 | 4 | For "(()", the longest valid parentheses substring is "()", which has length = 2. 5 | 6 | 7 | Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. 8 | -------------------------------------------------------------------------------- /062.unique-paths/unique-paths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | vector row(n+1,0); 5 | vector> dp(m+1,row); 6 | dp[0][1]=1; 7 | for(int i=1;i<=m;i++) 8 | for(int j=1;j<=n;j++) 9 | dp[i][j]=dp[i-1][j]+dp[i][j-1]; 10 | return dp[m][n]; 11 | } 12 | }; -------------------------------------------------------------------------------- /078.subsets/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a set of distinct integers, nums, return all possible subsets. 3 | 4 | Note: The solution set must not contain duplicate subsets. 5 | 6 | 7 | For example, 8 | If nums = [1,2,3], a solution is: 9 | 10 | 11 | 12 | [ 13 | [3], 14 | [1], 15 | [2], 16 | [1,2,3], 17 | [1,3], 18 | [2,3], 19 | [1,2], 20 | [] 21 | ] 22 | -------------------------------------------------------------------------------- /090.subsets-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a collection of integers that might contain duplicates, nums, return all possible subsets. 3 | 4 | Note: The solution set must not contain duplicate subsets. 5 | 6 | 7 | For example, 8 | If nums = [1,2,2], a solution is: 9 | 10 | 11 | 12 | [ 13 | [2], 14 | [1], 15 | [1,2,2], 16 | [2,2], 17 | [1,2], 18 | [] 19 | ] 20 | -------------------------------------------------------------------------------- /121.best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int res=0; 5 | for(int i=1;i& nums, int val) { 4 | for(int i=0;i& nums) { 4 | int result=nums[0]; 5 | for(int i=1;i0) 8 | nums[i]=nums[i-1]+nums[i]; 9 | result=max(result,nums[i]); 10 | } 11 | return result; 12 | } 13 | }; -------------------------------------------------------------------------------- /058.length-of-last-word/question.md: -------------------------------------------------------------------------------- 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 | 8 | For example, 9 | Given s = "Hello World", 10 | return 5. 11 | -------------------------------------------------------------------------------- /080.remove-duplicates-from-sorted-array-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Follow up for "Remove Duplicates": 3 | What if duplicates are allowed at most twice? 4 | 5 | 6 | For example, 7 | Given sorted array nums = [1,1,1,2,2,3], 8 | 9 | 10 | Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. 11 | -------------------------------------------------------------------------------- /011.container-with-most-water/question.md: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /015.3sum/question.md: -------------------------------------------------------------------------------- 1 | Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 2 | 3 | Note: The solution set must not contain duplicate triplets. 4 | 5 | 6 | For example, given array S = [-1, 0, 1, 2, -1, -4], 7 | 8 | A solution set is: 9 | [ 10 | [-1, 0, 1], 11 | [-1, -1, 2] 12 | ] 13 | -------------------------------------------------------------------------------- /034.search-for-a-range/question.md: -------------------------------------------------------------------------------- 1 | Given an array of integers 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 | 8 | For example, 9 | Given [5, 7, 7, 8, 8, 10] and target value 8, 10 | return [3, 4]. 11 | -------------------------------------------------------------------------------- /035.search-insert-position/question.md: -------------------------------------------------------------------------------- 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 | 6 | Here are few examples. 7 | [1,3,5,6], 5 → 2 8 | [1,3,5,6], 2 → 1 9 | [1,3,5,6], 7 → 4 10 | [1,3,5,6], 0 → 0 11 | -------------------------------------------------------------------------------- /135.candy/question.md: -------------------------------------------------------------------------------- 1 | 2 | There are N children standing in a line. Each child is assigned a rating value. 3 | 4 | 5 | You are giving candies to these children subjected to the following requirements: 6 | 7 | 8 | Each child must have at least one candy. 9 | Children with a higher rating get more candies than their neighbors. 10 | 11 | 12 | What is the minimum candies you must give? 13 | -------------------------------------------------------------------------------- /221.maximal-square/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 3 | 4 | 5 | For example, given the following matrix: 6 | 7 | 1 0 1 0 0 8 | 1 0 1 1 1 9 | 1 1 1 1 1 10 | 1 0 0 1 0 11 | 12 | Return 4. 13 | 14 | 15 | Credits:Special thanks to @Freezen for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /242.valid-anagram/valid-anagram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isAnagram(string s, string t) { 4 | int cnt[26] = {0}; 5 | for(auto c : s) cnt[c - 'a']++; 6 | for(auto c : t) cnt[c - 'a']--; 7 | for(auto c : cnt) if(c) return false; 8 | 9 | 10 | 11 | return s.size() != t.size() ? false : true; 12 | } 13 | }; -------------------------------------------------------------------------------- /001.two-sum/question.md: -------------------------------------------------------------------------------- 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 | 6 | Example: 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 | -------------------------------------------------------------------------------- /066.plus-one/plus-one.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector plusOne(vector& digits) { 4 | int add=1; 5 | for(int i=digits.size()-1;i>=0;i--) 6 | { 7 | digits[i]=(digits[i]+add)%10; 8 | if(digits[i]!=0) break; 9 | } 10 | if(digits[0]==0) digits.insert(digits.begin(),1); 11 | return digits; 12 | } 13 | }; -------------------------------------------------------------------------------- /150.evaluate-reverse-polish-notation/question.md: -------------------------------------------------------------------------------- 1 | 2 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. 3 | 4 | 5 | 6 | Valid operators are +, -, *, /. Each operand may be an integer or another expression. 7 | 8 | 9 | 10 | Some examples: 11 | 12 | ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 13 | ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 14 | 15 | -------------------------------------------------------------------------------- /047.permutations-ii/permutations-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> permuteUnique(vector& nums) { 4 | vector> result; 5 | sort(nums.begin(),nums.end()); 6 | do 7 | { 8 | result.push_back(nums); 9 | }while(next_permutation(nums.begin(),nums.end())); 10 | return result; 11 | } 12 | }; -------------------------------------------------------------------------------- /002.add-two-numbers/question.md: -------------------------------------------------------------------------------- 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 | 6 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 7 | Output: 7 -> 0 -> 8 -------------------------------------------------------------------------------- /036.valid-sudoku/question.md: -------------------------------------------------------------------------------- 1 | Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. 2 | 3 | The Sudoku board could be partially filled, where empty cells are filled with the character '.'. 4 | 5 | 6 | 7 | A partially filled sudoku which is valid. 8 | 9 | 10 | Note: 11 | A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. 12 | -------------------------------------------------------------------------------- /122.best-time-to-buy-and-sell-stock-ii/question.md: -------------------------------------------------------------------------------- 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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). -------------------------------------------------------------------------------- /168.excel-sheet-column-title/excel-sheet-column-title.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string convertToTitle(int n) { 4 | string res; 5 | while(n) 6 | { 7 | int c = (n % 26) - 1; 8 | if(c == -1) c = 25; 9 | res = char('A' + c) + res; 10 | n--; 11 | n /= 26; 12 | } 13 | return res; 14 | } 15 | }; -------------------------------------------------------------------------------- /043.multiply-strings/question.md: -------------------------------------------------------------------------------- 1 | Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. 2 | 3 | Note: 4 | 5 | The length of both num1 and num2 is < 110. 6 | Both num1 and num2 contains only digits 0-9. 7 | Both num1 and num2 does not contain any leading zero. 8 | You must not use any built-in BigInteger library or convert the inputs to integer directly. 9 | 10 | -------------------------------------------------------------------------------- /198.house-robber/house-robber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | int a = 0; 5 | int b = 0; 6 | for(int i = 0; i < nums.size(); i++) 7 | { 8 | if(i&1) 9 | a = max(a + nums[i], b); 10 | else 11 | b = max(a, b + nums[i]); 12 | } 13 | return max(a, b); 14 | } 15 | }; -------------------------------------------------------------------------------- /215.kth-largest-element-in-an-array/kth-largest-element-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findKthLargest(vector& nums, int k) { 4 | priority_queue, greater > q; 5 | for(int i = 0; i < nums.size(); i++) 6 | { 7 | q.push(nums[i]); 8 | if(q.size() > k) q.pop(); 9 | } 10 | return q.top(); 11 | } 12 | }; -------------------------------------------------------------------------------- /257.binary-tree-paths/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a binary tree, return all root-to-leaf paths. 3 | 4 | 5 | For example, given the following binary tree: 6 | 7 | 8 | 9 | 1 10 | / \ 11 | 2 3 12 | \ 13 | 5 14 | 15 | 16 | 17 | All root-to-leaf paths are: 18 | ["1->2->5", "1->3"] 19 | 20 | 21 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /019.remove-nth-node-from-end-of-list/question.md: -------------------------------------------------------------------------------- 1 | Given a linked list, remove the nth node from the end of list and return its head. 2 | 3 | 4 | For example, 5 | 6 | 7 | Given linked list: 1->2->3->4->5, and n = 2. 8 | 9 | After removing the second node from the end, the linked list becomes 1->2->3->5. 10 | 11 | 12 | 13 | Note: 14 | Given n will always be valid. 15 | Try to do this in one pass. 16 | -------------------------------------------------------------------------------- /055.jump-game/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | 4 | 5 | Each element in the array represents your maximum jump length at that position. 6 | 7 | 8 | Determine if you are able to reach the last index. 9 | 10 | 11 | 12 | For example: 13 | A = [2,3,1,1,4], return true. 14 | 15 | 16 | A = [3,2,1,0,4], return false. 17 | -------------------------------------------------------------------------------- /171.excel-sheet-column-number/question.md: -------------------------------------------------------------------------------- 1 | Related to question Excel Sheet Column Title 2 | Given a column title as appear in an Excel sheet, return its corresponding column number. 3 | 4 | For example: 5 | A -> 1 6 | B -> 2 7 | C -> 3 8 | ... 9 | Z -> 26 10 | AA -> 27 11 | AB -> 28 12 | 13 | Credits:Special thanks to @ts for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /223.rectangle-area/question.md: -------------------------------------------------------------------------------- 1 | Find the total area covered by two rectilinear rectangles in a 2D plane. 2 | Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. 3 | 4 | 5 | 6 | 7 | Assume that the total area is never beyond the maximum possible value of int. 8 | 9 | 10 | Credits:Special thanks to @mithmatt for adding this problem, creating the above image and all test cases. -------------------------------------------------------------------------------- /242.valid-anagram/question.md: -------------------------------------------------------------------------------- 1 | Given two strings s and t, write a function to determine if t is an anagram of s. 2 | 3 | For example, 4 | s = "anagram", t = "nagaram", return true. 5 | s = "rat", t = "car", return false. 6 | 7 | 8 | Note: 9 | You may assume the string contains only lowercase alphabets. 10 | 11 | Follow up: 12 | What if the inputs contain unicode characters? How would you adapt your solution to such case? -------------------------------------------------------------------------------- /060.permutation-sequence/question.md: -------------------------------------------------------------------------------- 1 | The set [1,2,3,…,n] contains a total of n! unique permutations. 2 | 3 | By listing and labeling all of the permutations in order, 4 | We get the following sequence (ie, for n = 3): 5 | 6 | "123" 7 | "132" 8 | "213" 9 | "231" 10 | "312" 11 | "321" 12 | 13 | 14 | 15 | Given n and k, return the kth permutation sequence. 16 | 17 | Note: Given n will be between 1 and 9 inclusive. -------------------------------------------------------------------------------- /279.perfect-squares/perfect-squares.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numSquares(int n) { 4 | vector dp(n + 1, INT_MAX); 5 | dp[0] = 0; 6 | for(int i = 1; i <= n; i++ ) 7 | { 8 | for(int j = 1; j <= sqrt(i); j++) 9 | { 10 | dp[i] = min(dp[i], dp[i - j * j] + 1); 11 | } 12 | } 13 | return dp[n]; 14 | } 15 | }; -------------------------------------------------------------------------------- /173.binary-search-tree-iterator/question.md: -------------------------------------------------------------------------------- 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. -------------------------------------------------------------------------------- /215.kth-largest-element-in-an-array/question.md: -------------------------------------------------------------------------------- 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 | For example, 4 | Given [3,2,1,5,6,4] and k = 2, return 5. 5 | 6 | 7 | Note: 8 | You may assume k is always valid, 1 ≤ k ≤ array's length. 9 | 10 | Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /223.rectangle-area/rectangle-area.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 4 | int areaA = (C - A) * (D - B); 5 | int areaB = (G - E) * (H - F); 6 | if(C < E || A > G || B > H || D < F) return areaA + areaB; 7 | int inter = (min(D, H) - max(B, F)) * (min(G, C) - max(A, E)); 8 | return areaA + areaB - inter; 9 | } 10 | }; -------------------------------------------------------------------------------- /119.pascals-triangle-ii/pascals-triangle-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getRow(int rowIndex) { 4 | vector res(1,1); 5 | for(int i=1;i<=rowIndex;i++) 6 | { 7 | vector temp=res; 8 | for(int j=0;j& nums) { 4 | vector res; 5 | for(auto i : nums) 6 | { 7 | auto tmp = lower_bound(res.begin(), res.end(), i); 8 | if(tmp == res.end()) res.push_back(i); 9 | else *tmp = i; 10 | } 11 | return res.size(); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /003.longest-substring-without-repeating-characters/question.md: -------------------------------------------------------------------------------- 1 | Given a string, find the length of the longest substring without repeating characters. 2 | 3 | Examples: 4 | 5 | Given "abcabcbb", the answer is "abc", which the length is 3. 6 | 7 | Given "bbbbb", the answer is "b", with the length of 1. 8 | 9 | Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. -------------------------------------------------------------------------------- /050.powx-n/powx-n.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double myPow(double x, long long n) { 4 | double result=1,base=x; 5 | while(n) 6 | { 7 | if(n<0) 8 | { 9 | base=1/base; 10 | n=-n; 11 | } 12 | if(n&1) result*=base; 13 | base*=base; 14 | n>>=1; 15 | } 16 | return result; 17 | } 18 | }; -------------------------------------------------------------------------------- /096.unique-binary-search-trees/question.md: -------------------------------------------------------------------------------- 1 | Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 2 | 3 | 4 | For example, 5 | Given n = 3, there are a total of 5 unique BST's. 6 | 7 | 8 | 1 3 3 2 1 9 | \ / / / \ \ 10 | 3 2 1 1 3 2 11 | / / \ \ 12 | 2 1 2 3 13 | 14 | -------------------------------------------------------------------------------- /164.maximum-gap/question.md: -------------------------------------------------------------------------------- 1 | Given an unsorted array, find the maximum difference between the successive elements in its sorted form. 2 | 3 | Try to solve it in linear time/space. 4 | 5 | Return 0 if the array contains less than 2 elements. 6 | 7 | You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range. 8 | 9 | Credits:Special thanks to @porker2008 for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /204.count-primes/count-primes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPrimes(int n) { 4 | vector mp(n, 0); 5 | int res = 0; 6 | for(int i = 2 ; i < n ; i++) 7 | { 8 | if(!mp[i]) 9 | { 10 | res++; 11 | if(i <= sqrt(n)) for(int j = i * i ; j < n ;j += i) mp[j] = 1; 12 | } 13 | } 14 | return res; 15 | } 16 | }; -------------------------------------------------------------------------------- /004.median-of-two-sorted-arrays/question.md: -------------------------------------------------------------------------------- 1 | There are two sorted arrays nums1 and nums2 of size m and n respectively. 2 | 3 | Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 4 | 5 | Example 1: 6 | 7 | nums1 = [1, 3] 8 | nums2 = [2] 9 | 10 | The median is 2.0 11 | 12 | 13 | 14 | Example 2: 15 | 16 | nums1 = [1, 2] 17 | nums2 = [3, 4] 18 | 19 | The median is (2 + 3)/2 = 2.5 20 | 21 | -------------------------------------------------------------------------------- /038.count-and-say/question.md: -------------------------------------------------------------------------------- 1 | The count-and-say sequence is the sequence of integers beginning as follows: 2 | 1, 11, 21, 1211, 111221, ... 3 | 4 | 5 | 6 | 1 is read off as "one 1" or 11. 7 | 11 is read off as "two 1s" or 21. 8 | 21 is read off as "one 2, then one 1" or 1211. 9 | 10 | 11 | 12 | Given an integer n, generate the nth sequence. 13 | 14 | 15 | 16 | Note: The sequence of integers will be represented as a string. 17 | 18 | -------------------------------------------------------------------------------- /073.set-matrix-zeroes/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 3 | 4 | 5 | click to show follow up. 6 | 7 | Follow up: 8 | 9 | 10 | Did you use extra space? 11 | A straight forward solution using O(mn) space is probably a bad idea. 12 | A simple improvement uses O(m + n) space, but still not the best solution. 13 | Could you devise a constant space solution? 14 | 15 | -------------------------------------------------------------------------------- /102.binary-tree-level-order-traversal/question.md: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /122.best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | if(prices.empty()) return 0; 5 | int res=0,pre=prices[0]; 6 | for(int i=0;iprices[i]) res+=prices[i+1]-prices[i]; 9 | pre=prices[i+1]; 10 | } 11 | return res; 12 | } 13 | }; -------------------------------------------------------------------------------- /188.best-time-to-buy-and-sell-stock-iv/question.md: -------------------------------------------------------------------------------- 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 | Credits:Special thanks to @Freezen for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /190.reverse-bits/reverse-bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | uint32_t reverseBits(uint32_t n) { 4 | n = (n >> 16) | (n << 16); 5 | n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8); 6 | n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4); 7 | n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2); 8 | n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1); 9 | return n; 10 | } 11 | }; -------------------------------------------------------------------------------- /162.find-peak-element/find-peak-element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findPeakElement(vector& nums) { 4 | int l = 0, r = nums.size()-1; 5 | while(l>1; 8 | if(nums[mid]>nums[mid+1] && nums[mid]>nums[mid-1]) return mid; 9 | if(nums[mid]> 1; 11 | if(isBadVersion(mid)) r = mid - 1; 12 | else l = mid + 1; 13 | } 14 | return l; 15 | } 16 | }; -------------------------------------------------------------------------------- /009.palindrome-number/palindrome-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) 4 | { 5 | if(x<0) return false; 6 | int base=1; 7 | while(x/base>=10) 8 | base*=10; 9 | while(x) 10 | { 11 | if(x/base!=x%10) return false; 12 | x=x-x/base*base; 13 | x/=10; 14 | base/=100; 15 | } 16 | return true; 17 | } 18 | }; -------------------------------------------------------------------------------- /154.find-minimum-in-rotated-sorted-array-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Follow up for "Find Minimum in Rotated Sorted Array": 3 | What if duplicates are allowed? 4 | 5 | Would this affect the run-time complexity? How and why? 6 | 7 | 8 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 9 | 10 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 11 | 12 | Find the minimum element. 13 | 14 | The array may contain duplicates. -------------------------------------------------------------------------------- /214.shortest-palindrome/question.md: -------------------------------------------------------------------------------- 1 | 2 | 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. 3 | 4 | 5 | For example: 6 | Given "aacecaaa", return "aaacecaaa". 7 | Given "abcd", return "dcbabcd". 8 | 9 | Credits:Special thanks to @ifanchu for adding this problem and creating all test cases. Thanks to @Freezen for additional test cases. -------------------------------------------------------------------------------- /018.4sum/question.md: -------------------------------------------------------------------------------- 1 | Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. 2 | 3 | Note: The solution set must not contain duplicate quadruplets. 4 | 5 | 6 | 7 | For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0. 8 | 9 | A solution set is: 10 | [ 11 | [-1, 0, 0, 1], 12 | [-2, -1, 1, 2], 13 | [-2, 0, 0, 2] 14 | ] 15 | -------------------------------------------------------------------------------- /130.surrounded-regions/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. 3 | 4 | A region is captured by flipping all 'O's into 'X's in that surrounded region. 5 | 6 | 7 | 8 | For example, 9 | 10 | X X X X 11 | X O O X 12 | X X O X 13 | X O X X 14 | 15 | 16 | 17 | 18 | After running your function, the board should be: 19 | 20 | X X X X 21 | X X X X 22 | X X X X 23 | X O X X 24 | 25 | -------------------------------------------------------------------------------- /263.ugly-number/question.md: -------------------------------------------------------------------------------- 1 | 2 | Write a program to check whether a given number is an ugly number. 3 | 4 | 5 | 6 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 7 | 8 | 9 | 10 | Note that 1 is typically treated as an ugly number. 11 | 12 | 13 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /069.sqrtx/sqrtx.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int mySqrt(int x) { 4 | long long l=0,r=x,mid; 5 | while(l<=r) 6 | { 7 | mid=(l+r)>>1; 8 | long long ans=mid*mid; 9 | if(ans<=x && (mid+1)*(mid+1)>x) 10 | return mid; 11 | if(ans>x) 12 | r=mid-1; 13 | else 14 | l=mid+1; 15 | } 16 | return mid; 17 | } 18 | }; -------------------------------------------------------------------------------- /153.find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int l = 0, r = nums.size()-1; 5 | while(nums[l]>nums[r]) 6 | { 7 | int mid = (l + r) >> 1; 8 | if(nums[mid] >= nums[l]) 9 | l = mid+1; 10 | else 11 | r = mid; 12 | } 13 | return nums[l]; 14 | } 15 | }; -------------------------------------------------------------------------------- /238.product-of-array-except-self/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 3 | 4 | Solve it without division and in O(n). 5 | 6 | For example, given [1,2,3,4], return [24,12,8,6]. 7 | 8 | Follow up: 9 | Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) -------------------------------------------------------------------------------- /011.container-with-most-water/container-with-most-water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxArea(vector& height) { 4 | int l=0,r=height.size()-1; 5 | int result=0; 6 | while(l='a' && s[i]<='z') || (s[i]>='0' && s[i]<='9')) temp+=s[i]; 8 | if((s[i]>='A' && s[i]<='Z') ) temp+=s[i]-'A'+'a'; 9 | } 10 | string temp2=temp; 11 | reverse(temp.begin(),temp.end()); 12 | return temp==temp2; 13 | } 14 | }; -------------------------------------------------------------------------------- /219.contains-duplicate-ii/contains-duplicate-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool containsNearbyDuplicate(vector& nums, int k) { 4 | unordered_map mp; 5 | for(int i = 0; i < nums.size(); i++) 6 | { 7 | if(mp.find(nums[i]) == mp.end()) mp[nums[i]] = i; 8 | else if(abs(mp[nums[i]]-i) <= k) return true; 9 | else mp[nums[i]] = i; 10 | } 11 | return false; 12 | } 13 | }; -------------------------------------------------------------------------------- /230.kth-smallest-element-in-a-bst/question.md: -------------------------------------------------------------------------------- 1 | Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. 2 | 3 | Note: 4 | You may assume k is always valid, 1 ? k ? BST's total elements. 5 | 6 | Follow up: 7 | What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? 8 | 9 | Credits:Special thanks to @ts for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /053.maximum-subarray/question.md: -------------------------------------------------------------------------------- 1 | 2 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 3 | 4 | 5 | For example, given the array [-2,1,-3,4,-1,2,1,-5,4], 6 | the contiguous subarray [4,-1,2,1] has the largest sum = 6. 7 | 8 | 9 | click to show more practice. 10 | 11 | More practice: 12 | 13 | If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 14 | -------------------------------------------------------------------------------- /062.unique-paths/question.md: -------------------------------------------------------------------------------- 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 | 9 | Above is a 3 x 7 grid. How many possible unique paths are there? 10 | 11 | 12 | Note: m and n will be at most 100. -------------------------------------------------------------------------------- /107.binary-tree-level-order-traversal-ii/question.md: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /113.path-sum-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 3 | 4 | 5 | For example: 6 | Given the below binary tree and sum = 22, 7 | 8 | 5 9 | / \ 10 | 4 8 11 | / / \ 12 | 11 13 4 13 | / \ / \ 14 | 7 2 5 1 15 | 16 | 17 | 18 | return 19 | 20 | [ 21 | [5,4,11,2], 22 | [5,8,4,5] 23 | ] 24 | 25 | -------------------------------------------------------------------------------- /124.binary-tree-maximum-path-sum/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a binary tree, find the maximum path sum. 3 | 4 | 5 | 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. 6 | 7 | 8 | For example: 9 | Given the below binary tree, 10 | 11 | 1 12 | / \ 13 | 2 3 14 | 15 | 16 | 17 | Return 6. 18 | -------------------------------------------------------------------------------- /174.dungeon-game/dungeon-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int calculateMinimumHP(vector>& dungeon) { 4 | int m = dungeon.size(); 5 | int n=dungeon[0].size(); 6 | vector dp(n+1, INT_MAX); 7 | dp[n-1] = 1; 8 | for(int i = m-1; i>=0; i--) 9 | for(int j =n-1; j>=0; j--) 10 | dp[j] = max(min(dp[j], dp[j+1])-dungeon[i][j], 1); 11 | return dp[0]; 12 | } 13 | }; -------------------------------------------------------------------------------- /258.add-digits/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 3 | 4 | 5 | 6 | For example: 7 | 8 | 9 | Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 10 | 11 | 12 | Follow up: 13 | Could you do it without any loop/recursion in O(1) runtime? 14 | 15 | 16 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /268.missing-number/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 3 | 4 | 5 | For example, 6 | Given nums = [0, 1, 3] return 2. 7 | 8 | 9 | 10 | Note: 11 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 12 | 13 | 14 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /081.search-in-rotated-sorted-array-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Follow up for "Search in Rotated Sorted Array": 3 | What if duplicates are allowed? 4 | 5 | Would this affect the run-time complexity? How and why? 6 | 7 | 8 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 9 | 10 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 11 | 12 | Write a function to determine if a given target is in the array. 13 | 14 | The array may contain duplicates. -------------------------------------------------------------------------------- /104.maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int maxDepth(TreeNode* root) { 13 | if(!root) return 0; 14 | return max(maxDepth(root->left),maxDepth(root->right))+1; 15 | } 16 | }; -------------------------------------------------------------------------------- /190.reverse-bits/question.md: -------------------------------------------------------------------------------- 1 | Reverse bits of a given 32 bits unsigned integer. 2 | 3 | For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). 4 | 5 | 6 | Follow up: 7 | If this function is called many times, how would you optimize it? 8 | 9 | 10 | Related problem: Reverse Integer 11 | 12 | Credits:Special thanks to @ts for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /058.length-of-last-word/length-of-last-word.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLastWord(string s) { 4 | int result=0,flag=0; 5 | for(int i=s.size()-1;i>=0;i--) 6 | { 7 | if(!flag && s[i]==' ') continue; 8 | if(s[i]!=' ') 9 | { 10 | flag=1; 11 | result++; 12 | } 13 | else 14 | break; 15 | } 16 | return result; 17 | } 18 | }; -------------------------------------------------------------------------------- /123.best-time-to-buy-and-sell-stock-iii/best-time-to-buy-and-sell-stock-iii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int b1=INT_MIN,b2=INT_MIN; 5 | int s1=0,s2=0; 6 | for(int i=0;i>& matrix, int target) { 4 | if(matrix.empty()) return false; 5 | int i = 0, j = matrix.size() - 1; 6 | while(i < matrix[0].size() && j >= 0) 7 | { 8 | if(matrix[j][i] == target) return true; 9 | else if (matrix[j][i] > target) j--; 10 | else i++; 11 | } 12 | return false; 13 | } 14 | }; -------------------------------------------------------------------------------- /017.letter-combinations-of-a-phone-number/question.md: -------------------------------------------------------------------------------- 1 | Given a digit string, return all possible letter combinations that the number could represent. 2 | 3 | 4 | 5 | A mapping of digit to letters (just like on the telephone buttons) is given below. 6 | 7 | 8 | 9 | Input:Digit string "23" 10 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 11 | 12 | 13 | 14 | Note: 15 | Although the above answer is in lexicographical order, your answer could be in any order you want. 16 | -------------------------------------------------------------------------------- /089.gray-code/gray-code.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector grayCode(int n) { 4 | if (n == 0) 5 | return vector(1, 0); 6 | vector pre_result = grayCode(n - 1); 7 | vector cur_result(pre_result); 8 | for (int i = pre_result.size() - 1; i >=0; --i) { 9 | cur_result.push_back((1<<(n - 1)) + pre_result[i]); 10 | } 11 | return cur_result; 12 | } 13 | }; -------------------------------------------------------------------------------- /091.decode-ways/question.md: -------------------------------------------------------------------------------- 1 | 2 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 3 | 4 | 5 | 6 | 'A' -> 1 7 | 'B' -> 2 8 | ... 9 | 'Z' -> 26 10 | 11 | 12 | 13 | Given an encoded message containing digits, determine the total number of ways to decode it. 14 | 15 | 16 | 17 | For example, 18 | Given encoded message "12", 19 | it could be decoded as "AB" (1 2) or "L" (12). 20 | 21 | 22 | 23 | The number of ways decoding "12" is 2. 24 | -------------------------------------------------------------------------------- /187.repeated-dna-sequences/question.md: -------------------------------------------------------------------------------- 1 | 2 | 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. 3 | 4 | Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. 5 | 6 | 7 | For example, 8 | 9 | Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT", 10 | 11 | Return: 12 | ["AAAAACCCCC", "CCCCCAAAAA"]. 13 | -------------------------------------------------------------------------------- /224.basic-calculator/question.md: -------------------------------------------------------------------------------- 1 | Implement a basic calculator to evaluate a simple expression string. 2 | 3 | The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . 4 | 5 | You may assume that the given expression is always valid. 6 | 7 | Some examples: 8 | 9 | "1 + 1" = 2 10 | " 2-1 + 2 " = 3 11 | "(1+(4+5+2)-3)+(6+8)" = 23 12 | 13 | 14 | 15 | 16 | Note: Do not use the eval built-in library function. 17 | -------------------------------------------------------------------------------- /063.unique-paths-ii/question.md: -------------------------------------------------------------------------------- 1 | Follow up for "Unique Paths": 2 | 3 | Now consider if some obstacles are added to the grids. How many unique paths would there be? 4 | 5 | An obstacle and empty space is marked as 1 and 0 respectively in the grid. 6 | 7 | For example, 8 | There is one obstacle in the middle of a 3x3 grid as illustrated below. 9 | 10 | [ 11 | [0,0,0], 12 | [0,1,0], 13 | [0,0,0] 14 | ] 15 | 16 | The total number of unique paths is 2. 17 | 18 | Note: m and n will be at most 100. -------------------------------------------------------------------------------- /022.generate-parentheses/generate-parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(vector &v,string s,int l,int r) 4 | { 5 | if(l==0 && r==0) 6 | v.push_back(s); 7 | if(l!=0) 8 | dfs(v,s+"(",l-1,r); 9 | if(r>l) 10 | dfs(v,s+")",l,r-1); 11 | } 12 | vector generateParenthesis(int n) 13 | { 14 | vector result; 15 | dfs(result,"",n,n); 16 | return result; 17 | } 18 | }; -------------------------------------------------------------------------------- /027.remove-element/question.md: -------------------------------------------------------------------------------- 1 | Given an array and a value, remove all instances of that value in place and return the new length. 2 | 3 | 4 | Do not allocate extra space for another array, you must do this in place with constant memory. 5 | 6 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 7 | 8 | 9 | Example: 10 | Given input array nums = [3,2,2,3], val = 3 11 | 12 | 13 | Your function should return length = 2, with the first two elements of nums being 2. -------------------------------------------------------------------------------- /084.largest-rectangle-in-histogram/question.md: -------------------------------------------------------------------------------- 1 | 2 | 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. 3 | 4 | 5 | 6 | 7 | Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. 8 | 9 | 10 | 11 | 12 | The largest rectangle is shown in the shaded area, which has area = 10 unit. 13 | 14 | 15 | 16 | For example, 17 | Given heights = [2,1,5,6,2,3], 18 | return 10. 19 | -------------------------------------------------------------------------------- /103.binary-tree-zigzag-level-order-traversal/question.md: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /115.distinct-subsequences/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a string S and a string T, count the number of distinct subsequences of T in S. 3 | 4 | 5 | 6 | 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). 7 | 8 | 9 | 10 | Here is an example: 11 | S = "rabbbit", T = "rabbit" 12 | 13 | 14 | Return 3. 15 | -------------------------------------------------------------------------------- /137.single-number-ii/single-number-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int res = 0; 5 | for(int i = 0 ; i < 32; i++) 6 | { 7 | int cnt = 0 ; 8 | for(int j = 0; j < nums.size() ;j++) 9 | { 10 | cnt += ((1 << i) & nums[j])>>i; 11 | } 12 | res |= cnt % 3 << i; 13 | //cout< res(1, 1); 5 | int i = 0, j = 0, k = 0; 6 | while(res.size() < n) 7 | { 8 | res.push_back(min(min(res[i] * 2, res[j] * 3), res[k] * 5)); 9 | if(res.back() == res[i] * 2) i++; 10 | if(res.back() == res[j] * 3) j++; 11 | if(res.back() == res[k] * 5) k++; 12 | } 13 | return res.back(); 14 | } 15 | }; -------------------------------------------------------------------------------- /134.gas-station/gas-station.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int canCompleteCircuit(vector& gas, vector& cost) { 4 | int sum = 0, minn = INT_MAX, pos; 5 | for(int i = 0;i < gas.size();i++) 6 | { 7 | sum+=(gas[i]-cost[i]); 8 | if(minn > sum) 9 | { 10 | minn = sum; 11 | pos = i; 12 | } 13 | } 14 | if(sum<0) return -1; 15 | return (pos+1) % gas.size(); 16 | } 17 | }; -------------------------------------------------------------------------------- /238.product-of-array-except-self/product-of-array-except-self.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector productExceptSelf(vector& nums) { 4 | vector res(nums.size(), 1); 5 | int s = 1, e = 1; 6 | int n = nums.size(); 7 | for(int i = 0; i < nums.size(); i++) 8 | { 9 | res[i] *= s; 10 | s *= nums[i]; 11 | res[n - 1 - i] *= e; 12 | e *= nums[n - 1 - i]; 13 | } 14 | return res; 15 | } 16 | }; -------------------------------------------------------------------------------- /275.h-index-ii/h-index-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hIndex(vector& citations) { 4 | int mid = -1, l = 0, r = citations.size()-1; 5 | while(l <= r) 6 | { 7 | mid = (l + r) >> 1; 8 | if(citations.size() - mid == citations[mid]) return citations[mid]; 9 | else if(citations.size() - mid > citations[mid]) l = mid + 1; 10 | else r = mid - 1; 11 | } 12 | return citations.size() - r - 1; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /091.decode-ways/decode-ways.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numDecodings(string s) { 4 | if(s.empty()) return 0; 5 | vector dp(s.size()+1,0); 6 | dp[0]=1; 7 | if(s[0]!='0') dp[1]=1; 8 | for(int i=1;i='0' && s[i]<='9' && s[i-1]=='1') || (s[i-1]=='2' && s[i]>='0' && s[i]<='6')) dp[i+1]+=dp[i-1]; 12 | } 13 | return dp[s.size()]; 14 | } 15 | }; -------------------------------------------------------------------------------- /112.path-sum/question.md: -------------------------------------------------------------------------------- 1 | 2 | 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. 3 | 4 | 5 | For example: 6 | Given the below binary tree and sum = 22, 7 | 8 | 5 9 | / \ 10 | 4 8 11 | / / \ 12 | 11 13 4 13 | / \ \ 14 | 7 2 1 15 | 16 | 17 | 18 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. -------------------------------------------------------------------------------- /024.swap-nodes-in-pairs/swap-nodes-in-pairs.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* swapPairs(ListNode* head) { 12 | if(head==NULL || head->next==NULL) return head; 13 | ListNode* p=head->next; 14 | head->next=swapPairs(p->next); 15 | p->next=head; 16 | return p; 17 | } 18 | }; -------------------------------------------------------------------------------- /078.subsets/subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> subsets(vector& nums) { 4 | vector> result(1); 5 | for(int i=0;i temp=result[j]; 11 | temp.push_back(nums[i]); 12 | result.push_back(temp); 13 | } 14 | } 15 | return result; 16 | } 17 | }; -------------------------------------------------------------------------------- /101.symmetric-tree/question.md: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /129.sum-root-to-leaf-numbers/question.md: -------------------------------------------------------------------------------- 1 | Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 2 | An example is the root-to-leaf path 1->2->3 which represents the number 123. 3 | 4 | Find the total sum of all root-to-leaf numbers. 5 | 6 | For example, 7 | 8 | 1 9 | / \ 10 | 2 3 11 | 12 | 13 | 14 | The root-to-leaf path 1->2 represents the number 12. 15 | The root-to-leaf path 1->3 represents the number 13. 16 | 17 | 18 | Return the sum = 12 + 13 = 25. 19 | -------------------------------------------------------------------------------- /216.combination-sum-iii/question.md: -------------------------------------------------------------------------------- 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 | 5 | 6 | Example 1: 7 | Input: k = 3, n = 7 8 | Output: 9 | 10 | [[1,2,4]] 11 | 12 | 13 | Example 2: 14 | Input: k = 3, n = 9 15 | Output: 16 | 17 | [[1,2,6], [1,3,5], [2,3,4]] 18 | 19 | 20 | 21 | Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /026.remove-duplicates-from-sorted-array/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 3 | 4 | 5 | Do not allocate extra space for another array, you must do this in place with constant memory. 6 | 7 | 8 | 9 | For example, 10 | Given input array nums = [1,1,2], 11 | 12 | 13 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. 14 | -------------------------------------------------------------------------------- /134.gas-station/question.md: -------------------------------------------------------------------------------- 1 | 2 | There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. 3 | 4 | 5 | 6 | You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. 7 | 8 | 9 | 10 | Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. 11 | 12 | 13 | 14 | Note: 15 | The solution is guaranteed to be unique. 16 | -------------------------------------------------------------------------------- /282.expression-add-operators/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. 3 | 4 | 5 | Examples: 6 | "123", 6 -> ["1+2+3", "1*2*3"] 7 | "232", 8 -> ["2*3+2", "2+3*2"] 8 | "105", 5 -> ["1*0+5","10-5"] 9 | "00", 0 -> ["0+0", "0-0", "0*0"] 10 | "3456237490", 9191 -> [] 11 | 12 | 13 | Credits:Special thanks to @davidtan1890 for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /026.remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int result=0; 5 | if(nums.size()>0) result=1; 6 | for(int i=1;inext) 13 | { 14 | delete node; 15 | return ; 16 | } 17 | node->val = node->next->val; 18 | node->next = node->next->next; 19 | } 20 | }; -------------------------------------------------------------------------------- /006.zigzag-conversion/question.md: -------------------------------------------------------------------------------- 1 | 2 | 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) 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 | 12 | Write the code that will take a string and make this conversion given a number of rows: 13 | 14 | string convert(string text, int nRows); 15 | 16 | convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 17 | -------------------------------------------------------------------------------- /071.simplify-path/question.md: -------------------------------------------------------------------------------- 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 | 8 | click to show corner cases. 9 | 10 | Corner Cases: 11 | 12 | 13 | 14 | Did you consider the case where path = "/../"? 15 | In this case, you should return "/". 16 | Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". 17 | In this case, you should ignore redundant slashes and return "/home/foo". 18 | 19 | -------------------------------------------------------------------------------- /226.invert-binary-tree/invert-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* invertTree(TreeNode* root) { 13 | if(!root) return root; 14 | swap(root->right, root->left); 15 | invertTree(root->right); 16 | invertTree(root->left); 17 | return root; 18 | } 19 | }; -------------------------------------------------------------------------------- /057.insert-interval/question.md: -------------------------------------------------------------------------------- 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 | 6 | Example 1: 7 | Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. 8 | 9 | 10 | 11 | Example 2: 12 | Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. 13 | 14 | 15 | 16 | This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. 17 | -------------------------------------------------------------------------------- /239.sliding-window-maximum/sliding-window-maximum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector maxSlidingWindow(vector& nums, int k) { 4 | vector res; 5 | deque q; 6 | for(int i = 0; i < nums.size(); i++) 7 | { 8 | if(!q.empty() && i - q.front() >= k) q.pop_front(); 9 | while(!q.empty() && nums[q.back()] <= nums[i]) q.pop_back(); 10 | q.push_back(i); 11 | if(i >= k - 1) res.push_back(nums[q.front()]); 12 | } 13 | return res; 14 | } 15 | }; -------------------------------------------------------------------------------- /274.h-index/h-index.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hIndex(vector& citations) { 4 | vector cnt(citations.size() + 2, 0); 5 | for(int i = 0; i < citations.size(); i++) 6 | { 7 | if(citations[i] > citations.size()) cnt[citations.size()]++; 8 | else cnt[citations[i]]++; 9 | } 10 | for(int i = citations.size() ; i >= 0; i--) 11 | { 12 | cnt[i] += cnt[i + 1]; 13 | if(cnt[i] >= i) return i; 14 | } 15 | return 0; 16 | } 17 | }; -------------------------------------------------------------------------------- /283.move-zeroes/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 3 | 4 | 5 | 6 | For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 7 | 8 | 9 | 10 | Note: 11 | 12 | You must do this in-place without making a copy of the array. 13 | Minimize the total number of operations. 14 | 15 | 16 | 17 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /048.rotate-image/rotate-image.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector>& matrix) { 4 | int n=matrix.size(); 5 | for(int i=0;i<=(n-1)/2;i++) 6 | { 7 | for(int j=0;j& nums) { 4 | int l = 0, r = nums.size()-1; 5 | while(l> 1; 8 | if(nums[mid] > nums[r]) 9 | l = mid+1; 10 | else if(nums[mid] < nums[r]) 11 | r = mid; 12 | else 13 | r--; 14 | } 15 | return nums[l]; 16 | } 17 | }; -------------------------------------------------------------------------------- /064.minimum-path-sum/minimum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minPathSum(vector>& grid) { 4 | if(grid.size()==0) return 0; 5 | for(int i=1;i& ratings) { 4 | vector dp(ratings.size(), 1); 5 | int res = 0; 6 | for(int i = 1; i < ratings.size();i++) 7 | { 8 | if(ratings[i]>ratings[i-1]) dp[i] = dp[i-1] + 1; 9 | } 10 | for(int i = ratings.size()-2;i >= 0 ;i--) 11 | { 12 | if(ratings[i] > ratings[i+1]) dp[i] = max(dp[i], dp[i+1] + 1) ; 13 | res += dp[i]; 14 | } 15 | return res + dp[ratings.size()-1]; 16 | } 17 | }; -------------------------------------------------------------------------------- /152.maximum-product-subarray/maximum-product-subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& nums) 4 | { 5 | int res = nums[0]; 6 | int minn = nums[0]; 7 | int maxx = nums[0]; 8 | for(int i = 1; i< nums.size();i++) 9 | { 10 | int x = maxx*nums[i]; 11 | int y = minn*nums[i]; 12 | maxx = max(max(x, y), nums[i]); 13 | minn = min(min(x, y), nums[i]); 14 | res = max(res, maxx); 15 | } 16 | return res; 17 | } 18 | }; -------------------------------------------------------------------------------- /019.remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | int cnt=0; 12 | ListNode* removeNthFromEnd(ListNode* head, int n) { 13 | if(head==NULL) return NULL; 14 | head->next=removeNthFromEnd(head->next,n); 15 | if(++cnt==n) 16 | return head->next; 17 | return head; 18 | } 19 | }; -------------------------------------------------------------------------------- /031.next-permutation/question.md: -------------------------------------------------------------------------------- 1 | 2 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 3 | 4 | 5 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 6 | 7 | 8 | The replacement must be in-place, do not allocate extra memory. 9 | 10 | 11 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 12 | 1,2,3 → 1,3,2 13 | 3,2,1 → 1,2,3 14 | 1,1,5 → 1,5,1 15 | -------------------------------------------------------------------------------- /088.merge-sorted-array/merge-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void merge(vector& nums1, int m, vector& nums2, int n) { 4 | int e1=m-1,e2=n-1,e3=m+n-1; 5 | while(e1>=0 || e2>=0) 6 | { 7 | if(e1==-1) 8 | nums1[e3--]=nums2[e2--]; 9 | else if(e2==-1) 10 | nums1[e3--]=nums1[e1--]; 11 | else if(nums1[e1]>nums2[e2]) 12 | nums1[e3--]=nums1[e1--]; 13 | else 14 | nums1[e3--]=nums2[e2--]; 15 | } 16 | } 17 | }; -------------------------------------------------------------------------------- /055.jump-game/jump-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int st=0; 5 | while(st=maxx) 11 | { 12 | maxx=i+nums[st+i]; 13 | pos=i; 14 | } 15 | } 16 | if(maxx==-1) return false; 17 | st+=pos; 18 | } 19 | return true; 20 | } 21 | }; -------------------------------------------------------------------------------- /065.valid-number/question.md: -------------------------------------------------------------------------------- 1 | Validate if a given string is numeric. 2 | 3 | 4 | Some examples: 5 | "0" => true 6 | " 0.1 " => true 7 | "abc" => false 8 | "1 a" => false 9 | "2e10" => true 10 | 11 | 12 | Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. 13 | 14 | 15 | 16 | Update (2015-02-10): 17 | The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition. 18 | -------------------------------------------------------------------------------- /220.contains-duplicate-iii/contains-duplicate-iii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool containsNearbyAlmostDuplicate(vector& nums, int k, long long t) { 4 | set s; 5 | for(int i = 0; i < nums.size(); i++) 6 | { 7 | if(i > k) s.erase(nums[i - k - 1]); 8 | set::iterator pos = s.lower_bound(nums[i] - t); 9 | //cout<<*pos<b.size()) swap(a,b); 7 | while(a.size()& nums) { 4 | if(nums.size()<2) return ; 5 | for(int i=nums.size()-1;i>0;i--) 6 | { 7 | if(nums[i]>nums[i-1]) 8 | { 9 | reverse(nums.begin()+i,nums.end()); 10 | vector::iterator it=upper_bound(nums.begin()+i,nums.end(),nums[i-1]); 11 | swap(*it,nums[i-1]); 12 | return ; 13 | } 14 | } 15 | reverse(nums.begin(),nums.end()); 16 | } 17 | }; -------------------------------------------------------------------------------- /079.word-search/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a 2D board and a word, find if the word exists in the grid. 3 | 4 | 5 | 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. 6 | 7 | 8 | 9 | For example, 10 | Given board = 11 | 12 | [ 13 | ['A','B','C','E'], 14 | ['S','F','C','S'], 15 | ['A','D','E','E'] 16 | ] 17 | 18 | 19 | word = "ABCCED", -> returns true, 20 | word = "SEE", -> returns true, 21 | word = "ABCB", -> returns false. 22 | -------------------------------------------------------------------------------- /179.largest-number/largest-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static bool cmp(string &a, string &b) 4 | { 5 | return a+b > b+a; 6 | } 7 | string largestNumber(vector& nums) 8 | { 9 | vector res; 10 | for(int i = 0; i < nums.size(); i++) 11 | res.push_back(to_string(nums[i])); 12 | sort(res.begin(), res.end(), cmp); 13 | string ans; 14 | for(int i = 0; i < res.size() ; i++) 15 | ans += res[i]; 16 | if(ans[0] == '0') ans = '0'; 17 | return ans; 18 | } 19 | }; -------------------------------------------------------------------------------- /227.basic-calculator-ii/question.md: -------------------------------------------------------------------------------- 1 | Implement a basic calculator to evaluate a simple expression string. 2 | 3 | The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. 4 | 5 | You may assume that the given expression is always valid. 6 | 7 | Some examples: 8 | 9 | "3+2*2" = 7 10 | " 3/2 " = 1 11 | " 3+5 / 2 " = 5 12 | 13 | 14 | 15 | 16 | Note: Do not use the eval built-in library function. 17 | 18 | 19 | Credits:Special thanks to @ts for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /041.first-missing-positive/first-missing-positive.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstMissingPositive(vector& nums) 4 | { 5 | unordered_map mp; 6 | for(int i=0;i0) 9 | mp[nums[i]]=1; 10 | } 11 | int result=1; 12 | for(int i=1;i<=nums.size()+1;i++) 13 | { 14 | if(!mp[i]) 15 | { 16 | result=i; 17 | break; 18 | } 19 | } 20 | return result; 21 | } 22 | }; -------------------------------------------------------------------------------- /132.palindrome-partitioning-ii/palindrome-partitioning-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCut(string s) { 4 | int n = s.size(); 5 | vector cut(n+1, 0); 6 | for (int i = 0; i <= n; i++) cut[i] = i-1; 7 | for (int i = 0; i < n; i++) 8 | { 9 | for (int j = 0; i-j >= 0 && i+j < n && s[i-j]==s[i+j] ; j++) cut[i+j+1] = min(cut[i+j+1],1+cut[i-j]); 10 | for (int j = 1; i-j+1 >= 0 && i+j < n && s[i-j+1] == s[i+j]; j++) cut[i+j+1] = min(cut[i+j+1],1+cut[i-j+1]); 11 | } 12 | return cut[n]; 13 | } 14 | }; -------------------------------------------------------------------------------- /260.single-number-iii/single-number-iii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector singleNumber(vector& nums) { 4 | int r = 0, n = nums.size(), i = 0, last = 0; 5 | vector ret(2, 0); 6 | 7 | for (i = 0; i < n; ++i) 8 | r ^= nums[i]; 9 | 10 | last = r & (~(r - 1)); 11 | for (i = 0; i < n; ++i) 12 | { 13 | if ((last & nums[i]) != 0) 14 | ret[0] ^= nums[i]; 15 | else 16 | ret[1] ^= nums[i]; 17 | } 18 | 19 | return ret; 20 | } 21 | }; -------------------------------------------------------------------------------- /287.find-the-duplicate-number/find-the-duplicate-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | if (nums.size() > 1) 5 | { 6 | int slow = nums[0]; 7 | int fast = nums[nums[0]]; 8 | while (slow != fast) 9 | { 10 | slow = nums[slow]; 11 | fast = nums[nums[fast]]; 12 | } 13 | 14 | fast = 0; 15 | while (fast != slow) 16 | { 17 | fast = nums[fast]; 18 | slow = nums[slow]; 19 | } 20 | return slow; 21 | } 22 | return -1; 23 | } 24 | }; -------------------------------------------------------------------------------- /111.minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int minDepth(TreeNode* root) { 13 | if(!root) return 0; 14 | int a=minDepth(root->left); 15 | int b=minDepth(root->right); 16 | if((a==0 && b!=0) || (a!=0 && b==0)) return max(a,b)+1; 17 | return min(a,b)+1; 18 | } 19 | }; -------------------------------------------------------------------------------- /115.distinct-subsequences/distinct-subsequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numDistinct(string s, string t) { 4 | vector temp(s.size()+1,0); 5 | vector> dp(t.size()+1,temp); 6 | for(int i=0;i<=s.size();i++) dp[0][i]=1; 7 | for(int i=1;i<=s.size();i++) 8 | { 9 | for(int j=1;j<=i && j<=t.size();j++) 10 | { 11 | dp[j][i]=dp[j][i-1]; 12 | if(s[i-1]==t[j-1]) dp[j][i]+=dp[j-1][i-1]; 13 | } 14 | } 15 | return dp[t.size()][s.size()]; 16 | } 17 | }; -------------------------------------------------------------------------------- /205.isomorphic-strings/question.md: -------------------------------------------------------------------------------- 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 | For example, 8 | Given "egg", "add", return true. 9 | 10 | Given "foo", "bar", return false. 11 | 12 | Given "paper", "title", return true. 13 | 14 | Note: 15 | You may assume both s and t have the same length. -------------------------------------------------------------------------------- /039.combination-sum/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. 3 | 4 | 5 | The same repeated number may be chosen from C unlimited number of times. 6 | 7 | 8 | Note: 9 | 10 | All numbers (including target) will be positive integers. 11 | The solution set must not contain duplicate combinations. 12 | 13 | 14 | 15 | 16 | For example, given candidate set [2, 3, 6, 7] and target 7, 17 | A solution set is: 18 | 19 | [ 20 | [7], 21 | [2, 2, 3] 22 | ] 23 | 24 | -------------------------------------------------------------------------------- /074.search-a-2d-matrix/search-a-2d-matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool searchMatrix(vector>& matrix, int target) { 4 | if(matrix.empty()) return false; 5 | int l=0,r=matrix.size()*matrix[0].size()-1; 6 | while(l<=r) 7 | { 8 | int mid=(l+r)>>1; 9 | int com=matrix[mid/matrix[0].size()][mid%matrix[0].size()]; 10 | if(com==target) return true; 11 | if(com dp(s.length(),0); 8 | for(int i=1;i> combine(int n, int k) { 4 | vector> result; 5 | vector temp(k,0); 6 | int now=0; 7 | while(now>=0) 8 | { 9 | temp[now]++; 10 | if(temp[now]>n) 11 | now--; 12 | else if(now==k-1) 13 | result.push_back(temp); 14 | else 15 | { 16 | temp[now+1]=temp[now]; 17 | now++; 18 | } 19 | } 20 | return result; 21 | } 22 | }; -------------------------------------------------------------------------------- /100.same-tree/same-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool isSameTree(TreeNode* p, TreeNode* q) { 13 | if(!p || !q) 14 | { 15 | if(!p && !q) return true; 16 | return false; 17 | } 18 | if(p->val!=q->val) return false; 19 | return isSameTree(p->left,q->left) && isSameTree(p->right,q->right); 20 | } 21 | }; -------------------------------------------------------------------------------- /034.search-for-a-range/search-for-a-range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | vector result(2,-1); 5 | // if(target<*nums.begin() || target>*(nums.end()-1)) 6 | // return result; 7 | int l=lower_bound(nums.begin(),nums.end(),target)-nums.begin(); 8 | int r=upper_bound(nums.begin(),nums.end(),target)-nums.begin(); 9 | if(l!=r) 10 | { 11 | result[0]=l; 12 | result[1]=r-1; 13 | } 14 | //cout< mp; 5 | mp['I']=1; 6 | mp['V']=5; 7 | mp['X']=10; 8 | mp['L']=50; 9 | mp['C']=100; 10 | mp['D']=500; 11 | mp['M']=1000; 12 | int result=0,pre=0; 13 | for(int i=0;ipre) 16 | result+=mp[s[i]]-2*pre; 17 | else 18 | result+=mp[s[i]]; 19 | pre=mp[s[i]]; 20 | } 21 | return result; 22 | } 23 | }; -------------------------------------------------------------------------------- /118.pascals-triangle/pascals-triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generate(int numRows) { 4 | vector> res; 5 | if(numRows < 1) return res; 6 | vector temp(1,1); 7 | res.push_back(temp); 8 | for(int i=1;i>& obstacleGrid) { 4 | if(obstacleGrid.size()==0) return 0; 5 | vector row(obstacleGrid[0].size()+1,0); 6 | vector> dp(obstacleGrid.size()+1,row); 7 | dp[0][1]=1; 8 | for(int i=1;i<=obstacleGrid.size();i++) 9 | for(int j=1;j<=obstacleGrid[0].size();j++) 10 | if(obstacleGrid[i-1][j-1]==0) 11 | dp[i][j]=dp[i-1][j]+dp[i][j-1]; 12 | return dp[obstacleGrid.size()][obstacleGrid[0].size()]; 13 | } 14 | }; -------------------------------------------------------------------------------- /121.best-time-to-buy-and-sell-stock/question.md: -------------------------------------------------------------------------------- 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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 4 | 5 | Example 1: 6 | 7 | Input: [7, 1, 5, 3, 6, 4] 8 | Output: 5 9 | 10 | max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 11 | 12 | 13 | 14 | Example 2: 15 | 16 | Input: [7, 6, 4, 3, 1] 17 | Output: 0 18 | 19 | In this case, no transaction is done, i.e. max profit = 0. 20 | 21 | -------------------------------------------------------------------------------- /139.word-break/word-break.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool wordBreak(string s, unordered_set& wordDict) { 4 | vector dp(s.size()+1, false); 5 | dp[0] = true; 6 | for (int i = 1; i<= s.size(); i++) 7 | { 8 | for(int j = 0; j < i; j++) 9 | { 10 | if(!dp[j]) continue; 11 | if(wordDict.find(s.substr(j, i-j)) != wordDict.end()) 12 | { 13 | dp[i] = true; 14 | break; 15 | } 16 | } 17 | } 18 | return dp[s.size()]; 19 | } 20 | }; -------------------------------------------------------------------------------- /214.shortest-palindrome/shortest-palindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string shortestPalindrome(string s) { 4 | string t = s; 5 | reverse(t.begin(), t.end()); 6 | t = s + '#' + t; 7 | vector next(2 * s.size() + 1, 0); 8 | for(int i = 1; i < t.size(); i++) 9 | { 10 | int pre = next[i - 1]; 11 | while(t[pre] != t[i] && pre != 0) pre = next[pre - 1]; 12 | if(t[pre] == t[i]) pre++; 13 | next[i] = pre; 14 | } 15 | return t.substr(s.size() + 1, s.size() - next[t.size() - 1]) + t.substr(0, s.size()); 16 | } 17 | }; -------------------------------------------------------------------------------- /073.set-matrix-zeroes/set-matrix-zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void setZeroes(vector>& matrix) { 4 | vector x; 5 | for(int i=0;i NULL 22 | / \ 23 | 2 -> 3 -> NULL 24 | / \ \ 25 | 4-> 5 -> 7 -> NULL 26 | 27 | -------------------------------------------------------------------------------- /209.minimum-size-subarray-sum/question.md: -------------------------------------------------------------------------------- 1 | 2 | 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. 3 | 4 | 5 | For example, given the array [2,3,1,2,4,3] and s = 7, 6 | the subarray [4,3] has the minimal length under the problem constraint. 7 | 8 | 9 | click to show more practice. 10 | 11 | More practice: 12 | 13 | If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). 14 | 15 | 16 | Credits:Special thanks to @Freezen for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /283.move-zeroes/move-zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void moveZeroes(vector& nums) { 4 | int p1 = 0, p2 = 0; 5 | while(p1 < nums.size()) 6 | { 7 | if(!nums[p1]) 8 | { 9 | p2 = max(p1, p2); 10 | while(p2 < nums.size()) 11 | { 12 | if(nums[p2]) 13 | { 14 | swap(nums[p1], nums[p2]); 15 | break; 16 | } 17 | p2++; 18 | } 19 | } 20 | p1++; 21 | } 22 | } 23 | }; -------------------------------------------------------------------------------- /299.bulls-and-cows/bulls-and-cows.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string getHint(string secret, string guess) { 4 | int A = 0, B = 0; 5 | unordered_map mp, mp2; 6 | for(int i = 0; i < secret.size(); i++) 7 | { 8 | if(secret[i] == guess[i]) A++; 9 | else 10 | { 11 | mp[secret[i]]++; 12 | mp2[guess[i]]++; 13 | } 14 | } 15 | for(auto k : mp) 16 | { 17 | B += min(k.second, mp2[k.first]); 18 | } 19 | 20 | return to_string(A) + "A" + to_string(B) + "B"; 21 | } 22 | }; -------------------------------------------------------------------------------- /045.jump-game-ii/jump-game-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int jump(vector& nums) { 4 | int st=0,result=0; 5 | while(st= nums.size()-1) return result+1; 8 | int maxx=0,pos=0; 9 | for(int i=1;st+i<=nums.size() && i<=nums[st];i++) 10 | { 11 | if(i+nums[st+i]>=maxx) 12 | { 13 | maxx=i+nums[st+i]; 14 | pos=i; 15 | } 16 | } 17 | st+=pos; 18 | result++; 19 | } 20 | return result; 21 | } 22 | }; -------------------------------------------------------------------------------- /141.linked-list-cycle/linked-list-cycle.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | bool hasCycle(ListNode *head) { 12 | if(!head) return false; 13 | ListNode* p = head; 14 | ListNode* q = head; 15 | while(p && q->next) 16 | { 17 | if(!q->next->next) break; 18 | q = q->next->next; 19 | p = p->next; 20 | if(p == q) return true; 21 | } 22 | return false; 23 | } 24 | }; -------------------------------------------------------------------------------- /206.reverse-linked-list/reverse-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* reverseList(ListNode* head) { 12 | if(!head) return NULL; 13 | ListNode* p = head; 14 | ListNode* q = p->next; 15 | p->next = NULL; 16 | while(q) 17 | { 18 | ListNode* r = q->next; 19 | q->next = p; 20 | p = q; 21 | q = r; 22 | } 23 | return p; 24 | } 25 | }; -------------------------------------------------------------------------------- /235.lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 | if(!root) return NULL; 14 | while((root->val - p->val) * (root->val - q->val) > 0) 15 | root = root->val > p->val ? root->left : root->right; 16 | return root; 17 | } 18 | }; -------------------------------------------------------------------------------- /260.single-number-iii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. 3 | 4 | 5 | For example: 6 | 7 | 8 | Given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. 9 | 10 | 11 | Note: 12 | 13 | The order of the result is not important. So in the above example, [5, 3] is also correct. 14 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? 15 | 16 | 17 | 18 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /020.valid-parentheses/valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | stack st; 5 | for(int i=0;i twoSum(vector& numbers, int target) { 4 | int l = 0, r = numbers.size()-1; 5 | vector res; 6 | while(l <= r) 7 | { 8 | if(numbers[l] + numbers[r] == target) 9 | { 10 | res.push_back(l+1); 11 | res.push_back(r+1); 12 | break; 13 | } 14 | else if(numbers[l] + numbers[r] > target) 15 | r--; 16 | else 17 | l++; 18 | } 19 | return res; 20 | } 21 | }; -------------------------------------------------------------------------------- /198.house-robber/question.md: -------------------------------------------------------------------------------- 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 | Credits:Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases. -------------------------------------------------------------------------------- /038.count-and-say/count-and-say.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string countAndSay(int n) { 4 | string result="1"; 5 | for(int i=1;i> generateMatrix(int n) { 4 | vector row(n,0); 5 | vector> result(n,row); 6 | int rows=n,cols=n,cnt=0; 7 | for(int x=0,y=0;x=y ;i--) result[rows-1][i]=++cnt; 12 | for(int i=rows-2;i>x ;i--) result[i][y]=++cnt; 13 | rows--; 14 | cols--; 15 | } 16 | return result; 17 | } 18 | }; -------------------------------------------------------------------------------- /162.find-peak-element/question.md: -------------------------------------------------------------------------------- 1 | A peak element is an element that is greater than its neighbors. 2 | 3 | Given an input array where num[i] ≠ num[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 num[-1] = num[n] = -∞. 8 | 9 | For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. 10 | 11 | click to show spoilers. 12 | 13 | Note: 14 | Your solution should be in logarithmic complexity. 15 | 16 | 17 | Credits:Special thanks to @ts for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /014.longest-common-prefix/longest-common-prefix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestCommonPrefix(vector& strs) { 4 | string result; 5 | int limit=INT_MAX; 6 | for(int i=0;i Returns -3. 26 | minStack.pop(); 27 | minStack.top(); --> Returns 0. 28 | minStack.getMin(); --> Returns -2. 29 | 30 | -------------------------------------------------------------------------------- /202.happy-number/question.md: -------------------------------------------------------------------------------- 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: 19 is a happy number 6 | 7 | 8 | 12 + 92 = 82 9 | 82 + 22 = 68 10 | 62 + 82 = 100 11 | 12 + 02 + 02 = 1 12 | 13 | 14 | Credits:Special thanks to @mithmatt and @ts for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /287.find-the-duplicate-number/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. 3 | 4 | 5 | 6 | Note: 7 | 8 | You must not modify the array (assume the array is read only). 9 | You must use only constant, O(1) extra space. 10 | Your runtime complexity should be less than O(n2). 11 | There is only one duplicate number in the array, but it could be repeated more than once. 12 | 13 | 14 | 15 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /209.minimum-size-subarray-sum/minimum-size-subarray-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSubArrayLen(int s, vector& nums) { 4 | int res = 0, l = 0, r = 0; 5 | int ans = INT_MAX; 6 | while(r <= nums.size()) 7 | {//cout<= s) 9 | { 10 | ans = min(ans, r - l); 11 | res -= nums[l++]; 12 | } 13 | else 14 | { 15 | if(r == nums.size()) break; 16 | res += nums[r++]; 17 | } 18 | 19 | } 20 | return ans == INT_MAX ? 0 : ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /025.reverse-nodes-in-k-group/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 3 | 4 | 5 | 6 | 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. 7 | 8 | You may not alter the values in the nodes, only nodes itself may be changed. 9 | 10 | Only constant memory is allowed. 11 | 12 | 13 | For example, 14 | Given this linked list: 1->2->3->4->5 15 | 16 | 17 | 18 | For k = 2, you should return: 2->1->4->3->5 19 | 20 | 21 | 22 | For k = 3, you should return: 3->2->1->4->5 23 | -------------------------------------------------------------------------------- /003.longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) 4 | { 5 | int len=s.length(); 6 | int st=0,en=0,result=0; 7 | int vis[1005]; 8 | memset(vis,0,sizeof(vis)); 9 | while(enINT_MAX) 23 | return 0; 24 | if(flag) 25 | ans=-ans; 26 | return (int)ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /054.spiral-matrix/spiral-matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector spiralOrder(vector>& matrix) { 4 | vector result; 5 | int m=matrix.size(); 6 | if(m==0) return result; 7 | int n=matrix[0].size(),x=0,y=0; 8 | for(;x=y && x!=m-1;i--) result.push_back(matrix[m-1][i]); 13 | for(int i=m-2;i>x && y!=n-1;i--) result.push_back(matrix[i][y]); 14 | } 15 | return result; 16 | } 17 | }; -------------------------------------------------------------------------------- /120.triangle/triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumTotal(vector>& triangle) { 4 | vector> dp=triangle; 5 | for(int i=1;i temp; 10 | if(j!=0) temp.push_back(dp[i-1][j-1]); 11 | if(j!=dp[i].size()-1) temp.push_back(dp[i-1][j]); 12 | sort(temp.begin(),temp.end()); 13 | dp[i][j]=temp[0]+dp[i][j]; 14 | } 15 | } 16 | sort(dp[dp.size()-1].begin(),dp[dp.size()-1].end()); 17 | return dp[dp.size()-1][0]; 18 | } 19 | }; -------------------------------------------------------------------------------- /203.remove-linked-list-elements/remove-linked-list-elements.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* removeElements(ListNode* head, int val) { 12 | ListNode* p = new ListNode(-1); 13 | p->next = head; 14 | ListNode* q = p; 15 | while(p->next) 16 | { 17 | if(p->next->val == val) 18 | p->next = p->next->next; 19 | else 20 | p = p->next; 21 | } 22 | return q->next; 23 | } 24 | }; -------------------------------------------------------------------------------- /001.two-sum/two-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector twoSum(vector& nums, int target) 5 | { 6 | vector result; 7 | unordered_map mp; 8 | for(int i=0;i(i+1) ) 15 | { 16 | //cout<& nums) 4 | { 5 | int result=nums.size(),pre=1; 6 | for(int i=1,j=1;i2) 12 | result--; 13 | else 14 | nums[j++]=nums[i]; 15 | } 16 | else 17 | { 18 | pre=1; 19 | nums[j++]=nums[i]; 20 | } 21 | } 22 | return result; 23 | } 24 | }; -------------------------------------------------------------------------------- /213.house-robber-ii/question.md: -------------------------------------------------------------------------------- 1 | Note: This is an extension of House Robber. 2 | 3 | After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street. 4 | 5 | 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. 6 | 7 | Credits:Special thanks to @Freezen for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /083.remove-duplicates-from-sorted-list/remove-duplicates-from-sorted-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* deleteDuplicates(ListNode* head) { 12 | ListNode* p=head; 13 | if(!p) return head; 14 | ListNode* pre=p; 15 | while(p->next!=NULL) 16 | { 17 | p=p->next; 18 | if(p->val==pre->val) 19 | pre->next=p->next; 20 | else 21 | pre=p; 22 | } 23 | return head; 24 | } 25 | }; -------------------------------------------------------------------------------- /089.gray-code/question.md: -------------------------------------------------------------------------------- 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 | For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 6 | 7 | 00 - 0 8 | 01 - 1 9 | 11 - 3 10 | 10 - 2 11 | 12 | 13 | Note: 14 | For a given n, a gray code sequence is not uniquely defined. 15 | 16 | For example, [0,2,3,1] is also a valid gray code sequence according to the above definition. 17 | 18 | For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that. -------------------------------------------------------------------------------- /110.balanced-binary-tree/balanced-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int dfs(TreeNode* root,bool& res) 13 | { 14 | if(!root) return 0; 15 | int a=dfs(root->left,res)+1; 16 | int b=dfs(root->right,res)+1; 17 | if(abs(a-b)>1) res=false; 18 | return max(a,b); 19 | } 20 | bool isBalanced(TreeNode* root) { 21 | bool res=true; 22 | dfs(root,res); 23 | return res; 24 | } 25 | }; -------------------------------------------------------------------------------- /140.word-break-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words. 3 | 4 | 5 | 6 | Return all such possible sentences. 7 | 8 | 9 | 10 | For example, given 11 | s = "catsanddog", 12 | dict = ["cat", "cats", "and", "sand", "dog"]. 13 | 14 | 15 | 16 | A solution is ["cats and dog", "cat sand dog"]. 17 | 18 | 19 | 20 | UPDATE (2017/1/4): 21 | The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes. 22 | -------------------------------------------------------------------------------- /144.binary-tree-preorder-traversal/binary-tree-preorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | void dfs(TreeNode* root, vector &res) 13 | { 14 | res.push_back(root->val); 15 | if(root->left) dfs(root->left, res); 16 | if(root->right) dfs(root->right, res); 17 | } 18 | vector preorderTraversal(TreeNode* root) { 19 | vector res; 20 | if(root) dfs(root, res); 21 | return res; 22 | } 23 | }; -------------------------------------------------------------------------------- /165.compare-version-numbers/question.md: -------------------------------------------------------------------------------- 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 | Here is an example of version numbers ordering: 9 | 0.1 < 1.1 < 1.2 < 13.37 10 | 11 | Credits:Special thanks to @ts for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /060.permutation-sequence/permutation-sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string getPermutation(int n, int k) { 4 | int mp[10]; 5 | mp[0]=mp[1]=1; 6 | vector v(1,1); 7 | for(int i=2;i<10;i++) 8 | { 9 | mp[i]=mp[i-1]*i; 10 | v.push_back(i); 11 | } 12 | string result; 13 | while(n--) 14 | { 15 | vector::iterator it=v.begin(); 16 | while(k>mp[n]) 17 | { 18 | k-=mp[n]; 19 | it++; 20 | } 21 | result+=('0'+*it); 22 | v.erase(it); 23 | 24 | } 25 | return result; 26 | } 27 | }; -------------------------------------------------------------------------------- /129.sum-root-to-leaf-numbers/sum-root-to-leaf-numbers.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | void dfs(TreeNode* root,int &res,int now) 13 | { 14 | if(!root) return ; 15 | if(!root->left && !root->right) res+=now*10+root->val; 16 | dfs(root->left,res,now*10+root->val); 17 | dfs(root->right,res,now*10+root->val); 18 | } 19 | int sumNumbers(TreeNode* root) { 20 | int res=0; 21 | dfs(root,res,0); 22 | return res; 23 | } 24 | }; -------------------------------------------------------------------------------- /205.isomorphic-strings/isomorphic-strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isIsomorphic(string s, string t) { 4 | unordered_map mp, mp2; 5 | for(int i = 0; i < s.size(); i++) 6 | { 7 | if(mp.find(s[i]) != mp.end()) 8 | { 9 | if(mp[s[i]] != t[i]) return false; 10 | 11 | } 12 | else 13 | mp[s[i]] = t[i]; 14 | if(mp2.find(t[i]) != mp2.end()) 15 | { 16 | if(mp2[t[i]] != s[i]) return false; 17 | 18 | } 19 | else 20 | mp2[t[i]] = s[i]; 21 | } 22 | return true; 23 | } 24 | }; -------------------------------------------------------------------------------- /012.integer-to-roman/integer-to-roman.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string intToRoman(int num) 4 | { 5 | string table[4][11]={ 6 | {"", "I","II","III","IV","V","VI","VII","VIII","IX"}, 7 | {"", "X", "XX","XXX","XL","L","LX","LXX","LXXX","XC"}, 8 | {"", "C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}, 9 | {"", "M", "MM","MMM"} 10 | }; 11 | string result = ""; 12 | int now=0; 13 | while (num > 0) 14 | { 15 | result=table[now][num%10]+result; 16 | num/=10; 17 | now++; 18 | } 19 | //reverse(result.begin(),result.end()); 20 | return result; 21 | } 22 | }; -------------------------------------------------------------------------------- /087.scramble-string/scramble-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isScramble(string s1, string s2) { 4 | if(s1==s2) return true; 5 | int cnt[256]={0}; 6 | for(int i=0;i &res) 13 | { 14 | 15 | if(root->left) dfs(root->left, res); 16 | if(root->right) dfs(root->right, res); 17 | res.push_back(root->val); 18 | } 19 | vector postorderTraversal(TreeNode* root) { 20 | vector res; 21 | if(root) dfs(root, res); 22 | return res; 23 | } 24 | }; -------------------------------------------------------------------------------- /042.trapping-rain-water/trapping-rain-water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trap(vector& height) { 4 | int l=0,r=height.size()-1,result=0,ml=0,mr=0; 5 | while(lval<=minn || root->val>=maxx) return false; 16 | if(dfs(root->left,minn,root->val) && dfs(root->right,root->val,maxx)) return true; 17 | return false; 18 | } 19 | bool isValidBST(TreeNode* root) { 20 | return dfs(root,(long long)INT_MIN-1,(long long)INT_MAX+1); 21 | } 22 | }; -------------------------------------------------------------------------------- /151.reverse-words-in-a-string/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an input string, reverse the string word by word. 3 | 4 | 5 | 6 | For example, 7 | Given s = "the sky is blue", 8 | return "blue is sky the". 9 | 10 | 11 | 12 | Update (2015-02-12): 13 | For C programmers: Try to solve it in-place in O(1) space. 14 | 15 | 16 | click to show clarification. 17 | 18 | Clarification: 19 | 20 | 21 | 22 | What constitutes a word? 23 | A sequence of non-space characters constitutes a word. 24 | Could the input string contain leading or trailing spaces? 25 | Yes. However, your reversed string should not contain leading or trailing spaces. 26 | How about multiple spaces between two words? 27 | Reduce them to a single space in the reversed string. 28 | 29 | 30 | -------------------------------------------------------------------------------- /108.convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* dfs(vector& nums,int l,int r) 13 | { 14 | if(l>r) return NULL; 15 | int mid=(l+r)>>1; 16 | TreeNode* p=new TreeNode(nums[mid]); 17 | p->left=dfs(nums,l,mid-1); 18 | p->right=dfs(nums,mid+1,r); 19 | return p; 20 | } 21 | TreeNode* sortedArrayToBST(vector& nums) { 22 | return dfs(nums,0,nums.size()-1); 23 | } 24 | }; -------------------------------------------------------------------------------- /112.path-sum/path-sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool dfs(TreeNode* root,int now,int sum) 13 | { 14 | now+=root->val; 15 | if(!root->left && !root->right) return now == sum; 16 | bool l=false,r=false; 17 | if(root->left) l=dfs(root->left,now,sum); 18 | if(root->right) r=dfs(root->right,now,sum); 19 | return l || r; 20 | } 21 | bool hasPathSum(TreeNode* root, int sum) { 22 | if(!root) return false; 23 | return dfs(root,0,sum); 24 | } 25 | }; -------------------------------------------------------------------------------- /116.populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree with next pointer. 3 | * struct TreeLinkNode { 4 | * int val; 5 | * TreeLinkNode *left, *right, *next; 6 | * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | void connect(TreeLinkNode *root) { 12 | if(!root) return ; 13 | if(root->left) 14 | { 15 | root->left->next=root->right; 16 | connect(root->left); 17 | } 18 | if(root->right) 19 | { 20 | if(root->next) root->right->next=root->next->left; 21 | connect(root->right); 22 | } 23 | } 24 | }; -------------------------------------------------------------------------------- /228.summary-ranges/summary-ranges.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector summaryRanges(vector& nums) { 4 | vector res; 5 | if(nums.empty()) return res; 6 | int s = nums[0], e = nums[0]; 7 | for(int i = 1; i < nums.size(); i++) 8 | { 9 | if(nums[i] == nums[i - 1] + 1) e = nums[i]; 10 | else 11 | { 12 | if(s == e) res.push_back(to_string(s)); 13 | else res.push_back(to_string(s) + "->" + to_string(e)); 14 | s = e = nums[i]; 15 | } 16 | } 17 | if(s == e) res.push_back(to_string(s)); 18 | else res.push_back(to_string(s) + "->" + to_string(e)); 19 | return res; 20 | } 21 | }; -------------------------------------------------------------------------------- /046.permutations/permutations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(vector> &result,vector nums,vector now) 4 | { 5 | if(nums.size() == 0) 6 | { 7 | result.push_back(now); 8 | return ; 9 | } 10 | for(int i=0;i temp=nums; 14 | temp.erase(temp.begin()+i); 15 | dfs(result,temp,now); 16 | now.pop_back(); 17 | } 18 | } 19 | vector> permute(vector& nums) 20 | { 21 | vector> result; 22 | vector now; 23 | dfs(result,nums,now); 24 | return result; 25 | } 26 | }; -------------------------------------------------------------------------------- /101.symmetric-tree/symmetric-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool dfs(TreeNode* t1,TreeNode* t2) 13 | { 14 | if(!t1 || !t2) 15 | { 16 | if(!t1 && !t2) return true; 17 | return false; 18 | } 19 | if(t1->val!=t2->val) return false; 20 | return dfs(t1->left,t2->right) && dfs(t1->right,t2->left); 21 | } 22 | bool isSymmetric(TreeNode* root) 23 | { 24 | if(!root) return true; 25 | return dfs(root->left,root->right); 26 | } 27 | }; -------------------------------------------------------------------------------- /278.first-bad-version/question.md: -------------------------------------------------------------------------------- 1 | 2 | You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 3 | 4 | 5 | 6 | Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. 7 | 8 | 9 | 10 | You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. 11 | 12 | 13 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /290.word-pattern/question.md: -------------------------------------------------------------------------------- 1 | Given a pattern and a string str, find if str follows the same pattern. 2 | Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. 3 | 4 | Examples: 5 | 6 | pattern = "abba", str = "dog cat cat dog" should return true. 7 | pattern = "abba", str = "dog cat cat fish" should return false. 8 | pattern = "aaaa", str = "dog cat cat dog" should return false. 9 | pattern = "abba", str = "dog dog dog dog" should return false. 10 | 11 | 12 | 13 | 14 | Notes: 15 | You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space. 16 | 17 | 18 | Credits:Special thanks to @minglotus6 for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /292.nim-game/question.md: -------------------------------------------------------------------------------- 1 | 2 | You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 3 | 4 | 5 | 6 | Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. 7 | 8 | 9 | 10 | For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 11 | 12 | 13 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /124.binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int dfs(TreeNode* root,int &res) 13 | { 14 | if(!root) return 0; 15 | int left=dfs(root->left,res); 16 | int right=dfs(root->right,res); 17 | res=max(res,left+right+root->val); 18 | return root->val+max(left,right)>0?root->val+max(left,right):0; 19 | } 20 | int maxPathSum(TreeNode* root) { 21 | int res=INT_MIN; 22 | dfs(root,res); 23 | return res; 24 | } 25 | }; -------------------------------------------------------------------------------- /199.binary-tree-right-side-view/binary-tree-right-side-view.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | void dfs(vector &res, TreeNode* root, int dep) 13 | { 14 | if(!root) return ; 15 | if(dep == res.size()) res.push_back(root->val); 16 | if(root->right) dfs(res, root->right, dep + 1); 17 | if(root->left) dfs(res, root->left, dep + 1); 18 | } 19 | vector rightSideView(TreeNode* root) { 20 | vector res, flag; 21 | dfs(res, root, 0); 22 | return res; 23 | } 24 | }; -------------------------------------------------------------------------------- /213.house-robber-ii/house-robber-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | int a1 = 0; 5 | int b1 = 0; 6 | int a2 = 0; 7 | int b2 = 0; 8 | if(nums.size() == 1) return nums[0]; 9 | for(int i = 0; i < nums.size(); i++) 10 | { 11 | if(i != nums.size() - 1) 12 | { 13 | if(i & 1) a1 = max(a1 + nums[i], b1); 14 | else b1 = max(b1 + nums[i], a1); 15 | } 16 | if(i != 0) 17 | { 18 | if(i & 1) a2 = max(a2 + nums[i], b2); 19 | else b2 = max(b2 + nums[i], a2); 20 | } 21 | } 22 | return max(max(a1, b1), max(a2, b2)); 23 | 24 | } 25 | }; -------------------------------------------------------------------------------- /236.lowest-common-ancestor-of-a-binary-tree/lowest-common-ancestor-of-a-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 | if(!root) return NULL; 14 | if(p == root || q == root) return root; 15 | TreeNode* l = lowestCommonAncestor(root->left, p, q); 16 | TreeNode* r = lowestCommonAncestor(root->right, p, q); 17 | if(!l) return r; 18 | else if(!r) return l; 19 | else return root; 20 | 21 | } 22 | }; -------------------------------------------------------------------------------- /097.interleaving-string/interleaving-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool dfs(string s1,string s2,string s3,map,int>& mp) 4 | { 5 | if(s3.empty()) return true; 6 | pair temp=make_pair(s1.size(),s2.size()); 7 | if(mp[temp]) return false; 8 | mp[temp]=1; 9 | if(!s1.empty() && s1[0]==s3[0] && dfs(s1.substr(1),s2,s3.substr(1),mp)) return true; 10 | if(!s2.empty() && s2[0]==s3[0] && dfs(s1,s2.substr(1),s3.substr(1),mp)) return true; 11 | 12 | return false; 13 | } 14 | bool isInterleave(string s1, string s2, string s3) { 15 | if(s1.size()+s2.size()!=s3.size()) return false; 16 | map,int> mp; 17 | return dfs(s1,s2,s3,mp); 18 | } 19 | }; -------------------------------------------------------------------------------- /188.best-time-to-buy-and-sell-stock-iv/best-time-to-buy-and-sell-stock-iv.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(int k, vector& prices) { 4 | if(k > prices.size()) 5 | { 6 | int res = 0; 7 | for(int i = 1 ; i < prices.size(); i++) if(prices[i] > prices[i-1]) res += prices[i]-prices[i-1]; 8 | return res; 9 | } 10 | vector sell(k+1, 0), buy(k+1, INT_MIN); 11 | for(int i = 0; i < prices.size() ; i++) 12 | { 13 | for(int j = k; j > 0 ; j--) 14 | { 15 | sell[j] = max(sell[j], buy[j] + prices[i]); 16 | buy[j] = max(buy[j], sell[j-1] - prices[i]); 17 | } 18 | } 19 | return sell[k]; 20 | } 21 | }; -------------------------------------------------------------------------------- /229.majority-element-ii/majority-element-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector majorityElement(vector& nums) { 4 | int a, b, c1 = 0, c2 = 0; 5 | for(auto now : nums) 6 | { 7 | if(now == a) c1++; 8 | else if(now == b) c2++; 9 | else if(c1 == 0) a = now, c1 = 1; 10 | else if(c2 == 0) b = now, c2 = 1; 11 | else c1--, c2--; 12 | } 13 | c1 = c2 = 0; 14 | for(auto now : nums) 15 | { 16 | if(now == a) c1++; 17 | else if(now == b) c2++; 18 | } 19 | vector res; 20 | if(c1 > nums.size() / 3) res.push_back(a); 21 | if(c2 > nums.size() / 3) res.push_back(b); 22 | return res; 23 | } 24 | }; -------------------------------------------------------------------------------- /230.kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | void dfs(TreeNode* root, int &k, int &res) 13 | { 14 | if(!root) return ; 15 | dfs(root->left, k, res); 16 | k--; 17 | if(!k) 18 | { 19 | res = root->val; 20 | return ; 21 | } 22 | dfs(root->right, k, res); 23 | } 24 | int kthSmallest(TreeNode* root, int k) { 25 | int res; 26 | dfs(root, k, res); 27 | return res; 28 | } 29 | }; -------------------------------------------------------------------------------- /295.find-median-from-data-stream/question.md: -------------------------------------------------------------------------------- 1 | Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. 2 | Examples: 3 | [2,3,4] , the median is 3 4 | [2,3], the median is (2 + 3) / 2 = 2.5 5 | 6 | 7 | Design a data structure that supports the following two operations: 8 | 9 | 10 | void addNum(int num) - Add a integer number from the data stream to the data structure. 11 | double findMedian() - Return the median of all elements so far. 12 | 13 | 14 | 15 | For example: 16 | 17 | addNum(1) 18 | addNum(2) 19 | findMedian() -> 1.5 20 | addNum(3) 21 | findMedian() -> 2 22 | 23 | 24 | Credits:Special thanks to @Louis1992 for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /049.anagrams/anagrams.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> groupAnagrams(vector& strs) { 4 | vector> result; 5 | unordered_map mp; 6 | int cnt=0; 7 | for(int i=0;i s; 14 | s.push_back(strs[i]); 15 | result.push_back(s); 16 | mp[temp]=cnt++; 17 | } 18 | else 19 | { 20 | result[mp[temp]].push_back(strs[i]); 21 | } 22 | } 23 | return result; 24 | } 25 | }; -------------------------------------------------------------------------------- /084.largest-rectangle-in-histogram/largest-rectangle-in-histogram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestRectangleArea(vector& heights) { 4 | if(heights.size()==0) return 0; 5 | vector x(1,-2),y(1,1); 6 | heights.push_back(-1); 7 | int result=0; 8 | for(int i=0;i=heights[i]) 12 | { 13 | result=max(result,x[x.size()-1]*(y[x.size()-1]+temp-1)); 14 | temp+=y[x.size()-1]; 15 | x.pop_back(); 16 | y.pop_back(); 17 | } 18 | x.push_back(heights[i]); 19 | y.push_back(temp); 20 | } 21 | return result; 22 | } 23 | }; -------------------------------------------------------------------------------- /216.combination-sum-iii/combination-sum-iii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(int k, int now, int n, int sum, vector> &res, vector path) 4 | { 5 | if(sum > n) return ; 6 | if(k == 0) 7 | { 8 | if(sum == n) res.push_back(path); 9 | return ; 10 | } 11 | if(now == 0) return ; 12 | for(int i = now; i > 0; i--) 13 | { 14 | vector tmp = path; 15 | tmp.push_back(i); 16 | dfs(k-1, i - 1, n, sum + i, res, tmp); 17 | } 18 | } 19 | vector> combinationSum3(int k, int n) { 20 | vector> res; 21 | vector path; 22 | dfs(k, 9, n, 0, res, path); 23 | return res; 24 | } 25 | }; -------------------------------------------------------------------------------- /075.sort-colors/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. 3 | 4 | 5 | 6 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 7 | 8 | 9 | 10 | Note: 11 | You are not suppose to use the library's sort function for this problem. 12 | 13 | 14 | click to show follow up. 15 | 16 | 17 | Follow up: 18 | A rather straight forward solution is a two-pass algorithm using counting sort. 19 | 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. 20 | Could you come up with an one-pass algorithm using only constant space? 21 | 22 | -------------------------------------------------------------------------------- /090.subsets-ii/subsets-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(vector>& res,vector nums,vector now) 4 | { 5 | if(nums.size()==0) 6 | { 7 | res.push_back(now); 8 | return ; 9 | } 10 | vector temp=now; 11 | int back=nums[nums.size()-1]; 12 | nums.pop_back(); 13 | now.push_back(back); 14 | dfs(res,nums,now); 15 | while(nums.size()>0 && nums[nums.size()-1]==back) nums.pop_back(); 16 | dfs(res,nums,temp); 17 | } 18 | vector> subsetsWithDup(vector& nums) { 19 | vector> res; 20 | vector now; 21 | sort(nums.begin(),nums.end()); 22 | dfs(res,nums,now); 23 | return res; 24 | } 25 | }; -------------------------------------------------------------------------------- /072.edit-distance/edit-distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDistance(string word1, string word2) { 4 | vector temp(word2.size()+1,0); 5 | vector> dp(word1.size()+1,temp); 6 | for(int i=0;i<=word1.size();i++) dp[i][0]=i; 7 | for(int i=0;i<=word2.size();i++) dp[0][i]=i; 8 | for(int i=1;i<=word1.size();i++) 9 | { 10 | for(int j=1;j<=word2.size();j++) 11 | { 12 | if(word1[i-1]==word2[j-1]) 13 | dp[i][j]=dp[i-1][j-1]; 14 | else 15 | { 16 | dp[i][j]=min(min(dp[i-1][j],dp[i][j-1]),dp[i-1][j-1])+1; 17 | } 18 | } 19 | } 20 | return dp[word1.size()][word2.size()]; 21 | } 22 | }; -------------------------------------------------------------------------------- /236.lowest-common-ancestor-of-a-binary-tree/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 3 | 4 | 5 | 6 | According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” 7 | 8 | 9 | 10 | _______3______ 11 | / \ 12 | ___5__ ___1__ 13 | / \ / \ 14 | 6 _2 0 8 15 | / \ 16 | 7 4 17 | 18 | 19 | 20 | For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. -------------------------------------------------------------------------------- /187.repeated-dna-sequences/repeated-dna-sequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findRepeatedDnaSequences(string s) { 4 | vector res; 5 | if(s.size() < 10) return res; 6 | unordered_map mp; 7 | unordered_map id; 8 | id['A'] = 0; 9 | id['C'] = 1; 10 | id['G'] = 2; 11 | id['T'] = 3; 12 | int temp = 0; 13 | for(int i = 0; i < s.size(); i++) 14 | { 15 | temp = (temp<<2| (id[s[i]] & 3)) & 0xfffff; 16 | if(i > 8) 17 | { 18 | if(mp[temp] == 1) res.push_back(s.substr(i - 9,10)); 19 | mp[temp]++; 20 | } 21 | } 22 | 23 | 24 | 25 | return res; 26 | } 27 | }; -------------------------------------------------------------------------------- /155.min-stack/min-stack.cpp: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | public: 3 | /** initialize your data structure here. */ 4 | stack s1,s2; 5 | MinStack() { 6 | 7 | } 8 | 9 | void push(int x) { 10 | s1.push(x); 11 | if(s2.empty() || x <= s2.top()) s2.push(x); 12 | } 13 | 14 | void pop() { 15 | if(s1.top() == s2.top()) s2.pop(); 16 | s1.pop(); 17 | } 18 | 19 | int top() { 20 | return s1.top(); 21 | } 22 | 23 | int getMin() { 24 | return s2.top(); 25 | } 26 | }; 27 | 28 | /** 29 | * Your MinStack object will be instantiated and called as such: 30 | * MinStack obj = new MinStack(); 31 | * obj.push(x); 32 | * obj.pop(); 33 | * int param_3 = obj.top(); 34 | * int param_4 = obj.getMin(); 35 | */ -------------------------------------------------------------------------------- /160.intersection-of-two-linked-lists/question.md: -------------------------------------------------------------------------------- 1 | Write a program to find the node at which the intersection of two singly linked lists begins. 2 | 3 | For example, the following two linked lists: 4 | 5 | A: a1 → a2 6 | ↘ 7 | c1 → c2 → c3 8 | ↗ 9 | B: b1 → b2 → b3 10 | 11 | begin to intersect at node c1. 12 | 13 | Notes: 14 | 15 | If the two linked lists have no intersection at all, return null. 16 | The linked lists must retain their original structure after the function returns. 17 | You may assume there are no cycles anywhere in the entire linked structure. 18 | Your code should preferably run in O(n) time and use only O(1) memory. 19 | 20 | 21 | 22 | Credits:Special thanks to @stellari for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /211.add-and-search-word-data-structure-design/question.md: -------------------------------------------------------------------------------- 1 | 2 | Design a data structure that supports the following two operations: 3 | 4 | 5 | void addWord(word) 6 | bool search(word) 7 | 8 | 9 | 10 | search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. 11 | 12 | 13 | For example: 14 | 15 | addWord("bad") 16 | addWord("dad") 17 | addWord("mad") 18 | search("pad") -> false 19 | search("bad") -> true 20 | search(".ad") -> true 21 | search("b..") -> true 22 | 23 | 24 | 25 | Note: 26 | You may assume that all words are consist of lowercase letters a-z. 27 | 28 | 29 | click to show hint. 30 | 31 | You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first. 32 | -------------------------------------------------------------------------------- /235.lowest-common-ancestor-of-a-binary-search-tree/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 3 | 4 | 5 | 6 | According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” 7 | 8 | 9 | 10 | _______6______ 11 | / \ 12 | ___2__ ___8__ 13 | / \ / \ 14 | 0 _4 7 9 15 | / \ 16 | 3 5 17 | 18 | 19 | 20 | For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. -------------------------------------------------------------------------------- /033.search-in-rotated-sorted-array/search-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) 4 | { 5 | int l=0,r=nums.size()-1; 6 | while(l<=r) 7 | { 8 | int mid=(r+l)/2; 9 | if(nums[mid]==target) 10 | return mid; 11 | if(nums[mid]>=nums[l]) 12 | { 13 | if(nums[l]<=target && nums[mid]>target) 14 | r=mid-1; 15 | else 16 | l=mid+1; 17 | } 18 | else 19 | { 20 | if(nums[r]>=target && nums[mid]next=head; 14 | ListNode* pre=res; 15 | for(int i=0;inext; 16 | ListNode* p=pre->next; 17 | ListNode* temp; 18 | for(int i=0;inext; 21 | p->next=temp->next; 22 | temp->next=pre->next; 23 | pre->next=temp; 24 | 25 | } 26 | 27 | return res->next; 28 | } 29 | }; --------------------------------------------------------------------------------