├── 050.powx-n ├── question.md └── powx-n.py ├── 147.insertion-sort-list └── question.md ├── 069.sqrtx ├── question.md └── sqrtx.py ├── 148.sort-list └── question.md ├── 161.one-edit-distance ├── question.md └── one-edit-distance.py ├── 014.longest-common-prefix └── question.md ├── 149.max-points-on-a-line └── question.md ├── 013.roman-to-integer ├── question.md └── roman-to-integer.py ├── 023.merge-k-sorted-lists └── question.md ├── 169.majority-element ├── majority-element.py └── question.md ├── 012.integer-to-roman └── question.md ├── 275.h-index-ii ├── question.md └── h-index-ii.py ├── 108.convert-sorted-array-to-binary-search-tree └── question.md ├── 109.convert-sorted-list-to-binary-search-tree └── question.md ├── 234.palindrome-linked-list └── question.md ├── 029.divide-two-integers └── question.md ├── 052.n-queens-ii └── question.md ├── 141.linked-list-cycle ├── question.md └── linked-list-cycle.py ├── 292.nim-game └── nim-game.py ├── 344.reverse-string ├── question.md └── reverse-string.py ├── 021.merge-two-sorted-lists └── question.md ├── 028.implement-strstr └── question.md ├── 067.add-binary └── question.md ├── 319.bulb-switcher └── bulb-switcher.py ├── 229.majority-element-ii └── question.md ├── 476.number-complement └── number-complement.py ├── 056.merge-intervals └── question.md ├── 061.rotate-list └── question.md ├── 231.power-of-two ├── power-of-two.py └── question.md ├── 266.palindrome-permutation └── question.md ├── 104.maximum-depth-of-binary-tree ├── question.md └── maximum-depth-of-binary-tree.py ├── 111.minimum-depth-of-binary-tree └── question.md ├── 204.count-primes └── question.md ├── 208.implement-trie-prefix-tree └── question.md ├── 206.reverse-linked-list └── question.md ├── 441.arranging-coins └── arranging-coins.py ├── 105.construct-binary-tree-from-preorder-and-inorder-traversal └── question.md ├── 151.reverse-words-in-a-string └── reverse-words-in-a-string.py ├── 342.power-of-four ├── power-of-four.py └── question.md ├── 434.number-of-segments-in-a-string ├── number-of-segments-in-a-string.py └── question.md ├── 100.same-tree ├── question.md └── same-tree.py ├── 106.construct-binary-tree-from-inorder-and-postorder-traversal └── question.md ├── 138.copy-list-with-random-pointer └── question.md ├── 258.add-digits ├── add-digits.py └── question.md ├── 268.missing-number ├── missing-number.py └── question.md ├── 285.inorder-successor-in-bst └── question.md ├── 219.contains-duplicate-ii └── question.md ├── 280.wiggle-sort └── question.md ├── 083.remove-duplicates-from-sorted-list └── question.md ├── 575.distribute-candies └── distribute-candies.py ├── 064.minimum-path-sum └── question.md ├── 136.single-number ├── question.md └── single-number.py ├── 217.contains-duplicate ├── question.md └── contains-duplicate.py ├── 561.array-partition-i └── array-partition-i.py ├── 205.isomorphic-strings └── isomorphic-strings.py ├── README.md ├── 070.climbing-stairs ├── question.md └── climbing-stairs.py ├── 119.pascals-triangle-ii ├── question.md └── pascals-triangle-ii.py ├── 172.factorial-trailing-zeroes ├── question.md └── factorial-trailing-zeroes.py ├── 453.minimum-moves-to-equal-array-elements ├── minimum-moves-to-equal-array-elements.py └── question.md ├── 020.valid-parentheses ├── question.md └── valid-parentheses.py ├── 118.pascals-triangle ├── question.md └── pascals-triangle.py ├── 252.meeting-rooms └── question.md ├── 326.power-of-three ├── power-of-three.py └── question.md ├── 521.longest-uncommon-subsequence-i └── longest-uncommon-subsequence-i.py ├── 110.balanced-binary-tree └── question.md ├── 191.number-of-1-bits ├── number-of-1-bits.py └── question.md ├── 220.contains-duplicate-iii └── question.md ├── 247.strobogrammatic-number-ii └── question.md ├── 253.meeting-rooms-ii └── question.md ├── 093.restore-ip-addresses └── question.md ├── 142.linked-list-cycle-ii └── question.md ├── 152.maximum-product-subarray └── question.md ├── 143.reorder-list └── question.md ├── 163.missing-ranges └── question.md ├── 233.number-of-digit-one ├── question.md └── number-of-digit-one.py ├── 201.bitwise-and-of-numbers-range ├── bitwise-and-of-numbers-range.py └── question.md ├── 371.sum-of-two-integers └── question.md ├── 153.find-minimum-in-rotated-sorted-array ├── question.md └── find-minimum-in-rotated-sorted-array.py ├── 404.sum-of-left-leaves └── question.md ├── 660.remove-9 ├── remove-9.py └── question.md ├── 082.remove-duplicates-from-sorted-list-ii └── question.md ├── 099.recover-binary-search-tree └── question.md ├── 504.base-7 ├── question.md └── base-7.py ├── 041.first-missing-positive ├── question.md └── first-missing-positive.py ├── 047.permutations-ii └── question.md ├── 049.anagrams └── question.md ├── 085.maximal-rectangle └── question.md ├── 097.interleaving-string └── question.md ├── 137.single-number-ii └── question.md ├── 515.find-largest-value-in-each-tree-row └── question.md ├── 598.range-addition-ii └── range-addition-ii.py ├── 059.spiral-matrix-ii └── question.md ├── 159.longest-substring-with-at-most-two-distinct-characters └── question.md ├── 628.maximum-product-of-three-numbers ├── maximum-product-of-three-numbers.py └── question.md ├── 046.permutations └── question.md ├── 049.group-anagrams └── question.md ├── 066.plus-one ├── question.md └── plus-one.py ├── 077.combinations ├── question.md └── combinations.py ├── 190.reverse-bits ├── reverse-bits.py └── question.md ├── 255.verify-preorder-sequence-in-binary-search-tree └── question.md ├── 340.longest-substring-with-at-most-k-distinct-characters └── question.md ├── 461.hamming-distance ├── hamming-distance.py └── question.md ├── 557.reverse-words-in-a-string-iii ├── reverse-words-in-a-string-iii.py └── question.md ├── 058.length-of-last-word ├── length-of-last-word.py └── question.md ├── 246.strobogrammatic-number ├── question.md └── strobogrammatic-number.py ├── 349.intersection-of-two-arrays ├── question.md └── intersection-of-two-arrays.py ├── 386.lexicographical-numbers └── question.md ├── 553.optimal-division └── optimal-division.py ├── 022.generate-parentheses └── question.md ├── 203.remove-linked-list-elements └── question.md ├── 270.closest-binary-search-tree-value └── question.md ├── 481.magical-string └── magical-string.py ├── 276.paint-fence ├── question.md └── paint-fence.py ├── 389.find-the-difference ├── find-the-difference.py └── question.md ├── 462.minimum-moves-to-equal-array-elements-ii └── minimum-moves-to-equal-array-elements-ii.py ├── 131.palindrome-partitioning └── question.md ├── 267.palindrome-permutation-ii └── question.md ├── 293.flip-game └── flip-game.py ├── 037.sudoku-solver └── question.md ├── 054.spiral-matrix └── question.md ├── 237.delete-node-in-a-linked-list ├── question.md └── delete-node-in-a-linked-list.py ├── 320.generalized-abbreviation ├── question.md └── generalized-abbreviation.py ├── 372.super-pow ├── super-pow.py └── question.md ├── 088.merge-sorted-array └── question.md ├── 338.counting-bits └── counting-bits.py ├── 633.sum-of-square-numbers ├── question.md └── sum-of-square-numbers.py ├── 072.edit-distance └── question.md ├── 345.reverse-vowels-of-a-string └── question.md ├── 492.construct-the-rectangle └── construct-the-rectangle.py ├── 007.reverse-integer └── reverse-integer.py ├── 024.swap-nodes-in-pairs └── question.md ├── 033.search-in-rotated-sorted-array └── question.md ├── 094.binary-tree-inorder-traversal └── question.md ├── 132.palindrome-partitioning-ii └── question.md ├── 144.binary-tree-preorder-traversal └── question.md ├── 145.binary-tree-postorder-traversal └── question.md ├── 346.moving-average-from-data-stream └── question.md ├── 005.longest-palindromic-substring └── question.md ├── 086.partition-list └── question.md ├── 092.reverse-linked-list-ii └── question.md ├── 123.best-time-to-buy-and-sell-stock-iii ├── question.md └── best-time-to-buy-and-sell-stock-iii.py ├── 128.longest-consecutive-sequence └── question.md ├── 168.excel-sheet-column-title ├── question.md └── excel-sheet-column-title.py ├── 222.count-complete-tree-nodes └── question.md ├── 273.integer-to-english-words └── question.md ├── 406.queue-reconstruction-by-height └── queue-reconstruction-by-height.py ├── 027.remove-element ├── remove-element.py └── question.md ├── 062.unique-paths ├── unique-paths.py └── question.md ├── 078.subsets ├── question.md └── subsets.py ├── 283.move-zeroes ├── move-zeroes.py └── question.md ├── 387.first-unique-character-in-a-string ├── question.md └── first-unique-character-in-a-string.py ├── 401.binary-watch └── binary-watch.py ├── 090.subsets-ii └── question.md ├── 122.best-time-to-buy-and-sell-stock-ii ├── best-time-to-buy-and-sell-stock-ii.py └── question.md ├── 290.word-pattern └── word-pattern.py ├── 400.nth-digit ├── nth-digit.py └── question.md ├── 480.sliding-window-median └── sliding-window-median.py ├── 594.longest-harmonious-subsequence ├── longest-harmonious-subsequence.py └── question.md ├── 250.count-univalue-subtrees └── question.md ├── 343.integer-break ├── integer-break.py └── question.md ├── 459.repeated-substring-pattern └── repeated-substring-pattern.py ├── 016.3sum-closest └── question.md ├── 032.longest-valid-parentheses └── question.md ├── 179.largest-number ├── question.md └── largest-number.py ├── 279.perfect-squares └── question.md ├── 442.find-all-duplicates-in-an-array ├── question.md └── find-all-duplicates-in-an-array.py ├── 502.ipo └── ipo.py ├── 080.remove-duplicates-from-sorted-array-ii └── question.md ├── 160.intersection-of-two-linked-lists └── intersection-of-two-linked-lists.py ├── 221.maximal-square └── question.md ├── 507.perfect-number ├── perfect-number.py └── question.md ├── 537.complex-number-multiplication └── complex-number-multiplication.py ├── 657.judge-route-circle └── judge-route-circle.py ├── 001.two-sum ├── question.md └── two-sum.py ├── 015.3sum └── question.md ├── 034.search-for-a-range └── question.md ├── 035.search-insert-position ├── question.md └── search-insert-position.py ├── 135.candy ├── question.md └── candy.py ├── 150.evaluate-reverse-polish-notation └── question.md ├── 347.top-k-frequent-elements └── question.md ├── 421.maximum-xor-of-two-numbers-in-an-array └── question.md ├── 485.max-consecutive-ones ├── max-consecutive-ones.py └── question.md ├── 422.valid-word-square └── valid-word-square.py ├── 625.minimum-factorization └── question.md ├── 011.container-with-most-water ├── question.md └── container-with-most-water.py ├── 257.binary-tree-paths └── question.md ├── 562.longest-line-of-consecutive-one-in-matrix └── question.md ├── 036.valid-sudoku └── question.md ├── 053.maximum-subarray ├── maximum-subarray.py └── question.md ├── 174.dungeon-game └── dungeon-game.py ├── 357.count-numbers-with-unique-digits ├── question.md └── count-numbers-with-unique-digits.py ├── 415.add-strings └── question.md ├── 002.add-two-numbers └── question.md ├── 019.remove-nth-node-from-end-of-list └── question.md ├── 043.multiply-strings └── question.md ├── 055.jump-game └── question.md ├── 170.two-sum-iii-data-structure-design └── question.md ├── 556.next-greater-element-iii └── question.md ├── 171.excel-sheet-column-number └── question.md ├── 334.increasing-triplet-subsequence └── increasing-triplet-subsequence.py ├── 395.longest-substring-with-at-least-k-repeating-characters └── longest-substring-with-at-least-k-repeating-characters.py ├── 456.132-pattern └── 132-pattern.py ├── 060.permutation-sequence └── question.md ├── 223.rectangle-area ├── question.md └── rectangle-area.py ├── 228.summary-ranges └── question.md ├── 242.valid-anagram └── question.md ├── 440.k-th-smallest-in-lexicographical-order └── question.md ├── 121.best-time-to-buy-and-sell-stock └── best-time-to-buy-and-sell-stock.py ├── 226.invert-binary-tree └── question.md ├── 303.range-sum-query-immutable └── question.md ├── 369.plus-one-linked-list └── question.md ├── 560.subarray-sum-equals-k ├── subarray-sum-equals-k.py └── question.md ├── 611.valid-triangle-number └── valid-triangle-number.py ├── 004.median-of-two-sorted-arrays └── question.md ├── 096.unique-binary-search-trees ├── question.md └── unique-binary-search-trees.py ├── 102.binary-tree-level-order-traversal └── question.md ├── 173.binary-search-tree-iterator └── question.md ├── 215.kth-largest-element-in-an-array └── question.md ├── 260.single-number-iii └── single-number-iii.py ├── 539.minimum-time-difference └── question.md ├── 605.can-place-flowers └── can-place-flowers.py ├── 003.longest-substring-without-repeating-characters └── question.md ├── 073.set-matrix-zeroes └── question.md ├── 376.wiggle-subsequence └── wiggle-subsequence.py ├── 452.minimum-number-of-arrows-to-burst-balloons └── minimum-number-of-arrows-to-burst-balloons.py ├── 483.smallest-good-base └── smallest-good-base.py ├── 493.reverse-pairs ├── reverse-pairs.py └── question.md ├── 551.student-attendance-record-i └── student-attendance-record-i.py ├── 026.remove-duplicates-from-sorted-array ├── remove-duplicates-from-sorted-array.py └── question.md ├── 071.simplify-path ├── simplify-path.py └── question.md ├── 164.maximum-gap └── question.md ├── 263.ugly-number ├── ugly-number.py └── question.md ├── 390.elimination-game └── elimination-game.py ├── 130.surrounded-regions └── question.md ├── 188.best-time-to-buy-and-sell-stock-iv └── question.md ├── 315.count-of-smaller-numbers-after-self └── count-of-smaller-numbers-after-self.py ├── 356.line-reflection ├── line-reflection.py └── question.md ├── 402.remove-k-digits └── remove-k-digits.py ├── 187.repeated-dna-sequences ├── repeated-dna-sequences.py └── question.md ├── 259.3sum-smaller ├── question.md └── 3sum-smaller.py ├── 367.valid-perfect-square └── question.md ├── 419.battleships-in-a-board └── battleships-in-a-board.py ├── 498.diagonal-traverse └── question.md ├── 525.contiguous-array └── contiguous-array.py ├── 154.find-minimum-in-rotated-sorted-array-ii └── question.md ├── 214.shortest-palindrome └── question.md ├── 251.flatten-2d-vector └── question.md ├── 330.patching-array └── patching-array.py ├── 377.combination-sum-iv └── combination-sum-iv.py ├── 018.4sum └── question.md ├── 451.sort-characters-by-frequency └── sort-characters-by-frequency.py ├── 554.brick-wall └── brick-wall.py ├── 113.path-sum-ii └── question.md ├── 397.integer-replacement └── integer-replacement.py ├── 517.super-washing-machines └── super-washing-machines.py ├── 606.construct-string-from-binary-tree └── construct-string-from-binary-tree.py ├── 646.maximum-length-of-pair-chain └── maximum-length-of-pair-chain.py ├── 030.substring-with-concatenation-of-all-words └── question.md ├── 089.gray-code └── gray-code.py ├── 095.unique-binary-search-trees-ii └── question.md ├── 107.binary-tree-level-order-traversal-ii └── question.md ├── 162.find-peak-element └── find-peak-element.py ├── 238.product-of-array-except-self ├── question.md └── product-of-array-except-self.py ├── 264.ugly-number-ii ├── question.md └── ugly-number-ii.py ├── 322.coin-change └── coin-change.py ├── 564.find-the-closest-palindrome ├── question.md └── find-the-closest-palindrome.py ├── 042.trapping-rain-water └── question.md ├── 124.binary-tree-maximum-path-sum └── question.md ├── 311.sparse-matrix-multiplication ├── question.md └── sparse-matrix-multiplication.py ├── 081.search-in-rotated-sorted-array-ii └── question.md ├── 091.decode-ways └── question.md ├── 448.find-all-numbers-disappeared-in-an-array └── question.md ├── 455.assign-cookies └── assign-cookies.py ├── 500.keyboard-row └── question.md ├── 516.longest-palindromic-subsequence └── question.md ├── 125.valid-palindrome ├── question.md └── valid-palindrome.py ├── 230.kth-smallest-element-in-a-bst └── question.md ├── 248.strobogrammatic-number-iii └── question.md ├── 274.h-index └── h-index.py ├── 301.remove-invalid-parentheses └── question.md ├── 416.partition-equal-subset-sum └── partition-equal-subset-sum.py ├── 477.total-hamming-distance └── total-hamming-distance.py ├── 017.letter-combinations-of-a-phone-number └── question.md ├── 200.number-of-islands └── question.md ├── 224.basic-calculator └── question.md ├── 243.shortest-word-distance └── question.md ├── 265.paint-house-ii └── paint-house-ii.py ├── 339.nested-list-weight-sum └── question.md ├── 383.ransom-note └── ransom-note.py ├── 544.output-contest-matches └── output-contest-matches.py ├── 063.unique-paths-ii └── question.md ├── 103.binary-tree-zigzag-level-order-traversal └── question.md ├── 157.read-n-characters-given-read4 └── question.md ├── 316.remove-duplicate-letters └── question.md ├── 084.largest-rectangle-in-histogram └── question.md ├── 167.two-sum-ii-input-array-is-sorted └── two-sum-ii-input-array-is-sorted.py ├── 199.binary-tree-right-side-view └── question.md ├── 235.lowest-common-ancestor-of-a-binary-search-tree └── lowest-common-ancestor-of-a-binary-search-tree.py ├── 392.is-subsequence └── is-subsequence.py ├── 530.minimum-absolute-difference-in-bst └── question.md ├── 566.reshape-the-matrix └── reshape-the-matrix.py ├── 659.split-array-into-consecutive-subsequences └── split-array-into-consecutive-subsequences.py ├── 158.read-n-characters-given-read4-ii-call-multiple-times └── question.md ├── 198.house-robber └── house-robber.py ├── 412.fizz-buzz └── fizz-buzz.py ├── 643.maximum-average-subarray-i └── question.md ├── 101.symmetric-tree └── question.md ├── 112.path-sum └── question.md ├── 186.reverse-words-in-a-string-ii └── question.md ├── 202.happy-number └── happy-number.py ├── 325.maximum-size-subarray-sum-equals-k └── maximum-size-subarray-sum-equals-k.py ├── 396.rotate-function └── rotate-function.py ├── 503.next-greater-element-ii └── next-greater-element-ii.py ├── 538.convert-bst-to-greater-tree └── question.md ├── 552.student-attendance-record-ii └── student-attendance-record-ii.py ├── 565.array-nesting └── array-nesting.py ├── 645.set-mismatch └── set-mismatch.py ├── 115.distinct-subsequences └── question.md ├── 129.sum-root-to-leaf-numbers └── question.md ├── 216.combination-sum-iii └── question.md ├── 378.kth-smallest-element-in-a-sorted-matrix └── question.md ├── 484.find-permutation └── find-permutation.py ├── 278.first-bad-version └── first-bad-version.py ├── 354.russian-doll-envelopes └── question.md ├── 513.find-bottom-left-tree-value └── question.md ├── 520.detect-capital └── detect-capital.py ├── 609.find-duplicate-file-in-system └── find-duplicate-file-in-system.py ├── 074.search-a-2d-matrix └── question.md ├── 446.arithmetic-slices-ii-subsequence └── arithmetic-slices-ii-subsequence.py ├── 467.unique-substrings-in-wraparound-string └── unique-substrings-in-wraparound-string.py ├── 482.license-key-formatting └── license-key-formatting.py ├── 593.valid-square └── valid-square.py ├── 637.average-of-levels-in-binary-tree └── question.md ├── 120.triangle └── question.md ├── 134.gas-station └── question.md ├── 272.closest-binary-search-tree-value-ii └── question.md ├── 282.expression-add-operators └── question.md ├── 394.decode-string └── decode-string.py ├── 409.longest-palindrome └── question.md ├── 076.minimum-window-substring └── question.md ├── 189.rotate-array └── question.md ├── 374.guess-number-higher-or-lower └── question.md ├── 535.encode-and-decode-tinyurl └── question.md ├── 583.delete-operation-for-two-strings └── question.md ├── 006.zigzag-conversion └── question.md ├── 166.fraction-to-recurring-decimal └── question.md ├── 307.range-sum-query-mutable └── question.md └── 370.range-addition └── range-addition.py /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. -------------------------------------------------------------------------------- /069.sqrtx/question.md: -------------------------------------------------------------------------------- 1 | Implement int sqrt(int x). 2 | 3 | Compute and return the square root of x. -------------------------------------------------------------------------------- /148.sort-list/question.md: -------------------------------------------------------------------------------- 1 | Sort a linked list in O(n log n) time using constant space complexity. -------------------------------------------------------------------------------- /161.one-edit-distance/question.md: -------------------------------------------------------------------------------- 1 | Given two strings S and T, determine if they are both one edit distance apart. -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /169.majority-element/majority-element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def majorityElement(self, num): 3 | return sorted(num)[len(num) / 2] 4 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /292.nim-game/nim-game.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canWinNim(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | return not n % 4 == 0 8 | -------------------------------------------------------------------------------- /344.reverse-string/question.md: -------------------------------------------------------------------------------- 1 | Write a function that takes a string as input and returns the string reversed. 2 | 3 | 4 | Example: 5 | Given s = "hello", return "olleh". 6 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /319.bulb-switcher/bulb-switcher.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def bulbSwitch(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | return int(n ** 0.5) 8 | -------------------------------------------------------------------------------- /344.reverse-string/reverse-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseString(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | return s[::-1] 8 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /476.number-complement/number-complement.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findComplement(self, num): 3 | i = 1 4 | while i <= num: 5 | i = i << 1 6 | return (i - 1) ^ num 7 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /231.power-of-two/power-of-two.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPowerOfTwo(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | return n != 0 and (n & -n) == n 8 | -------------------------------------------------------------------------------- /266.palindrome-permutation/question.md: -------------------------------------------------------------------------------- 1 | Given a string, determine if a permutation of the string could form a palindrome. 2 | 3 | For example, 4 | "code" -> False, "aab" -> True, "carerac" -> True. 5 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /441.arranging-coins/arranging-coins.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def arrangeCoins(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | return int((((1 + 8 * n) ** 0.5) - 1) / 2) 8 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /151.reverse-words-in-a-string/reverse-words-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseWords(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | return " ".join(s.split()[::-1]) 8 | -------------------------------------------------------------------------------- /342.power-of-four/power-of-four.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPowerOfFour(self, num): 3 | """ 4 | :type num: int 5 | :rtype: bool 6 | """ 7 | return num & (num - 1) == 0 and (num - 1) % 3 == 0 8 | -------------------------------------------------------------------------------- /434.number-of-segments-in-a-string/number-of-segments-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countSegments(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | return len(s.split()) 8 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /258.add-digits/add-digits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def addDigits(self, num): 3 | """ 4 | :type num: int 5 | :rtype: int 6 | """ 7 | if num < 10: 8 | return num 9 | return 1 + (num - 1) % 9 10 | -------------------------------------------------------------------------------- /268.missing-number/missing-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def missingNumber(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | n = len(nums) 8 | return (n * (n + 1)) / 2 - sum(nums) 9 | -------------------------------------------------------------------------------- /285.inorder-successor-in-bst/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a binary search tree and a node in it, find the in-order successor of that node in the BST. 3 | 4 | 5 | 6 | Note: If the given node has no in-order successor in the tree, return null. 7 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /280.wiggle-sort/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... 3 | 4 | 5 | For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. 6 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /575.distribute-candies/distribute-candies.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def distributeCandies(self, candies): 3 | """ 4 | :type candies: List[int] 5 | :rtype: int 6 | """ 7 | return min(len(candies) / 2, len(set(candies))) 8 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /561.array-partition-i/array-partition-i.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def arrayPairSum(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | return sum([c for i, c in enumerate(sorted(nums)) if i % 2 == 0]) 8 | -------------------------------------------------------------------------------- /205.isomorphic-strings/isomorphic-strings.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isIsomorphic(self, s, t): 3 | """ 4 | :type s: str 5 | :type t: str 6 | :rtype: bool 7 | """ 8 | return len(set(s)) == len(set(t)) == len(set(zip(s, t))) 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # leetcode solutions using python 2 | This is my leetcode solution folder. 3 | 4 | Language: python 5 | 6 | Last updated: 2017-06-27 7 | 8 | The source code was fetched using the tool [leetcode-spider](https://github.com/Ma63d/leetcode-spider). 9 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /453.minimum-moves-to-equal-array-elements/minimum-moves-to-equal-array-elements.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minMoves(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | return sum(nums) - len(nums) * min(nums) 8 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /136.single-number/single-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def singleNumber(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | for i in range(1, len(nums)): 8 | nums[0] ^= nums[i] 9 | return nums[0] 10 | -------------------------------------------------------------------------------- /252.meeting-rooms/question.md: -------------------------------------------------------------------------------- 1 | Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. 2 | 3 | 4 | For example, 5 | Given [[0, 30],[5, 10],[15, 20]], 6 | return false. 7 | -------------------------------------------------------------------------------- /326.power-of-three/power-of-three.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPowerOfThree(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | if n > 0: 8 | return (1162261467 % n) == 0 9 | else: 10 | return False 11 | -------------------------------------------------------------------------------- /521.longest-uncommon-subsequence-i/longest-uncommon-subsequence-i.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLUSlength(self, a, b): 3 | """ 4 | :type a: str 5 | :type b: str 6 | :rtype: int 7 | """ 8 | return max(len(a), len(b)) if a != b else -1 9 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /191.number-of-1-bits/number-of-1-bits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def hammingWeight(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | ans = 0 8 | while n > 0: 9 | n -= (n & -n) 10 | ans += 1 11 | return ans 12 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /247.strobogrammatic-number-ii/question.md: -------------------------------------------------------------------------------- 1 | A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 2 | Find all strobogrammatic numbers that are of length = n. 3 | For example, 4 | Given n = 2, return ["11","69","88","96"]. 5 | -------------------------------------------------------------------------------- /253.meeting-rooms-ii/question.md: -------------------------------------------------------------------------------- 1 | Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. 2 | 3 | 4 | For example, 5 | Given [[0, 30],[5, 10],[15, 20]], 6 | return 2. 7 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /163.missing-ranges/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges. 3 | 4 | 5 | For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"]. 6 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /201.bitwise-and-of-numbers-range/bitwise-and-of-numbers-range.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def rangeBitwiseAnd(self, m, n): 3 | """ 4 | :type m: int 5 | :type n: int 6 | :rtype: int 7 | """ 8 | while m < n: 9 | n = n & n - 1 10 | return n 11 | -------------------------------------------------------------------------------- /371.sum-of-two-integers/question.md: -------------------------------------------------------------------------------- 1 | Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 2 | 3 | Example: 4 | Given a = 1 and b = 2, return 3. 5 | 6 | 7 | Credits:Special thanks to @fujiaozhu for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /404.sum-of-left-leaves/question.md: -------------------------------------------------------------------------------- 1 | Find the sum of all left leaves in a given binary tree. 2 | 3 | Example: 4 | 5 | 3 6 | / \ 7 | 9 20 8 | / \ 9 | 15 7 10 | 11 | There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 12 | 13 | -------------------------------------------------------------------------------- /660.remove-9/remove-9.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def newInteger(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | ans = 0 8 | k = 1 9 | while n > 0: 10 | ans += (n % 9) * k 11 | k *= 10 12 | n /= 9 13 | return ans 14 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /504.base-7/question.md: -------------------------------------------------------------------------------- 1 | Given an integer, return its base 7 string representation. 2 | 3 | Example 1: 4 | 5 | Input: 100 6 | Output: "202" 7 | 8 | 9 | 10 | Example 2: 11 | 12 | Input: -7 13 | Output: "-10" 14 | 15 | 16 | 17 | Note: 18 | The input will be in range of [-1e7, 1e7]. 19 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /326.power-of-three/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an integer, write a function to determine if it is a power of three. 3 | 4 | 5 | Follow up: 6 | Could you do it without using any loop / recursion? 7 | 8 | 9 | Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /515.find-largest-value-in-each-tree-row/question.md: -------------------------------------------------------------------------------- 1 | You need to find the largest value in each row of a binary tree. 2 | 3 | Example: 4 | 5 | Input: 6 | 7 | 1 8 | / \ 9 | 3 2 10 | / \ \ 11 | 5 3 9 12 | 13 | Output: [1, 3, 9] 14 | 15 | 16 | -------------------------------------------------------------------------------- /598.range-addition-ii/range-addition-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxCount(self, m, n, ops): 3 | """ 4 | :type m: int 5 | :type n: int 6 | :type ops: List[List[int]] 7 | :rtype: int 8 | """ 9 | return reduce(operator.mul, map(min, zip(*ops + [[m, n]]))) 10 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /159.longest-substring-with-at-most-two-distinct-characters/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a string, find the length of the longest substring T that contains at most 2 distinct characters. 3 | 4 | 5 | 6 | For example, 7 | 8 | Given s = “eceba”, 9 | 10 | 11 | 12 | T is "ece" which its length is 3. 13 | -------------------------------------------------------------------------------- /628.maximum-product-of-three-numbers/maximum-product-of-three-numbers.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maximumProduct(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | nums.sort() 8 | return max(nums[0] * nums[1] * nums[-1], nums[-1] * nums[-2] * nums[-3]) 9 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /049.group-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. -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /172.factorial-trailing-zeroes/factorial-trailing-zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def trailingZeroes(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | count, k = 0, 5 8 | while n: 9 | k = n / 5 10 | count += k 11 | n = k 12 | return count 13 | -------------------------------------------------------------------------------- /190.reverse-bits/reverse-bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param n, an integer 3 | # @return an integer 4 | def reverseBits(self, n): 5 | ans = 0 6 | mask = 1 7 | for _ in range(32): 8 | ans <<= 1 9 | if mask & n: 10 | ans |= 1 11 | n >>= 1 12 | return ans 13 | -------------------------------------------------------------------------------- /255.verify-preorder-sequence-in-binary-search-tree/question.md: -------------------------------------------------------------------------------- 1 | Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree. 2 | 3 | You may assume each number in the sequence is unique. 4 | 5 | Follow up: 6 | Could you do it using only constant space complexity? -------------------------------------------------------------------------------- /340.longest-substring-with-at-most-k-distinct-characters/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a string, find the length of the longest substring T that contains at most k distinct characters. 3 | 4 | 5 | 6 | For example, 7 | 8 | Given s = “eceba” and k = 2, 9 | 10 | 11 | 12 | T is "ece" which its length is 3. 13 | -------------------------------------------------------------------------------- /461.hamming-distance/hamming-distance.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def hammingDistance(self, x, y): 3 | """ 4 | :type x: int 5 | :type y: int 6 | :rtype: int 7 | """ 8 | x = x ^ y 9 | y = 0 10 | while x: 11 | y += 1 12 | x = x & (x - 1) 13 | return y 14 | -------------------------------------------------------------------------------- /557.reverse-words-in-a-string-iii/reverse-words-in-a-string-iii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseWords(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | s = s.split() 8 | for i, word in enumerate(s): 9 | s[i] = word[::-1] 10 | return " ".join(s) 11 | -------------------------------------------------------------------------------- /058.length-of-last-word/length-of-last-word.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lengthOfLastWord(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | if len(s) == 0: 8 | return 0 9 | s = s.split() 10 | if len(s) > 0: 11 | return len(s[-1]) 12 | return 0 13 | -------------------------------------------------------------------------------- /246.strobogrammatic-number/question.md: -------------------------------------------------------------------------------- 1 | A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 2 | Write a function to determine if a number is strobogrammatic. The number is represented as a string. 3 | For example, the numbers "69", "88", and "818" are all strobogrammatic. -------------------------------------------------------------------------------- /349.intersection-of-two-arrays/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given two arrays, write a function to compute their intersection. 3 | 4 | 5 | Example: 6 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. 7 | 8 | 9 | Note: 10 | 11 | Each element in the result must be unique. 12 | The result can be in any order. 13 | 14 | -------------------------------------------------------------------------------- /386.lexicographical-numbers/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an integer n, return 1 - n in lexicographical order. 3 | 4 | 5 | 6 | For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. 7 | 8 | 9 | 10 | Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000. 11 | -------------------------------------------------------------------------------- /553.optimal-division/optimal-division.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def optimalDivision(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: str 6 | """ 7 | if len(nums) < 3: 8 | return "/".join(map(str, nums)) 9 | return "%s/(%s)" % (nums[0], "/".join(map(str, nums[1:]))) 10 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /270.closest-binary-search-tree-value/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. 3 | 4 | Note: 5 | 6 | Given target value is a floating point. 7 | You are guaranteed to have only one unique value in the BST that is closest to the target. 8 | -------------------------------------------------------------------------------- /481.magical-string/magical-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def magicalString(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | s = "122" 8 | p = 2 9 | while len(s) < n: 10 | s += str((3 - int(s[-1]))) * int(s[p]) 11 | p += 1 12 | return s[:n].count("1") 13 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /276.paint-fence/question.md: -------------------------------------------------------------------------------- 1 | 2 | There is a fence with n posts, each post can be painted with one of the k colors. 3 | You have to paint all the posts such that no more than two adjacent fence posts have the same color. 4 | Return the total number of ways you can paint the fence. 5 | 6 | Note: 7 | n and k are non-negative integers. -------------------------------------------------------------------------------- /389.find-the-difference/find-the-difference.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findTheDifference(self, s, t): 3 | """ 4 | :type s: str 5 | :type t: str 6 | :rtype: str 7 | """ 8 | sum1 = sum(map(ord, [c for c in s])) 9 | sum2 = sum(map(ord, [c for c in t])) 10 | return chr(sum2 - sum1) 11 | -------------------------------------------------------------------------------- /462.minimum-moves-to-equal-array-elements-ii/minimum-moves-to-equal-array-elements-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minMoves2(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | nums.sort() 8 | mid = nums[len(nums) / 2] 9 | return sum(abs(num - mid) for num in nums) 10 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /267.palindrome-permutation-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form. 3 | 4 | 5 | For example: 6 | 7 | 8 | Given s = "aabb", return ["abba", "baab"]. 9 | 10 | 11 | Given s = "abc", return []. 12 | -------------------------------------------------------------------------------- /293.flip-game/flip-game.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def generatePossibleNextMoves(self, s): 3 | """ 4 | :type s: str 5 | :rtype: List[str] 6 | """ 7 | ans = [] 8 | for i in range(0, len(s) - 1): 9 | if s[i:i + 2] == "++": 10 | ans.append(s[:i] + "--" + s[i + 2:]) 11 | return ans 12 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /217.contains-duplicate/contains-duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def containsDuplicate(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: bool 6 | """ 7 | nums.sort() 8 | for i in range(0, len(nums) - 1): 9 | if nums[i] == nums[i + 1]: 10 | return True 11 | return False 12 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /320.generalized-abbreviation/question.md: -------------------------------------------------------------------------------- 1 | Write a function to generate the generalized abbreviations of a word. 2 | 3 | 4 | Example: 5 | 6 | Given word = "word", return the following list (order does not matter): 7 | ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] 8 | 9 | -------------------------------------------------------------------------------- /372.super-pow/super-pow.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def superPow(self, a, b): 3 | """ 4 | :type a: int 5 | :type b: List[int] 6 | :rtype: int 7 | """ 8 | ret = 1 9 | k = 1 10 | for num in reversed(b): 11 | ret *= a ** (num) % 1337 12 | a = a ** 10 % 1337 13 | return ret % 1337 14 | -------------------------------------------------------------------------------- /434.number-of-segments-in-a-string/question.md: -------------------------------------------------------------------------------- 1 | Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. 2 | 3 | Please note that the string does not contain any non-printable characters. 4 | 5 | Example: 6 | 7 | Input: "Hello, my name is John" 8 | Output: 5 9 | 10 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /338.counting-bits/counting-bits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countBits(self, num): 3 | """ 4 | :type num: int 5 | :rtype: List[int] 6 | """ 7 | if num == 0: 8 | return [0] 9 | ans = [0, 1] 10 | j = 0 11 | for i in range(2, num + 1): 12 | ans.append(ans[i & (i - 1)] + 1) 13 | return ans 14 | -------------------------------------------------------------------------------- /633.sum-of-square-numbers/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c. 3 | 4 | 5 | Example 1: 6 | 7 | Input: 5 8 | Output: True 9 | Explanation: 1 * 1 + 2 * 2 = 5 10 | 11 | 12 | 13 | 14 | Example 2: 15 | 16 | Input: 3 17 | Output: False 18 | 19 | 20 | -------------------------------------------------------------------------------- /070.climbing-stairs/climbing-stairs.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def climbStairs(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | if n <= 1: 8 | return 1 9 | pre, ppre = 1, 1 10 | for i in range(2, n + 1): 11 | tmp = pre 12 | pre = ppre + pre 13 | ppre = tmp 14 | return pre 15 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /345.reverse-vowels-of-a-string/question.md: -------------------------------------------------------------------------------- 1 | Write a function that takes a string as input and reverse only the vowels of a string. 2 | 3 | 4 | Example 1: 5 | Given s = "hello", return "holle". 6 | 7 | 8 | 9 | Example 2: 10 | Given s = "leetcode", return "leotcede". 11 | 12 | 13 | 14 | Note: 15 | The vowels does not include the letter "y". 16 | -------------------------------------------------------------------------------- /492.construct-the-rectangle/construct-the-rectangle.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def constructRectangle(self, area): 3 | """ 4 | :type area: int 5 | :rtype: List[int] 6 | """ 7 | root = int(area ** 0.5) 8 | while root > 0: 9 | if area % root == 0: 10 | return int(area / root), root 11 | root -= 1 12 | -------------------------------------------------------------------------------- /007.reverse-integer/reverse-integer.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverse(self, x): 3 | """ 4 | :type x: int 5 | :rtype: int 6 | """ 7 | sign = x < 0 and -1 or 1 8 | x = abs(x) 9 | ans = 0 10 | while x: 11 | ans = ans * 10 + x % 10 12 | x /= 10 13 | return sign * ans if ans <= 0x7fffffff else 0 14 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /050.powx-n/powx-n.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def myPow(self, x, n): 3 | """ 4 | :type x: float 5 | :type n: int 6 | :rtype: float 7 | """ 8 | if n < 0: 9 | n = -n 10 | x = 1 / x 11 | ans = 1 12 | while n: 13 | if n & 1: 14 | ans *= x 15 | x *= x 16 | n >>= 1 17 | return ans 18 | -------------------------------------------------------------------------------- /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? -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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? -------------------------------------------------------------------------------- /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? -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /346.moving-average-from-data-stream/question.md: -------------------------------------------------------------------------------- 1 | Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. 2 | 3 | For example, 4 | 5 | MovingAverage m = new MovingAverage(3); 6 | m.next(1) = 1 7 | m.next(10) = (1 + 10) / 2 8 | m.next(3) = (1 + 10 + 3) / 3 9 | m.next(5) = (10 + 3 + 5) / 3 10 | 11 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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). -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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" -------------------------------------------------------------------------------- /406.queue-reconstruction-by-height/queue-reconstruction-by-height.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reconstructQueue(self, people): 3 | """ 4 | :type people: List[List[int]] 5 | :rtype: List[List[int]] 6 | """ 7 | queue = [] 8 | for p in sorted(people, key=lambda (h, k): (-h, k)): 9 | queue.insert(p[1], p) 10 | return queue 11 | -------------------------------------------------------------------------------- /027.remove-element/remove-element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeElement(self, nums, val): 3 | """ 4 | :type nums: List[int] 5 | :type val: int 6 | :rtype: int 7 | """ 8 | slow = -1 9 | for i in range(0, len(nums)): 10 | if nums[i] != val: 11 | slow += 1 12 | nums[slow] = nums[i] 13 | return slow + 1 14 | -------------------------------------------------------------------------------- /062.unique-paths/unique-paths.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def uniquePaths(self, m, n): 3 | """ 4 | :type m: int 5 | :type n: int 6 | :rtype: int 7 | """ 8 | dp = [1] * n 9 | 10 | for i in range(1, m): 11 | pre = 1 12 | for j in range(1, n): 13 | dp[j] = dp[j] + pre 14 | pre = dp[j] 15 | return dp[-1] 16 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /283.move-zeroes/move-zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def moveZeroes(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: void Do not return anything, modify nums in-place instead. 6 | """ 7 | i = j = 0 8 | for i in range(0, len(nums)): 9 | if nums[i] != 0: 10 | nums[j], nums[i] = nums[i], nums[j] 11 | j += 1 12 | -------------------------------------------------------------------------------- /387.first-unique-character-in-a-string/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 3 | 4 | Examples: 5 | 6 | s = "leetcode" 7 | return 0. 8 | 9 | s = "loveleetcode", 10 | return 2. 11 | 12 | 13 | 14 | 15 | Note: You may assume the string contain only lowercase letters. 16 | -------------------------------------------------------------------------------- /401.binary-watch/binary-watch.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def readBinaryWatch(self, num): 3 | """ 4 | :type num: int 5 | :rtype: List[str] 6 | """ 7 | ans = [] 8 | for i in range(0, 12): 9 | for j in range(0, 60): 10 | if (bin(i) + bin(j)).count("1") == num: 11 | ans.append("%d:%02d" % (i, j)) 12 | return ans 13 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /122.best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProfit(self, prices): 3 | """ 4 | :type prices: List[int] 5 | :rtype: int 6 | """ 7 | ans = 0 8 | for i in range(1, len(prices)): 9 | if prices[i] > prices[i - 1]: 10 | ans += prices[i] - prices[i - 1] 11 | return ans 12 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /290.word-pattern/word-pattern.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def wordPattern(self, pattern, str): 3 | """ 4 | :type pattern: str 5 | :type str: str 6 | :rtype: bool 7 | """ 8 | str = str.split() 9 | a = zip(pattern, str) 10 | print 11 | a 12 | return len(pattern) == len(str) and len(set(a)) == len(set(pattern)) == len(set(str)) 13 | -------------------------------------------------------------------------------- /342.power-of-four/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 3 | 4 | Example: 5 | Given num = 16, return true. 6 | Given num = 5, return false. 7 | 8 | 9 | Follow up: Could you solve it without loops/recursion? 10 | 11 | Credits:Special thanks to @yukuairoy for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /400.nth-digit/nth-digit.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findNthDigit(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | start, size, step = 1, 1, 9 8 | while n > size * step: 9 | n -= size * step 10 | size += 1 11 | start *= 10 12 | step *= 10 13 | return int(str(start + (n - 1) // size)[(n - 1) % size]) 14 | -------------------------------------------------------------------------------- /480.sliding-window-median/sliding-window-median.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def medianSlidingWindow(self, nums, k): 3 | window = sorted(nums[:k]) 4 | medians = [] 5 | for a, b in zip(nums, nums[k:] + [0]): 6 | medians.append((window[k / 2] + window[~(k / 2)]) / 2.) 7 | window.remove(a) 8 | bisect.insort(window, b) 9 | return medians 10 | -------------------------------------------------------------------------------- /594.longest-harmonious-subsequence/longest-harmonious-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLHS(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | ans = 0 8 | d = collections.Counter(nums) 9 | for num in nums: 10 | if num + 1 in d: 11 | ans = max(ans, d[num] + d[num + 1]) 12 | return ans 13 | -------------------------------------------------------------------------------- /250.count-univalue-subtrees/question.md: -------------------------------------------------------------------------------- 1 | Given a binary tree, count the number of uni-value subtrees. 2 | A Uni-value subtree means all nodes of the subtree have the same value. 3 | 4 | 5 | For example: 6 | Given binary tree, 7 | 8 | 5 9 | / \ 10 | 1 5 11 | / \ \ 12 | 5 5 5 13 | 14 | 15 | 16 | return 4. 17 | -------------------------------------------------------------------------------- /343.integer-break/integer-break.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def integerBreak(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | if n <= 3: 8 | return n - 1 9 | if n % 3 == 0: 10 | return 3 ** (n / 3) 11 | if n % 3 == 1: 12 | return 3 ** ((n / 3) - 1) * 4 13 | if n % 3 == 2: 14 | return 3 ** (n / 3) * 2 15 | -------------------------------------------------------------------------------- /459.repeated-substring-pattern/repeated-substring-pattern.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | 3 | def repeatedSubstringPattern(self, str): 4 | """ 5 | :type str: str 6 | :rtype: bool 7 | """ 8 | for i in range(0, len(str) / 2): 9 | if not len(str) % (i + 1) and str[:i + 1] * (len(str) / (i + 1)) == str: 10 | return True 11 | return False 12 | -------------------------------------------------------------------------------- /016.3sum-closest/question.md: -------------------------------------------------------------------------------- 1 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 2 | 3 | 4 | For example, given array S = {-1 2 1 -4}, and target = 1. 5 | 6 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 7 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /179.largest-number/question.md: -------------------------------------------------------------------------------- 1 | Given a list of non negative integers, arrange them such that they form the largest number. 2 | 3 | For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. 4 | 5 | Note: The result may be very large, so you need to return a string instead of an integer. 6 | 7 | Credits:Special thanks to @ts for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /279.perfect-squares/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. 3 | 4 | 5 | 6 | For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9. 7 | 8 | 9 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /442.find-all-duplicates-in-an-array/question.md: -------------------------------------------------------------------------------- 1 | Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 2 | 3 | Find all the elements that appear twice in this array. 4 | 5 | Could you do it without extra space and in O(n) runtime? 6 | 7 | Example: 8 | 9 | Input: 10 | [4,3,2,7,8,2,3,1] 11 | 12 | Output: 13 | [2,3] 14 | -------------------------------------------------------------------------------- /502.ipo/ipo.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMaximizedCapital(self, k, W, Profits, Capital): 3 | current = [] 4 | future = sorted(zip(Capital, Profits))[::-1] 5 | for _ in range(k): 6 | while future and future[-1][0] <= W: 7 | heapq.heappush(current, -future.pop()[1]) 8 | if current: 9 | W -= heapq.heappop(current) 10 | return W 11 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /160.intersection-of-two-linked-lists/intersection-of-two-linked-lists.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getIntersectionNode(self, headA, headB): 3 | if headA is None or headB is None: 4 | return None 5 | pa = headA 6 | pb = headB 7 | while pa is not pb: 8 | pa = headB if pa is None else pa.next 9 | pb = headA if pb is None else pb.next 10 | return pa 11 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /507.perfect-number/perfect-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def checkPerfectNumber(self, num): 3 | """ 4 | :type num: int 5 | :rtype: bool 6 | """ 7 | ans = 1 8 | div = 2 9 | while div ** 2 <= num: 10 | if num % div == 0: 11 | ans += div 12 | ans += num / div 13 | div += 1 14 | return ans == num if num != 1 else False 15 | -------------------------------------------------------------------------------- /537.complex-number-multiplication/complex-number-multiplication.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def complexNumberMultiply(self, a, b): 3 | """ 4 | :type a: str 5 | :type b: str 6 | :rtype: str 7 | """ 8 | (ar, ac), (br, bc) = map(int, a[:-1].split("+")), map(int, b[:-1].split("+")) 9 | return "{}+{}i".format(str(ar * br - ac * bc), str(ar * bc + br * ac)) 10 | -------------------------------------------------------------------------------- /657.judge-route-circle/judge-route-circle.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def judgeCircle(self, moves): 3 | """ 4 | :type moves: str 5 | :rtype: bool 6 | """ 7 | x = y = 0 8 | dirs = {"U": (0, 1), "D": (0, -1), "L": (-1, 0), "R": (1, 0)} 9 | for move in moves: 10 | dx, dy = dirs[move] 11 | x += dx 12 | y += dy 13 | return x == y == 0 14 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /347.top-k-frequent-elements/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a non-empty array of integers, return the k most frequent elements. 3 | 4 | For example, 5 | Given [1,1,1,2,2,3] and k = 2, return [1,2]. 6 | 7 | 8 | Note: 9 | 10 | You may assume k is always valid, 1 ≤ k ≤ number of unique elements. 11 | Your algorithm's time complexity must be better than O(n log n), where n is the array's size. 12 | -------------------------------------------------------------------------------- /421.maximum-xor-of-two-numbers-in-an-array/question.md: -------------------------------------------------------------------------------- 1 | Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231. 2 | 3 | Find the maximum result of ai XOR aj, where 0 ≤ i, j < n. 4 | 5 | Could you do this in O(n) runtime? 6 | 7 | Example: 8 | 9 | Input: [3, 10, 5, 25, 2, 8] 10 | 11 | Output: 28 12 | 13 | Explanation: The maximum result is 5 ^ 25 = 28. 14 | 15 | -------------------------------------------------------------------------------- /485.max-consecutive-ones/max-consecutive-ones.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMaxConsecutiveOnes(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | ans = 0 8 | count = 0 9 | for num in nums: 10 | if num == 1: 11 | count += 1 12 | else: 13 | count = 0 14 | ans = max(ans, count) 15 | return ans 16 | -------------------------------------------------------------------------------- /078.subsets/subsets.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def subsets(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[List[int]] 6 | """ 7 | 8 | def dfs(nums, index, path, ans): 9 | ans.append(path) 10 | [dfs(nums, i + 1, path + [nums[i]], ans) for i in range(index, len(nums))] 11 | 12 | ans = [] 13 | dfs(nums, 0, [], ans) 14 | return ans 15 | -------------------------------------------------------------------------------- /422.valid-word-square/valid-word-square.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def validWordSquare(self, words): 3 | """ 4 | :type words: List[str] 5 | :rtype: bool 6 | """ 7 | for i in range(0, len(words)): 8 | for j in range(0, len(words[i])): 9 | if j >= len(words) or i >= len(words[j]) or words[j][i] != words[i][j]: 10 | return False 11 | return True 12 | -------------------------------------------------------------------------------- /625.minimum-factorization/question.md: -------------------------------------------------------------------------------- 1 | Given a positive integer a, find the smallest positive integer b whose multiplication of each digit equals to a. 2 | 3 | 4 | If there is no answer or the answer is not fit in 32-bit signed integer, then return 0. 5 | 6 | 7 | Example 1 8 | Input: 9 | 48 10 | Output: 11 | 68 12 | 13 | 14 | 15 | Example 2 16 | Input: 17 | 15 18 | 19 | Output: 20 | 35 21 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /069.sqrtx/sqrtx.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def mySqrt(self, x): 3 | """ 4 | :type x: int 5 | :rtype: int 6 | """ 7 | lo = 0 8 | hi = x 9 | while lo <= hi: 10 | mid = (hi + lo) // 2 11 | v = mid * mid 12 | if v < x: 13 | lo = mid + 1 14 | elif v > x: 15 | hi = mid - 1 16 | else: 17 | return mid 18 | return hi 19 | -------------------------------------------------------------------------------- /118.pascals-triangle/pascals-triangle.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def generate(self, numRows): 3 | """ 4 | :type numRows: int 5 | :rtype: List[List[int]] 6 | """ 7 | ans = [[1] * n for n in range(1, numRows + 1)] 8 | for i in range(1, numRows + 1): 9 | for j in range(0, i - 2): 10 | ans[i - 1][1 + j] = ans[i - 2][j] + ans[i - 2][j + 1] 11 | return ans 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. -------------------------------------------------------------------------------- /562.longest-line-of-consecutive-one-in-matrix/question.md: -------------------------------------------------------------------------------- 1 | Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be horizontal, vertical, diagonal or anti-diagonal. 2 | 3 | Example: 4 | 5 | Input: 6 | [[0,1,1,0], 7 | [0,1,1,0], 8 | [0,0,0,1]] 9 | Output: 3 10 | 11 | 12 | 13 | 14 | Hint: 15 | The number of elements in the given matrix will not exceed 10,000. 16 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /053.maximum-subarray/maximum-subarray.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxSubArray(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if len(nums) == 0: 8 | return 0 9 | preSum = maxSum = nums[0] 10 | for i in range(1, len(nums)): 11 | preSum = max(preSum + nums[i], nums[i]) 12 | maxSum = max(maxSum, preSum) 13 | return maxSum 14 | -------------------------------------------------------------------------------- /174.dungeon-game/dungeon-game.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def calculateMinimumHP(self, dungeon): 3 | """ 4 | :type dungeon: List[List[int]] 5 | :rtype: int 6 | """ 7 | n = len(dungeon[0]) 8 | need = [2 ** 31] * (n - 1) + [1] 9 | for row in dungeon[::-1]: 10 | for j in range(n)[::-1]: 11 | need[j] = max(min(need[j:j + 2]) - row[j], 1) 12 | return need[0] 13 | -------------------------------------------------------------------------------- /357.count-numbers-with-unique-digits/question.md: -------------------------------------------------------------------------------- 1 | Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n. 2 | 3 | 4 | Example: 5 | Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99]) 6 | 7 | 8 | Credits:Special thanks to @memoryless for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /415.add-strings/question.md: -------------------------------------------------------------------------------- 1 | Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. 2 | 3 | Note: 4 | 5 | The length of both num1 and num2 is < 5100. 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 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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). -------------------------------------------------------------------------------- /170.two-sum-iii-data-structure-design/question.md: -------------------------------------------------------------------------------- 1 | Design and implement a TwoSum class. It should support the following operations: add and find. 2 | 3 | 4 | add - Add the number to an internal data structure. 5 | find - Find if there exists any pair of numbers which sum is equal to the value. 6 | 7 | 8 | 9 | For example, 10 | 11 | add(1); add(3); add(5); 12 | find(4) -> true 13 | find(7) -> false 14 | 15 | -------------------------------------------------------------------------------- /556.next-greater-element-iii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1. 3 | 4 | Example 1: 5 | 6 | Input: 12 7 | Output: 21 8 | 9 | 10 | 11 | Example 2: 12 | 13 | Input: 21 14 | Output: -1 15 | 16 | -------------------------------------------------------------------------------- /020.valid-parentheses/valid-parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isValid(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | stack = [] 8 | d = ["()", "[]", "{}"] 9 | for i in range(0, len(s)): 10 | stack.append(s[i]) 11 | if len(stack) >= 2 and stack[-2] + stack[-1] in d: 12 | stack.pop() 13 | stack.pop() 14 | return len(stack) == 0 15 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /334.increasing-triplet-subsequence/increasing-triplet-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def increasingTriplet(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: bool 6 | """ 7 | a = b = float("inf") 8 | for num in nums: 9 | if num <= a: 10 | a = num 11 | elif num <= b: 12 | b = num 13 | else: 14 | return True 15 | return False 16 | -------------------------------------------------------------------------------- /395.longest-substring-with-at-least-k-repeating-characters/longest-substring-with-at-least-k-repeating-characters.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def longestSubstring(self, s, k): 3 | """ 4 | :type s: str 5 | :type k: int 6 | :rtype: int 7 | """ 8 | for c in set(s): 9 | if s.count(c) < k: 10 | return max([self.longestSubstring(t, k) for t in s.split(c)]) 11 | return len(s) 12 | -------------------------------------------------------------------------------- /456.132-pattern/132-pattern.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def find132pattern(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: bool 6 | """ 7 | ak = float("-inf") 8 | stack = [] 9 | for num in reversed(nums): 10 | if ak > num: 11 | return True 12 | while stack and stack[-1] < num: 13 | ak = stack.pop() 14 | stack += num, 15 | return False 16 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /228.summary-ranges/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a sorted integer array without duplicates, return the summary of its ranges. 3 | 4 | Example 1: 5 | 6 | Input: [0,1,2,4,5,7] 7 | Output: ["0->2","4->5","7"] 8 | 9 | 10 | 11 | Example 2: 12 | 13 | Input: [0,2,3,4,6,8,9] 14 | Output: ["0","2->4","6","8->9"] 15 | 16 | 17 | 18 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating 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? -------------------------------------------------------------------------------- /389.find-the-difference/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given two strings s and t which consist of only lowercase letters. 3 | 4 | String t is generated by random shuffling string s and then add one more letter at a random position. 5 | 6 | Find the letter that was added in t. 7 | 8 | Example: 9 | 10 | Input: 11 | s = "abcd" 12 | t = "abcde" 13 | 14 | Output: 15 | e 16 | 17 | Explanation: 18 | 'e' is the letter that was added. 19 | -------------------------------------------------------------------------------- /440.k-th-smallest-in-lexicographical-order/question.md: -------------------------------------------------------------------------------- 1 | Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n. 2 | 3 | Note: 1 ≤ k ≤ n ≤ 109. 4 | 5 | Example: 6 | 7 | Input: 8 | n: 13 k: 2 9 | 10 | Output: 11 | 10 12 | 13 | Explanation: 14 | The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. 15 | 16 | 17 | -------------------------------------------------------------------------------- /001.two-sum/two-sum.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def twoSum(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: List[int] 7 | """ 8 | d = {} 9 | for i, num in enumerate(nums): 10 | if target - num in d: 11 | return [d[target - num], i] 12 | d[num] = i 13 | # no special case handling because it's assumed that it has only one solution 14 | -------------------------------------------------------------------------------- /121.best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProfit(self, prices): 3 | """ 4 | :type prices: List[int] 5 | :rtype: int 6 | """ 7 | if not prices: 8 | return 0 9 | ans = 0 10 | pre = prices[0] 11 | for i in range(1, len(prices)): 12 | pre = min(pre, prices[i]) 13 | ans = max(prices[i] - pre, ans) 14 | return ans 15 | -------------------------------------------------------------------------------- /226.invert-binary-tree/question.md: -------------------------------------------------------------------------------- 1 | Invert a binary tree. 2 | 4 3 | / \ 4 | 2 7 5 | / \ / \ 6 | 1 3 6 9 7 | 8 | to 9 | 4 10 | / \ 11 | 7 2 12 | / \ / \ 13 | 9 6 3 1 14 | 15 | Trivia: 16 | This problem was inspired by this original tweet by Max Howell: 17 | Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off. -------------------------------------------------------------------------------- /303.range-sum-query-immutable/question.md: -------------------------------------------------------------------------------- 1 | Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 2 | 3 | Example: 4 | 5 | Given nums = [-2, 0, 3, -5, 2, -1] 6 | 7 | sumRange(0, 2) -> 1 8 | sumRange(2, 5) -> -1 9 | sumRange(0, 5) -> -3 10 | 11 | 12 | 13 | Note: 14 | 15 | You may assume that the array does not change. 16 | There are many calls to sumRange function. 17 | 18 | -------------------------------------------------------------------------------- /369.plus-one-linked-list/question.md: -------------------------------------------------------------------------------- 1 | Given a non-negative integer represented as non-empty a singly linked list 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. 6 | 7 | Example: 8 | 9 | Input: 10 | 1->2->3 11 | 12 | Output: 13 | 1->2->4 14 | 15 | -------------------------------------------------------------------------------- /066.plus-one/plus-one.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def plusOne(self, digits): 3 | """ 4 | :type digits: List[int] 5 | :rtype: List[int] 6 | """ 7 | carry = 1 8 | for i in reversed(range(0, len(digits))): 9 | digit = (digits[i] + carry) % 10 10 | carry = 1 if digit < digits[i] else 0 11 | digits[i] = digit 12 | if carry == 1: 13 | return [1] + digits 14 | return digits 15 | -------------------------------------------------------------------------------- /233.number-of-digit-one/number-of-digit-one.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countDigitOne(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | m = 1 8 | ones = 0 9 | while m <= n: 10 | r = (n / m) % 10 11 | if r > 1: 12 | ones += m 13 | elif r == 1: 14 | ones += n % m + 1 15 | 16 | ones += (n / (m * 10)) * m 17 | m *= 10 18 | return ones 19 | -------------------------------------------------------------------------------- /560.subarray-sum-equals-k/subarray-sum-equals-k.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def subarraySum(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: int 7 | """ 8 | preSum = ans = 0 9 | visit = {0: 1} 10 | for i, n in enumerate(nums): 11 | preSum += n 12 | ans += visit.get(preSum - k, 0) 13 | visit[preSum] = visit.get(preSum, 0) + 1 14 | return ans 15 | -------------------------------------------------------------------------------- /611.valid-triangle-number/valid-triangle-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def triangleNumber(self, nums): 3 | ans = 0 4 | nums.sort() 5 | for i in range(2, len(nums)): 6 | start = 0 7 | end = i - 1 8 | while start < end: 9 | if nums[start] + nums[end] > nums[i]: 10 | ans += end - start 11 | end -= 1 12 | else: 13 | start += 1 14 | return ans 15 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /077.combinations/combinations.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def combine(self, n, k): 3 | if k == 1: 4 | return [[i] for i in range(1, n + 1)] 5 | elif k == n: 6 | return [[i for i in range(1, n + 1)]] 7 | else: 8 | rs = [] 9 | rs += self.combine(n - 1, k) 10 | part = self.combine(n - 1, k - 1) 11 | for ls in part: 12 | ls.append(n) 13 | rs += part 14 | return rs 15 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /168.excel-sheet-column-title/excel-sheet-column-title.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def convertToTitle(self, n): 3 | """ 4 | :type n: int 5 | :rtype: str 6 | """ 7 | ans = "" 8 | while n > 0: 9 | y = n % 26 10 | if y == 0: 11 | char = "Z" 12 | n -= 26 13 | else: 14 | char = chr(ord("A") + y - 1) 15 | ans += char 16 | n = n / 26 17 | return ans[::-1] 18 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /246.strobogrammatic-number/strobogrammatic-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isStrobogrammatic(self, num): 3 | """ 4 | :type num: str 5 | :rtype: bool 6 | """ 7 | start, end, legal = 0, len(num) - 1, "01689" 8 | while start <= end: 9 | if "".join(sorted(num[start] + num[end])) not in ["00", "11", "88", "69"]: 10 | return False 11 | start += 1 12 | end -= 1 13 | return True 14 | -------------------------------------------------------------------------------- /260.single-number-iii/single-number-iii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def singleNumber(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | xor = 0 8 | for num in nums: 9 | xor ^= num 10 | 11 | xor = xor & -xor 12 | a, b = 0, 0 13 | for num in nums: 14 | if num & xor: 15 | a ^= num 16 | else: 17 | b ^= num 18 | 19 | return a, b 20 | -------------------------------------------------------------------------------- /276.paint-fence/paint-fence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numWays(self, n, k): 3 | """ 4 | :type n: int 5 | :type k: int 6 | :rtype: int 7 | """ 8 | if n > 2 and k == 1: 9 | return 0 10 | if n < 2: 11 | return n * k 12 | pre = k * k 13 | ppre = k 14 | for i in range(2, n): 15 | tmp = pre 16 | pre = (k - 1) * (pre + ppre) 17 | ppre = tmp 18 | return pre 19 | -------------------------------------------------------------------------------- /539.minimum-time-difference/question.md: -------------------------------------------------------------------------------- 1 | Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes difference between any two time points in the list. 2 | 3 | Example 1: 4 | 5 | Input: ["23:59","00:00"] 6 | Output: 1 7 | 8 | 9 | 10 | Note: 11 | 12 | The number of time points in the given list is at least 2 and won't exceed 20000. 13 | The input time is legal and ranges from 00:00 to 23:59. 14 | 15 | -------------------------------------------------------------------------------- /560.subarray-sum-equals-k/question.md: -------------------------------------------------------------------------------- 1 | Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 2 | 3 | Example 1: 4 | 5 | Input:nums = [1,1,1], k = 2 6 | Output: 2 7 | 8 | 9 | 10 | Note: 11 | 12 | The length of the array is in range [1, 20,000]. 13 | The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. 14 | 15 | 16 | -------------------------------------------------------------------------------- /605.can-place-flowers/can-place-flowers.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canPlaceFlowers(self, flowerbed, n): 3 | """ 4 | :type flowerbed: List[int] 5 | :type n: int 6 | :rtype: bool 7 | """ 8 | ans = 0 9 | cnt = 1 10 | for plot in flowerbed: 11 | if plot == 0: 12 | cnt += 1 13 | else: 14 | ans += abs(cnt - 1) / 2 15 | cnt = 0 16 | return ans + cnt / 2 >= n 17 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /372.super-pow/question.md: -------------------------------------------------------------------------------- 1 | 2 | Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array. 3 | 4 | 5 | Example1: 6 | 7 | a = 2 8 | b = [3] 9 | 10 | Result: 8 11 | 12 | 13 | 14 | Example2: 15 | 16 | a = 2 17 | b = [1,0] 18 | 19 | Result: 1024 20 | 21 | 22 | 23 | Credits:Special thanks to @Stomach_ache for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /376.wiggle-subsequence/wiggle-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def wiggleMaxLength(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if not nums: 8 | return 0 9 | up = down = 1 10 | for i in range(1, len(nums)): 11 | if nums[i] > nums[i - 1]: 12 | up = down + 1 13 | elif nums[i] < nums[i - 1]: 14 | down = up + 1 15 | return max(up, down) 16 | -------------------------------------------------------------------------------- /452.minimum-number-of-arrows-to-burst-balloons/minimum-number-of-arrows-to-burst-balloons.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMinArrowShots(self, points): 3 | """ 4 | :type points: List[List[int]] 5 | :rtype: int 6 | """ 7 | ans = 0 8 | points.sort(key=lambda p: p[1]) 9 | end = float("-inf") 10 | for s, e in points: 11 | if s > end: 12 | ans += 1 13 | end = e 14 | return ans 15 | -------------------------------------------------------------------------------- /483.smallest-good-base/smallest-good-base.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | class Solution(object): 5 | def smallestGoodBase(self, n): 6 | """ 7 | :type n: str 8 | :rtype: str 9 | """ 10 | n = int(n) 11 | max_m = int(math.log(n, 2)) # Refer [7] 12 | for m in range(max_m, 1, -1): 13 | k = int(n ** m ** -1) 14 | if (k ** (m + 1) - 1) / (k - 1) == n: 15 | return str(k) 16 | return str(n - 1) 17 | -------------------------------------------------------------------------------- /493.reverse-pairs/reverse-pairs.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | 3 | 4 | class Solution(object): 5 | def reversePairs(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | n = len(nums) 11 | ans = 0 12 | bst = [] 13 | for num in nums: 14 | right = 2 * num 15 | idx = bisect.bisect_right(bst, right) 16 | ans += len(bst) - idx 17 | bisect.insort(bst, num) 18 | return ans 19 | -------------------------------------------------------------------------------- /551.student-attendance-record-i/student-attendance-record-i.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def checkRecord(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | a = l = 0 8 | for c in s: 9 | if c == "L": 10 | l += 1 11 | elif c == "A": 12 | a += 1 13 | l = 0 14 | else: 15 | l = 0 16 | if a > 1 or l > 2: 17 | return False 18 | return True 19 | -------------------------------------------------------------------------------- /557.reverse-words-in-a-string-iii/question.md: -------------------------------------------------------------------------------- 1 | Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. 2 | 3 | Example 1: 4 | 5 | Input: "Let's take LeetCode contest" 6 | Output: "s'teL ekat edoCteeL tsetnoc" 7 | 8 | 9 | 10 | Note: 11 | In the string, each word is separated by single space and there will not be any extra space in the string. 12 | -------------------------------------------------------------------------------- /660.remove-9/question.md: -------------------------------------------------------------------------------- 1 | Start from integer 1, remove any integer that contains 9 such as 9, 19, 29... 2 | 3 | So now, you will have a new integer sequence: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ... 4 | 5 | Given a positive integer n, you need to return the n-th integer after removing. Note that 1 will be the first integer. 6 | 7 | Example 1: 8 | 9 | Input: 9 10 | Output: 10 11 | 12 | 13 | 14 | 15 | Hint: n will not exceed 9 x 10^8. 16 | -------------------------------------------------------------------------------- /026.remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeDuplicates(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if len(nums) <= 1: 8 | return len(nums) 9 | slow = 0 10 | for i in range(1, len(nums)): 11 | if nums[i] != nums[slow]: 12 | slow += 1 13 | nums[slow] = nums[i] 14 | return slow + 1 15 | -------------------------------------------------------------------------------- /071.simplify-path/simplify-path.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def simplifyPath(self, path): 3 | """ 4 | :type path: str 5 | :rtype: str 6 | """ 7 | path = path.split("/") 8 | stack = [] 9 | for p in path: 10 | if p in ["", "."]: 11 | continue 12 | if p == "..": 13 | if stack: 14 | stack.pop() 15 | else: 16 | stack.append(p) 17 | return "/" + "/".join(stack) 18 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /263.ugly-number/ugly-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isUgly(self, n): 3 | """ 4 | :type num: int 5 | :rtype: bool 6 | """ 7 | if n <= 0: 8 | return False 9 | while n % 2 == 0 or n % 3 == 0 or n % 5 == 0: 10 | if n % 2 == 0: 11 | n /= 2 12 | if n % 3 == 0: 13 | n /= 3 14 | if n % 5 == 0: 15 | n /= 5 16 | if n == 1: 17 | return True 18 | return False 19 | -------------------------------------------------------------------------------- /390.elimination-game/elimination-game.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lastRemaining(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | count = n 8 | head = 1 9 | isFromLeft = True 10 | step = 1 11 | while count > 1: 12 | if isFromLeft or count % 2 == 1: 13 | head = head + step 14 | count /= 2 15 | step *= 2 16 | isFromLeft = not isFromLeft 17 | return head 18 | -------------------------------------------------------------------------------- /119.pascals-triangle-ii/pascals-triangle-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getRow(self, rowIndex): 3 | """ 4 | :type rowIndex: int 5 | :rtype: List[int] 6 | """ 7 | fact = [1] * (rowIndex + 1) 8 | ans = [1] * (rowIndex + 1) 9 | for i in range(1, rowIndex + 1): 10 | fact[i] = fact[i - 1] * i 11 | for i in range(1, rowIndex): 12 | ans[i] = fact[-1] / (fact[i] * fact[rowIndex - i]) 13 | return ans 14 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /315.count-of-smaller-numbers-after-self/count-of-smaller-numbers-after-self.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | 3 | 4 | class Solution(object): 5 | def countSmaller(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: List[int] 9 | """ 10 | ans = [] 11 | bst = [] 12 | for num in reversed(nums): 13 | idx = bisect.bisect_left(bst, num) 14 | ans.append(idx) 15 | bisect.insort(bst, num) 16 | return ans[::-1] 17 | -------------------------------------------------------------------------------- /356.line-reflection/line-reflection.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isReflected(self, points): 3 | """ 4 | :type points: List[List[int]] 5 | :rtype: bool 6 | """ 7 | if len(points) < 2: 8 | return True 9 | twoTimesMid = min(points)[0] + max(points)[0] 10 | d = set([(i, j) for i, j in points]) 11 | for i, j in points: 12 | if (twoTimesMid - i, j) not in d: 13 | return False 14 | return True 15 | -------------------------------------------------------------------------------- /387.first-unique-character-in-a-string/first-unique-character-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstUniqChar(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | letters = [0] * 26 8 | for c in s: 9 | ci = ord(c) - ord('a') 10 | letters[ci] += 1 11 | for i in range(0, len(s)): 12 | ci = ord(s[i]) - ord('a') 13 | if letters[ci] == 1: 14 | return i 15 | return -1 16 | -------------------------------------------------------------------------------- /402.remove-k-digits/remove-k-digits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeKdigits(self, num, k): 3 | """ 4 | :type num: str 5 | :type k: int 6 | :rtype: str 7 | """ 8 | stack = [] 9 | for c in num: 10 | while k > 0 and stack and stack[-1] > c: 11 | stack.pop() 12 | k -= 1 13 | stack.append(c) 14 | if k > 0: 15 | stack = stack[:-k] 16 | return "".join(stack).lstrip("0") or "0" 17 | -------------------------------------------------------------------------------- /187.repeated-dna-sequences/repeated-dna-sequences.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findRepeatedDnaSequences(self, s): 3 | """ 4 | :type s: str 5 | :rtype: List[str] 6 | """ 7 | d = {} 8 | ans = [] 9 | for i in range(len(s) - 9): 10 | key = s[i:i + 10] 11 | if key in d: 12 | d[key] += 1 13 | if d[key] == 2: 14 | ans.append(key) 15 | else: 16 | d[key] = 1 17 | return ans 18 | -------------------------------------------------------------------------------- /259.3sum-smaller/question.md: -------------------------------------------------------------------------------- 1 | Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target. 2 | 3 | For example, given nums = [-2, 0, 1, 3], and target = 2. 4 | 5 | Return 2. Because there are two triplets which sums are less than 2: 6 | 7 | [-2, 0, 1] 8 | [-2, 0, 3] 9 | 10 | 11 | Follow up: 12 | Could you solve it in O(n2) runtime? 13 | -------------------------------------------------------------------------------- /357.count-numbers-with-unique-digits/count-numbers-with-unique-digits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countNumbersWithUniqueDigits(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int4 6 | """ 7 | if n <= 1: 8 | return 10 ** n 9 | dp = [0] * (n + 1) 10 | dp[0] = 0 11 | dp[1] = 9 12 | k = 9 13 | for i in range(2, n + 1): 14 | dp[i] = max(dp[i - 1] * k, 0) 15 | k -= 1 16 | return sum(dp) + 1 17 | -------------------------------------------------------------------------------- /367.valid-perfect-square/question.md: -------------------------------------------------------------------------------- 1 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 2 | 3 | 4 | Note: Do not use any built-in library function such as sqrt. 5 | 6 | 7 | Example 1: 8 | 9 | Input: 16 10 | Returns: True 11 | 12 | 13 | 14 | Example 2: 15 | 16 | Input: 14 17 | Returns: False 18 | 19 | 20 | 21 | Credits:Special thanks to @elmirap for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /419.battleships-in-a-board/battleships-in-a-board.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countBattleships(self, board): 3 | """ 4 | :type board: List[List[str]] 5 | :rtype: int 6 | """ 7 | ans = 0 8 | for i in range(0, len(board)): 9 | for j in range(0, len(board[0])): 10 | if board[i][j] == "X" and (i == 0 or board[i - 1][j] != "X") and (j == 0 or board[i][j - 1] != "X"): 11 | ans += 1 12 | return ans 13 | -------------------------------------------------------------------------------- /442.find-all-duplicates-in-an-array/find-all-duplicates-in-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findDuplicates(self, nums): 3 | ans = [] 4 | for i in range(0, len(nums)): 5 | while nums[nums[i] - 1] != nums[i]: 6 | tmp = nums[nums[i] - 1] 7 | nums[nums[i] - 1] = nums[i] 8 | nums[i] = tmp 9 | for i in range(0, len(nums)): 10 | if i + 1 != nums[i]: 11 | ans.append(nums[i]) 12 | return ans 13 | -------------------------------------------------------------------------------- /453.minimum-moves-to-equal-array-elements/question.md: -------------------------------------------------------------------------------- 1 | Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1. 2 | 3 | Example: 4 | 5 | Input: 6 | [1,2,3] 7 | 8 | Output: 9 | 3 10 | 11 | Explanation: 12 | Only three moves are needed (remember each move increments two elements): 13 | 14 | [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 15 | 16 | -------------------------------------------------------------------------------- /498.diagonal-traverse/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. 3 | 4 | 5 | Example: 6 | 7 | Input: 8 | [ 9 | [ 1, 2, 3 ], 10 | [ 4, 5, 6 ], 11 | [ 7, 8, 9 ] 12 | ] 13 | Output: [1,2,4,7,5,3,6,8,9] 14 | Explanation: 15 | 16 | 17 | 18 | 19 | Note: 20 | 21 | The total number of elements of the given matrix will not exceed 10,000. 22 | 23 | -------------------------------------------------------------------------------- /525.contiguous-array/contiguous-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMaxLength(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | d = {0: -1} 8 | count = ans = 0 9 | delta = {1: -1, 0: 1} 10 | for i in range(len(nums)): 11 | count += delta.get(nums[i], 0) 12 | if count in d: 13 | ans = max(ans, i - d[count]) 14 | else: 15 | d[count] = i 16 | return ans 17 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /251.flatten-2d-vector/question.md: -------------------------------------------------------------------------------- 1 | 2 | Implement an iterator to flatten a 2d vector. 3 | 4 | 5 | For example, 6 | Given 2d vector = 7 | 8 | [ 9 | [1,2], 10 | [3], 11 | [4,5,6] 12 | ] 13 | 14 | 15 | 16 | By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6]. 17 | 18 | 19 | 20 | Follow up: 21 | As an added challenge, try to code it using only iterators in C++ or iterators in Java. 22 | -------------------------------------------------------------------------------- /330.patching-array/patching-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minPatches(self, nums, n): 3 | """ 4 | :type nums: List[int] 5 | :type n: int 6 | :rtype: int 7 | """ 8 | i = 0 9 | patches = 0 10 | miss = 1 11 | while miss <= n: 12 | if i < len(nums) and nums[i] <= miss: 13 | miss += nums[i] 14 | i += 1 15 | else: 16 | miss += miss 17 | patches += 1 18 | return patches 19 | -------------------------------------------------------------------------------- /377.combination-sum-iv/combination-sum-iv.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def combinationSum4(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: int 7 | """ 8 | dp = [0] * (target + 1) 9 | dp[0] = 1 10 | 11 | for i in range(1, target + 1): 12 | for j in range(1, len(nums) + 1): 13 | if i - nums[j - 1] >= 0: 14 | dp[i] += dp[i - nums[j - 1]] 15 | return dp[-1] 16 | -------------------------------------------------------------------------------- /507.perfect-number/question.md: -------------------------------------------------------------------------------- 1 | We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself. 2 | 3 | Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not. 4 | 5 | 6 | Example: 7 | 8 | Input: 28 9 | Output: True 10 | Explanation: 28 = 1 + 2 + 4 + 7 + 14 11 | 12 | 13 | 14 | Note: 15 | The input number n will not exceed 100,000,000. (1e8) 16 | -------------------------------------------------------------------------------- /633.sum-of-square-numbers/sum-of-square-numbers.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def judgeSquareSum(self, c): 3 | """ 4 | :type c: int 5 | :rtype: bool 6 | """ 7 | n = int(c ** 0.5) 8 | start = 0 9 | end = n 10 | while start <= end: 11 | mid = start ** 2 + end ** 2 12 | if mid == c: 13 | return True 14 | elif mid < c: 15 | start += 1 16 | else: 17 | end -= 1 18 | return False 19 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /161.one-edit-distance/one-edit-distance.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isOneEditDistance(self, s, t): 3 | """ 4 | :type s: str 5 | :type t: str 6 | :rtype: bool 7 | """ 8 | if len(s) >= len(t): 9 | i = 0 10 | while i < len(t) and s[i] == t[i]: 11 | i += 1 12 | return s != t and (s[i + 1:] == t[i:] if len(s) != len(t) else s[i + 1:] == t[i + 1:]) 13 | else: 14 | return self.isOneEditDistance(t, s) 15 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /349.intersection-of-two-arrays/intersection-of-two-arrays.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def intersection(self, nums1, nums2): 3 | """ 4 | :type nums1: List[int] 5 | :type nums2: List[int] 6 | :rtype: List[int] 7 | """ 8 | d = {} 9 | ans = [] 10 | for num in nums1: 11 | d[num] = d.get(num, 0) + 1 12 | 13 | for num in nums2: 14 | if num in d: 15 | ans.append(num) 16 | del d[num] 17 | return ans 18 | -------------------------------------------------------------------------------- /451.sort-characters-by-frequency/sort-characters-by-frequency.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution(object): 5 | def frequencySort(self, s): 6 | """ 7 | :type s: str 8 | :rtype: str 9 | """ 10 | d = Counter(s) 11 | buf = {} 12 | for k, v in d.items(): 13 | buf[v] = buf.get(v, "") + k * v 14 | ans = "" 15 | for i in reversed(range(0, len(s))): 16 | ans += buf.get(i, "") 17 | return ans 18 | -------------------------------------------------------------------------------- /554.brick-wall/brick-wall.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def leastBricks(self, wall): 3 | """ 4 | :type wall: List[List[int]] 5 | :rtype: int 6 | """ 7 | ans = len(wall) 8 | count = 0 9 | d = {} 10 | for w in wall: 11 | coverage = 0 12 | for brick in w[:-1]: 13 | coverage += brick 14 | d[coverage] = d.get(coverage, 0) + 1 15 | count = max(count, d.get(coverage, 0)) 16 | return ans - count 17 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /397.integer-replacement/integer-replacement.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def integerReplacement(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | ans = 0 8 | while n != 1: 9 | if n == 3: 10 | n -= 1 11 | elif n & 1: 12 | if ((n + 1) & n) <= ((n - 1) & (n - 2)): 13 | n += 1 14 | else: 15 | n -= 1 16 | else: 17 | n >>= 1 18 | ans += 1 19 | return ans 20 | -------------------------------------------------------------------------------- /517.super-washing-machines/super-washing-machines.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMinMoves(self, machines): 3 | """ 4 | :type machines: List[int] 5 | :rtype: int 6 | """ 7 | if sum(machines) % len(machines) != 0: 8 | return -1 9 | target = sum(machines) / len(machines) 10 | total = 0 11 | ans = 0 12 | for v in machines: 13 | total += target - v 14 | ans = max(ans, abs(total), v - target) 15 | return ans 16 | -------------------------------------------------------------------------------- /606.construct-string-from-binary-tree/construct-string-from-binary-tree.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def tree2str(self, t): 3 | """ 4 | :type t: TreeNode 5 | :rtype: str 6 | """ 7 | if not t: 8 | return "" 9 | res = "" 10 | left = self.tree2str(t.left) 11 | right = self.tree2str(t.right) 12 | if left or right: 13 | res += "(%s)" % left 14 | if right: 15 | res += "(%s)" % right 16 | return str(t.val) + res 17 | -------------------------------------------------------------------------------- /646.maximum-length-of-pair-chain/maximum-length-of-pair-chain.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLongestChain(self, pairs): 3 | """ 4 | :type pairs: List[List[int]] 5 | :rtype: int 6 | """ 7 | tails = [] 8 | for start, end in sorted(pairs): 9 | idx = bisect.bisect_left(tails, start) 10 | if idx == len(tails): 11 | tails.append(end) 12 | else: 13 | tails[idx] = min(tails[idx], end) 14 | return len(tails) 15 | -------------------------------------------------------------------------------- /030.substring-with-concatenation-of-all-words/question.md: -------------------------------------------------------------------------------- 1 | 2 | You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. 3 | 4 | 5 | 6 | For example, given: 7 | s: "barfoothefoobarman" 8 | words: ["foo", "bar"] 9 | 10 | 11 | 12 | You should return the indices: [0,9]. 13 | (order does not matter). 14 | -------------------------------------------------------------------------------- /089.gray-code/gray-code.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def grayCode(self, n): 3 | """ 4 | :type n: int 5 | :rtype: List[int] 6 | """ 7 | if n < 1: 8 | return [0] 9 | ans = [0] * (2 ** n) 10 | ans[1] = 1 11 | mask = 0x01 12 | i = 1 13 | while i < n: 14 | mask <<= 1 15 | for j in range(0, 2 ** i): 16 | root = (2 ** i) 17 | ans[root + j] = ans[root - j - 1] | mask 18 | i += 1 19 | return ans 20 | -------------------------------------------------------------------------------- /095.unique-binary-search-trees-ii/question.md: -------------------------------------------------------------------------------- 1 | Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n. 2 | 3 | 4 | For example, 5 | Given n = 3, your program should return all 5 unique BST's shown below. 6 | 7 | 8 | 1 3 3 2 1 9 | \ / / / \ \ 10 | 3 2 1 1 3 2 11 | / / \ \ 12 | 2 1 2 3 13 | 14 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /162.find-peak-element/find-peak-element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findPeakElement(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | start, end = 0, len(nums) - 1 8 | while start + 1 < end: 9 | mid = start + (end - start) / 2 10 | if nums[mid] < nums[mid + 1]: 11 | start = mid 12 | else: 13 | end = mid 14 | if nums[start] > nums[end]: 15 | return start 16 | return end 17 | -------------------------------------------------------------------------------- /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.) -------------------------------------------------------------------------------- /264.ugly-number-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Write a program to find the n-th ugly number. 3 | 4 | 5 | 6 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. 7 | 8 | 9 | 10 | Note that 1 is typically treated as an ugly number, and n does not exceed 1690. 11 | 12 | 13 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /322.coin-change/coin-change.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def coinChange(self, coins, amount): 3 | """ 4 | :type coins: List[int] 5 | :type amount: int 6 | :rtype: int 7 | """ 8 | 9 | dp = [float("inf")] * (amount + 1) 10 | dp[0] = 0 11 | for i in range(1, amount + 1): 12 | for coin in coins: 13 | if i - coin >= 0: 14 | dp[i] = min(dp[i], dp[i - coin] + 1) 15 | return dp[-1] if dp[-1] != float("inf") else -1 16 | -------------------------------------------------------------------------------- /564.find-the-closest-palindrome/question.md: -------------------------------------------------------------------------------- 1 | Given an integer n, find the closest integer (not including itself), which is a palindrome. 2 | 3 | The 'closest' is defined as absolute difference minimized between two integers. 4 | 5 | Example 1: 6 | 7 | Input: "123" 8 | Output: "121" 9 | 10 | 11 | 12 | Note: 13 | 14 | The input n is a positive integer represented by string, whose length will not exceed 18. 15 | If there is a tie, return the smaller one as answer. 16 | 17 | -------------------------------------------------------------------------------- /011.container-with-most-water/container-with-most-water.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxArea(self, height): 3 | """ 4 | :type height: List[int] 5 | :rtype: int 6 | """ 7 | ans = left = 0 8 | right = len(height) - 1 9 | while left < right: 10 | ans = max(ans, (right - left) * min(height[left], height[right])) 11 | if height[left] <= height[right]: 12 | left += 1 13 | else: 14 | right -= 1 15 | return ans 16 | -------------------------------------------------------------------------------- /042.trapping-rain-water/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. 3 | 4 | 5 | 6 | For example, 7 | Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 8 | 9 | 10 | 11 | 12 | The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /238.product-of-array-except-self/product-of-array-except-self.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # better way 3 | def productExceptSelf(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: List[int] 7 | """ 8 | dp = [1] * len(nums) 9 | for i in range(1, len(nums)): 10 | dp[i] = dp[i - 1] * nums[i - 1] 11 | prod = 1 12 | for i in reversed(range(0, len(nums))): 13 | dp[i] = dp[i] * prod 14 | prod *= nums[i] 15 | return dp 16 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /311.sparse-matrix-multiplication/question.md: -------------------------------------------------------------------------------- 1 | Given two sparse matrices A and B, return the result of AB. 2 | 3 | You may assume that A's column number is equal to B's row number. 4 | 5 | Example: 6 | 7 | 8 | A = [ 9 | [ 1, 0, 0], 10 | [-1, 0, 3] 11 | ] 12 | 13 | B = [ 14 | [ 7, 0, 0 ], 15 | [ 0, 0, 0 ], 16 | [ 0, 0, 1 ] 17 | ] 18 | 19 | 20 | | 1 0 0 | | 7 0 0 | | 7 0 0 | 21 | AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | 22 | | 0 0 1 | 23 | -------------------------------------------------------------------------------- /485.max-consecutive-ones/question.md: -------------------------------------------------------------------------------- 1 | Given a binary array, find the maximum number of consecutive 1s in this array. 2 | 3 | Example 1: 4 | 5 | Input: [1,1,0,1,1,1] 6 | Output: 3 7 | Explanation: The first two digits or the last three digits are consecutive 1s. 8 | The maximum number of consecutive 1s is 3. 9 | 10 | 11 | 12 | Note: 13 | 14 | The input array will only contain 0 and 1. 15 | The length of input array is a positive integer and will not exceed 10,000 16 | 17 | -------------------------------------------------------------------------------- /013.roman-to-integer/roman-to-integer.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def romanToInt(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | d = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} 8 | ans = 0 9 | for i in range(0, len(s) - 1): 10 | c = s[i] 11 | cafter = s[i + 1] 12 | if d[c] < d[cafter]: 13 | ans -= d[c] 14 | else: 15 | ans += d[c] 16 | ans += d[s[-1]] 17 | return ans 18 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /153.find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMin(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | start, end, mid = 0, len(nums) - 1, 0 8 | while start + 1 < end: 9 | mid = start + (end - start) / 2 10 | if nums[start] <= nums[mid]: 11 | start = mid 12 | else: 13 | end = mid 14 | return min(nums[0], nums[start], nums[end]) 15 | -------------------------------------------------------------------------------- /448.find-all-numbers-disappeared-in-an-array/question.md: -------------------------------------------------------------------------------- 1 | Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 2 | 3 | Find all the elements of [1, n] inclusive that do not appear in this array. 4 | 5 | Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. 6 | 7 | Example: 8 | 9 | Input: 10 | [4,3,2,7,8,2,3,1] 11 | 12 | Output: 13 | [5,6] 14 | 15 | -------------------------------------------------------------------------------- /455.assign-cookies/assign-cookies.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution(object): 5 | def findContentChildren(self, children, cookies): 6 | """ 7 | :type g: List[int] 8 | :type s: List[int] 9 | :rtype: int 10 | """ 11 | cookies.sort() 12 | children.sort() 13 | i = 0 14 | for cookie in cookies: 15 | if i >= len(children): 16 | break 17 | if children[i] <= cookie: 18 | i += 1 19 | return i 20 | -------------------------------------------------------------------------------- /500.keyboard-row/question.md: -------------------------------------------------------------------------------- 1 | Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: ["Hello", "Alaska", "Dad", "Peace"] 12 | Output: ["Alaska", "Dad"] 13 | 14 | 15 | 16 | Note: 17 | 18 | You may use one character in the keyboard more than once. 19 | You may assume the input string will only contain letters of alphabet. 20 | 21 | -------------------------------------------------------------------------------- /516.longest-palindromic-subsequence/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. 3 | 4 | 5 | Example 1: 6 | Input: 7 | 8 | "bbbab" 9 | 10 | Output: 11 | 12 | 4 13 | 14 | One possible longest palindromic subsequence is "bbbb". 15 | 16 | 17 | Example 2: 18 | Input: 19 | 20 | "cbbd" 21 | 22 | Output: 23 | 24 | 2 25 | 26 | One possible longest palindromic subsequence is "bb". 27 | -------------------------------------------------------------------------------- /125.valid-palindrome/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 3 | 4 | 5 | 6 | For example, 7 | "A man, a plan, a canal: Panama" is a palindrome. 8 | "race a car" is not a palindrome. 9 | 10 | 11 | 12 | Note: 13 | Have you consider that the string might be empty? This is a good question to ask during an interview. 14 | 15 | For the purpose of this problem, we define empty string as valid palindrome. 16 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /237.delete-node-in-a-linked-list/delete-node-in-a-linked-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def deleteNode(self, node): 9 | """ 10 | :type node: ListNode 11 | :rtype: void Do not return anything, modify node in-place instead. 12 | """ 13 | node.val = node.next.val 14 | node.next = node.next.next 15 | -------------------------------------------------------------------------------- /248.strobogrammatic-number-iii/question.md: -------------------------------------------------------------------------------- 1 | A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 2 | Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high. 3 | For example, 4 | Given low = "50", high = "100", return 3. Because 69, 88, and 96 are three strobogrammatic numbers. 5 | 6 | 7 | Note: 8 | Because the range might be a large number, the low and high numbers are represented as string. 9 | -------------------------------------------------------------------------------- /274.h-index/h-index.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def hIndex(self, citations): 3 | """ 4 | :type citations: List[int] 5 | :rtype: int 6 | """ 7 | n = len(citations) 8 | dp = [0] * (n + 1) 9 | for c in citations: 10 | if c > n: 11 | dp[n] += 1 12 | else: 13 | dp[c] += 1 14 | 15 | total = 0 16 | for i in reversed(range(1, len(dp))): 17 | total += dp[i] 18 | if total >= i: 19 | return i 20 | return 0 21 | -------------------------------------------------------------------------------- /301.remove-invalid-parentheses/question.md: -------------------------------------------------------------------------------- 1 | 2 | Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. 3 | 4 | Note: The input string may contain letters other than the parentheses ( and ). 5 | 6 | 7 | 8 | Examples: 9 | 10 | "()())()" -> ["()()()", "(())()"] 11 | "(a)())()" -> ["(a)()()", "(a())()"] 12 | ")(" -> [""] 13 | 14 | 15 | 16 | Credits:Special thanks to @hpplayer for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /356.line-reflection/question.md: -------------------------------------------------------------------------------- 1 | Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points. 2 | 3 | 4 | Example 1: 5 | 6 | 7 | Given points = [[1,1],[-1,1]], return true. 8 | 9 | 10 | 11 | Example 2: 12 | 13 | 14 | Given points = [[1,1],[-1,-1]], return false. 15 | 16 | 17 | Follow up: 18 | Could you do better than O(n2)? 19 | 20 | 21 | Credits:Special thanks to @memoryless for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /416.partition-equal-subset-sum/partition-equal-subset-sum.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canPartition(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: bool 6 | """ 7 | s = sum(nums) 8 | if s == 0: 9 | return True 10 | if s % 2 == 0: 11 | s, current = s / 2, 0 12 | for num in nums: 13 | current |= ((current or 1) << num) % (1 << (s + 1)) 14 | if current >= 1 << s: 15 | return True 16 | return False 17 | -------------------------------------------------------------------------------- /477.total-hamming-distance/total-hamming-distance.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def totalHammingDistance(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | ans = 0 8 | mask = 1 9 | for j in range(0, 32): 10 | ones = zeros = 0 11 | for num in nums: 12 | if num & mask: 13 | ones += 1 14 | else: 15 | zeros += 1 16 | ans += ones * zeros 17 | mask = mask << 1 18 | return ans 19 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /035.search-insert-position/search-insert-position.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def searchInsert(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: int 7 | """ 8 | lo = 0 9 | hi = len(nums) 10 | while lo < hi: 11 | mid = lo + (hi - lo) / 2 12 | if nums[mid] > target: 13 | hi = mid 14 | elif nums[mid] < target: 15 | lo = mid + 1 16 | else: 17 | return mid 18 | return lo 19 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /200.number-of-islands/question.md: -------------------------------------------------------------------------------- 1 | Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 2 | 3 | Example 1: 4 | 11110110101100000000 5 | Answer: 1 6 | Example 2: 7 | 11000110000010000011 8 | Answer: 3 9 | 10 | Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /223.rectangle-area/rectangle-area.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def computeArea(self, A, B, C, D, E, F, G, H): 3 | """ 4 | :type A: int 5 | :type B: int 6 | :type C: int 7 | :type D: int 8 | :type E: int 9 | :type F: int 10 | :type G: int 11 | :type H: int 12 | :rtype: int 13 | """ 14 | area = (C - A) * (D - B) + (G - E) * (H - F) 15 | overlap = max(min(C, G) - max(A, E), 0) * max(min(D, H) - max(B, F), 0) 16 | return area - overlap 17 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /243.shortest-word-distance/question.md: -------------------------------------------------------------------------------- 1 | Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. 2 | For example, 3 | Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. 4 | 5 | 6 | Given word1 = “coding”, word2 = “practice”, return 3. 7 | Given word1 = "makes", word2 = "coding", return 1. 8 | 9 | 10 | 11 | Note: 12 | You may assume that word1 does not equal to word2, and word1 and word2 are both in the list. 13 | -------------------------------------------------------------------------------- /265.paint-house-ii/paint-house-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minCostII(self, costs): 3 | """ 4 | :type costs: List[List[int]] 5 | :rtype: int 6 | """ 7 | if not costs: 8 | return 0 9 | dp = [[0] * len(costs[0]) for _ in range(0, len(costs))] 10 | dp[0] = costs[0] 11 | for i in range(1, len(costs)): 12 | for j in range(0, len(costs[0])): 13 | dp[i][j] = min(dp[i - 1][:j] + dp[i - 1][j + 1:]) + costs[i][j] 14 | return min(dp[-1]) 15 | -------------------------------------------------------------------------------- /339.nested-list-weight-sum/question.md: -------------------------------------------------------------------------------- 1 | Given a nested list of integers, return the sum of all integers in the list weighted by their depth. 2 | 3 | Each element is either an integer, or a list -- whose elements may also be integers or other lists. 4 | 5 | Example 1: 6 | Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at depth 1) 7 | 8 | Example 2: 9 | Given the list [1,[4,[6]]], return 27. (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4*2 + 6*3 = 27) 10 | -------------------------------------------------------------------------------- /383.ransom-note/ransom-note.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canConstruct(self, ransomNote, magazine): 3 | """ 4 | :type ransomNote: str 5 | :type magazine: str 6 | :rtype: bool 7 | """ 8 | letters = [0] * 26 9 | for c in magazine: 10 | letters[ord(c) - ord('a')] += 1 11 | 12 | for c in ransomNote: 13 | if letters[ord(c) - ord('a')] == 0: 14 | return False 15 | else: 16 | letters[ord(c) - ord('a')] -= 1 17 | return True 18 | -------------------------------------------------------------------------------- /544.output-contest-matches/output-contest-matches.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findContestMatch(self, n): 3 | """ 4 | :type n: int 5 | :rtype: str 6 | """ 7 | 8 | def helper(schedule): 9 | if len(schedule) == 1: 10 | return schedule[0] 11 | m = [] 12 | for i in range(len(schedule) / 2): 13 | m.append("({},{})".format(schedule[i], schedule[-i - 1])) 14 | return helper(m) 15 | 16 | return helper(map(str, range(1, n + 1))) 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. -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /157.read-n-characters-given-read4/question.md: -------------------------------------------------------------------------------- 1 | 2 | The API: int read4(char *buf) reads 4 characters at a time from a file. 3 | 4 | 5 | 6 | The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. 7 | 8 | 9 | 10 | By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file. 11 | 12 | 13 | 14 | Note: 15 | The read function will only be called once for each test case. 16 | -------------------------------------------------------------------------------- /316.remove-duplicate-letters/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. 3 | 4 | 5 | 6 | Example: 7 | 8 | 9 | Given "bcabc" 10 | Return "abc" 11 | 12 | 13 | Given "cbacdcbc" 14 | Return "acdb" 15 | 16 | 17 | Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /167.two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def twoSum(self, nums, target): 3 | """ 4 | :type numbers: List[int] 5 | :type target: int 6 | :rtype: List[int] 7 | """ 8 | start, end = 0, len(nums) - 1 9 | while start < end: 10 | s = nums[start] + nums[end] 11 | if s > target: 12 | end -= 1 13 | elif s < target: 14 | start += 1 15 | else: 16 | return (start + 1, end + 1) 17 | -------------------------------------------------------------------------------- /179.largest-number/largest-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param {integer[]} nums 3 | # @return {string} 4 | def largestNumber(self, nums): 5 | def cmpFunc(a, b): 6 | stra, strb = str(a), str(b) 7 | if stra + strb < strb + stra: 8 | return -1 9 | elif stra + strb > strb + stra: 10 | return 1 11 | else: 12 | return 0 13 | 14 | nums.sort(cmp=cmpFunc, reverse=True) 15 | return "".join(str(num) for num in nums) if sum(nums) != 0 else "0" 16 | -------------------------------------------------------------------------------- /199.binary-tree-right-side-view/question.md: -------------------------------------------------------------------------------- 1 | Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. 2 | 3 | 4 | For example: 5 | Given the following binary tree, 6 | 7 | 1 <--- 8 | / \ 9 | 2 3 <--- 10 | \ \ 11 | 5 4 <--- 12 | 13 | 14 | 15 | You should return [1, 3, 4]. 16 | 17 | 18 | Credits:Special thanks to @amrsaqr for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /235.lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lowestCommonAncestor(self, root, p, q): 3 | """ 4 | :type root: TreeNode 5 | :type p: TreeNode 6 | :type q: TreeNode 7 | :rtype: TreeNode 8 | """ 9 | a, b = sorted([p.val, q.val]) 10 | while not a <= root.val <= b: 11 | if a > root.val: 12 | root = root.right 13 | else: 14 | root = root.left 15 | return root 16 | -------------------------------------------------------------------------------- /275.h-index-ii/h-index-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def hIndex(self, citations): 3 | """ 4 | :type citations: List[int] 5 | :rtype: int 6 | """ 7 | if not citations: 8 | return 0 9 | n = len(citations) 10 | start, end = 0, n - 1 11 | while start < end: 12 | mid = start + (end - start) / 2 13 | if citations[mid] >= n - mid: 14 | end = mid 15 | else: 16 | start = mid + 1 17 | return n - start if citations[start] != 0 else 0 18 | -------------------------------------------------------------------------------- /392.is-subsequence/is-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isSubsequence(self, s, t): 3 | """ 4 | :type s: str 5 | :type t: str 6 | :rtype: bool 7 | """ 8 | d = collections.defaultdict(list) 9 | for i, c in enumerate(t): 10 | d[c].append(i) 11 | start = 0 12 | for c in s: 13 | idx = bisect.bisect_left(d[c], start) 14 | if len(d[c]) == 0 or idx >= len(d[c]): 15 | return False 16 | start = d[c][idx] + 1 17 | return True 18 | -------------------------------------------------------------------------------- /530.minimum-absolute-difference-in-bst/question.md: -------------------------------------------------------------------------------- 1 | Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. 2 | 3 | 4 | Example: 5 | 6 | Input: 7 | 8 | 1 9 | \ 10 | 3 11 | / 12 | 2 13 | 14 | Output: 15 | 1 16 | 17 | Explanation: 18 | The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3). 19 | 20 | 21 | 22 | 23 | Note: 24 | There are at least two nodes in this BST. 25 | -------------------------------------------------------------------------------- /566.reshape-the-matrix/reshape-the-matrix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def matrixReshape(self, nums, r, c): 3 | """ 4 | :type nums: List[List[int]] 5 | :type r: int 6 | :type c: int 7 | :rtype: List[List[int]] 8 | """ 9 | if r * c != len(nums) * len(nums[0]): 10 | return nums 11 | m = len(nums) 12 | n = len(nums[0]) 13 | ans = [[0] * c for _ in range(r)] 14 | for i in range(r * c): 15 | ans[i / c][i % c] = nums[i / n][i % n] 16 | return ans 17 | -------------------------------------------------------------------------------- /659.split-array-into-consecutive-subsequences/split-array-into-consecutive-subsequences.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPossible(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: bool 6 | """ 7 | d = collections.defaultdict(list) 8 | for num in nums: 9 | if d[num - 1]: 10 | heapq.heappush(d[num], heapq.heappop(d[num - 1]) + 1) 11 | else: 12 | heapq.heappush(d[num], 1) 13 | return not any(length < 3 for length in sum(d.values(), [])) 14 | -------------------------------------------------------------------------------- /158.read-n-characters-given-read4-ii-call-multiple-times/question.md: -------------------------------------------------------------------------------- 1 | 2 | The API: int read4(char *buf) reads 4 characters at a time from a file. 3 | 4 | 5 | 6 | The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. 7 | 8 | 9 | 10 | By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file. 11 | 12 | 13 | 14 | Note: 15 | The read function may be called multiple times. 16 | -------------------------------------------------------------------------------- /198.house-robber/house-robber.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def rob(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if len(nums) == 0: 8 | return 0 9 | if len(nums) <= 2: 10 | return max(nums) 11 | dp = [0 for i in range(0, 2)] 12 | dp[0] = nums[0] 13 | dp[1] = max(nums[1], nums[0]) 14 | for i in range(2, len(nums)): 15 | dp[i % 2] = max(dp[(i - 1) % 2], dp[(i - 2) % 2] + nums[i]) 16 | return dp[(len(nums) - 1) % 2] 17 | -------------------------------------------------------------------------------- /264.ugly-number-ii/ugly-number-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def nthUglyNumber(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | dp = [0] * (n + 1) 8 | dp[1] = 1 9 | i2 = i3 = i5 = 1 10 | for i in range(2, n + 1): 11 | dp[i] = min(dp[i2] * 2, dp[i3] * 3, dp[i5] * 5) 12 | if dp[i] == dp[i2] * 2: 13 | i2 += 1 14 | if dp[i] == dp[i3] * 3: 15 | i3 += 1 16 | if dp[i] == dp[i5] * 5: 17 | i5 += 1 18 | return dp[-1] 19 | -------------------------------------------------------------------------------- /343.integer-break/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. 3 | 4 | 5 | 6 | For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4). 7 | 8 | 9 | 10 | Note: You may assume that n is not less than 2 and not larger than 58. 11 | 12 | 13 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /412.fizz-buzz/fizz-buzz.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def fizzBuzz(self, n): 3 | """ 4 | :type n: int 5 | :rtype: List[str] 6 | """ 7 | ans = [] 8 | for i in range(1, n + 1): 9 | stmt1 = i % 3 == 0 10 | stmt2 = i % 5 == 0 11 | if stmt1 and stmt2: 12 | ans.append("FizzBuzz") 13 | elif stmt1: 14 | ans.append("Fizz") 15 | elif stmt2: 16 | ans.append("Buzz") 17 | else: 18 | ans.append(str(i)) 19 | 20 | return ans 21 | -------------------------------------------------------------------------------- /504.base-7/base-7.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def convertToBase7(self, num): 3 | """ 4 | :type num: int 5 | :rtype: str 6 | """ 7 | 8 | def convertHelper(num, base): 9 | sign = "" 10 | if num < 0: 11 | sign = "-" 12 | num = abs(num) 13 | ans = 0 14 | unit = 1 15 | while num: 16 | ans += (num % base) * unit 17 | num /= base 18 | unit *= 10 19 | return sign + str(ans) 20 | 21 | return convertHelper(num, 7) 22 | -------------------------------------------------------------------------------- /643.maximum-average-subarray-i/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value. 3 | 4 | 5 | Example 1: 6 | 7 | Input: [1,12,-5,-6,50,3], k = 4 8 | Output: 12.75 9 | Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75 10 | 11 | 12 | 13 | Note: 14 | 15 | 1 <= k <= n <= 30,000. 16 | Elements of the given array will be in the range [-10,000, 10,000]. 17 | 18 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /104.maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def maxDepth(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: int 13 | """ 14 | if not root: 15 | return 0 16 | return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 17 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /186.reverse-words-in-a-string-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. 3 | 4 | 5 | 6 | The input string does not contain leading or trailing spaces and the words are always separated by a single space. 7 | 8 | 9 | 10 | For example, 11 | Given s = "the sky is blue", 12 | return "blue is sky the". 13 | 14 | 15 | 16 | Could you do it in-place without allocating extra space? 17 | 18 | 19 | Related problem: Rotate Array -------------------------------------------------------------------------------- /202.happy-number/happy-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isHappy(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | record = {} 8 | sq_sum = 0 9 | while n != 1: 10 | sq_sum = 0 11 | sub_num = n 12 | while sub_num > 0: 13 | sq_sum += (sub_num % 10) * (sub_num % 10) 14 | sub_num /= 10 15 | if sq_sum in record: 16 | return False 17 | else: 18 | record[sq_sum] = 1 19 | n = sq_sum 20 | return True 21 | -------------------------------------------------------------------------------- /325.maximum-size-subarray-sum-equals-k/maximum-size-subarray-sum-equals-k.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxSubArrayLen(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: int 7 | """ 8 | d = {0: -1} 9 | maxLen = 0 10 | _sum = 0 11 | for i in range(0, len(nums)): 12 | _sum += nums[i] 13 | if _sum not in d: 14 | d[_sum] = i 15 | if _sum - k in d: 16 | maxLen = max(maxLen, i - d[_sum - k]) 17 | return maxLen 18 | -------------------------------------------------------------------------------- /396.rotate-function/rotate-function.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxRotateFunction(self, A): 3 | """ 4 | :type A: List[int] 5 | :rtype: int 6 | """ 7 | if not A: 8 | return 0 9 | 10 | sumA = sum(A) 11 | fk = 0 12 | n = len(A) 13 | for i, num in enumerate(A): 14 | fk += i * num 15 | idx = n - 1 16 | ans = float("-inf") 17 | for _ in range(n): 18 | fk += sumA - n * A[idx] 19 | ans = max(ans, fk) 20 | idx -= 1 21 | return ans 22 | -------------------------------------------------------------------------------- /493.reverse-pairs/question.md: -------------------------------------------------------------------------------- 1 | Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j]. 2 | 3 | You need to return the number of important reverse pairs in the given array. 4 | 5 | Example1: 6 | 7 | Input: [1,3,2,3,1] 8 | Output: 2 9 | 10 | 11 | Example2: 12 | 13 | Input: [2,4,3,5,1] 14 | Output: 3 15 | 16 | 17 | Note: 18 | 19 | The length of the given array will not exceed 50,000. 20 | All the numbers in the input array are in the range of 32-bit integer. 21 | 22 | -------------------------------------------------------------------------------- /503.next-greater-element-ii/next-greater-element-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def nextGreaterElements(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | ans = [-1] * len(nums) 8 | n = len(nums) 9 | stack = [] 10 | nums *= 2 11 | for i, num in enumerate(nums): 12 | while stack and nums[stack[-1]] < num: 13 | top = stack.pop() 14 | if top < n: 15 | ans[top] = num 16 | stack.append(i) 17 | return ans 18 | -------------------------------------------------------------------------------- /538.convert-bst-to-greater-tree/question.md: -------------------------------------------------------------------------------- 1 | Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. 2 | 3 | 4 | Example: 5 | 6 | Input: The root of a Binary Search Tree like this: 7 | 5 8 | / \ 9 | 2 13 10 | 11 | Output: The root of a Greater Tree like this: 12 | 18 13 | / \ 14 | 20 13 15 | 16 | -------------------------------------------------------------------------------- /552.student-attendance-record-ii/student-attendance-record-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def checkRecord(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | M = 10 ** 9 + 7 8 | dp = [0] * (n + 1) 9 | dp[:3] = [1, 2, 4] 10 | 11 | for i in range(3, n + 1): 12 | dp[i] = (dp[i - 1] + dp[i - 2] + dp[i - 3]) % M 13 | ans = dp[n] 14 | 15 | for i in range(1, n + 1): 16 | ans += (dp[i - 1] * dp[n - i]) % M 17 | ans %= M 18 | return ans % M 19 | -------------------------------------------------------------------------------- /565.array-nesting/array-nesting.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def arrayNesting(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | cache = [0] * len(nums) 8 | ans = 0 9 | for i, start in enumerate(nums): 10 | if cache[i]: 11 | continue 12 | p = start 13 | length = 1 14 | while nums[p] != start: 15 | cache[nums[p]] = 1 16 | p = nums[p] 17 | length += 1 18 | ans = max(ans, length) 19 | return ans 20 | -------------------------------------------------------------------------------- /645.set-mismatch/set-mismatch.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findErrorNums(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | ans = [-1, -1] 8 | diff = diffSquare = 0 9 | for i, num in enumerate(nums): 10 | diff += i + 1 - num 11 | diffSquare += (i + 1) ** 2 - num ** 2 12 | ans[1] = (diffSquare / diff + diff) / 2 13 | ans[0] = ans[1] - diff 14 | ans.sort() 15 | if diff > 0: 16 | return ans 17 | return ans[::-1] 18 | -------------------------------------------------------------------------------- /096.unique-binary-search-trees/unique-binary-search-trees.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def _numTrees(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | dp = [0] * (n + 1) 8 | dp[0] = dp[1] = 1 9 | for i in range(2, n + 1): 10 | for j in range(1, i + 1): 11 | dp[i] += dp[j - 1] * dp[i - j] 12 | return dp[-1] 13 | 14 | def numTrees(self, n): 15 | ans = 1 16 | for i in range(1, n + 1): 17 | ans = ans * (n + i) / i 18 | return ans / (n + 1) 19 | -------------------------------------------------------------------------------- /115.distinct-subsequences/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a string S and a string T, count the number of distinct subsequences of S which equals T. 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 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /378.kth-smallest-element-in-a-sorted-matrix/question.md: -------------------------------------------------------------------------------- 1 | Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. 2 | 3 | 4 | Note that it is the kth smallest element in the sorted order, not the kth distinct element. 5 | 6 | 7 | Example: 8 | 9 | matrix = [ 10 | [ 1, 5, 9], 11 | [10, 11, 13], 12 | [12, 13, 15] 13 | ], 14 | k = 8, 15 | 16 | return 13. 17 | 18 | 19 | 20 | Note: 21 | You may assume k is always valid, 1 ≤ k ≤ n2. -------------------------------------------------------------------------------- /400.nth-digit/question.md: -------------------------------------------------------------------------------- 1 | Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 2 | 3 | Note: 4 | n is positive and will fit within the range of a 32-bit signed integer (n < 231). 5 | 6 | 7 | Example 1: 8 | 9 | Input: 10 | 3 11 | 12 | Output: 13 | 3 14 | 15 | 16 | 17 | Example 2: 18 | 19 | Input: 20 | 11 21 | 22 | Output: 23 | 0 24 | 25 | Explanation: 26 | The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. 27 | 28 | -------------------------------------------------------------------------------- /461.hamming-distance/question.md: -------------------------------------------------------------------------------- 1 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 2 | 3 | Given two integers x and y, calculate the Hamming distance. 4 | 5 | Note: 6 | 0 ≤ x, y < 231. 7 | 8 | 9 | Example: 10 | 11 | Input: x = 1, y = 4 12 | 13 | Output: 2 14 | 15 | Explanation: 16 | 1 (0 0 0 1) 17 | 4 (0 1 0 0) 18 | ↑ ↑ 19 | 20 | The above arrows point to positions where the corresponding bits are different. 21 | 22 | -------------------------------------------------------------------------------- /484.find-permutation/find-permutation.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findPermutation(self, s): 3 | """ 4 | :type s: str 5 | :rtype: List[int] 6 | """ 7 | ans = range(1, len(s) + 2) 8 | cnt = 0 9 | for i in range(len(s)): 10 | if s[i] == "D": 11 | cnt += 1 12 | else: 13 | ans[i - cnt:i + 1] = ans[i - cnt:i + 1][::-1] 14 | cnt = 0 15 | if s[-1] == "D": 16 | ans[len(s) - cnt:len(s) + 1] = ans[len(s) - cnt:len(s) + 1][::-1] 17 | return ans 18 | -------------------------------------------------------------------------------- /125.valid-palindrome/valid-palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPalindrome(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | start, end = 0, len(s) - 1 8 | while start < end: 9 | if not s[start].isalnum(): 10 | start += 1 11 | continue 12 | if not s[end].isalnum(): 13 | end -= 1 14 | continue 15 | if s[start].lower() != s[end].lower(): 16 | return False 17 | start += 1 18 | end -= 1 19 | return True 20 | -------------------------------------------------------------------------------- /278.first-bad-version/first-bad-version.py: -------------------------------------------------------------------------------- 1 | # The isBadVersion API is already defined for you. 2 | # @param version, an integer 3 | # @return a bool 4 | # def isBadVersion(version): 5 | 6 | class Solution(object): 7 | def firstBadVersion(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | lo = 1 13 | hi = n 14 | while lo < hi: 15 | mid = lo + (hi - lo) / 2 16 | if isBadVersion(mid): 17 | hi = mid 18 | else: 19 | lo = mid + 1 20 | return lo 21 | -------------------------------------------------------------------------------- /354.russian-doll-envelopes/question.md: -------------------------------------------------------------------------------- 1 | You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope. 2 | 3 | 4 | What is the maximum number of envelopes can you Russian doll? (put one inside other) 5 | 6 | 7 | Example: 8 | Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). 9 | -------------------------------------------------------------------------------- /513.find-bottom-left-tree-value/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a binary tree, find the leftmost value in the last row of the tree. 3 | 4 | 5 | Example 1: 6 | 7 | Input: 8 | 9 | 2 10 | / \ 11 | 1 3 12 | 13 | Output: 14 | 1 15 | 16 | 17 | 18 | Example 2: 19 | 20 | Input: 21 | 22 | 1 23 | / \ 24 | 2 3 25 | / / \ 26 | 4 5 6 27 | / 28 | 7 29 | 30 | Output: 31 | 7 32 | 33 | 34 | 35 | Note: 36 | You may assume the tree (i.e., the given root node) is not NULL. 37 | -------------------------------------------------------------------------------- /520.detect-capital/detect-capital.py: -------------------------------------------------------------------------------- 1 | import string 2 | 3 | 4 | class Solution(object): 5 | def detectCapitalUse(self, word): 6 | """ 7 | :type word: str 8 | :rtype: bool 9 | """ 10 | ud = set(string.uppercase) 11 | ld = set(string.lowercase) 12 | n = len(word) 13 | cap = 0 14 | for c in word: 15 | if c in ud: 16 | cap += 1 17 | if cap == n: 18 | return True 19 | if cap == 1 and word[0] in ud: 20 | return True 21 | return False if cap > 0 else True 22 | -------------------------------------------------------------------------------- /609.find-duplicate-file-in-system/find-duplicate-file-in-system.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findDuplicate(self, paths): 3 | """ 4 | :type paths: List[str] 5 | :rtype: List[List[str]] 6 | """ 7 | d = collections.defaultdict(list) 8 | for path in paths: 9 | raw = path.split(" ") 10 | dirPath = raw[0] 11 | for data in raw[1:]: 12 | name, sign = data.split("(") 13 | d[sign].append(dirPath + "/" + name) 14 | return filter(lambda x: len(x) > 1, d.values()) 15 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /074.search-a-2d-matrix/question.md: -------------------------------------------------------------------------------- 1 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 2 | 3 | 4 | 5 | Integers in each row are sorted from left to right. 6 | The first integer of each row is greater than the last integer of the previous row. 7 | 8 | 9 | 10 | 11 | For example, 12 | 13 | Consider the following matrix: 14 | 15 | 16 | [ 17 | [1, 3, 5, 7], 18 | [10, 11, 16, 20], 19 | [23, 30, 34, 50] 20 | ] 21 | 22 | 23 | Given target = 3, return true. -------------------------------------------------------------------------------- /446.arithmetic-slices-ii-subsequence/arithmetic-slices-ii-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numberOfArithmeticSlices(self, A): 3 | """ 4 | :type A: List[int] 5 | :rtype: int 6 | """ 7 | ans = 0 8 | dp = [collections.defaultdict(int) for _ in A] 9 | for i in range(len(A)): 10 | for j in range(i): 11 | diff = A[i] - A[j] 12 | dp[i][diff] += 1 13 | if diff in dp[j]: 14 | dp[i][diff] += dp[j][diff] 15 | ans += dp[j][diff] 16 | return ans 17 | -------------------------------------------------------------------------------- /467.unique-substrings-in-wraparound-string/unique-substrings-in-wraparound-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findSubstringInWraproundString(self, p): 3 | """ 4 | :type p: str 5 | :rtype: int 6 | """ 7 | d = {} 8 | cnt = 0 9 | for i in range(len(p)): 10 | if i > 0 and (ord(p[i]) - ord(p[i - 1]) == 1 or ord(p[i - 1]) - ord(p[i]) == 25): 11 | cnt += 1 12 | else: 13 | cnt = 1 14 | d[ord(p[i])] = max(d.get(ord(p[i]), 0), cnt) 15 | 16 | return sum(d.values()) 17 | -------------------------------------------------------------------------------- /482.license-key-formatting/license-key-formatting.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def licenseKeyFormatting(self, S, K): 3 | """ 4 | :type S: str 5 | :type K: int 6 | :rtype: str 7 | """ 8 | s = S.split("-") 9 | s = "".join(s) 10 | n = len(s) 11 | start = n % K 12 | res = [] 13 | if start != 0: 14 | res.append(s[:start].upper()) 15 | for k in range(0, (len(s) - start) / K): 16 | res.append(s[start:start + K].upper()) 17 | start += K 18 | return "-".join(res) 19 | -------------------------------------------------------------------------------- /593.valid-square/valid-square.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def validSquare(self, p1, p2, p3, p4): 3 | """ 4 | :type p1: List[int] 5 | :type p2: List[int] 6 | :type p3: List[int] 7 | :type p4: List[int] 8 | :rtype: bool 9 | """ 10 | dist = lambda a, b: ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) 11 | sideLens = set([dist(p1, p2), dist(p1, p3), dist(p1, p4), dist(p2, p3), dist(p2, p4), dist(p3, p4)]) 12 | if len(sideLens) != 2 or 0 in sideLens: 13 | return False 14 | return True 15 | -------------------------------------------------------------------------------- /628.maximum-product-of-three-numbers/question.md: -------------------------------------------------------------------------------- 1 | Given an integer array, find three numbers whose product is maximum and output the maximum product. 2 | 3 | Example 1: 4 | 5 | Input: [1,2,3] 6 | Output: 6 7 | 8 | 9 | 10 | Example 2: 11 | 12 | Input: [1,2,3,4] 13 | Output: 24 14 | 15 | 16 | 17 | Note: 18 | 19 | The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. 20 | Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. 21 | 22 | -------------------------------------------------------------------------------- /637.average-of-levels-in-binary-tree/question.md: -------------------------------------------------------------------------------- 1 | Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. 2 | 3 | Example 1: 4 | 5 | Input: 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | Output: [3, 14.5, 11] 12 | Explanation: 13 | The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. 14 | 15 | 16 | 17 | Note: 18 | 19 | The range of node's value is in the range of 32-bit signed integer. 20 | 21 | -------------------------------------------------------------------------------- /120.triangle/question.md: -------------------------------------------------------------------------------- 1 | Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 2 | 3 | 4 | For example, given the following triangle 5 | 6 | [ 7 | [2], 8 | [3,4], 9 | [6,5,7], 10 | [4,1,8,3] 11 | ] 12 | 13 | 14 | 15 | The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 16 | 17 | 18 | 19 | Note: 20 | Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. 21 | -------------------------------------------------------------------------------- /123.best-time-to-buy-and-sell-stock-iii/best-time-to-buy-and-sell-stock-iii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProfit(self, prices): 3 | """ 4 | :type prices: List[int] 5 | :rtype: int 6 | """ 7 | buy1 = buy2 = float("-inf") 8 | sell1 = sell2 = 0 9 | 10 | for i in range(len(prices)): 11 | sell1 = max(prices[i] + buy1, sell1) 12 | buy1 = max(buy1, -prices[i]) 13 | sell2 = max(sell2, prices[i] + buy2) 14 | buy2 = max(sell1 - prices[i], buy2) 15 | return max(sell1, sell2) 16 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /135.candy/candy.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def candy(self, ratings): 3 | """ 4 | :type ratings: List[int] 5 | :rtype: int 6 | """ 7 | n = len(ratings) 8 | left = [1] * n 9 | ans = 0 10 | for i in range(1, n): 11 | if ratings[i] > ratings[i - 1]: 12 | left[i] = left[i - 1] + 1 13 | ans = left[-1] 14 | for i in reversed(range(0, n - 1)): 15 | if ratings[i] > ratings[i + 1]: 16 | left[i] = max(left[i], left[i + 1] + 1) 17 | ans += left[i] 18 | return ans 19 | -------------------------------------------------------------------------------- /272.closest-binary-search-tree-value-ii/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target. 3 | 4 | Note: 5 | 6 | Given target value is a floating point. 7 | You may assume k is always valid, that is: k ≤ total nodes. 8 | You are guaranteed to have only one unique set of k values in the BST that are closest to the target. 9 | 10 | Follow up: 11 | Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)? 12 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /311.sparse-matrix-multiplication/sparse-matrix-multiplication.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def multiply(self, A, B): 3 | """ 4 | :type A: List[List[int]] 5 | :type B: List[List[int]] 6 | :rtype: List[List[int]] 7 | """ 8 | ret = [[0 for j in range(len(B[0]))] for i in range(len(A))] 9 | 10 | for i, row in enumerate(A): 11 | for k, a in enumerate(row): 12 | if a: 13 | for j, b in enumerate(B[k]): 14 | if b: 15 | ret[i][j] += a * b 16 | return ret 17 | -------------------------------------------------------------------------------- /394.decode-string/decode-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def decodeString(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | num = "" 8 | stack = [["", 1]] 9 | for c in s: 10 | if c in "0123456789": 11 | num += c 12 | elif c == "[": 13 | stack.append(["", int(num)]) 14 | num = "" 15 | elif c == "]": 16 | ss, k = stack.pop() 17 | stack[-1][0] += ss * k 18 | else: 19 | stack[-1][0] += c 20 | return stack[-1][0] 21 | -------------------------------------------------------------------------------- /409.longest-palindrome/question.md: -------------------------------------------------------------------------------- 1 | Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. 2 | 3 | This is case sensitive, for example "Aa" is not considered a palindrome here. 4 | 5 | Note: 6 | Assume the length of given string will not exceed 1,010. 7 | 8 | 9 | Example: 10 | 11 | Input: 12 | "abccccdd" 13 | 14 | Output: 15 | 7 16 | 17 | Explanation: 18 | One longest palindrome that can be built is "dccaccd", whose length is 7. 19 | 20 | -------------------------------------------------------------------------------- /564.find-the-closest-palindrome/find-the-closest-palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def nearestPalindromic(self, n): 3 | """ 4 | :type n: str 5 | :rtype: str 6 | """ 7 | l = len(n) 8 | cands = set([str(10 ** l + 1), str(10 ** (l - 1) - 1)]) 9 | prefix = int(n[:(l + 1) / 2]) 10 | for half in map(str, [prefix - 1, prefix, prefix + 1]): 11 | cands.add(half + [half, half[:-1]][l & 1][::-1]) 12 | cands.discard(n) 13 | return min(cands, key=lambda x: (abs(int(x) - int(n)), int(x))) 14 | -------------------------------------------------------------------------------- /076.minimum-window-substring/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). 3 | 4 | 5 | 6 | For example, 7 | S = "ADOBECODEBANC" 8 | T = "ABC" 9 | 10 | 11 | Minimum window is "BANC". 12 | 13 | 14 | 15 | Note: 16 | If there is no such window in S that covers all characters in T, return the empty string "". 17 | 18 | 19 | If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. 20 | -------------------------------------------------------------------------------- /100.same-tree/same-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def isSameTree(self, p, q): 10 | """ 11 | :type p: TreeNode 12 | :type q: TreeNode 13 | :rtype: bool 14 | """ 15 | if not p or not q: 16 | return p == q 17 | return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 18 | -------------------------------------------------------------------------------- /141.linked-list-cycle/linked-list-cycle.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def hasCycle(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: bool 12 | """ 13 | fast = slow = head 14 | while fast and fast.next: 15 | fast = fast.next.next 16 | slow = slow.next 17 | if slow == fast: 18 | return True 19 | return False 20 | -------------------------------------------------------------------------------- /259.3sum-smaller/3sum-smaller.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def threeSumSmaller(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: int 7 | """ 8 | ans = 0 9 | nums.sort() 10 | for i in range(0, len(nums)): 11 | start, end = i + 1, len(nums) - 1 12 | while start < end: 13 | if nums[i] + nums[start] + nums[end] < target: 14 | ans += end - start 15 | start += 1 16 | else: 17 | end -= 1 18 | 19 | return ans 20 | -------------------------------------------------------------------------------- /041.first-missing-positive/first-missing-positive.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstMissingPositive(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | i = 0 8 | while i < len(nums): 9 | if 0 < nums[i] <= len(nums) and nums[nums[i] - 1] != nums[i]: 10 | nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] 11 | else: 12 | i += 1 13 | 14 | for i in range(0, len(nums)): 15 | if nums[i] != i + 1: 16 | return i + 1 17 | return len(nums) + 1 18 | -------------------------------------------------------------------------------- /189.rotate-array/question.md: -------------------------------------------------------------------------------- 1 | Rotate an array of n elements to the right by k steps. 2 | For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. 3 | 4 | Note: 5 | Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 6 | 7 | 8 | [show hint] 9 | Hint: 10 | Could you do it in-place with O(1) extra space? 11 | 12 | 13 | Related problem: Reverse Words in a String II 14 | 15 | Credits:Special thanks to @Freezen for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /374.guess-number-higher-or-lower/question.md: -------------------------------------------------------------------------------- 1 | We are playing the Guess Game. The game is as follows: 2 | 3 | I pick a number from 1 to n. You have to guess which number I picked. 4 | 5 | Every time you guess wrong, I'll tell you whether the number is higher or lower. 6 | 7 | You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): 8 | 9 | -1 : My number is lower 10 | 1 : My number is higher 11 | 0 : Congrats! You got it! 12 | 13 | 14 | Example: 15 | 16 | n = 10, I pick 6. 17 | 18 | Return 6. 19 | 20 | -------------------------------------------------------------------------------- /535.encode-and-decode-tinyurl/question.md: -------------------------------------------------------------------------------- 1 | Note: This is a companion problem to the System Design problem: Design TinyURL. 2 | 3 | TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. 4 | 5 | Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. -------------------------------------------------------------------------------- /583.delete-operation-for-two-strings/question.md: -------------------------------------------------------------------------------- 1 | 2 | Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string. 3 | 4 | 5 | Example 1: 6 | 7 | Input: "sea", "eat" 8 | Output: 2 9 | Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea". 10 | 11 | 12 | 13 | Note: 14 | 15 | The length of given words won't exceed 500. 16 | Characters in given words can only be lower-case letters. 17 | 18 | -------------------------------------------------------------------------------- /594.longest-harmonious-subsequence/question.md: -------------------------------------------------------------------------------- 1 | We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1. 2 | 3 | Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences. 4 | 5 | Example 1: 6 | 7 | Input: [1,3,2,2,5,2,3,7] 8 | Output: 5 9 | Explanation: The longest harmonious subsequence is [3,2,2,2,3]. 10 | 11 | 12 | 13 | Note: 14 | The length of the input array will not exceed 20,000. 15 | 16 | 17 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /166.fraction-to-recurring-decimal/question.md: -------------------------------------------------------------------------------- 1 | Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. 2 | 3 | If the fractional part is repeating, enclose the repeating part in parentheses. 4 | 5 | For example, 6 | 7 | Given numerator = 1, denominator = 2, return "0.5". 8 | Given numerator = 2, denominator = 1, return "2". 9 | Given numerator = 2, denominator = 3, return "0.(6)". 10 | 11 | 12 | 13 | Credits:Special thanks to @Shangrila for adding this problem and creating all test cases. -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /307.range-sum-query-mutable/question.md: -------------------------------------------------------------------------------- 1 | Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 2 | 3 | The update(i, val) function modifies nums by updating the element at index i to val. 4 | 5 | Example: 6 | 7 | Given nums = [1, 3, 5] 8 | 9 | sumRange(0, 2) -> 9 10 | update(1, 2) 11 | sumRange(0, 2) -> 8 12 | 13 | 14 | 15 | Note: 16 | 17 | The array is only modifiable by the update function. 18 | You may assume the number of calls to update and sumRange function is distributed evenly. 19 | 20 | -------------------------------------------------------------------------------- /320.generalized-abbreviation/generalized-abbreviation.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def generateAbbreviations(self, word): 3 | """ 4 | :type word: str 5 | :rtype: List[str] 6 | """ 7 | 8 | def dfs(w, start, res): 9 | res.append(w) 10 | for i in range(start, len(w)): 11 | for l in range(1, len(w) - i + 1): 12 | lstr = str(l) 13 | llen = len(lstr) 14 | dfs(w[:i] + lstr + w[i + l:], i + 2 + llen - 1, res) 15 | 16 | res = [] 17 | dfs(word, 0, res) 18 | return res 19 | -------------------------------------------------------------------------------- /370.range-addition/range-addition.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getModifiedArray(self, length, updates): 3 | """ 4 | :type length: int 5 | :type updates: List[List[int]] 6 | :rtype: List[int] 7 | """ 8 | ans = [0] * length 9 | for update in updates: 10 | start, end, delta = update 11 | ans[start] += delta 12 | if end + 1 < length: 13 | ans[end + 1] -= delta 14 | 15 | delta = 0 16 | for i in range(0, length): 17 | delta += ans[i] 18 | ans[i] = delta 19 | return ans 20 | --------------------------------------------------------------------------------