├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── download_solutions.py ├── questions ├── 1-bit-and-2-bit-characters │ └── Solution.py ├── 132-pattern │ └── Solution.py ├── 3sum-closest │ └── Solution.java ├── 3sum │ ├── Solution.java │ └── Solution.py ├── 4sum-ii │ └── Solution.py ├── 4sum │ └── Solution.py ├── accounts-merge │ └── Solution.py ├── actors-and-directors-who-cooperated-at-least-three-times │ └── Solution.sql ├── add-and-search-word-data-structure-design │ └── Solution.py ├── add-binary │ └── Solution.java ├── add-digits │ └── Solution.cpp ├── add-one-row-to-tree │ └── Solution.py ├── add-strings │ └── Solution.py ├── add-to-array-form-of-integer │ └── Solution.py ├── add-two-numbers-ii │ └── Solution.py ├── add-two-numbers │ ├── Solution.java │ └── Solution.py ├── alien-dictionary │ └── Solution.py ├── all-nodes-distance-k-in-binary-tree │ └── Solution.py ├── all-oone-data-structure │ └── Solution.py ├── all-paths-from-source-to-target │ └── Solution.py ├── all-possible-full-binary-trees │ └── Solution.py ├── ambiguous-coordinates │ └── Solution.py ├── android-unlock-patterns │ └── Solution.py ├── angle-between-hands-of-a-clock │ └── Solution.py ├── arithmetic-slices-ii-subsequence │ └── Solution.py ├── arithmetic-slices │ └── Solution.py ├── arranging-coins │ └── Solution.py ├── array-nesting │ └── Solution.py ├── array-partition-i │ └── Solution.py ├── array-partition │ └── Solution.py ├── article-views-i │ └── Solution.sql ├── assign-cookies │ └── Solution.py ├── asteroid-collision │ └── Solution.py ├── available-captures-for-rook │ └── Solution.py ├── average-of-levels-in-binary-tree │ └── Solution.py ├── backspace-string-compare │ └── Solution.py ├── bag-of-tokens │ └── Solution.py ├── balanced-binary-tree │ └── Solution.java ├── base-7 │ └── Solution.py ├── baseball-game │ └── Solution.py ├── basic-calculator-ii │ └── Solution.py ├── basic-calculator │ └── Solution.py ├── battleships-in-a-board │ └── Solution.py ├── beautiful-arrangement-ii │ └── Solution.py ├── beautiful-arrangement │ └── Solution.py ├── beautiful-array │ └── Solution.py ├── best-time-to-buy-and-sell-stock-ii │ └── Solution.py ├── best-time-to-buy-and-sell-stock-iii │ └── Solution.py ├── best-time-to-buy-and-sell-stock-iv │ └── Solution.py ├── best-time-to-buy-and-sell-stock-with-cooldown │ └── Solution.py ├── best-time-to-buy-and-sell-stock-with-transaction-fee │ └── Solution.py ├── best-time-to-buy-and-sell-stock │ └── Solution.py ├── big-countries │ └── Solution.sql ├── binary-gap │ └── Solution.py ├── binary-number-with-alternating-bits │ └── Solution.py ├── binary-prefix-divisible-by-5 │ └── Solution.py ├── binary-search-tree-iterator │ └── Solution.py ├── binary-search │ └── Solution.py ├── binary-tree-cameras │ └── Solution.py ├── binary-tree-inorder-traversal │ └── Solution.py ├── binary-tree-level-order-traversal-ii │ └── Solution.java ├── binary-tree-level-order-traversal │ ├── Solution.java │ └── Solution.py ├── binary-tree-maximum-path-sum │ └── Solution.py ├── binary-tree-paths │ └── Solution.java ├── binary-tree-postorder-traversal │ └── Solution.py ├── binary-tree-preorder-traversal │ └── Solution.py ├── binary-tree-pruning │ └── Solution.py ├── binary-tree-right-side-view │ └── Solution.py ├── binary-tree-tilt │ └── Solution.py ├── binary-tree-vertical-order-traversal │ └── Solution.py ├── binary-tree-zigzag-level-order-traversal │ └── Solution.py ├── binary-trees-with-factors │ └── Solution.py ├── binary-watch │ └── Solution.py ├── bitwise-and-of-numbers-range │ └── Solution.py ├── boats-to-save-people │ └── Solution.py ├── brick-wall │ └── Solution.py ├── broken-calculator │ └── Solution.py ├── buddy-strings │ └── Solution.py ├── bulb-switcher │ └── Solution.py ├── bulls-and-cows │ └── Solution.java ├── burst-balloons │ └── Solution.py ├── campus-bikes-ii │ └── Solution.py ├── campus-bikes │ └── Solution.py ├── can-place-flowers │ └── Solution.java ├── candy │ └── Solution.py ├── car-pooling │ └── Solution.py ├── cells-with-odd-values-in-a-matrix │ └── Solution.py ├── champagne-tower │ └── Solution.py ├── cheapest-flights-within-k-stops │ └── Solution.py ├── check-array-formation-through-concatenation │ └── Solution.py ├── check-completeness-of-a-binary-tree │ └── Solution.py ├── check-if-a-string-contains-all-binary-codes-of-size-k │ └── Solution.py ├── check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree │ └── Solution.py ├── check-if-it-is-a-straight-line │ └── Solution.py ├── check-if-two-string-arrays-are-equivalent │ └── Solution.py ├── classes-more-than-5-students │ └── Solution.sql ├── climbing-stairs │ └── Solution.java ├── clone-graph │ └── Solution.py ├── closest-binary-search-tree-value │ └── Solution.py ├── coin-change-2 │ └── Solution.py ├── coin-change-ii │ └── Solution.py ├── coin-change │ └── Solution.py ├── combination-sum-ii │ └── Solution.py ├── combination-sum-iii │ └── Solution.py ├── combination-sum-iv │ └── Solution.py ├── combination-sum │ ├── Solution.java │ └── Solution.py ├── combinations │ ├── Solution.java │ └── Solution.py ├── combine-two-tables │ └── Solution.sql ├── compare-version-numbers │ ├── Solution.java │ └── Solution.py ├── complement-of-base-10-integer │ └── Solution.py ├── complex-number-multiplication │ └── Solution.py ├── consecutive-characters │ └── Solution.py ├── consecutive-numbers │ └── Solution.sql ├── construct-binary-search-tree-from-preorder-traversal │ └── Solution.py ├── construct-binary-tree-from-inorder-and-postorder-traversal │ └── Solution.py ├── construct-binary-tree-from-preorder-and-inorder-traversal │ └── Solution.py ├── construct-binary-tree-from-string │ └── Solution.py ├── construct-quad-tree │ └── Solution.py ├── construct-string-from-binary-tree │ └── Solution.py ├── construct-the-rectangle │ └── Solution.py ├── container-with-most-water │ ├── Solution.java │ └── Solution.py ├── contains-duplicate-ii │ ├── Solution.java │ └── Solution.py ├── contains-duplicate-iii │ └── Solution.py ├── contains-duplicate │ ├── Solution.java │ └── Solution.py ├── contiguous-array │ └── Solution.py ├── continuous-subarray-sum │ └── Solution.py ├── convert-a-number-to-hexadecimal │ └── Solution.py ├── convert-binary-number-in-a-linked-list-to-integer │ └── Solution.py ├── convert-binary-search-tree-to-sorted-doubly-linked-list │ └── Solution.py ├── convert-bst-to-greater-tree │ └── Solution.java ├── convert-sorted-array-to-binary-search-tree │ └── Solution.py ├── convert-sorted-list-to-binary-search-tree │ └── Solution.py ├── copy-list-with-random-pointer │ └── Solution.java ├── count-all-valid-pickup-and-delivery-options │ └── Solution.py ├── count-and-say │ └── Solution.java ├── count-binary-substrings │ └── Solution.py ├── count-complete-tree-nodes │ └── Solution.py ├── count-equal-and-divisible-pairs-in-an-array │ └── Solution.py ├── count-good-nodes-in-binary-tree │ └── Solution.py ├── count-integers-with-even-digit-sum │ └── Solution.py ├── count-numbers-with-unique-digits │ └── Solution.py ├── count-of-smaller-numbers-after-self │ └── Solution.py ├── count-operations-to-obtain-zero │ └── Solution.py ├── count-primes │ └── Solution.py ├── count-sorted-vowel-strings │ └── Solution.py ├── count-square-submatrices-with-all-ones │ └── Solution.py ├── count-vowels-permutation │ └── Solution.py ├── counting-bits │ └── Solution.java ├── counting-elements │ └── Solution.py ├── counting-words-with-a-given-prefix │ └── Solution.py ├── course-schedule-ii │ └── Solution.py ├── course-schedule │ └── Solution.py ├── cousins-in-binary-tree │ └── Solution.py ├── cracking-the-safe │ └── Solution.py ├── critical-connections-in-a-network │ └── Solution.py ├── custom-sort-string │ └── Solution.py ├── customer-placing-the-largest-number-of-orders │ └── Solution.sql ├── customers-who-never-order │ └── Solution.sql ├── daily-temperatures │ └── Solution.py ├── day-of-the-week │ └── Solution.py ├── day-of-the-year │ └── Solution.py ├── decode-string │ └── Solution.py ├── decode-ways │ └── Solution.py ├── decoded-string-at-index │ └── Solution.py ├── deepest-leaves-sum │ └── Solution.py ├── defanging-an-ip-address │ └── Solution.py ├── degree-of-an-array │ └── Solution.py ├── delete-and-earn │ └── Solution.py ├── delete-columns-to-make-sorted │ └── Solution.py ├── delete-duplicate-emails │ └── Solution.sql ├── delete-node-in-a-linked-list │ ├── Solution.cpp │ └── Solution.py ├── department-highest-salary │ └── Solution.sql ├── department-top-three-salaries │ └── Solution.sql ├── design-add-and-search-words-data-structure │ └── Solution.py ├── design-hashmap │ └── Solution.py ├── design-hashset │ └── Solution.py ├── design-linked-list │ └── Solution.py ├── design-search-autocomplete-system │ └── Solution.py ├── design-snake-game │ └── Solution.py ├── design-tic-tac-toe │ └── Solution.py ├── design-twitter │ └── Solution.py ├── design-underground-system │ └── Solution.py ├── detect-capital │ └── Solution.py ├── determine-if-string-halves-are-alike │ └── Solution.py ├── determine-if-two-strings-are-close │ └── Solution.py ├── di-string-match │ └── Solution.py ├── diagonal-traverse │ └── Solution.py ├── diameter-of-binary-tree │ ├── Solution.java │ └── Solution.py ├── different-ways-to-add-parentheses │ └── Solution.py ├── distance-between-bus-stops │ └── Solution.py ├── distribute-candies-to-people │ └── Solution.py ├── distribute-candies │ └── Solution.py ├── divide-two-integers │ └── Solution.py ├── divisor-game │ └── Solution.py ├── domino-and-tromino-tiling │ └── Solution.py ├── dungeon-game │ └── Solution.py ├── duplicate-emails │ └── Solution.sql ├── duplicate-zeros │ └── Solution.py ├── edit-distance │ ├── Solution.cpp │ └── Solution.java ├── employee-importance │ └── Solution.py ├── employees-earning-more-than-their-managers │ └── Solution.sql ├── encode-and-decode-strings │ └── Solution.py ├── encode-and-decode-tinyurl │ └── Solution.py ├── erect-the-fence │ └── Solution.py ├── evaluate-division │ └── Solution.py ├── evaluate-reverse-polish-notation │ └── Solution.py ├── excel-sheet-column-number │ └── Solution.py ├── excel-sheet-column-title │ └── Solution.py ├── exchange-seats │ └── Solution.sql ├── exclusive-time-of-functions │ └── Solution.py ├── expression-add-operators │ └── Solution.py ├── expressive-words │ └── Solution.py ├── factorial-trailing-zeroes │ └── Solution.py ├── fair-candy-swap │ └── Solution.py ├── fibonacci-number │ └── Solution.py ├── find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree │ └── Solution.py ├── find-all-anagrams-in-a-string │ └── Solution.java ├── find-all-duplicates-in-an-array │ └── Solution.py ├── find-all-numbers-disappeared-in-an-array │ └── Solution.java ├── find-anagram-mappings │ └── Solution.py ├── find-and-replace-in-string │ └── Solution.py ├── find-and-replace-pattern │ └── Solution.py ├── find-common-characters │ └── Solution.py ├── find-customer-referee │ └── Solution.sql ├── find-duplicate-file-in-system │ └── Solution.py ├── find-first-and-last-position-of-element-in-sorted-array │ └── Solution.py ├── find-if-path-exists-in-graph │ └── Solution.py ├── find-k-closest-elements │ └── Solution.py ├── find-median-from-data-stream │ └── Solution.java ├── find-minimum-in-rotated-sorted-array │ └── Solution.py ├── find-mode-in-binary-search-tree │ └── Solution.py ├── find-original-array-from-doubled-array │ └── Solution.py ├── find-peak-element │ ├── Solution.java │ └── Solution.py ├── find-pivot-index │ └── Solution.py ├── find-players-with-zero-or-one-losses │ └── Solution.py ├── find-smallest-letter-greater-than-target │ └── Solution.py ├── find-the-celebrity │ └── Solution.py ├── find-the-difference │ └── Solution.py ├── find-the-duplicate-number │ ├── Solution.java │ └── Solution.py ├── find-the-index-of-the-first-occurrence-in-a-string │ └── Solution.py ├── find-the-smallest-divisor-given-a-threshold │ └── Solution.py ├── find-the-town-judge │ └── Solution.py ├── find-words-that-can-be-formed-by-characters │ └── Solution.py ├── first-bad-version │ └── Solution.py ├── first-missing-positive │ └── Solution.py ├── first-unique-character-in-a-string │ └── Solution.py ├── first-unique-number │ └── Solution.py ├── fixed-point │ └── Solution.py ├── fizz-buzz │ └── Solution.py ├── flatten-2d-vector │ └── Solution.py ├── flatten-a-multilevel-doubly-linked-list │ └── Solution.py ├── flatten-binary-tree-to-linked-list │ └── Solution.py ├── flatten-nested-list-iterator │ └── Solution.py ├── flip-equivalent-binary-trees │ └── Solution.py ├── flipping-an-image │ └── Solution.java ├── flood-fill │ └── Solution.py ├── fraction-to-recurring-decimal │ └── Solution.py ├── friends-of-appropriate-ages │ └── Solution.py ├── fruit-into-baskets │ └── Solution.py ├── furthest-building-you-can-reach │ └── Solution.py ├── game-of-life │ └── Solution.py ├── game-play-analysis-i │ └── Solution.sql ├── gas-station │ └── Solution.py ├── generate-parentheses │ └── Solution.java ├── generate-random-point-in-a-circle │ └── Solution.py ├── goat-latin │ └── Solution.py ├── gray-code │ └── Solution.py ├── greatest-common-divisor-of-strings │ └── Solution.py ├── group-anagrams │ └── Solution.py ├── group-shifted-strings │ └── Solution.py ├── groups-of-special-equivalent-strings │ └── Solution.py ├── guess-number-higher-or-lower │ └── Solution.py ├── guess-the-word │ └── Solution.py ├── h-index-2 │ └── Solution.java ├── h-index-ii │ └── Solution.py ├── h-index │ └── Solution.java ├── hamming-distance │ └── Solution.java ├── happy-number │ └── Solution.java ├── height-checker │ └── Solution.py ├── house-robber-ii │ └── Solution.py ├── house-robber-iii │ └── Solution.py ├── house-robber │ ├── Solution.java │ └── Solution.py ├── human-traffic-of-stadium │ └── Solution.sql ├── image-smoother │ └── Solution.py ├── implement-queue-using-stacks │ └── Solution.py ├── implement-stack-using-queues │ └── Solution.py ├── implement-strstr │ └── Solution.java ├── implement-trie-prefix-tree │ └── Solution.py ├── increasing-order-search-tree │ └── Solution.py ├── increasing-subsequences │ └── Solution.py ├── increasing-triplet-subsequence │ └── Solution.py ├── inorder-successor-in-bst │ └── Solution.py ├── insert-delete-getrandom-o1 │ └── Solution.py ├── insert-interval │ └── Solution.py ├── insert-into-a-binary-search-tree │ └── Solution.py ├── insert-into-a-sorted-circular-linked-list │ └── Solution.py ├── insertion-sort-list │ └── Solution.py ├── integer-break │ └── Solution.py ├── integer-to-english-words │ └── Solution.java ├── integer-to-roman │ └── Solution.java ├── interleaving-string │ └── Solution.py ├── intersection-of-two-arrays-ii │ └── Solution.py ├── intersection-of-two-arrays │ └── Solution.py ├── intersection-of-two-linked-lists │ ├── Solution.java │ └── Solution.py ├── interval-list-intersections │ └── Solution.py ├── invert-binary-tree │ ├── Solution.java │ └── Solution.py ├── is-graph-bipartite │ └── Solution.py ├── is-subsequence │ ├── Solution.java │ └── Solution.py ├── island-perimeter │ └── Solution.py ├── isomorphic-strings │ ├── Solution.java │ └── Solution.py ├── iterator-for-combination │ └── Solution.py ├── jewels-and-stones │ └── Solution.py ├── judge-route-circle │ └── Solution.py ├── jump-game-ii │ └── Solution.py ├── jump-game-iii │ └── Solution.py ├── jump-game-iv │ └── Solution.py ├── jump-game-vi │ └── Solution.py ├── jump-game │ └── Solution.java ├── k-closest-points-to-origin │ └── Solution.py ├── k-diff-pairs-in-an-array │ └── Solution.py ├── k-inverse-pairs-array │ └── Solution.py ├── k-th-symbol-in-grammar │ └── Solution.py ├── keep-multiplying-found-values-by-two │ └── Solution.py ├── keyboard-row │ └── Solution.py ├── keys-and-rooms │ └── Solution.py ├── knight-dialer │ └── Solution.py ├── koko-eating-bananas │ └── Solution.py ├── kth-largest-element-in-a-stream │ └── Solution.py ├── kth-largest-element-in-an-array │ └── Solution.py ├── kth-missing-positive-number │ └── Solution.py ├── kth-smallest-element-in-a-bst │ └── Solution.py ├── kth-smallest-element-in-a-sorted-matrix │ └── Solution.py ├── kth-smallest-number-in-multiplication-table │ └── Solution.py ├── largest-divisible-subset │ └── Solution.py ├── largest-number-at-least-twice-of-others │ └── Solution.py ├── largest-number │ └── Solution.py ├── largest-perimeter-triangle │ └── Solution.py ├── largest-plus-sign │ └── Solution.py ├── largest-rectangle-in-histogram │ └── Solution.py ├── largest-time-for-given-digits │ └── Solution.py ├── largest-triangle-area │ └── Solution.py ├── last-stone-weight-ii │ └── Solution.py ├── last-stone-weight │ └── Solution.py ├── leaf-similar-trees │ └── Solution.java ├── leftmost-column-with-at-least-a-one │ └── Solution.py ├── lemonade-change │ └── Solution.py ├── length-of-last-word │ └── Solution.java ├── letter-case-permutation │ └── Solution.py ├── letter-combinations-of-a-phone-number │ └── Solution.java ├── lfu-cache │ └── Solution.py ├── license-key-formatting │ └── Solution.py ├── linked-list-cycle-ii │ └── Solution.java ├── linked-list-cycle │ └── Solution.java ├── linked-list-random-node │ └── Solution.py ├── logger-rate-limiter │ └── Solution.py ├── logical-or-of-two-binary-grids-represented-as-quad-trees │ └── Solution.py ├── long-pressed-name │ └── Solution.py ├── longest-absolute-file-path │ └── Solution.py ├── longest-arithmetic-subsequence │ └── Solution.py ├── longest-common-prefix │ └── Solution.java ├── longest-common-subsequence │ └── Solution.py ├── longest-consecutive-sequence │ └── Solution.py ├── longest-continuous-increasing-subsequence │ └── Solution.py ├── longest-duplicate-substring │ └── Solution.py ├── longest-harmonious-subsequence │ └── Solution.py ├── longest-increasing-path-in-a-matrix │ └── Solution.py ├── longest-increasing-subsequence │ └── Solution.java ├── longest-palindrome │ └── Solution.py ├── longest-palindromic-subsequence │ └── Solution.py ├── longest-palindromic-substring │ └── Solution.py ├── longest-repeating-character-replacement │ └── Solution.py ├── longest-string-chain │ └── Solution.py ├── longest-subsequence-with-limited-sum │ └── Solution.py ├── longest-substring-with-at-most-k-distinct-characters │ └── Solution.py ├── longest-substring-with-at-most-two-distinct-characters │ └── Solution.py ├── longest-substring-without-repeating-characters │ ├── Solution.java │ └── Solution.py ├── longest-uncommon-subsequence-i │ └── Solution.py ├── longest-uncommon-subsequence-ii │ └── Solution.py ├── longest-univalue-path │ └── Solution.py ├── longest-valid-parentheses │ └── Solution.py ├── longest-word-in-dictionary-through-deleting │ └── Solution.py ├── longest-word-in-dictionary │ └── Solution.py ├── lowest-common-ancestor-of-a-binary-search-tree │ ├── Solution.java │ └── Solution.py ├── lowest-common-ancestor-of-a-binary-tree │ └── Solution.py ├── lowest-common-ancestor-of-deepest-leaves │ └── Solution.py ├── lru-cache │ └── Solution.py ├── magic-squares-in-grid │ └── Solution.py ├── majority-element-ii │ ├── Solution.java │ └── Solution.py ├── majority-element │ ├── Solution.java │ └── Solution.py ├── make-the-string-great │ └── Solution.py ├── making-a-large-island │ └── Solution.py ├── matchsticks-to-square │ └── Solution.py ├── matrix-cells-in-distance-order │ └── Solution.py ├── max-area-of-island │ └── Solution.py ├── max-consecutive-ones-ii │ └── Solution.py ├── max-consecutive-ones-iii │ └── Solution.py ├── max-consecutive-ones │ └── Solution.java ├── max-number-of-k-sum-pairs │ └── Solution.py ├── max-points-on-a-line │ └── Solution.java ├── maximal-rectangle │ └── Solution.py ├── maximal-square │ └── Solution.py ├── maximize-distance-to-closest-person │ └── Solution.py ├── maximize-sum-of-array-after-k-negations │ └── Solution.py ├── maximum-69-number │ └── Solution.py ├── maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts │ └── Solution.py ├── maximum-average-subarray-i │ └── Solution.py ├── maximum-bags-with-full-capacity-of-rocks │ └── Solution.py ├── maximum-binary-tree │ └── Solution.py ├── maximum-depth-of-binary-tree │ ├── Solution.java │ └── Solution.py ├── maximum-depth-of-n-ary-tree │ └── Solution.py ├── maximum-difference-between-node-and-ancestor │ └── Solution.py ├── maximum-erasure-value │ └── Solution.py ├── maximum-frequency-stack │ └── Solution.py ├── maximum-gap │ └── Solution.py ├── maximum-number-of-balloons │ └── Solution.py ├── maximum-performance-of-a-team │ └── Solution.py ├── maximum-product-of-splitted-binary-tree │ └── Solution.py ├── maximum-product-of-three-numbers │ └── Solution.py ├── maximum-product-of-word-lengths │ └── Solution.py ├── maximum-product-subarray │ └── Solution.py ├── maximum-profit-in-job-scheduling │ └── Solution.py ├── maximum-size-subarray-sum-equals-k │ └── Solution.py ├── maximum-subarray │ ├── Solution.java │ └── Solution.py ├── maximum-sum-circular-subarray │ └── Solution.py ├── maximum-swap │ └── Solution.py ├── maximum-units-on-a-truck │ └── Solution.py ├── maximum-width-of-binary-tree │ └── Solution.py ├── maximum-width-ramp │ └── Solution.py ├── maximum-xor-of-two-numbers-in-an-array │ └── Solution.py ├── median-of-two-sorted-arrays │ └── Solution.py ├── meeting-rooms-ii │ └── Solution.py ├── meeting-rooms │ └── Solution.py ├── merge-intervals │ └── Solution.py ├── merge-k-sorted-lists │ └── Solution.py ├── merge-sorted-array │ └── Solution.java ├── merge-two-binary-trees │ └── Solution.java ├── merge-two-sorted-lists │ ├── Solution.java │ └── Solution.py ├── middle-of-the-linked-list │ └── Solution.py ├── min-cost-climbing-stairs │ └── Solution.py ├── min-stack │ ├── Solution.java │ └── Solution.py ├── minimize-deviation-in-array │ └── Solution.py ├── minimum-absolute-difference-in-bst │ └── Solution.py ├── minimum-absolute-difference │ └── Solution.py ├── minimum-add-to-make-parentheses-valid │ └── Solution.py ├── minimum-area-rectangle-ii │ └── Solution.py ├── minimum-area-rectangle │ └── Solution.py ├── minimum-average-difference │ └── Solution.py ├── minimum-cost-to-hire-k-workers │ └── Solution.py ├── minimum-cost-to-move-chips-to-the-same-position │ └── Solution.py ├── minimum-depth-of-binary-tree │ └── Solution.java ├── minimum-distance-between-bst-nodes │ └── Solution.py ├── minimum-domino-rotations-for-equal-row │ └── Solution.py ├── minimum-falling-path-sum │ └── Solution.py ├── minimum-genetic-mutation │ └── Solution.py ├── minimum-height-trees │ └── Solution.py ├── minimum-index-sum-of-two-lists │ └── Solution.py ├── minimum-moves-to-equal-array-elements-ii │ └── Solution.py ├── minimum-moves-to-equal-array-elements │ └── Solution.py ├── minimum-number-of-arrows-to-burst-balloons │ └── Solution.py ├── minimum-number-of-refueling-stops │ └── Solution.py ├── minimum-operations-to-make-array-equal │ └── Solution.py ├── minimum-path-sum │ └── Solution.py ├── minimum-remove-to-make-valid-parentheses │ └── Solution.py ├── minimum-size-subarray-sum │ └── Solution.py ├── minimum-sum-of-four-digit-number-after-splitting-digits │ └── Solution.py ├── minimum-swaps-to-make-sequences-increasing │ └── Solution.py ├── minimum-time-difference │ └── Solution.py ├── minimum-time-to-make-rope-colorful │ └── Solution.py ├── minimum-time-visiting-all-points │ └── Solution.py ├── minimum-value-to-get-positive-step-by-step-sum │ └── Solution.py ├── minimum-window-substring │ └── Solution.py ├── mirror-reflection │ └── Solution.py ├── missing-number │ └── Solution.java ├── missing-ranges │ └── Solution.py ├── monotone-increasing-digits │ └── Solution.py ├── monotonic-array │ └── Solution.py ├── most-common-word │ └── Solution.py ├── most-stones-removed-with-same-row-or-column │ └── Solution.py ├── move-zeroes │ └── Solution.cpp ├── multiply-strings │ └── Solution.java ├── my-calendar-i │ └── Solution.py ├── my-calendar-ii │ └── Solution.py ├── my-calendar-iii │ └── Solution.py ├── n-ary-tree-level-order-traversal │ └── Solution.py ├── n-ary-tree-postorder-traversal │ └── Solution.py ├── n-ary-tree-preorder-traversal │ └── Solution.py ├── n-queens-ii │ └── Solution.py ├── n-queens │ └── Solution.py ├── n-repeated-element-in-size-2n-array │ └── Solution.py ├── n-th-tribonacci-number │ └── Solution.py ├── nearest-exit-from-entrance-in-maze │ └── Solution.py ├── network-delay-time │ └── Solution.py ├── new-21-game │ └── Solution.py ├── next-closest-time │ └── Solution.py ├── next-greater-element-i │ └── Solution.py ├── next-greater-element-ii │ └── Solution.java ├── next-greater-element-iii │ └── Solution.py ├── next-greater-node-in-linked-list │ └── Solution.py ├── next-permutation │ └── Solution.py ├── nim-game │ ├── Solution.cpp │ └── Solution.java ├── non-decreasing-array │ └── Solution.py ├── non-decreasing-subsequences │ └── Solution.py ├── non-overlapping-intervals │ └── Solution.py ├── not-boring-movies │ └── Solution.sql ├── nth-highest-salary │ └── Solution.sql ├── number-complement │ └── Solution.py ├── number-of-1-bits │ ├── Solution.java │ └── Solution.py ├── number-of-boomerangs │ └── Solution.py ├── number-of-connected-components-in-an-undirected-graph │ └── Solution.py ├── number-of-dice-rolls-with-target-sum │ └── Solution.py ├── number-of-digit-one │ ├── Solution.cpp │ └── Solution.py ├── number-of-equivalent-domino-pairs │ └── Solution.py ├── number-of-islands │ └── Solution.py ├── number-of-lines-to-write-string │ └── Solution.py ├── number-of-matching-subsequences │ └── Solution.py ├── number-of-provinces │ └── Solution.py ├── number-of-recent-calls │ └── Solution.py ├── number-of-segments-in-a-string │ └── Solution.py ├── number-of-steps-to-reduce-a-number-to-zero │ └── Solution.py ├── number-of-subarrays-with-bounded-maximum │ └── Solution.py ├── number-of-submatrices-that-sum-to-target │ └── Solution.py ├── number-of-valid-words-for-each-puzzle │ └── Solution.py ├── numbers-with-same-consecutive-differences │ └── Solution.py ├── occurrences-after-bigram │ └── Solution.py ├── odd-even-jump │ └── Solution.py ├── odd-even-linked-list │ └── Solution.java ├── one-edit-distance │ └── Solution.py ├── ones-and-zeroes │ └── Solution.py ├── online-stock-span │ └── Solution.py ├── open-the-lock │ └── Solution.py ├── orderly-queue │ └── Solution.py ├── out-of-boundary-paths │ └── Solution.py ├── pacific-atlantic-water-flow │ └── Solution.py ├── paint-house-iii │ └── Solution.py ├── pairs-of-songs-with-total-durations-divisible-by-60 │ └── Solution.py ├── palindrome-linked-list │ ├── Solution.java │ └── Solution.py ├── palindrome-number │ └── Solution.java ├── palindrome-pairs │ └── Solution.py ├── palindrome-partitioning-ii │ └── Solution.py ├── palindrome-partitioning │ └── Solution.py ├── palindromic-substrings │ └── Solution.py ├── partition-array-into-disjoint-intervals │ └── Solution.py ├── partition-array-into-three-parts-with-equal-sum │ └── Solution.py ├── partition-equal-subset-sum │ └── Solution.py ├── partition-labels │ └── Solution.py ├── partition-list │ └── Solution.py ├── partitioning-into-minimum-number-of-deci-binary-numbers │ └── Solution.py ├── pascals-triangle-ii │ └── Solution.java ├── pascals-triangle │ └── Solution.java ├── patching-array │ └── Solution.java ├── path-sum-ii │ ├── Solution.java │ └── Solution.py ├── path-sum-iii │ └── Solution.java ├── path-sum │ ├── Solution.java │ └── Solution.py ├── path-with-minimum-effort │ └── Solution.py ├── peak-index-in-a-mountain-array │ └── Solution.py ├── peeking-iterator │ └── Solution.java ├── perfect-number │ └── Solution.py ├── perfect-squares │ └── Solution.java ├── perform-string-shifts │ └── Solution.py ├── permutation-in-string │ └── Solution.py ├── permutation-sequence │ └── Solution.py ├── permutations-ii │ └── Solution.py ├── permutations │ ├── Solution.java │ └── Solution.py ├── plus-one │ └── Solution.java ├── poor-pigs │ └── Solution.py ├── populating-next-right-pointers-in-each-node-ii │ └── Solution.py ├── populating-next-right-pointers-in-each-node │ └── Solution.py ├── positions-of-large-groups │ └── Solution.py ├── possible-bipartition │ └── Solution.py ├── pow(x,n) │ └── Solution.java ├── power-of-four │ └── Solution.py ├── power-of-three │ └── Solution.py ├── power-of-two │ └── Solution.py ├── powerful-integers │ └── Solution.py ├── powx-n │ └── Solution.py ├── prefix-and-suffix-search │ └── Solution.py ├── prime-number-of-set-bits-in-binary-representation │ └── Solution.py ├── print-in-order │ └── Solution.py ├── product-of-array-except-self │ └── Solution.py ├── projection-area-of-3d-shapes │ └── Solution.java ├── pseudo-palindromic-paths-in-a-binary-tree │ └── Solution.py ├── queue-reconstruction-by-height │ └── Solution.py ├── random-pick-index │ └── Solution.py ├── random-pick-with-weight │ └── Solution.py ├── range-addition-ii │ └── Solution.py ├── range-sum-of-bst │ └── Solution.py ├── range-sum-query-2d-immutable │ └── Solution.java ├── range-sum-query-2d-mutable │ └── Solution.py ├── range-sum-query-immutable │ └── Solution.java ├── range-sum-query-mutable │ └── Solution.py ├── rank-scores │ └── Solution.sql ├── ransom-note │ └── Solution.py ├── read-n-characters-given-read4-ii-call-multiple-times │ └── Solution.py ├── read-n-characters-given-read4 │ └── Solution.py ├── reconstruct-itinerary │ └── Solution.py ├── rectangle-area │ └── Solution.py ├── rectangle-overlap │ └── Solution.py ├── reduce-array-size-to-the-half │ └── Solution.py ├── regular-expression-matching │ └── Solution.py ├── relative-ranks │ └── Solution.py ├── relative-sort-array │ └── Solution.py ├── remove-all-adjacent-duplicates-in-string-ii │ └── Solution.py ├── remove-all-adjacent-duplicates-in-string │ └── Solution.py ├── remove-covered-intervals │ └── Solution.py ├── remove-duplicate-letters │ └── Solution.py ├── remove-duplicates-from-sorted-array-ii │ └── Solution.java ├── remove-duplicates-from-sorted-array │ └── Solution.java ├── remove-duplicates-from-sorted-list-ii │ ├── Solution.cpp │ ├── Solution.java │ └── Solution.py ├── remove-duplicates-from-sorted-list │ ├── Solution.java │ └── Solution.py ├── remove-element │ └── Solution.java ├── remove-invalid-parentheses │ └── Solution.py ├── remove-k-digits │ └── Solution.py ├── remove-linked-list-elements │ ├── Solution.java │ └── Solution.py ├── remove-nth-node-from-end-of-list │ └── Solution.java ├── remove-outermost-parentheses │ └── Solution.py ├── remove-palindromic-subsequences │ └── Solution.py ├── remove-stones-to-minimize-the-total │ └── Solution.py ├── reorder-list │ └── Solution.py ├── reorganize-string │ └── Solution.py ├── repeated-dna-sequences │ ├── Solution.java │ └── Solution.py ├── repeated-string-match │ └── Solution.py ├── repeated-substring-pattern │ └── Solution.py ├── reshape-the-matrix │ └── Solution.py ├── restore-ip-addresses │ └── Solution.py ├── reverse-bits │ ├── Solution.java │ └── Solution.py ├── reverse-integer │ └── Solution.java ├── reverse-linked-list-ii │ └── Solution.java ├── reverse-linked-list │ ├── Solution.java │ └── Solution.py ├── reverse-nodes-in-k-group │ └── Solution.py ├── reverse-only-letters │ └── Solution.py ├── reverse-string-ii │ └── Solution.py ├── reverse-string │ └── Solution.java ├── reverse-vowels-of-a-string │ └── Solution.py ├── reverse-words-in-a-string-iii │ └── Solution.py ├── reverse-words-in-a-string │ └── Solution.py ├── rising-temperature │ └── Solution.sql ├── rle-iterator │ └── Solution.py ├── robot-return-to-origin │ └── Solution.py ├── robot-room-cleaner │ └── Solution.py ├── roman-to-integer │ └── Solution.java ├── rotate-array │ ├── Solution.java │ └── Solution.py ├── rotate-image │ └── Solution.py ├── rotate-list │ ├── Solution.java │ └── Solution.py ├── rotate-string │ └── Solution.py ├── rotated-digits │ └── Solution.py ├── running-sum-of-1d-array │ └── Solution.py ├── russian-doll-envelopes │ └── Solution.py ├── sales-analysis-iii │ └── Solution.sql ├── sales-person │ └── Solution.sql ├── same-tree │ └── Solution.java ├── score-of-parentheses │ └── Solution.py ├── search-a-2d-matrix-ii │ └── Solution.py ├── search-a-2d-matrix │ └── Solution.java ├── search-in-a-binary-search-tree │ └── Solution.py ├── search-in-rotated-sorted-array-ii │ └── Solution.py ├── search-in-rotated-sorted-array │ ├── Solution.java │ └── Solution.py ├── search-insert-position │ ├── Solution.java │ └── Solution.py ├── search-suggestions-system │ └── Solution.py ├── second-highest-salary │ └── Solution.sql ├── second-minimum-node-in-a-binary-tree │ └── Solution.py ├── self-dividing-numbers │ └── Solution.py ├── sentence-similarity │ └── Solution.py ├── serialize-and-deserialize-binary-tree │ └── Solution.py ├── serialize-and-deserialize-bst │ └── Solution.py ├── set-matrix-zeroes │ └── Solution.java ├── set-mismatch │ └── Solution.py ├── shift-2d-grid │ └── Solution.py ├── shifting-letters │ └── Solution.py ├── short-encoding-of-words │ └── Solution.py ├── shortest-completing-word │ └── Solution.py ├── shortest-distance-from-all-buildings │ └── Solution.py ├── shortest-distance-to-a-character │ └── Solution.py ├── shortest-path-in-binary-matrix │ └── Solution.py ├── shortest-path-visiting-all-nodes │ └── Solution.py ├── shortest-unsorted-continuous-subarray │ └── Solution.java ├── shortest-way-to-form-string │ └── Solution.py ├── shuffle-an-array │ └── Solution.py ├── simplify-path │ └── Solution.py ├── single-element-in-a-sorted-array │ └── Solution.py ├── single-number-ii │ └── Solution.java ├── single-number-iii │ └── Solution.java ├── single-number │ └── Solution.java ├── single-threaded-cpu │ └── Solution.py ├── sliding-window-maximum │ └── Solution.py ├── slowest-key │ └── Solution.py ├── smallest-integer-divisible-by-k │ └── Solution.py ├── smallest-range-i │ └── Solution.py ├── smallest-string-with-a-given-numeric-value │ └── Solution.py ├── smallest-string-with-swaps │ └── Solution.py ├── smallest-subsequence-of-distinct-characters │ └── Solution.py ├── smallest-subtree-with-all-the-deepest-nodes │ └── Solution.py ├── sort-array-by-parity-ii │ └── Solution.py ├── sort-array-by-parity │ └── Solution.py ├── sort-characters-by-frequency │ └── Solution.py ├── sort-colors │ ├── Solution.java │ └── Solution.py ├── sort-even-and-odd-indices-independently │ └── Solution.py ├── sort-list │ └── Solution.py ├── sparse-matrix-multiplication │ └── Solution.py ├── spiral-matrix-ii │ └── Solution.py ├── spiral-matrix-iii │ └── Solution.py ├── spiral-matrix │ ├── Solution.java │ └── Solution.py ├── split-a-string-in-balanced-strings │ └── Solution.py ├── split-array-largest-sum │ └── Solution.py ├── split-linked-list-in-parts │ └── Solution.py ├── sqrtx │ ├── Solution.cpp │ └── Solution.py ├── squares-of-a-sorted-array │ └── Solution.py ├── stone-game-iv │ └── Solution.py ├── stone-game-vii │ └── Solution.py ├── stone-game │ └── Solution.py ├── stream-of-characters │ └── Solution.py ├── string-compression │ └── Solution.py ├── string-to-integer-atoi │ └── Solution.py ├── string-to-integer │ ├── Solution.java │ └── Solution.py ├── strobogrammatic-number-ii │ └── Solution.py ├── strobogrammatic-number │ └── Solution.py ├── student-attendance-record-i │ └── Solution.py ├── subarray-sum-equals-k │ └── Solution.java ├── subdomain-visit-count │ └── Solution.py ├── subsets-ii │ └── Solution.py ├── subsets │ └── Solution.py ├── subtree-of-another-tree │ └── Solution.java ├── sudoku-solver │ └── Solution.py ├── sum-of-distances-in-tree │ └── Solution.py ├── sum-of-even-numbers-after-queries │ └── Solution.py ├── sum-of-left-leaves │ └── Solution.py ├── sum-of-root-to-leaf-binary-numbers │ └── Solution.py ├── sum-of-square-numbers │ └── Solution.py ├── sum-of-subarray-minimums │ └── Solution.py ├── sum-of-two-integers │ └── Solution.java ├── sum-root-to-leaf-numbers │ └── Solution.java ├── summary-ranges │ ├── Solution.java │ └── Solution.py ├── super-ugly-number │ └── Solution.py ├── surface-area-of-3d-shapes │ └── Solution.py ├── surrounded-regions │ └── Solution.py ├── swap-adjacent-in-lr-string │ └── Solution.py ├── swap-nodes-in-pairs │ └── Solution.java ├── swap-salary │ └── Solution.sql ├── swapping-nodes-in-a-linked-list │ └── Solution.py ├── symmetric-tree │ └── Solution.java ├── target-sum │ └── Solution.py ├── task-scheduler │ └── Solution.py ├── teemo-attacking │ └── Solution.py ├── tenth-line │ └── Solution.sh ├── the-k-weakest-rows-in-a-matrix │ └── Solution.py ├── the-kth-factor-of-n │ └── Solution.py ├── the-number-of-weak-characters-in-the-game │ └── Solution.py ├── the-skyline-problem │ └── Solution.py ├── third-maximum-number │ └── Solution.py ├── time-based-key-value-store │ └── Solution.py ├── to-lower-case │ └── Solution.py ├── toeplitz-matrix │ └── Solution.py ├── top-k-frequent-elements │ └── Solution.py ├── top-k-frequent-words │ └── Solution.py ├── total-hamming-distance │ └── Solution.py ├── transpose-file │ └── Solution.sh ├── transpose-matrix │ └── Solution.py ├── trapping-rain-water │ └── Solution.py ├── triangle │ └── Solution.py ├── trim-a-binary-search-tree │ └── Solution.py ├── trips-and-users │ └── Solution.sql ├── two-city-scheduling │ └── Solution.py ├── two-sum-ii-input-array-is-sorted │ └── Solution.py ├── two-sum-iv-input-is-a-bst │ └── Solution.py ├── two-sum │ ├── Solution.java │ └── Solution.py ├── ugly-number-ii │ └── Solution.java ├── ugly-number │ └── Solution.java ├── uncommon-words-from-two-sentences │ └── Solution.py ├── uncrossed-lines │ └── Solution.py ├── unique-binary-search-trees-ii │ └── Solution.py ├── unique-binary-search-trees │ └── Solution.py ├── unique-email-addresses │ └── Solution.py ├── unique-morse-code-words │ └── Solution.py ├── unique-number-of-occurrences │ └── Solution.py ├── unique-paths-ii │ └── Solution.py ├── unique-paths-iii │ └── Solution.py ├── unique-paths │ └── Solution.py ├── univalued-binary-tree │ └── Solution.py ├── user-activity-for-the-past-30-days-i │ └── Solution.sql ├── utf-8-validation │ └── Solution.py ├── valid-anagram │ └── Solution.java ├── valid-boomerang │ └── Solution.py ├── valid-mountain-array │ └── Solution.py ├── valid-number │ └── Solution.py ├── valid-palindrome-ii │ └── Solution.py ├── valid-palindrome │ └── Solution.java ├── valid-parentheses │ └── Solution.java ├── valid-parenthesis-string │ └── Solution.py ├── valid-perfect-square │ └── Solution.cpp ├── valid-phone-numbers │ └── Solution.sh ├── valid-sudoku │ └── Solution.java ├── valid-triangle-number │ └── Solution.py ├── valid-word-abbreviation │ └── Solution.py ├── valid-word-square │ └── Solution.py ├── validate-binary-search-tree │ └── Solution.java ├── validate-ip-address │ └── Solution.py ├── validate-stack-sequences │ └── Solution.py ├── verify-preorder-serialization-of-a-binary-tree │ └── Solution.py ├── verifying-an-alien-dictionary │ └── Solution.py ├── vertical-order-traversal-of-a-binary-tree │ └── Solution.py ├── vowel-spellchecker │ └── Solution.py ├── walking-robot-simulation │ └── Solution.java ├── walls-and-gates │ └── Solution.py ├── where-will-the-ball-fall │ └── Solution.py ├── wiggle-sort-ii │ └── Solution.py ├── wiggle-subsequence │ └── Solution.py ├── wildcard-matching │ └── Solution.java ├── word-abbreviation │ └── Solution.py ├── word-break-ii │ └── Solution.py ├── word-break │ └── Solution.java ├── word-frequency │ └── Solution.sh ├── word-ladder-ii │ └── Solution.py ├── word-ladder │ ├── Solution.java │ └── Solution.py ├── word-pattern │ └── Solution.java ├── word-search-ii │ └── Solution.py ├── word-search │ └── Solution.py ├── word-squares │ └── Solution.py ├── word-subsets │ └── Solution.py ├── x-of-a-kind-in-a-deck-of-cards │ └── Solution.py └── zigzag-conversion │ └── Solution.py ├── test_requirements.txt └── validate_solutions.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | 14 | # ignore vim 15 | *.swp 16 | 17 | # ignore cache 18 | .cache/ 19 | 20 | # VSCode config 21 | .vscode/ 22 | 23 | __pycache__/ 24 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.6" 4 | # command to install dependencies 5 | install: 6 | - pip install -r test_requirements.txt 7 | # command to run tests 8 | script: 9 | - python validate_solutions.py 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 franklingu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /questions/4sum-ii/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero. 4 | To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1. 5 | Example: 6 | 7 | Input: 8 | A = [ 1, 2] 9 | B = [-2,-1] 10 | C = [-1, 2] 11 | D = [ 0, 2] 12 | 13 | Output: 14 | 2 15 | 16 | Explanation: 17 | The two tuples are: 18 | 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 19 | 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0 20 | 21 |   22 | 23 | """ 24 | 25 | 26 | class Solution: 27 | def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int: 28 | AB = collections.Counter(a+b for a in A for b in B) 29 | return sum(AB[-c-d] for c in C for d in D) -------------------------------------------------------------------------------- /questions/add-digits/Solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 3 | * For example: 4 | * Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. 5 | * Since 2 has only one digit, return it. 6 | * 7 | */ 8 | 9 | class Solution { 10 | public: 11 | int addDigits(int num) { 12 | if (num/10 == 0) { 13 | return num; 14 | } 15 | 16 | int answer = 0; 17 | 18 | while (num > 0) { 19 | answer += num %10; 20 | num = num / 10; 21 | } 22 | 23 | return addDigits(answer); 24 | } 25 | }; 26 | 27 | /** 28 | * Follow up: 29 | * Could you do it without any loop/recursion in O(1) runtime? 30 | */ 31 | 32 | public class Solution { 33 | public int addDigits(int num) { 34 | if (num == 0) { 35 | return 0; 36 | } 37 | int answer = num%9; 38 | if (answer == 0) { 39 | return 9; 40 | } else { 41 | return answer; 42 | } 43 | } 44 | }; -------------------------------------------------------------------------------- /questions/android-unlock-patterns/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def numberOfPatterns(self, m: int, n: int) -> int: 9 | skip = {} 10 | 11 | skip[(1,7)] = 4 12 | skip[(1,3)] = 2 13 | skip[(1,9)] = 5 14 | skip[(2,8)] = 5 15 | skip[(3,7)] = 5 16 | skip[(3,9)] = 6 17 | skip[(4,6)] = 5 18 | skip[(7,9)] = 8 19 | self.res = 0 20 | def dfs(used, last): 21 | if len(used) >= m: 22 | self.res += 1 23 | if len(used) == n: 24 | return 25 | for j in range(1, 10): 26 | if j not in used: # if j is not used 27 | # Sort the vertices of the edge to search in skip 28 | edge = (min(last, j), max(last, j)) 29 | if edge not in skip or skip[edge] in used: 30 | dfs(used + [j], j) 31 | for i in range(1, 10): 32 | dfs([i], i) 33 | return self.res -------------------------------------------------------------------------------- /questions/angle-between-hands-of-a-clock/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | ![img1](https://assets.leetcode.com/uploads/2019/12/26/sample_1_1673.png) 9 | 10 | Input: hour = 12, minutes = 30 11 | Output: 165 12 | Example 2: 13 | 14 | ![img2](https://assets.leetcode.com/uploads/2019/12/26/sample_2_1673.png) 15 | 16 | Input: hour = 3, minutes = 30 17 | Output: 75 18 | Example 3: 19 | 20 | ![img3](https://assets.leetcode.com/uploads/2019/12/26/sample_3_1673.png) 21 | 22 | Input: hour = 3, minutes = 15 23 | Output: 7.5 24 | Example 4: 25 | 26 | 27 | Input: hour = 4, minutes = 50 28 | Output: 155 29 | Example 5: 30 | 31 | 32 | Input: hour = 12, minutes = 0 33 | Output: 0 34 | 35 | 36 | Constraints: 37 | 38 | 1 <= hour <= 12 39 | 0 <= minutes <= 59 40 | Answers within 10^-5 of the actual value will be accepted as correct. 41 | """ -------------------------------------------------------------------------------- /questions/arranging-coins/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. 4 | Given n, find the total number of full staircase rows that can be formed. 5 | n is a non-negative integer and fits within the range of a 32-bit signed integer. 6 | Example 1: 7 | 8 | n = 5 9 | 10 | The coins can form the following rows: 11 | ¤ 12 | ¤ ¤ 13 | ¤ ¤ 14 | 15 | Because the 3rd row is incomplete, we return 2. 16 | 17 | 18 | Example 2: 19 | 20 | n = 8 21 | 22 | The coins can form the following rows: 23 | ¤ 24 | ¤ ¤ 25 | ¤ ¤ ¤ 26 | ¤ ¤ 27 | 28 | Because the 4th row is incomplete, we return 3. 29 | 30 | 31 | """ 32 | 33 | 34 | class Solution: 35 | def arrangeCoins(self, n: int) -> int: 36 | t = int((n * 2) ** 0.5) + 2 37 | for i in range(t, 0, -1): 38 | if i * (i + 1) // 2 <= n: 39 | return i 40 | return 0 -------------------------------------------------------------------------------- /questions/array-partition-i/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. 3 | 4 | Example 1: 5 | Input: [1,4,3,2] 6 | 7 | Output: 4 8 | Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). 9 | Note: 10 | n is a positive integer, which is in the range of [1, 10000]. 11 | All the integers in the array will be in the range of [-10000, 10000]. 12 | """ 13 | class Solution(object): 14 | def arrayPairSum(self, nums): 15 | """ 16 | :type nums: List[int] 17 | :rtype: int 18 | """ 19 | nums.sort() 20 | ret = 0 21 | for idx, num in enumerate(nums): 22 | if idx % 2 == 0: 23 | ret += num 24 | return ret 25 | 26 | -------------------------------------------------------------------------------- /questions/base-7/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an integer, return its base 7 string representation. 4 | Example 1: 5 | 6 | Input: 100 7 | Output: "202" 8 | 9 | 10 | Example 2: 11 | 12 | Input: -7 13 | Output: "-10" 14 | 15 | 16 | Note: 17 | The input will be in range of [-1e7, 1e7]. 18 | 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def convertToBase7(self, num): 24 | """ 25 | :type num: int 26 | :rtype: str 27 | """ 28 | if num == 0: 29 | return '0' 30 | elif num < 0: 31 | is_negative = True 32 | num = -num 33 | else: 34 | is_negative = False 35 | r = [] 36 | while num >= 7: 37 | num, d = divmod(num, 7) 38 | r.append(str(d)) 39 | if num > 0: 40 | r.append(str(num)) 41 | can = ''.join(reversed(r)) 42 | return can if not is_negative else '-' + can -------------------------------------------------------------------------------- /questions/best-time-to-buy-and-sell-stock-with-cooldown/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Say you have an array for which the ith element is the price of a given stock on day i. 4 | 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) with the following restrictions: 5 | 6 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 7 | After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day) 8 | 9 | Example: 10 | 11 | Input: [1,2,3,0,2] 12 | Output: 3 13 | Explanation: transactions = [buy, sell, cooldown, buy, sell] 14 | 15 | """ 16 | 17 | 18 | class Solution: 19 | def maxProfit(self, prices: List[int]) -> int: 20 | notHold, notHold_cooldown, hold = 0, float('-inf'), float('-inf') 21 | for p in prices: 22 | hold, notHold, notHold_cooldown = max(hold, notHold - p), max(notHold, notHold_cooldown), hold + p 23 | return max(notHold, notHold_cooldown) -------------------------------------------------------------------------------- /questions/binary-number-with-alternating-bits/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. 3 | 4 | Example 1: 5 | Input: 5 6 | Output: True 7 | Explanation: 8 | The binary representation of 5 is: 101 9 | Example 2: 10 | Input: 7 11 | Output: False 12 | Explanation: 13 | The binary representation of 7 is: 111. 14 | Example 3: 15 | Input: 11 16 | Output: False 17 | Explanation: 18 | The binary representation of 11 is: 1011. 19 | Example 4: 20 | Input: 10 21 | Output: True 22 | Explanation: 23 | The binary representation of 10 is: 1010. 24 | """ 25 | class Solution(object): 26 | def hasAlternatingBits(self, n): 27 | """ 28 | :type n: int 29 | :rtype: bool 30 | """ 31 | p = None 32 | for c in bin(n): 33 | if c == p: 34 | return False 35 | p = c 36 | return True 37 | 38 | -------------------------------------------------------------------------------- /questions/binary-prefix-divisible-by-5/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | You are given a binary array nums (0-indexed). 4 | We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit). 5 | 6 | For example, if nums = [1,0,1], then x0 = 1, x1 = 2, and x2 = 5. 7 | 8 | Return an array of booleans answer where answer[i] is true if xi is divisible by 5. 9 |   10 | Example 1: 11 | 12 | Input: nums = [0,1,1] 13 | Output: [true,false,false] 14 | Explanation: The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. 15 | Only the first number is divisible by 5, so answer[0] is true. 16 | 17 | Example 2: 18 | 19 | Input: nums = [1,1,1] 20 | Output: [false,false,false] 21 | 22 |   23 | Constraints: 24 | 25 | 1 <= nums.length <= 105 26 | nums[i] is either 0 or 1. 27 | 28 | 29 | """ 30 | 31 | 32 | class Solution: 33 | def prefixesDivBy5(self, nums: List[int]) -> List[bool]: 34 | remainder = 0 35 | ret = [] 36 | for n in nums: 37 | c = remainder * 2 + n 38 | _, remainder = divmod(c, 5) 39 | ret.append(remainder == 0) 40 | return ret 41 | -------------------------------------------------------------------------------- /questions/binary-tree-level-order-traversal/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 3 | 4 | For example: 5 | Given binary tree [3,9,20,null,null,15,7], 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its level order traversal as: 12 | [ 13 | [3], 14 | [9,20], 15 | [15,7] 16 | ] 17 | """ 18 | 19 | 20 | # Definition for a binary tree node. 21 | # class TreeNode: 22 | # def __init__(self, x): 23 | # self.val = x 24 | # self.left = None 25 | # self.right = None 26 | 27 | class Solution: 28 | def levelOrder(self, root: TreeNode) -> List[List[int]]: 29 | def build_levels(node, levels, level): 30 | if node is None: 31 | return 32 | if len(levels) == level: 33 | levels.append([]) 34 | levels[level].append(node.val) 35 | build_levels(node.left, levels, level + 1) 36 | build_levels(node.right, levels, level + 1) 37 | 38 | levels = [] 39 | build_levels(root, levels, 0) 40 | return levels 41 | -------------------------------------------------------------------------------- /questions/binary-tree-preorder-traversal/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, return the preorder traversal of its nodes' values. 3 | 4 | Example: 5 | 6 | Input: [1,null,2,3] 7 | 1 8 | \ 9 | 2 10 | / 11 | 3 12 | 13 | Output: [1,2,3] 14 | Follow up: Recursive solution is trivial, could you do it iteratively? 15 | """ 16 | 17 | 18 | # Definition for a binary tree node. 19 | # class TreeNode: 20 | # def __init__(self, x): 21 | # self.val = x 22 | # self.left = None 23 | # self.right = None 24 | 25 | class Solution: 26 | def preorderTraversal(self, root: TreeNode) -> List[int]: 27 | if root is None: 28 | return [] 29 | return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right) 30 | 31 | 32 | class Solution2: 33 | def preorderTraversal(self, root: TreeNode) -> List[int]: 34 | ret = [] 35 | stk = [root] 36 | while stk: 37 | curr = stk.pop() 38 | if curr is None: 39 | continue 40 | ret.append(curr.val) 41 | stk.append(curr.right) 42 | stk.append(curr.left) 43 | return ret 44 | -------------------------------------------------------------------------------- /questions/bitwise-and-of-numbers-range/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 3 | 4 | Example 1: 5 | 6 | Input: [5,7] 7 | Output: 4 8 | Example 2: 9 | 10 | Input: [0,1] 11 | Output: 0 12 | """ 13 | 14 | class Solution: 15 | def rangeBitwiseAnd(self, m: int, n: int) -> int: 16 | if m == n: 17 | return m 18 | start = bin(m)[2:] 19 | diff = bin(m^n)[2:] 20 | if len(diff) >= len(start): 21 | return 0 22 | else: 23 | return int(start[:-len(diff)]+''.join(['0' for i in range(len(diff))]), 2) 24 | 25 | -------------------------------------------------------------------------------- /questions/bulb-switcher/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. 4 | On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. 5 | Return the number of bulbs that are on after n rounds. 6 |   7 | Example 1: 8 | 9 | 10 | Input: n = 3 11 | Output: 1 12 | Explanation: At first, the three bulbs are [off, off, off]. 13 | After the first round, the three bulbs are [on, on, on]. 14 | After the second round, the three bulbs are [on, off, on]. 15 | After the third round, the three bulbs are [on, off, off]. 16 | So you should return 1 because there is only one bulb is on. 17 | Example 2: 18 | 19 | Input: n = 0 20 | Output: 0 21 | 22 | Example 3: 23 | 24 | Input: n = 1 25 | Output: 1 26 | 27 |   28 | Constraints: 29 | 30 | 0 <= n <= 109 31 | 32 | 33 | """ 34 | 35 | 36 | class Solution: 37 | def bulbSwitch(self, n: int) -> int: 38 | return int(n ** 0.5) -------------------------------------------------------------------------------- /questions/campus-bikes-ii/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> int: 9 | def dis(i, j): 10 | return abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1]) 11 | 12 | h = [[0, 0, 0]] 13 | seen = set() 14 | while True: 15 | cost, i, taken = heapq.heappop(h) 16 | if (i, taken) in seen: continue 17 | seen.add((i, taken)) 18 | if i == len(workers): 19 | return cost 20 | for j in range(len(bikes)): 21 | if taken & (1 << j) == 0: 22 | heapq.heappush(h, [cost + dis(i, j), i + 1, taken | (1 << j)]) 23 | -------------------------------------------------------------------------------- /questions/campus-bikes/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> List[int]: 9 | distances = [] 10 | for i, worker in enumerate(workers): 11 | for j, bike in enumerate(bikes): 12 | distances.append((abs(worker[0] - bike[0]) + abs(worker[1] - bike[1]), i, j)) 13 | distances.sort() 14 | assigned = set() 15 | taken = set() 16 | track = [-1] * len(workers) 17 | for dist, i, j in distances: 18 | if i in assigned or j in taken: 19 | continue 20 | assigned.add(i) 21 | taken.add(j) 22 | track[i] = j 23 | if len(assigned) == len(workers): 24 | break 25 | return track -------------------------------------------------------------------------------- /questions/classes-more-than-5-students/Solution.sql: -------------------------------------------------------------------------------- 1 | /* There is a table courses with columns: student and class 2 | 3 | Please list out all classes which have more than or equal to 5 students. 4 | 5 | For example, the table: 6 | 7 | +---------+------------+ 8 | | student | class | 9 | +---------+------------+ 10 | | A | Math | 11 | | B | English | 12 | | C | Math | 13 | | D | Biology | 14 | | E | Math | 15 | | F | Computer | 16 | | G | Math | 17 | | H | Math | 18 | | I | Math | 19 | +---------+------------+ 20 | 21 | Should output: 22 | 23 | +---------+ 24 | | class | 25 | +---------+ 26 | | Math | 27 | +---------+ 28 | 29 | Note: 30 | The students should not be counted duplicate in each course. 31 | */ 32 | 33 | select class from courses group by class having count(distinct student) >= 5; 34 | -------------------------------------------------------------------------------- /questions/climbing-stairs/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * You are climbing a stair case. It takes n steps to reach to the top. 3 | * 4 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 5 | */ 6 | 7 | public class Solution { 8 | public int climbStairs(int n) { 9 | if (n <= 0) { 10 | return 0; 11 | } else if (n == 1) { 12 | return 1; 13 | } 14 | int[] arr = new int[n]; 15 | arr[0] = 1; 16 | return countWays(n, arr); 17 | } 18 | 19 | private int countWays(int n, int[] arr) { 20 | if (n < 0) { 21 | return -1; 22 | } else if (n == 0) { 23 | return 1; 24 | } 25 | if (arr[n - 1] != 0) { 26 | return arr[n - 1]; 27 | } 28 | int result1 = countWays(n - 1, arr), result2 = countWays(n - 2, arr); 29 | arr[n - 1] = result1 + result2; 30 | 31 | return arr[n - 1]; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /questions/closest-binary-search-tree-value/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | # Definition for a binary tree node. 8 | # class TreeNode: 9 | # def __init__(self, x): 10 | # self.val = x 11 | # self.left = None 12 | # self.right = None 13 | 14 | class Solution: 15 | def closestValue(self, root: TreeNode, target: float) -> int: 16 | def inorder(node): 17 | if node is None: 18 | return 19 | yield from inorder(node.left) 20 | yield node.val 21 | yield from inorder(node.right) 22 | 23 | diff, val = None, None 24 | for n in inorder(root): 25 | if diff is None or diff > abs(n - target): 26 | diff = abs(n - target) 27 | val = n 28 | if n > target: 29 | break 30 | return val -------------------------------------------------------------------------------- /questions/combination-sum-iii/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. 3 | 4 | Note: 5 | 6 | All numbers will be positive integers. 7 | The solution set must not contain duplicate combinations. 8 | Example 1: 9 | 10 | Input: k = 3, n = 7 11 | Output: [[1,2,4]] 12 | Example 2: 13 | 14 | Input: k = 3, n = 9 15 | Output: [[1,2,6], [1,3,5], [2,3,4]] 16 | """ 17 | 18 | 19 | import itertools 20 | 21 | 22 | class Solution: 23 | def combinationSum3(self, k: int, n: int) -> List[List[int]]: 24 | res = [] 25 | for t in itertools.combinations(list(range(1, 10)), k): 26 | if sum(t) == n: 27 | res.append(list(t)) 28 | return res 29 | -------------------------------------------------------------------------------- /questions/combinations/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 3 | 4 | Example: 5 | 6 | Input: n = 4, k = 2 7 | Output: 8 | [ 9 | [2,4], 10 | [3,4], 11 | [2,3], 12 | [1,2], 13 | [1,3], 14 | [1,4], 15 | ] 16 | """ 17 | 18 | 19 | class Solution: 20 | def combine(self, n: int, k: int) -> List[List[int]]: 21 | def fill_results(index, n, curr, results): 22 | if len(curr) == k: 23 | results.append(list(curr)) 24 | return 25 | elif index > n: 26 | return 27 | curr.append(index) 28 | fill_results(index + 1, n, curr, results) 29 | curr.pop() 30 | fill_results(index + 1, n, curr, results) 31 | 32 | results = [] 33 | curr = [] 34 | fill_results(1, n, curr, results) 35 | return results 36 | -------------------------------------------------------------------------------- /questions/combine-two-tables/Solution.sql: -------------------------------------------------------------------------------- 1 | # Table: Person 2 | # +-------------+---------+ 3 | # | Column Name | Type | 4 | # ------------+---------+ 5 | # | PersonId | int | 6 | # | FirstName | varchar | 7 | # | LastName | varchar | 8 | # +-------------+---------+ 9 | # PersonId is the primary key column for this table. 10 | 11 | 12 | # Table: Address 13 | # +-------------+---------+ 14 | # | Column Name | Type | 15 | # +------------+---------+ 16 | # | AddressId | int | 17 | # | PersonId | int | 18 | # | City | varchar | 19 | # | State | varchar | 20 | # +-------------+---------+ 21 | # AddressId is the primary key column for this table. 22 | 23 | 24 | # Write a SQL query for a report that provides the following 25 | # information for each person in the Person table, regardless 26 | # if there is an address for each of those people: 27 | #################################### 28 | # FirstName, LastName, City, State # 29 | #################################### 30 | 31 | 32 | # Write your MySQL query statement below 33 | SELECT FirstName, LastName, City, State FROM Person p LEFT JOIN Address a ON p.PersonId = a.PersonId; -------------------------------------------------------------------------------- /questions/consecutive-numbers/Solution.sql: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a SQL query to find all numbers that appear at least three times consecutively. 3 | * 4 | * +----+-----+ 5 | * | Id | Num | 6 | * +----+-----+ 7 | * | 1 | 1 | 8 | * | 2 | 1 | 9 | * | 3 | 1 | 10 | * | 4 | 2 | 11 | * | 5 | 1 | 12 | * | 6 | 2 | 13 | * | 7 | 2 | 14 | * +----+-----+ 15 | * For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times. 16 | * 17 | * +-----------------+ 18 | * | ConsecutiveNums | 19 | * +-----------------+ 20 | * | 1 | 21 | * +-----------------+ 22 | */ 23 | # Write your MySQL query statement below 24 | SELECT DISTINCT l1.Num As ConsecutiveNums 25 | FROM Logs l1, Logs l2, Logs l3 26 | WHERE l1.Num = l2.Num 27 | AND l2.Num = l3.Num 28 | AND l1.Id = l2.Id + 1 29 | AND l2.Id = l3.Id + 1; 30 | -------------------------------------------------------------------------------- /questions/container-with-most-water/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). 3 | * n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, 4 | * which together with x-axis forms a container, such that the container contains the most water. 5 | * 6 | * Note: You may not slant the container. 7 | */ 8 | 9 | public class Solution { 10 | public int maxArea(int[] height) { 11 | if (height == null || height.length <= 1) { 12 | return 0; 13 | } 14 | int max = 0; 15 | int left = 0; 16 | int right = height.length - 1; 17 | 18 | while (left < right) { 19 | max = Math.max(max, (right - left) * Math.min(height[left], height[right])); 20 | if (height[left] > height[right]) { 21 | right--; 22 | } else { 23 | left++; 24 | } 25 | } 26 | 27 | return max; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /questions/contains-duplicate-ii/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers and an integer k, find out whether there are two 3 | * distinct indices i and j in the array such that nums[i] = nums[j] and the 4 | *difference between i and j is at most k. 5 | */ 6 | 7 | public class Solution { 8 | public boolean containsNearbyDuplicate(int[] nums, int k) { 9 | HashMap st = new HashMap(); 10 | for (int i = 0; i < nums.length; i++) { 11 | if (st.containsKey(nums[i]) && i - st.get(nums[i]).intValue() <= k) { 12 | return true; 13 | } 14 | st.put(nums[i], i); 15 | } 16 | return false; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /questions/contains-duplicate-ii/Solution.py: -------------------------------------------------------------------------------- 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 | 4 | Example 1: 5 | 6 | Input: nums = [1,2,3,1], k = 3 7 | Output: true 8 | Example 2: 9 | 10 | Input: nums = [1,0,1,1], k = 1 11 | Output: true 12 | Example 3: 13 | 14 | Input: nums = [1,2,3,1,2,3], k = 2 15 | Output: false 16 | """ 17 | 18 | 19 | class Solution: 20 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 21 | track = {} 22 | for i, n in enumerate(nums): 23 | if n not in track: 24 | track[n] = i 25 | continue 26 | if i - track[n] <= k: 27 | return True 28 | else: 29 | track[n] = i 30 | return False 31 | -------------------------------------------------------------------------------- /questions/contains-duplicate/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers, find if the array contains any duplicates. 3 | * Your function should return true if any value 4 | * appears at least twice in the array, and it should return false if every 5 | * element is distinct. 6 | */ 7 | 8 | public class Solution { 9 | public boolean containsDuplicate(int[] nums) { 10 | HashSet st = new HashSet(); 11 | for (int i = 0; i < nums.length; i++) { 12 | if (st.contains(nums[i])) { 13 | return true; 14 | } 15 | st.add(nums[i]); 16 | } 17 | return false; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /questions/contains-duplicate/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers, find if the array contains any duplicates. 3 | 4 | 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. 5 | 6 | Example 1: 7 | 8 | Input: [1,2,3,1] 9 | Output: true 10 | Example 2: 11 | 12 | Input: [1,2,3,4] 13 | Output: false 14 | Example 3: 15 | 16 | Input: [1,1,1,3,3,4,3,2,4,2] 17 | Output: true 18 | """ 19 | 20 | class Solution: 21 | def containsDuplicate(self, nums: List[int]) -> bool: 22 | return len(nums) != len(set(nums)) 23 | -------------------------------------------------------------------------------- /questions/convert-binary-search-tree-to-sorted-doubly-linked-list/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | """ 8 | # Definition for a Node. 9 | class Node: 10 | def __init__(self, val, left, right): 11 | self.val = val 12 | self.left = left 13 | self.right = right 14 | """ 15 | class Solution: 16 | def treeToDoublyList(self, root: 'Node') -> 'Node': 17 | if root is None: 18 | return None 19 | lh = self.treeToDoublyList(root.left) 20 | rh = self.treeToDoublyList(root.right) 21 | lt, rt = None, None 22 | if lh is None: 23 | lh = lt = root 24 | else: 25 | lt = lh.left 26 | lt.right = root 27 | root.left = lt 28 | if rh is None: 29 | root.right = None 30 | rh = rt = root 31 | else: 32 | rt = rh.left 33 | rh.left = root 34 | root.right = rh 35 | lh.left = rt 36 | rt.right = lh 37 | return lh -------------------------------------------------------------------------------- /questions/convert-sorted-array-to-binary-search-tree/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 3 | """ 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | def sortedArrayToBST(self, nums): 14 | """ 15 | :type nums: List[int] 16 | :rtype: TreeNode 17 | """ 18 | if not nums: 19 | return None 20 | mid_idx = len(nums) / 2 21 | root = TreeNode(nums[mid_idx]) 22 | root.left = Solution().sortedArrayToBST(nums[:mid_idx]) 23 | root.right = Solution().sortedArrayToBST(nums[mid_idx + 1:]) 24 | return root 25 | -------------------------------------------------------------------------------- /questions/count-all-valid-pickup-and-delivery-options/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given n orders, each order consist in pickup and delivery services.  4 | Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).  5 | Since the answer may be too large, return it modulo 10^9 + 7. 6 |   7 | Example 1: 8 | 9 | Input: n = 1 10 | Output: 1 11 | Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1. 12 | 13 | Example 2: 14 | 15 | Input: n = 2 16 | Output: 6 17 | Explanation: All possible orders: 18 | (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). 19 | This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. 20 | 21 | Example 3: 22 | 23 | Input: n = 3 24 | Output: 90 25 | 26 |   27 | Constraints: 28 | 29 | 1 <= n <= 500 30 | 31 | 32 | """ 33 | 34 | 35 | class Solution: 36 | def countOrders(self, n: int) -> int: 37 | if n == 1: 38 | return 1 39 | else: 40 | return (n*(2*n-1)*self.countOrders(n-1))%(10**9+7) -------------------------------------------------------------------------------- /questions/count-complete-tree-nodes/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a complete binary tree, count the number of nodes. 3 | 4 | Note: 5 | 6 | Definition of a complete binary tree from Wikipedia: 7 | 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. 8 | 9 | Example: 10 | 11 | Input: 12 | 1 13 | / \ 14 | 2 3 15 | / \ / 16 | 4 5 6 17 | 18 | Output: 6 19 | """ 20 | 21 | # Definition for a binary tree node. 22 | # class TreeNode: 23 | # def __init__(self, x): 24 | # self.val = x 25 | # self.left = None 26 | # self.right = None 27 | 28 | class Solution: 29 | def countNodes(self, root: TreeNode) -> int: 30 | if root is None: 31 | return 0 32 | return self.countNodes(root.left) + 1 + self.countNodes(root.right) 33 | -------------------------------------------------------------------------------- /questions/count-integers-with-even-digit-sum/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. 4 | The digit sum of a positive integer is the sum of all its digits. 5 |   6 | Example 1: 7 | 8 | Input: num = 4 9 | Output: 2 10 | Explanation: 11 | The only integers less than or equal to 4 whose digit sums are even are 2 and 4. 12 | 13 | Example 2: 14 | 15 | Input: num = 30 16 | Output: 14 17 | Explanation: 18 | The 14 integers less than or equal to 30 whose digit sums are even are 19 | 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28. 20 | 21 |   22 | Constraints: 23 | 24 | 1 <= num <= 1000 25 | 26 | 27 | """ 28 | 29 | 30 | class Solution: 31 | def countEven(self, num: int) -> int: 32 | def sum_digits(n): 33 | s = 0 34 | while n > 0: 35 | n, r = divmod(n, 10) 36 | s += r 37 | return s 38 | 39 | r = 0 40 | for n in range(1, num + 1): 41 | if sum_digits(n) % 2 == 0: 42 | r += 1 43 | return r -------------------------------------------------------------------------------- /questions/count-numbers-with-unique-digits/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n. 4 | 5 | Example: 6 | 7 | Input: 2 8 | Output: 91 9 | Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, 10 |   excluding 11,22,33,44,55,66,77,88,99 11 | 12 | 13 |   14 | Constraints: 15 | 16 | 0 <= n <= 8 17 | 18 | 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def countNumbersWithUniqueDigits(self, n): 24 | """ 25 | :type n: int 26 | :rtype: int 27 | """ 28 | if n == 0: 29 | return 1 30 | elif n == 1: 31 | return 10 32 | ret = 9 33 | step = 9 34 | for i in xrange(n - 1): 35 | ret *= step 36 | step -= 1 37 | return ret + self.countNumbersWithUniqueDigits(n - 1) -------------------------------------------------------------------------------- /questions/count-of-smaller-numbers-after-self/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]. 4 |   5 | Example 1: 6 | 7 | Input: nums = [5,2,6,1] 8 | Output: [2,1,1,0] 9 | Explanation: 10 | To the right of 5 there are 2 smaller elements (2 and 1). 11 | To the right of 2 there is only 1 smaller element (1). 12 | To the right of 6 there is 1 smaller element (1). 13 | To the right of 1 there is 0 smaller element. 14 | 15 | Example 2: 16 | 17 | Input: nums = [-1] 18 | Output: [0] 19 | 20 | Example 3: 21 | 22 | Input: nums = [-1,-1] 23 | Output: [0,0] 24 | 25 |   26 | Constraints: 27 | 28 | 1 <= nums.length <= 105 29 | -104 <= nums[i] <= 104 30 | 31 | 32 | """ 33 | 34 | 35 | import bisect 36 | 37 | 38 | class Solution: 39 | def countSmaller(self, nums: List[int]) -> List[int]: 40 | tail = [] 41 | counts = [] 42 | for n in reversed(nums): 43 | index = bisect.bisect_left(tail, n) 44 | counts.append(index) 45 | tail.insert(index, n) 46 | return counts[::-1] -------------------------------------------------------------------------------- /questions/count-primes/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Count the number of prime numbers less than a non-negative number, n. 3 | 4 | Example: 5 | 6 | Input: 10 7 | Output: 4 8 | Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 9 | """ 10 | 11 | 12 | class Solution: 13 | def countPrimes(self, n: int) -> int: 14 | if n <= 2: 15 | return 0 16 | candidates = [2] 17 | for i in range(3, n, 2): 18 | candidates.append(i) 19 | primes = set(candidates) 20 | for i, num in enumerate(candidates): 21 | if num not in primes: 22 | continue 23 | runner = num + num 24 | while runner <= n: 25 | if runner in primes: 26 | primes.remove(runner) 27 | runner += num 28 | return len(primes) 29 | -------------------------------------------------------------------------------- /questions/count-sorted-vowel-strings/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. 4 | A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. 5 |   6 | Example 1: 7 | 8 | Input: n = 1 9 | Output: 5 10 | Explanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"]. 11 | 12 | Example 2: 13 | 14 | Input: n = 2 15 | Output: 15 16 | Explanation: The 15 sorted strings that consist of vowels only are 17 | ["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"]. 18 | Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet. 19 | 20 | Example 3: 21 | 22 | Input: n = 33 23 | Output: 66045 24 | 25 |   26 | Constraints: 27 | 28 | 1 <= n <= 50  29 | 30 | 31 | """ 32 | 33 | 34 | class Solution: 35 | def countVowelStrings(self, n: int) -> int: 36 | arr = [1 for _ in range(5)] 37 | for _ in range(n - 1): 38 | for i in range(3, -1, -1): 39 | arr[i] = arr[i] + arr[i + 1] 40 | return sum(arr) -------------------------------------------------------------------------------- /questions/counting-elements/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def countElements(self, arr: List[int]) -> int: 9 | res = 0 10 | ss = set(arr) 11 | for a in arr: 12 | if a + 1 in ss: 13 | res += 1 14 | return res -------------------------------------------------------------------------------- /questions/counting-words-with-a-given-prefix/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | You are given an array of strings words and a string pref. 4 | Return the number of strings in words that contain pref as a prefix. 5 | A prefix of a string s is any leading contiguous substring of s. 6 |   7 | Example 1: 8 | 9 | Input: words = ["pay","attention","practice","attend"], pref = "at" 10 | Output: 2 11 | Explanation: The 2 strings that contain "at" as a prefix are: "attention" and "attend". 12 | 13 | Example 2: 14 | 15 | Input: words = ["leetcode","win","loops","success"], pref = "code" 16 | Output: 0 17 | Explanation: There are no strings that contain "code" as a prefix. 18 | 19 |   20 | Constraints: 21 | 22 | 1 <= words.length <= 100 23 | 1 <= words[i].length, pref.length <= 100 24 | words[i] and pref consist of lowercase English letters. 25 | 26 | 27 | """ 28 | 29 | 30 | class Solution: 31 | def prefixCount(self, words: List[str], pref: str) -> int: 32 | return len([w for w in words if w.startswith(pref)]) -------------------------------------------------------------------------------- /questions/customers-who-never-order/Solution.sql: -------------------------------------------------------------------------------- 1 | /** 2 | * Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything. 3 | * 4 | * Table: Customers. 5 | * 6 | * +----+-------+ 7 | * | Id | Name | 8 | * +----+-------+ 9 | * | 1 | Joe | 10 | * | 2 | Henry | 11 | * | 3 | Sam | 12 | * | 4 | Max | 13 | * +----+-------+ 14 | * Table: Orders. 15 | * 16 | * +----+------------+ 17 | * | Id | CustomerId | 18 | * +----+------------+ 19 | * | 1 | 3 | 20 | * | 2 | 1 | 21 | * +----+------------+ 22 | * Using the above tables as example, return the following: 23 | * 24 | * +-----------+ 25 | * | Customers | 26 | * +-----------+ 27 | * | Henry | 28 | * | Max | 29 | * +-----------+ 30 | */ 31 | 32 | select Name as Customers from Customers as c where c.Id not in (select distinct CustomerId from Orders); 33 | -------------------------------------------------------------------------------- /questions/daily-temperatures/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | 4 | Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. 5 | 6 | For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. 7 | 8 | Note: 9 | The length of temperatures will be in the range [1, 30000]. 10 | Each temperature will be an integer in the range [30, 100]. 11 | 12 | """ 13 | 14 | 15 | class Solution: 16 | def dailyTemperatures(self, T: List[int]) -> List[int]: 17 | ret = [] 18 | ts = {} 19 | for i, t in enumerate(reversed(T)): 20 | mmax = None 21 | for t2 in range(t + 1, 101): 22 | if t2 not in ts: 23 | continue 24 | if mmax is None or ts[t2] > mmax: 25 | mmax = ts[t2] 26 | ret.append(i - mmax if mmax is not None else 0) 27 | ts[t] = i 28 | return ret[::-1] -------------------------------------------------------------------------------- /questions/day-of-the-week/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a date, return the corresponding day of the week for that date. 4 | The input is given as three integers representing the day, month and year respectively. 5 | Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}. 6 |   7 | Example 1: 8 | 9 | Input: day = 31, month = 8, year = 2019 10 | Output: "Saturday" 11 | 12 | Example 2: 13 | 14 | Input: day = 18, month = 7, year = 1999 15 | Output: "Sunday" 16 | 17 | Example 3: 18 | 19 | Input: day = 15, month = 8, year = 1993 20 | Output: "Sunday" 21 | 22 |   23 | Constraints: 24 | 25 | The given dates are valid dates between the years 1971 and 2100. 26 | 27 | 28 | """ 29 | 30 | 31 | class Solution: 32 | def dayOfTheWeek(self, day: int, month: int, year: int) -> str: 33 | return datetime.datetime(year, month, day).strftime('%A') 34 | -------------------------------------------------------------------------------- /questions/day-of-the-year/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year. 4 |   5 | Example 1: 6 | 7 | Input: date = "2019-01-09" 8 | Output: 9 9 | Explanation: Given date is the 9th day of the year in 2019. 10 | 11 | Example 2: 12 | 13 | Input: date = "2019-02-10" 14 | Output: 41 15 | 16 |   17 | Constraints: 18 | 19 | date.length == 10 20 | date[4] == date[7] == '-', and all other date[i]'s are digits 21 | date represents a calendar date between Jan 1st, 1900 and Dec 31th, 2019. 22 | 23 | 24 | """ 25 | 26 | 27 | from datetime import datetime 28 | 29 | class Solution: 30 | def dayOfYear(self, date: str) -> int: 31 | dt = datetime.strptime(date, '%Y-%m-%d') 32 | return dt.timetuple().tm_yday 33 | -------------------------------------------------------------------------------- /questions/deepest-leaves-sum/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a binary tree, return the sum of values of its deepest leaves. 4 |   5 | Example 1: 6 | 7 | 8 | Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] 9 | Output: 15 10 | 11 |   12 | Constraints: 13 | 14 | The number of nodes in the tree is between 1 and 10^4. 15 | The value of nodes is between 1 and 100. 16 | 17 | """ 18 | 19 | 20 | # Definition for a binary tree node. 21 | # class TreeNode: 22 | # def __init__(self, val=0, left=None, right=None): 23 | # self.val = val 24 | # self.left = left 25 | # self.right = right 26 | class Solution: 27 | def deepestLeavesSum(self, root: TreeNode) -> int: 28 | stk = [root] 29 | while True: 30 | ne = [] 31 | for node in stk: 32 | if node.left is not None: 33 | ne.append(node.left) 34 | if node.right is not None: 35 | ne.append(node.right) 36 | if not ne: 37 | break 38 | stk = ne 39 | return sum([n.val for n in stk]) -------------------------------------------------------------------------------- /questions/defanging-an-ip-address/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a valid (IPv4) IP address, return a defanged version of that IP address. 4 | A defanged IP address replaces every period "." with "[.]". 5 |   6 | Example 1: 7 | Input: address = "1.1.1.1" 8 | Output: "1[.]1[.]1[.]1" 9 | Example 2: 10 | Input: address = "255.100.50.0" 11 | Output: "255[.]100[.]50[.]0" 12 | 13 |   14 | Constraints: 15 | 16 | The given address is a valid IPv4 address. 17 | 18 | """ 19 | 20 | 21 | class Solution: 22 | def defangIPaddr(self, address: str) -> str: 23 | return '[.]'.join(address.split('.')) -------------------------------------------------------------------------------- /questions/delete-duplicate-emails/Solution.sql: -------------------------------------------------------------------------------- 1 | -- Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id. 2 | 3 | -- +----+------------------+ 4 | -- | Id | Email | 5 | -- +----+------------------+ 6 | -- | 1 | john@example.com | 7 | -- | 2 | bob@example.com | 8 | -- | 3 | john@example.com | 9 | -- +----+------------------+ 10 | -- Id is the primary key column for this table. 11 | 12 | -- For example, after running your query, the above Person table should have the following rows: 13 | 14 | -- +----+------------------+ 15 | -- | Id | Email | 16 | -- +----+------------------+ 17 | -- | 1 | john@example.com | 18 | -- | 2 | bob@example.com | 19 | -- +----+------------------+ 20 | 21 | # Write your MySQL query statement below 22 | Delete a1 from Person a1 join Person a2 on a1.id > a2.id and a1.email = a2.email; 23 | -------------------------------------------------------------------------------- /questions/delete-node-in-a-linked-list/Solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a function to delete a node (except the tail) 3 | * in a singly linked list, given only access to that node. 4 | * 5 | * Supposed the linked list is 1 -> 2 -> 3 -> 4 and you 6 | * are given the third node with value 3, the linked list 7 | * should become 1 -> 2 -> 4 after calling your function. 8 | */ 9 | 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * struct ListNode { 14 | * int val; 15 | * ListNode *next; 16 | * ListNode(int x) : val(x), next(NULL) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | /** 22 | * copy values over from the rest of the list 23 | * @node: pointer to the node to be deleted 24 | */ 25 | void deleteNode(ListNode* node) { 26 | if (node == NULL) { 27 | return; 28 | } 29 | ListNode* next = node -> next; 30 | 31 | if (next != NULL) { 32 | node->val = next->val; 33 | node->next = next->next; 34 | 35 | delete next; 36 | } 37 | 38 | } 39 | }; -------------------------------------------------------------------------------- /questions/detect-capital/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a word, you need to judge whether the usage of capitals in it is right or not. 4 | We define the usage of capitals in a word to be right when one of the following cases holds: 5 | 6 | All letters in this word are capitals, like "USA". 7 | All letters in this word are not capitals, like "leetcode". 8 | Only the first letter in this word is capital, like "Google". 9 | 10 | Otherwise, we define that this word doesn't use capitals in a right way. 11 | 12 |   13 | Example 1: 14 | 15 | Input: "USA" 16 | Output: True 17 | 18 |   19 | Example 2: 20 | 21 | Input: "FlaG" 22 | Output: False 23 | 24 |   25 | Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters. 26 | 27 | """ 28 | 29 | 30 | class Solution: 31 | def detectCapitalUse(self, word: str) -> bool: 32 | return word.isupper() or word.islower() or word == word.title() -------------------------------------------------------------------------------- /questions/duplicate-emails/Solution.sql: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a SQL query to find all duplicate emails in a table named Person. 3 | * 4 | * +----+---------+ 5 | * | Id | Email | 6 | * +----+---------+ 7 | * | 1 | a@b.com | 8 | * | 2 | c@d.com | 9 | * | 3 | a@b.com | 10 | * +----+---------+ 11 | * For example, your query should return the following for the above table: 12 | * 13 | * +---------+ 14 | * | Email | 15 | * +---------+ 16 | * | a@b.com | 17 | * +---------+ 18 | * Note: All emails are in lowercase. 19 | */ 20 | select Email from Person group by Email having count(Email) > 1; 21 | -------------------------------------------------------------------------------- /questions/edit-distance/Solution.cpp: -------------------------------------------------------------------------------- 1 | 2 | //Problem Link : https://leetcode.com/problems/edit-distance/ 3 | //Technique Used : DP 4 | 5 | class Solution { 6 | public: 7 | int minDistance(string word1, string word2) { 8 | int n=word1.length(); 9 | int m=word2.length(); 10 | int dp[n+1][m+1]; 11 | for(int i=0;i<=n;i++){ 12 | for(int j=0;j<=m;j++){ 13 | if(i==0) 14 | dp[i][j]=j; 15 | else if(j==0) 16 | dp[i][j]=i; 17 | else if(word1[i-1]==word2[j-1]) 18 | dp[i][j]=dp[i-1][j-1]; 19 | else 20 | dp[i][j]=1+min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1])); 21 | 22 | } 23 | } 24 | return dp[n][m]; 25 | } 26 | }; -------------------------------------------------------------------------------- /questions/employees-earning-more-than-their-managers/Solution.sql: -------------------------------------------------------------------------------- 1 | /** 2 | * The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id. 3 | * 4 | * +----+-------+--------+-----------+ 5 | * | Id | Name | Salary | ManagerId | 6 | * +----+-------+--------+-----------+ 7 | * | 1 | Joe | 70000 | 3 | 8 | * | 2 | Henry | 80000 | 4 | 9 | * | 3 | Sam | 60000 | NULL | 10 | * | 4 | Max | 90000 | NULL | 11 | * +----+-------+--------+-----------+ 12 | * Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager. 13 | * 14 | * +----------+ 15 | * | Employee | 16 | * +----------+ 17 | * | Joe | 18 | * +----------+ 19 | */ 20 | select e.name as Employee from Employee as e join Employee as e2 on e.ManagerId = e2.Id where e.Salary > e2.Salary; 21 | -------------------------------------------------------------------------------- /questions/encode-and-decode-strings/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Codec: 8 | 9 | def encode(self, strs): 10 | """Encodes a list of strings to a single string. 11 | 12 | :type strs: List[str] 13 | :rtype: str 14 | """ 15 | return ''.join('%d:' % len(s) + s for s in strs) 16 | 17 | 18 | def decode(self, s): 19 | """Decodes a single string to a list of strings. 20 | 21 | :type s: str 22 | :rtype: List[str] 23 | """ 24 | strs = [] 25 | i = 0 26 | while i < len(s): 27 | j = s.find(':', i) 28 | i = j + 1 + int(s[i:j]) 29 | strs.append(s[j+1:i]) 30 | return strs 31 | 32 | 33 | # Your Codec object will be instantiated and called as such: 34 | # codec = Codec() 35 | # codec.decode(codec.encode(strs)) -------------------------------------------------------------------------------- /questions/encode-and-decode-tinyurl/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Note: This is a companion problem to the System Design problem: Design TinyURL. 4 | 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. 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. 6 | 7 | """ 8 | 9 | 10 | class Codec: 11 | 12 | def __init__(self): 13 | self.urls = [] 14 | 15 | def encode(self, longUrl): 16 | self.urls.append(longUrl) 17 | return 'http://tinyurl.com/' + str(len(self.urls) - 1) 18 | 19 | def decode(self, shortUrl): 20 | return self.urls[int(shortUrl.split('/')[-1])] 21 | 22 | 23 | # Your Codec object will be instantiated and called as such: 24 | # codec = Codec() 25 | # codec.decode(codec.encode(url)) -------------------------------------------------------------------------------- /questions/excel-sheet-column-number/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a column title as appear in an Excel sheet, return its corresponding column number. 3 | 4 | For example: 5 | 6 | A -> 1 7 | B -> 2 8 | C -> 3 9 | ... 10 | Z -> 26 11 | AA -> 27 12 | AB -> 28 13 | ... 14 | Example 1: 15 | 16 | Input: "A" 17 | Output: 1 18 | Example 2: 19 | 20 | Input: "AB" 21 | Output: 28 22 | Example 3: 23 | 24 | Input: "ZY" 25 | Output: 701 26 | """ 27 | 28 | 29 | class Solution: 30 | def titleToNumber(self, s: str) -> int: 31 | ret = 0 32 | for c in s: 33 | n = ord(c) - ord('A') + 1 34 | ret = ret * 26 + n 35 | return ret 36 | -------------------------------------------------------------------------------- /questions/excel-sheet-column-title/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 3 | 4 | For example: 5 | 6 | 1 -> A 7 | 2 -> B 8 | 3 -> C 9 | ... 10 | 26 -> Z 11 | 27 -> AA 12 | 28 -> AB 13 | ... 14 | Example 1: 15 | 16 | Input: 1 17 | Output: "A" 18 | Example 2: 19 | 20 | Input: 28 21 | Output: "AB" 22 | Example 3: 23 | 24 | Input: 701 25 | Output: "ZY" 26 | """ 27 | 28 | 29 | class Solution: 30 | def convertToTitle(self, n: int) -> str: 31 | def find_char(c): 32 | return chr(ord('A') + c - 1) 33 | 34 | ret = [] 35 | while n > 0: 36 | n, r = divmod(n, 26) 37 | if r == 0: 38 | r = 26 39 | n -= 1 40 | ret.append(find_char(r)) 41 | return ''.join(reversed(ret)) 42 | -------------------------------------------------------------------------------- /questions/factorial-trailing-zeroes/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer n, return the number of trailing zeroes in n!. 3 | 4 | Example 1: 5 | 6 | Input: 3 7 | Output: 0 8 | Explanation: 3! = 6, no trailing zero. 9 | Example 2: 10 | 11 | Input: 5 12 | Output: 1 13 | Explanation: 5! = 120, one trailing zero. 14 | Note: Your solution should be in logarithmic time complexity. 15 | """ 16 | 17 | class Solution: 18 | def trailingZeroes(self, n: int) -> int: 19 | ret = 0 20 | while n > 0: 21 | n, r = divmod(n, 5) 22 | ret += n 23 | return ret 24 | -------------------------------------------------------------------------------- /questions/fibonacci-number/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 4 | 5 | F(0) = 0, F(1) = 1 6 | F(n) = F(n - 1) + F(n - 2), for n > 1. 7 | 8 | Given n, calculate F(n). 9 |   10 | Example 1: 11 | 12 | Input: n = 2 13 | Output: 1 14 | Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 15 | 16 | Example 2: 17 | 18 | Input: n = 3 19 | Output: 2 20 | Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 21 | 22 | Example 3: 23 | 24 | Input: n = 4 25 | Output: 3 26 | Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 27 | 28 |   29 | Constraints: 30 | 31 | 0 <= n <= 30 32 | 33 | 34 | """ 35 | 36 | 37 | class Solution: 38 | def fib(self, n: int) -> int: 39 | if n == 0: 40 | return 0 41 | elif n == 1: 42 | return 1 43 | prev, curr = 0, 1 44 | while n >= 2: 45 | prev, curr = curr, prev + curr 46 | n -= 1 47 | return curr -------------------------------------------------------------------------------- /questions/find-all-duplicates-in-an-array/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 4 | Find all the elements that appear twice in this array. 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 | 15 | """ 16 | 17 | 18 | class Solution: 19 | def findDuplicates(self, nums: List[int]) -> List[int]: 20 | ret = [] 21 | for i in range(len(nums)): 22 | j = abs(nums[i]) - 1 23 | if nums[j] <= 0 : 24 | ret.append(j + 1) 25 | nums[j] = -nums[j] 26 | for i in range(len(nums)): 27 | if nums[i] <= 0: 28 | nums[i] = -nums[i] 29 | return ret -------------------------------------------------------------------------------- /questions/find-anagram-mappings/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def anagramMappings(self, A: List[int], B: List[int]) -> List[int]: 9 | indices = {} 10 | for i, n in enumerate(B): 11 | if n not in indices: 12 | indices[n] = [] 13 | indices[n].append(i) 14 | ans = [] 15 | for n in A: 16 | ans.append(indices[n].pop()) 17 | return ans -------------------------------------------------------------------------------- /questions/find-common-characters/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order. 4 |   5 | Example 1: 6 | Input: words = ["bella","label","roller"] 7 | Output: ["e","l","l"] 8 | Example 2: 9 | Input: words = ["cool","lock","cook"] 10 | Output: ["c","o"] 11 | 12 |   13 | Constraints: 14 | 15 | 1 <= words.length <= 100 16 | 1 <= words[i].length <= 100 17 | words[i] consists of lowercase English letters. 18 | 19 | 20 | """ 21 | 22 | 23 | class Solution: 24 | def commonChars(self, words: List[str]) -> List[str]: 25 | tr = Counter(words[0]) 26 | for word in words: 27 | counter = Counter(word) 28 | new_tr = {} 29 | for c in tr: 30 | if c not in counter: 31 | continue 32 | new_tr[c] = min(tr[c], counter[c]) 33 | tr = new_tr 34 | ret = [] 35 | for c, l in tr.items(): 36 | if l <= 0: 37 | continue 38 | for _ in range(l): 39 | ret.append(c) 40 | return ret -------------------------------------------------------------------------------- /questions/find-minimum-in-rotated-sorted-array/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 3 | 4 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 5 | 6 | Find the minimum element. 7 | 8 | You may assume no duplicate exists in the array. 9 | 10 | Example 1: 11 | 12 | Input: [3,4,5,1,2] 13 | Output: 1 14 | Example 2: 15 | 16 | Input: [4,5,6,7,0,1,2] 17 | Output: 0 18 | """ 19 | 20 | 21 | class Solution: 22 | def findMin(self, nums: List[int]) -> int: 23 | start, end = 0, len(nums) - 1 24 | while start < end: 25 | if start == end - 1: 26 | return nums[start] if nums[start] < nums[end] else nums[end] 27 | mid = (start + end) // 2 28 | if nums[start] > nums[end]: 29 | if nums[mid] > nums[start]: 30 | start = mid + 1 31 | else: 32 | end = mid 33 | else: 34 | return nums[start] 35 | return nums[start] 36 | -------------------------------------------------------------------------------- /questions/find-the-celebrity/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | # The knows API is already defined for you. 8 | # @param a, person a 9 | # @param b, person b 10 | # @return a boolean, whether a knows b 11 | # def knows(a, b): 12 | 13 | class Solution(object): 14 | def findCelebrity(self, n): 15 | """ 16 | :type n: int 17 | :rtype: int 18 | """ 19 | guess = 0 20 | for i in xrange(n): 21 | if knows(guess, i): 22 | guess = i 23 | for i in xrange(n): 24 | if i != guess and knows(guess, i): 25 | return -1 26 | for i in xrange(n): 27 | if i != guess and not knows(i, guess): 28 | return -1 29 | return guess -------------------------------------------------------------------------------- /questions/find-the-difference/Solution.py: -------------------------------------------------------------------------------- 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 | 20 | """ 21 | 22 | 23 | class Solution(object): 24 | def findTheDifference(self, s, t): 25 | """ 26 | :type s: str 27 | :type t: str 28 | :rtype: str 29 | """ 30 | mapping = [0] * 26 31 | for c in s: 32 | mapping[ord(c) - ord('a')] += 1 33 | for c in t: 34 | mapping[ord(c) - ord('a')] -= 1 35 | for idx, num in enumerate(mapping): 36 | if num < 0: 37 | return str(chr(ord('a') + idx)) 38 | return None 39 | -------------------------------------------------------------------------------- /questions/find-the-duplicate-number/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive) 3 | * Assume that there is only one duplicate number, find the duplicate one. 4 | * O(1) extra space. Smaller than O(n^2) time complexcity. 5 | * Input: [2,1,2] 6 | * Output: 2 7 | */ 8 | 9 | public class Solution { 10 | public int findDuplicate(int[] nums) { 11 | int btm=1, top=nums.length-1; 12 | while(btm != top){ 13 | int bigger_count=0, smaller_count=0, mid_count=0; 14 | int mid=(btm+top)/2; 15 | for(int i=0; i mid && nums[i] <= top) bigger_count++; 17 | else if(nums[i] <= mid && nums[i] >= btm) smaller_count++; 18 | } 19 | if(mid_count > 1) return mid; 20 | if(smaller_count > bigger_count){ 21 | top=mid; 22 | } 23 | else{ 24 | btm=mid+1; 25 | } 26 | } 27 | return btm; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /questions/first-missing-positive/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an unsorted integer array, find the smallest missing positive integer. 3 | 4 | Example 1: 5 | 6 | Input: [1,2,0] 7 | Output: 3 8 | Example 2: 9 | 10 | Input: [3,4,-1,1] 11 | Output: 2 12 | Example 3: 13 | 14 | Input: [7,8,9,11,12] 15 | Output: 1 16 | Follow up: 17 | 18 | Your algorithm should run in O(n) time and uses constant extra space. 19 | """ 20 | 21 | class Solution: 22 | def firstMissingPositive(self, nums: List[int]) -> int: 23 | for i, n in enumerate(nums): 24 | if n <= 0: 25 | nums[i] = 0 26 | for n in nums: 27 | i = abs(n) - 1 28 | if not (0 <= i < len(nums)): 29 | continue 30 | if nums[i] == 0: 31 | nums[i] = -inf 32 | elif nums[i] > 0: 33 | nums[i] = -nums[i] 34 | for i, n in enumerate(nums): 35 | if n >= 0: 36 | return i + 1 37 | return len(nums) + 1 38 | -------------------------------------------------------------------------------- /questions/first-unique-character-in-a-string/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. 4 | Examples: 5 | 6 | s = "leetcode" 7 | return 0. 8 | 9 | s = "loveleetcode" 10 | return 2. 11 | 12 |   13 | Note: You may assume the string contains only lowercase English letters. 14 | 15 | """ 16 | 17 | 18 | class Solution: 19 | def firstUniqChar(self, s: str) -> int: 20 | import collections 21 | track = collections.Counter(s) 22 | for i, c in enumerate(s): 23 | if track[c] == 1: 24 | return i 25 | return -1 -------------------------------------------------------------------------------- /questions/fixed-point/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def fixedPoint(self, A: List[int]) -> int: 9 | for i, a in enumerate(A): 10 | if i == a: 11 | return i 12 | return -1 -------------------------------------------------------------------------------- /questions/fizz-buzz/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Write a program that outputs the string representation of numbers from 1 to n. 4 | But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. 5 | Example: 6 | 7 | n = 15, 8 | 9 | Return: 10 | [ 11 | "1", 12 | "2", 13 | "Fizz", 14 | "4", 15 | "Buzz", 16 | "Fizz", 17 | "7", 18 | "8", 19 | "Fizz", 20 | "Buzz", 21 | "11", 22 | "Fizz", 23 | "13", 24 | "14", 25 | "FizzBuzz" 26 | ] 27 | 28 | 29 | """ 30 | 31 | 32 | class Solution: 33 | def fizzBuzz(self, n: int) -> List[str]: 34 | ret = [] 35 | for i in range(1, n + 1): 36 | r3, r5 = i % 3, i % 5 37 | if r3 == 0 and r5 == 0: 38 | ret.append('FizzBuzz') 39 | elif r3 == 0: 40 | ret.append('Fizz') 41 | elif r5 == 0: 42 | ret.append('Buzz') 43 | else: 44 | ret.append(str(i)) 45 | return ret -------------------------------------------------------------------------------- /questions/flatten-2d-vector/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Vector2D: 8 | 9 | def __init__(self, v: List[List[int]]): 10 | self.idx1 = 0 11 | self.idx2 = 0 12 | self.v = v 13 | 14 | def next(self) -> int: 15 | ls = self.v[self.idx1] 16 | elem = ls[self.idx2] 17 | if self.idx2 == len(ls) - 1: 18 | self.idx2 = 0 19 | self.idx1 += 1 20 | else: 21 | self.idx2 += 1 22 | return elem 23 | 24 | def hasNext(self) -> bool: 25 | while self.idx1 < len(self.v) and self.idx2 >= len(self.v[self.idx1]): 26 | self.idx2 = 0 27 | self.idx1 += 1 28 | if self.idx1 >= len(self.v): 29 | return False 30 | if self.idx2 >= len(self.v[self.idx1]): 31 | return False 32 | return True 33 | 34 | 35 | # Your Vector2D object will be instantiated and called as such: 36 | # obj = Vector2D(v) 37 | # param_1 = obj.next() 38 | # param_2 = obj.hasNext() -------------------------------------------------------------------------------- /questions/group-anagrams/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of strings, group anagrams together. 3 | 4 | Example: 5 | 6 | Input: ["eat", "tea", "tan", "ate", "nat", "bat"], 7 | Output: 8 | [ 9 | ["ate","eat","tea"], 10 | ["nat","tan"], 11 | ["bat"] 12 | ] 13 | Note: 14 | 15 | All inputs will be in lowercase. 16 | The order of your output does not matter. 17 | """ 18 | 19 | 20 | class Solution: 21 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 22 | import collections 23 | track = {} 24 | for ss in strs: 25 | cnts = collections.Counter(ss) 26 | cnts = tuple(sorted(cnts.items())) 27 | if cnts not in track: 28 | track[cnts] = [] 29 | track[cnts].append(ss) 30 | return [v for k, v in track.items()] 31 | -------------------------------------------------------------------------------- /questions/group-shifted-strings/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def groupStrings(self, strings: List[str]) -> List[List[str]]: 9 | track = {} 10 | for s in strings: 11 | diffs = [] 12 | for i, c in enumerate(s): 13 | if i == 0: 14 | continue 15 | diffs.append((ord(c) - ord(s[i - 1]) + 26) % 26) 16 | key = tuple(diffs) 17 | if key not in track: 18 | track[key] = [] 19 | track[key].append(s) 20 | return list(track.values()) -------------------------------------------------------------------------------- /questions/h-index-2/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Follow up for H-Index: What if the citations array is 3 | * sorted in ascending order? Could you optimize your algorithm? 4 | */ 5 | 6 | public class Solution { 7 | public int hIndex(int[] citations) { 8 | int length = citations.length; 9 | for (int i = 0 ; i < length ; i++) { 10 | if (citations[i] >= (length - i) && (i == 0 || citations[i-1] <= (length - i))) { 11 | return (length - i); 12 | } 13 | } 14 | 15 | return 0; 16 | } 17 | } -------------------------------------------------------------------------------- /questions/hamming-distance/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 3 | * 4 | * Given two integers x and y, calculate the Hamming distance. 5 | * 6 | * Note: 7 | * 0 ≤ x, y < 231. 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 | */ 23 | 24 | public class Solution { 25 | public int hammingDistance(int x, int y) { 26 | int diff = 0; 27 | for (int idx = 0; idx < 32; idx++) { 28 | if ((x >> idx & 1) != (y >> idx & 1)) { 29 | diff++; 30 | } 31 | } 32 | return diff; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /questions/implement-strstr/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Implement strStr(). 3 | * 4 | * Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 5 | */ 6 | 7 | public class Solution { 8 | /** 9 | * A more efficient implementation could be found 10 | * https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm 11 | */ 12 | public int strStr(String haystack, String needle) { 13 | int runner = 0; 14 | boolean found = false; 15 | boolean matching = true; 16 | while (needle.length() + runner <= haystack.length()) { 17 | matching = true; 18 | for (int i = 0; i < needle.length(); i++) { 19 | if (needle.charAt(i) != haystack.charAt(i + runner)) { 20 | matching = false; 21 | break; 22 | } 23 | } 24 | if (matching) { 25 | found = true; 26 | break; 27 | } 28 | runner++; 29 | } 30 | 31 | return found ? runner : -1; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /questions/inorder-successor-in-bst/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | # Definition for a binary tree node. 8 | # class TreeNode: 9 | # def __init__(self, x): 10 | # self.val = x 11 | # self.left = None 12 | # self.right = None 13 | 14 | class Solution: 15 | def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': 16 | def inorder(node): 17 | if node is None: 18 | return 19 | yield from inorder(node.left) 20 | yield node 21 | yield from inorder(node.right) 22 | 23 | prev = None 24 | for n in inorder(root): 25 | if prev is None: 26 | prev = n 27 | continue 28 | if prev == p: 29 | return n 30 | prev = n 31 | return None -------------------------------------------------------------------------------- /questions/insert-into-a-sorted-circular-linked-list/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | """ 8 | # Definition for a Node. 9 | class Node: 10 | def __init__(self, val, next): 11 | self.val = val 12 | self.next = next 13 | """ 14 | class Solution: 15 | def insert(self, head: 'Node', insertVal: int) -> 'Node': 16 | new_node = Node(insertVal, head) 17 | if not head: 18 | return new_node 19 | node = head 20 | while True: 21 | if node.next.val < node.val and (insertVal <= node.next.val or insertVal >= node.val): 22 | break 23 | elif node.val <= insertVal <= node.next.val: 24 | break 25 | elif node.next == head: 26 | break 27 | node = node.next 28 | new_node.next = node.next 29 | node.next = new_node 30 | return head -------------------------------------------------------------------------------- /questions/integer-break/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an integer n, break it into the sum of at least two positive integers and maximize the product of those integers. 4 | Return the maximum product you can get. 5 |   6 | Example 1: 7 | 8 | Input: n = 2 9 | Output: 1 10 | Explanation: 2 = 1 + 1, 1 × 1 = 1. 11 | 12 | Example 2: 13 | 14 | Input: n = 10 15 | Output: 36 16 | Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. 17 | 18 |   19 | Constraints: 20 | 21 | 2 <= n <= 58 22 | 23 | 24 | """ 25 | 26 | 27 | class Solution: 28 | def integerBreak(self, n: int) -> int: 29 | dp = [1 for _ in range(n + 1)] 30 | for i in range(3, n + 1): 31 | for j in range(1, i): 32 | dp[i] = max(dp[i], dp[j] * dp[i - j], j * dp[i - j], j * (i - j)) 33 | print(dp) 34 | return dp[-1] -------------------------------------------------------------------------------- /questions/invert-binary-tree/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Invert a binary tree. 3 | * 4 | * Example: 5 | * 6 | * Input: 7 | * 8 | * 4 9 | * / \ 10 | * 2 7 11 | * / \ / \ 12 | * 1 3 6 9 13 | * 14 | * Output: 15 | * 16 | * 4 17 | * / \ 18 | * 7 2 19 | * / \ / \ 20 | * 9 6 3 1 21 | */ 22 | /** 23 | * Definition for a binary tree node. 24 | * public class TreeNode { 25 | * int val; 26 | * TreeNode left; 27 | * TreeNode right; 28 | * TreeNode(int x) { val = x; } 29 | * } 30 | */ 31 | class Solution { 32 | public TreeNode invertTree(TreeNode root) { 33 | if (root == null) { 34 | return root; 35 | } 36 | TreeNode t = new TreeNode(root.val); 37 | t.left = invertTree(root.right); 38 | t.right = invertTree(root.left); 39 | return t; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /questions/invert-binary-tree/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Invert a binary tree. 3 | 4 | Example: 5 | 6 | Input: 7 | 8 | 4 9 | / \ 10 | 2 7 11 | / \ / \ 12 | 1 3 6 9 13 | Output: 14 | 15 | 4 16 | / \ 17 | 7 2 18 | / \ / \ 19 | 9 6 3 1 20 | Trivia: 21 | This problem was inspired by this original tweet by Max Howell: 22 | 23 | Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off. 24 | """ 25 | 26 | 27 | # Definition for a binary tree node. 28 | # class TreeNode: 29 | # def __init__(self, x): 30 | # self.val = x 31 | # self.left = None 32 | # self.right = None 33 | 34 | class Solution: 35 | def invertTree(self, root: TreeNode) -> TreeNode: 36 | if root is None: 37 | return None 38 | left = self.invertTree(root.right) 39 | right = self.invertTree(root.left) 40 | root.left = left 41 | root.right = right 42 | return root 43 | -------------------------------------------------------------------------------- /questions/is-subsequence/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isSubsequence(String s, String t) { 3 | 4 | if(s.length()>t.length()) 5 | return false; 6 | 7 | if(s.length() == 0){ 8 | return true; 9 | } 10 | 11 | int j =0; 12 | 13 | for(int i=0; i int: 31 | ret = 0 32 | nd, cd = 0, 0 33 | for i in range(len(nums) - 1): 34 | n = nums[i] 35 | nd = max(n + i, nd) 36 | if cd == i: 37 | ret += 1 38 | cd = nd 39 | return ret -------------------------------------------------------------------------------- /questions/jump-game/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of non-negative integers, you are initially positioned at the 3 | * first index of the array. 4 | * 5 | * Each element in the array represents your maximum jump length at that position. 6 | * 7 | * Determine if you are able to reach the last index. 8 | * 9 | * For example: 10 | * A = [2,3,1,1,4], return true. 11 | * 12 | * A = [3,2,1,0,4], return false. 13 | */ 14 | 15 | public class Solution { 16 | public boolean canJump(int[] nums) { 17 | int maxIdx = 0, tmp; 18 | for (int i = 0 ; i < nums.length - 1; i++) { 19 | tmp = i + nums[i]; 20 | maxIdx = (maxIdx >= i && tmp > maxIdx) ? tmp : maxIdx; 21 | } 22 | 23 | return maxIdx >= (nums.length - 1); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /questions/k-th-symbol-in-grammar/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. 4 | Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed). 5 | 6 | Examples: 7 | Input: N = 1, K = 1 8 | Output: 0 9 | 10 | Input: N = 2, K = 1 11 | Output: 0 12 | 13 | Input: N = 2, K = 2 14 | Output: 1 15 | 16 | Input: N = 4, K = 5 17 | Output: 1 18 | 19 | Explanation: 20 | row 1: 0 21 | row 2: 01 22 | row 3: 0110 23 | row 4: 01101001 24 | 25 | Note: 26 | 27 | N will be an integer in the range [1, 30]. 28 | K will be an integer in the range [1, 2^(N-1)]. 29 | 30 | 31 | """ 32 | 33 | 34 | class Solution: 35 | def kthGrammar(self, N: int, K: int) -> int: 36 | if N == 1: 37 | return 0 38 | elif N == 2: 39 | if K == 1: 40 | return 0 41 | else: 42 | return 1 43 | prev = self.kthGrammar(N - 1, (K + 1) >> 1) 44 | if prev == K & 1: 45 | return 1 46 | return 0 -------------------------------------------------------------------------------- /questions/kth-largest-element-in-an-array/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find the kth largest element in an unsorted array. 3 | Note that it is the kth largest element in the sorted order, 4 | not the kth distinct element. 5 | 6 | Example 1: 7 | 8 | Input: [3,2,1,5,6,4] and k = 2 9 | Output: 5 10 | 11 | Example 2: 12 | 13 | Input: [3,2,3,1,2,4,5,5,6] and k = 4 14 | Output: 4 15 | 16 | Note: 17 | You may assume k is always valid, 1 ≤ k ≤ array's length. 18 | """ 19 | 20 | import heapq 21 | 22 | class Solution: 23 | def findKthLargest(self, nums, k): 24 | """ 25 | :type nums: List[int] 26 | :type k: int 27 | :rtype: int 28 | """ 29 | return heapq.nlargest(k, nums)[-1] 30 | 31 | -------------------------------------------------------------------------------- /questions/kth-smallest-element-in-a-sorted-matrix/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | 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. 4 | 5 | Note that it is the kth smallest element in the sorted order, not the kth distinct element. 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 | Note: 20 | You may assume k is always valid, 1 ≤ k ≤ n2. 21 | """ 22 | 23 | 24 | import heapq 25 | 26 | 27 | class Solution: 28 | def kthSmallest(self, matrix: List[List[int]], k: int) -> int: 29 | ## method 1, using heap 30 | hp = [(row[0], 0, i) for i, row in enumerate(matrix)] 31 | heapq.heapify(hp) 32 | for _ in range(k): 33 | curr, idx, row_idx = heapq.heappop(hp) 34 | idx += 1 35 | if idx < len(matrix[row_idx]): 36 | heapq.heappush(hp, (matrix[row_idx][idx], idx, row_idx)) 37 | return curr -------------------------------------------------------------------------------- /questions/kth-smallest-number-in-multiplication-table/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed). 4 | Given three integers m, n, and k, return the kth smallest element in the m x n multiplication table. 5 |   6 | Example 1: 7 | 8 | 9 | Input: m = 3, n = 3, k = 5 10 | Output: 3 11 | Explanation: The 5th smallest number is 3. 12 | 13 | Example 2: 14 | 15 | 16 | Input: m = 2, n = 3, k = 6 17 | Output: 6 18 | Explanation: The 6th smallest number is 6. 19 | 20 |   21 | Constraints: 22 | 23 | 1 <= m, n <= 3 * 104 24 | 1 <= k <= m * n 25 | 26 | 27 | """ 28 | 29 | 30 | class Solution: 31 | def findKthNumber(self, m: int, n: int, k: int) -> int: 32 | def count(x): 33 | return sum(min(x//i, n) for i in range(1,m+1)) 34 | 35 | L, R, mid, ans = 0, m*n, 0, 0 36 | while L <= R: 37 | mid = (L + R) >> 1 38 | if count(mid) < k: 39 | L = mid + 1 40 | else: 41 | R, ans = mid - 1, mid 42 | return ans -------------------------------------------------------------------------------- /questions/largest-number/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a list of non negative integers, arrange them such that they form the largest number. 3 | 4 | Example 1: 5 | 6 | Input: [10,2] 7 | Output: "210" 8 | Example 2: 9 | 10 | Input: [3,30,34,5,9] 11 | Output: "9534330" 12 | Note: The result may be very large, so you need to return a string instead of an integer. 13 | """ 14 | 15 | import functools 16 | 17 | class Solution: 18 | def largestNumber(self, nums: List[int]) -> str: 19 | def cmp(a, b): 20 | n1 = int(str(a) + str(b)) 21 | n2 = int(str(b) + str(a)) 22 | return n2 - n1 23 | 24 | ns = sorted(nums, key=functools.cmp_to_key(cmp)) 25 | ret = ''.join((str(n) for n in ns)) 26 | if ret and ret[0] == '0': 27 | return '0' 28 | return ret 29 | -------------------------------------------------------------------------------- /questions/leftmost-column-with-at-least-a-one/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | # """ 8 | # This is BinaryMatrix's API interface. 9 | # You should not implement it, or speculate about its implementation 10 | # """ 11 | #class BinaryMatrix(object): 12 | # def get(self, x: int, y: int) -> int: 13 | # def dimensions(self) -> list[]: 14 | 15 | class Solution: 16 | def leftMostColumnWithOne(self, mat: 'BinaryMatrix') -> int: 17 | n, m = mat.dimensions() 18 | ret = -1 19 | x, y = 0, m - 1 20 | while y >= 0 and x < n: 21 | val = mat.get(x, y) 22 | if val == 0: 23 | x += 1 24 | else: 25 | ret = y 26 | y -= 1 27 | return ret -------------------------------------------------------------------------------- /questions/length-of-last-word/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', 3 | * return the length of last word in the string. 4 | * 5 | * If the last word does not exist, return 0. 6 | * 7 | * Note: A word is defined as a character sequence consists of non-space characters only. 8 | * 9 | * For example, 10 | * Given s = "Hello World", 11 | * return 5. 12 | */ 13 | 14 | public class Solution { 15 | public int lengthOfLastWord(String s) { 16 | if (s == null || s.isEmpty()) { 17 | return 0; 18 | } 19 | int len = 0; 20 | boolean inWord = false; 21 | for (int i = s.length() - 1; i >= 0; i--) { 22 | if (s.charAt(i) == ' ') { 23 | if (inWord) { 24 | return len; 25 | } 26 | } else { 27 | len++; 28 | inWord = true; 29 | } 30 | } 31 | return len; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /questions/letter-case-permutation/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. 3 | 4 | Examples: 5 | Input: S = "a1b2" 6 | Output: ["a1b2", "a1B2", "A1b2", "A1B2"] 7 | 8 | Input: S = "3z4" 9 | Output: ["3z4", "3Z4"] 10 | 11 | Input: S = "12345" 12 | Output: ["12345"] 13 | Note: 14 | 15 | S will be a string with length at most 12. 16 | S will consist only of letters or digits. 17 | """ 18 | class Solution(object): 19 | def letterCasePermutation(self, S): 20 | """ 21 | :type S: str 22 | :rtype: List[str] 23 | """ 24 | r = [''] 25 | for c in S: 26 | tmp = [] 27 | if c.isalpha(): 28 | for s in r: 29 | tmp.append(s + c.lower()) 30 | tmp.append(s + c.upper()) 31 | else: 32 | for s in r: 33 | tmp.append(s + c) 34 | r = tmp 35 | return r 36 | 37 | -------------------------------------------------------------------------------- /questions/linked-list-cycle/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a linked list, determine if it has a cycle in it. 3 | * 4 | * Follow up: 5 | * Can you solve it without using extra space? 6 | */ 7 | 8 | /** 9 | * Definition for singly-linked list. 10 | * class ListNode { 11 | * int val; 12 | * ListNode next; 13 | * ListNode(int x) { 14 | * val = x; 15 | * next = null; 16 | * } 17 | * } 18 | */ 19 | public class Solution { 20 | public boolean hasCycle(ListNode head) { 21 | if (head == null) { 22 | return false; 23 | } 24 | ListNode fast = head.next; 25 | ListNode slow = head; 26 | while (fast != null && slow != null) { 27 | if (fast.next == null) { 28 | return false; 29 | } 30 | if (fast == slow) { 31 | return true; 32 | } 33 | fast = fast.next.next; 34 | slow = slow.next; 35 | } 36 | 37 | return false; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /questions/logger-rate-limiter/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Logger: 8 | 9 | def __init__(self): 10 | """ 11 | Initialize your data structure here. 12 | """ 13 | self.track = {} 14 | 15 | def shouldPrintMessage(self, timestamp: int, message: str) -> bool: 16 | """ 17 | Returns true if the message should be printed in the given timestamp, otherwise returns false. 18 | If this method returns false, the message will not be printed. 19 | The timestamp is in seconds granularity. 20 | """ 21 | if message not in self.track: 22 | ret = True 23 | else: 24 | ret = timestamp - self.track[message] >= 10 25 | if ret: 26 | self.track[message] = timestamp 27 | return ret 28 | 29 | 30 | # Your Logger object will be instantiated and called as such: 31 | # obj = Logger() 32 | # param_1 = obj.shouldPrintMessage(timestamp,message) -------------------------------------------------------------------------------- /questions/longest-common-prefix/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a function to find the longest common prefix string amongst an array of strings. 3 | */ 4 | 5 | public class Solution { 6 | public String longestCommonPrefix(String[] strs) { 7 | if (strs == null || strs.length <= 0) { 8 | return ""; 9 | } else if (strs.length == 1) { 10 | return strs[0]; 11 | } 12 | StringBuilder sb = new StringBuilder(); 13 | int currPos = 0; 14 | char currChar = 'a'; 15 | while (true) { 16 | if (strs[0].length() > currPos) { 17 | currChar = strs[0].charAt(currPos); 18 | } else { 19 | break; 20 | } 21 | for (int i = 0; i < strs.length; i++) { 22 | if (strs[i].length() > currPos && strs[i].charAt(currPos) == currChar) { 23 | continue; 24 | } else { 25 | return sb.toString(); 26 | } 27 | } 28 | sb.append(currChar); 29 | currPos++; 30 | } 31 | 32 | return sb.toString(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /questions/longest-palindromic-subsequence/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. 4 | Example 1: 5 | Input: 6 | 7 | "bbbab" 8 | 9 | Output: 10 | 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 | 25 | 2 26 | 27 | One possible longest palindromic subsequence is "bb". 28 |   29 | Constraints: 30 | 31 | 1 <= s.length <= 1000 32 | s consists only of lowercase English letters. 33 | 34 | 35 | """ 36 | 37 | 38 | class Solution: 39 | def longestPalindromeSubseq(self, s: str) -> int: 40 | n = len(s) 41 | dp = [[1] * n for _ in range(n)] 42 | for j in range(1, len(s)): 43 | for i in reversed(range(0, j)): 44 | if s[i] == s[j]: 45 | dp[i][j] = 2 + dp[i + 1][(j - 1)] if i + 1 <= j - 1 else 2 46 | else: 47 | dp[i][j] = max(dp[i + 1][j], dp[i][(j - 1)]) 48 | return dp[0][(n-1)] -------------------------------------------------------------------------------- /questions/longest-substring-with-at-most-k-distinct-characters/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int: 9 | counter = {} 10 | start = 0 11 | m_len = 0 12 | for i, c in enumerate(s): 13 | if c not in counter: 14 | counter[c] = 1 15 | else: 16 | counter[c] += 1 17 | while len(counter.keys()) > k: 18 | counter[s[start]] -= 1 19 | if counter[s[start]] == 0: 20 | del counter[s[start]] 21 | start += 1 22 | m_len = max(m_len, i - start + 1) 23 | return m_len -------------------------------------------------------------------------------- /questions/longest-substring-with-at-most-two-distinct-characters/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int: 9 | counter = {} 10 | max_cnt, start = 0, 0 11 | for i, c in enumerate(s): 12 | if c not in counter: 13 | counter[c] = 0 14 | counter[c] += 1 15 | while len(counter) > 2 and start <= i: 16 | counter[s[start]] -= 1 17 | if counter[s[start]] == 0: 18 | del counter[s[start]] 19 | start += 1 20 | max_cnt = max(max_cnt, i - start + 1) 21 | return max_cnt -------------------------------------------------------------------------------- /questions/longest-substring-without-repeating-characters/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a string, find the length of the longest substring without repeating characters. For example, the 3 | * longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the 4 | * longest substring is "b", with the length of 1. 5 | */ 6 | 7 | public class Solution { 8 | public int lengthOfLongestSubstring(String s) { 9 | int ans=0, l=0, last_index=0; 10 | HashMap map = new HashMap (); 11 | for(int i=0; ians) ans=l; 15 | map.put(s.charAt(i),i); 16 | } 17 | else{ 18 | if(last_index<=map.get(s.charAt(i))){ 19 | last_index = map.get(s.charAt(i))+1; 20 | } 21 | l = i-last_index+1; 22 | if(l>ans) ans=l; 23 | map.put(s.charAt(i),i); 24 | } 25 | } 26 | return ans; 27 | } 28 | } -------------------------------------------------------------------------------- /questions/majority-element/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of size n, find the majority element. The majority element is the element 3 | * that appears more than ⌊ n/2 ⌋ times. 4 | * 5 | * You may assume that the array is non-empty and the majority element always exist in the array. 6 | */ 7 | 8 | public class Solution { 9 | public int majorityElement(int[] nums) { 10 | int cnt = 1, tmp = nums[0]; 11 | 12 | for (int i = 1; i < nums.length; i++) { 13 | if (cnt == 0) { 14 | tmp = nums[i]; 15 | } 16 | if (nums[i] == tmp) { 17 | cnt++; 18 | } else { 19 | cnt--; 20 | } 21 | } 22 | 23 | return tmp; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /questions/majority-element/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 3 | 4 | You may assume that the array is non-empty and the majority element always exist in the array. 5 | 6 | Example 1: 7 | 8 | Input: [3,2,3] 9 | Output: 3 10 | Example 2: 11 | 12 | Input: [2,2,1,1,1,2,2] 13 | Output: 2 14 | """ 15 | 16 | 17 | class Solution: 18 | def majorityElement(self, nums: List[int]) -> int: 19 | vote = nums[0] 20 | count = 0 21 | for num in nums: 22 | if num == vote: 23 | count += 1 24 | else: 25 | count -= 1 26 | if count <= 0: 27 | vote = num 28 | count = 1 29 | return vote 30 | -------------------------------------------------------------------------------- /questions/max-consecutive-ones-ii/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def findMaxConsecutiveOnes(self, nums: List[int]) -> int: 9 | mmax = 0 10 | start = 0 11 | zeros = 0 12 | for i, n in enumerate(nums): 13 | if n == 1: 14 | mmax = max(mmax, i - start + 1) 15 | else: 16 | zeros += 1 17 | while zeros > 1: 18 | if nums[start] == 0: 19 | zeros -= 1 20 | start += 1 21 | mmax = max(mmax, i - start + 1) 22 | return max(mmax, len(nums) - start) -------------------------------------------------------------------------------- /questions/max-consecutive-ones/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a binary array, find the maximum number of consecutive 1s in this array. 3 | * 4 | * Example 1: 5 | * 6 | * Input: [1,1,0,1,1,1] 7 | * Output: 3 8 | * Explanation: 9 | * The first two digits or the last three digits are consecutive 1s. 10 | * The maximum number of consecutive 1s is 3. 11 | * 12 | * Note: 13 | * The input array will only contain 0 and 1. 14 | * The length of input array is a positive integer and will not exceed 10,000 15 | * 16 | */ 17 | 18 | class Solution { 19 | public int findMaxConsecutiveOnes(int[] nums) { 20 | int max = 0; 21 | int curr = 0; 22 | for (int i = 0; i < nums.length; i++) { 23 | if (nums[i] == 1) { 24 | curr += 1; 25 | } else { 26 | if (max < curr) { 27 | max = curr; 28 | } 29 | curr = 0; 30 | } 31 | } 32 | if (max < curr) { 33 | max = curr; 34 | } 35 | return max; 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /questions/maximal-square/Solution.py: -------------------------------------------------------------------------------- 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 | Example: 5 | 6 | Input: 7 | 8 | 1 0 1 0 0 9 | 1 0 1 1 1 10 | 1 1 1 1 1 11 | 1 0 0 1 0 12 | 13 | Output: 4 14 | """ 15 | 16 | 17 | class Solution: 18 | def maximalSquare(self, matrix: List[List[str]]) -> int: 19 | dp = [[0] * len(matrix[0]) for _ in range(len(matrix))] 20 | ans = 0 21 | for i in range(len(matrix)): 22 | for j in range(len(matrix[0])): 23 | if i == 0 or j == 0: 24 | dp[i][j] = int(matrix[i][j]) 25 | else: 26 | if matrix[i][j] == '1': 27 | dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1 28 | ans = max(ans, dp[i][j]) 29 | return ans * ans 30 | 31 | -------------------------------------------------------------------------------- /questions/maximum-69-number/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | You are given a positive integer num consisting only of digits 6 and 9. 4 | Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6). 5 |   6 | Example 1: 7 | 8 | Input: num = 9669 9 | Output: 9969 10 | Explanation: 11 | Changing the first digit results in 6669. 12 | Changing the second digit results in 9969. 13 | Changing the third digit results in 9699. 14 | Changing the fourth digit results in 9666. 15 | The maximum number is 9969. 16 | 17 | Example 2: 18 | 19 | Input: num = 9996 20 | Output: 9999 21 | Explanation: Changing the last digit 6 to 9 results in the maximum number. 22 | 23 | Example 3: 24 | 25 | Input: num = 9999 26 | Output: 9999 27 | Explanation: It is better not to apply any change. 28 | 29 |   30 | Constraints: 31 | 32 | 1 <= num <= 104 33 | num consists of only 6 and 9 digits. 34 | 35 | 36 | """ 37 | 38 | 39 | class Solution: 40 | def maximum69Number (self, num: int) -> int: 41 | s = list(str(num)) 42 | for i, e in enumerate(s): 43 | if e == '6': 44 | s[i] = '9' 45 | break 46 | return int(''.join(s)) -------------------------------------------------------------------------------- /questions/maximum-average-subarray-i/Solution.py: -------------------------------------------------------------------------------- 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 | Example 1: 5 | Input: [1,12,-5,-6,50,3], k = 4 6 | Output: 12.75 7 | Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75 8 | Note: 9 | 1 <= k <= n <= 30,000. 10 | Elements of the given array will be in the range [-10,000, 10,000]. 11 | """ 12 | class Solution(object): 13 | def findMaxAverage(self, nums, k): 14 | """ 15 | :type nums: List[int] 16 | :type k: int 17 | :rtype: float 18 | """ 19 | m, s = None, 0 20 | for i, n in enumerate(nums): 21 | if i < k: 22 | s += n 23 | continue 24 | if m is None: 25 | m = s 26 | s = s + n - nums[i - k] 27 | m = max(m, s) 28 | if m is None: 29 | m = s 30 | return m / float(k) 31 | 32 | -------------------------------------------------------------------------------- /questions/maximum-depth-of-binary-tree/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a binary tree, find its maximum depth. 3 | * 4 | * The maximum depth is the number of nodes along the longest path 5 | * from the root node down to the farthest leaf node. 6 | */ 7 | 8 | /** 9 | * Definition for a binary tree node. 10 | * public class TreeNode { 11 | * int val; 12 | * TreeNode left; 13 | * TreeNode right; 14 | * TreeNode(int x) { val = x; } 15 | * } 16 | */ 17 | public class Solution { 18 | public int maxDepth(TreeNode root) { 19 | if (root == null) { 20 | return 0; 21 | } 22 | int leftDepth = maxDepth(root.left); 23 | int rightDepth = maxDepth(root.right); 24 | return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /questions/maximum-depth-of-binary-tree/Solution.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, find its maximum depth. 3 | 4 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 5 | 6 | Note: A leaf is a node with no children. 7 | 8 | Example: 9 | 10 | Given binary tree [3,9,20,null,null,15,7], 11 | 12 | 3 13 | / \ 14 | 9 20 15 | / \ 16 | 15 7 17 | return its depth = 3. 18 | 19 | 20 | ''' 21 | 22 | 23 | # Definition for a binary tree node. 24 | # class TreeNode: 25 | # def __init__(self, x): 26 | # self.val = x 27 | # self.left = None 28 | # self.right = None 29 | 30 | class Solution: 31 | def maxDepth(self, root: TreeNode) -> int: 32 | if root is None: 33 | return 0 34 | return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 35 | -------------------------------------------------------------------------------- /questions/maximum-number-of-balloons/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. 4 | You can use each character in text at most once. Return the maximum number of instances that can be formed. 5 |   6 | Example 1: 7 | 8 | 9 | Input: text = "nlaebolko" 10 | Output: 1 11 | 12 | Example 2: 13 | 14 | 15 | Input: text = "loonbalxballpoon" 16 | Output: 2 17 | 18 | Example 3: 19 | 20 | Input: text = "leetcode" 21 | Output: 0 22 | 23 |   24 | Constraints: 25 | 26 | 1 <= text.length <= 104 27 | text consists of lower case English letters only. 28 | 29 | 30 | """ 31 | 32 | 33 | class Solution: 34 | def maxNumberOfBalloons(self, text: str) -> int: 35 | base = Counter('balloon') 36 | tr = {} 37 | for a in text: 38 | if a not in base: 39 | continue 40 | tr[a] = tr.get(a, 0) + 1 41 | multiple = len(text) 42 | for k in base.keys(): 43 | if k not in tr: 44 | return 0 45 | multiple = min(multiple, tr[k] // base[k]) 46 | return multiple 47 | -------------------------------------------------------------------------------- /questions/maximum-product-of-three-numbers/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an integer array nums, find three numbers whose product is maximum and return the maximum product. 4 |   5 | Example 1: 6 | Input: nums = [1,2,3] 7 | Output: 6 8 | Example 2: 9 | Input: nums = [1,2,3,4] 10 | Output: 24 11 | Example 3: 12 | Input: nums = [-1,-2,-3] 13 | Output: -6 14 | 15 |   16 | Constraints: 17 | 18 | 3 <= nums.length <= 104 19 | -1000 <= nums[i] <= 1000 20 | 21 | 22 | """ 23 | 24 | 25 | class Solution(object): 26 | def maximumProduct(self, nums): 27 | """ 28 | :type nums: List[int] 29 | :rtype: int 30 | """ 31 | if len(nums) == 3: 32 | return nums[0] * nums[1] * nums[2] 33 | positive = sorted([n for n in nums if n >= 0]) 34 | negative = sorted([n for n in nums if n < 0]) 35 | cs1 = positive[-3:] 36 | cs2 = negative[:2] 37 | if len(cs1) < 3: 38 | return cs2[1] * cs2[0] * cs1[-1] 39 | m = cs1[1] * cs1[0] * cs1[2] 40 | if len(cs2) == 2: 41 | m = max(cs2[1] * cs2[0] * cs1[2], m) 42 | return m -------------------------------------------------------------------------------- /questions/maximum-size-subarray-sum-equals-k/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def maxSubArrayLen(self, nums: List[int], k: int) -> int: 9 | mm = 0 10 | sums = {0: -1} 11 | curr = 0 12 | for i, n in enumerate(nums): 13 | curr += n 14 | if curr - k in sums: 15 | mm = max(mm, i - sums[curr - k]) 16 | if curr not in sums: 17 | sums[curr] = i 18 | return mm -------------------------------------------------------------------------------- /questions/maximum-subarray/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 3 | * 4 | * For example, given the array [−2,1,−3,4,−1,2,1,−5,4], 5 | * the contiguous subarray [4,−1,2,1] has the largest sum = 6. 6 | */ 7 | 8 | public class Solution { 9 | public int maxSubArray(int[] nums) { 10 | if (nums == null || nums.length <= 0) { 11 | return 0; 12 | } 13 | int sum = 0, maxSofar = nums[0]; 14 | for (int i = 0; i < nums.length; i++) { 15 | sum += nums[i]; 16 | maxSofar = Math.max(maxSofar, sum); 17 | if (sum < 0) { 18 | sum = 0; 19 | } 20 | } 21 | 22 | return maxSofar; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /questions/meeting-rooms-ii/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def minMeetingRooms(self, intervals: List[List[int]]) -> int: 9 | from collections import Counter 10 | start = Counter([interval[0] for interval in intervals]) 11 | end = Counter([interval[1] for interval in intervals]) 12 | nums = set(start.keys()).union(set(end.keys())) 13 | mm = 0 14 | curr = 0 15 | for n in sorted(nums): 16 | if n in end: 17 | curr -= end[n] 18 | if n in start: 19 | curr += start[n] 20 | mm = max(mm, curr) 21 | return mm -------------------------------------------------------------------------------- /questions/meeting-rooms/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def canAttendMeetings(self, intervals: List[List[int]]) -> bool: 9 | intervals.sort() 10 | prev = None 11 | for interval in intervals: 12 | if prev is None: 13 | prev = interval 14 | continue 15 | if prev[1] > interval[0]: 16 | return False 17 | prev = interval 18 | return True -------------------------------------------------------------------------------- /questions/merge-intervals/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a collection of intervals, merge all overlapping intervals. 3 | 4 | Example 1: 5 | 6 | Input: [[1,3],[2,6],[8,10],[15,18]] 7 | Output: [[1,6],[8,10],[15,18]] 8 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 9 | Example 2: 10 | 11 | Input: [[1,4],[4,5]] 12 | Output: [[1,5]] 13 | Explanation: Intervals [1,4] and [4,5] are considered overlapping. 14 | NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature. 15 | """ 16 | 17 | 18 | class Solution: 19 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 20 | intervals.sort() 21 | ret = [] 22 | for i, interval in enumerate(intervals): 23 | if i == 0: 24 | ret.append(interval) 25 | continue 26 | if interval[0] > ret[-1][1]: 27 | ret.append(list(interval)) 28 | else: 29 | ret[-1][1] = max(ret[-1][1], interval[1]) 30 | return ret 31 | -------------------------------------------------------------------------------- /questions/merge-two-sorted-lists/Solution.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | Example: 5 | 6 | Input: 1->2->4, 1->3->4 7 | Output: 1->1->2->3->4->4 8 | ''' 9 | 10 | 11 | # Definition for singly-linked list. 12 | # class ListNode: 13 | # def __init__(self, x): 14 | # self.val = x 15 | # self.next = None 16 | 17 | class Solution: 18 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 19 | curr1, curr2, curr, nh = l1, l2, None, None 20 | while curr1 is not None or curr2 is not None: 21 | if curr1 is None or (curr2 is not None and curr2.val < curr1.val): 22 | if curr: 23 | curr.next = curr2 24 | curr = curr2 25 | curr2 = curr2.next 26 | else: 27 | if curr: 28 | curr.next = curr1 29 | curr = curr1 30 | curr1 = curr1.next 31 | if nh is None: 32 | nh = curr 33 | return nh 34 | -------------------------------------------------------------------------------- /questions/min-stack/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 3 | * 4 | * push(x) -- Push element x onto stack. 5 | * pop() -- Removes the element on top of the stack. 6 | * top() -- Get the top element. 7 | * getMin() -- Retrieve the minimum element in the stack. 8 | */ 9 | 10 | class MinStack { 11 | private Stack st = new Stack(); 12 | private Stack minSt = new Stack(); 13 | 14 | public void push(int x) { 15 | st.push(x); 16 | if (minSt.isEmpty()) { 17 | minSt.push(x); 18 | } else { 19 | int val = minSt.peek().intValue(); 20 | minSt.push(val < x ? val : x); 21 | } 22 | } 23 | 24 | public void pop() { 25 | minSt.pop(); 26 | st.pop(); 27 | } 28 | 29 | public int top() { 30 | return st.peek().intValue(); 31 | } 32 | 33 | public int getMin() { 34 | return minSt.peek().intValue(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /questions/minimum-area-rectangle/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a set of points in the xy-plane, determine the minimum area of a rectangle formed from these points, with sides parallel to the x and y axes. 4 | If there isn't any rectangle, return 0. 5 |   6 | 7 | Example 1: 8 | 9 | Input: [[1,1],[1,3],[3,1],[3,3],[2,2]] 10 | Output: 4 11 | 12 | 13 | Example 2: 14 | 15 | Input: [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]] 16 | Output: 2 17 | 18 |   19 | Note: 20 | 21 | 1 <= points.length <= 500 22 | 0 <= points[i][0] <= 40000 23 | 0 <= points[i][1] <= 40000 24 | All points are distinct. 25 | 26 | 27 | 28 | """ 29 | 30 | 31 | class Solution: 32 | def minAreaRect(self, points: List[List[int]]) -> int: 33 | seen = set() 34 | res = float('inf') 35 | for x1, y1 in points: 36 | for x2, y2 in seen: 37 | if (x1, y2) in seen and (x2, y1) in seen: 38 | area = abs(x1 - x2) * abs(y1 - y2) 39 | if area and area < res: 40 | res = area 41 | seen.add((x1, y1)) 42 | return res if res < float('inf') else 0 -------------------------------------------------------------------------------- /questions/minimum-depth-of-binary-tree/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a binary tree, find its minimum depth. 3 | * 4 | * The minimum depth is the number of nodes along the shortest path from the 5 | * root node down to the nearest leaf node. 6 | */ 7 | 8 | /** 9 | * Definition for a binary tree node. 10 | * public class TreeNode { 11 | * int val; 12 | * TreeNode left; 13 | * TreeNode right; 14 | * TreeNode(int x) { val = x; } 15 | * } 16 | */ 17 | public class Solution { 18 | public int minDepth(TreeNode root) { 19 | if (root == null) { 20 | return 0; 21 | } 22 | if (root.left == null && root.right == null) { 23 | return 1; 24 | } else if (root.left == null) { 25 | return minDepth(root.right) + 1; 26 | } else if (root.right == null) { 27 | return minDepth(root.left) + 1; 28 | } 29 | int leftDepth = minDepth(root.left); 30 | int rightDepth = minDepth(root.right); 31 | return (leftDepth < rightDepth ? leftDepth : rightDepth) + 1; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /questions/minimum-size-subarray-sum/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. 3 | 4 | Example: 5 | 6 | Input: s = 7, nums = [2,3,1,2,4,3] 7 | Output: 2 8 | Explanation: the subarray [4,3] has the minimal length under the problem constraint. 9 | Follow up: 10 | If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). 11 | """ 12 | 13 | 14 | class Solution: 15 | def minSubArrayLen(self, s: int, nums: List[int]) -> int: 16 | mlen = len(nums) + 1 17 | start = 0 18 | ss = 0 19 | for i, n in enumerate(nums): 20 | ss += n 21 | while ss >= s: 22 | mlen = min(i - start + 1, mlen) 23 | ss -= nums[start] 24 | start += 1 25 | return mlen if mlen != len(nums) + 1 else 0 26 | -------------------------------------------------------------------------------- /questions/minimum-time-difference/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list. 4 |   5 | Example 1: 6 | Input: timePoints = ["23:59","00:00"] 7 | Output: 1 8 | Example 2: 9 | Input: timePoints = ["00:00","23:59","00:00"] 10 | Output: 0 11 | 12 |   13 | Constraints: 14 | 15 | 2 <= timePoints <= 2 * 104 16 | timePoints[i] is in the format "HH:MM". 17 | 18 | 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def findMinDifference(self, timePoints): 24 | """ 25 | :type timePoints: List[str] 26 | :rtype: int 27 | """ 28 | def to_minutes(ts): 29 | return int(ts[:2]) * 60 + int(ts[3:]) 30 | 31 | minutes = [to_minutes(el) for el in timePoints] 32 | minutes.sort() 33 | prev, mm = None, abs(minutes[0] + 60 * 24 - minutes[-1]) 34 | for num in minutes: 35 | if prev is None: 36 | prev = num 37 | continue 38 | if mm > num - prev: 39 | mm = num - prev 40 | prev = num 41 | return mm -------------------------------------------------------------------------------- /questions/mirror-reflection/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2. 4 | The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor. 5 | Given the two integers p and q, return the number of the receptor that the ray meets first. 6 | The test cases are guaranteed so that the ray will meet a receptor eventually. 7 |   8 | Example 1: 9 | 10 | 11 | Input: p = 2, q = 1 12 | Output: 2 13 | Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall. 14 | 15 | Example 2: 16 | 17 | Input: p = 3, q = 1 18 | Output: 1 19 | 20 |   21 | Constraints: 22 | 23 | 1 <= q <= p <= 1000 24 | 25 | 26 | """ 27 | 28 | 29 | class Solution: 30 | def mirrorReflection(self, p: int, q: int) -> int: 31 | L = lcm(p,q) 32 | 33 | if (L//q)%2 == 0: 34 | return 2 35 | 36 | return (L//p)%2 -------------------------------------------------------------------------------- /questions/missing-number/Solution.java: -------------------------------------------------------------------------------- 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 | * For example, 5 | * Given nums = [0, 1, 3] return 2. 6 | * 7 | * Note: 8 | * Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 9 | */ 10 | 11 | public class Solution { 12 | public int missingNumber(int[] nums) { 13 | int sum = 0; 14 | for (int i = nums.length - 1; i >= 0; i--) { 15 | sum += nums[i]; 16 | } 17 | 18 | return (nums.length + 1) * nums.length / 2 - sum; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /questions/missing-ranges/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]: 9 | def convert_repr(ret): 10 | res = [] 11 | for l, u in ret: 12 | if l == u: 13 | res.append(str(l)) 14 | else: 15 | res.append('{}->{}'.format(l, u)) 16 | return res 17 | 18 | ret = [] 19 | prev = lower - 1 20 | for n in nums: 21 | if prev + 1 < n: 22 | ret.append([prev + 1, n - 1]) 23 | prev = n 24 | if prev + 1 <= upper: 25 | ret.append([prev + 1, upper]) 26 | return convert_repr(ret) -------------------------------------------------------------------------------- /questions/n-repeated-element-in-size-2n-array/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. 4 | Return the element repeated N times. 5 |   6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: [1,2,3,3] 12 | Output: 3 13 | 14 | 15 | Example 2: 16 | 17 | Input: [2,1,2,5,3,2] 18 | Output: 2 19 | 20 | 21 | Example 3: 22 | 23 | Input: [5,1,5,2,5,3,5,4] 24 | Output: 5 25 | 26 |   27 | Note: 28 | 29 | 4 <= A.length <= 10000 30 | 0 <= A[i] < 10000 31 | A.length is even 32 | 33 | 34 | 35 | 36 | 37 | """ 38 | 39 | 40 | class Solution(object): 41 | def repeatedNTimes(self, A): 42 | """ 43 | :type A: List[int] 44 | :rtype: int 45 | """ 46 | s = set() 47 | for n in A: 48 | if n in s: 49 | return n 50 | s.add(n) 51 | return -1 -------------------------------------------------------------------------------- /questions/n-th-tribonacci-number/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | The Tribonacci sequence Tn is defined as follows:  4 | T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. 5 | Given n, return the value of Tn. 6 |   7 | Example 1: 8 | 9 | Input: n = 4 10 | Output: 4 11 | Explanation: 12 | T_3 = 0 + 1 + 1 = 2 13 | T_4 = 1 + 1 + 2 = 4 14 | 15 | Example 2: 16 | 17 | Input: n = 25 18 | Output: 1389537 19 | 20 |   21 | Constraints: 22 | 23 | 0 <= n <= 37 24 | The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1. 25 | 26 | """ 27 | 28 | 29 | class Solution: 30 | def tribonacci(self, n: int) -> int: 31 | arr = [0, 1, 1] 32 | if n <= 2: 33 | return arr[n] 34 | n -= 2 35 | while n > 0: 36 | arr[0], arr[1], arr[2] = arr[1], arr[2], arr[0] + arr[1] + arr[2] 37 | n -= 1 38 | return arr[2] -------------------------------------------------------------------------------- /questions/nim-game/Solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * You are playing the following Nim Game with your friend: 3 | * There is a heap of stones on the table, each time one of 4 | * you take turns to remove 1 to 3 stones. The one who removes 5 | * the last stone will be the winner. You will take the first 6 | * turn to remove the stones. 7 | * 8 | * Both of you are very clever and have optimal strategies for 9 | * the game. Write a function to determine whether you can win 10 | * the game given the number of stones in the heap. 11 | * 12 | * For example, if there are 4 stones in the heap, then you will 13 | * never win the game: no matter 1, 2, or 3 stones you remove, 14 | * the last stone will always be removed by your friend. 15 | */ 16 | class Solution { 17 | public: 18 | bool canWinNim(int n) { 19 | return n % 4 != 0; 20 | } 21 | }; -------------------------------------------------------------------------------- /questions/nim-game/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of 3 | * you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the 4 | * first turn to remove the stones. 5 | * 6 | * Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you 7 | * can win the game given the number of stones in the heap. 8 | * 9 | * For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you 10 | * remove, the last stone will always be removed by your friend. 11 | */ 12 | 13 | public class Solution { 14 | public boolean canWinNim(int n) { 15 | return (n % 4) != 0; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /questions/nth-highest-salary/Solution.sql: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a SQL query to get the nth highest salary from the Employee table. 3 | * 4 | * +----+--------+ 5 | * | Id | Salary | 6 | * +----+--------+ 7 | * | 1 | 100 | 8 | * | 2 | 200 | 9 | * | 3 | 300 | 10 | * +----+--------+ 11 | * For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null. 12 | * 13 | * +------------------------+ 14 | * | getNthHighestSalary(2) | 15 | * +------------------------+ 16 | * | 200 | 17 | * +------------------------+ 18 | */ 19 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 20 | BEGIN 21 | RETURN ( 22 | # Write your MySQL query statement below. 23 | select Salary from 24 | (select Salary, @curRank := @curRank + 1 AS rank from 25 | (select distinct Salary from Employee) as tmpe, 26 | (SELECT @curRank := 0) as r order by Salary desc 27 | ) as tmp 28 | where rank = N 29 | ); 30 | END 31 | -------------------------------------------------------------------------------- /questions/number-of-1-bits/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a function that takes an unsigned integer and returns the number of ’1' bits it has 3 | * (also known as the Hamming weight). 4 | * 5 | * For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, 6 | * so the function should return 3. 7 | */ 8 | 9 | public class Solution { 10 | // you need to treat n as an unsigned value 11 | public int hammingWeight(int n) { 12 | int num = 0; 13 | while (n != 0) { 14 | n = n & (n - 1); 15 | num++; 16 | } 17 | 18 | return num; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /questions/number-of-connected-components-in-an-undirected-graph/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | from collections import defaultdict 8 | 9 | class Solution: 10 | def countComponents(self, n: int, edges: List[List[int]]) -> int: 11 | connections = defaultdict(set) 12 | for v1, v2 in edges: 13 | connections[v1].add(v2) 14 | connections[v2].add(v1) 15 | cnt = 0 16 | visited = set() 17 | for i in range(n): 18 | if i in visited: 19 | continue 20 | cnt += 1 21 | stack = [i] 22 | while stack: 23 | curr = stack.pop() 24 | if curr in visited: 25 | continue 26 | visited.add(curr) 27 | for ne in connections.get(curr, set()): 28 | if ne in visited: 29 | continue 30 | stack.append(ne) 31 | return cnt -------------------------------------------------------------------------------- /questions/number-of-digit-one/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. 3 | 4 | Example: 5 | 6 | Input: 13 7 | Output: 6 8 | Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. 9 | """ 10 | 11 | 12 | class Solution: 13 | def countDigitOne(self, n: int) -> int: 14 | cnt = 0 15 | mark = 1 16 | while n >= mark: 17 | c, r = divmod(n, (mark * 10)) 18 | cnt += c * mark 19 | if r >= mark: 20 | cnt += min(r - mark + 1, mark) 21 | mark *= 10 22 | return cnt 23 | -------------------------------------------------------------------------------- /questions/number-of-equivalent-domino-pairs/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can be rotated to be equal to another domino. 4 | Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j]. 5 |   6 | Example 1: 7 | 8 | Input: dominoes = [[1,2],[2,1],[3,4],[5,6]] 9 | Output: 1 10 | 11 | Example 2: 12 | 13 | Input: dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]] 14 | Output: 3 15 | 16 |   17 | Constraints: 18 | 19 | 1 <= dominoes.length <= 4 * 104 20 | dominoes[i].length == 2 21 | 1 <= dominoes[i][j] <= 9 22 | 23 | 24 | """ 25 | 26 | 27 | class Solution: 28 | def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: 29 | tr = {} 30 | for a, b in dominoes: 31 | if a > b: 32 | a, b = b, a 33 | key = (a, b) 34 | tr[key] = tr.get(key, 0) + 1 35 | ret = 0 36 | for v in tr.values(): 37 | ret += max((v - 1) * v // 2, 0) 38 | return ret -------------------------------------------------------------------------------- /questions/one-edit-distance/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def isOneEditDistance(self, s: str, t: str) -> bool: 9 | if abs(len(s) - len(t)) > 1: 10 | return False 11 | if len(s) < len(t): 12 | s, t = t, s 13 | i, j = 0, 0 14 | seen_change = False 15 | while i < len(s) and j < len(t): 16 | if s[i] != t[j]: 17 | if seen_change: 18 | return False 19 | seen_change = True 20 | if len(s) > len(t): 21 | i += 1 22 | else: 23 | i += 1 24 | j += 1 25 | else: 26 | i += 1 27 | j += 1 28 | if i != len(s) or j != len(t): 29 | if not seen_change: 30 | seen_change = True 31 | else: 32 | return False 33 | return seen_change -------------------------------------------------------------------------------- /questions/palindrome-number/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Determine whether an integer is a palindrome. Do this without extra space. 3 | */ 4 | 5 | public class Solution { 6 | public boolean isPalindrome(int x) { 7 | if (x < 0) { 8 | return false; 9 | } 10 | int x_t = x; 11 | int digits = 0; 12 | while (x_t > 0) { 13 | x_t /= 10; 14 | digits++; 15 | } 16 | int num1, num2; 17 | for (int i = 0, j = digits - 1; i < j; i++, j--) { 18 | num1 = x / tensPower(i) % 10; 19 | num2 = x / tensPower(j) % 10; 20 | if (num1 == num2) { 21 | continue; 22 | } else { 23 | return false; 24 | } 25 | } 26 | return true; 27 | } 28 | 29 | private int tensPower(int n) { 30 | int sum = 1; 31 | while (n > 0) { 32 | sum *= 10; 33 | n--; 34 | } 35 | return sum; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /questions/palindrome-partitioning/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | 4 | Return all possible palindrome partitioning of s. 5 | 6 | Example: 7 | 8 | Input: "aab" 9 | Output: 10 | [ 11 | ["aa","b"], 12 | ["a","a","b"] 13 | ] 14 | """ 15 | 16 | 17 | class Solution: 18 | def partition(self, s: str) -> List[List[str]]: 19 | ret = [] 20 | def isPal(s): 21 | return s == s[::-1] 22 | 23 | def backtrack(s, l): 24 | if not s: 25 | ret.append(l) 26 | return 27 | for i in range(1, len(s)+1): 28 | if isPal(s[:i]): 29 | backtrack(s[i:], l+[s[:i]]) 30 | 31 | backtrack(s, []) 32 | return ret 33 | -------------------------------------------------------------------------------- /questions/partition-equal-subset-sum/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. 4 |   5 | Example 1: 6 | 7 | Input: nums = [1,5,11,5] 8 | Output: true 9 | Explanation: The array can be partitioned as [1, 5, 5] and [11]. 10 | 11 | Example 2: 12 | 13 | Input: nums = [1,2,3,5] 14 | Output: false 15 | Explanation: The array cannot be partitioned into equal sum subsets. 16 | 17 |   18 | Constraints: 19 | 20 | 1 <= nums.length <= 200 21 | 1 <= nums[i] <= 100 22 | 23 | 24 | """ 25 | 26 | 27 | class Solution: 28 | def canPartition(self, nums: List[int]) -> bool: 29 | ss = sum(nums) 30 | if ss % 2 == 1: 31 | return False 32 | possible_sums = {0} 33 | for n in nums: 34 | possible_sums.update({(v + n) for v in possible_sums}) 35 | return (ss // 2) in possible_sums -------------------------------------------------------------------------------- /questions/partitioning-into-minimum-number-of-deci-binary-numbers/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not. 4 | Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n. 5 |   6 | Example 1: 7 | 8 | Input: n = "32" 9 | Output: 3 10 | Explanation: 10 + 11 + 11 = 32 11 | 12 | Example 2: 13 | 14 | Input: n = "82734" 15 | Output: 8 16 | 17 | Example 3: 18 | 19 | Input: n = "27346209830709182346" 20 | Output: 9 21 | 22 |   23 | Constraints: 24 | 25 | 1 <= n.length <= 105 26 | n consists of only digits. 27 | n does not contain any leading zeros and represents a positive integer. 28 | 29 | 30 | """ 31 | 32 | 33 | class Solution: 34 | def minPartitions(self, n: str) -> int: 35 | return max([ord(c) - ord('0') for c in n]) -------------------------------------------------------------------------------- /questions/pascals-triangle-ii/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an index k, return the kth row of the Pascal's triangle. 3 | * 4 | * For example, given k = 3, 5 | * Return [1,3,3,1]. 6 | * 7 | * Note: 8 | * Could you optimize your algorithm to use only O(k) extra space? 9 | */ 10 | 11 | public class Solution { 12 | public List getRow(int rowIndex) { 13 | List results = new LinkedList(); 14 | if (rowIndex == 0) { 15 | results.add(1); 16 | return results; 17 | } else if (rowIndex == 1) { 18 | results.add(1); 19 | results.add(1); 20 | return results; 21 | } 22 | results.add(1); 23 | results.add(1); 24 | int prev = 1, tmp = 0; 25 | for (int i = 1; i < rowIndex; i++) { 26 | prev = 1; 27 | for (int j = 1; j <= i; j++) { 28 | tmp = results.get(j); 29 | results.set(j, tmp + prev); 30 | prev = tmp; 31 | } 32 | results.add(1); 33 | } 34 | 35 | return results; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /questions/peak-index-in-a-mountain-array/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Let's call an array A a mountain if the following properties hold: 3 | 4 | A.length >= 3 5 | There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 6 | Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. 7 | 8 | Example 1: 9 | 10 | Input: [0,1,0] 11 | Output: 1 12 | Example 2: 13 | 14 | Input: [0,2,1,0] 15 | Output: 1 16 | Note: 17 | 18 | 3 <= A.length <= 10000 19 | 0 <= A[i] <= 10^6 20 | A is a mountain, as defined above. 21 | """ 22 | class Solution(object): 23 | def peakIndexInMountainArray(self, A): 24 | """ 25 | :type A: List[int] 26 | :rtype: int 27 | """ 28 | last_idx = len(A) - 1 29 | for idx, num in enumerate(A): 30 | if idx == 0 or idx == last_idx: 31 | continue 32 | if A[idx - 1] < num > A[idx + 1]: 33 | return idx 34 | return -1 35 | 36 | -------------------------------------------------------------------------------- /questions/perform-string-shifts/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def stringShift(self, s: str, shift: List[List[int]]) -> str: 9 | distance = 0 10 | for d, step in shift: 11 | if d == 0: 12 | distance += step 13 | else: 14 | distance -= step 15 | distance = distance % len(s) 16 | return s[distance:] + s[:distance] -------------------------------------------------------------------------------- /questions/permutations-ii/Solution.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 3 | 4 | Example: 5 | 6 | Input: [1,1,2] 7 | Output: 8 | [ 9 | [1,1,2], 10 | [1,2,1], 11 | [2,1,1] 12 | ] 13 | ''' 14 | 15 | from collections import Counter 16 | 17 | 18 | class Solution: 19 | def permuteUnique(self, nums: List[int]) -> List[List[int]]: 20 | def generate_permutations(candidates, curr, perms): 21 | if sum(candidates.values()) == 0: 22 | perms.append(list(curr)) 23 | return 24 | for n in list(candidates.keys()): 25 | if candidates[n] == 0: 26 | continue 27 | curr.append(n) 28 | candidates[n] -= 1 29 | generate_permutations(candidates, curr, perms) 30 | curr.pop() 31 | candidates[n] += 1 32 | 33 | curr = [] 34 | candidates = Counter(nums) 35 | perms = [] 36 | generate_permutations(candidates, curr, perms) 37 | return perms 38 | -------------------------------------------------------------------------------- /questions/permutations/Solution.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of distinct integers, return all possible permutations. 3 | 4 | Example: 5 | 6 | Input: [1,2,3] 7 | Output: 8 | [ 9 | [1,2,3], 10 | [1,3,2], 11 | [2,1,3], 12 | [2,3,1], 13 | [3,1,2], 14 | [3,2,1] 15 | ] 16 | ''' 17 | 18 | 19 | class Solution: 20 | def permute(self, nums: List[int]) -> List[List[int]]: 21 | def generate_permutation(nums, ret, curr, visited): 22 | if len(curr) == len(nums): 23 | ret.append(list(curr)) 24 | return 25 | for num in nums: 26 | if num in visited: 27 | continue 28 | visited.add(num) 29 | curr.append(num) 30 | generate_permutation(nums, ret, curr, visited) 31 | curr.pop() 32 | visited.remove(num) 33 | 34 | ret = [] 35 | curr = [] 36 | visited = set() 37 | generate_permutation(nums, ret, curr, visited) 38 | return ret 39 | -------------------------------------------------------------------------------- /questions/plus-one/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a non-negative number represented as an array of digits, plus one to the number. 3 | * 4 | * The digits are stored such that the most significant digit is at the head of the list. 5 | */ 6 | 7 | public class Solution { 8 | public int[] plusOne(int[] digits) { 9 | if (digits == null) { 10 | return null; 11 | } 12 | return addOneRec(digits.clone(), 1, digits.length - 1); 13 | } 14 | 15 | private int[] addOneRec(int[] digits, int carry, int pos) { 16 | if (carry == 0) { 17 | return digits; 18 | } 19 | int temp = digits[pos] + carry; 20 | if (temp <= 9) { 21 | digits[pos] = temp; 22 | return digits; 23 | } 24 | digits[pos] = temp % 10; 25 | if (pos == 0) { 26 | int[] result = new int[digits.length + 1]; 27 | System.arraycopy(digits, 0, result, 1, digits.length); 28 | result[0] = temp / 10; 29 | return result; 30 | } else { 31 | return addOneRec(digits, temp / 10, pos + 1); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /questions/pow(x,n)/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Implement pow(x, n). 3 | */ 4 | public class Solution { 5 | public double myPow(double x, int n) { 6 | if (n == 0 || Double.compare(x, 1) == 0 || (Double.compare(x, -1) == 0 && n %2 == 0)) { 7 | return 1.00; 8 | } else if (Double.compare(x, 0) == 0) { 9 | return 0.00; 10 | } else if (n == 1) { 11 | return x; 12 | } else if (n < 0) { 13 | return myPow(1/x, -1*n); 14 | } 15 | 16 | 17 | if (n%2 == 0) { 18 | return myPow(x*x, n/2); 19 | } else { 20 | return x* myPow(x, n-1); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /questions/power-of-four/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an integer n, return true if it is a power of four. Otherwise, return false. 4 | An integer n is a power of four, if there exists an integer x such that n == 4x. 5 |   6 | Example 1: 7 | Input: n = 16 8 | Output: true 9 | Example 2: 10 | Input: n = 5 11 | Output: false 12 | Example 3: 13 | Input: n = 1 14 | Output: true 15 | 16 |   17 | Constraints: 18 | 19 | -231 <= n <= 231 - 1 20 | 21 |   22 | Follow up: Could you solve it without loops/recursion? 23 | """ 24 | 25 | 26 | class Solution(object): 27 | def isPowerOfFour(self, num): 28 | """ 29 | :type num: int 30 | :rtype: bool 31 | """ 32 | if num <= 0: 33 | return False 34 | if num == 1: 35 | return True 36 | s = bin(num)[2:] 37 | if s[0] != '1': 38 | return False 39 | p = s[1:] 40 | if int(p) != 0: 41 | return False 42 | return len(p) % 2 == 0 -------------------------------------------------------------------------------- /questions/power-of-three/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an integer n, return true if it is a power of three. Otherwise, return false. 4 | An integer n is a power of three, if there exists an integer x such that n == 3x. 5 |   6 | Example 1: 7 | Input: n = 27 8 | Output: true 9 | Example 2: 10 | Input: n = 0 11 | Output: false 12 | Example 3: 13 | Input: n = 9 14 | Output: true 15 | Example 4: 16 | Input: n = 45 17 | Output: false 18 | 19 |   20 | Constraints: 21 | 22 | -231 <= n <= 231 - 1 23 | 24 |   25 | Follow up: Could you do it without using any loop / recursion? 26 | """ 27 | 28 | 29 | class Solution: 30 | def isPowerOfThree(self, n: int) -> bool: 31 | while n > 3: 32 | n, r = divmod(n, 3) 33 | if r != 0: 34 | return False 35 | return n == 1 or n == 3 -------------------------------------------------------------------------------- /questions/power-of-two/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer, write a function to determine if it is a power of two. 3 | 4 | Example 1: 5 | 6 | Input: 1 7 | Output: true 8 | Explanation: 20 = 1 9 | Example 2: 10 | 11 | Input: 16 12 | Output: true 13 | Explanation: 24 = 16 14 | Example 3: 15 | 16 | Input: 218 17 | Output: false 18 | """ 19 | 20 | 21 | class Solution(object): 22 | def isPowerOfTwo(self, n): 23 | """ 24 | :type n: int 25 | :rtype: bool 26 | """ 27 | if n <= 0: 28 | return False 29 | if n == 1: 30 | return True 31 | s = bin(n)[2:] 32 | if s[0] != '1': 33 | return False 34 | return all((el == '0' for el in s[1:])) 35 | 36 | 37 | class Solution2: 38 | def isPowerOfTwo(self, n: int) -> bool: 39 | if n <= 0: 40 | return False 41 | return (n & (n - 1)) == 0 42 | -------------------------------------------------------------------------------- /questions/powx-n/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Implement pow(x, n), which calculates x raised to the power n (i.e. xn). 4 |   5 | Example 1: 6 | 7 | Input: x = 2.00000, n = 10 8 | Output: 1024.00000 9 | 10 | Example 2: 11 | 12 | Input: x = 2.10000, n = 3 13 | Output: 9.26100 14 | 15 | Example 3: 16 | 17 | Input: x = 2.00000, n = -2 18 | Output: 0.25000 19 | Explanation: 2-2 = 1/22 = 1/4 = 0.25 20 | 21 |   22 | Constraints: 23 | 24 | -100.0 < x < 100.0 25 | -231 <= n <= 231-1 26 | -104 <= xn <= 104 27 | 28 | 29 | """ 30 | 31 | 32 | class Solution: 33 | def myPow(self, x: float, n: int) -> float: 34 | if n < 0: 35 | is_negative = True 36 | n = -n 37 | elif n == 0: 38 | return 1 39 | else: 40 | is_negative = False 41 | runner = x 42 | ret = 1 43 | while n > 0: 44 | bit = n & 1 45 | n = n >> 1 46 | if bit > 0: 47 | ret *= runner 48 | runner *= runner 49 | if ret == 0: 50 | return 0 51 | return ret if not is_negative else 1/ ret -------------------------------------------------------------------------------- /questions/product-of-array-except-self/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 3 | 4 | Example: 5 | 6 | Input: [1,2,3,4] 7 | Output: [24,12,8,6] 8 | Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. 9 | 10 | Note: Please solve it without division and in O(n). 11 | 12 | Follow up: 13 | Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) 14 | """ 15 | 16 | 17 | class Solution: 18 | def productExceptSelf(self, nums: List[int]) -> List[int]: 19 | ret = [1] * len(nums) 20 | for i in range(1, len(nums)): 21 | ret[i] = ret[i - 1] * nums[i - 1] 22 | acc = 1 23 | for i in range(len(nums) - 2, -1, -1): 24 | acc = acc * nums[i + 1] 25 | ret[i] = ret[i] * acc 26 | return ret 27 | -------------------------------------------------------------------------------- /questions/range-sum-of-bst/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high]. 4 |   5 | Example 1: 6 | 7 | 8 | Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 9 | Output: 32 10 | 11 | Example 2: 12 | 13 | 14 | Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 15 | Output: 23 16 | 17 |   18 | Constraints: 19 | 20 | The number of nodes in the tree is in the range [1, 2 * 104]. 21 | 1 <= Node.val <= 105 22 | 1 <= low <= high <= 105 23 | All Node.val are unique. 24 | 25 | """ 26 | 27 | 28 | # Definition for a binary tree node. 29 | # class TreeNode: 30 | # def __init__(self, x): 31 | # self.val = x 32 | # self.left = None 33 | # self.right = None 34 | 35 | class Solution: 36 | def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: 37 | if root is None: 38 | return 0 39 | if L <= root.val <= R: 40 | ss = root.val 41 | else: 42 | ss = 0 43 | return self.rangeSumBST(root.left, L, R) + ss + self.rangeSumBST(root.right, L, R) -------------------------------------------------------------------------------- /questions/range-sum-query-2d-mutable/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class NumMatrix: 8 | 9 | def __init__(self, matrix: List[List[int]]): 10 | for row in matrix: 11 | for col in range(1, len(row)): 12 | row[col] += row[col-1] 13 | self.matrix = matrix 14 | 15 | def update(self, row: int, col: int, val: int) -> None: 16 | original = self.matrix[row][col] 17 | if col != 0: 18 | original -= self.matrix[row][col-1] 19 | 20 | diff = original - val 21 | 22 | for y in range(col, len(self.matrix[0])): 23 | self.matrix[row][y] -= diff 24 | 25 | def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: 26 | sum = 0 27 | for x in range(row1, row2+1): 28 | sum += self.matrix[x][col2] 29 | if col1 != 0: 30 | sum -= self.matrix[x][col1-1] 31 | return sum 32 | 33 | 34 | # Your NumMatrix object will be instantiated and called as such: 35 | # obj = NumMatrix(matrix) 36 | # obj.update(row,col,val) 37 | # param_2 = obj.sumRegion(row1,col1,row2,col2) -------------------------------------------------------------------------------- /questions/rectangle-area/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles. 4 | The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2). 5 | The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2). 6 |   7 | Example 1: 8 | 9 | 10 | Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2 11 | Output: 45 12 | 13 | Example 2: 14 | 15 | Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 16 | Output: 16 17 | 18 |   19 | Constraints: 20 | 21 | -104 <= ax1 <= ax2 <= 104 22 | -104 <= ay1 <= ay2 <= 104 23 | -104 <= bx1 <= bx2 <= 104 24 | -104 <= by1 <= by2 <= 104 25 | 26 | 27 | """ 28 | 29 | 30 | class Solution: 31 | def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int: 32 | return (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) - max(min(ax2,bx2)-max(ax1,bx1), 0) * max(min(ay2,by2)-max(ay1,by1), 0) -------------------------------------------------------------------------------- /questions/remove-all-adjacent-duplicates-in-string/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them. 4 | We repeatedly make duplicate removals on S until we no longer can. 5 | Return the final string after all such duplicate removals have been made.  It is guaranteed the answer is unique. 6 |   7 | Example 1: 8 | 9 | Input: "abbaca" 10 | Output: "ca" 11 | Explanation: 12 | For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca". 13 | 14 |   15 | Note: 16 | 17 | 1 <= S.length <= 20000 18 | S consists only of English lowercase letters. 19 | 20 | 21 | """ 22 | 23 | 24 | class Solution: 25 | def removeDuplicates(self, S: str) -> str: 26 | stk = [] 27 | for a in S: 28 | if stk and stk[-1] == a: 29 | stk.pop() 30 | continue 31 | stk.append(a) 32 | return ''.join(stk) -------------------------------------------------------------------------------- /questions/remove-duplicate-letters/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. 3 | 4 | Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/ 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: s = "bcabc" 11 | Output: "abc" 12 | Example 2: 13 | 14 | Input: s = "cbacdcbc" 15 | Output: "acdb" 16 | 17 | 18 | Constraints: 19 | 20 | 1 <= s.length <= 104 21 | s consists of lowercase English letters. 22 | 23 | """ 24 | 25 | 26 | class Solution: 27 | def removeDuplicateLetters(self, s: str) -> str: 28 | last_occ = {c: i for i, c in enumerate(s)} 29 | stack = ["!"] 30 | visited = set() 31 | 32 | for i, symbol in enumerate(s): 33 | if symbol in visited: 34 | continue 35 | while (symbol < stack[-1] and last_occ[stack[-1]] > i): 36 | visited.remove(stack.pop()) 37 | stack.append(symbol) 38 | visited.add(symbol) 39 | return "".join(stack)[1:] 40 | -------------------------------------------------------------------------------- /questions/remove-duplicates-from-sorted-array-ii/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Follow up for "Remove Duplicates": 3 | * What if duplicates are allowed at most twice? 4 | * 5 | * For example, 6 | * Given sorted array nums = [1,1,1,2,2,3], 7 | * Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. 8 | * It doesn't matter what you leave beyond the new length. 9 | */ 10 | 11 | public class Solution { 12 | public int removeDuplicates(int[] nums) { 13 | if (nums == null || nums.length <= 0) { 14 | return 0; 15 | } 16 | int acc = 1; 17 | int runner = 1; 18 | int curr = 1; 19 | while (runner < nums.length) { 20 | if (nums[runner] == nums[runner - 1]) { 21 | acc++; 22 | if (acc <= 2) { 23 | nums[curr] = nums[runner]; 24 | curr++; 25 | } 26 | } else { 27 | nums[curr] = nums[runner]; 28 | curr++; 29 | acc = 1; 30 | } 31 | runner++; 32 | } 33 | return curr; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /questions/remove-duplicates-from-sorted-array/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a sorted array, remove the duplicates in place such that each element appear 3 | * only once and return the new length. 4 | * 5 | * Do not allocate extra space for another array, you must do this in place with constant memory. 6 | * 7 | * For example, 8 | * Given input array nums = [1,1,2], 9 | * 10 | * Your function should return length = 2, with the first two elements of nums being 1 and 2 11 | * respectively. It doesn't matter what you leave beyond the new length. 12 | */ 13 | 14 | public class Solution { 15 | public int removeDuplicates(int[] nums) { 16 | if (nums == null || nums.length <= 0) { 17 | return 0; 18 | } else if (nums.length <= 1) { 19 | return 1; 20 | } 21 | int curr = 0; 22 | int runner = 1; 23 | while (runner < nums.length) { 24 | if (nums[runner] != nums[curr]) { 25 | curr++; 26 | nums[curr] = nums[runner]; 27 | } 28 | runner++; 29 | } 30 | 31 | return curr+1; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /questions/remove-duplicates-from-sorted-list/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a sorted linked list, delete all duplicates such that each element appear only once. 3 | * 4 | * For example, 5 | * Given 1->1->2, return 1->2. 6 | * Given 1->1->2->3->3, return 1->2->3. 7 | */ 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * public class ListNode { 12 | * int val; 13 | * ListNode next; 14 | * ListNode(int x) { val = x; } 15 | * } 16 | */ 17 | public class Solution { 18 | public ListNode deleteDuplicates(ListNode head) { 19 | if (head == null) { 20 | return null; 21 | } 22 | ListNode runner = head; 23 | ListNode temp; 24 | while (runner != null && runner.next != null) { 25 | if (runner.val == runner.next.val) { 26 | temp = runner.next; 27 | runner.next = temp.next; 28 | temp.next = null; 29 | } else { 30 | runner = runner.next; 31 | } 32 | } 33 | 34 | return head; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /questions/remove-duplicates-from-sorted-list/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def deleteDuplicates(self, head: ListNode) -> ListNode: 9 | nh = ListNode(None) 10 | prev, curr = nh, head 11 | while curr is not None: 12 | if curr.val == prev.val: 13 | curr = curr.next 14 | else: 15 | prev.next = curr 16 | prev = curr 17 | curr = curr.next 18 | prev.next = None 19 | return nh.next 20 | -------------------------------------------------------------------------------- /questions/remove-element/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array and a value, remove all instances of that value in place and return the new length. 3 | * 4 | * The order of elements can be changed. It doesn't matter what you leave beyond the new length. 5 | */ 6 | 7 | public class Solution { 8 | public int removeElement(int[] nums, int val) { 9 | if (nums == null) { 10 | return 0; 11 | } 12 | int curr = 0; 13 | int runner = 0; 14 | while (runner < nums.length) { 15 | if (nums[runner] != val) { 16 | nums[curr] = nums[runner]; 17 | curr++; 18 | } 19 | runner++; 20 | } 21 | 22 | return curr; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /questions/remove-linked-list-elements/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Remove all elements from a linked list of integers that have value val. 3 | 4 | Example: 5 | 6 | Input: 1->2->6->3->4->5->6, val = 6 7 | Output: 1->2->3->4->5 8 | """ 9 | 10 | # Definition for singly-linked list. 11 | # class ListNode: 12 | # def __init__(self, x): 13 | # self.val = x 14 | # self.next = None 15 | 16 | class Solution: 17 | def removeElements(self, head: ListNode, val: int) -> ListNode: 18 | nh = ListNode(None) 19 | nh.next = head 20 | prev, curr = nh, head 21 | while curr is not None: 22 | n = curr.next 23 | if curr.val == val: 24 | prev.next = n 25 | curr = n 26 | else: 27 | prev = curr 28 | curr = n 29 | return nh.next 30 | -------------------------------------------------------------------------------- /questions/repeated-dna-sequences/Solution.py: -------------------------------------------------------------------------------- 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 | Example: 7 | 8 | Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" 9 | 10 | Output: ["AAAAACCCCC", "CCCCCAAAAA"] 11 | """ 12 | 13 | 14 | class Solution: 15 | def findRepeatedDnaSequences(self, s: str) -> List[str]: 16 | track = {} 17 | ret = set() 18 | for i in range(10, len(s) + 1): 19 | sub = s[i - 10:i] 20 | if sub not in track: 21 | track[sub] = True 22 | else: 23 | ret.add(sub) 24 | return list(ret) 25 | -------------------------------------------------------------------------------- /questions/repeated-string-match/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1. 3 | 4 | For example, with A = "abcd" and B = "cdabcdab". 5 | 6 | Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd"). 7 | 8 | Note: 9 | The length of A and B will be between 1 and 10000. 10 | """ 11 | class Solution(object): 12 | def repeatedStringMatch(self, A, B): 13 | """ 14 | :type A: str 15 | :type B: str 16 | :rtype: int 17 | """ 18 | if B in A: 19 | return 1 20 | l = len(B) / len(A) + 2 21 | t = A * l 22 | try: 23 | r = t.index(B) 24 | except ValueError: 25 | return -1 26 | q, rm = divmod((r + len(B)), len(A)) 27 | if rm == 0: 28 | return q 29 | return q + 1 30 | 31 | -------------------------------------------------------------------------------- /questions/reverse-bits/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Reverse bits of a given 32 bits unsigned integer. 3 | * 4 | * For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), 5 | * return 964176192 (represented in binary as 00111001011110000010100101000000). 6 | * 7 | * Follow up: 8 | * If this function is called many times, how would you optimize it? 9 | */ 10 | 11 | public class Solution { 12 | // you need treat n as an unsigned value 13 | public int reverseBits(int n) { 14 | int[] arr = new int[32]; 15 | long mask = 1; 16 | long nL = n; 17 | long sum = 0; 18 | for (int i = 0; i < 32; i++) { 19 | if ((nL & mask) > 0) { 20 | arr[32 - 1 - i] = 1; 21 | } 22 | mask = mask << 1; 23 | } 24 | mask = 1; 25 | for (int i = 0; i < 32; i++) { 26 | if (arr[i] == 1) { 27 | sum = sum | (mask << i); 28 | } 29 | } 30 | return (int)(sum); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /questions/reverse-linked-list/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Reverse a singly linked list. 3 | */ 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; } 11 | * } 12 | */ 13 | public class Solution { 14 | public ListNode reverseList(ListNode head) { 15 | if (head == null) { 16 | return head; 17 | } 18 | ListNode prev = head, curr = head.next, temp = null, temp1; 19 | while (prev != null && curr != null) { 20 | prev.next = temp; 21 | temp = curr.next; 22 | curr.next = prev; 23 | prev = curr; 24 | curr = temp; 25 | temp = prev.next; 26 | } 27 | return prev; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /questions/reverse-linked-list/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reverse a singly linked list. 3 | 4 | Example: 5 | 6 | Input: 1->2->3->4->5->NULL 7 | Output: 5->4->3->2->1->NULL 8 | Follow up: 9 | 10 | A linked list can be reversed either iteratively or recursively. Could you implement both? 11 | """ 12 | 13 | 14 | # Definition for singly-linked list. 15 | # class ListNode: 16 | # def __init__(self, x): 17 | # self.val = x 18 | # self.next = None 19 | 20 | class Solution: 21 | def reverseList(self, head: ListNode) -> ListNode: 22 | prev, curr = None, head 23 | while curr is not None: 24 | tmp = curr.next 25 | curr.next = prev 26 | prev = curr 27 | curr = tmp 28 | return prev 29 | -------------------------------------------------------------------------------- /questions/reverse-string/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a function that takes a string as input and returns the string reversed. 3 | * 4 | * Example: 5 | * Given s = "hello", return "olleh". 6 | */ 7 | 8 | import java.util.*; 9 | class Solution { 10 | public String reverseString(String s) { 11 | StringBuilder input1 = new StringBuilder(); 12 | input1.append(s); 13 | return input1.reverse().toString(); 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /questions/reverse-vowels-of-a-string/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Write a function that takes a string as input and reverse only the vowels of a string. 4 | Example 1: 5 | 6 | Input: "hello" 7 | Output: "holle" 8 | 9 | 10 | Example 2: 11 | 12 | Input: "leetcode" 13 | Output: "leotcede" 14 | 15 | Note: 16 | The vowels does not include the letter "y". 17 |   18 | 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def reverseVowels(self, s): 24 | """ 25 | :type s: str 26 | :rtype: str 27 | """ 28 | if not s: 29 | return s 30 | r = list(s) 31 | s, e = 0, len(s) - 1 32 | vowels = set('aeiouAEIOU') 33 | while s < e: 34 | while s < e and r[s] not in vowels: 35 | s += 1 36 | while s < e and r[e] not in vowels: 37 | e -= 1 38 | if s < e: 39 | r[s], r[e] = r[e], r[s] 40 | s += 1 41 | e -= 1 42 | return ''.join(r) -------------------------------------------------------------------------------- /questions/reverse-words-in-a-string/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an input string, reverse the string word by word. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: "the sky is blue" 9 | Output: "blue is sky the" 10 | Example 2: 11 | 12 | Input: " hello world! " 13 | Output: "world! hello" 14 | Explanation: Your reversed string should not contain leading or trailing spaces. 15 | Example 3: 16 | 17 | Input: "a good example" 18 | Output: "example good a" 19 | Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. 20 | 21 | 22 | Note: 23 | 24 | A word is defined as a sequence of non-space characters. 25 | Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. 26 | You need to reduce multiple spaces between two words to a single space in the reversed string. 27 | 28 | 29 | Follow up: 30 | 31 | For C programmers, try to solve it in-place in O(1) extra space. 32 | """ 33 | 34 | 35 | class Solution: 36 | def reverseWords(self, s: str) -> str: 37 | return ' '.join([w for w in s.split(' ') if w][::-1]) 38 | -------------------------------------------------------------------------------- /questions/rising-temperature/Solution.sql: -------------------------------------------------------------------------------- 1 | -- Given a Weather table, write a SQL query to find all dates' Ids with higher temperature compared to its previous (yesterday's) dates. 2 | 3 | -- +---------+------------------+------------------+ 4 | -- | Id(INT) | RecordDate(DATE) | Temperature(INT) | 5 | -- +---------+------------------+------------------+ 6 | -- | 1 | 2015-01-01 | 10 | 7 | -- | 2 | 2015-01-02 | 25 | 8 | -- | 3 | 2015-01-03 | 20 | 9 | -- | 4 | 2015-01-04 | 30 | 10 | -- +---------+------------------+------------------+ 11 | 12 | -- For example, return the following Ids for the above Weather table: 13 | 14 | -- +----+ 15 | -- | Id | 16 | -- +----+ 17 | -- | 2 | 18 | -- | 4 | 19 | -- +----+ 20 | 21 | # Write your MySQL query statement below 22 | select w1.Id from Weather as w1, Weather as w2 where Date(DATE_ADD(w1.RecordDate,INTERVAL -1 DAY)) = w2.RecordDate and w1.Temperature > w2.Temperature; 23 | 24 | -------------------------------------------------------------------------------- /questions/roman-to-integer/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a roman numeral, convert it to an integer. 3 | * 4 | * Input is guaranteed to be within the range from 1 to 3999. 5 | */ 6 | 7 | public class Solution { 8 | public int romanToInt(String s) { 9 | char[] arr = {'I', 'V', 'X', 'L', 'C', 'D', 'M'}; 10 | int[] mapped = {1, 5, 10, 50, 100, 500, 1000}; 11 | int sum = 0; 12 | int currPos = 0; 13 | int prevPos = 0; 14 | for (int i = s.length() - 1; i >= 0; i--) { 15 | currPos = indexOfTarget(arr, s.charAt(i)); 16 | if (currPos < prevPos) { 17 | sum -= mapped[currPos]; 18 | } else { 19 | sum += mapped[currPos]; 20 | } 21 | prevPos = currPos; 22 | } 23 | 24 | return sum; 25 | } 26 | 27 | private int indexOfTarget(char[] arr, char target) { 28 | for (int i = 0; i < arr.length; i++) { 29 | if (arr[i] == target) { 30 | return i; 31 | } 32 | } 33 | return -1; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /questions/rotate-array/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rotate an array of n elements to the right by k steps. 3 | * 4 | * 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]. 5 | * 6 | * Note: 7 | * Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 8 | */ 9 | 10 | public class Solution { 11 | public void rotate(int[] nums, int k) { 12 | k = k % nums.length; 13 | rotatePart(nums, 0, nums.length - 1); 14 | rotatePart(nums, 0, k -1); 15 | rotatePart(nums, k, nums.length - 1); 16 | } 17 | 18 | private void rotatePart(int[] nums, int start, int end) { 19 | while (start < end) { 20 | int temp = nums[end]; 21 | nums[end] = nums[start]; 22 | nums[start] = temp; 23 | start++; 24 | end--; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /questions/running-sum-of-1d-array/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). 4 | Return the running sum of nums. 5 |   6 | Example 1: 7 | 8 | Input: nums = [1,2,3,4] 9 | Output: [1,3,6,10] 10 | Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. 11 | Example 2: 12 | 13 | Input: nums = [1,1,1,1,1] 14 | Output: [1,2,3,4,5] 15 | Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]. 16 | Example 3: 17 | 18 | Input: nums = [3,1,2,10,1] 19 | Output: [3,4,6,16,17] 20 | 21 |   22 | Constraints: 23 | 24 | 1 <= nums.length <= 1000 25 | -10^6 <= nums[i] <= 10^6 26 | 27 | """ 28 | 29 | 30 | class Solution: 31 | def runningSum(self, nums: List[int]) -> List[int]: 32 | ret = [] 33 | s = 0 34 | for a in nums: 35 | s += a 36 | ret.append(s) 37 | return ret -------------------------------------------------------------------------------- /questions/same-tree/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given two binary trees, write a function to check if they are equal or not. 3 | * 4 | * Two binary trees are considered equal if they are structurally identical and 5 | * the nodes have the same value. 6 | */ 7 | 8 | /** 9 | * Definition for a binary tree node. 10 | * public class TreeNode { 11 | * int val; 12 | * TreeNode left; 13 | * TreeNode right; 14 | * TreeNode(int x) { val = x; } 15 | * } 16 | */ 17 | public class Solution { 18 | public boolean isSameTree(TreeNode p, TreeNode q) { 19 | if (p == null && q == null) { 20 | return true; 21 | } else if (p == null) { 22 | return false; 23 | } else if (q == null) { 24 | return false; 25 | } else if (p.val != q.val) { 26 | return false; 27 | } else { 28 | boolean isLeftSame = isSameTree(p.left, q.left); 29 | boolean isRightSame = isSameTree(p.right, q.right); 30 | return isLeftSame && isRightSame; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /questions/search-insert-position/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a sorted array and a target value, return the index if the target is found. 3 | * If not, return the index where it would be if it were inserted in order. 4 | * 5 | * You may assume no duplicates in the array. 6 | * 7 | * Here are few examples. 8 | * [1,3,5,6], 5 → 2 9 | * [1,3,5,6], 2 → 1 10 | * [1,3,5,6], 7 → 4 11 | * [1,3,5,6], 0 → 0 12 | */ 13 | 14 | public class Solution { 15 | public int searchInsert(int[] nums, int target) { 16 | int start = 0; 17 | int end = nums.length - 1; 18 | int mid = (start + end) / 2; 19 | while (start < end) { 20 | if (nums[mid] == target) { 21 | return mid; 22 | } else if (nums[mid] < target) { 23 | start = mid + 1; 24 | mid = (start + end) / 2; 25 | } else { 26 | end = mid - 1; 27 | mid = (start + end) / 2; 28 | } 29 | } 30 | 31 | mid = (start + end) / 2; 32 | if (nums[mid] >= target) { 33 | return mid; 34 | } else { 35 | return mid + 1; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /questions/search-insert-position/Solution.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | You may assume no duplicates in the array. 5 | 6 | Example 1: 7 | 8 | Input: [1,3,5,6], 5 9 | Output: 2 10 | Example 2: 11 | 12 | Input: [1,3,5,6], 2 13 | Output: 1 14 | Example 3: 15 | 16 | Input: [1,3,5,6], 7 17 | Output: 4 18 | Example 4: 19 | 20 | Input: [1,3,5,6], 0 21 | Output: 0 22 | ''' 23 | 24 | 25 | import bisect 26 | 27 | 28 | class Solution: 29 | def searchInsert(self, nums: List[int], target: int) -> int: 30 | return bisect.bisect_left(nums, target) 31 | -------------------------------------------------------------------------------- /questions/second-highest-salary/Solution.sql: -------------------------------------------------------------------------------- 1 | # Write a SQL query to get the second highest salary from the Employee table. 2 | # +----+--------+ 3 | # | Id | Salary | 4 | # +----+--------+ 5 | # | 1 | 100 | 6 | # | 2 | 200 | 7 | # | 3 | 300 | 8 | # +----+--------+ 9 | 10 | # For example, given the above Employee table, the second highest salary is 200. 11 | # If there is no second highest salary, then the query should return null. 12 | 13 | # Write your MySQL query statement below 14 | SELECT (SELECT Salary FROM Employee GROUP BY Salary ORDER BY Salary DESC LIMIT 1,1) AS SecondHighestSalary; -------------------------------------------------------------------------------- /questions/sentence-similarity/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | from collections import defaultdict 8 | 9 | class Solution: 10 | def areSentencesSimilar(self, words1: List[str], words2: List[str], pairs: List[List[str]]) -> bool: 11 | if len(words1) != len(words2): 12 | return False 13 | similar_map = defaultdict(set) 14 | for w1, w2 in pairs: 15 | similar_map[w1].add(w2) 16 | similar_map[w2].add(w1) 17 | for w1, w2 in zip(words1, words2): 18 | if w1 == w2: 19 | continue 20 | if w1 in similar_map.get(w2, []): 21 | continue 22 | return False 23 | return True 24 | -------------------------------------------------------------------------------- /questions/set-mismatch/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number. 3 | 4 | Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array. 5 | 6 | Example 1: 7 | Input: nums = [1,2,2,4] 8 | Output: [2,3] 9 | Note: 10 | The given array size will in the range [2, 10000]. 11 | The given array's numbers won't have any order. 12 | """ 13 | class Solution(object): 14 | def findErrorNums(self, nums): 15 | """ 16 | :type nums: List[int] 17 | :rtype: List[int] 18 | """ 19 | s = set() 20 | for n in nums: 21 | if n not in s: 22 | s.add(n) 23 | else: 24 | t = n 25 | break 26 | l = len(nums) 27 | missing = l * (l + 1) / 2 - sum(nums) + t 28 | return [t, missing] 29 | 30 | -------------------------------------------------------------------------------- /questions/shortest-way-to-form-string/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | from collections import Counter 8 | 9 | class Solution: 10 | def shortestWay(self, source: str, target: str) -> int: 11 | counter = Counter(source) 12 | count = 0 13 | start = 0 14 | for i, e in enumerate(target): 15 | if e not in counter: 16 | return - 1 17 | found = False 18 | while start < len(source): 19 | if found: 20 | break 21 | if source[start] == e: 22 | found = True 23 | start += 1 24 | if start >= len(source): 25 | start = 0 26 | count += 1 27 | if not found: 28 | return -1 29 | if start > 0: 30 | count += 1 31 | return count -------------------------------------------------------------------------------- /questions/single-element-in-a-sorted-array/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once. 4 | Follow up: Your solution should run in O(log n) time and O(1) space. 5 |   6 | Example 1: 7 | Input: nums = [1,1,2,3,3,4,4,8,8] 8 | Output: 2 9 | Example 2: 10 | Input: nums = [3,3,7,7,10,11,11] 11 | Output: 10 12 | 13 |   14 | Constraints: 15 | 16 | 1 <= nums.length <= 10^5 17 | 0 <= nums[i] <= 10^5 18 | 19 | """ 20 | 21 | 22 | class Solution: 23 | def singleNonDuplicate(self, nums: List[int]) -> int: 24 | low = 0 25 | high = len(nums) - 1 26 | while low < high: 27 | mid = (low + high)//2 28 | if mid%2 ==0: 29 | mid +=1 30 | if nums[mid] == nums[mid - 1]: 31 | low = mid + 1 32 | else: 33 | high = mid - 1 34 | return nums[low] -------------------------------------------------------------------------------- /questions/single-number-ii/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers, every element appears three times except for one. Find that single one. 3 | * Note: 4 | * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 5 | */ 6 | 7 | public class Solution { 8 | public int singleNumber(int[] nums) { 9 | int[] mapping = new int[32]; 10 | for (int i = 0; i < nums.length; i++) { 11 | int temp = nums[i], counter = 31; 12 | while (counter >= 0) { 13 | mapping[counter] += (temp >> counter) & 1; 14 | counter--; 15 | } 16 | } 17 | int target = 0; 18 | for (int i = 0; i < 32; i++) { 19 | target += (1 & (mapping[i] % 3)) << i; 20 | } 21 | 22 | return target; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /questions/single-number/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers, every element appears twice except for one. Find that single one. 3 | * 4 | * Note: 5 | * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | */ 7 | 8 | public class Solution { 9 | public int singleNumber(int[] nums) { 10 | int num = 0; 11 | for (int i = 0; i < nums.length; i++) { 12 | num = num ^ nums[i]; 13 | } 14 | return num; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /questions/smallest-range-i/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array nums of integers, for each integer nums[i] we may choose any x with -k <= x <= k, and add x to nums[i]. 3 | 4 | After this process, we have some array result. 5 | 6 | Return the smallest possible difference between the maximum value of result and the minimum value of result. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [1], k = 0 13 | Output: 0 14 | Explanation: result = [1] 15 | Example 2: 16 | 17 | Input: nums = [0,10], k = 2 18 | Output: 6 19 | Explanation: result = [2,8] 20 | Example 3: 21 | 22 | Input: nums = [1,3,6], k = 3 23 | Output: 0 24 | Explanation: result = [3,3,3] or result = [4,4,4] 25 | 26 | 27 | Note: 28 | 29 | 1 <= nums.length <= 10000 30 | 0 <= nums[i] <= 10000 31 | 0 <= k <= 10000 32 | """ 33 | 34 | class Solution: 35 | def smallestRangeI(self, A: List[int], K: int) -> int: 36 | if K == 0: 37 | return max(A) - min(A) 38 | r = max(A) - min(A) - K * 2 39 | return r if r > 0 else 0 -------------------------------------------------------------------------------- /questions/smallest-subsequence-of-distinct-characters/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once. 3 | 4 | Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/ 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: s = "bcabc" 11 | Output: "abc" 12 | Example 2: 13 | 14 | Input: s = "cbacdcbc" 15 | Output: "acdb" 16 | 17 | 18 | Constraints: 19 | 20 | 1 <= s.length <= 1000 21 | s consists of lowercase English letters. 22 | 23 | """ 24 | 25 | class Solution: 26 | def smallestSubsequence(self, s: str) -> str: 27 | last_occ = {c: i for i, c in enumerate(s)} 28 | stack = ["!"] 29 | visited = set() 30 | 31 | for i, symbol in enumerate(s): 32 | if symbol in visited: 33 | continue 34 | while (symbol < stack[-1] and last_occ[stack[-1]] > i): 35 | visited.remove(stack.pop()) 36 | stack.append(symbol) 37 | visited.add(symbol) 38 | return "".join(stack)[1:] 39 | -------------------------------------------------------------------------------- /questions/sort-array-by-parity/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array nums of non-negative integers, return an array consisting of all the even elements of nums, followed by all the odd elements of nums. 3 | 4 | You may return any answer array that satisfies this condition. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [3,1,2,4] 11 | Output: [2,4,3,1] 12 | The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. 13 | 14 | 15 | Note: 16 | 17 | 1 <= nums.length <= 5000 18 | 0 <= nums[i] <= 5000 19 | """ 20 | 21 | class Solution(object): 22 | def sortArrayByParity(self, A): 23 | """ 24 | :type A: List[int] 25 | :rtype: List[int] 26 | """ 27 | r1, r2 = [], [] 28 | for e in A: 29 | if e % 2 == 0: 30 | r1.append(e) 31 | else: 32 | r2.append(e) 33 | return r1 + r2 34 | -------------------------------------------------------------------------------- /questions/sparse-matrix-multiplication/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def multiply(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]: 9 | if A is None or B is None: return None 10 | m, n, l = len(A), len(A[0]), len(B[0]) 11 | if len(B) != n: 12 | raise Exception("A's column number must be equal to B's row number.") 13 | C = [[0 for _ in range(l)] for _ in range(m)] 14 | for i, row in enumerate(A): 15 | for k, eleA in enumerate(row): 16 | if eleA: 17 | for j, eleB in enumerate(B[k]): 18 | if eleB: C[i][j] += eleA * eleB 19 | return C -------------------------------------------------------------------------------- /questions/sqrtx/Solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Implement int sqrt(int x). 3 | * Compute and return the square root of x. 4 | */ 5 | class Solution { 6 | public: 7 | int mySqrt(int x) { 8 | int power = 1; 9 | int guess = 1; 10 | 11 | // check for overflow with power > 0 12 | while (x > power && power > 0) { 13 | power *= 4; 14 | guess *= 2; 15 | } 16 | 17 | guess /= 2; 18 | int odd = 2*guess + 1; 19 | int square = guess*guess; 20 | 21 | while (square <= x && square >= 0) { 22 | if (square == x) { 23 | return odd/2; 24 | } 25 | 26 | square += odd; 27 | odd += 2; 28 | } 29 | 30 | return (odd - 2)/2; 31 | } 32 | }; -------------------------------------------------------------------------------- /questions/sqrtx/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement int sqrt(int x). 3 | 4 | Compute and return the square root of x. 5 | """ 6 | 7 | 8 | class Solution(object): 9 | def mySqrt(self, x): 10 | """ 11 | :type x: int 12 | :rtype: int 13 | """ 14 | if x < 0: 15 | return None 16 | elif x < 2: 17 | return x 18 | ret = x / 2 19 | cal = ret * ret 20 | while True: 21 | if cal == x: 22 | break 23 | prev = ret 24 | ret = (ret + x / ret) / 2 25 | next_cal = ret * ret 26 | if (cal > x and next_cal < x): 27 | break 28 | elif (cal < x and next_cal > x): 29 | ret = prev 30 | break 31 | elif prev == ret: 32 | break 33 | return ret 34 | -------------------------------------------------------------------------------- /questions/squares-of-a-sorted-array/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. 4 |   5 | Example 1: 6 | 7 | Input: nums = [-4,-1,0,3,10] 8 | Output: [0,1,9,16,100] 9 | Explanation: After squaring, the array becomes [16,1,0,9,100]. 10 | After sorting, it becomes [0,1,9,16,100]. 11 | 12 | Example 2: 13 | 14 | Input: nums = [-7,-3,2,3,11] 15 | Output: [4,9,9,49,121] 16 | 17 |   18 | Constraints: 19 | 20 | 1 <= nums.length <= 104 21 | -104 <= nums[i] <= 104 22 | nums is sorted in non-decreasing order. 23 | 24 |   25 | Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach? 26 | """ 27 | 28 | 29 | class Solution: 30 | def sortedSquares(self, nums: List[int]) -> List[int]: 31 | return sorted([e * e for e in nums]) -------------------------------------------------------------------------------- /questions/strobogrammatic-number/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def isStrobogrammatic(self, num: str) -> bool: 9 | track = { 10 | 0: 0, 11 | 1: 1, 12 | 6: 9, 13 | 8: 8, 14 | 9: 6, 15 | } 16 | start, end = 0, len(num) - 1 17 | while start <= end: 18 | if start == end: 19 | if num[start] not in '018': 20 | return False 21 | else: 22 | return True 23 | sc = ord(num[start]) - ord('0') 24 | ec = ord(num[end]) - ord('0') 25 | if track.get(sc, -1) != ec: 26 | return False 27 | start += 1 28 | end -= 1 29 | return True -------------------------------------------------------------------------------- /questions/student-attendance-record-i/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | You are given a string representing an attendance record for a student. The record only contains the following three characters: 4 | 5 | 6 | 7 | 'A' : Absent. 8 | 'L' : Late. 9 | 'P' : Present. 10 | 11 | 12 | 13 | A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). 14 | You need to return whether the student could be rewarded according to his attendance record. 15 | Example 1: 16 | 17 | Input: "PPALLP" 18 | Output: True 19 | 20 | 21 | Example 2: 22 | 23 | Input: "PPALLL" 24 | Output: False 25 | 26 | 27 | 28 | """ 29 | 30 | 31 | class Solution(object): 32 | def checkRecord(self, s): 33 | """ 34 | :type s: str 35 | :rtype: bool 36 | """ 37 | ca, cl = 0, 0 38 | for c in s: 39 | if c == 'A': 40 | ca += 1 41 | cl = 0 42 | elif c == 'L': 43 | cl += 1 44 | else: 45 | cl = 0 46 | if ca > 1 or cl > 2: 47 | return False 48 | return True -------------------------------------------------------------------------------- /questions/subarray-sum-equals-k/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 3 | * 4 | * Example 1: 5 | * 6 | * Input:nums = [1,1,1], k = 2 7 | * Output: 2 8 | * 9 | * Note: 10 | * 11 | * The length of the array is in range [1, 20,000]. 12 | * The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. 13 | * 14 | */ 15 | 16 | class Solution { 17 | public int subarraySum(int[] nums, int k) { 18 | int[] sums = new int[nums.length + 1]; 19 | sums[0] = 0; 20 | for (int i = 0; i < nums.length; i++) { 21 | sums[i + 1] = sums[i] + nums[i]; 22 | } 23 | int ret = 0; 24 | for (int i = 0; i < nums.length; i++) { 25 | for (int j = i + 1; j <= nums.length; j++) { 26 | if (sums[j] - sums[i] == k) { 27 | ret++; 28 | } 29 | } 30 | } 31 | return ret; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /questions/subsets/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a set of distinct integers, nums, return all possible subsets (the power set). 3 | 4 | Note: The solution set must not contain duplicate subsets. 5 | 6 | Example: 7 | 8 | Input: nums = [1,2,3] 9 | Output: 10 | [ 11 | [3], 12 | [1], 13 | [2], 14 | [1,2,3], 15 | [1,3], 16 | [2,3], 17 | [1,2], 18 | [] 19 | ] 20 | """ 21 | 22 | 23 | class Solution: 24 | def subsets(self, nums: List[int]) -> List[List[int]]: 25 | def generate_subset(nums, ret, curr, index): 26 | if index >= len(nums): 27 | ret.append(list(curr)) 28 | return 29 | generate_subset(nums, ret, curr, index + 1) 30 | curr.append(nums[index]) 31 | generate_subset(nums, ret, curr, index + 1) 32 | curr.pop() 33 | 34 | ret = [] 35 | curr = [] 36 | generate_subset(nums, ret, curr, 0) 37 | return ret 38 | -------------------------------------------------------------------------------- /questions/sum-of-left-leaves/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Find the sum of all left leaves in a given binary tree. 4 | Example: 5 | 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | 12 | There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 13 | 14 | 15 | """ 16 | 17 | 18 | # Definition for a binary tree node. 19 | # class TreeNode(object): 20 | # def __init__(self, x): 21 | # self.val = x 22 | # self.left = None 23 | # self.right = None 24 | 25 | class Solution(object): 26 | def sumOfLeftLeaves(self, root): 27 | """ 28 | :type root: TreeNode 29 | :rtype: int 30 | """ 31 | if root is None: 32 | return 0 33 | if root.left is not None and (root.left.left is None and root.left.right is None): 34 | res1 = root.left.val 35 | else: 36 | res1 = self.sumOfLeftLeaves(root.left) 37 | res2 = self.sumOfLeftLeaves(root.right) 38 | return res1 + res2 -------------------------------------------------------------------------------- /questions/sum-of-square-numbers/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. 4 |   5 | Example 1: 6 | 7 | Input: c = 5 8 | Output: true 9 | Explanation: 1 * 1 + 2 * 2 = 5 10 | 11 | Example 2: 12 | 13 | Input: c = 3 14 | Output: false 15 | 16 | Example 3: 17 | 18 | Input: c = 4 19 | Output: true 20 | 21 | Example 4: 22 | 23 | Input: c = 2 24 | Output: true 25 | 26 | Example 5: 27 | 28 | Input: c = 1 29 | Output: true 30 | 31 |   32 | Constraints: 33 | 34 | 0 <= c <= 231 - 1 35 | 36 | 37 | """ 38 | 39 | 40 | class Solution(object): 41 | def judgeSquareSum(self, c): 42 | """ 43 | :type c: int 44 | :rtype: bool 45 | """ 46 | t = int(c ** 0.5) + 1 47 | for n in xrange(0, t): 48 | m = c - n * n 49 | a = int(m ** 0.5) 50 | if a * a == m: 51 | return True 52 | return False -------------------------------------------------------------------------------- /questions/sum-of-two-integers/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 3 | * 4 | * Example: 5 | * Given a = 1 and b = 2, return 3. 6 | * 7 | * Credits: 8 | * Special thanks to @fujiaozhu for adding this problem and creating all test cases. 9 | */ 10 | 11 | public class Solution { 12 | public int getSum(int a, int b) { 13 | while (b != 0) { 14 | int carry = a & b; 15 | a = a ^ b; 16 | b = carry << 1; 17 | } 18 | return a; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /questions/summary-ranges/Solution.py: -------------------------------------------------------------------------------- 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 | Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range. 9 | Example 2: 10 | 11 | Input: [0,2,3,4,6,8,9] 12 | Output: ["0","2->4","6","8->9"] 13 | Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range. 14 | """ 15 | 16 | 17 | class Solution: 18 | def summaryRanges(self, nums: List[int]) -> List[str]: 19 | rgs = [] 20 | for n in nums: 21 | if not rgs: 22 | rgs.append([n]) 23 | continue 24 | last = rgs[-1] 25 | if last[-1] == n - 1: 26 | last = last + [n] if len(last) == 1 else [last[0], n] 27 | rgs[-1] = last 28 | else: 29 | rgs.append([n]) 30 | ret = [] 31 | for rg in rgs: 32 | if len(rg) == 1: 33 | ret.append(str(rg[0])) 34 | else: 35 | ret.append('{}->{}'.format(rg[0], rg[1])) 36 | return ret 37 | -------------------------------------------------------------------------------- /questions/swap-salary/Solution.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table. 3 | 4 | For example: 5 | 6 | | id | name | sex | salary | 7 | |----|------|-----|--------| 8 | | 1 | A | m | 2500 | 9 | | 2 | B | f | 1500 | 10 | | 3 | C | m | 5500 | 11 | | 4 | D | f | 500 | 12 | 13 | After running your query, the above salary table should have the following rows: 14 | 15 | | id | name | sex | salary | 16 | |----|------|-----|--------| 17 | | 1 | A | f | 2500 | 18 | | 2 | B | m | 1500 | 19 | | 3 | C | f | 5500 | 20 | | 4 | D | m | 500 | 21 | */ 22 | /* this needs to update the original table */ 23 | Update salary SET sex = CASE sex WHEN 'f' THEN 'm' ELSE 'f' END; 24 | -------------------------------------------------------------------------------- /questions/tenth-line/Solution.sh: -------------------------------------------------------------------------------- 1 | ## How would you print just the 10th line of a file? 2 | ## 3 | ## For example, assume that file.txt has the following content: 4 | ## 5 | ## Line 1 6 | ## Line 2 7 | ## Line 3 8 | ## Line 4 9 | ## Line 5 10 | ## Line 6 11 | ## Line 7 12 | ## Line 8 13 | ## Line 9 14 | ## Line 10 15 | ## Your script should output the tenth line, which is: 16 | ## Line 10 17 | 18 | # Read from the file file.txt and output the tenth line to stdout. 19 | tail -n+10 file.txt | head -n1 20 | -------------------------------------------------------------------------------- /questions/to-lower-case/Solution.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/franklingu/leetcode-solutions/7ad7e5c1c040510b7b7bd225ed4297054464dbc6/questions/to-lower-case/Solution.py -------------------------------------------------------------------------------- /questions/top-k-frequent-elements/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a non-empty array of integers, return the k most frequent elements. 4 | Example 1: 5 | 6 | Input: nums = [1,1,1,2,2,3], k = 2 7 | Output: [1,2] 8 | 9 | 10 | Example 2: 11 | 12 | Input: nums = [1], k = 1 13 | Output: [1] 14 | 15 | Note: 16 | 17 | You may assume k is always valid, 1 ≤ k ≤ number of unique elements. 18 | Your algorithm's time complexity must be better than O(n log n), where n is the array's size. 19 | It's guaranteed that the answer is unique, in other words the set of the top k frequent elements is unique. 20 | You can return the answer in any order. 21 | 22 | 23 | """ 24 | 25 | 26 | class Solution: 27 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 28 | import collections 29 | import heapq 30 | items = collections.Counter(nums).items() 31 | return [key for value, key in heapq.nlargest(k, [(value, key) for key, value in items])] -------------------------------------------------------------------------------- /questions/transpose-file/Solution.sh: -------------------------------------------------------------------------------- 1 | ## Given a text file file.txt, transpose its content. 2 | ## 3 | ## You may assume that each row has the same number of columns and each field is separated by the ' ' character. 4 | ## 5 | ## For example, if file.txt has the following content: 6 | ## 7 | ## name age 8 | ## alice 21 9 | ## ryan 30 10 | ## Output the following: 11 | ## 12 | ## name alice ryan 13 | ## age 21 30 14 | 15 | # Read from the file file.txt and print its transposed content to stdout. 16 | awk ' 17 | { 18 | for (i = 1; i <= NF; i++) { 19 | if(NR == 1) { 20 | s[i] = $i; 21 | } else { 22 | s[i] = s[i] " " $i; 23 | } 24 | } 25 | } 26 | END { 27 | for (i = 1; s[i] != ""; i++) { 28 | print s[i]; 29 | } 30 | }' file.txt 31 | -------------------------------------------------------------------------------- /questions/transpose-matrix/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a matrix A, return the transpose of A. 3 | 4 | The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [[1,2,3],[4,5,6],[7,8,9]] 11 | Output: [[1,4,7],[2,5,8],[3,6,9]] 12 | Example 2: 13 | 14 | Input: [[1,2,3],[4,5,6]] 15 | Output: [[1,4],[2,5],[3,6]] 16 | 17 | 18 | Note: 19 | 20 | 1 <= A.length <= 1000 21 | 1 <= A[0].length <= 1000 22 | """ 23 | class Solution(object): 24 | def transpose(self, A): 25 | """ 26 | :type A: List[List[int]] 27 | :rtype: List[List[int]] 28 | """ 29 | if not A: 30 | return [] 31 | ret = [] 32 | for j in range(len(A[0])): 33 | c = [] 34 | for i, r in enumerate(A): 35 | c.append(A[i][j]) 36 | ret.append(c) 37 | return ret 38 | -------------------------------------------------------------------------------- /questions/two-sum/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers, find two numbers such that they add up to a specific target number. 3 | * The function twoSum should return indices of the two numbers such that they add up to the target, 4 | * where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. 5 | * 6 | * You may assume that each input would have exactly one solution. 7 | * 8 | * Input: numbers={2, 7, 11, 15}, target=9 9 | * Output: index1=1, index2=2 10 | */ 11 | 12 | 13 | public class Solution { 14 | public int[] twoSum(int[] nums, int target) { 15 | int[] results = new int[2]; 16 | for (int i = 0; i < nums.length; i++) { 17 | for (int j = i + 1; j < nums.length; j++) { 18 | if (nums[i] + nums[j] == target) { 19 | results[0] = i + 1; 20 | results[1] = j + 1; 21 | return results; 22 | } 23 | } 24 | } 25 | return results; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /questions/two-sum/Solution.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 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 | 14 | 15 | class Solution: 16 | def twoSum(self, nums: List[int], target: int) -> List[int]: 17 | track = {} 18 | for i, n in enumerate(nums): 19 | if n not in track: 20 | track[n] = [i] 21 | else: 22 | track[n].append(i) 23 | for k in track: 24 | left = target - k 25 | if left not in track: 26 | continue 27 | if left == k and len(track[k]) == 1: 28 | continue 29 | elif left == k: 30 | return track[k] 31 | return [track[k][0], track[left][0]] 32 | -------------------------------------------------------------------------------- /questions/ugly-number/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a program to check whether a given number is an ugly number. 3 | * 4 | * Ugly numbers are positive numbers whose prime factors only include 5 | * 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it 6 | * includes another prime factor 7. 7 | * 8 | * Note that 1 is typically treated as an ugly number. 9 | */ 10 | 11 | public class Solution { 12 | public boolean isUgly(int num) { 13 | if (num == 0) { 14 | return false; 15 | } 16 | 17 | while (num % 2 == 0) { num /= 2; } 18 | while (num % 3 == 0) { num /= 3; } 19 | while (num % 5 == 0) { num /= 5; } 20 | 21 | if (num == 1) { 22 | return true; 23 | } 24 | 25 | return false; 26 | } 27 | } -------------------------------------------------------------------------------- /questions/unique-binary-search-trees/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. 4 |   5 | Example 1: 6 | 7 | 8 | Input: n = 3 9 | Output: 5 10 | 11 | Example 2: 12 | 13 | Input: n = 1 14 | Output: 1 15 | 16 |   17 | Constraints: 18 | 19 | 1 <= n <= 19 20 | 21 | 22 | """ 23 | 24 | 25 | class Solution(object): 26 | def numTrees(self, n): 27 | """ 28 | :type n: int 29 | :rtype: int 30 | """ 31 | d={} 32 | def help(n): 33 | if n in d: 34 | return d[n] 35 | if n<=2: 36 | d[n]=n 37 | return n 38 | result=0 39 | for i in range(1,n-1): 40 | result+=help(i)*help(n-i-1) 41 | result+=2*help(n-1) 42 | d[n]=result 43 | return result 44 | help(n) 45 | return d[n] -------------------------------------------------------------------------------- /questions/unique-number-of-occurrences/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise. 4 |   5 | Example 1: 6 | 7 | Input: arr = [1,2,2,1,1,3] 8 | Output: true 9 | Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. 10 | Example 2: 11 | 12 | Input: arr = [1,2] 13 | Output: false 14 | 15 | Example 3: 16 | 17 | Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] 18 | Output: true 19 | 20 |   21 | Constraints: 22 | 23 | 1 <= arr.length <= 1000 24 | -1000 <= arr[i] <= 1000 25 | 26 | 27 | """ 28 | 29 | 30 | class Solution: 31 | def uniqueOccurrences(self, arr: List[int]) -> bool: 32 | counter = Counter(arr) 33 | freqs = list(counter.values()) 34 | return len(freqs) == len(set(freqs)) -------------------------------------------------------------------------------- /questions/valid-anagram/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given two strings s and t, write a function to determine if t is an anagram of s. 3 | * 4 | * For example, 5 | * s = "anagram", t = "nagaram", return true. 6 | * s = "rat", t = "car", return false. 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? 13 | */ 14 | 15 | public class Solution { 16 | public boolean isAnagram(String s, String t) { 17 | if (s.length() != t.length()) { 18 | return false; 19 | } 20 | int[] mapping = new int[256]; 21 | for (int i = 0; i < s.length(); i++) { 22 | mapping[(int)(s.charAt(i))]++; 23 | } 24 | for (int i = 0; i < t.length(); i++) { 25 | mapping[(int)(t.charAt(i))]--; 26 | } 27 | for (int i = 0; i < mapping.length; i++) { 28 | if (mapping[i] != 0) { 29 | return false; 30 | } 31 | } 32 | return true; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /questions/valid-boomerang/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang. 4 | A boomerang is a set of three points that are all distinct and not in a straight line. 5 |   6 | Example 1: 7 | Input: points = [[1,1],[2,3],[3,2]] 8 | Output: true 9 | Example 2: 10 | Input: points = [[1,1],[2,2],[3,3]] 11 | Output: false 12 | 13 |   14 | Constraints: 15 | 16 | points.length == 3 17 | points[i].length == 2 18 | 0 <= xi, yi <= 100 19 | 20 | 21 | """ 22 | 23 | 24 | class Solution: 25 | def isBoomerang(self, points: List[List[int]]) -> bool: 26 | p1, p2, p3 = points 27 | if p1 == p2 or p1 == p3 or p2 == p3: 28 | return False 29 | return (p2[1] - p1[1]) * (p3[0] - p1[0]) != (p3[1] - p1[1]) * (p2[0] - p1[0]) 30 | -------------------------------------------------------------------------------- /questions/valid-phone-numbers/Solution.sh: -------------------------------------------------------------------------------- 1 | ## Given a text file file.txt that contains list of phone numbers (one per line), write a one liner bash script to print all valid phone numbers. 2 | ## 3 | ## You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit) 4 | ## 5 | ## You may also assume each line in the text file must not contain leading or trailing white spaces. 6 | ## 7 | ## For example, assume that file.txt has the following content: 8 | ## 9 | ## 987-123-4567 10 | ## 123 456 7890 11 | ## (123) 456-7890 12 | ## Your script should output the following valid phone numbers: 13 | ## 987-123-4567 14 | ## (123) 456-7890 15 | 16 | cat file.txt | grep -Eo '^(\([0-9]{3}\) ){1}[0-9]{3}-[0-9]{4}$|^([0-9]{3}-){2}[0-9]{4}$' 17 | -------------------------------------------------------------------------------- /questions/valid-triangle-number/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. 4 |   5 | Example 1: 6 | 7 | Input: nums = [2,2,3,4] 8 | Output: 3 9 | Explanation: Valid combinations are: 10 | 2,3,4 (using the first 2) 11 | 2,3,4 (using the second 2) 12 | 2,2,3 13 | 14 | Example 2: 15 | 16 | Input: nums = [4,2,3,4] 17 | Output: 4 18 | 19 |   20 | Constraints: 21 | 22 | 1 <= nums.length <= 1000 23 | 0 <= nums[i] <= 1000 24 | 25 | 26 | """ 27 | 28 | 29 | class Solution: 30 | def triangleNumber(self, nums: List[int]) -> int: 31 | count = 0 32 | nums.sort() 33 | for k in range(len(nums)-1,1,-1): 34 | i = 0 35 | j = k-1 36 | while i < j: 37 | if nums[i] + nums[j] > nums[k]: 38 | count += j - i 39 | j -= 1 40 | else: 41 | i += 1 42 | return count -------------------------------------------------------------------------------- /questions/valid-word-abbreviation/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def validWordAbbreviation(self, word: str, abbr: str) -> bool: 9 | runner = 0 10 | curr = 0 11 | for i, c in enumerate(abbr): 12 | if c.isalpha(): 13 | runner += curr 14 | curr = 0 15 | if runner >= len(word) or c != word[runner]: 16 | return False 17 | runner += 1 18 | else: 19 | if curr == 0 and c == '0': 20 | return False 21 | curr = curr * 10 + ord(c) - ord('0') 22 | runner += curr 23 | if runner != len(word): 24 | return False 25 | return True -------------------------------------------------------------------------------- /questions/valid-word-square/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def validWordSquare(self, words: List[str]) -> bool: 9 | N = len(words) 10 | for row in words: 11 | N = max(len(row), N) 12 | for i in range(N): 13 | for j in range(i + 1, N): 14 | c1, c2 = None, None 15 | try: 16 | c1 = words[i][j] 17 | except IndexError: 18 | pass 19 | try: 20 | c2 = words[j][i] 21 | except IndexError: 22 | pass 23 | if c1 != c2: 24 | return False 25 | return True -------------------------------------------------------------------------------- /questions/wiggle-sort-ii/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... 4 | You may assume the input array always has a valid answer. 5 |   6 | Example 1: 7 | 8 | Input: nums = [1,5,1,1,6,4] 9 | Output: [1,6,1,5,1,4] 10 | Explanation: [1,4,1,5,1,6] is also accepted. 11 | 12 | Example 2: 13 | 14 | Input: nums = [1,3,2,2,3,1] 15 | Output: [2,3,1,3,1,2] 16 | 17 |   18 | Constraints: 19 | 20 | 1 <= nums.length <= 5 * 104 21 | 0 <= nums[i] <= 5000 22 | It is guaranteed that there will be an answer for the given input nums. 23 | 24 |   25 | Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space? 26 | """ 27 | 28 | 29 | class Solution: 30 | def wiggleSort(self, nums: List[int]) -> None: 31 | """ 32 | Do not return anything, modify nums in-place instead. 33 | """ 34 | nums.sort() 35 | half = len(nums[::2]) 36 | nums[::2], nums[1::2] = nums[:half][::-1], nums[half:][::-1] 37 | -------------------------------------------------------------------------------- /questions/word-abbreviation/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | class Solution: 8 | def wordsAbbreviation(self, dict: List[str]) -> List[str]: 9 | def shorten(word, idx): 10 | return word if idx > len(word) - 3 else \ 11 | word[:idx] + str(len(word)-1-idx) + word[-1] 12 | 13 | res = [shorten(word, 1) for word in dict] 14 | pre = {word : 1 for word in dict} 15 | n = len(dict) 16 | for i in range(n): 17 | while True: 18 | duplicate = [j for j in range(i, n) if res[i] == res[j]] 19 | if len(duplicate) == 1: break 20 | for k in duplicate: 21 | pre[dict[k]] += 1 22 | res[k] = shorten(dict[k], pre[dict[k]]) 23 | return res 24 | -------------------------------------------------------------------------------- /questions/word-frequency/Solution.sh: -------------------------------------------------------------------------------- 1 | ## Write a bash script to calculate the frequency of each word in a text file words.txt. 2 | ## 3 | ## For simplicity sake, you may assume: 4 | ## 5 | ## words.txt contains only lowercase characters and space ' ' characters. 6 | ## Each word must consist of lowercase characters only. 7 | ## Words are separated by one or more whitespace characters. 8 | ## For example, assume that words.txt has the following content: 9 | ## 10 | ## the day is sunny the the 11 | ## the sunny is is 12 | ## Your script should output the following, sorted by descending frequency: 13 | ## the 4 14 | ## is 3 15 | ## sunny 2 16 | ## day 1 17 | ## Note: 18 | ## Don't worry about handling ties, it is guaranteed that each word's frequency count is unique. 19 | 20 | # Read from the file words.txt and output the word frequency list to stdout. 21 | cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -rn | awk '{print $2" "$1}' 22 | -------------------------------------------------------------------------------- /questions/word-squares/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | None 4 | """ 5 | 6 | 7 | import collections 8 | 9 | 10 | class Solution: 11 | def wordSquares(self, words: List[str]) -> List[List[str]]: 12 | n = len(words[0]) 13 | fulls = collections.defaultdict(list) 14 | for word in words: 15 | for i in range(n): 16 | fulls[word[:i]].append(word) 17 | def build(square): 18 | if len(square) == n: 19 | squares.append(square) 20 | return 21 | for word in fulls[''.join(list(zip(*square))[len(square)])]: 22 | build(square + [word]) 23 | squares = [] 24 | for word in words: 25 | build([word]) 26 | return squares -------------------------------------------------------------------------------- /test_requirements.txt: -------------------------------------------------------------------------------- 1 | cssselect 2 | lxml 3 | requests 4 | beautifulsoup4 5 | --------------------------------------------------------------------------------