├── .github └── FUNDING.yml ├── 1-lclighter-data-idlgt255811883-data-bundle-id0-stylebackground-image-linear-gradienttransparent-0-transparent-calc50-4px-rgb204-242-241-calc50-4px-rgb204-242-241-100-transition-background-position-120ms-ease-in-out-0s-padding-120ms-ease-in-out-0s-background-size-100-200-background-position-initial-user-select-auto-two-sum-lclighterdiv-classlinerthreadicon-linerfirst-lineroverlapse-data-highlight-id255811883-data-bundle-id0-idlgt255811883-stylebackground-image-url-and-quot-https-photogetlinercom-liner-service-bucket-user-photo-default-color-2-vsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-divdiv-classlinerthreadicon-linersecond-data-highlight-id257820954-data-bundle-id0-idlgt257820954-stylebackground-image-url-and-quot-https-photogetlinercom-liner-service-bucket-user-photo-default-color-5-gsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-div ├── 1-lclighter-data-idlgt255811883-data-bundle-id0-stylebackground-image-linear-gradienttransparent-0-transparent-calc50-4px-rgb204-242-241-calc50-4px-rgb204-242-241-100-transition-background-position-120ms-ease-in-out-0s-padding-120ms-ease-in-out-0s-background-size-100-200-background-position-initial-user-select-auto-two-sum-lclighterdiv-classlinerthreadicon-linerfirst-lineroverlapse-data-highlight-id255811883-data-bundle-id0-idlgt255811883-stylebackground-image-url-and-quot-https-photogetlinercom-liner-service-bucket-user-photo-default-color-2-vsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-divdiv-classlinerthreadicon-linersecond-data-highlight-id257820954-data-bundle-id0-idlgt257820954-stylebackground-image-url-and-quot-https-photogetlinercom-liner-service-bucket-user-photo-default-color-5-gsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-div.py ├── NOTES.md └── README.md ├── 100-same-tree ├── 100-same-tree.py └── README.md ├── 1004-max-consecutive-ones-iii ├── 1004-max-consecutive-ones-iii.py ├── NOTES.md └── README.md ├── 101-symmetric-tree ├── 101-symmetric-tree.py └── NOTES.md ├── 102-binary-tree-level-order-traversal ├── 102-binary-tree-level-order-traversal.py ├── NOTES.md └── README.md ├── 103-binary-tree-zigzag-level-order-traversal ├── 103-binary-tree-zigzag-level-order-traversal.py ├── NOTES.md └── README.md ├── 107-binary-tree-level-order-traversal-ii ├── 107-binary-tree-level-order-traversal-ii.py ├── NOTES.md └── README.md ├── 108-convert-sorted-array-to-binary-search-tree ├── 108-convert-sorted-array-to-binary-search-tree.py ├── NOTES.md └── README.md ├── 111-minimum-depth-of-binary-tree ├── 111-minimum-depth-of-binary-tree.py ├── NOTES.md └── README.md ├── 112-path-sum ├── 112-path-sum.py ├── NOTES.md └── README.md ├── 113-path-sum-ii ├── 113-path-sum-ii.py └── NOTES.md ├── 116-populating-next-right-pointers-in-each-node ├── 116-populating-next-right-pointers-in-each-node.py ├── NOTES.md └── README.md ├── 117-populating-next-right-pointers-in-each-node-ii ├── 117-populating-next-right-pointers-in-each-node-ii.py ├── NOTES.md └── README.md ├── 121-best-time-to-buy-and-sell-stock ├── 121-best-time-to-buy-and-sell-stock.py ├── NOTES.md └── README.md ├── 122-best-time-to-buy-and-sell-stock-ii ├── 122-best-time-to-buy-and-sell-stock-ii.py ├── NOTES.md └── README.md ├── 124-binary-tree-maximum-path-sum ├── 124-binary-tree-maximum-path-sum.py ├── NOTES.md └── README.md ├── 125-valid-palindrome ├── NOTES.md └── README.md ├── 127-word-ladder ├── 127-word-ladder.java ├── NOTES.md └── README.md ├── 1281-subtract-the-product-and-sum-of-digits-of-an-integer ├── 1281-subtract-the-product-and-sum-of-digits-of-an-integer.py └── NOTES.md ├── 129-sum-root-to-leaf-numbers ├── 129-sum-root-to-leaf-numbers.py └── README.md ├── 1323-maximum-69-number ├── 1323-maximum-69-number.py ├── NOTES.md └── README.md ├── 133-clone-graph ├── 133-clone-graph.py ├── NOTES.md └── README.md ├── 134-gas-station ├── 134-gas-station.py ├── NOTES.md └── README.md ├── 1342-number-of-steps-to-reduce-a-number-to-zero ├── 1342-number-of-steps-to-reduce-a-number-to-zero.py ├── NOTES.md └── README.md ├── 1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree ├── 1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.py ├── NOTES.md └── README.md ├── 142-linked-list-cycle-ii ├── 142-linked-list-cycle-ii.py ├── NOTES.md └── README.md ├── 143-reorder-list ├── 143-reorder-list.py ├── NOTES.md └── README.md ├── 146-lru-cache ├── 146-lru-cache.py └── README.md ├── 148-sort-list ├── 148-sort-list.py ├── NOTES.md └── README.md ├── 1480-running-sum-of-1d-array ├── 1480-running-sum-of-1d-array.py ├── NOTES.md └── README.md ├── 1486-xor-operation-in-an-array ├── 1486-xor-operation-in-an-array.py ├── NOTES.md └── README.md ├── 15-3sum ├── 15-3sum.py ├── NOTES.md └── README.md ├── 1512-number-of-good-pairs ├── 1512-number-of-good-pairs.py ├── NOTES.md └── README.md ├── 1528-shuffle-string ├── NOTES.md └── README.md ├── 1534-count-good-triplets ├── 1534-count-good-triplets.py ├── NOTES.md └── README.md ├── 155-min-stack ├── NOTES.md └── README.md ├── 1557-minimum-number-of-vertices-to-reach-all-nodes ├── 1557-minimum-number-of-vertices-to-reach-all-nodes.py ├── NOTES.md └── README.md ├── 16-3sum-closest ├── 16-3sum-closest.py ├── NOTES.md └── README.md ├── 160-intersection-of-two-linked-lists ├── 160-intersection-of-two-linked-lists.py └── README.md ├── 162-find-peak-element ├── 162-find-peak-element.py ├── NOTES.md └── README.md ├── 169-majority-element ├── 169-majority-element.py ├── NOTES.md └── README.md ├── 17-letter-combinations-of-a-phone-number ├── 17-letter-combinations-of-a-phone-number.py ├── NOTES.md └── README.md ├── 171-excel-sheet-column-number ├── 171-excel-sheet-column-number.py ├── NOTES.md └── README.md ├── 1780-check-if-number-is-a-sum-of-powers-of-three ├── 1780-check-if-number-is-a-sum-of-powers-of-three.py ├── NOTES.md └── README.md ├── 18-4sum ├── 18-4sum.py ├── NOTES.md └── README.md ├── 1812-determine-color-of-a-chessboard-square ├── 1812-determine-color-of-a-chessboard-square.py ├── NOTES.md └── README.md ├── 189-rotate-array ├── 189-rotate-array.py └── NOTES.md ├── 19-remove-nth-node-from-end-of-list ├── NOTES.md └── README.md ├── 199-binary-tree-right-side-view ├── 199-binary-tree-right-side-view.py ├── NOTES.md └── README.md ├── 2-add-two-numbers ├── 2-add-two-numbers.py ├── NOTES.md └── README.md ├── 20-valid-parentheses ├── 20-valid-parentheses.py ├── NOTES.md └── README.md ├── 200-number-of-islands ├── 200-number-of-islands.py ├── NOTES.md └── README.md ├── 2011-final-value-of-variable-after-performing-operations ├── 2011-final-value-of-variable-after-performing-operations.py ├── NOTES.md └── README.md ├── 202-happy-number ├── 202-happy-number.py ├── NOTES.md └── README.md ├── 203-remove-linked-list-elements ├── 203-remove-linked-list-elements.py ├── NOTES.md └── README.md ├── 205-isomorphic-strings ├── 205-isomorphic-strings.js ├── 205-isomorphic-strings.py └── README.md ├── 2059-minimum-operations-to-convert-number ├── 2059-minimum-operations-to-convert-number.py ├── NOTES.md └── README.md ├── 206-reverse-linked-list ├── 206-reverse-linked-list.py ├── NOTES.md └── README.md ├── 207-course-schedule ├── 207-course-schedule.py ├── NOTES.md └── README.md ├── 208-implement-trie-prefix-tree ├── 208-implement-trie-prefix-tree.py ├── NOTES.md └── README.md ├── 2089-find-target-indices-after-sorting-array ├── 2089-find-target-indices-after-sorting-array.py ├── NOTES.md └── README.md ├── 209-minimum-size-subarray-sum ├── 209-minimum-size-subarray-sum.py ├── NOTES.md └── README.md ├── 21-merge-two-sorted-lists ├── 21-merge-two-sorted-lists.py ├── NOTES.md └── README.md ├── 210-course-schedule-ii ├── 210-course-schedule-ii.py ├── NOTES.md └── README.md ├── 215-kth-largest-element-in-an-array ├── 215-kth-largest-element-in-an-array.py └── README.md ├── 217-contains-duplicate ├── 217-contains-duplicate.py ├── NOTES.md └── README.md ├── 219-contains-duplicate-ii ├── 219-contains-duplicate-ii.py ├── NOTES.md └── README.md ├── 220-contains-duplicate-iii ├── 220-contains-duplicate-iii.py └── NOTES.md ├── 222-count-complete-tree-nodes ├── 222-count-complete-tree-nodes.py └── README.md ├── 2235-add-two-integers ├── 2235-add-two-integers.py ├── NOTES.md └── README.md ├── 2236-root-equals-sum-of-children ├── 2236-root-equals-sum-of-children.cpp ├── 2236-root-equals-sum-of-children.py ├── NOTES.md └── README.md ├── 229-majority-element-ii ├── 229-majority-element-ii.py └── README.md ├── 23-merge-k-sorted-lists ├── 23-merge-k-sorted-lists.py ├── NOTES.md └── README.md ├── 231-power-of-two ├── 231-power-of-two.py ├── NOTES.md └── README.md ├── 234-palindrome-linked-list ├── 234-palindrome-linked-list.py ├── NOTES.md └── README.md ├── 237-delete-node-in-a-linked-list ├── NOTES.md └── README.md ├── 240-search-a-2d-matrix-ii ├── 240-search-a-2d-matrix-ii.py ├── NOTES.md └── README.md ├── 242-valid-anagram ├── 242-valid-anagram.py └── README.md ├── 257-binary-tree-paths ├── 257-binary-tree-paths.py ├── NOTES.md └── README.md ├── 26-remove-duplicates-from-sorted-array ├── 26-remove-duplicates-from-sorted-array.py └── README.md ├── 27-remove-element ├── 27-remove-element.py ├── NOTES.md └── README.md ├── 275-h-index-ii ├── 275-h-index-ii.py ├── NOTES.md └── README.md ├── 278-first-bad-version ├── 278-first-bad-version.py ├── NOTES.md └── README.md ├── 28-implement-strstr ├── 28-implement-strstr.py └── NOTES.md ├── 283-move-zeroes ├── NOTES.md └── README.md ├── 287-find-the-duplicate-number ├── 287-find-the-duplicate-number.py ├── NOTES.md └── README.md ├── 295-find-median-from-data-stream ├── 295-find-median-from-data-stream.java ├── NOTES.md └── README.md ├── 3-longest-substring-without-repeating-characters ├── 3-longest-substring-without-repeating-characters.py ├── NOTES.md └── README.md ├── 30-substring-with-concatenation-of-all-words ├── 30-substring-with-concatenation-of-all-words.py └── NOTES.md ├── 303-range-sum-query-immutable ├── 303-range-sum-query-immutable.py ├── NOTES.md └── README.md ├── 304-range-sum-query-2d-immutable ├── 304-range-sum-query-2d-immutable.py ├── NOTES.md └── README.md ├── 326-power-of-three ├── 326-power-of-three.py ├── NOTES.md └── README.md ├── 33-search-in-rotated-sorted-array ├── 33-search-in-rotated-sorted-array.py ├── NOTES.md └── README.md ├── 34-find-first-and-last-position-of-element-in-sorted-array ├── 34-find-first-and-last-position-of-element-in-sorted-array.py ├── NOTES.md └── README.md ├── 342-power-of-four ├── 342-power-of-four.py ├── NOTES.md └── README.md ├── 344-reverse-string ├── 344-reverse-string.py └── README.md ├── 349-intersection-of-two-arrays ├── 349-intersection-of-two-arrays.py ├── NOTES.md └── README.md ├── 35-search-insert-position ├── 35-search-insert-position.py ├── NOTES.md └── README.md ├── 392-is-subsequence ├── 392-is-subsequence.py └── README.md ├── 4-median-of-two-sorted-arrays ├── 4-median-of-two-sorted-arrays.py ├── NOTES.md └── README.md ├── 409-longest-palindrome ├── 409-longest-palindrome.py ├── NOTES.md └── README.md ├── 41-first-missing-positive ├── 41-first-missing-positive.py ├── NOTES.md └── README.md ├── 412-fizz-buzz └── 412-fizz-buzz.py ├── 414-third-maximum-number ├── 414-third-maximum-number.py ├── NOTES.md └── README.md ├── 417-pacific-atlantic-water-flow ├── 417-pacific-atlantic-water-flow.py ├── NOTES.md └── README.md ├── 424-longest-repeating-character-replacement ├── 424-longest-repeating-character-replacement.py ├── NOTES.md └── README.md ├── 437-path-sum-iii ├── 437-path-sum-iii.py ├── NOTES.md └── README.md ├── 438-find-all-anagrams-in-a-string ├── 438-find-all-anagrams-in-a-string.py ├── NOTES.md └── README.md ├── 442-find-all-duplicates-in-an-array ├── 442-find-all-duplicates-in-an-array.py ├── NOTES.md └── README.md ├── 448-find-all-numbers-disappeared-in-an-array ├── 448-find-all-numbers-disappeared-in-an-array.py ├── NOTES.md └── README.md ├── 451-sort-characters-by-frequency ├── 451-sort-characters-by-frequency.py ├── NOTES.md └── README.md ├── 457-circular-array-loop ├── 457-circular-array-loop.py ├── NOTES.md └── README.md ├── 46-permutations ├── 46-permutations.py ├── NOTES.md └── README.md ├── 463-island-perimeter ├── 463-island-perimeter.py └── README.md ├── 49-group-anagrams ├── 49-group-anagrams.py ├── NOTES.md └── README.md ├── 50-powx-n ├── 50-powx-n.py ├── NOTES.md └── README.md ├── 500-keyboard-row ├── 500-keyboard-row.py ├── NOTES.md └── README.md ├── 509-fibonacci-number ├── 509-fibonacci-number.py └── README.md ├── 515-find-largest-value-in-each-tree-row ├── 515-find-largest-value-in-each-tree-row.py ├── NOTES.md └── README.md ├── 53-maximum-subarray ├── 53-maximum-subarray.py ├── NOTES.md └── README.md ├── 532-k-diff-pairs-in-an-array ├── 532-k-diff-pairs-in-an-array.py ├── NOTES.md └── README.md ├── 543-diameter-of-binary-tree ├── 543-diameter-of-binary-tree.py ├── NOTES.md └── README.md ├── 547-number-of-provinces ├── 547-number-of-provinces.py ├── NOTES.md └── README.md ├── 56-merge-intervals ├── 56-merge-intervals.py ├── NOTES.md └── README.md ├── 58-length-of-last-word ├── 58-length-of-last-word.py ├── NOTES.md └── README.md ├── 581-shortest-unsorted-continuous-subarray ├── 581-shortest-unsorted-continuous-subarray.py ├── NOTES.md └── README.md ├── 60-permutation-sequence ├── 60-permutation-sequence.py ├── NOTES.md └── README.md ├── 637-average-of-levels-in-binary-tree ├── 637-average-of-levels-in-binary-tree.py ├── NOTES.md └── README.md ├── 643-maximum-average-subarray-i ├── 643-maximum-average-subarray-i.py ├── NOTES.md └── README.md ├── 645-set-mismatch ├── 645-set-mismatch.py ├── NOTES.md └── README.md ├── 67-add-binary └── NOTES.md ├── 69-sqrtx └── NOTES.md ├── 70-climbing-stairs ├── 70-climbing-stairs.py ├── NOTES.md └── README.md ├── 704-binary-search ├── NOTES.md └── README.md ├── 724-find-pivot-index ├── 724-find-pivot-index.py └── README.md ├── 73-set-matrix-zeroes ├── 73-set-matrix-zeroes.py ├── NOTES.md └── README.md ├── 74-search-a-2d-matrix ├── 74-search-a-2d-matrix.py ├── NOTES.md └── README.md ├── 743-network-delay-time ├── NOTES.md └── README.md ├── 75-sort-colors ├── 75-sort-colors.py ├── NOTES.md └── README.md ├── 752-open-the-lock ├── 752-open-the-lock.py └── README.md ├── 76-minimum-window-substring ├── 76-minimum-window-substring.py └── README.md ├── 771-jewels-and-stones ├── 771-jewels-and-stones.py ├── NOTES.md └── README.md ├── 78-subsets ├── 78-subsets.py ├── NOTES.md └── README.md ├── 79-word-search ├── NOTES.md └── README.md ├── 81-search-in-rotated-sorted-array-ii ├── 81-search-in-rotated-sorted-array-ii.py ├── NOTES.md └── README.md ├── 83-remove-duplicates-from-sorted-list ├── 83-remove-duplicates-from-sorted-list.py ├── NOTES.md └── README.md ├── 836-rectangle-overlap ├── 836-rectangle-overlap.py └── README.md ├── 841-keys-and-rooms ├── 841-keys-and-rooms.py ├── NOTES.md └── README.md ├── 841-lclighter-data-idlgt257723750-data-bundle-id0-stylebackground-image-linear-gradienttransparent-0-transparent-calc50-4px-rgb204-242-241-calc50-4px-rgb204-242-241-100-transition-background-position-120ms-ease-in-out-0s-padding-120ms-ease-in-out-0s-background-size-100-200-background-position-initial-user-select-auto-keys-and-rooms-lclighterdiv-classlinerthreadicon-linerfirst-data-highlight-id257723750-data-bundle-id0-idlgt257723750-stylebackground-image-url-and-quot-https-profilegetlinercom-liner-service-bucket-user-photo-default-color-10-wsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-div ├── 841-lclighter-data-idlgt257723750-data-bundle-id0-stylebackground-image-linear-gradienttransparent-0-transparent-calc50-4px-rgb204-242-241-calc50-4px-rgb204-242-241-100-transition-background-position-120ms-ease-in-out-0s-padding-120ms-ease-in-out-0s-background-size-100-200-background-position-initial-user-select-auto-keys-and-rooms-lclighterdiv-classlinerthreadicon-linerfirst-data-highlight-id257723750-data-bundle-id0-idlgt257723750-stylebackground-image-url-and-quot-https-profilegetlinercom-liner-service-bucket-user-photo-default-color-10-wsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-div.py ├── NOTES.md └── README.md ├── 844-backspace-string-compare ├── 844-backspace-string-compare.py └── README.md ├── 852-peak-index-in-a-mountain-array ├── 852-peak-index-in-a-mountain-array.py └── README.md ├── 860-lemonade-change └── NOTES.md ├── 876-middle-of-the-linked-list ├── 876-middle-of-the-linked-list.py ├── NOTES.md └── README.md ├── 9-palindrome-number ├── 9-palindrome-number.py ├── NOTES.md └── README.md ├── 904-fruit-into-baskets ├── 904-fruit-into-baskets.py ├── NOTES.md └── README.md ├── 912-sort-an-array ├── 912-sort-an-array.py ├── NOTES.md └── README.md ├── 94-binary-tree-inorder-traversal ├── 94-binary-tree-inorder-traversal.py └── NOTES.md ├── 986-interval-list-intersections ├── 986-interval-list-intersections.py ├── NOTES.md └── README.md ├── CodeSignal2.py ├── DoublyLinkedList Insertion ├── Easy ├── BinarySearch ├── FirstBadVersion ├── Number of 1 Bits ├── RansomNote ├── SearchInsertPosition ├── SortArrayByParty └── TwoSum ├── Helpful.md ├── hard └── median-of-two-sorted-arrays.py ├── medium ├── Add Two Numbers ├── BinaryTree_Right_Side ├── Coin Change.py ├── Domino and Trimino └── Heap_HireK └── number-of-provinces ├── README.md └── number-of-provinces.py /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | 15 | -------------------------------------------------------------------------------- /1-lclighter-data-idlgt255811883-data-bundle-id0-stylebackground-image-linear-gradienttransparent-0-transparent-calc50-4px-rgb204-242-241-calc50-4px-rgb204-242-241-100-transition-background-position-120ms-ease-in-out-0s-padding-120ms-ease-in-out-0s-background-size-100-200-background-position-initial-user-select-auto-two-sum-lclighterdiv-classlinerthreadicon-linerfirst-lineroverlapse-data-highlight-id255811883-data-bundle-id0-idlgt255811883-stylebackground-image-url-and-quot-https-photogetlinercom-liner-service-bucket-user-photo-default-color-2-vsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-divdiv-classlinerthreadicon-linersecond-data-highlight-id257820954-data-bundle-id0-idlgt257820954-stylebackground-image-url-and-quot-https-photogetlinercom-liner-service-bucket-user-photo-default-color-5-gsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-div/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /100-same-tree/100-same-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: 9 | if not(p or q): #both should be None 10 | return True 11 | 12 | if not(p and q): #one of them are None 13 | return False 14 | 15 | if p.val != q.val: 16 | return False 17 | return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 18 | 19 | 20 | -------------------------------------------------------------------------------- /1004-max-consecutive-ones-iii/1004-max-consecutive-ones-iii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestOnes(self, s: List[int], k: int) -> int: 3 | longest, max_repeat, start = 0, 0, 0 4 | for end in range(len(s)): 5 | right = s[end] 6 | if right: 7 | max_repeat += 1 8 | 9 | if (end - start - max_repeat + 1) > k: 10 | if s[start]: 11 | max_repeat -= 1 12 | start += 1 13 | 14 | longest = max(longest, end - start + 1) 15 | return longest -------------------------------------------------------------------------------- /1004-max-consecutive-ones-iii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /101-symmetric-tree/101-symmetric-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def isSymmetric(self, root: Optional[TreeNode]) -> bool: 9 | def is_mirror(a, b): 10 | if not a and not b: 11 | return True 12 | if a and b and a.val == b.val: 13 | return is_mirror(a.left, b.right) and is_mirror(a.right, b.left) 14 | return not root or is_mirror(root.left, root.right) -------------------------------------------------------------------------------- /101-symmetric-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /102-binary-tree-level-order-traversal/102-binary-tree-level-order-traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: 9 | level = [root] 10 | res = [] 11 | while any(level): 12 | res.append([node.val for node in level]) 13 | new_level = [] 14 | for node in level: 15 | if node.left: 16 | new_level.append(node.left) 17 | if node.right: 18 | new_level.append(node.right) 19 | 20 | level = new_level 21 | return res 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /102-binary-tree-level-order-traversal/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /102-binary-tree-level-order-traversal/README.md: -------------------------------------------------------------------------------- 1 |

102. Binary Tree Level Order Traversal

Medium


Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: root = [3,9,20,null,null,15,7]
 7 | Output: [[3],[9,20],[15,7]]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: root = [1]
13 | Output: [[1]]
14 | 
15 | 16 |

Example 3:

17 | 18 |
Input: root = []
19 | Output: []
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 | 29 |
-------------------------------------------------------------------------------- /103-binary-tree-zigzag-level-order-traversal/103-binary-tree-zigzag-level-order-traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: 9 | result = [] 10 | if root is None: 11 | return result 12 | 13 | queue = deque() 14 | queue.append(root) 15 | flag = 1 16 | while queue: 17 | levelSize = len(queue) 18 | currentLevel = [] 19 | for _ in range(levelSize): 20 | currentNode = queue.popleft() 21 | # add the node to the current level 22 | currentLevel.append(currentNode.val) 23 | # insert the children of current node in the queue 24 | if currentNode.left: 25 | queue.append(currentNode.left) 26 | if currentNode.right: 27 | queue.append(currentNode.right) 28 | currentLevel = currentLevel[::flag] 29 | flag *= -1 30 | result.append(currentLevel) 31 | return result -------------------------------------------------------------------------------- /103-binary-tree-zigzag-level-order-traversal/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /103-binary-tree-zigzag-level-order-traversal/README.md: -------------------------------------------------------------------------------- 1 |

103. Binary Tree Zigzag Level Order Traversal

Medium


Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: root = [3,9,20,null,null,15,7]
 7 | Output: [[3],[20,9],[15,7]]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: root = [1]
13 | Output: [[1]]
14 | 
15 | 16 |

Example 3:

17 | 18 |
Input: root = []
19 | Output: []
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 | 29 |
-------------------------------------------------------------------------------- /107-binary-tree-level-order-traversal-ii/107-binary-tree-level-order-traversal-ii.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]: 9 | level = [root] 10 | res = [] 11 | while any(level): 12 | res.append([node.val for node in level]) 13 | new_level = [] 14 | for node in level: 15 | if node.left: 16 | new_level.append(node.left) 17 | if node.right: 18 | new_level.append(node.right) 19 | 20 | level = new_level 21 | result = res[::-1] 22 | return result -------------------------------------------------------------------------------- /107-binary-tree-level-order-traversal-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /107-binary-tree-level-order-traversal-ii/README.md: -------------------------------------------------------------------------------- 1 |

107. Binary Tree Level Order Traversal II

Medium


Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: root = [3,9,20,null,null,15,7]
 7 | Output: [[15,7],[9,20],[3]]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: root = [1]
13 | Output: [[1]]
14 | 
15 | 16 |

Example 3:

17 | 18 |
Input: root = []
19 | Output: []
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 | 29 |
-------------------------------------------------------------------------------- /108-convert-sorted-array-to-binary-search-tree/108-convert-sorted-array-to-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: 9 | def dfs(l, r): 10 | if l < 0 or r >= len(nums) or l > r or l >= len(nums): 11 | return None 12 | md = (l + r) // 2 13 | first = TreeNode(val = nums[md]) 14 | first.right = dfs(md + 1, r) 15 | first.left = dfs(l, md - 1) 16 | 17 | return first 18 | return dfs(0, len(nums) - 1) 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /108-convert-sorted-array-to-binary-search-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /111-minimum-depth-of-binary-tree/111-minimum-depth-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def minDepth(self, root: Optional[TreeNode]) -> int: 9 | if root is None: 10 | return 0 11 | depth = 0 12 | level = deque() 13 | level.append(root) 14 | while any(level): 15 | depth+=1 16 | len_list = len(level) 17 | for _ in range(len_list): 18 | node = level.popleft() 19 | if not node.left and not node.right: 20 | return depth 21 | if node.left: 22 | level.append(node.left) 23 | if node.right: 24 | level.append(node.right) 25 | 26 | -------------------------------------------------------------------------------- /111-minimum-depth-of-binary-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /111-minimum-depth-of-binary-tree/README.md: -------------------------------------------------------------------------------- 1 |

111. Minimum Depth of Binary Tree

Easy


Given a binary tree, find its minimum depth.

2 | 3 |

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

4 | 5 |

Note: A leaf is a node with no children.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
Input: root = [3,9,20,null,null,15,7]
11 | Output: 2
12 | 
13 | 14 |

Example 2:

15 | 16 |
Input: root = [2,null,3,null,4,null,5,null,6]
17 | Output: 5
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 | 27 |
-------------------------------------------------------------------------------- /112-path-sum/112-path-sum.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: 9 | q = [root] 10 | if not root: return False 11 | while q: 12 | node = q.pop(0) #return the first element 13 | if node.left == None and node.right == None: #leaves 14 | if node.val == targetSum: 15 | return True 16 | 17 | 18 | if node.left: 19 | node.left.val = node.val + node.left.val 20 | q.append(node.left) 21 | if node.right: 22 | node.right.val = node.val + node.right.val 23 | q.append(node.right) 24 | 25 | return False 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /112-path-sum/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /113-path-sum-ii/113-path-sum-ii.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | 9 | 10 | def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]: 11 | all_path = [] 12 | def recursive_sum(current, targetSum, currentPath, all_path): 13 | if not current : return 14 | currentPath.append(current.val) 15 | if current.val == targetSum and not current.right and not current.left: 16 | all_path.append(list(currentPath)) 17 | else: 18 | recursive_sum(current.left, targetSum - current.val, currentPath, all_path) 19 | recursive_sum(current.right, targetSum - current.val, currentPath, all_path) 20 | 21 | del currentPath[-1] 22 | 23 | recursive_sum(root, targetSum, [], all_path) 24 | return all_path 25 | 26 | -------------------------------------------------------------------------------- /113-path-sum-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /116-populating-next-right-pointers-in-each-node/116-populating-next-right-pointers-in-each-node.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | self.next = next 9 | """ 10 | 11 | class Solution: 12 | def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': 13 | if root is None: 14 | return 15 | if root.left and root.right: 16 | root.left.next = root.right 17 | if root.next: 18 | root.right.next = root.next.left 19 | else: 20 | root.right.next = None 21 | self.connect(root.left) 22 | self.connect(root.right) 23 | return root -------------------------------------------------------------------------------- /116-populating-next-right-pointers-in-each-node/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /117-populating-next-right-pointers-in-each-node-ii/117-populating-next-right-pointers-in-each-node-ii.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | self.next = next 9 | """ 10 | 11 | class Solution: 12 | def connect(self, root: 'Node') -> 'Node': 13 | if root is None: 14 | return 15 | 16 | queue = deque() 17 | queue.append(root) 18 | while queue: 19 | previousNode = None 20 | levelSize = len(queue) 21 | # connect all nodes of this level 22 | for _ in range(levelSize): 23 | currentNode = queue.popleft() 24 | if previousNode: 25 | previousNode.next = currentNode 26 | previousNode = currentNode 27 | 28 | # insert the children of current node in the queue 29 | if currentNode.left: 30 | queue.append(currentNode.left) 31 | if currentNode.right: 32 | queue.append(currentNode.right) 33 | return root -------------------------------------------------------------------------------- /117-populating-next-right-pointers-in-each-node-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | mn, mx = float('inf'), 0 4 | for i in range(len(prices)): 5 | mn = min(prices[i], mn) 6 | mx = max(mx, prices[i] - mn) 7 | return mx -------------------------------------------------------------------------------- /121-best-time-to-buy-and-sell-stock/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /122-best-time-to-buy-and-sell-stock-ii/122-best-time-to-buy-and-sell-stock-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | profit = 0 4 | for i in range(1, len(prices)): 5 | if prices[i] > prices[i-1]: 6 | profit += prices[i] - prices[i-1] 7 | return profit -------------------------------------------------------------------------------- /122-best-time-to-buy-and-sell-stock-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /124-binary-tree-maximum-path-sum/124-binary-tree-maximum-path-sum.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def maxPathSum(self, root: Optional[TreeNode]) -> int: 9 | res = [root.val] 10 | 11 | #return max path without spliting 12 | def dfs(node): 13 | if not node: return 0 14 | leftmax = dfs(node.left) 15 | rightmax = dfs(node.right) 16 | leftmax = max(leftmax, 0) 17 | rightmax = max(rightmax, 0) 18 | 19 | #comput max path with split 20 | res[0] = max(node.val + leftmax + rightmax, res[0]) 21 | return node.val + max(leftmax, rightmax) 22 | 23 | dfs(root) 24 | return res[0] 25 | 26 | -------------------------------------------------------------------------------- /124-binary-tree-maximum-path-sum/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /125-valid-palindrome/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /127-word-ladder/127-word-ladder.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int ladderLength(String beginWord, String endWord, List wordList) { 3 | if (wordList == null || beginWord == endWord) 4 | return 0; 5 | if (!wordList.contains(endWord)) 6 | return 0; 7 | 8 | wordList.add(beginWord); 9 | final int N = wordList.size(); 10 | 11 | int distance[] = new int[N]; 12 | 13 | bfs(N - 1, wordList, distance); 14 | 15 | for (int i = 0; i < N; i++) 16 | if (wordList.get(i).equals(endWord) && distance[i] != Integer.MAX_VALUE) 17 | return distance[i] + 1; 18 | 19 | return 0; 20 | } 21 | private void bfs(int startNode, List words, int distance[]) { 22 | final int INF = Integer.MAX_VALUE; 23 | Arrays.fill(distance, INF); 24 | 25 | Queue queue = new LinkedList<>(); 26 | distance[startNode] = 0; 27 | queue.add(startNode); 28 | 29 | while (!queue.isEmpty()) { 30 | int node = queue.poll(); 31 | 32 | for (int neighbour = 0; neighbour < words.size(); neighbour++) 33 | if (distance[neighbour] == INF && oneTransformationAway(words.get(node), words.get(neighbour))) { 34 | distance[neighbour] = distance[node] + 1; 35 | queue.add(neighbour); 36 | } 37 | } 38 | } 39 | private boolean oneTransformationAway(String source, String destination) { 40 | if (source == null || destination == null) 41 | return source == null && destination == null; 42 | if (source.length() != destination.length()) 43 | return false; 44 | 45 | int transformations = 0; 46 | for (int i = 0; i < source.length(); i++) 47 | if (source.charAt(i) != destination.charAt(i)) 48 | transformations++; 49 | 50 | return transformations == 1; 51 | } 52 | } -------------------------------------------------------------------------------- /127-word-ladder/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /1281-subtract-the-product-and-sum-of-digits-of-an-integer/1281-subtract-the-product-and-sum-of-digits-of-an-integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subtractProductAndSum(self, n: int) -> int: 3 | p = 1 4 | s = 0 5 | while n > 0: 6 | k = n % 10 7 | p *= k 8 | s += k 9 | n = n // 10 10 | return p - s 11 | 12 | -------------------------------------------------------------------------------- /1281-subtract-the-product-and-sum-of-digits-of-an-integer/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /129-sum-root-to-leaf-numbers/129-sum-root-to-leaf-numbers.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def recursive(self, current, pathSum): 9 | if not current: return 0 10 | pathSum = 10 * pathSum + current.val 11 | if not (current.left or current.right): 12 | return pathSum 13 | return self.recursive(current.left, pathSum) + self.recursive(current.right, pathSum) 14 | 15 | 16 | def sumNumbers(self, root: Optional[TreeNode]) -> int: 17 | return self.recursive(root, 0) 18 | 19 | 20 | -------------------------------------------------------------------------------- /1323-maximum-69-number/1323-maximum-69-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximum69Number (self, num: int) -> int: 3 | s = 0 4 | l = [int(x) for x in str(num)] 5 | for i in range(len(l)): 6 | if l[i] == 6: 7 | l[i] += 3 8 | break 9 | else: 10 | continue 11 | for k in range(len(l)): 12 | s += l[k] * 10**(len(l) - k - 1) 13 | 14 | return s 15 | 16 | -------------------------------------------------------------------------------- /1323-maximum-69-number/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /133-clone-graph/133-clone-graph.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val = 0, neighbors = None): 5 | self.val = val 6 | self.neighbors = neighbors if neighbors is not None else [] 7 | """ 8 | 9 | class Solution: 10 | def cloneGraph(self, node: 'Node') -> 'Node': 11 | d = {} 12 | def dfs(node): 13 | ''' 14 | return the clone graph 15 | ''' 16 | if node in d: 17 | return d[node] 18 | 19 | copy = Node(node.val) 20 | d[node] = copy 21 | for nei in node.neighbors: 22 | copy.neighbors.append(dfs(nei)) 23 | return copy 24 | 25 | return dfs(node) if node else None -------------------------------------------------------------------------------- /133-clone-graph/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /134-gas-station/134-gas-station.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 3 | remaining, prev_remianing, candidate = 0, 0, 0 4 | for i in range(len(gas)): 5 | remaining += gas[i] - cost[i] 6 | if remaining < 0: #negative 7 | candidate = i + 1 8 | prev_remianing += remaining 9 | remaining = 0 10 | if candidate == len(gas) or remaining + prev_remianing < 0: 11 | return -1 12 | return candidate 13 | -------------------------------------------------------------------------------- /134-gas-station/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /1342-number-of-steps-to-reduce-a-number-to-zero/1342-number-of-steps-to-reduce-a-number-to-zero.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfSteps(self, num: int) -> int: 3 | step = 0 4 | while num: 5 | if not num%2 : 6 | num /= 2 7 | else: 8 | num -= 1 9 | step += 1 10 | 11 | return step -------------------------------------------------------------------------------- /1342-number-of-steps-to-reduce-a-number-to-zero/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode: 10 | if cloned: 11 | if cloned.val == target.val: 12 | return cloned 13 | else: 14 | return self.getTargetCopy(original, cloned.right, target) or self.getTargetCopy(original, cloned.left, target) 15 | else: 16 | return -------------------------------------------------------------------------------- /1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /142-linked-list-cycle-ii/142-linked-list-cycle-ii.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 detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: 9 | d = {} 10 | if head is None: 11 | return None 12 | while head.next is not None: 13 | if head in d.keys(): 14 | return head 15 | d[head] = head.next 16 | head = head.next 17 | return None -------------------------------------------------------------------------------- /142-linked-list-cycle-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /143-reorder-list/143-reorder-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def reorderList(self, head: Optional[ListNode]) -> None: 8 | """ 9 | Do not return anything, modify head in-place instead. 10 | """ 11 | slow, fast = head, head.next 12 | while fast and fast.next: 13 | slow = slow.next 14 | fast = fast.next.next 15 | second = slow.next 16 | prev = slow.next = None 17 | #reverse 18 | while second: 19 | temp = second.next 20 | second.next = prev 21 | prev = second 22 | second = temp 23 | 24 | #merge the 2 half 25 | first, second = head, prev 26 | while second: 27 | temp1, temp2 = first.next, second.next 28 | first.next = second 29 | second.next = temp1 30 | first = temp1 31 | second = temp2 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /143-reorder-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /146-lru-cache/146-lru-cache.py: -------------------------------------------------------------------------------- 1 | class LRUCache: 2 | 3 | def __init__(self, capacity: int): 4 | self.capacity = capacity 5 | self.d = {} 6 | self.stack = [] 7 | def get(self, key: int) -> int: 8 | if key in self.d.keys(): 9 | #updating 10 | self.stack.remove(key) 11 | self.stack.append(key) 12 | return self.d[key] 13 | else: 14 | return -1 15 | def put(self, key: int, value: int) -> None: 16 | if key not in self.stack: 17 | if len(self.stack) == self.capacity: 18 | del self.d[self.stack[0]] 19 | self.stack.pop(0) 20 | self.stack.append(key) 21 | self.d[key] = value 22 | else: 23 | self.stack.append(key) 24 | self.d[key] = value 25 | else: 26 | self.d[key] = value 27 | self.stack.remove(key) 28 | self.stack.append(key) 29 | 30 | 31 | 32 | 33 | 34 | # Your LRUCache object will be instantiated and called as such: 35 | # obj = LRUCache(capacity) 36 | # param_1 = obj.get(key) 37 | # obj.put(key,value) -------------------------------------------------------------------------------- /148-sort-list/148-sort-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def getMid(self, head): 8 | s, f = head, head.next 9 | while f and f.next: 10 | s = s.next 11 | f = f.next.next 12 | return s 13 | 14 | def merge(self, list1, list2): 15 | d = ListNode() #new list 16 | tail = d #pointer of the new list 17 | while list1 and list2: 18 | if list1.val < list2.val: 19 | tail.next = list1 20 | list1 = list1.next 21 | else: 22 | tail.next = list2 23 | list2 = list2.next 24 | tail = tail.next 25 | if list1: 26 | tail.next = list1 27 | if list2: 28 | tail.next = list2 29 | 30 | return d.next 31 | 32 | def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: 33 | if not head or not head.next: 34 | return head 35 | #splitting into 2 heads 36 | l = head 37 | r = self.getMid(head) 38 | t = r.next 39 | r.next = None 40 | r = t 41 | 42 | l = self.sortList(l) 43 | r = self.sortList(r) 44 | 45 | #collecting 46 | return self.merge(l, r) 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /148-sort-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /1480-running-sum-of-1d-array/1480-running-sum-of-1d-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def runningSum(self, nums: List[int]) -> List[int]: 3 | for i in range(1, len(nums)): 4 | nums[i] += nums[i-1] 5 | return nums -------------------------------------------------------------------------------- /1480-running-sum-of-1d-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /1486-xor-operation-in-an-array/1486-xor-operation-in-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def xorOperation(self, n: int, start: int) -> int: 3 | x = 0 4 | for i in range(n): 5 | x ^= start + 2 *i 6 | 7 | return x 8 | -------------------------------------------------------------------------------- /1486-xor-operation-in-an-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /1486-xor-operation-in-an-array/README.md: -------------------------------------------------------------------------------- 1 |

1486. XOR Operation in an Array

Easy


You are given an integer n and an integer start.

2 | 3 |

Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length.

4 | 5 |

Return the bitwise XOR of all elements of nums.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
Input: n = 5, start = 0
11 | Output: 8
12 | Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
13 | Where "^" corresponds to bitwise XOR operator.
14 | 
15 | 16 |

Example 2:

17 | 18 |
Input: n = 4, start = 3
19 | Output: 8
20 | Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.
21 | 
22 | 23 |

 

24 |

Constraints:

25 | 26 |
    27 |
  • 1 <= n <= 1000
  • 28 |
  • 0 <= start <= 1000
  • 29 |
  • n == nums.length
  • 30 |
31 |
-------------------------------------------------------------------------------- /15-3sum/15-3sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search_pair(self, arr, target_sum, left, triplets): 3 | right = len(arr) - 1 4 | while(left < right): 5 | current_sum = arr[left] + arr[right] 6 | if current_sum == target_sum: # found the triplet 7 | triplets.append([-target_sum, arr[left], arr[right]]) 8 | left += 1 9 | right -= 1 10 | while left < right and arr[left] == arr[left - 1]: 11 | left += 1 # skip same element to avoid duplicate triplets 12 | while left < right and arr[right] == arr[right + 1]: 13 | right -= 1 # skip same element to avoid duplicate triplets 14 | elif target_sum > current_sum: 15 | left += 1 # we need a pair with a bigger sum 16 | else: 17 | right -= 1 # we need a pair with a smaller sum 18 | def threeSum(self, arr: List[int]) -> List[List[int]]: 19 | arr.sort() 20 | triplets = [] 21 | for i in range(len(arr)): 22 | if i > 0 and arr[i] == arr[i-1]: # skip same element to avoid duplicate triplets 23 | continue 24 | self.search_pair(arr, -arr[i], i+1, triplets) 25 | 26 | 27 | return triplets 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /15-3sum/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /1512-number-of-good-pairs/1512-number-of-good-pairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numIdenticalPairs(self, nums: List[int]) -> int: 3 | n = 0 4 | for i in range(len(nums)): 5 | for j in range(i+1, len(nums)): 6 | if nums[i] == nums[j]: n += 1 7 | return n -------------------------------------------------------------------------------- /1512-number-of-good-pairs/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /1528-shuffle-string/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /1534-count-good-triplets/1534-count-good-triplets.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int: 3 | count = 0 4 | def good(t1, t2, result): 5 | if abs(t1 - t2) <= result: 6 | return True 7 | return False 8 | 9 | for i in range(len(arr) - 2): 10 | for j in range(i + 1, len(arr) - 1): 11 | if good(arr[i], arr[j], a): 12 | for k in range(j + 1, len(arr)): 13 | if good(arr[j], arr[k], b) and good(arr[k], arr[i], c): 14 | count += 1 15 | 16 | return count 17 | -------------------------------------------------------------------------------- /1534-count-good-triplets/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /155-min-stack/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /1557-minimum-number-of-vertices-to-reach-all-nodes/1557-minimum-number-of-vertices-to-reach-all-nodes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: 3 | visited = [0]*n 4 | minm = [] 5 | for pair in edges: 6 | visited[pair[1]] = 1 7 | 8 | for i in range(n): 9 | if visited[i] == 0: 10 | minm.append(i) 11 | 12 | return minm 13 | """ 14 | 1. For loop and put the key and list 15 | 2. make a union between the 2 sets of each until reach the list == n 16 | 3. if the n reached then: return the list of the number of lists 17 | 4. It is more than 2 18 | """ 19 | 20 | -------------------------------------------------------------------------------- /1557-minimum-number-of-vertices-to-reach-all-nodes/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /16-3sum-closest/16-3sum-closest.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSumClosest(self, nums: List[int], target: int) -> int: 3 | best_s = 100000 4 | nums.sort() 5 | 6 | for i in range(len(nums)-2): 7 | left = i + 1 8 | right = len(nums) - 1 9 | 10 | while left < right: 11 | s = nums[i] + nums[left] + nums[right] 12 | if s == target: 13 | return s 14 | if abs(target - s) < abs(target - best_s): 15 | best_s = s 16 | if s <= target: 17 | left += 1 18 | while nums[left] == nums[left - 1] and left < right: 19 | left += 1 20 | else: 21 | right -= 1 22 | return best_s 23 | -------------------------------------------------------------------------------- /16-3sum-closest/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /160-intersection-of-two-linked-lists/160-intersection-of-two-linked-lists.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 sizeof(self, headA: ListNode): 9 | count = 0 10 | current = headA 11 | while current is not None: 12 | current = current.next 13 | count += 1 14 | return count 15 | 16 | def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: 17 | a = self.sizeof(headA) 18 | b = self.sizeof(headB) 19 | if a == b: 20 | while headA: 21 | if headA is headB: 22 | return headA 23 | headA = headA.next 24 | headB = headB.next 25 | 26 | if b > a: 27 | d = b - a 28 | for i in range(d): 29 | headB = headB.next 30 | else: 31 | d = a - b 32 | for i in range(d): 33 | headA = headA.next 34 | 35 | while headA and headB: 36 | if headA is headB: 37 | return headA 38 | headA = headA.next 39 | headB = headB.next 40 | return None 41 | 42 | -------------------------------------------------------------------------------- /162-find-peak-element/162-find-peak-element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findPeakElement(self, nums: List[int]) -> int: 3 | if len(nums) == 0: 4 | return -1 5 | if len(nums) == 1: 6 | return 0 7 | if nums[0] > nums[1]: 8 | return 0 9 | if nums[-1] > nums[-2]: 10 | return len(nums) - 1 11 | left = 0 12 | right = len(nums) - 1 13 | while left < right: 14 | mid = (left + right) // 2 15 | if nums[mid] > nums[mid + 1]: 16 | right = mid 17 | else: 18 | left = mid + 1 19 | return left -------------------------------------------------------------------------------- /162-find-peak-element/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /169-majority-element/169-majority-element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def majorityElement(self, nums: List[int]) -> int: 3 | n = len(nums)//2 4 | k = set(nums) 5 | for i in k: 6 | if nums.count(i) > n: 7 | return i 8 | -------------------------------------------------------------------------------- /169-majority-element/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /169-majority-element/README.md: -------------------------------------------------------------------------------- 1 |

169. Majority Element

Easy


Given an array nums of size n, return the majority element.

2 | 3 |

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

4 | 5 |

 

6 |

Example 1:

7 |
Input: nums = [3,2,3]
 8 | Output: 3
 9 | 

Example 2:

10 |
Input: nums = [2,2,1,1,1,2,2]
11 | Output: 2
12 | 
13 |

 

14 |

Constraints:

15 | 16 |
    17 |
  • n == nums.length
  • 18 |
  • 1 <= n <= 5 * 104
  • 19 |
  • -109 <= nums[i] <= 109
  • 20 |
21 | 22 |

 

23 | Follow-up: Could you solve the problem in linear time and in O(1) space?
-------------------------------------------------------------------------------- /17-letter-combinations-of-a-phone-number/17-letter-combinations-of-a-phone-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def letterCombinations(self, digits: str) -> List[str]: 3 | 4 | D = { 5 | "2": "abc", 6 | "3": "def", 7 | "4": "ghi", 8 | "5": "jkl", 9 | "6": "mno", 10 | "7": "pqrs", 11 | "8": "tuv", 12 | "9": "wxyz" 13 | } 14 | 15 | if len(digits) == 0: 16 | return [] 17 | 18 | def backtrack(index,path): 19 | 20 | if len(path) == len(digits): 21 | ret.append("".join(path)) 22 | return 23 | 24 | 25 | 26 | letters = D[digits[index]] 27 | for letter in letters: 28 | 29 | path.append(letter) 30 | 31 | backtrack(index+1,path) # returns once a path is fully formed 32 | 33 | path.pop() # we remove last letter since it should be replace by new letter in for loop 34 | 35 | ret = [] 36 | path = [] 37 | backtrack(0, path) 38 | return ret 39 | -------------------------------------------------------------------------------- /17-letter-combinations-of-a-phone-number/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /171-excel-sheet-column-number/171-excel-sheet-column-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def titleToNumber(self, columnTitle: str) -> int: 3 | n = len(columnTitle) 4 | sm, pos = 0, 0 5 | for i in reversed(columnTitle): 6 | x = ord(i) - 64 7 | sm += x * 26**pos 8 | pos+=1 9 | 10 | return sm -------------------------------------------------------------------------------- /171-excel-sheet-column-number/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /1780-check-if-number-is-a-sum-of-powers-of-three/1780-check-if-number-is-a-sum-of-powers-of-three.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkPowersOfThree(self, n: int) -> bool: 3 | if n % 3 == 2: 4 | return False 5 | elif n > 3: 6 | n = n // 3 7 | return self.checkPowersOfThree(n) 8 | else: 9 | return True 10 | -------------------------------------------------------------------------------- /1780-check-if-number-is-a-sum-of-powers-of-three/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /18-4sum/18-4sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fourSum(self, nums: List[int], target: int) -> List[List[int]]: 3 | nums.sort() 4 | res, quad = [], [] 5 | 6 | def ksum(k, start, target): 7 | if k != 2: 8 | for i in range(start, len(nums)-k+1): 9 | if i > start and nums[i] == nums[i-1]: 10 | continue 11 | quad.append(nums[i]) 12 | ksum(k-1, i+1, target - nums[i]) 13 | quad.pop() 14 | return 15 | l, r = start, len(nums)-1 16 | while l < r: 17 | if nums[l] + nums[r] < target: 18 | l += 1 19 | elif nums[l] + nums[r] > target: 20 | r -= 1 21 | else: 22 | res.append(quad + [nums[l], nums[r]]) 23 | l += 1 24 | while l < r and nums[l] == nums[l-1]: 25 | l+=1 26 | ksum(4, 0, target) 27 | return res -------------------------------------------------------------------------------- /18-4sum/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /1812-determine-color-of-a-chessboard-square/1812-determine-color-of-a-chessboard-square.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def squareIsWhite(self, coordinates: str) -> bool: 3 | w_even = ['a', 'c', 'e', 'g'] 4 | 5 | if coordinates[0] in w_even: 6 | if int(coordinates[1]) %2 == 0:#even 7 | return True 8 | else: 9 | return False 10 | else: 11 | if int(coordinates[1]) %2 == 0:#even 12 | return False 13 | else: 14 | return True -------------------------------------------------------------------------------- /1812-determine-color-of-a-chessboard-square/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /189-rotate-array/189-rotate-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, nums: List[int], k: int) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | n = len(nums) 7 | k = k%n 8 | right = nums[:n - k] 9 | left = nums[n - k:] 10 | l = left + right 11 | for i in range(len(nums)): 12 | nums[i] = l[i] 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /189-rotate-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /19-remove-nth-node-from-end-of-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /199-binary-tree-right-side-view/199-binary-tree-right-side-view.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def rightSideView(self, root: Optional[TreeNode]) -> List[int]: 9 | result = [] 10 | if root is None: 11 | return 12 | 13 | queue = deque() 14 | queue.append(root) 15 | while queue: 16 | levelSize = len(queue) 17 | count = 0 18 | # connect all nodes of this level 19 | for _ in range(levelSize): 20 | currentNode = queue.popleft() 21 | count += 1 22 | if count == levelSize: 23 | result.append(currentNode.val) 24 | 25 | # insert the children of current node in the queue 26 | if currentNode.left: 27 | queue.append(currentNode.left) 28 | if currentNode.right: 29 | queue.append(currentNode.right) 30 | return result -------------------------------------------------------------------------------- /199-binary-tree-right-side-view/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /199-binary-tree-right-side-view/README.md: -------------------------------------------------------------------------------- 1 |

199. Binary Tree Right Side View

Medium


Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: root = [1,2,3,null,5,null,4]
 7 | Output: [1,3,4]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: root = [1,null,3]
13 | Output: [1,3]
14 | 
15 | 16 |

Example 3:

17 | 18 |
Input: root = []
19 | Output: []
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • The number of nodes in the tree is in the range [0, 100].
  • 27 |
  • -100 <= Node.val <= 100
  • 28 |
29 |
-------------------------------------------------------------------------------- /2-add-two-numbers/2-add-two-numbers.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | 7 | class Solution: 8 | def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: 9 | a1 = "" 10 | a2 = "" 11 | while l1.next != None: 12 | a1 += str(l1.val) 13 | l1 = l1.next 14 | while l2.next != None: 15 | a2 += str(l2.val) 16 | l2 = l2.next 17 | a1 += str(l1.val) 18 | a2 += str(l2.val) 19 | a1 = a1[::-1] 20 | a2 = a2[::-1] 21 | a3 = int(a1) + int(a2) 22 | a3 = list(str(a3)) 23 | x = ListNode() 24 | for i in range(0,len(a3)): 25 | if i == len(a3)-1: 26 | x.val = a3[i] 27 | else: 28 | temp = ListNode() 29 | temp.val = a3[i] 30 | temp.next = x.next 31 | x.next = temp 32 | return x 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /2-add-two-numbers/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /20-valid-parentheses/20-valid-parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s: str) -> bool: 3 | stack = [] 4 | d = { 5 | ")":"(", 6 | "]":"[", 7 | "}":"{" 8 | } 9 | 10 | for c in s: 11 | if c in d.values(): 12 | stack.append(c) 13 | elif c in d.keys(): 14 | if stack == [] or d[c] != stack.pop(): 15 | return False 16 | return stack == [] 17 | -------------------------------------------------------------------------------- /20-valid-parentheses/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /200-number-of-islands/200-number-of-islands.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numIslands(self, grid: List[List[str]]) -> int: 3 | def dfs(i, j): 4 | visited.add((i, j)) #set of tuples 5 | #make for the same row 6 | if j+1 < m and (i, j+1) not in visited and grid[i][j+1] == '1': 7 | dfs(i, j+1) 8 | if i+1 < n and (i+1, j) not in visited and grid[i+1][j] == '1': 9 | dfs(i+1, j) 10 | if j > 0 and (i, j-1) not in visited and grid[i][j-1] == '1': 11 | dfs(i, j-1) 12 | if i > 0 and (i-1, j) not in visited and grid[i-1][j] == '1': 13 | dfs(i-1, j) 14 | 15 | 16 | #main function 17 | n = len(grid) #rows 18 | m = len(grid[0]) #cols 19 | visited = set() 20 | NoIsland = 0 21 | for i in range(n): 22 | for j in range(m): 23 | #starting land 24 | if grid[i][j] == '1' and (i, j) not in visited: 25 | NoIsland += 1 26 | visited.add((i, j)) 27 | dfs(i, j) 28 | 29 | 30 | return NoIsland 31 | 32 | 33 | ''' 34 | Pesudo 35 | NoIslands = 0 36 | visited = set() #set of tuples 37 | for i in range(rows): 38 | for j in range(col): 39 | #starting land 40 | if g[i][j] == 1 and noted not in visited: 41 | NoIslands+= 1 42 | visited.add(g[i][j]) 43 | #traversing the right and bottom 44 | while g[i][j]: 45 | if g[i][j+1] == 1: visited.add(g[i][j+1]) 46 | if g[i+1][j] == 1: visited.add(g[i+1][j]) 47 | 48 | 49 | ''' -------------------------------------------------------------------------------- /200-number-of-islands/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /2011-final-value-of-variable-after-performing-operations/2011-final-value-of-variable-after-performing-operations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def finalValueAfterOperations(self, operations: List[str]) -> int: 3 | x = 0 4 | for operat in operations: 5 | if operat[0] == '-' or operat[-1] == '-': 6 | x -= 1 7 | else: 8 | x += 1 9 | return x -------------------------------------------------------------------------------- /2011-final-value-of-variable-after-performing-operations/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /202-happy-number/202-happy-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumOfSquares(self, n): 3 | output= 0 4 | while n: 5 | digit = n % 10 6 | digit = digit**2 7 | 8 | output += digit 9 | n = n // 10 10 | return output 11 | def isHappy(self, n: int) -> bool: 12 | visit = set() 13 | while n not in visit: 14 | visit.add(n) 15 | n = self.sumOfSquares(n) 16 | if n == 1: 17 | return True 18 | return False 19 | -------------------------------------------------------------------------------- /202-happy-number/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /203-remove-linked-list-elements/203-remove-linked-list-elements.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: 8 | dummy = ListNode(next = head) #creating a dummy node at the begin 9 | prev = dummy 10 | current = head 11 | while current: 12 | nxt = current.next 13 | if current.val == val: 14 | prev.next = nxt 15 | else: 16 | prev = current 17 | current = nxt 18 | 19 | return dummy.next 20 | 21 | -------------------------------------------------------------------------------- /203-remove-linked-list-elements/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /203-remove-linked-list-elements/README.md: -------------------------------------------------------------------------------- 1 |

203. Remove Linked List Elements

Easy


Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: head = [1,2,6,3,4,5,6], val = 6
 7 | Output: [1,2,3,4,5]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: head = [], val = 1
13 | Output: []
14 | 
15 | 16 |

Example 3:

17 | 18 |
Input: head = [7,7,7,7], val = 7
19 | Output: []
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • The number of nodes in the list is in the range [0, 104].
  • 27 |
  • 1 <= Node.val <= 50
  • 28 |
  • 0 <= val <= 50
  • 29 |
30 |
-------------------------------------------------------------------------------- /205-isomorphic-strings/205-isomorphic-strings.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string} t 4 | * @return {boolean} 5 | */ 6 | var isIsomorphic = function(s, t) { 7 | let arr1 = {} 8 | let arr2 = {} 9 | for (let i=0;i bool: 3 | arr1 = {} 4 | arr2 = {} 5 | if len(set(s)) != len(set(t)): 6 | return False 7 | for i in range(len(s)): 8 | if s[i] in arr1 and t[i] in arr2: 9 | if arr1[s[i]] != arr2[t[i]]: 10 | return False 11 | 12 | arr1[s[i]] = i 13 | arr2[t[i]] = i 14 | return True 15 | -------------------------------------------------------------------------------- /2059-minimum-operations-to-convert-number/2059-minimum-operations-to-convert-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: 3 | q = collections.deque([(start, 0)]) 4 | visited = {start} #it is a set contains start 5 | 6 | while q: 7 | x, c = q.popleft() 8 | c += 1 9 | for num in nums: 10 | for newx in (x+num, x-num, x^num): 11 | if newx == goal: return c 12 | if newx < 0 or 1000 < newx or newx in visited: 13 | continue 14 | visited.add(newx) 15 | q.append((newx, c)) 16 | return -1 -------------------------------------------------------------------------------- /2059-minimum-operations-to-convert-number/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /206-reverse-linked-list/206-reverse-linked-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | prev = None 9 | current = head 10 | while (current is not None): 11 | next = current.next 12 | current.next = prev 13 | prev = current 14 | current = next 15 | return prev -------------------------------------------------------------------------------- /206-reverse-linked-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /207-course-schedule/207-course-schedule.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: 3 | premap = {i: [] for i in range(numCourses)} 4 | #fill it 5 | for crs, pre in prerequisites: 6 | premap[crs].append(pre) 7 | visit = set() 8 | #dfs 9 | def dfs(crs): 10 | #2 base cases 11 | if crs in visit: return False 12 | if premap[crs] == []: return True 13 | visit.add(crs) 14 | 15 | for pre in premap[crs]: 16 | if not dfs(pre): return False 17 | 18 | visit.remove(crs) #already visited 19 | premap[crs] = [] 20 | return True 21 | 22 | #main function 23 | for crs in range(numCourses): 24 | if not dfs(crs): return False 25 | return True 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /207-course-schedule/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /208-implement-trie-prefix-tree/208-implement-trie-prefix-tree.py: -------------------------------------------------------------------------------- 1 | class TrieNode: 2 | def __init__(self): 3 | self.childern = {} 4 | self.endOfWord = False 5 | 6 | class Trie: 7 | def __init__(self): 8 | self.root = TrieNode() 9 | 10 | 11 | def insert(self, word: str) -> None: 12 | cur = self.root 13 | for c in word: 14 | if c not in cur.childern: 15 | cur.childern[c] = TrieNode() 16 | cur = cur.childern[c] 17 | cur.endOfWord = True 18 | 19 | def search(self, word: str) -> bool: 20 | cur = self.root 21 | for c in word: 22 | if c not in cur.childern: 23 | return False 24 | cur = cur.childern[c] 25 | return cur.endOfWord 26 | 27 | def startsWith(self, prefix: str) -> bool: 28 | cur = self.root 29 | for c in prefix: 30 | if c not in cur.childern: 31 | return False 32 | cur = cur.childern[c] 33 | return True 34 | 35 | # Your Trie object will be instantiated and called as such: 36 | # obj = Trie() 37 | # obj.insert(word) 38 | # param_2 = obj.search(word) 39 | # param_3 = obj.startsWith(prefix) -------------------------------------------------------------------------------- /208-implement-trie-prefix-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /2089-find-target-indices-after-sorting-array/2089-find-target-indices-after-sorting-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def targetIndices(self, nums: List[int], target: int) -> List[int]: 3 | nums = sorted(nums) 4 | l = [] 5 | i = 0 6 | while i < len(nums): 7 | if nums[i] == target: 8 | l.append(i) 9 | i += 1 10 | return l -------------------------------------------------------------------------------- /2089-find-target-indices-after-sorting-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /209-minimum-size-subarray-sum/209-minimum-size-subarray-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSubArrayLen(self, target: int, nums: List[int]) -> int: 3 | k = math.inf 4 | arrsum, arrstart = 0, 0 5 | for arrend in range(len(nums)): 6 | arrsum += nums[arrend] 7 | while arrsum >= target: 8 | k = min(k, arrend-arrstart+1) 9 | arrsum -= nums[arrstart] 10 | arrstart+=1 11 | return k if k != math.inf else 0 12 | -------------------------------------------------------------------------------- /209-minimum-size-subarray-sum/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /21-merge-two-sorted-lists/21-merge-two-sorted-lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: 8 | d = ListNode() 9 | tail = d 10 | while list1 and list2: 11 | if list1.val < list2.val: 12 | tail.next = list1 #it is a node itself 13 | list1 = list1.next 14 | else: 15 | tail.next = list2 16 | list2 = list2.next 17 | tail = tail.next 18 | if list1: 19 | tail.next = list1 20 | if list2: 21 | tail.next = list2 22 | 23 | return d.next -------------------------------------------------------------------------------- /21-merge-two-sorted-lists/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /210-course-schedule-ii/210-course-schedule-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: 3 | premap = {i: [] for i in range(numCourses)} 4 | rl = [] 5 | #fill it 6 | for crs, pre in prerequisites: #all of this are pairs 7 | premap[crs].append(pre) 8 | 9 | visit = set() 10 | #dfs 11 | def dfs(crs): 12 | #2 base cases 13 | if crs in visit: return [] 14 | if premap[crs] == []: 15 | rl.append(crs) 16 | return rl 17 | visit.add(crs) 18 | 19 | for pre in premap[crs]: 20 | if not dfs(pre): return [] 21 | 22 | visit.remove(crs) #already visited 23 | premap[crs] = [] 24 | rl.append(crs) 25 | 26 | return rl 27 | 28 | #main function 29 | for crs in range(numCourses): 30 | if not dfs(crs): return [] 31 | rl = list(dict.fromkeys(rl)) 32 | 33 | return rl -------------------------------------------------------------------------------- /210-course-schedule-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /215-kth-largest-element-in-an-array/215-kth-largest-element-in-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findKthLargest(self, nums: List[int], k: int) -> int: 3 | for i in range(k - 1): 4 | mx = max(nums) 5 | nums.remove(mx) 6 | 7 | return max(nums) -------------------------------------------------------------------------------- /215-kth-largest-element-in-an-array/README.md: -------------------------------------------------------------------------------- 1 |

215. Kth Largest Element in an Array

Medium


Given an integer array nums and an integer k, return the kth largest element in the array.

2 | 3 |

Note that it is the kth largest element in the sorted order, not the kth distinct element.

4 | 5 |

 

6 |

Example 1:

7 |
Input: nums = [3,2,1,5,6,4], k = 2
 8 | Output: 5
 9 | 

Example 2:

10 |
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
11 | Output: 4
12 | 
13 |

 

14 |

Constraints:

15 | 16 |
    17 |
  • 1 <= k <= nums.length <= 104
  • 18 |
  • -104 <= nums[i] <= 104
  • 19 |
20 |
-------------------------------------------------------------------------------- /217-contains-duplicate/217-contains-duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | d = {} 4 | for n in nums: 5 | if n in d.keys(): 6 | return True 7 | else: 8 | d[n] = 1 9 | return False 10 | -------------------------------------------------------------------------------- /217-contains-duplicate/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /219-contains-duplicate-ii/219-contains-duplicate-ii.py: -------------------------------------------------------------------------------- 1 | from sortedcontainers import SortedList 2 | class Solution: 3 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 4 | s = SortedList() 5 | for i, n in enumerate(nums): 6 | if i>k: s.remove(nums[i-k-1]) 7 | pos1 = bisect_left(s, n) 8 | pos2 = bisect_right(s, n) 9 | if pos1 != pos2: return True 10 | s.add(n) 11 | return False 12 | -------------------------------------------------------------------------------- /219-contains-duplicate-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /220-contains-duplicate-iii/220-contains-duplicate-iii.py: -------------------------------------------------------------------------------- 1 | from sortedcontainers import SortedList 2 | class Solution: 3 | def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: 4 | if k<0 or t<0: 5 | return False 6 | s = SortedList() 7 | for i, n in enumerate(nums): 8 | if i > k: s.remove(nums[i-k-1]) 9 | pos1 = bisect_left(s,n - t) 10 | pos2 = bisect_right(s, n + t) 11 | if pos1 != pos2: return True 12 | s.add(n) 13 | return False 14 | -------------------------------------------------------------------------------- /220-contains-duplicate-iii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /222-count-complete-tree-nodes/222-count-complete-tree-nodes.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def countNodes(self, root: Optional[TreeNode]) -> int: 9 | 10 | if root is None: 11 | return 0 12 | return 1 + self.countNodes(root.left) + self.countNodes(root.right) 13 | -------------------------------------------------------------------------------- /2235-add-two-integers/2235-add-two-integers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sum(self, num1: int, num2: int) -> int: 3 | return num1 + num2 -------------------------------------------------------------------------------- /2235-add-two-integers/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /2235-add-two-integers/README.md: -------------------------------------------------------------------------------- 1 |

2235. Add Two Integers

Easy


Given two integers num1 and num2, return the sum of the two integers. 2 |

 

3 |

Example 1:

4 | 5 |
Input: num1 = 12, num2 = 5
 6 | Output: 17
 7 | Explanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: num1 = -10, num2 = 4
13 | Output: -6
14 | Explanation: num1 + num2 = -6, so -6 is returned.
15 | 
16 | 17 |

 

18 |

Constraints:

19 | 20 |
    21 |
  • -100 <= num1, num2 <= 100
  • 22 |
23 |
-------------------------------------------------------------------------------- /2236-root-equals-sum-of-children/2236-root-equals-sum-of-children.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool checkTree(TreeNode* root) { 15 | return root->val == (root->left->val + root->right->val); 16 | } 17 | }; -------------------------------------------------------------------------------- /2236-root-equals-sum-of-children/2236-root-equals-sum-of-children.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def checkTree(self, root: Optional[TreeNode]) -> bool: 9 | l = root.left 10 | r = root.right 11 | if root.val == l.val + r.val: 12 | return True 13 | else: 14 | return False -------------------------------------------------------------------------------- /2236-root-equals-sum-of-children/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /229-majority-element-ii/229-majority-element-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def majorityElement(self, nums: List[int]) -> List[int]: 3 | l = [] 4 | n = len(nums) // 3 5 | k = set(nums) 6 | for i in k: 7 | if nums.count(i) > n: 8 | l.append(i) 9 | 10 | return l 11 | -------------------------------------------------------------------------------- /23-merge-k-sorted-lists/23-merge-k-sorted-lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: 8 | if not lists or len(lists) == 0: 9 | return None 10 | 11 | while len(lists) > 1: 12 | merged = [] 13 | for i in range(0, len(lists), 2): 14 | l1 = lists[i] 15 | l2 = lists[i + 1] if (i+1) < len(lists) else None 16 | merged.append(self.mergelist(l1, l2)) 17 | lists = merged 18 | return lists[0] 19 | 20 | def mergelist(self, list1, list2): 21 | d = ListNode() #new list 22 | tail = d #pointer of the new list 23 | while list1 and list2: 24 | if list1.val < list2.val: 25 | tail.next = list1 26 | list1 = list1.next 27 | else: 28 | tail.next = list2 29 | list2 = list2.next 30 | tail = tail.next 31 | if list1: 32 | tail.next = list1 33 | if list2: 34 | tail.next = list2 35 | 36 | return d.next -------------------------------------------------------------------------------- /23-merge-k-sorted-lists/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /231-power-of-two/231-power-of-two.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfTwo(self, n: int) -> bool: 3 | #Negative 4 | if n < 0: 5 | return False 6 | #Base Case 7 | if n == 1 or n ==2: 8 | return True 9 | #Recursive 10 | elif n > 2: 11 | n = n / 2 12 | return self.isPowerOfTwo(n) 13 | else: 14 | return False 15 | 16 | #Complixity = lg(n) 17 | #Space = lg(n) 18 | 19 | 20 | -------------------------------------------------------------------------------- /231-power-of-two/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /234-palindrome-linked-list/234-palindrome-linked-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def size(self, head): 8 | count = 0 9 | current_node = head 10 | while(current_node != None): 11 | count += 1 12 | current_node = current_node.next 13 | return count 14 | 15 | def isPalindrome(self, head: Optional[ListNode]) -> bool: 16 | n = self.size(head) 17 | md = n // 2 18 | c = 0 19 | stack = [] 20 | current = head 21 | if n == 1: 22 | return True 23 | if n == 2: 24 | if current.val != current.next.val: 25 | return False 26 | else: 27 | return True 28 | 29 | while c < md and current: 30 | stack.append(current.val) 31 | current = current.next 32 | c += 1 33 | if current and n % 2 != 0: #odd 34 | current = current.next 35 | 36 | while current: 37 | p = stack.pop() 38 | if p != current.val: 39 | return False 40 | current = current.next 41 | return True 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /234-palindrome-linked-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /234-palindrome-linked-list/README.md: -------------------------------------------------------------------------------- 1 |

234. Palindrome Linked List

Easy


Given the head of a singly linked list, return true if it is a palindrome.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: head = [1,2,2,1]
 7 | Output: true
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: head = [1,2]
13 | Output: false
14 | 
15 | 16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • The number of nodes in the list is in the range [1, 105].
  • 21 |
  • 0 <= Node.val <= 9
  • 22 |
23 | 24 |

 

25 | Follow up: Could you do it in O(n) time and O(1) space?
-------------------------------------------------------------------------------- /237-delete-node-in-a-linked-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /240-search-a-2d-matrix-ii/240-search-a-2d-matrix-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: 3 | m = len(matrix[0]) #cols 4 | for i in range(len(matrix)): #rows 5 | if target == matrix[i][0] or target == matrix[i][m-1]: 6 | return True 7 | elif target < matrix[i][m-1]: 8 | if target > matrix[i][0]: 9 | for j in range(m): 10 | if target == matrix[i][j]: 11 | return True 12 | return False -------------------------------------------------------------------------------- /240-search-a-2d-matrix-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /242-valid-anagram/242-valid-anagram.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAnagram(self, s: str, t: str) -> bool: 3 | if len(s) != len(t): 4 | return False 5 | s = sorted(s) 6 | t = sorted(t) 7 | if s == t: 8 | return True 9 | return False 10 | -------------------------------------------------------------------------------- /257-binary-tree-paths/257-binary-tree-paths.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: 9 | all_path = [] 10 | def recursive_sum(current, currentPath, all_path): 11 | if not current : return 12 | currentPath = currentPath + str(current.val) 13 | if not current.right and not current.left: 14 | all_path.append(currentPath) 15 | else: 16 | recursive_sum(current.left, currentPath + "->", all_path) 17 | recursive_sum(current.right, currentPath + "->", all_path) 18 | 19 | 20 | 21 | recursive_sum(root,"", all_path) 22 | return all_path -------------------------------------------------------------------------------- /257-binary-tree-paths/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /257-binary-tree-paths/README.md: -------------------------------------------------------------------------------- 1 |

257. Binary Tree Paths

Easy


Given the root of a binary tree, return all root-to-leaf paths in any order.

2 | 3 |

A leaf is a node with no children.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: root = [1,2,3,null,5]
 9 | Output: ["1->2->5","1->3"]
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: root = [1]
15 | Output: ["1"]
16 | 
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • The number of nodes in the tree is in the range [1, 100].
  • 23 |
  • -100 <= Node.val <= 100
  • 24 |
25 |
-------------------------------------------------------------------------------- /26-remove-duplicates-from-sorted-array/26-remove-duplicates-from-sorted-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums: List[int]) -> int: 3 | f = max(nums) + 1 4 | n = len(nums) 5 | for i in range(len(nums) - 1): 6 | if nums[i] == nums[i+1]: 7 | nums[i] = f 8 | n -= 1 9 | nums.sort() 10 | nums = nums[:n] 11 | 12 | return n -------------------------------------------------------------------------------- /27-remove-element/27-remove-element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeElement(self, nums: List[int], val: int) -> int: 3 | c = nums.count(val) 4 | for i in range(c): 5 | nums.remove(val) 6 | 7 | -------------------------------------------------------------------------------- /27-remove-element/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /275-h-index-ii/275-h-index-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hIndex(self, citations: List[int]) -> int: 3 | n = len(citations) 4 | l = 0 5 | r = n - 1 6 | 7 | while l <= r: 8 | mid = (l + r) // 2 9 | if (n - mid) <= citations[mid]: 10 | r = mid - 1 11 | else: 12 | l = mid + 1 13 | return n - l 14 | -------------------------------------------------------------------------------- /275-h-index-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /278-first-bad-version/278-first-bad-version.py: -------------------------------------------------------------------------------- 1 | # The isBadVersion API is already defined for you. 2 | # def isBadVersion(version: int) -> bool: 3 | 4 | class Solution: 5 | def firstBadVersion(self, n: int) -> int: 6 | high = n + 1 7 | low = 1 8 | while low <= high: 9 | mid = (low + high) // 2 10 | if isBadVersion(mid): 11 | high = mid - 1 12 | else: 13 | low = mid + 1 14 | mid = low 15 | return mid 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /278-first-bad-version/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /28-implement-strstr/28-implement-strstr.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def strStr(self, haystack: str, needle: str) -> int: 3 | n = len(needle) 4 | for i in range(0, len(haystack) - n + 1): 5 | if needle == haystack[i:i+n]: 6 | return i 7 | return -1 8 | -------------------------------------------------------------------------------- /28-implement-strstr/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /283-move-zeroes/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /283-move-zeroes/README.md: -------------------------------------------------------------------------------- 1 |

283. Move Zeroes

Easy


Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

2 | 3 |

Note that you must do this in-place without making a copy of the array.

4 | 5 |

 

6 |

Example 1:

7 |
Input: nums = [0,1,0,3,12]
 8 | Output: [1,3,12,0,0]
 9 | 

Example 2:

10 |
Input: nums = [0]
11 | Output: [0]
12 | 
13 |

 

14 |

Constraints:

15 | 16 |
    17 |
  • 1 <= nums.length <= 104
  • 18 |
  • -231 <= nums[i] <= 231 - 1
  • 19 |
20 | 21 |

 

22 | Follow up: Could you minimize the total number of operations done?
-------------------------------------------------------------------------------- /287-find-the-duplicate-number/287-find-the-duplicate-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicate(self, nums: List[int]) -> int: 3 | nums = sorted(nums) 4 | for i in range(len(nums)-1): 5 | if nums[i] == nums[i+1]: 6 | return nums[i] -------------------------------------------------------------------------------- /287-find-the-duplicate-number/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /295-find-median-from-data-stream/295-find-median-from-data-stream.java: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | 3 | private PriorityQueue firstHalf; 4 | private PriorityQueue secondHalf; 5 | 6 | public MedianFinder() { 7 | firstHalf = new PriorityQueue((a, b) -> b - a); 8 | secondHalf = new PriorityQueue(); 9 | } 10 | 11 | public void addNum(int num) { 12 | if (firstHalf.size() == 0 || num <= firstHalf.peek()) { 13 | firstHalf.add(num); 14 | if (firstHalf.size() > secondHalf.size() + 1) 15 | secondHalf.add(firstHalf.poll()); 16 | } else { 17 | secondHalf.add(num); 18 | if (secondHalf.size() > firstHalf.size()) 19 | firstHalf.add(secondHalf.poll()); 20 | } 21 | } 22 | 23 | public double findMedian() { 24 | if (firstHalf.size() > secondHalf.size()) { 25 | return 1.0 * firstHalf.peek(); 26 | } else { 27 | double sum = firstHalf.peek() + secondHalf.peek(); 28 | return sum / 2; 29 | } 30 | } 31 | } 32 | 33 | /** 34 | * Your MedianFinder object will be instantiated and called as such: 35 | * MedianFinder obj = new MedianFinder(); 36 | * obj.addNum(num); 37 | * double param_2 = obj.findMedian(); 38 | */ -------------------------------------------------------------------------------- /295-find-median-from-data-stream/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /3-longest-substring-without-repeating-characters/3-longest-substring-without-repeating-characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, str1: str) -> int: 3 | d = {} 4 | startwindow = 0 5 | longest = 0 6 | 7 | for i in range(len(str1)): 8 | right = str1[i] 9 | if right in d: 10 | startwindow = max(startwindow, d[right] + 1) 11 | d[right] = i 12 | longest = max(longest, i - startwindow + 1) 13 | 14 | return longest 15 | -------------------------------------------------------------------------------- /3-longest-substring-without-repeating-characters/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /30-substring-with-concatenation-of-all-words/30-substring-with-concatenation-of-all-words.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findSubstring(self, s: str, words: List[str]) -> List[int]: 3 | if len(words) == 0 or len(words[0]) == 0: 4 | return [] 5 | result = [] 6 | word_freq = {} 7 | for w in words: 8 | if w not in word_freq: 9 | word_freq[w] = 0 10 | word_freq[w] += 1 11 | count = len(words) 12 | length = len(words[0]) 13 | for i in range((len(s) - count * length)+1): 14 | seen = {} 15 | for j in range(count): 16 | next_index = i + j * length 17 | word = s[next_index: next_index + length] 18 | 19 | if word not in word_freq: break 20 | if word not in seen: 21 | seen[word] = 0 22 | seen[word] += 1 23 | if seen[word] > word_freq.get(word, 0): break 24 | if j+1 == count: result.append(i) 25 | 26 | 27 | return result -------------------------------------------------------------------------------- /30-substring-with-concatenation-of-all-words/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /303-range-sum-query-immutable/303-range-sum-query-immutable.py: -------------------------------------------------------------------------------- 1 | class NumArray: 2 | 3 | def __init__(self, nums: List[int]): 4 | self.nums = nums 5 | 6 | def sumRange(self, left: int, right: int) -> int: 7 | i = left 8 | n = right 9 | summ = 0 10 | while i <= n: 11 | summ += self.nums[i] 12 | i+= 1 13 | return summ 14 | 15 | 16 | # Your NumArray object will be instantiated and called as such: 17 | # obj = NumArray(nums) 18 | # param_1 = obj.sumRange(left,right) -------------------------------------------------------------------------------- /303-range-sum-query-immutable/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /304-range-sum-query-2d-immutable/304-range-sum-query-2d-immutable.py: -------------------------------------------------------------------------------- 1 | class NumMatrix: 2 | 3 | def __init__(self, matrix: List[List[int]]): 4 | m = len(matrix) 5 | n = len(matrix[0]) 6 | 7 | self.prefix = [[0 for _ in range(n + 1)] for _ in range(m + 1)] 8 | for i in range(1,m+1): 9 | for j in range(1,n+1): 10 | self.prefix[i][j] = self.prefix[i-1][j] + self.prefix[i][j-1] + matrix[i-1][j-1] - self.prefix[i-1][j-1] 11 | 12 | 13 | def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: 14 | return self.prefix[row2+1][col2+1] - self.prefix[row1][col2+1] - self.prefix[row2+1][col1] + self.prefix[row1][col1] 15 | 16 | 17 | # Your NumMatrix object will be instantiated and called as such: 18 | # obj = NumMatrix(matrix) 19 | # param_1 = obj.sumRegion(row1,col1,row2,col2) -------------------------------------------------------------------------------- /304-range-sum-query-2d-immutable/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /326-power-of-three/326-power-of-three.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfThree(self, n: int) -> bool: 3 | if n < 0: 4 | return False 5 | if n == 1 or n == 3: 6 | return True 7 | 8 | if n > 3: 9 | n = n / 3 10 | return self.isPowerOfThree(n) 11 | else: 12 | return False 13 | -------------------------------------------------------------------------------- /326-power-of-three/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /326-power-of-three/README.md: -------------------------------------------------------------------------------- 1 |

326. Power of Three

Easy


Given an integer n, return true if it is a power of three. Otherwise, return false.

2 | 3 |

An integer n is a power of three, if there exists an integer x such that n == 3x.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: n = 27
 9 | Output: true
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: n = 0
15 | Output: false
16 | 
17 | 18 |

Example 3:

19 | 20 |
Input: n = 9
21 | Output: true
22 | 
23 | 24 |

 

25 |

Constraints:

26 | 27 |
    28 |
  • -231 <= n <= 231 - 1
  • 29 |
30 | 31 |

 

32 | Follow up: Could you solve it without loops/recursion?
-------------------------------------------------------------------------------- /33-search-in-rotated-sorted-array/33-search-in-rotated-sorted-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | for i in nums: 4 | if i == target: 5 | return nums.index(i) 6 | return -1 7 | -------------------------------------------------------------------------------- /33-search-in-rotated-sorted-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /34-find-first-and-last-position-of-element-in-sorted-array/34-find-first-and-last-position-of-element-in-sorted-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchRange(self, nums: List[int], target: int) -> List[int]: 3 | for i in range(len(nums)): 4 | if nums[i] == target: 5 | start = i 6 | while i+1 < len(nums) and nums[i+1] == target: 7 | i+= 1 8 | return[start, i] 9 | return [-1, -1] 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /34-find-first-and-last-position-of-element-in-sorted-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /342-power-of-four/342-power-of-four.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfFour(self, n: int) -> bool: 3 | #Negative 4 | if n < 0: 5 | return False 6 | #Base Case 7 | if n == 1 or n == 4: 8 | return True 9 | #Recursive 10 | elif n > 4: 11 | n = n / 4 12 | return self.isPowerOfFour(n) 13 | else: 14 | return False 15 | 16 | #Complixity = lg(n) 17 | #Space = lg(n) -------------------------------------------------------------------------------- /342-power-of-four/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /344-reverse-string/344-reverse-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseString(self, s: List[str]) -> None: 3 | """ 4 | Do not return anything, modify s in-place instead. 5 | """ 6 | i = 0 7 | j = len(s) - 1 8 | while i < j : 9 | s[i], s[j] = s[j], s[i] 10 | i += 1 11 | j -= 1 12 | 13 | -------------------------------------------------------------------------------- /344-reverse-string/README.md: -------------------------------------------------------------------------------- 1 |

344. Reverse String

Easy


Write a function that reverses a string. The input string is given as an array of characters s.

2 | 3 |

You must do this by modifying the input array in-place with O(1) extra memory.

4 | 5 |

 

6 |

Example 1:

7 |
Input: s = ["h","e","l","l","o"]
 8 | Output: ["o","l","l","e","h"]
 9 | 

Example 2:

10 |
Input: s = ["H","a","n","n","a","h"]
11 | Output: ["h","a","n","n","a","H"]
12 | 
13 |

 

14 |

Constraints:

15 | 16 | 20 |
-------------------------------------------------------------------------------- /349-intersection-of-two-arrays/349-intersection-of-two-arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 | l = [] 4 | a = 0 5 | b = 0 6 | if len(nums1) > len(nums2): 7 | a = len(nums1) 8 | else: 9 | b = len(nums2) 10 | 11 | if a: 12 | for it in nums2: 13 | if it in nums1: 14 | l.append(it) 15 | nums1.remove(it) 16 | else: 17 | for it in nums1: 18 | if it in nums2: 19 | l.append(it) 20 | nums2.remove(it) 21 | 22 | 23 | return list(set(l)) 24 | -------------------------------------------------------------------------------- /349-intersection-of-two-arrays/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /349-intersection-of-two-arrays/README.md: -------------------------------------------------------------------------------- 1 |

349. Intersection of Two Arrays

Easy


Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: nums1 = [1,2,2,1], nums2 = [2,2]
 7 | Output: [2]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
13 | Output: [9,4]
14 | Explanation: [4,9] is also accepted.
15 | 
16 | 17 |

 

18 |

Constraints:

19 | 20 |
    21 |
  • 1 <= nums1.length, nums2.length <= 1000
  • 22 |
  • 0 <= nums1[i], nums2[i] <= 1000
  • 23 |
24 |
-------------------------------------------------------------------------------- /35-search-insert-position/35-search-insert-position.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchInsert(self, nums: List[int], target: int) -> int: 3 | low = 0 4 | high = len(nums) - 1 5 | mid = (low + high) // 2 6 | while low <= high: 7 | if target < nums[mid]: 8 | high = mid - 1 9 | elif target > nums[mid]: 10 | low = mid + 1 11 | elif target == nums[mid]: 12 | return mid 13 | mid = (low + high) // 2 14 | return mid + 1 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /35-search-insert-position/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /392-is-subsequence/392-is-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSubsequence(self, s: str, t: str) -> bool: 3 | n = len(s) 4 | m = len(t) 5 | 6 | if n == 0: 7 | return True 8 | if m == 0: 9 | return False 10 | 11 | if s[n-1] == t[m-1]: 12 | return self.isSubsequence(s[:n-1], t[:m-1]) 13 | return self.isSubsequence(s[:n], t[:m-1]) 14 | 15 | -------------------------------------------------------------------------------- /4-median-of-two-sorted-arrays/4-median-of-two-sorted-arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchInsert(self, nums: List[int], target: int,priority) -> int: 3 | low = 0 4 | high = len(nums) - 1 5 | mid = (low + high) // 2 6 | while low <= high: 7 | if target < nums[mid]: 8 | high = mid - 1 9 | elif target > nums[mid]: 10 | low = mid + 1 11 | elif target == nums[mid]: 12 | if priority: 13 | low = mid +1 14 | else: 15 | high = mid -1 16 | mid = (low + high) // 2 17 | return mid + 1 18 | 19 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 20 | n = len(nums1) + len(nums2) 21 | needed = [] 22 | med = [] 23 | needed.append(n // 2) 24 | if n % 2 == 0: 25 | needed.append(n // 2 - 1) 26 | for i in range(len(nums1)): 27 | m = i + self.searchInsert(nums2, nums1[i],True) 28 | if m in needed: 29 | needed.remove(m) 30 | med.append(nums1[i]) 31 | for i in range(len(nums2)): 32 | m = i + self.searchInsert(nums1, nums2[i],False) 33 | if m in needed: 34 | needed.remove(m) 35 | med.append(nums2[i]) 36 | return sum(med) / len(med) 37 | -------------------------------------------------------------------------------- /4-median-of-two-sorted-arrays/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /409-longest-palindrome/409-longest-palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestPalindrome(self, s: str) -> int: 3 | #longest palindrome length = number of even repeated + number of the max(odd) 4 | d = {} 5 | mx = 0 6 | sm = 0 7 | odd = False 8 | 9 | if len(s) == 2 and s[0] == s[1]: 10 | return len(s) 11 | elif len(s) == 1 or len(s) == 2: 12 | return 1 13 | 14 | for k in s: 15 | if k not in d: 16 | d[k] = 1 17 | else: 18 | d[k] += 1 19 | 20 | for v in d.values(): 21 | if v % 2 == 0: 22 | sm += v 23 | else: 24 | mx = max(mx, v) #mx = 3 25 | sm += v - 1 26 | odd = True 27 | if not odd: 28 | return sm 29 | return sm + 1 30 | -------------------------------------------------------------------------------- /409-longest-palindrome/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /41-first-missing-positive/41-first-missing-positive.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstMissingPositive(self, nums: List[int]) -> int: 3 | d = {} 4 | for i in nums: 5 | if i not in d: 6 | d[i] = 1 7 | 8 | a = 1 9 | while True: 10 | v = d.get(a, -1) 11 | if v == -1: #not here 12 | return a 13 | a+= 1 -------------------------------------------------------------------------------- /41-first-missing-positive/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /41-first-missing-positive/README.md: -------------------------------------------------------------------------------- 1 |

41. First Missing Positive

Hard


Given an unsorted integer array nums, return the smallest missing positive integer.

2 | 3 |

You must implement an algorithm that runs in O(n) time and uses constant extra space.

4 | 5 |

 

6 |

Example 1:

7 |
Input: nums = [1,2,0]
 8 | Output: 3
 9 | 

Example 2:

10 |
Input: nums = [3,4,-1,1]
11 | Output: 2
12 | 

Example 3:

13 |
Input: nums = [7,8,9,11,12]
14 | Output: 1
15 | 
16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • 1 <= nums.length <= 5 * 105
  • 21 |
  • -231 <= nums[i] <= 231 - 1
  • 22 |
23 |
-------------------------------------------------------------------------------- /412-fizz-buzz/412-fizz-buzz.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fizzBuzz(self, n: int) -> List[str]: 3 | l = [] 4 | for i in range(1, n+1): 5 | if i % 3 == 0 and i % 5 == 0: 6 | l.append("FizzBuzz") 7 | elif i % 3 ==0: 8 | l.append("Fizz") 9 | elif i % 5 == 0: 10 | l.append("Buzz") 11 | else: 12 | l.append(str(i)) 13 | return l 14 | -------------------------------------------------------------------------------- /414-third-maximum-number/414-third-maximum-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def thirdMax(self, nums: List[int]) -> int: 3 | l = sorted(nums) 4 | k = [] 5 | for i in l: 6 | if i not in k: 7 | k.append(i) 8 | if len(k) < 3: 9 | return k[-1] 10 | else: 11 | return k[-3] 12 | -------------------------------------------------------------------------------- /414-third-maximum-number/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /417-pacific-atlantic-water-flow/417-pacific-atlantic-water-flow.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def pacificAtlantic(self, height: List[List[int]]) -> List[List[int]]: 3 | n = len(height) #rows 4 | m = len(height[0]) #cols 5 | pac = set() 6 | atle = set() 7 | 8 | 9 | def dfs_helper(i, j, visited, prev): 10 | try: 11 | cur = height[i][j] 12 | except: 13 | pass 14 | 15 | 16 | #check the coordinations 17 | if (j < 0) or (i < 0) or j == m or i == n or (cur < prev) or (i, j) in visited: 18 | return 19 | #add the pair to visit 20 | visited.add((i, j)) 21 | #check neighbor 22 | dfs_helper(i,j+1,visited,cur) 23 | dfs_helper(i,j-1,visited,cur) 24 | dfs_helper(i+1,j,visited,cur) 25 | dfs_helper(i-1,j,visited,cur) 26 | 27 | 28 | #check top and bottom rows 29 | for c in range(m): 30 | dfs_helper(0, c, pac, height[0][c]) 31 | dfs_helper(n-1, c, atle, height[n-1][c]) 32 | #check left and right cols 33 | for r in range(n): 34 | dfs_helper(r, 0, pac, height[r][0]) 35 | dfs_helper(r, m-1, atle, height[r][m-1]) 36 | 37 | winner = [] 38 | #announce the winners 39 | for row in range(n): 40 | for col in range(m): 41 | if (row, col) in pac and (row, col) in atle: 42 | winner.append((row, col)) 43 | 44 | return winner 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /417-pacific-atlantic-water-flow/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /424-longest-repeating-character-replacement/424-longest-repeating-character-replacement.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def characterReplacement(self, s: str, k: int) -> int: 3 | d = {} 4 | longest, max_repeat, start = 0, 0, 0 5 | for end in range(len(s)): 6 | right = s[end] 7 | if right not in d: 8 | d[right] = 0 9 | d[right] += 1 10 | 11 | max_repeat = max(max_repeat, d[right]) 12 | if (end - start - max_repeat + 1) > k: 13 | left = s[start] 14 | d[left] -= 1 15 | start += 1 16 | 17 | longest = max(longest, end - start + 1) 18 | return longest -------------------------------------------------------------------------------- /424-longest-repeating-character-replacement/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /437-path-sum-iii/437-path-sum-iii.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int: 9 | self.total = 0 10 | def helper(node, cur): 11 | if not node: 12 | return 13 | helper(node.right, cur + node.val) 14 | helper(node.left, cur + node.val) 15 | if cur + node.val == targetSum: self.total += 1 16 | def dfs(node): 17 | if not node: return 18 | helper(node, 0) 19 | dfs(node.left) 20 | dfs(node.right) 21 | dfs(root) 22 | return self.total 23 | 24 | -------------------------------------------------------------------------------- /437-path-sum-iii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /437-path-sum-iii/README.md: -------------------------------------------------------------------------------- 1 |

437. Path Sum III

Medium


Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.

2 | 3 |

The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
 9 | Output: 3
10 | Explanation: The paths that sum to 8 are shown.
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
16 | Output: 3
17 | 
18 | 19 |

 

20 |

Constraints:

21 | 22 |
    23 |
  • The number of nodes in the tree is in the range [0, 1000].
  • 24 |
  • -109 <= Node.val <= 109
  • 25 |
  • -1000 <= targetSum <= 1000
  • 26 |
27 |
-------------------------------------------------------------------------------- /438-find-all-anagrams-in-a-string/438-find-all-anagrams-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findAnagrams(self, str1: str, pattern: str) -> List[int]: 3 | result_indexes = [] 4 | d = {} 5 | start, matched = 0, 0 6 | for p in pattern: 7 | if p not in d: 8 | d[p] = 0 9 | d[p] += 1 10 | 11 | for end in range(len(str1)): 12 | right = str1[end] 13 | if right in d: 14 | d[right] -= 1 15 | if d[right] == 0: 16 | matched += 1 17 | 18 | if matched == len(d): result_indexes.append(start) 19 | 20 | #Shrinking the window 21 | if end >= len(pattern) - 1: #need to move 22 | left = str1[start] 23 | start += 1 24 | if left in d: 25 | if d[left] == 0: 26 | matched -= 1 27 | d[left] += 1 28 | 29 | return result_indexes -------------------------------------------------------------------------------- /438-find-all-anagrams-in-a-string/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /442-find-all-duplicates-in-an-array/442-find-all-duplicates-in-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicates(self, nums: List[int]) -> List[int]: 3 | nums.sort() 4 | arr = [] 5 | for i in range(1, len(nums)): 6 | if nums[i-1] == nums[i]: 7 | arr.append(nums[i-1]) 8 | return set(arr) -------------------------------------------------------------------------------- /442-find-all-duplicates-in-an-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /448-find-all-numbers-disappeared-in-an-array/448-find-all-numbers-disappeared-in-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 3 | a = set(nums) 4 | l = [i for i in range(1, len(nums)+1)] 5 | arr = [] 6 | for i in range(len(nums)): 7 | if l[i] not in a: 8 | arr.append(l[i]) 9 | return arr 10 | -------------------------------------------------------------------------------- /448-find-all-numbers-disappeared-in-an-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /448-find-all-numbers-disappeared-in-an-array/README.md: -------------------------------------------------------------------------------- 1 |

448. Find All Numbers Disappeared in an Array

Easy


Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

2 | 3 |

 

4 |

Example 1:

5 |
Input: nums = [4,3,2,7,8,2,3,1]
 6 | Output: [5,6]
 7 | 

Example 2:

8 |
Input: nums = [1,1]
 9 | Output: [2]
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • n == nums.length
  • 16 |
  • 1 <= n <= 105
  • 17 |
  • 1 <= nums[i] <= n
  • 18 |
19 | 20 |

 

21 |

Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

22 |
-------------------------------------------------------------------------------- /451-sort-characters-by-frequency/451-sort-characters-by-frequency.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def frequencySort(self, s: str) -> str: 3 | t = "" 4 | d = {} 5 | for c in s: 6 | if c not in d.keys(): 7 | d[c] = 1 8 | else: 9 | d[c] += 1 10 | 11 | d = dict(sorted(d.items(), key=lambda item: item[1], reverse = True)) 12 | for k, v in d.items(): 13 | t+= k*v 14 | 15 | return t 16 | -------------------------------------------------------------------------------- /451-sort-characters-by-frequency/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /457-circular-array-loop/457-circular-array-loop.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def find_index(self, arr, is_forward, current_index): 3 | direction = arr[current_index]>= 0 4 | if is_forward != direction: 5 | return -1 6 | next_index = (current_index + arr[current_index]) % len(arr) 7 | if next_index == current_index: 8 | next_index = -1 9 | 10 | return next_index 11 | 12 | def circularArrayLoop(self, nums: List[int]) -> bool: 13 | for i in range(len(nums)): 14 | is_forward = nums[i] >= 0 15 | slow, fast = i, i 16 | while True: 17 | slow = self.find_index(nums, is_forward, slow) 18 | fast = self.find_index(nums, is_forward, fast) 19 | if fast != -1: 20 | fast = self.find_index(nums, is_forward, fast) 21 | if fast == -1 or slow == fast or slow == -1: 22 | break 23 | if fast == slow and slow != -1: 24 | return True 25 | return False 26 | 27 | -------------------------------------------------------------------------------- /457-circular-array-loop/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /46-permutations/46-permutations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def permute(self, nums: List[int]) -> List[List[int]]: 3 | ans=[] 4 | if len(nums)==1: 5 | return [list(nums)] 6 | 7 | for i in range(len(nums)): 8 | n=nums.pop(0) 9 | li=self.permute(nums) 10 | for j in li: 11 | j.append(n) 12 | ans.extend(li) 13 | nums.append(n) 14 | return ans -------------------------------------------------------------------------------- /46-permutations/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /46-permutations/README.md: -------------------------------------------------------------------------------- 1 |

46. Permutations

Medium


Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

2 | 3 |

 

4 |

Example 1:

5 |
Input: nums = [1,2,3]
 6 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 7 | 

Example 2:

8 |
Input: nums = [0,1]
 9 | Output: [[0,1],[1,0]]
10 | 

Example 3:

11 |
Input: nums = [1]
12 | Output: [[1]]
13 | 
14 |

 

15 |

Constraints:

16 | 17 |
    18 |
  • 1 <= nums.length <= 6
  • 19 |
  • -10 <= nums[i] <= 10
  • 20 |
  • All the integers of nums are unique.
  • 21 |
22 |
-------------------------------------------------------------------------------- /463-island-perimeter/463-island-perimeter.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def islandPerimeter(self, grid: List[List[int]]) -> int: 3 | n = len(grid) 4 | m = len(grid[0]) 5 | prem = 0 6 | grid = [[0]*m] + grid + [[0]*m] #add rows of only zeros at top and bottom of grid 7 | for i in range(n+2): 8 | grid[i] = [0]+grid[i]+[0] 9 | 10 | 11 | for r in range(1, n+1): 12 | for c in range(1, m+1): 13 | if grid[r][c] == 1: 14 | #check corners 15 | if not grid[r-1][c]: prem += 1 16 | if not grid[r+1][c]: prem += 1 17 | if not grid[r][c-1]: prem += 1 18 | if not grid[r][c+1]: prem += 1 19 | return prem 20 | 21 | -------------------------------------------------------------------------------- /49-group-anagrams/49-group-anagrams.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 3 | d = {} #key and list 4 | for i in strs: 5 | s = ''.join(sorted(i)) 6 | if s not in d.keys(): 7 | d[s] = [i] 8 | else: 9 | d[s] += [i] 10 | 11 | return list(d.values()) 12 | 13 | 14 | -------------------------------------------------------------------------------- /49-group-anagrams/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /50-powx-n/50-powx-n.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x: float, n: int) -> float: 3 | return x**n -------------------------------------------------------------------------------- /50-powx-n/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /500-keyboard-row/500-keyboard-row.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findWords(self, words: List[str]) -> List[str]: 3 | r1 = "qwertyuiop" 4 | r2 = "asdfghjkl" 5 | r3 = "zxcvbnm" 6 | l = [] 7 | for k in words: 8 | c1, c2, c3 = 0,0,0 9 | i = k.lower() 10 | for j in i: 11 | if j in r1: 12 | c1 += 1 13 | elif j in r2: 14 | c2 += 1 15 | elif j in r3: 16 | c3 += 1 17 | if c1 == len(k) or c2 == len(k) or c3 == len(k): 18 | l.append(k) 19 | return l -------------------------------------------------------------------------------- /500-keyboard-row/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /509-fibonacci-number/509-fibonacci-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fib(self, n: int) -> int: 3 | if n == 0: 4 | return 0 5 | elif n == 1: 6 | return 1 7 | else: 8 | return self.fib(n-1) + self.fib(n-2) -------------------------------------------------------------------------------- /515-find-largest-value-in-each-tree-row/515-find-largest-value-in-each-tree-row.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def largestValues(self, root: Optional[TreeNode]) -> List[int]: 9 | result = [] 10 | level = [root] 11 | while any(level): 12 | result.append(max([node.val for node in level])) 13 | new_level = [] 14 | for node in level: 15 | if node.left: 16 | new_level.append(node.left) 17 | if node.right: 18 | new_level.append(node.right) 19 | level = new_level 20 | return result -------------------------------------------------------------------------------- /515-find-largest-value-in-each-tree-row/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /515-find-largest-value-in-each-tree-row/README.md: -------------------------------------------------------------------------------- 1 |

515. Find Largest Value in Each Tree Row

Medium


Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: root = [1,3,2,5,3,null,9]
 7 | Output: [1,3,9]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: root = [1,2,3]
13 | Output: [1,3]
14 | 
15 | 16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • The number of nodes in the tree will be in the range [0, 104].
  • 21 |
  • -231 <= Node.val <= 231 - 1
  • 22 |
23 |
-------------------------------------------------------------------------------- /53-maximum-subarray/53-maximum-subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | w = 0 4 | s = float('-inf') 5 | i = 0 6 | while i < len(nums): 7 | w += nums[i] 8 | s = max(s, w) 9 | w = max(w, 0) 10 | 11 | i += 1 12 | return s 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /53-maximum-subarray/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /532-k-diff-pairs-in-an-array/532-k-diff-pairs-in-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findPairs(self, nums: List[int], k: int) -> int: 3 | d = {} 4 | p = 0 5 | r = [] 6 | #save the unique 7 | for i in nums: 8 | if i not in d.keys(): 9 | d[i] = 1 10 | else: 11 | d[i] += 1 12 | r.append(i) 13 | if k == 0: 14 | return len(set(r)) 15 | #check 16 | for s in d.keys(): 17 | if (s+k) in d.keys() and (s+k) != s: 18 | p+=1 19 | return p 20 | -------------------------------------------------------------------------------- /532-k-diff-pairs-in-an-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /543-diameter-of-binary-tree/543-diameter-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: 9 | res = [0] 10 | def dfs(node): 11 | if not node: return -1 12 | left = dfs(node.left) 13 | right = dfs(node.right) 14 | res[0] = max(res[0], 2 + left + right) 15 | 16 | return 1 + max(left, right) 17 | dfs(root) 18 | return res[0] -------------------------------------------------------------------------------- /543-diameter-of-binary-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /547-number-of-provinces/547-number-of-provinces.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findCircleNum(self, isConnected: List[List[int]]) -> int: 3 | def dfs(a): 4 | visited.add(a) 5 | for b in range(len(isConnected)): 6 | if b not in visited and isConnected[a][b]: 7 | dfs(b) 8 | 9 | 10 | prov = 0 11 | visited = set() 12 | for a in range(len(isConnected)): #row by row 13 | if a not in visited: 14 | prov += 1 15 | dfs(a) 16 | 17 | return prov 18 | -------------------------------------------------------------------------------- /547-number-of-provinces/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /56-merge-intervals/56-merge-intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 3 | l = [] 4 | #sorting 5 | intervals.sort(key = lambda x: x[0]) 6 | s, e = intervals[0] 7 | 8 | for i in range(1, len(intervals)): 9 | if s <= intervals[i][0] <= e or s <= intervals[i][1] <= e: 10 | s, e = [min(s, intervals[i][0]), max(e, intervals[i][1])] 11 | continue 12 | 13 | l.append([s, e]) 14 | s, e = intervals[i] 15 | l.append([s, e]) 16 | return l -------------------------------------------------------------------------------- /56-merge-intervals/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /56-merge-intervals/README.md: -------------------------------------------------------------------------------- 1 |

56. Merge Intervals

Medium


Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: intervals = [[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] overlap, merge them into [1,6].
 9 | 
10 | 11 |

Example 2:

12 | 13 |
Input: intervals = [[1,4],[4,5]]
14 | Output: [[1,5]]
15 | Explanation: Intervals [1,4] and [4,5] are considered overlapping.
16 | 
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • 1 <= intervals.length <= 104
  • 23 |
  • intervals[i].length == 2
  • 24 |
  • 0 <= starti <= endi <= 104
  • 25 |
26 |
-------------------------------------------------------------------------------- /58-length-of-last-word/58-length-of-last-word.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | l = s.strip(" ").split(" ") 4 | return len(l[-1]) 5 | -------------------------------------------------------------------------------- /58-length-of-last-word/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /581-shortest-unsorted-continuous-subarray/581-shortest-unsorted-continuous-subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findUnsortedSubarray(self, arr: List[int]) -> int: 3 | low, high = 0, len(arr) - 1 4 | # find the first number out of sorting order from the beginning 5 | while (low < len(arr) - 1 and arr[low] <= arr[low + 1]): 6 | low += 1 7 | 8 | if low == len(arr) - 1: # if the array is sorted 9 | return 0 10 | 11 | # find the first number out of sorting order from the end 12 | while (high > 0 and arr[high] >= arr[high - 1]): 13 | high -= 1 14 | 15 | # find the maximum and minimum of the subarray 16 | subarray_max = -math.inf 17 | subarray_min = math.inf 18 | for k in range(low, high+1): 19 | subarray_max = max(subarray_max, arr[k]) 20 | subarray_min = min(subarray_min, arr[k]) 21 | 22 | # extend the subarray to include any number which is bigger than the minimum of the subarray 23 | while (low > 0 and arr[low-1] > subarray_min): 24 | low -= 1 25 | # extend the subarray to include any number which is smaller than the maximum of the subarray 26 | while (high < len(arr)-1 and arr[high+1] < subarray_max): 27 | high += 1 28 | 29 | return high - low + 1 30 | 31 | -------------------------------------------------------------------------------- /581-shortest-unsorted-continuous-subarray/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /60-permutation-sequence/60-permutation-sequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getPermutation(self, n: int, k: int) -> str: 3 | #build permutions with memorization 4 | permutations = [] 5 | unused = list(range(1, n+1)) 6 | fact = [1]*(n+1) #base case 7 | for i in range(1, n+1): 8 | fact[i] = i * fact[i-1] 9 | k -= 1 10 | while n > 0: 11 | len_part = fact[n] // n 12 | i = k//len_part 13 | permutations.append(unused[i]) 14 | unused.pop(i) 15 | n -= 1 16 | k %= len_part 17 | return ''.join(map(str, permutations)) 18 | -------------------------------------------------------------------------------- /60-permutation-sequence/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /637-average-of-levels-in-binary-tree/637-average-of-levels-in-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: 9 | def avg(a): 10 | return sum(a) / len(a) 11 | result = [] 12 | level = [root] 13 | av = [] 14 | while any(level): 15 | result.append([node.val for node in level]) 16 | new_level = [] 17 | for node in level: 18 | if node.left: 19 | new_level.append(node.left) 20 | if node.right: 21 | new_level.append(node.right) 22 | level = new_level 23 | for l in result: 24 | av.append(avg(l)) 25 | return av 26 | -------------------------------------------------------------------------------- /637-average-of-levels-in-binary-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /637-average-of-levels-in-binary-tree/README.md: -------------------------------------------------------------------------------- 1 |

637. Average of Levels in Binary Tree

Easy


Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted. 2 |

 

3 |

Example 1:

4 | 5 |
Input: root = [3,9,20,null,null,15,7]
 6 | Output: [3.00000,14.50000,11.00000]
 7 | Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.
 8 | Hence return [3, 14.5, 11].
 9 | 
10 | 11 |

Example 2:

12 | 13 |
Input: root = [3,9,20,15,7]
14 | Output: [3.00000,14.50000,11.00000]
15 | 
16 | 17 |

 

18 |

Constraints:

19 | 20 |
    21 |
  • The number of nodes in the tree is in the range [1, 104].
  • 22 |
  • -231 <= Node.val <= 231 - 1
  • 23 |
24 |
-------------------------------------------------------------------------------- /643-maximum-average-subarray-i/643-maximum-average-subarray-i.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMaxAverage(self, nums: List[int], k: int) -> float: 3 | arrsum, arrstart = 0, 0 4 | res = [] 5 | for arrend in range(len(nums)): 6 | arrsum += nums[arrend] 7 | if arrend >= k-1: 8 | res.append(arrsum/k) 9 | arrsum -= nums[arrstart] 10 | arrstart+=1 11 | return max(res) -------------------------------------------------------------------------------- /643-maximum-average-subarray-i/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /643-maximum-average-subarray-i/README.md: -------------------------------------------------------------------------------- 1 |

643. Maximum Average Subarray I

Easy


You are given an integer array nums consisting of n elements, and an integer k.

2 | 3 |

Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: nums = [1,12,-5,-6,50,3], k = 4
 9 | Output: 12.75000
10 | Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: nums = [5], k = 1
16 | Output: 5.00000
17 | 
18 | 19 |

 

20 |

Constraints:

21 | 22 |
    23 |
  • n == nums.length
  • 24 |
  • 1 <= k <= n <= 105
  • 25 |
  • -104 <= nums[i] <= 104
  • 26 |
27 |
-------------------------------------------------------------------------------- /645-set-mismatch/645-set-mismatch.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findErrorNums(self, nums: List[int]) -> List[int]: 3 | i = 0 4 | while i < len(nums): 5 | j = nums[i] - 1 6 | if nums[i] != nums[j]: 7 | nums[i], nums[j] = nums[j], nums[i] 8 | else: 9 | i += 1 10 | 11 | 12 | for i in range(len(nums)): 13 | if nums[i] != i + 1: 14 | return [nums[i], i+1] 15 | return [-1, -1] 16 | 17 | -------------------------------------------------------------------------------- /645-set-mismatch/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /67-add-binary/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /69-sqrtx/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /70-climbing-stairs/70-climbing-stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | one, two = 1, 1 4 | for i in range(n-1): 5 | temp = one 6 | one = one + two 7 | two = temp 8 | return one -------------------------------------------------------------------------------- /70-climbing-stairs/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /70-climbing-stairs/README.md: -------------------------------------------------------------------------------- 1 |

70. Climbing Stairs

Easy


You are climbing a staircase. It takes n steps to reach the top.

2 | 3 |

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: n = 2
 9 | Output: 2
10 | Explanation: There are two ways to climb to the top.
11 | 1. 1 step + 1 step
12 | 2. 2 steps
13 | 
14 | 15 |

Example 2:

16 | 17 |
Input: n = 3
18 | Output: 3
19 | Explanation: There are three ways to climb to the top.
20 | 1. 1 step + 1 step + 1 step
21 | 2. 1 step + 2 steps
22 | 3. 2 steps + 1 step
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • 1 <= n <= 45
  • 30 |
31 |
-------------------------------------------------------------------------------- /704-binary-search/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /724-find-pivot-index/724-find-pivot-index.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def pivotIndex(self, nums: List[int]) -> int: 3 | k = 0 4 | r = sum(nums) 5 | for i in range(len(nums)): 6 | r -= nums[i] 7 | if k == r: 8 | return i 9 | k += nums[i] 10 | 11 | return -1 -------------------------------------------------------------------------------- /73-set-matrix-zeroes/73-set-matrix-zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def setZeroes(self, matrix: List[List[int]]) -> None: 3 | """ 4 | Do not return anything, modify matrix in-place instead. 5 | """ 6 | menna = [x[:] for x in matrix] 7 | n = len(matrix) # high 8 | m = len(matrix[0]) # width 9 | 10 | for i in range(n): 11 | for j in range(m): 12 | if menna[i][j] == 0: 13 | for k in range(n): 14 | matrix[k][j] = 0 15 | for k in range(m): 16 | matrix[i][k] = 0 17 | -------------------------------------------------------------------------------- /73-set-matrix-zeroes/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /74-search-a-2d-matrix/74-search-a-2d-matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: 3 | row,col=len(matrix),len(matrix[0]) 4 | low,high=0,row*col-1 5 | while(low<=high): 6 | mid=(low+high)//2 7 | 8 | num=matrix[mid//col][mid%col] 9 | 10 | if num==target: 11 | return True 12 | elif(num None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | for i in range(len(nums)): 7 | for j in range(len(nums)): 8 | if nums[i] < nums[j]: 9 | nums[i], nums[j] = nums[j], nums[i] 10 | return nums 11 | -------------------------------------------------------------------------------- /75-sort-colors/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /752-open-the-lock/752-open-the-lock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def openLock(self, deadends: List[str], target: str) -> int: 3 | if "0000" in deadends: 4 | return -1 5 | 6 | def childern(lock): 7 | res = [] 8 | for i in range(4): 9 | #increment 10 | digit = str((int(lock[i]) + 1) % 10) 11 | res.append(lock[:i] + digit + lock[i+1:]) 12 | #decrement 13 | digit = str((int(lock[i]) - 1 + 10) % 10) 14 | res.append(lock[:i] + digit + lock[i+1:]) 15 | return res 16 | 17 | q = deque() 18 | visit = set(deadends) 19 | q.append(["0000", 0]) #lock steps 20 | while q: 21 | lock, steps = q.popleft() 22 | if lock == target: 23 | return steps 24 | for child in childern(lock): 25 | if child not in visit: 26 | visit.add(child) 27 | q.append([child, steps+1]) 28 | 29 | return -1 -------------------------------------------------------------------------------- /76-minimum-window-substring/76-minimum-window-substring.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minWindow(self, s: str, t: str) -> str: 3 | start, substr, matched = 0, 0, 0 4 | d = {} 5 | min_length = len(s) + 1 6 | for i in t: 7 | if i not in d: 8 | d[i] = 0 9 | d[i] += 1 10 | 11 | for end in range(len(s)): 12 | right = s[end] 13 | if right in d: 14 | d[right] -= 1 15 | if d[right] == 0: 16 | matched += 1 17 | while matched == len(d): 18 | if min_length > end - start + 1: 19 | min_length = end - start + 1 20 | substr = start 21 | 22 | left = s[start] 23 | start += 1 24 | 25 | if left in d: 26 | if d[left] == 0: 27 | matched -= 1 28 | d[left] += 1 29 | 30 | if min_length > len(s): 31 | return "" 32 | return s[substr:substr + min_length] 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /771-jewels-and-stones/771-jewels-and-stones.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numJewelsInStones(self, jewels: str, stones: str) -> int: 3 | c = 0 4 | for i in jewels: 5 | c += stones.count(i) 6 | return c -------------------------------------------------------------------------------- /771-jewels-and-stones/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /771-jewels-and-stones/README.md: -------------------------------------------------------------------------------- 1 |

771. Jewels and Stones

Easy


You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.

2 | 3 |

Letters are case sensitive, so "a" is considered a different type of stone from "A".

4 | 5 |

 

6 |

Example 1:

7 |
Input: jewels = "aA", stones = "aAAbbbb"
 8 | Output: 3
 9 | 

Example 2:

10 |
Input: jewels = "z", stones = "ZZ"
11 | Output: 0
12 | 
13 |

 

14 |

Constraints:

15 | 16 |
    17 |
  • 1 <= jewels.length, stones.length <= 50
  • 18 |
  • jewels and stones consist of only English letters.
  • 19 |
  • All the characters of jewels are unique.
  • 20 |
21 |
-------------------------------------------------------------------------------- /78-subsets/78-subsets.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsets(self, nums: List[int]) -> List[List[int]]: 3 | subsets = [] 4 | subsets.append([]) 5 | for current in nums: 6 | n = len(subsets) 7 | for i in range(n): 8 | set1 = list(subsets[i]) 9 | set1.append(current) 10 | subsets.append(set1) 11 | return subsets -------------------------------------------------------------------------------- /78-subsets/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /78-subsets/README.md: -------------------------------------------------------------------------------- 1 |

78. Subsets

Medium


Given an integer array nums of unique elements, return all possible subsets (the power set).

2 | 3 |

The solution set must not contain duplicate subsets. Return the solution in any order.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: nums = [1,2,3]
 9 | Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: nums = [0]
15 | Output: [[],[0]]
16 | 
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • 1 <= nums.length <= 10
  • 23 |
  • -10 <= nums[i] <= 10
  • 24 |
  • All the numbers of nums are unique.
  • 25 |
26 |
-------------------------------------------------------------------------------- /79-word-search/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /81-search-in-rotated-sorted-array-ii/81-search-in-rotated-sorted-array-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> bool: 3 | for i in nums: 4 | if i == target: 5 | return True 6 | return False 7 | -------------------------------------------------------------------------------- /81-search-in-rotated-sorted-array-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /83-remove-duplicates-from-sorted-list/83-remove-duplicates-from-sorted-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | if head: 9 | current = head 10 | while current.next: 11 | if current.val == current.next.val: 12 | current.next = current.next.next 13 | else: 14 | current = current.next 15 | return head -------------------------------------------------------------------------------- /83-remove-duplicates-from-sorted-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /83-remove-duplicates-from-sorted-list/README.md: -------------------------------------------------------------------------------- 1 |

83. Remove Duplicates from Sorted List

Easy


Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: head = [1,1,2]
 7 | Output: [1,2]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: head = [1,1,2,3,3]
13 | Output: [1,2,3]
14 | 
15 | 16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • The number of nodes in the list is in the range [0, 300].
  • 21 |
  • -100 <= Node.val <= 100
  • 22 |
  • The list is guaranteed to be sorted in ascending order.
  • 23 |
24 |
-------------------------------------------------------------------------------- /836-rectangle-overlap/836-rectangle-overlap.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isRectangleOverlap(self, rec1, rec2): 3 | # check if either rectangle is actually a line 4 | if (rec1[0] == rec1[2] or rec1[1] == rec1[3] or \ 5 | rec2[0] == rec2[2] or rec2[1] == rec2[3]): 6 | # the line cannot have positive overlap 7 | return False 8 | 9 | return not (rec1[2] <= rec2[0] or # left 10 | rec1[3] <= rec2[1] or # bottom 11 | rec1[0] >= rec2[2] or # right 12 | rec1[1] >= rec2[3]) # top -------------------------------------------------------------------------------- /841-keys-and-rooms/841-keys-and-rooms.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: 3 | visited = set() 4 | stack = [0] 5 | while stack: 6 | room = stack.pop() 7 | visited.add(room) 8 | for k in rooms[room]: 9 | if k not in visited: 10 | stack.append(k) 11 | return len(visited) == len(rooms) -------------------------------------------------------------------------------- /841-keys-and-rooms/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /841-keys-and-rooms/README.md: -------------------------------------------------------------------------------- 1 |

841. Keys and Rooms

Medium


There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.

2 | 3 |

When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.

4 | 5 |

Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
Input: rooms = [[1],[2],[3],[]]
11 | Output: true
12 | Explanation: 
13 | We visit room 0 and pick up key 1.
14 | We then visit room 1 and pick up key 2.
15 | We then visit room 2 and pick up key 3.
16 | We then visit room 3.
17 | Since we were able to visit every room, we return true.
18 | 
19 | 20 |

Example 2:

21 | 22 |
Input: rooms = [[1,3],[3,0,1],[2],[0]]
23 | Output: false
24 | Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.
25 | 
26 | 27 |

 

28 |

Constraints:

29 | 30 |
    31 |
  • n == rooms.length
  • 32 |
  • 2 <= n <= 1000
  • 33 |
  • 0 <= rooms[i].length <= 1000
  • 34 |
  • 1 <= sum(rooms[i].length) <= 3000
  • 35 |
  • 0 <= rooms[i][j] < n
  • 36 |
  • All the values of rooms[i] are unique.
  • 37 |
38 |
-------------------------------------------------------------------------------- /841-lclighter-data-idlgt257723750-data-bundle-id0-stylebackground-image-linear-gradienttransparent-0-transparent-calc50-4px-rgb204-242-241-calc50-4px-rgb204-242-241-100-transition-background-position-120ms-ease-in-out-0s-padding-120ms-ease-in-out-0s-background-size-100-200-background-position-initial-user-select-auto-keys-and-rooms-lclighterdiv-classlinerthreadicon-linerfirst-data-highlight-id257723750-data-bundle-id0-idlgt257723750-stylebackground-image-url-and-quot-https-profilegetlinercom-liner-service-bucket-user-photo-default-color-10-wsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-div/841-lclighter-data-idlgt257723750-data-bundle-id0-stylebackground-image-linear-gradienttransparent-0-transparent-calc50-4px-rgb204-242-241-calc50-4px-rgb204-242-241-100-transition-background-position-120ms-ease-in-out-0s-padding-120ms-ease-in-out-0s-background-size-100-200-background-position-initial-user-select-auto-keys-and-rooms-lclighterdiv-classlinerthreadicon-linerfirst-data-highlight-id257723750-data-bundle-id0-idlgt257723750-stylebackground-image-url-and-quot-https-profilegetlinercom-liner-service-bucket-user-photo-default-color-10-wsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-div.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: 3 | visited = set() 4 | stack = collections.deque([0]) 5 | while stack: 6 | room = stack.pop() 7 | visited.add(room) 8 | for k in rooms[room]: 9 | if k not in visited: 10 | stack.append(k) 11 | return len(visited) == len(rooms) -------------------------------------------------------------------------------- /841-lclighter-data-idlgt257723750-data-bundle-id0-stylebackground-image-linear-gradienttransparent-0-transparent-calc50-4px-rgb204-242-241-calc50-4px-rgb204-242-241-100-transition-background-position-120ms-ease-in-out-0s-padding-120ms-ease-in-out-0s-background-size-100-200-background-position-initial-user-select-auto-keys-and-rooms-lclighterdiv-classlinerthreadicon-linerfirst-data-highlight-id257723750-data-bundle-id0-idlgt257723750-stylebackground-image-url-and-quot-https-profilegetlinercom-liner-service-bucket-user-photo-default-color-10-wsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-div/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /844-backspace-string-compare/844-backspace-string-compare.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def backspaceCompare(self, s: str, t: str) -> bool: 3 | def remove(s): 4 | stack = [] 5 | i = 0 6 | while i < len(s): 7 | if s[i] == '#' and len(stack) > 0: 8 | stack.pop() 9 | i += 1 10 | elif s[i] == '#' and len(stack) == 0: 11 | i += 1 12 | else: 13 | stack.append(s[i]) 14 | i += 1 15 | return stack 16 | 17 | return remove(s) == remove(t) -------------------------------------------------------------------------------- /852-peak-index-in-a-mountain-array/852-peak-index-in-a-mountain-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def peakIndexInMountainArray(self, arr: List[int]) -> int: 3 | mx, mx1 = 0, 0 4 | i = 0 5 | while i < len(arr): 6 | mx = max(arr[:i+1]) 7 | mx1 = max(arr[i:]) 8 | if mx == mx1: 9 | return i 10 | i+= 1 11 | -------------------------------------------------------------------------------- /860-lemonade-change/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /876-middle-of-the-linked-list/876-middle-of-the-linked-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | s, f = head, head.next 9 | while f and f.next: 10 | s = s.next 11 | f = f.next.next 12 | if f: 13 | return s.next 14 | return s 15 | 16 | -------------------------------------------------------------------------------- /876-middle-of-the-linked-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /876-middle-of-the-linked-list/README.md: -------------------------------------------------------------------------------- 1 |

876. Middle of the Linked List

Easy


Given the head of a singly linked list, return the middle node of the linked list.

2 | 3 |

If there are two middle nodes, return the second middle node.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: head = [1,2,3,4,5]
 9 | Output: [3,4,5]
10 | Explanation: The middle node of the list is node 3.
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: head = [1,2,3,4,5,6]
16 | Output: [4,5,6]
17 | Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • The number of nodes in the list is in the range [1, 100].
  • 25 |
  • 1 <= Node.val <= 100
  • 26 |
27 |
-------------------------------------------------------------------------------- /9-palindrome-number/9-palindrome-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, x: int) -> bool: 3 | x = str(x) 4 | i = 0 5 | j = len(x) - 1 6 | while i < j: 7 | if x[i] != x[j]: 8 | return False 9 | else: 10 | i += 1 11 | j -= 1 12 | return True 13 | 14 | -------------------------------------------------------------------------------- /9-palindrome-number/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /904-fruit-into-baskets/904-fruit-into-baskets.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def totalFruit(self, fruits: List[int]) -> int: 3 | d = {} 4 | startwindow = 0 5 | longest = 0 6 | 7 | for i in range(len(fruits)): 8 | right = fruits[i] 9 | if right not in d: 10 | d[right] = 0 11 | d[right] += 1 12 | 13 | while len(d) > 2: 14 | left_char = fruits[startwindow] 15 | d[left_char] -= 1 16 | if d[left_char] == 0: 17 | del d[left_char] 18 | startwindow += 1 19 | longest = max(longest, i - startwindow + 1) 20 | 21 | return longest -------------------------------------------------------------------------------- /904-fruit-into-baskets/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /912-sort-an-array/912-sort-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortArray(self, nums: List[int]) -> List[int]: 3 | nums.sort() 4 | return nums -------------------------------------------------------------------------------- /912-sort-an-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /912-sort-an-array/README.md: -------------------------------------------------------------------------------- 1 |

912. Sort an Array

Medium


Given an array of integers nums, sort the array in ascending order and return it.

2 | 3 |

You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: nums = [5,2,3,1]
 9 | Output: [1,2,3,5]
10 | Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: nums = [5,1,1,2,0,0]
16 | Output: [0,0,1,1,2,5]
17 | Explanation: Note that the values of nums are not necessairly unique.
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= nums.length <= 5 * 104
  • 25 |
  • -5 * 104 <= nums[i] <= 5 * 104
  • 26 |
27 |
-------------------------------------------------------------------------------- /94-binary-tree-inorder-traversal/94-binary-tree-inorder-traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: 9 | if not root: 10 | return [] 11 | return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right) -------------------------------------------------------------------------------- /94-binary-tree-inorder-traversal/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /986-interval-list-intersections/986-interval-list-intersections.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: 3 | res = [] 4 | a_ptr, b_ptr = 0, 0 5 | sa, sb = len(firstList), len(secondList) 6 | temp = [] 7 | while a_ptr < sa and b_ptr < sb: 8 | if secondList[b_ptr][0] <= firstList[a_ptr][1] and firstList[a_ptr][0] <= secondList[b_ptr][1]: 9 | temp.append(max(firstList[a_ptr][0], secondList[b_ptr][0])) 10 | temp.append(min(firstList[a_ptr][1], secondList[b_ptr][1])) 11 | res.append(temp) 12 | temp = [] 13 | if firstList[a_ptr][1] > secondList[b_ptr][1]: 14 | b_ptr += 1 15 | else: 16 | a_ptr += 1 17 | return res -------------------------------------------------------------------------------- /986-interval-list-intersections/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /DoublyLinkedList Insertion: -------------------------------------------------------------------------------- 1 | # import requests 2 | # import mysql.connector 3 | # import pandas as pd 4 | 5 | class NodeList(): 6 | def __init__(self, data): 7 | self.data = data 8 | self.next = None 9 | self.prev = None 10 | 11 | class List(): 12 | def __init__(self): 13 | self.head = None 14 | 15 | def insert_h(self, vl): 16 | node = NodeList(data = vl) 17 | node.next = self.head 18 | 19 | if self.head is not None: 20 | self.head.prev = node 21 | else: 22 | self.head = node 23 | 24 | def insert_t(self, val): 25 | #create a new node 26 | node = NodeList(data = val) 27 | #Storing the original head 28 | last = self.head 29 | 30 | #Empty list 31 | if self.head is None: 32 | node.prev = None 33 | self.head = node 34 | return 35 | 36 | #reach the last node in the current list 37 | while last.next is not None: 38 | last = last.next 39 | 40 | last.next = node 41 | node.prev = last 42 | 43 | 44 | -------------------------------------------------------------------------------- /Easy/BinarySearch: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | low = 0 4 | high = len(nums) - 1 5 | while low <= high: 6 | mid = (low + high) // 2 7 | if target < nums[mid]: 8 | high = mid - 1 9 | elif target > nums[mid]: 10 | low = mid + 1 11 | elif target == nums[mid]: 12 | return nums.index(target) 13 | return -1 14 | -------------------------------------------------------------------------------- /Easy/FirstBadVersion: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstBadVersion(self, n: int) -> int: 3 | high = n + 1 4 | low = 1 5 | while low <= high: 6 | mid = (low + high) // 2 7 | if isBadVersion(mid): 8 | high = mid - 1 9 | else: 10 | low = mid + 1 11 | mid = low 12 | return mid 13 | -------------------------------------------------------------------------------- /Easy/Number of 1 Bits: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, n: int) -> int: 3 | return len(''.join(str(bin(n)).split('0')))-1 4 | -------------------------------------------------------------------------------- /Easy/RansomNote: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canConstruct(self, ransomNote: str, magazine: str) -> bool: 3 | ransomNote = list(ransomNote) 4 | magazine = list(magazine) 5 | for k in ransomNote: 6 | if k not in magazine: 7 | return False 8 | else: 9 | magazine.remove(k) 10 | #ransomNote.remove(k) 11 | return True 12 | -------------------------------------------------------------------------------- /Easy/SearchInsertPosition: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchInsert(self, nums: List[int], target: int) -> int: 3 | low = 0 4 | high = len(nums) - 1 5 | mid = (low + high) // 2 6 | while low <= high: 7 | if target < nums[mid]: 8 | high = mid - 1 9 | elif target > nums[mid]: 10 | low = mid + 1 11 | elif target == nums[mid]: 12 | return mid 13 | mid = (low + high) // 2 14 | return mid + 1 15 | -------------------------------------------------------------------------------- /Easy/SortArrayByParty: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortArrayByParity(self, A: List[int]) -> List[int]: 3 | le = [] 4 | lo = [] 5 | for i in range(len(A)): 6 | if A[i]%2 == 0: 7 | le.append(A[i]) 8 | else: 9 | lo.append(A[i]) 10 | return le + lo 11 | -------------------------------------------------------------------------------- /Easy/TwoSum: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | new = sorted(nums) 4 | i = 0 5 | j = len(nums) - 1 6 | ls = [] 7 | while j > i: 8 | l = new[i] 9 | m = new[j] 10 | k = l + m 11 | if k == target: 12 | ls.append(nums.index(l)) 13 | nums[nums.index(l)] = '_' 14 | ls.append(nums.index(m)) 15 | return ls 16 | else: 17 | if k > target: 18 | j-=1 19 | else: 20 | i+=1 21 | -------------------------------------------------------------------------------- /Helpful.md: -------------------------------------------------------------------------------- 1 | To Generate list of chars with numbers 2 | ```python 3 | characters = {} 4 | for character in string.ascii.lowercase: 5 | characters[character] = 0 6 | 7 | dict = {chr(ord('a') + i) : chr(ord('a') + i) for i in range(26)} 8 | 9 | ``` 10 | #merge Intervals: 11 | https://leetcode.com/problems/insert-interval/ 12 | https://leetcode.com/problems/non-overlapping-intervals/ 13 | https://leetcode.com/problems/meeting-rooms-ii/ [course] 14 | https://leetcode.com/discuss/interview-question/396248/Facebook-or-Phone-Screen-or-Point-in-max-overlapping-intervals 15 | https://leetcode.com/discuss/interview-question/124552/minimum-number-of-train-stops 16 | https://leetcode.com/problems/maximum-profit-in-job-scheduling/ 17 | https://leetcode.com/problems/employee-free-time/ 18 | 19 | #Cyclic Sort 20 | https://leetcode.com/problems/find-all-duplicates-in-an-array/submissions/ 21 | https://leetcode.com/problems/kth-missing-positive-number/ 22 | https://leetcode.com/problems/kth-missing-positive-number/ 23 | 24 | #Reverse LinkedList 25 | https://leetcode.com/problems/reverse-linked-list-ii/ 26 | https://leetcode.com/problems/reverse-nodes-in-k-group/ 27 | 28 | #Heaps 29 | https://leetcode.com/problems/find-median-from-data-stream/ 30 | https://leetcode.com/problems/sliding-window-median/ 31 | https://leetcode.com/problems/ipo/ 32 | https://www.youtube.com/watch?v=e7ZYZmGImSE&ab_channel=ImranSarwar 33 | https://leetcode.com/problems/find-right-interval/ 34 | 35 | #Subset 36 | https://leetcode.com/problems/subsets/ 37 | https://leetcode.com/problems/subsets-ii/ 38 | 39 | 40 | -------------------------------------------------------------------------------- /hard/median-of-two-sorted-arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchInsert(self, nums: List[int], target: int,priority) -> int: 3 | low = 0 4 | high = len(nums) - 1 5 | mid = (low + high) // 2 6 | while low <= high: 7 | if target < nums[mid]: 8 | high = mid - 1 9 | elif target > nums[mid]: 10 | low = mid + 1 11 | elif target == nums[mid]: 12 | if priority: 13 | low = mid +1 14 | else: 15 | high = mid -1 16 | mid = (low + high) // 2 17 | return mid + 1 18 | 19 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 20 | n = len(nums1) + len(nums2) 21 | needed = [] 22 | med = [] 23 | needed.append(n // 2) 24 | if n % 2 == 0: 25 | needed.append(n // 2 - 1) 26 | for i in range(len(nums1)): 27 | m = i + self.searchInsert(nums2, nums1[i],True) 28 | if m in needed: 29 | needed.remove(m) 30 | med.append(nums1[i]) 31 | for i in range(len(nums2)): 32 | m = i + self.searchInsert(nums1, nums2[i],False) 33 | if m in needed: 34 | needed.remove(m) 35 | med.append(nums2[i]) 36 | return sum(med) / len(med) 37 | -------------------------------------------------------------------------------- /medium/Add Two Numbers: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | 7 | class Solution: 8 | def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: 9 | a1 = "" 10 | a2 = "" 11 | while l1.next != None: 12 | a1 += str(l1.val) 13 | l1 = l1.next 14 | while l2.next != None: 15 | a2 += str(l2.val) 16 | l2 = l2.next 17 | a1 += str(l1.val) 18 | a2 += str(l2.val) 19 | a1 = a1[::-1] 20 | a2 = a2[::-1] 21 | a3 = int(a1) + int(a2) 22 | a3 = list(str(a3)) 23 | x = ListNode() 24 | for i in range(0,len(a3)): 25 | if i == len(a3)-1: 26 | x.val = a3[i] 27 | else: 28 | temp = ListNode() 29 | temp.val = a3[i] 30 | temp.next = x.next 31 | x.next = temp 32 | return x 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /medium/BinaryTree_Right_Side: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def rightSideView(self, root: Optional[TreeNode]) -> List[int]: 9 | result = [] 10 | if root is None: 11 | return 12 | 13 | queue = deque() 14 | queue.append(root) 15 | while queue: 16 | levelSize = len(queue) 17 | count = 0 18 | # connect all nodes of this level 19 | for _ in range(levelSize): 20 | currentNode = queue.popleft() 21 | count += 1 22 | if count == levelSize: 23 | result.append(currentNode.val) 24 | 25 | # insert the children of current node in the queue 26 | if currentNode.left: 27 | queue.append(currentNode.left) 28 | if currentNode.right: 29 | queue.append(currentNode.right) 30 | return result 31 | -------------------------------------------------------------------------------- /medium/Coin Change.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def __init__(self): 4 | self.ls = {0: (0, True)} 5 | def coins(self, c, a): 6 | if a in self.ls.keys(): 7 | return self.ls[a] 8 | else: 9 | ans = [] 10 | for i in range(len(c)): 11 | if a >= c[i]: 12 | k = self.coins(c, a - c[i]) 13 | f = k[1] 14 | if f: 15 | ans.append(k[0]+1) 16 | if len(ans) == 0: 17 | self.ls[a] = (0, False) 18 | return (0, False) 19 | m = min(ans) 20 | self.ls[a] = (m, True) 21 | return (m, True) 22 | 23 | def coinChange(self, c: List[int], a: int) -> int: 24 | k = self.coins(c, a) 25 | if k[1]: 26 | return k[0] 27 | return -1 28 | -------------------------------------------------------------------------------- /medium/Domino and Trimino: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numTilings(self, n: int) -> int: 3 | num = {} 4 | md = 1e9 5 | md += 7 6 | num[0] = 0 7 | num[1] = 1 8 | num[2] = 2 9 | num[3] = 5 10 | if n <= 3: 11 | return num[n] 12 | for i in range(4, n+1): 13 | num[i] = 2*num[i-1] + num[i-3] 14 | num[i]%=md 15 | return int(num[n]) 16 | 17 | -------------------------------------------------------------------------------- /medium/Heap_HireK: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def totalCost(self, costs: List[int], k: int, candidates: int) -> int: 3 | heap = [] 4 | left = 0 5 | 6 | for i, v in enumerate(costs): 7 | if len(heap) < candidates: 8 | heap.append([costs[i], i]) 9 | left = i 10 | 11 | 12 | right = len(costs) 13 | while right > left + 1 and len(heap) < candidates * 2: 14 | right -= 1 15 | heap.append([costs[right], right]) 16 | 17 | res = 0 18 | heapify(heap) 19 | 20 | while k: 21 | cost, index = heappop(heap) 22 | res += cost 23 | k -= 1 24 | if index <= left: 25 | if left + 1 < right: 26 | left += 1 27 | heappush(heap,[costs[left], left]) 28 | elif index >= right: 29 | if right - 1 > left: 30 | right -= 1 31 | heappush(heap, [costs[right], right]) 32 | 33 | 34 | return res 35 | -------------------------------------------------------------------------------- /number-of-provinces/number-of-provinces.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findCircleNum(self, isConnected: List[List[int]]) -> int: 3 | def dfs(a): 4 | visited.add(a) 5 | for b in range(len(isConnected)): 6 | if b not in visited and isConnected[a][b]: 7 | dfs(b) 8 | 9 | 10 | prov = 0 11 | visited = set() 12 | for a in range(len(isConnected)): #row by row 13 | if a not in visited: 14 | prov += 1 15 | dfs(a) 16 | 17 | return prov 18 | --------------------------------------------------------------------------------