├── .gitignore ├── README.md ├── adventofcode ├── 2021 │ ├── 1_1.py │ └── 1_2.py └── 2022 │ ├── day01_1.go │ ├── day01_1.input │ ├── day01_2.go │ ├── day02_1.go │ ├── day02_1.input │ ├── day02_2.go │ ├── day02_2.input │ ├── day04.py │ ├── day05.py │ ├── day06.go │ ├── day07.go │ ├── day08.go │ └── run.go ├── bin ├── index.py ├── install-hook.sh ├── leetcode-anki.py └── readme-check-hook.py ├── binarysearch.com ├── Nearest-Bus-Stop-From-a-House.py ├── Non-Adjacent-Combination-Sum.py ├── Smallest-Number-With-No-Adjacent-Duplicates.py └── Sublist-with-Largest-Min-Length-Product.py ├── codeforces └── 103715 │ ├── A.py │ ├── B.py │ ├── B_1.input │ ├── B_2.input │ ├── B_3.input │ ├── C.py │ ├── C_1.input │ ├── C_2.input │ ├── C_3.input │ ├── D.py │ ├── D_1.input │ ├── D_2.input │ └── D_3.input ├── codejam ├── 2020-04-04 │ ├── ESAb_ATAd │ │ └── esab_atad.py │ ├── Indicium │ │ ├── indicium.py │ │ ├── indicium_test.input │ │ ├── indicium_test.output │ │ └── indicium_test.py │ ├── Nesting_Depth │ │ ├── nesting_depth.py │ │ ├── nesting_depth_test.input │ │ ├── nesting_depth_test.output │ │ └── nesting_depth_test.py │ ├── Parenting_Partnering_Returns │ │ ├── parenting_partnering_returns.py │ │ ├── parenting_partnering_returns_test.input │ │ ├── parenting_partnering_returns_test.output │ │ └── parenting_partnering_returns_test.py │ └── Vestigium │ │ ├── vestigium.py │ │ ├── vestigium_test.input │ │ ├── vestigium_test.output │ │ └── vestigium_test.py ├── 2020-04-19 │ └── Expogo │ │ ├── expogo.input │ │ └── expogo.py └── 2022-04-02 │ └── Punched_Cards │ ├── punched_cards.input │ └── punched_cards.py ├── cormen-introduction ├── 22.1-3.py ├── 32_3-1.py ├── binary-search.py ├── binary_tree.py ├── deque.py ├── heap.py ├── kmp.py ├── linear-search.py ├── linked_list.py ├── merge-sort.py ├── object_array_representation.py ├── print_binary_tree.py ├── queue-two-stacks.py ├── queue.py ├── really-simple-sort.py ├── selection-sort.py ├── stack-two-queue.py ├── stack.py └── tree.py ├── coursera └── c-plus-plus-white │ ├── week1 │ ├── A+B.cpp │ ├── binary.cpp │ ├── equation.cpp │ ├── gcd.cpp │ ├── min-string.cpp │ ├── second-match.cpp │ └── smallest-string-with-a-given-numeric-value.py │ └── week2 │ ├── anagram.cpp │ ├── average-temperature.cpp │ ├── calendar.cpp │ ├── capital-list.cpp │ ├── factorial.cpp │ ├── move-strings.cpp │ ├── palindome-filter.cpp │ ├── queue.cpp │ └── reverse.cpp ├── crypto └── ethereumbook │ ├── Dockerfile │ ├── README.md │ ├── nft_test │ ├── contracts │ │ ├── Migrations.sol │ │ └── NFT.sol │ ├── migrations │ │ ├── 1_initial_migration.js │ │ └── 2_deploy_contracts.js │ ├── package.json │ └── truffle-config.js │ ├── requirements.txt │ ├── run_devserver.sh │ ├── test.py │ └── test.sol ├── design_patterns ├── decorator.py └── observer.py ├── hacker-cup └── 2020 │ └── qualification_round │ ├── A │ ├── travel_restrictions.py │ ├── travel_restrictions_input.txt │ ├── travel_restrictions_output.txt │ ├── travel_restrictions_sample_input.txt │ ├── travel_restrictions_validation_input.txt │ └── travel_restrictions_validation_output.txt │ ├── B │ ├── alchemy.py │ ├── alchemy_sample_input.txt │ ├── alchemy_validation_input.txt │ └── alchemy_validation_output.txt │ ├── C │ ├── timber.py │ ├── timber_output.txt │ ├── timber_sample_input.txt │ ├── timber_sample_output.txt │ ├── timber_validation_input.txt │ └── timber_validation_output.txt │ ├── D1 │ ├── running_on_fumes_chapter_1.py │ ├── running_on_fumes_chapter_1_sample_input.txt │ ├── running_on_fumes_chapter_1_validation_input.txt │ └── running_on_fumes_chapter_1_validation_output.txt │ └── D2 │ ├── running_on_fumes_chapter_2.py │ ├── running_on_fumes_chapter_2_sample_input.txt │ ├── running_on_fumes_chapter_2_validation_input.txt │ └── running_on_fumes_chapter_2_validation_output.txt ├── hackerrank ├── 2d-array.py ├── climbing-the-leaderboard.py ├── counting-valleys.py ├── ctci-array-left-rotation.py ├── ctci-bubble-sort.py ├── ctci-merge-sort.py ├── jumping-on-the-clouds.py ├── magic-square-forming.py ├── repeated-string.py └── sock-merchant.py ├── l33tcode ├── 01-matrix.py ├── 132-pattern.py ├── 24-game.py ├── 3sum-closest.py ├── 3sum-with-multiplicity.py ├── 3sum.py ├── 4-keys-keyboard.py ├── 4sum-ii.py ├── 4sum.py ├── accounts-merge.py ├── add-and-search-word-data-structure-design.py ├── add-binary.py ├── add-bold-tag-in-string.py ├── add-digits.py ├── add-one-row-to-tree.py ├── add-to-array-form-of-integer.py ├── add-two-numbers-ii.py ├── add-two-numbers.py ├── advantage-shuffle.py ├── airplane-seat-assignment-probability.py ├── alert-using-same-key-card-three-or-more-times-in-a-one-hour-period.py ├── alien-dictionary.py ├── all-elements-in-two-binary-search-trees.py ├── all-paths-from-source-lead-to-destination.py ├── all-paths-from-source-to-target.go ├── all-paths-from-source-to-target.py ├── all-possible-full-binary-trees.py ├── ambiguous-coordinates.py ├── android-unlock-patterns.py ├── angle-between-hands-of-a-clock.py ├── apply-operations-to-an-array.py ├── arithmetic-slices-ii-subsequence.py ├── arithmetic-slices.py ├── arithmetic-subarrays.py ├── arranging-coins.py ├── array-nesting.py ├── asteroid-collision.py ├── average-of-levels-in-binary-tree.py ├── average-waiting-time.py ├── backspace-string-compare.py ├── bag-of-tokens.py ├── balance-a-binary-search-tree.py ├── balanced-binary-tree.py ├── basic-calculator-ii.py ├── basic-calculator.py ├── battleships-in-a-board.go ├── beautiful-arrangement.py ├── best-meeting-point.py ├── best-position-for-a-service-centre.py ├── best-sightseeing-pair.py ├── best-time-to-buy-and-sell-stock-ii.py ├── best-time-to-buy-and-sell-stock-iii.py ├── best-time-to-buy-and-sell-stock-iv.py ├── best-time-to-buy-and-sell-stock-with-cooldown.py ├── best-time-to-buy-and-sell-stock-with-transaction-fee.py ├── best-time-to-buy-and-sell-stock.py ├── binary-prefix-divisible-by-5.py ├── binary-search-tree-iterator.py ├── binary-search-tree-to-greater-sum-tree.py ├── binary-search.py ├── binary-string-with-substrings-representing-1-to-n.py ├── binary-tree-coloring-game.py ├── binary-tree-inorder-traversal.py ├── binary-tree-level-order-traversal-ii.py ├── binary-tree-level-order-traversal.py ├── binary-tree-longest-consecutive-sequence-ii.py ├── binary-tree-maximum-path-sum.py ├── binary-tree-postorder-traversal.py ├── binary-tree-preorder-traversal.py ├── binary-tree-pruning.go ├── binary-tree-right-side-view.py ├── binary-tree-tilt.py ├── binary-tree-vertical-order-traversal.py ├── binary-tree-zigzag-level-order-traversal.py ├── binary-trees-with-factors.py ├── bitwise-and-of-numbers-range.py ├── bitwise-ors-of-subarrays.py ├── boats-to-save-people.py ├── brace-expansion.py ├── broken-calculator.py ├── buddy-strings.py ├── build-an-array-with-stack-operations.py ├── buildings-with-an-ocean-view.py ├── bulls-and-cows.py ├── burst-balloons.py ├── bus-routes.py ├── camelcase-matching.py ├── campus-bikes-ii.py ├── campus-bikes.py ├── can-convert-string-in-k-moves.py ├── can-i-win.py ├── can-place-flowers.py ├── candy.py ├── capacity-to-ship-packages-within-d-days.go ├── capacity-to-ship-packages-within-d-days.py ├── car-fleet.py ├── car-pooling.py ├── champagne-tower.py ├── cheapest-flights-within-k-stops.py ├── check-array-formation-through-concatenation.py ├── check-completeness-of-a-binary-tree.py ├── check-if-a-string-contains-all-binary-codes-of-size-k.py ├── check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree.py ├── check-if-all-1s-are-at-least-length-k-places-away.py ├── check-if-it-is-a-good-array.py ├── check-if-it-is-a-straight-line.go ├── check-if-there-is-a-valid-partition-for-the-array.py ├── check-if-two-string-arrays-are-equivalent.py ├── cherry-pickup-ii.py ├── circle-and-rectangle-overlapping.py ├── circular-array-loop.py ├── climbing-stairs.py ├── clone-graph.py ├── closest-binary-search-tree-value-ii.py ├── closest-binary-search-tree-value.py ├── closest-node-to-path-in-tree.py ├── clumsy-factorial.py ├── coin-change-2.go ├── coin-change-ii.py ├── coin-change.py ├── combination-sum-ii.py ├── combination-sum-iii.py ├── combination-sum-iv.py ├── combination-sum.py ├── combinations.py ├── compare-version-numbers.py ├── complement-of-base-10-integer.py ├── concatenation-of-consecutive-binary-numbers.py ├── consecutive-characters.py ├── consecutive-numbers-sum.py ├── constrained-subsequence-sum.py ├── construct-binary-search-tree-from-preorder-traversal.py ├── construct-binary-tree-from-inorder-and-postorder-traversal.py ├── construct-binary-tree-from-preorder-and-postorder-traversal.go ├── construct-binary-tree-from-string.py ├── construct-k-palindrome-strings.py ├── construct-smallest-number-from-di-string.py ├── construct-string-from-binary-tree.py ├── construct-the-lexicographically-largest-valid-sequence.go ├── container-with-most-water.py ├── contains-duplicate-iii.py ├── contiguous-array.py ├── continuous-subarray-sum.py ├── convert-binary-number-in-a-linked-list-to-integer.py ├── convert-bst-to-greater-tree.py ├── coordinate-with-maximum-network-quality.py ├── copy-list-with-random-pointer.py ├── count-all-valid-pickup-and-delivery-options.py ├── count-and-say.py ├── count-complete-tree-nodes.py ├── count-good-nodes-in-binary-tree.py ├── count-integers-in-intervals.py ├── count-largest-group.py ├── count-nice-pairs-in-an-array.py ├── count-nodes-equal-to-average-of-subtree.py ├── count-number-of-bad-pairs.py ├── count-number-of-homogenous-substrings.py ├── count-number-of-teams.go ├── count-numbers-with-unique-digits.py ├── count-odd-numbers-in-an-interval-range.py ├── count-of-range-sum.py ├── count-of-smaller-numbers-after-self.py ├── count-servers-that-communicate.py ├── count-sorted-vowel-strings.py ├── count-square-submatrices-with-all-ones.go ├── count-sub-islands.py ├── count-submatrices-with-all-ones.py ├── count-substrings-that-differ-by-one-character.py ├── count-vowels-permutation.py ├── count-ways-to-make-array-with-product.py ├── counting-bits.py ├── counting_elements.py ├── couples-holding-hands.py ├── course-schedule-ii.py ├── course-schedule.py ├── cousins-in-binary-tree.go ├── create-sorted-array-through-instructions.py ├── critical-connections-in-a-network.py ├── daily-temperatures.go ├── daily-temperatures.py ├── decode-string.py ├── decode-ways-ii.py ├── decode-ways.py ├── decoded-string-at-index.py ├── deepest-leaves-sum.go ├── defuse-the-bomb.py ├── delete-columns-to-make-sorted.py ├── delete-node-in-a-bst.py ├── delete-node-in-a-linked-list.go ├── delete-nodes-and-return-forest.py ├── delete-tree-nodes.py ├── design-add-and-search-words-data-structure.py ├── design-an-expression-tree-with-evaluate-function.py ├── design-browser-history.py ├── design-circular-queue.py ├── design-excel-sum-formula.py ├── design-front-middle-back-queue.py ├── design-graph-with-shortest-path-calculator.py ├── design-hashset.py ├── design-hit-counter.py ├── design-in-memory-file-system.py ├── design-most-recently-used-queue.go ├── design-parking-system.py ├── design-phone-directory.py ├── design-search-autocomplete-system.py ├── design-underground-system.py ├── design-video-sharing-platform.py ├── destroy-sequential-targets.py ├── detect-capital.py ├── detect-cycles-in-2d-grid.py ├── determine-if-a-cell-is-reachable-at-a-given-time.py ├── determine-if-string-halves-are-alike.go ├── determine-if-two-strings-are-close.go ├── determine-if-two-strings-are-close.py ├── diagonal-traverse-ii.py ├── diagonal-traverse.py ├── diameter-of-binary-tree.py ├── dice-roll-simulation.py ├── distinct-numbers-in-each-subarray.py ├── distinct-subsequences.py ├── distribute-candies-to-people.py ├── distribute-candies.py ├── distribute-coins-in-binary-tree.py ├── distribute-repeating-integers.py ├── divide-chocolate.py ├── divide-two-integers.py ├── divisor-game.py ├── domino-and-tromino-tiling.py ├── dot-product-of-two-sparse-vectors.py ├── dota2-senate.py ├── dungeon-game.py ├── earliest-possible-day-of-full-bloom.go ├── edit-distance.py ├── element-appearing-more-than-25-in-sorted-array.py ├── eliminate-maximum-number-of-monsters.py ├── employee-free-time.py ├── encode-and-decode-strings.py ├── encode-and-decode-tinyurl.py ├── encode-n-ary-tree-to-binary-tree.py ├── encode-number.py ├── evaluate-division.py ├── evaluate-reverse-polish-notation.go ├── evaluate-reverse-polish-notation.py ├── evaluate-the-bracket-pairs-of-a-string.py ├── exam-room.py ├── excel-sheet-column-number.py ├── excel-sheet-column-title.py ├── expression-add-operators.py ├── extra-characters-in-a-string.py ├── fancy-sequence.py ├── fibonacci-number.py ├── filling-bookcase-shelves.py ├── find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.py ├── find-all-anagrams-in-a-string.go ├── find-all-duplicates-in-an-array.go ├── find-and-replace-in-string.py ├── find-and-replace-pattern.go ├── find-common-characters.py ├── find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.py ├── find-duplicate-subtrees.py ├── find-elements-in-a-contaminated-binary-tree.py ├── find-first-and-last-position-of-element-in-sorted-array.py ├── find-if-path-exists-in-graph.go ├── find-in-mountain-array.py ├── find-k-closest-elements.py ├── find-k-length-substrings-with-no-repeated-characters.py ├── find-k-pairs-with-smallest-sums.py ├── find-largest-value-in-each-tree-row.py ├── find-leaves-of-binary-tree.py ├── find-longest-awesome-substring.py ├── find-median-from-data-stream.py ├── find-minimum-in-rotated-sorted-array-ii.py ├── find-minimum-in-rotated-sorted-array.py ├── find-mode-in-binary-search-tree.py ├── find-nearest-right-node-in-binary-tree.py ├── find-peak-element.py ├── find-permutation.py ├── find-players-with-zero-or-one-losses.go ├── find-right-interval.py ├── find-root-of-n-ary-tree.py ├── find-smallest-common-element-in-all-rows.py ├── find-the-celebrity.py ├── find-the-difference.py ├── find-the-duplicate-number.go ├── find-the-longest-substring-containing-vowels-in-even-counts.py ├── find-the-most-competitive-subsequence.py ├── find-the-original-array-of-prefix-xor.py ├── find-the-punishment-number-of-an-integer.py ├── find-the-smallest-divisor-given-a-threshold.py ├── find-the-town-judge.go ├── find-the-winner-of-an-array-game.py ├── find-two-non-overlapping-sub-arrays-each-with-target-sum.py ├── find-unique-binary-string.py ├── finding-the-number-of-visible-mountains.py ├── first-bad-version.py ├── first-missing-positive.py ├── first-unique-character-in-a-string.go ├── first-unique-number.py ├── fizz-buzz.py ├── flatten-a-multilevel-doubly-linked-list.py ├── flatten-binary-tree-to-linked-list.py ├── flatten-nested-list-iterator.py ├── flip-equivalent-binary-trees.py ├── flipping-an-image.py ├── flood-fill.py ├── flower-planting-with-no-adjacent.py ├── friend-circles.py ├── frog-jump.py ├── fruit-into-baskets.py ├── game-of-life.py ├── gas-station.py ├── generate-parentheses.go ├── generate-parentheses.py ├── generate-random-point-in-a-circle.py ├── get-maximum-in-generated-array.py ├── goat-latin.py ├── graph-valid-tree.py ├── gray-code.py ├── greatest-sum-divisible-by-three.py ├── group-anagrams.py ├── group-the-people-given-the-group-size-they-belong-to.go ├── grumpy-bookstore-owner.py ├── guess-number-higher-or-lower.py ├── h-index-ii.go ├── h-index.py ├── hamming-distance.py ├── happy-number.py ├── heaters.py ├── height-checker.py ├── hexspeak.py ├── house-robber-ii.py ├── house-robber-iii.py ├── house-robber.py ├── image-overlap.py ├── implement-queue-using-stacks.go ├── implement-stack-using-queues.py ├── implement-strstr.py ├── implement-trie-prefix-tree.py ├── increasing-decreasing-string.py ├── increasing-order-search-tree.py ├── increasing-triplet-subsequence.py ├── inorder-successor-in-bst-ii.py ├── inorder-successor-in-bst.py ├── insert-delete-getrandom-o1-duplicates-allowed.py ├── insert-delete-getrandom-o1.py ├── insert-interval.py ├── insert-into-a-binary-search-tree.py ├── insert-into-a-sorted-circular-linked-list.py ├── insertion-sort-list.go ├── insertion-sort-list.py ├── insufficient-nodes-in-root-to-leaf-paths.py ├── integer-break.py ├── integer-to-english-words.py ├── integer-to-roman.py ├── interleaving-string.py ├── intersection-of-two-linked-lists.py ├── interval-list-intersections.py ├── invert-binary-tree.go ├── invert-binary-tree.py ├── is-graph-bipartite.py ├── is-subsequence.go ├── island-perimeter.py ├── isomorphic-strings.py ├── iterator-for-combination.py ├── jewels-and-stones.py ├── jump-game-ii.py ├── jump-game-iii.py ├── jump-game-iv.py ├── jump-game-vi.py ├── jump-game.go ├── jump-game.py ├── k-closest-points-to-origin.py ├── k-concatenation-maximum-sum.py ├── k-diff-pairs-in-an-array.py ├── k-th-symbol-in-grammar.py ├── keys-and-rooms.go ├── keys-and-rooms.py ├── kill-process.py ├── knight-dialer.py ├── knight-probability-in-chessboard.py ├── koko-eating-bananas.py ├── kth-ancestor-of-a-tree-node.py ├── kth-largest-element-in-an-array.py ├── kth-missing-positive-number.py ├── kth-smallest-element-in-a-bst.py ├── kth-smallest-number-in-multiplication-table.py ├── largest-divisible-subset.py ├── largest-number.py ├── largest-plus-sign.py ├── largest-rectangle-in-histogram.py ├── largest-submatrix-with-rearrangements.py ├── largest-sum-of-averages.py ├── largest-time-for-given-digits.py ├── last-moment-before-all-ants-fall-out-of-a-plank.py ├── last-stone-weight-ii.py ├── last-stone-weight.py ├── leaf-similar-trees.go ├── leaf-similar-trees.py ├── leftmost-column-with-at-least-a-one.py ├── length-of-last-word.py ├── length-of-longest-fibonacci-subsequence.py ├── letter-case-permutation.py ├── letter-combinations-of-a-phone-number.py ├── letter-tile-possibilities.py ├── lfu-cache.py ├── license-key-formatting.py ├── linked-list-cycle-ii.py ├── linked-list-cycle.py ├── linked-list-in-binary-tree.py ├── linked-list-random-node.py ├── logger-rate-limiter.py ├── longest-absolute-file-path.py ├── longest-arithmetic-sequence.py ├── longest-arithmetic-subsequence-of-given-difference.py ├── longest-arithmetic-subsequence.py ├── longest-common-prefix.py ├── longest-common-subsequence.py ├── longest-consecutive-sequence.py ├── longest-duplicate-substring.py ├── longest-happy-prefix.py ├── longest-happy-string.py ├── longest-harmonious-subsequence.py ├── longest-increasing-path-in-a-matrix.py ├── longest-increasing-subsequence.py ├── longest-line-of-consecutive-one-in-matrix.py ├── longest-mountain-in-array.py ├── longest-palindrome.py ├── longest-palindromic-subsequence.py ├── longest-palindromic-substring.go ├── longest-palindromic-substring.py ├── longest-repeating-character-replacement.py ├── longest-repeating-substring.py ├── longest-string-chain.py ├── longest-subarray-of-1s-after-deleting-one-element.py ├── longest-substring-with-at-least-k-repeating-characters.py ├── longest-substring-with-at-most-k-distinct-characters.py ├── longest-substring-with-at-most-two-distinct-characters.py ├── longest-substring-without-repeating-characters.py ├── longest-turbulent-subarray.py ├── longest-valid-parentheses.py ├── longest-zigzag-path-in-a-binary-tree.py ├── lowest-common-ancestor-of-a-binary-search-tree.py ├── lowest-common-ancestor-of-a-binary-tree.py ├── lowest-common-ancestor-of-deepest-leaves.py ├── lru-cache.py ├── majority-element-ii.py ├── majority-element.go ├── make-array-strictly-increasing.py ├── make-the-prefix-sum-non-negative.py ├── making-a-large-island.py ├── managers-with-at-least-5-direct-reports.sql ├── matrix-block-sum.py ├── max-consecutive-ones-ii.go ├── max-consecutive-ones-iii.py ├── max-dot-product-of-two-subsequences.py ├── max-increase-to-keep-city-skyline.py ├── max-number-of-k-sum-pairs.py ├── max-points-on-a-line.py ├── max-sum-of-a-pair-with-equal-sum-of-digits.go ├── max-sum-of-a-pair-with-equal-sum-of-digits.py ├── maximal-network-rank.py ├── maximal-rectangle.py ├── maximal-square.py ├── maximize-distance-to-closest-person.py ├── maximize-sum-of-array-after-k-negations.py ├── maximum-absolute-sum-of-any-subarray.py ├── maximum-average-subarray-ii.py ├── maximum-average-subtree.py ├── maximum-bags-with-full-capacity-of-rocks.go ├── maximum-binary-string-after-change.py ├── maximum-binary-tree.py ├── maximum-depth-of-binary-tree.py ├── maximum-difference-between-node-and-ancestor.py ├── maximum-distance-in-arrays.py ├── maximum-frequency-stack.py ├── maximum-gap.py ├── maximum-length-of-a-concatenated-string-with-unique-characters.py ├── maximum-length-of-pair-chain.py ├── maximum-length-of-repeated-subarray.py ├── maximum-length-of-subarray-with-positive-product.py ├── maximum-level-sum-of-a-binary-tree.py ├── maximum-number-of-balloons.py ├── maximum-number-of-coins-you-can-get.py ├── maximum-number-of-vowels-in-a-substring-of-given-length.py ├── maximum-performance-of-a-team.py ├── maximum-points-you-can-obtain-from-cards.py ├── maximum-product-of-splitted-binary-tree.py ├── maximum-product-of-three-numbers.py ├── maximum-product-subarray.py ├── maximum-profit-in-job-scheduling.py ├── maximum-repeating-substring.py ├── maximum-running-time-of-n-computers.py ├── maximum-subarray.py ├── maximum-sum-bst-in-binary-tree.py ├── maximum-sum-circular-subarray.go ├── maximum-white-tiles-covered-by-a-carpet.py ├── maximum-width-of-binary-tree.go ├── maximum-width-of-binary-tree.py ├── maximum-xor-of-two-numbers-in-an-array.py ├── mean-of-array-after-removing-some-elements.py ├── median-of-two-sorted-arrays.py ├── meeting-rooms-ii.py ├── meeting-rooms.py ├── meeting-scheduler.py ├── merge-intervals.py ├── merge-k-sorted-lists.py ├── merge-sorted-array.py ├── merge-two-2d-arrays-by-summing-values.py ├── merge-two-sorted-lists.py ├── middle-of-the-linked-list.go ├── middle-of-the-linked-list.py ├── min-cost-climbing-stairs.py ├── min-cost-to-connect-all-points.py ├── min-stack.py ├── minesweeper.py ├── minimize-deviation-in-array.py ├── minimize-max-distance-to-gas-station.py ├── minimize-the-maximum-difference-of-pairs.py ├── minimize-the-maximum-difference-of-pairs.rs ├── minimum-add-to-make-parentheses-valid.py ├── minimum-adjacent-swaps-for-k-consecutive-ones.py ├── minimum-ascii-delete-sum-for-two-strings.py ├── minimum-average-difference.go ├── minimum-cost-for-tickets.py ├── minimum-cost-to-hire-k-workers.py ├── minimum-cost-to-move-chips-to-the-same-position.py ├── minimum-cost-tree-from-leaf-values.py ├── minimum-deletions-to-make-character-frequencies-unique.py ├── minimum-deletions-to-make-string-balanced.py ├── minimum-depth-of-binary-tree.py ├── minimum-difference-between-largest-and-smallest-value-in-three-moves.py ├── minimum-difficulty-of-a-job-schedule.py ├── minimum-domino-rotations-for-equal-row.py ├── minimum-falling-path-sum-ii.py ├── minimum-falling-path-sum.py ├── minimum-flips-in-binary-tree-to-get-result.py ├── minimum-height-trees.py ├── minimum-insertions-to-balance-a-parentheses-string.py ├── minimum-moves-to-equal-array-elements-ii.py ├── minimum-number-of-arrows-to-burst-balloons.py ├── minimum-number-of-increments-on-subarrays-to-form-a-target-array.py ├── minimum-number-of-operations-to-make-array-continuous.py ├── minimum-number-of-operations-to-make-array-empty.py ├── minimum-number-of-refueling-stops.py ├── minimum-number-of-removals-to-make-mountain-array.py ├── minimum-number-of-taps-to-open-to-water-a-garden.py ├── minimum-number-of-vertices-to-reach-all-nodes.py ├── minimum-numbers-of-function-calls-to-make-target-array.py ├── minimum-operations-to-exceed-threshold-value-ii.py ├── minimum-operations-to-reduce-x-to-zero.py ├── minimum-path-sum.py ├── minimum-penalty-for-a-shop.py ├── minimum-remove-to-make-valid-parentheses.py ├── minimum-replacements-to-sort-the-array.py ├── minimum-score-triangulation-of-polygon.py ├── minimum-speed-to-arrive-on-time.py ├── minimum-swaps-to-group-all-1s-together.py ├── minimum-swaps-to-make-sequences-increasing.go ├── minimum-swaps-to-make-sequences-increasing.py ├── minimum-value-to-get-positive-step-by-step-sum.py ├── minimum-window-subsequence.py ├── minimum-window-substring.py ├── mirror-reflection.py ├── missing-number.py ├── missing-ranges.py ├── monotonic-array.py ├── most-profitable-path-in-a-tree.py ├── move-pieces-to-obtain-a-string.py ├── move-zeroes.py ├── moving-average-from-data-stream.py ├── multiply-strings.py ├── n-queens-ii.go ├── n-queens.go ├── n-queens.py ├── n-repeated-element-in-size-2n-array.py ├── n-th-tribonacci-number.py ├── nested-list-weight-sum.py ├── network-delay-time.py ├── next-greater-element-i.py ├── next-greater-element-iii.py ├── next-greater-node-in-linked-list.py ├── next-permutation.py ├── non-decreasing-array.py ├── non-overlapping-intervals.py ├── number-complement.go ├── number-of-1-bits.py ├── number-of-connected-components-in-an-undirected-graph.go ├── number-of-connected-components-in-an-undirected-graph.py ├── number-of-corner-rectangles.py ├── number-of-dice-rolls-with-target-sum.py ├── number-of-distinct-islands-ii.py ├── number-of-distinct-islands.py ├── number-of-enclaves.py ├── number-of-flowers-in-full-bloom.py ├── number-of-good-pairs.py ├── number-of-good-ways-to-split-a-string.py ├── number-of-islands-ii.py ├── number-of-islands.py ├── number-of-longest-increasing-subsequence.py ├── number-of-music-playlists.py ├── number-of-provinces.py ├── number-of-recent-calls.py ├── number-of-sets-of-k-non-overlapping-line-segments.py ├── number-of-squareful-arrays.py ├── number-of-steps-to-reduce-a-number-to-zero.py ├── number-of-students-doing-homework-at-a-given-time.py ├── number-of-students-unable-to-eat-lunch.py ├── number-of-sub-arrays-with-odd-sum.py ├── number-of-valid-words-for-each-puzzle.py ├── number-of-ways-to-buy-pens-and-pencils.py ├── number-of-ways-to-divide-a-long-corridor.py ├── number-of-ways-to-form-a-target-string-given-a-dictionary.py ├── number-of-ways-to-split-a-string.py ├── number-of-ways-to-stay-in-the-same-place-after-some-steps.py ├── numbers-at-most-n-given-digit-set.py ├── numbers-with-same-consecutive-differences.py ├── occurrences-after-bigram.py ├── odd-even-jump.py ├── odd-even-linked-list.go ├── one-edit-distance.py ├── ones-and-zeroes.py ├── online-stock-span.go ├── online-stock-span.py ├── open-the-lock.py ├── output-contest-matches.go ├── pacific-atlantic-water-flow.py ├── paint-house-ii.py ├── paint-house.go ├── painting-the-walls.py ├── pairs-of-songs-with-total-durations-divisible-by-60.py ├── palindrome-number.py ├── palindrome-pairs.py ├── palindrome-partitioning-ii.py ├── palindrome-partitioning.py ├── palindrome-permutation.py ├── palindromic-substrings.py ├── pancake-sorting.py ├── parallel-courses-ii.py ├── parallel-courses-iii.py ├── partition-array-for-maximum-sum.py ├── partition-array-into-three-parts-with-equal-sum.py ├── partition-equal-subset-sum.py ├── partition-labels.go ├── partition-labels.py ├── partition-list.py ├── partition-to-k-equal-sum-subsets.py ├── pascals-triangle-ii.py ├── pascals-triangle.py ├── path-sum-iii.py ├── path-sum-iv.go ├── path-sum.py ├── path-with-minimum-effort.py ├── peak-index-in-a-mountain-array.py ├── peeking-iterator.py ├── perfect-squares.py ├── perform-string-shifts.py ├── permutation-in-string.py ├── permutation-sequence.py ├── permutations-ii.py ├── permutations.py ├── pizza-with-3n-slices.py ├── plus-one-linked-list.cpp ├── plus-one-linked-list.py ├── plus-one.go ├── plus-one.py ├── poor-pigs.py ├── populating-next-right-pointers-in-each-node-ii.py ├── populating-next-right-pointers-in-each-node.py ├── possible-bipartition.go ├── possible-bipartition.py ├── power-of-four.go ├── power-of-two.go ├── powx-n.go ├── powx-n.py ├── predict-the-winner.py ├── previous-permutation-with-one-swap.py ├── print-binary-tree.py ├── print-immutable-linked-list-in-reverse.go ├── print-immutable-linked-list-in-reverse.py ├── prison-cells-after-n-days.py ├── product-of-array-except-self.py ├── product-of-the-last-k-numbers.py ├── pseudo-palindromic-paths-in-a-binary-tree.py ├── push-dominoes.py ├── queue-reconstruction-by-height.go ├── queue-reconstruction-by-height.py ├── rabbits-in-forest.go ├── random-pick-with-weight.py ├── random-point-in-non-overlapping-rectangles.py ├── range-addition.py ├── range-sum-of-bst.py ├── range-sum-of-sorted-subarray-sums.py ├── range-sum-query-2d-immutable.py ├── range-sum-query-2d-mutable.py ├── range-sum-query-immutable.py ├── range-sum-query-mutable.py ├── ransom-note.go ├── reach-a-number.py ├── reaching-points.py ├── read-n-characters-given-read4-ii-call-multiple-times.py ├── read-n-characters-given-read4.py ├── reconstruct-itinerary.py ├── recover-a-tree-from-preorder-traversal.py ├── recover-binary-search-tree.py ├── recyclable-and-low-fat-products.sql ├── reduce-array-size-to-the-half.py ├── reduction-operations-to-make-the-array-elements-equal.py ├── redundant-connection-ii.py ├── redundant-connection.py ├── reformat-date.py ├── regions-cut-by-slashes.py ├── regular-expression-matching.py ├── remove-all-adjacent-duplicates-in-string.py ├── remove-colored-pieces-if-both-neighbors-are-the-same-color.py ├── remove-covered-intervals.py ├── remove-duplicate-letters.py ├── remove-duplicates-from-sorted-array-ii.py ├── remove-duplicates-from-sorted-array.py ├── remove-duplicates-from-sorted-list-ii.py ├── remove-duplicates-from-sorted-list.py ├── remove-element.py ├── remove-interval.py ├── remove-k-digits.go ├── remove-k-digits.py ├── remove-linked-list-elements.py ├── remove-nth-node-from-end-of-list.py ├── remove-outermost-parentheses.py ├── remove-palindromic-subsequences.py ├── remove-stones-to-minimize-the-total.py ├── reorder-list.py ├── reordered-power-of-2.py ├── reorganize-string.go ├── reorganize-string.py ├── repeated-dna-sequences.py ├── repeated-string-match.py ├── repeated-substring-pattern.py ├── requirements.txt ├── restore-ip-addresses.py ├── restore-the-array-from-adjacent-pairs.py ├── reveal-cards-in-increasing-order.py ├── reverse-bits.py ├── reverse-integer.py ├── reverse-linked-list-ii.py ├── reverse-linked-list.py ├── reverse-nodes-in-k-group.py ├── reverse-string-ii.py ├── reverse-string.py ├── reverse-words-in-a-string-ii.py ├── reverse-words-in-a-string-iii.py ├── reverse-words-in-a-string.py ├── richest-customer-wealth.py ├── robot-bounded-in-circle.py ├── robot-room-cleaner.py ├── roman-to-integer.py ├── rotate-array.py ├── rotate-image.py ├── rotate-list.py ├── rotting-oranges.py ├── running-sum-of-1d-array.py ├── same-tree.go ├── same-tree.py ├── score-after-flipping-matrix.go ├── score-after-flipping-matrix.py ├── score-of-parentheses.py ├── scramble-string.py ├── search-a-2d-matrix-ii.py ├── search-a-2d-matrix.py ├── search-in-a-binary-search-tree.py ├── search-in-a-sorted-array-of-unknown-size.py ├── search-in-rotated-sorted-array-ii.go ├── search-in-rotated-sorted-array-ii.py ├── search-in-rotated-sorted-array.go ├── search-in-rotated-sorted-array.py ├── search-insert-position.go ├── search-insert-position.py ├── seat-reservation-manager.py ├── second-minimum-node-in-a-binary-tree.py ├── sentence-screen-fitting.py ├── sequence-reconstruction.py ├── sequential-digits.py ├── sequentially-ordinal-rank-tracker.py ├── serialize-and-deserialize-binary-tree.py ├── serialize-and-deserialize-bst.py ├── set-matrix-zeroes.py ├── set-mismatch.py ├── shopping-offers.py ├── short-encoding-of-words.py ├── shortest-distance-from-all-buildings.py ├── shortest-distance-to-a-character.py ├── shortest-palindrome.py ├── shortest-path-in-a-grid-with-obstacles-elimination.py ├── shortest-path-in-binary-matrix.py ├── shortest-path-visiting-all-nodes.py ├── shortest-unsorted-continuous-subarray.py ├── shortest-way-to-form-string.py ├── shortest-word-distance-ii.py ├── shortest-word-distance.py ├── similar-string-groups.py ├── simplify-path.py ├── single-element-in-a-sorted-array.py ├── single-number-ii.py ├── single-number-iii.py ├── single-number.py ├── single-row-keyboard.go ├── single-row-keyboard.py ├── sliding-window-maximum.py ├── sliding-window-median.py ├── slowest-key.py ├── smallest-common-region.py ├── smallest-integer-divisible-by-k.py ├── smallest-range-ii.py ├── smallest-subtree-with-all-the-deepest-nodes.py ├── smallest-sufficient-team.py ├── snapshot-array.go ├── snapshot-array.py ├── sort-an-array.py ├── sort-array-by-increasing-frequency.py ├── sort-array-by-parity-ii.py ├── sort-array-by-parity.py ├── sort-characters-by-frequency.py ├── sort-colors.py ├── sort-integers-by-the-number-of-1-bits.py ├── sort-integers-by-the-power-value.py ├── sort-items-by-groups-respecting-dependencies.py ├── sort-list.py ├── sort-the-matrix-diagonally.py ├── soup-servings.py ├── spiral-matrix-ii.py ├── spiral-matrix.py ├── split-array-into-consecutive-subsequences.py ├── split-array-largest-sum.py ├── split-linked-list-in-parts.py ├── sqrtx.py ├── squares-of-a-sorted-array.py ├── squirrel-simulation.py ├── stone-game-ii.py ├── stone-game-iv.py ├── stone-game.py ├── strange-printer.py ├── stream-of-characters.py ├── string-to-integer-atoi.py ├── string-transforms-into-another-string.py ├── strobogrammatic-number.py ├── strong-password-checker.py ├── student-attendance-record-i.py ├── student-attendance-record-ii.py ├── subarray-product-less-than-k.py ├── subarray-sum-equals-k.py ├── subarray-sums-divisible-by-k.py ├── subarray-with-elements-greater-than-varying-threshold.py ├── subdomain-visit-count.py ├── subsets-ii.py ├── subsets.go ├── subsets.py ├── substring-with-concatenation-of-all-words.py ├── sudoku-solver.py ├── sum-of-absolute-differences-in-a-sorted-array.py ├── sum-of-distances-in-tree.py ├── sum-of-left-leaves.py ├── sum-of-nodes-with-even-valued-grandparent.go ├── sum-of-root-to-leaf-binary-numbers.py ├── sum-root-to-leaf-numbers.py ├── summary-ranges.py ├── surrounded-regions.py ├── swap-for-longest-repeated-character-substring.py ├── swap-nodes-in-pairs.go ├── swap-nodes-in-pairs.py ├── swapping-nodes-in-a-linked-list.py ├── symmetric-tree.py ├── synonymous-sentences.py ├── tallest-billboard.py ├── target-sum.go ├── target-sum.py ├── task-scheduler.py ├── teemo-attacking.py ├── text-justification.py ├── the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.py ├── the-k-weakest-rows-in-a-matrix.py ├── the-kth-factor-of-n.py ├── the-maze-ii.py ├── the-maze-iii.py ├── the-maze.py ├── the-most-similar-path-in-a-graph.py ├── the-skyline-problem.py ├── thousand-separator.py ├── tiling-a-rectangle-with-the-fewest-squares.py ├── time-needed-to-inform-all-employees.py ├── to-lower-case.py ├── toeplitz-matrix.py ├── top-k-frequent-elements.py ├── top-k-frequent-words.py ├── toss-strange-coins.py ├── total-hamming-distance.py ├── trapping-rain-water.py ├── triangle.py ├── trim-a-binary-search-tree.py ├── two-city-scheduling.py ├── two-sum-ii-input-array-is-sorted.py ├── two-sum-iii-data-structure-design.py ├── two-sum-iv-input-is-a-bst.py ├── two-sum-less-than-k.py ├── two-sum.py ├── ugly-number-ii.py ├── uncrossed-lines.py ├── unique-binary-search-trees-ii.py ├── unique-binary-search-trees.go ├── unique-binary-search-trees.py ├── unique-email-addresses.py ├── unique-length-3-palindromic-subsequences.py ├── unique-morse-code-words.py ├── unique-number-of-occurrences.go ├── unique-paths-ii.py ├── unique-paths-iii.py ├── unique-paths.py ├── valid-anagram.py ├── valid-boomerang.py ├── valid-mountain-array.py ├── valid-number.py ├── valid-palindrome-ii.py ├── valid-palindrome-iii.py ├── valid-palindrome.py ├── valid-parentheses.py ├── valid-parenthesis-string.py ├── valid-perfect-square.py ├── valid-square.py ├── valid-sudoku.py ├── validate-binary-search-tree.py ├── validate-binary-tree-nodes.py ├── validate-ip-address.py ├── verifying-an-alien-dictionary.py ├── vertical-order-traversal-of-a-binary-tree.py ├── video-stitching.py ├── vowel-spellchecker.py ├── walking-robot-simulation.py ├── walls-and-gates.py ├── web-crawler-multithreaded.go ├── widest-vertical-area-between-two-points-containing-no-points.py ├── wiggle-sort.py ├── wiggle-subsequence.py ├── wildcard-matching.py ├── word-break-ii.py ├── word-break.py ├── word-ladder-ii.py ├── word-ladder.py ├── word-pattern.py ├── word-search-ii.py ├── word-search.go ├── word-search.py ├── word-squares.py ├── word-subsets.py ├── zigzag-conversion.py └── zigzag-iterator.py ├── l33tcode_rs ├── Cargo.lock ├── Cargo.toml └── src │ ├── divide_array_into_equal_pairs.rs │ ├── lib.rs │ ├── longest_nice_subarray.rs │ ├── minimum_number_of_operations_to_make_elements_in_array_distinct.rs │ └── partition_array_according_to_given_pivot.rs ├── pramp ├── array-index-and-element-equality.py ├── array-of-array-products.py ├── busiest-time-in-the-mall.py └── largest-smaller-bst-key.py ├── presentations └── faang_learning_group │ └── quicksort │ ├── basic_quicksort.py │ ├── complexity_analisys.md │ ├── extra.md │ ├── intro.md │ ├── k-select.md │ ├── k-select.py │ ├── links.md │ ├── problems.md │ ├── quicksort.py │ └── randomized_quicksort.py ├── setup.cfg ├── tlpi └── fileio │ └── tee.c └── yandex └── qualification-for-mentors ├── component-path.go ├── component-path.py ├── component-path_1.input ├── component-path_2.input ├── component-path_3.input ├── matrix-multiplication.go ├── matrix-multiplication.py ├── matrix-multiplication_1.input ├── matrix-multiplication_2.input ├── matrix-multiplication_3.input ├── matrix-multiplication_4.input ├── matrix-multiplication_5.input ├── palindrome-concatenation-rabin-karp.go ├── palindrome-concatenation-rabin-karp.py ├── palindrome-concatenation.go ├── palindrome-concatenation.py ├── palindrome-concatenation_1.input ├── palindrome-concatenation_2.input └── palindrome-concatenation_3.input /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .*.swp 3 | .cache 4 | .mypy 5 | .mypy_cache 6 | __pycache__ 7 | a.out 8 | .pyre 9 | l33tcode_rs/target/ 10 | src/** 11 | target/** 12 | -------------------------------------------------------------------------------- /adventofcode/2022/day01_1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "strconv" 9 | ) 10 | 11 | func day1_1() { 12 | file, err := os.Open("day01_1.input") 13 | 14 | if err != nil { 15 | log.Fatal(err) 16 | } 17 | 18 | defer file.Close() 19 | 20 | scanner := bufio.NewScanner(file) 21 | 22 | soFar := 0 23 | max := 0 24 | 25 | for scanner.Scan() { 26 | text := scanner.Text() 27 | 28 | if text == "" { 29 | soFar = 0 30 | } else { 31 | value, err := strconv.Atoi(text) 32 | 33 | if err != nil { 34 | log.Fatal(err) 35 | } 36 | 37 | soFar += value 38 | } 39 | 40 | if soFar > max { 41 | max = soFar 42 | } 43 | } 44 | 45 | if err := scanner.Err(); err != nil { 46 | log.Fatal(err) 47 | } 48 | 49 | fmt.Println(max) 50 | } 51 | -------------------------------------------------------------------------------- /adventofcode/2022/day02_1.input: -------------------------------------------------------------------------------- 1 | A Y 2 | B X 3 | C Z 4 | -------------------------------------------------------------------------------- /adventofcode/2022/run.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | day1_2() 5 | } 6 | -------------------------------------------------------------------------------- /bin/install-hook.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script to install the README.md file validation pre-commit hook 3 | 4 | # Set the source and destination paths 5 | HOOK_SOURCE="$(pwd)/bin/readme-check-hook.py" 6 | HOOK_DEST="$(git rev-parse --git-dir)/hooks/pre-commit" 7 | 8 | # Make sure the source file exists 9 | if [ ! -f "$HOOK_SOURCE" ]; then 10 | echo "Error: Hook source file not found at $HOOK_SOURCE" 11 | exit 1 12 | fi 13 | 14 | # Copy the hook to the git hooks directory 15 | cp "$HOOK_SOURCE" "$HOOK_DEST" 16 | 17 | # Make the hook executable 18 | chmod +x "$HOOK_DEST" 19 | 20 | echo "Pre-commit hook installed successfully!" 21 | echo "The hook will run automatically on each commit to validate README.md file references." 22 | -------------------------------------------------------------------------------- /binarysearch.com/Sublist-with-Largest-Min-Length-Product.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def solve(self, nums: List[int], pos: int) -> int: 6 | stack: List[int] = [] 7 | 8 | nums.append(0) 9 | max_area = max(nums[pos], min(nums) * len(nums)) 10 | 11 | for right_pos in range(len(nums)): 12 | while stack and nums[stack[-1]] > nums[right_pos]: 13 | height = nums[stack.pop()] 14 | left_pos = stack[-1] + 1 if stack else 0 15 | area = (right_pos - left_pos) * height 16 | 17 | if left_pos <= pos < right_pos: 18 | max_area = max(max_area, area) 19 | 20 | stack.append(right_pos) 21 | 22 | return max_area 23 | -------------------------------------------------------------------------------- /codeforces/103715/A.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from typing import List 3 | 4 | 5 | def read_int() -> int: 6 | return int(sys.stdin.readline()) 7 | 8 | 9 | def read_list_int(length: int) -> List[int]: 10 | result = list(map(int, sys.stdin.readline().split())) 11 | 12 | assert ( 13 | len(result) == length 14 | ), f"List must of of length of {length}, but got {result}" 15 | 16 | return result 17 | 18 | 19 | def main() -> None: 20 | x, y, t1, t2 = read_list_int(4) 21 | 22 | print(x * t1 + y * t2) 23 | 24 | 25 | if __name__ == "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /codeforces/103715/B_1.input: -------------------------------------------------------------------------------- 1 | 9 2 | No***way. 3 | -------------------------------------------------------------------------------- /codeforces/103715/B_2.input: -------------------------------------------------------------------------------- 1 | 17 2 | Yes,*****you*can. 3 | -------------------------------------------------------------------------------- /codeforces/103715/B_3.input: -------------------------------------------------------------------------------- 1 | 12 2 | qWe**,r*.Ry. 3 | -------------------------------------------------------------------------------- /codeforces/103715/C_1.input: -------------------------------------------------------------------------------- 1 | 5 12 2 | 3 1 4 2 5 3 | -------------------------------------------------------------------------------- /codeforces/103715/C_2.input: -------------------------------------------------------------------------------- 1 | 2 17 2 | 23 65 3 | -------------------------------------------------------------------------------- /codeforces/103715/C_3.input: -------------------------------------------------------------------------------- 1 | 1 5 2 | 5 3 | -------------------------------------------------------------------------------- /codeforces/103715/D_1.input: -------------------------------------------------------------------------------- 1 | 3 2 2 | 3 -2 4 3 | 1 6 4 | -------------------------------------------------------------------------------- /codeforces/103715/D_2.input: -------------------------------------------------------------------------------- 1 | 1 1 2 | 7 3 | -7 4 | -------------------------------------------------------------------------------- /codeforces/103715/D_3.input: -------------------------------------------------------------------------------- 1 | 4 3 2 | -1 -2 -3 -4 3 | -1 -2 -3 4 | -------------------------------------------------------------------------------- /codejam/2020-04-04/Indicium/indicium_test.input: -------------------------------------------------------------------------------- 1 | 13 2 | 3 6 3 | 2 3 4 | 2 2 5 | 2 3 6 | 2 4 7 | 3 3 8 | 3 4 9 | 3 5 10 | 3 6 11 | 3 7 12 | 3 8 13 | 3 9 14 | 50 50 15 | -------------------------------------------------------------------------------- /codejam/2020-04-04/Indicium/indicium_test.output: -------------------------------------------------------------------------------- 1 | Case #1: POSSIBLE 2 | 3 1 2 3 | 1 2 3 4 | 2 3 1 5 | Case #2: IMPOSSIBLE 6 | -------------------------------------------------------------------------------- /codejam/2020-04-04/Indicium/indicium_test.py: -------------------------------------------------------------------------------- 1 | from indicium import find_possible_sums, find_possible_fill 2 | 3 | 4 | class TestSolution: 5 | def test_find_possible_sums1(self): 6 | assert find_possible_sums(10, 2, 5) == [[2, 2, 2, 2, 2]] 7 | 8 | def test_find_possible_sums2(self): 9 | for i in range(1): 10 | assert find_possible_sums(2500, 50, 50) == [[50] * 50] 11 | 12 | def test_find_possible_fill1(self): 13 | assert find_possible_fill(3, [[2,2,2]]) == [[2,1,3], [3,2,1], [1,3,2]] 14 | 15 | def test_find_possible_fill2(self): 16 | assert find_possible_fill(50, find_possible_sums(50, 50, 50)) == [[2,1,3], [3,2,1], [1,3,2]] 17 | -------------------------------------------------------------------------------- /codejam/2020-04-04/Nesting_Depth/nesting_depth_test.input: -------------------------------------------------------------------------------- 1 | 8 2 | 0000 3 | 101 4 | 111000 5 | 1 6 | 021 7 | 312 8 | 4 9 | 221 10 | lol 11 | -------------------------------------------------------------------------------- /codejam/2020-04-04/Nesting_Depth/nesting_depth_test.output: -------------------------------------------------------------------------------- 1 | Case #1: 0000 2 | Case #2: (1)0(1) 3 | Case #3: (111)000 4 | Case #4: (1) 5 | Case #5: 0((2)1) 6 | Case #6: (((3))1(2)) 7 | Case #7: ((((4)))) 8 | Case #8: ((22)1) 9 | -------------------------------------------------------------------------------- /codejam/2020-04-04/Parenting_Partnering_Returns/parenting_partnering_returns_test.input: -------------------------------------------------------------------------------- 1 | 8 2 | 3 3 | 360 480 4 | 420 540 5 | 600 660 6 | 3 7 | 0 1440 8 | 1 3 9 | 2 4 10 | 5 11 | 99 150 12 | 1 100 13 | 100 301 14 | 2 5 15 | 150 250 16 | 2 17 | 0 720 18 | 720 1440 19 | 0 20 | 1 21 | 1 1 22 | 6 23 | 0 100 24 | 90 200 25 | 190 300 26 | 210 400 27 | 350 1000 28 | 700 800 29 | 2 30 | 1 2 31 | 1 2 32 | 1 33 | 1 1 34 | -------------------------------------------------------------------------------- /codejam/2020-04-04/Parenting_Partnering_Returns/parenting_partnering_returns_test.output: -------------------------------------------------------------------------------- 1 | Case #1: CJC 2 | Case #2: IMPOSSIBLE 3 | Case #3: JCCJJ 4 | Case #4: CC 5 | Case #5: 6 | Case #6: C 7 | Case #7: CJCJCJ 8 | Case #8: CJ 9 | -------------------------------------------------------------------------------- /codejam/2020-04-04/Vestigium/vestigium_test.input: -------------------------------------------------------------------------------- 1 | 3 2 | 4 3 | 1 2 3 4 4 | 2 1 4 3 5 | 3 4 1 2 6 | 4 3 2 1 7 | 4 8 | 2 2 2 2 9 | 2 3 2 3 10 | 2 2 2 3 11 | 2 2 2 2 12 | 3 13 | 2 1 3 14 | 1 3 2 15 | 1 2 3 16 | -------------------------------------------------------------------------------- /codejam/2020-04-04/Vestigium/vestigium_test.output: -------------------------------------------------------------------------------- 1 | Case #1: 4 0 0 2 | Case #2: 9 4 4 3 | Case #3: 8 0 2 4 | -------------------------------------------------------------------------------- /codejam/2020-04-19/Expogo/expogo.input: -------------------------------------------------------------------------------- 1 | 5 2 | 2 3 3 | -2 -3 4 | 3 0 5 | -1 1 6 | 1000000000 1000000000 7 | -------------------------------------------------------------------------------- /codejam/2022-04-02/Punched_Cards/punched_cards.input: -------------------------------------------------------------------------------- 1 | 5 2 | 3 4 3 | 2 2 4 | 2 3 5 | 1 1 6 | 0 0 7 | -------------------------------------------------------------------------------- /cormen-introduction/linear-search.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | x = sorted([ randint(0, 100) for i in xrange(0, 100) ]) 4 | search = 32 5 | 6 | 7 | def linear_search(x, search): 8 | i = 0 9 | while i < len(x): 10 | if x[i] == search: 11 | return i 12 | i += 1 13 | return -1 14 | 15 | 16 | def linear_search_optimized(x, search): 17 | i = 0 18 | last = x[len(x) - 1] 19 | x[len(x) - 1] = search 20 | while x[i] != search: 21 | i += 1 22 | if i == (len(x) - 1): 23 | if last == search: 24 | return i 25 | else: 26 | return -1 27 | else: 28 | return i 29 | 30 | 31 | print linear_search(x, search) 32 | print linear_search_optimized(x, search) 33 | -------------------------------------------------------------------------------- /cormen-introduction/selection-sort.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | x = [ randint(0, 100) for i in xrange(0, 100) ] 4 | 5 | 6 | def selection_sort(x): 7 | index_left_max = 0 8 | 9 | for i in xrange(len(x)): 10 | left_max = -1 11 | for j in xrange(i, len(x)): 12 | if x[j] > left_max: 13 | left_max = x[j] 14 | index_left_max = j 15 | x[index_left_max] = x[i] 16 | x[i] = left_max 17 | 18 | return x 19 | 20 | print selection_sort(x) 21 | -------------------------------------------------------------------------------- /cormen-introduction/tree.py: -------------------------------------------------------------------------------- 1 | class TreeNode(): 2 | parent = None 3 | left = None 4 | right = None 5 | key = None 6 | 7 | class Tree(): 8 | root = TreeNode() 9 | def insert() 10 | -------------------------------------------------------------------------------- /coursera/c-plus-plus-white/week1/A+B.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int left; 7 | int right; 8 | 9 | cin >> left; 10 | cin >> right; 11 | 12 | cout << left + right << endl; 13 | } 14 | -------------------------------------------------------------------------------- /coursera/c-plus-plus-white/week1/binary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | int num; 8 | cin >> num; 9 | 10 | vector container = {}; 11 | string result = ""; 12 | 13 | while (num > 0) { 14 | container.push_back(num & 1); 15 | num = num >> 1; 16 | } 17 | 18 | for (int pos = container.size() - 1; pos >= 0; pos--) { 19 | result.append(to_string(container[pos])); 20 | } 21 | 22 | cout << result << endl; 23 | } 24 | -------------------------------------------------------------------------------- /coursera/c-plus-plus-white/week1/equation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | double a, b, c; 8 | cin >> a; 9 | cin >> b; 10 | cin >> c; 11 | 12 | double root1, root2, discriminant; 13 | 14 | discriminant = b * b - 4 * a * c; 15 | 16 | if (a == 0 && b != 0) { 17 | cout << -c / b << endl; 18 | } else if (a != 0 and discriminant >= 0) { 19 | root1 = (-b + sqrt(discriminant)) / (2 * a); 20 | root2 = (-b - sqrt(discriminant)) / (2 * a); 21 | 22 | if (root1 == root2) { 23 | cout << root1 << endl; 24 | } else { 25 | cout << root1 << endl; 26 | cout << root2 << endl; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /coursera/c-plus-plus-white/week1/gcd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int left, right, tmp; 7 | 8 | cin >> left; 9 | cin >> right; 10 | 11 | while (right != 0) { 12 | tmp = right; 13 | right = left % right; 14 | left = tmp; 15 | } 16 | 17 | cout << left << endl; 18 | } 19 | -------------------------------------------------------------------------------- /coursera/c-plus-plus-white/week1/min-string.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string minString; 8 | string x, y, z; 9 | 10 | cin >> x; 11 | cin >> y; 12 | cin >> z; 13 | 14 | minString = x; 15 | 16 | if (y < minString) { 17 | minString = y; 18 | } 19 | 20 | if (z < minString) { 21 | minString = z; 22 | } 23 | 24 | cout << minString << endl; 25 | } 26 | -------------------------------------------------------------------------------- /coursera/c-plus-plus-white/week1/second-match.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | char target = 'f'; 8 | bool seen = false; 9 | 10 | string input; 11 | 12 | cin >> input; 13 | 14 | for (int pos = 0; pos < input.size(); pos++) { 15 | if (input[pos] == target) { 16 | if (seen) { 17 | cout << pos << endl; 18 | return 0; 19 | } else { 20 | seen = true; 21 | } 22 | } 23 | } 24 | 25 | if (seen) { 26 | cout << -1 << endl; 27 | } else { 28 | cout << -2 << endl; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /coursera/c-plus-plus-white/week2/factorial.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int Factorial(int number) { 6 | if (number <= 0) { 7 | return 1; 8 | } 9 | 10 | return Factorial(number - 1) * number; 11 | } 12 | 13 | int main() { 14 | cout << Factorial(10) << endl; 15 | cout << Factorial(0) << endl; 16 | cout << Factorial(-1) << endl; 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /coursera/c-plus-plus-white/week2/reverse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void Reverse(vector& toReverse) { 7 | int left = 0; 8 | int right = toReverse.size() - 1; 9 | int tmp; 10 | 11 | while (left < right) { 12 | tmp = toReverse[left]; 13 | toReverse[left] = toReverse[right]; 14 | toReverse[right] = tmp; 15 | left++; 16 | right--; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /crypto/ethereumbook/README.md: -------------------------------------------------------------------------------- 1 | # FAQ 2 | 3 | * **Compile a smart contract** 4 | ``` 5 | solc -o test.out --bin --ast-compact-json --asm test.sol 6 | ``` 7 | * **Download openzeppelin** 8 | ``` 9 | git clone https://github.com/OpenZeppelin/openzeppelin-contracts.git 10 | ``` 11 | * **Build and run docker** 12 | ``` 13 | sudo docker build --build-arg user=${USER} --build-arg uid=$(id -u ${USER}) -t eth . 14 | sudo docker run --ipc=host --security-opt apparmor:unconfined --device /dev/fuse --cap-add ALL -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=${DISPLAY} -h ${HOSTNAME} -v ${HOME}/.Xauthority:${HOME}/.Xauthority -v $(pwd)/:$(pwd) --net=host -it eth bash 15 | ``` 16 | * **Run ganache from docker** 17 | `/tmp/ganache` 18 | -------------------------------------------------------------------------------- /crypto/ethereumbook/nft_test/contracts/Migrations.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity >=0.4.22 <0.9.0; 3 | 4 | contract Migrations { 5 | address public owner = msg.sender; 6 | uint public last_completed_migration; 7 | 8 | modifier restricted() { 9 | require( 10 | msg.sender == owner, 11 | "This function is restricted to the contract's owner" 12 | ); 13 | _; 14 | } 15 | 16 | function setCompleted(uint completed) public restricted { 17 | last_completed_migration = completed; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /crypto/ethereumbook/nft_test/migrations/1_initial_migration.js: -------------------------------------------------------------------------------- 1 | const Migrations = artifacts.require("Migrations"); 2 | 3 | module.exports = function (deployer) { 4 | deployer.deploy(Migrations); 5 | }; 6 | -------------------------------------------------------------------------------- /crypto/ethereumbook/nft_test/migrations/2_deploy_contracts.js: -------------------------------------------------------------------------------- 1 | var NFT = artifacts.require("NFT"); 2 | 3 | module.exports = function(deployer) { 4 | deployer.deploy(NFT); 5 | // Additional contracts can be deployed here 6 | }; 7 | -------------------------------------------------------------------------------- /crypto/ethereumbook/nft_test/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "openzeppelin-solidity": "4.6.0" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /crypto/ethereumbook/requirements.txt: -------------------------------------------------------------------------------- 1 | web3 2 | py-solc-x 3 | eth-utils 4 | -------------------------------------------------------------------------------- /crypto/ethereumbook/run_devserver.sh: -------------------------------------------------------------------------------- 1 | geth --dev --datadir=ethereum-dev --http 2 | -------------------------------------------------------------------------------- /crypto/ethereumbook/test.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: CC-BY-SA-4.0 2 | 3 | // Version of Solidity compiler this program was written for 4 | pragma solidity ^0.8.13; 5 | 6 | // Our first contract is a faucet! 7 | contract Faucet { 8 | // Accept any incoming amount 9 | receive() external payable {} 10 | 11 | // Give out ether to anyone who asks 12 | function withdraw(uint withdraw_amount) public { 13 | // Limit withdrawal amount 14 | require(withdraw_amount <= 100000000000000000); 15 | 16 | // Send the amount to the address that requested it 17 | payable(msg.sender).transfer(withdraw_amount); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /hacker-cup/2020/qualification_round/A/travel_restrictions_sample_input.txt: -------------------------------------------------------------------------------- 1 | 5 2 | 2 3 | YY 4 | YY 5 | 2 6 | NY 7 | YY 8 | 2 9 | NN 10 | YY 11 | 5 12 | YNNYY 13 | YYYNY 14 | 10 15 | NYYYNNYYYY 16 | YYNYYNYYNY 17 | -------------------------------------------------------------------------------- /hacker-cup/2020/qualification_round/A/travel_restrictions_validation_input.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 2 3 | YY 4 | YY 5 | 2 6 | NY 7 | YY 8 | 2 9 | NN 10 | YY 11 | 5 12 | YNNYY 13 | YYYNY 14 | 10 15 | NYYYNNYYYY 16 | YYNYYNYYNY 17 | 20 18 | YYNYNYNYNNYYYYYYNYNY 19 | NYYYNYNYYNNYNYYNNYYY 20 | 50 21 | NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN 22 | NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN 23 | 50 24 | YNYYYYNYNYYYNYYYYYYYYYNYYYYYYYYYYYYYYYYYYYYNYNYYYY 25 | YYYYYYYYYYYYYYNYYYYYYYNYYYYYNYYYYNYYNYYYYNNYYYYYYY 26 | -------------------------------------------------------------------------------- /hacker-cup/2020/qualification_round/B/alchemy_sample_input.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 3 3 | BAB 4 | 3 5 | BBB 6 | 5 7 | AABBA 8 | 7 9 | BAAABAA 10 | 11 11 | BBBAABAAAAB 12 | 11 13 | BABBBABBABB 14 | -------------------------------------------------------------------------------- /hacker-cup/2020/qualification_round/B/alchemy_validation_output.txt: -------------------------------------------------------------------------------- 1 | Case #1: Y 2 | Case #2: N 3 | Case #3: Y 4 | Case #4: N 5 | Case #5: Y 6 | Case #6: N 7 | Case #7: Y 8 | Case #8: N 9 | Case #9: Y 10 | Case #10: N 11 | Case #11: Y 12 | Case #12: N 13 | -------------------------------------------------------------------------------- /hacker-cup/2020/qualification_round/C/timber_sample_input.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 2 3 | 0 5 4 | 5 4 5 | 2 6 | 0 5 7 | 9 4 8 | 3 9 | 0 5 10 | 9 3 11 | 2 6 12 | 5 13 | 3 2 14 | 2 8 15 | -4 5 16 | 8 5 17 | 1 4 18 | 6 19 | -15 15 20 | -9 9 21 | -3 3 22 | 5 5 23 | 9 9 24 | 18 18 25 | 8 26 | 10 20 27 | 20 20 28 | 30 20 29 | 40 20 30 | 50 20 31 | 60 20 32 | 70 20 33 | 80 20 34 | 12 35 | 13 8 36 | -14 5 37 | 2 19 38 | 33 10 39 | -31 9 40 | 15 21 41 | 5 3 42 | -22 16 43 | -6 11 44 | 25 12 45 | -40 24 46 | 21 18 47 | 2 48 | -500000000 500000000 49 | 500000000 500000000 50 | -------------------------------------------------------------------------------- /hacker-cup/2020/qualification_round/C/timber_sample_output.txt: -------------------------------------------------------------------------------- 1 | Case #1: 9 2 | Case #2: 9 3 | Case #3: 6 4 | Case #4: 12 5 | Case #5: 33 6 | Case #6: 80 7 | Case #7: 56 8 | Case #8: 1000000000 9 | -------------------------------------------------------------------------------- /hacker-cup/2020/qualification_round/C/timber_validation_output.txt: -------------------------------------------------------------------------------- 1 | Case #1: 9 2 | Case #2: 9 3 | Case #3: 6 4 | Case #4: 12 5 | Case #5: 33 6 | Case #6: 80 7 | Case #7: 56 8 | Case #8: 1000000000 9 | Case #9: 518198 10 | Case #10: 508315 11 | Case #11: 913948 12 | Case #12: 4318266 13 | Case #13: 4032734 14 | -------------------------------------------------------------------------------- /hacker-cup/2020/qualification_round/D1/running_on_fumes_chapter_1_sample_input.txt: -------------------------------------------------------------------------------- 1 | 7 2 | 5 3 3 | 0 4 | 20 5 | 30 6 | 0 7 | 10 8 | 5 2 9 | 0 10 | 20 11 | 30 12 | 0 13 | 10 14 | 5 1 15 | 0 16 | 20 17 | 30 18 | 0 19 | 10 20 | 4 1 21 | 99 22 | 88 23 | 77 24 | 66 25 | 4 4 26 | 99 27 | 88 28 | 77 29 | 66 30 | 6 2 31 | 0 32 | 0 33 | 20 34 | 30 35 | 0 36 | 10 37 | 12 3 38 | 0 39 | 1 40 | 4 41 | 7 42 | 0 43 | 5 44 | 9 45 | 8 46 | 0 47 | 3 48 | 0 49 | 6 50 | -------------------------------------------------------------------------------- /hacker-cup/2020/qualification_round/D1/running_on_fumes_chapter_1_validation_output.txt: -------------------------------------------------------------------------------- 1 | Case #1: 20 2 | Case #2: 30 3 | Case #3: -1 4 | Case #4: 165 5 | Case #5: 0 6 | Case #6: 50 7 | Case #7: 19 8 | Case #8: 0 9 | Case #9: -1 10 | Case #10: 2999999979 11 | Case #11: 3333744 12 | Case #12: 627743982 13 | Case #13: 1041706719 14 | Case #14: 135999268450 15 | Case #15: 25350250167 16 | Case #16: 10259 17 | -------------------------------------------------------------------------------- /hacker-cup/2020/qualification_round/D2/running_on_fumes_chapter_2_sample_input.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 4 1 2 3 3 | 0 10 4 | 4 20 5 | 4 30 6 | 1 40 7 | 8 1 5 3 8 | 0 30 9 | 3 20 10 | 1 0 11 | 7 10 12 | 8 0 13 | 1 0 14 | 6 20 15 | 6 30 16 | 8 2 5 3 17 | 0 30 18 | 3 20 19 | 1 0 20 | 7 10 21 | 8 0 22 | 1 0 23 | 6 20 24 | 6 30 25 | 8 3 5 3 26 | 0 30 27 | 3 20 28 | 1 0 29 | 7 10 30 | 8 0 31 | 1 0 32 | 6 20 33 | 6 30 34 | 15 1 3 14 35 | 0 28 36 | 1 18 37 | 1 17 38 | 2 8 39 | 4 13 40 | 4 2 41 | 2 6 42 | 5 37 43 | 8 37 44 | 9 21 45 | 6 22 46 | 2 33 47 | 1 11 48 | 8 5 49 | 12 8 50 | 15 5 11 12 51 | 0 0 52 | 7 28 53 | 1 19 54 | 6 5 55 | 15 0 56 | 5 0 57 | 15 0 58 | 1 12 59 | 8 6 60 | 5 20 61 | 2 0 62 | 4 0 63 | 6 10 64 | 4 8 65 | 1 22 66 | -------------------------------------------------------------------------------- /hacker-cup/2020/qualification_round/D2/running_on_fumes_chapter_2_validation_output.txt: -------------------------------------------------------------------------------- 1 | Case #1: 40 2 | Case #2: -1 3 | Case #3: 60 4 | Case #4: 20 5 | Case #5: 104 6 | Case #6: 17 7 | Case #7: 19 8 | Case #8: 0 9 | Case #9: 2999999982 10 | Case #10: 5 11 | Case #11: 210 12 | Case #12: -1 13 | Case #13: -1 14 | Case #14: 525 15 | Case #15: 410 16 | Case #16: 2165 17 | -------------------------------------------------------------------------------- /hackerrank/2d-array.py: -------------------------------------------------------------------------------- 1 | def hourglassSum(arr): 2 | result = float("-inf") 3 | for x in range(len(arr) - 2): 4 | for y in range(len(arr) - 2): 5 | result = max( 6 | result, 7 | sum( 8 | [ 9 | arr[y][x], 10 | arr[y][x + 1], 11 | arr[y][x + 2], 12 | arr[y + 2][x], 13 | arr[y + 2][x + 1], 14 | arr[y + 2][x + 2], 15 | arr[y + 1][x + 1], 16 | ] 17 | ), 18 | ) 19 | 20 | return result 21 | -------------------------------------------------------------------------------- /hackerrank/ctci-array-left-rotation.py: -------------------------------------------------------------------------------- 1 | def rotLeft(a, d): 2 | shift = d % len(a) 3 | 4 | return a[shift:] + a[:shift] 5 | -------------------------------------------------------------------------------- /hackerrank/ctci-bubble-sort.py: -------------------------------------------------------------------------------- 1 | def countSwaps(a): 2 | swaps = 0 3 | 4 | for end_pos in reversed(range(len(a))): 5 | for pos in range(end_pos): 6 | if a[pos] > a[pos + 1]: 7 | a[pos], a[pos + 1] = a[pos + 1], a[pos] 8 | swaps += 1 9 | 10 | print("Array is sorted in {} swaps.".format(swaps)) 11 | print("First Element: {}".format(a[0])) 12 | print("Last Element: {}".format(a[-1])) 13 | -------------------------------------------------------------------------------- /hackerrank/repeated-string.py: -------------------------------------------------------------------------------- 1 | def repeatedString(s, n): 2 | return s.count("a") * (n // len(s)) + s[:(n % len(s))].count("a") 3 | 4 | 5 | class TestRepeatedString: 6 | def test_one1(self): 7 | assert repeatedString("a", 1000000000000) == 1000000000000 8 | 9 | def test_one2(self): 10 | assert repeatedString("b", 1000000000000) == 0 11 | 12 | def test_custom1(self): 13 | assert repeatedString("aba", 10) == 7 14 | -------------------------------------------------------------------------------- /hackerrank/sock-merchant.py: -------------------------------------------------------------------------------- 1 | def sockMerchant(n, ar): 2 | items_with_color = {} 3 | 4 | for i in range(n): 5 | items_with_color[ar[i]] = items_with_color.get(ar[i], 0) + 1 6 | 7 | result = 0 8 | 9 | for k, v in items_with_color.items(): 10 | result += v // 2 11 | 12 | return result 13 | 14 | 15 | class TestSockMerchant: 16 | def test_empty(self): 17 | assert sockMerchant(0, []) == 0 18 | 19 | def test_one(self): 20 | assert sockMerchant(1, [1]) == 0 21 | 22 | def test_two1(self): 23 | assert sockMerchant(2, [1, 2]) == 0 24 | 25 | def test_two1(self): 26 | assert sockMerchant(2, [2, 2]) == 1 27 | 28 | def test_custom1(self): 29 | assert sockMerchant(9, [10, 20, 20, 10, 10, 30, 50, 10, 20]) == 3 30 | -------------------------------------------------------------------------------- /l33tcode/add-binary.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addBinary(self, a: str, b: str) -> str: 3 | carry = 0 4 | num_a, num_b = int(a, 2), int(b, 2) 5 | 6 | while num_b: 7 | add = num_a ^ num_b 8 | carry = (num_a & num_b) << 1 9 | num_a, num_b = add, carry 10 | 11 | return bin(num_a)[2:] 12 | -------------------------------------------------------------------------------- /l33tcode/add-digits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addDigits(self, num: int) -> int: 3 | if num == 0: 4 | return 0 5 | 6 | return num % 9 or 9 7 | -------------------------------------------------------------------------------- /l33tcode/add-to-array-form-of-integer.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def addToArrayForm(self, num: List[int], k: int) -> List[int]: 6 | result: List[int] = [] 7 | 8 | num1, num2 = num, list(map(int, str(k))) 9 | 10 | if len(num2) > len(num1): 11 | num1, num2 = num2, num1 12 | 13 | carry = 0 14 | 15 | for pos in range(len(num1)): 16 | digit1, digit2 = num1[-pos - 1], num2[-pos - 1] if pos < len(num2) else 0 17 | 18 | digit = (digit1 + digit2 + carry) % 10 19 | carry = (digit1 + digit2 + carry) // 10 20 | 21 | result.append(digit) 22 | 23 | if carry > 0: 24 | result.append(carry) 25 | 26 | return list(reversed(result)) 27 | -------------------------------------------------------------------------------- /l33tcode/airplane-seat-assignment-probability.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nthPersonGetsNthSeat(self, n: int) -> float: 3 | return 0.5 if n > 1 else 1 4 | -------------------------------------------------------------------------------- /l33tcode/all-paths-from-source-to-target.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: 3 | result = [] 4 | 5 | visited = set() 6 | path = [] 7 | 8 | def dfs(node): 9 | if node in visited: 10 | return 11 | 12 | if node == len(graph) - 1: 13 | result.append(path + [node]) 14 | return 15 | 16 | visited.add(node) 17 | 18 | for next_node in graph[node]: 19 | path.append(node) 20 | dfs(next_node) 21 | path.pop() 22 | 23 | visited.remove(node) 24 | 25 | dfs(0) 26 | 27 | return result 28 | -------------------------------------------------------------------------------- /l33tcode/angle-between-hands-of-a-clock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def angleClock(self, hour: int, minutes: int) -> float: 3 | def hour_to_angle(hour: int, minute: int) -> int: 4 | if hour == 12: 5 | hour = 0 6 | return hour * 360 / 12 + minute * 360 / (12 * 60) 7 | 8 | def minute_to_angle(minute: int) -> int: 9 | return minute * 360 / 60 10 | 11 | angle = abs(hour_to_angle(hour, minutes) - minute_to_angle(minutes)) 12 | 13 | return min(360 - angle, angle) 14 | -------------------------------------------------------------------------------- /l33tcode/apply-operations-to-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def applyOperations(self, nums: list[int]) -> list[int]: 3 | for i in range(len(nums) - 1): 4 | if nums[i] == nums[i + 1]: 5 | nums[i] *= 2 6 | nums[i + 1] = 0 7 | 8 | ptr = 0 9 | 10 | for pos, num in enumerate(nums): 11 | if num != 0: 12 | nums[ptr], nums[pos] = nums[pos], nums[ptr] 13 | ptr += 1 14 | 15 | return nums 16 | -------------------------------------------------------------------------------- /l33tcode/arithmetic-slices.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | class Solution: 5 | def numberOfArithmeticSlices(self, A: List[int]) -> int: 6 | if len(A) < 3: 7 | return 0 8 | 9 | count = 2 10 | diff = A[1] - A[0] 11 | 12 | result = 0 13 | comb = lambda n: math.factorial(n) // math.factorial(n - 2) // 2 14 | 15 | for pos in range(2, len(A)): 16 | if A[pos] - A[pos - 1] == diff: 17 | count += 1 18 | else: 19 | if count > 1: 20 | result += comb(count) - (count - 1) 21 | diff = A[pos] - A[pos - 1] 22 | count = 2 23 | 24 | if count > 1: 25 | result += comb(count) - (count - 1) 26 | 27 | return result 28 | -------------------------------------------------------------------------------- /l33tcode/arithmetic-subarrays.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def checkArithmeticSubarrays( 6 | self, nums: List[int], l: List[int], r: List[int] 7 | ) -> List[bool]: 8 | result: List[bool] = [] 9 | 10 | def is_arithmetic(left: int, right: int) -> bool: 11 | arr = sorted(nums[left:right]) 12 | 13 | if len(arr) < 2: 14 | return True 15 | 16 | diff = arr[1] - arr[0] 17 | 18 | for pos in range(1, len(arr)): 19 | if diff != arr[pos] - arr[pos - 1]: 20 | return False 21 | 22 | return True 23 | 24 | for left, right in zip(l, r): 25 | result.append(is_arithmetic(left, right + 1)) 26 | 27 | return result 28 | -------------------------------------------------------------------------------- /l33tcode/arranging-coins.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | class Solution: 5 | def arrangeCoins(self, n: int) -> int: 6 | # sum = n * (n + 1) / 2 7 | # n^2 + n - 2 * sum = 0 8 | # n^2 + 2 * (1/2) * n + 1/4 - 1/4 - 2 * sum = 0 9 | # (n + 1/2)^2 = 1/4 + 2 * sum 10 | # n = sqrt(1/4 + 2 * sum) - 1/2 11 | return int(math.sqrt(1 / 4 + 2 * n) - 1 / 2) 12 | -------------------------------------------------------------------------------- /l33tcode/array-nesting.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def arrayNesting(self, nums: List[int]) -> int: 6 | visited: List[bool] = [False] * len(nums) 7 | 8 | def follow_cycle(start_pos: int) -> int: 9 | length = 1 10 | 11 | pos = start_pos 12 | 13 | while (pos := nums[pos]) != start_pos: 14 | visited[pos] = True 15 | length += 1 16 | 17 | return length 18 | 19 | max_length = 0 20 | for pos in range(len(nums)): 21 | if not visited[pos]: 22 | max_length = max(max_length, follow_cycle(pos)) 23 | 24 | return max_length 25 | -------------------------------------------------------------------------------- /l33tcode/asteroid-collision.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def asteroidCollision(self, asteroids: List[int]) -> List[int]: 6 | stack: List[int] = [] 7 | 8 | for asteroid in asteroids: 9 | if asteroid < 0: 10 | while stack and stack[-1] > 0: 11 | if stack[-1] < -asteroid: 12 | stack.pop() 13 | elif stack[-1] == -asteroid: 14 | stack.pop() 15 | break 16 | else: 17 | break 18 | else: 19 | stack.append(asteroid) 20 | else: 21 | stack.append(asteroid) 22 | 23 | return stack 24 | -------------------------------------------------------------------------------- /l33tcode/average-waiting-time.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def averageWaitingTime(self, customers: List[List[int]]) -> float: 6 | end = 0 7 | 8 | avg_wait_time = 0.0 9 | customers_served = 0 10 | 11 | for arrival, time in customers: 12 | end = max(arrival, end) + time 13 | avg_wait_time = avg_wait_time * customers_served / ( 14 | customers_served + 1 15 | ) + (end - arrival) / (customers_served + 1) 16 | customers_served += 1 17 | 18 | return avg_wait_time 19 | -------------------------------------------------------------------------------- /l33tcode/battleships-in-a-board.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func countBattleships(board [][]byte) int { 4 | count := 0 5 | for row, _ := range make([]bool, len(board)) { 6 | for col, _ := range make([]bool, len(board[row])) { 7 | seen := false 8 | if row > 0 { 9 | if board[row-1][col] == 'X' { 10 | seen = true 11 | } 12 | } 13 | if col > 0 { 14 | if board[row][col-1] == 'X' { 15 | seen = true 16 | } 17 | } 18 | if !seen && board[row][col] == 'X'{ 19 | count += 1 20 | } 21 | } 22 | } 23 | 24 | return count 25 | } 26 | -------------------------------------------------------------------------------- /l33tcode/best-time-to-buy-and-sell-stock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices): 3 | result = 0 4 | min_so_far = float("+inf") 5 | 6 | for price in prices: 7 | result = max(result, price - min_so_far) 8 | min_so_far = min(min_so_far, price) 9 | 10 | return result 11 | -------------------------------------------------------------------------------- /l33tcode/binary-search-tree-to-greater-sum-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 bstToGst(self, root: TreeNode) -> TreeNode: 10 | def inorder(node, added): 11 | if node is None: 12 | return added 13 | node.val += inorder(node.right, added) 14 | return inorder(node.left, node.val) 15 | 16 | if root: 17 | inorder(root, 0) 18 | return root 19 | else: 20 | return 21 | -------------------------------------------------------------------------------- /l33tcode/binary-string-with-substrings-representing-1-to-n.py: -------------------------------------------------------------------------------- 1 | from typing import Set 2 | 3 | 4 | class Solution: 5 | def queryString(self, S: str, N: int) -> bool: 6 | seen: Set[int] = set() 7 | 8 | for start in range(len(S)): 9 | rolling_hash = 0 10 | end = start 11 | 12 | for end in range(start, len(S)): 13 | rolling_hash <<= 1 14 | rolling_hash += int(S[end]) 15 | 16 | if rolling_hash <= N: 17 | seen.add(rolling_hash) 18 | else: 19 | break 20 | 21 | seen.discard(0) 22 | 23 | return len(seen) == N 24 | -------------------------------------------------------------------------------- /l33tcode/binary-tree-preorder-traversal.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 preorderTraversal(self, root): 10 | if not root: 11 | return [] 12 | 13 | stack = [root] 14 | result = [] 15 | 16 | while stack: 17 | node = stack.pop() 18 | 19 | result.append(node.val) 20 | 21 | if node.right: 22 | stack.append(node.right) 23 | 24 | if node.left: 25 | stack.append(node.left) 26 | 27 | return result 28 | -------------------------------------------------------------------------------- /l33tcode/binary-tree-pruning.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func pruneTree(root *TreeNode) *TreeNode { 10 | var dfs func(node *TreeNode) bool 11 | dfs = func(node *TreeNode) bool { 12 | if node == nil { 13 | return false 14 | } 15 | left, right := dfs(node.Left), dfs(node.Right) 16 | if !left { 17 | node.Left = nil 18 | } 19 | if !right { 20 | node.Right = nil 21 | } 22 | 23 | return left || right || node.Val == 1 24 | } 25 | 26 | if dfs(root) { 27 | return root 28 | } 29 | 30 | return nil 31 | } 32 | -------------------------------------------------------------------------------- /l33tcode/bitwise-and-of-numbers-range.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rangeBitwiseAnd(self, m: int, n: int) -> int: 3 | return m >> (m - n).bit_length() << (m - n).bit_length() & n 4 | -------------------------------------------------------------------------------- /l33tcode/boats-to-save-people.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def numRescueBoats(self, people: List[int], limit: int) -> int: 6 | people.sort() 7 | 8 | left, right = 0, len(people) - 1 9 | 10 | boats = len(people) 11 | 12 | while left < right: 13 | if people[left] + people[right] <= limit: 14 | left += 1 15 | boats -= 1 16 | 17 | right -= 1 18 | 19 | 20 | return boats 21 | -------------------------------------------------------------------------------- /l33tcode/broken-calculator.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def brokenCalc(self, X: int, Y: int) -> int: 3 | steps = 0 4 | while X < Y: 5 | if Y & 1 == 1: 6 | Y += 1 7 | else: 8 | Y //= 2 9 | 10 | steps += 1 11 | 12 | return steps + (X - Y) 13 | -------------------------------------------------------------------------------- /l33tcode/build-an-array-with-stack-operations.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def buildArray(self, target: List[int], n: int) -> List[str]: 6 | stack = [] 7 | ops = [] 8 | 9 | target_pos = 0 10 | 11 | for num in range(1, n + 1): 12 | if target_pos == len(target): 13 | break 14 | 15 | stack.append(num) 16 | ops.append("Push") 17 | 18 | if stack[-1] != target[target_pos]: 19 | stack.pop() 20 | ops.append("Pop") 21 | else: 22 | target_pos += 1 23 | 24 | return ops 25 | -------------------------------------------------------------------------------- /l33tcode/buildings-with-an-ocean-view.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findBuildings(self, heights: List[int]) -> List[int]: 6 | stack: List[int] = [] 7 | 8 | for pos in range(len(heights)): 9 | while stack and heights[stack[-1]] <= heights[pos]: 10 | stack.pop() 11 | 12 | stack.append(pos) 13 | 14 | return stack 15 | -------------------------------------------------------------------------------- /l33tcode/can-i-win.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | 4 | class Solution: 5 | def canIWin(self, max_int: int, total: int) -> bool: 6 | @lru_cache(None) 7 | def dp(bitmask: int, left: int) -> bool: 8 | if left <= 0: 9 | return False 10 | 11 | for num in range(1, max_int + 1): 12 | if bitmask & (1 << num) == 0: 13 | if not dp(bitmask | (1 << num), left - num): 14 | return True 15 | 16 | return False 17 | 18 | if total == 0: 19 | return True 20 | 21 | if total > max_int * (max_int + 1) // 2: 22 | return False 23 | 24 | return dp(0, total) 25 | -------------------------------------------------------------------------------- /l33tcode/car-fleet.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def carFleet(self, target: int, position: List[int], speed: List[int],) -> int: 6 | prev_time = 0 7 | count = len(position) 8 | 9 | for car_pos, car_speed in reversed(sorted(zip(position, speed))): 10 | target_time = (target - car_pos) / float(car_speed) 11 | 12 | if target_time <= prev_time: 13 | count -= 1 14 | else: 15 | prev_time = target_time 16 | 17 | return count 18 | -------------------------------------------------------------------------------- /l33tcode/car-pooling.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def carPooling(self, trips: List[List[int]], capacity: int) -> bool: 6 | last = 0 7 | 8 | for _, _, end in trips: 9 | last = max(last, end) 10 | 11 | path = [0] * (last + 1) 12 | 13 | for num_passengers, begin, end in trips: 14 | path[begin] += num_passengers 15 | path[end] -= num_passengers 16 | 17 | passengers = 0 18 | for num_passengers in path: 19 | passengers += num_passengers 20 | if passengers > capacity: 21 | return False 22 | 23 | return True 24 | -------------------------------------------------------------------------------- /l33tcode/champagne-tower.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: 3 | tower_row = [float(poured)] 4 | 5 | for row in range(query_row + 1): 6 | tower_row_prev = tower_row 7 | tower_row = [0.0] * (row + 2) 8 | for col in range(row + 1): 9 | excess = tower_row_prev[col] - 1 10 | if excess > 0: 11 | tower_row[col] += excess / 2 12 | tower_row[col + 1] += excess / 2 13 | tower_row_prev[col] = 1 14 | 15 | return tower_row_prev[query_glass] 16 | -------------------------------------------------------------------------------- /l33tcode/check-array-formation-through-concatenation.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: 6 | first_piece_map = {pieces[pos][0]: pos for pos in range(len(pieces))} 7 | 8 | pos = 0 9 | 10 | while pos < len(arr): 11 | if not arr[pos] in first_piece_map: 12 | return False 13 | 14 | cur_pieces = pieces[first_piece_map[arr[pos]]] 15 | 16 | if cur_pieces == arr[pos : pos + len(cur_pieces)]: 17 | pos += len(cur_pieces) 18 | else: 19 | return False 20 | 21 | return True 22 | -------------------------------------------------------------------------------- /l33tcode/check-if-a-string-contains-all-binary-codes-of-size-k.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hasAllCodes(self, s: str, k: int) -> bool: 3 | cache = set() 4 | power = 2 ** k 5 | for pos in range(len(s) - k + 1): 6 | cache.add(s[pos:(pos + k)]) 7 | if len(cache) == power: 8 | return True 9 | 10 | return False 11 | -------------------------------------------------------------------------------- /l33tcode/check-if-all-1s-are-at-least-length-k-places-away.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def kLengthApart(self, nums: List[int], k: int) -> bool: 6 | one = -1 7 | 8 | for pos in range(len(nums)): 9 | if nums[pos] == 1: 10 | if one >= 0 and pos - one - 1 < k: 11 | return False 12 | one = pos 13 | 14 | return True 15 | -------------------------------------------------------------------------------- /l33tcode/check-if-it-is-a-good-array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def isGoodArray(self, nums: List[int]) -> bool: 6 | def gcd(x: int, y: int) -> int: 7 | if y == 0: 8 | return x 9 | 10 | return gcd(y, x % y) 11 | 12 | if not nums: 13 | return False 14 | 15 | result = nums[0] 16 | 17 | for pos in range(1, len(nums)): 18 | result = gcd(result, nums[pos]) 19 | 20 | return result == 1 21 | -------------------------------------------------------------------------------- /l33tcode/check-if-it-is-a-straight-line.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func checkStraightLine(coordinates [][]int) bool { 4 | k := func(x1, y1, x2, y2 int) float64 { return float64(y2-y1) / float64(x2-x1) } 5 | b := func(x1, y1, x2, y2 int) float64 { return float64(y1*x2-y2*x1) / float64(x2-x1) } 6 | 7 | point1 := coordinates[0] 8 | point2 := coordinates[1] 9 | 10 | k_init := k(point1[0], point1[1], point2[0], point2[1]) 11 | b_init := b(point1[0], point1[1], point2[0], point2[1]) 12 | 13 | for _, point := range coordinates[2:] { 14 | k_new := k(point1[0], point1[1], point[0], point[1]) 15 | b_new := b(point1[0], point1[1], point[0], point[1]) 16 | if k_new != k_init || b_new != b_init { 17 | return false 18 | } 19 | } 20 | return true 21 | } 22 | -------------------------------------------------------------------------------- /l33tcode/check-if-there-is-a-valid-partition-for-the-array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def validPartition(self, nums: List[int]) -> bool: 6 | dp = [nums[-2] == nums[-1], False, True, False] 7 | 8 | for pos in reversed(range(len(nums) - 2)): 9 | dp = [False] + dp[:-1] 10 | dp[0] |= dp[2] & (nums[pos] == nums[pos + 1]) 11 | dp[0] |= dp[3] & (nums[pos] == nums[pos + 1] == nums[pos + 2]) 12 | dp[0] |= dp[3] & (nums[pos] == nums[pos + 1] - 1 == nums[pos + 2] - 2) 13 | 14 | return dp[0] 15 | -------------------------------------------------------------------------------- /l33tcode/closest-binary-search-tree-value.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 closestValue(self, root: TreeNode, target: float) -> int: 9 | def dfs(node: TreeNode, closest: int) -> int: 10 | closest = min(closest, node.val, key=lambda x: abs(x - target)) 11 | if node.left and node.val > target: 12 | closest = dfs(node.left, closest) 13 | if node.right and node.val < target: 14 | closest = dfs(node.right, closest) 15 | 16 | return closest 17 | 18 | return dfs(root, float("-inf")) 19 | -------------------------------------------------------------------------------- /l33tcode/coin-change-2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func change(amount int, coins []int) int { 4 | dp := [][]int{} 5 | dp = append(dp, make([]int, amount+1)) 6 | dp[0][0] = 1 7 | for pos, _ := range coins { 8 | dp = append(dp, make([]int, amount+1)) 9 | dp[pos+1][0] = 1 10 | } 11 | 12 | for coin_pos, coin := range coins { 13 | for amount_pos, _ := range make([]int, amount) { 14 | dp[coin_pos+1][amount_pos+1] = dp[coin_pos][amount_pos+1] 15 | if amount_pos+1-coin >= 0 { 16 | dp[coin_pos+1][amount_pos+1] += dp[coin_pos+1][amount_pos+1-coin] 17 | } 18 | } 19 | } 20 | 21 | return dp[len(coins)][amount] 22 | } 23 | -------------------------------------------------------------------------------- /l33tcode/coin-change-ii.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def change(self, amount: int, coins: List[int]) -> int: 6 | dp = [0] * (amount + 1) 7 | dp[0] = 1 8 | 9 | for coin in coins: 10 | for pos in range(1, amount + 1): 11 | if pos - coin >= 0: 12 | dp[pos] += dp[pos - coin] 13 | 14 | return dp[amount] 15 | -------------------------------------------------------------------------------- /l33tcode/combination-sum-iv.py: -------------------------------------------------------------------------------- 1 | from functools import cache 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def combinationSum4(self, nums: List[int], target: int) -> int: 7 | @cache 8 | def dfs(total: int) -> int: 9 | if total > target: 10 | return 0 11 | 12 | if total == target: 13 | return 1 14 | 15 | count = 0 16 | for num in nums: 17 | count += dfs(total + num) 18 | 19 | return count 20 | 21 | return dfs(0) 22 | -------------------------------------------------------------------------------- /l33tcode/compare-version-numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def compareVersion(self, version1: str, version2: str) -> int: 3 | ptr1, ptr2 = 0, 0 4 | 5 | while ptr1 < len(version1) or ptr2 < len(version2): 6 | num1, num2 = 0, 0 7 | 8 | while ptr1 < len(version1) and version1[ptr1] != ".": 9 | num1 = num1 * 10 + int(version1[ptr1]) 10 | ptr1 += 1 11 | ptr1 += 1 12 | 13 | while ptr2 < len(version2) and version2[ptr2] != ".": 14 | num2 = num2 * 10 + int(version2[ptr2]) 15 | ptr2 += 1 16 | ptr2 += 1 17 | 18 | if num1 < num2: 19 | return -1 20 | elif num1 > num2: 21 | return 1 22 | 23 | return 0 24 | -------------------------------------------------------------------------------- /l33tcode/concatenation-of-consecutive-binary-numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def concatenatedBinary(self, n: int) -> int: 3 | MOD = 10 ** 9 + 7 4 | shift = 1 5 | target = 2 6 | result = 0 7 | 8 | for num in range(1, n + 1): 9 | if target == num: 10 | shift += 1 11 | target <<= 1 12 | 13 | result <<= shift 14 | result |= num 15 | 16 | result %= MOD 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /l33tcode/consecutive-numbers-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def consecutiveNumbersSum(self, N: int) -> int: 3 | arithmetic_progression_sum = 0 4 | result = 0 5 | 6 | for count in range(1, N + 1): 7 | arithmetic_progression_sum += count 8 | 9 | if (N - arithmetic_progression_sum) / count + 1 < 1: 10 | break 11 | 12 | if (N - arithmetic_progression_sum) % count == 0: 13 | result += 1 14 | 15 | return result 16 | -------------------------------------------------------------------------------- /l33tcode/constrained-subsequence-sum.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | from typing import List, Tuple 3 | 4 | 5 | class Solution: 6 | def constrainedSubsetSum(self, nums: List[int], k: int) -> int: 7 | heap: List[Tuple[int, int]] = [] # (-max_sum, pos) 8 | max_sum = nums[0] 9 | 10 | for pos, num in enumerate(nums): 11 | while heap and heap[0][1] < pos - k: 12 | heapq.heappop(heap) 13 | 14 | max_prev_sum = max(0, -heap[0][0]) if heap else 0 15 | heapq.heappush(heap, (-(max_prev_sum + num), pos)) 16 | max_sum = max(max_sum, max_prev_sum + num) 17 | 18 | return max_sum 19 | -------------------------------------------------------------------------------- /l33tcode/container-with-most-water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, heights: list[int]) -> int: 3 | left, right = 0, len(heights) - 1 4 | result = 0 5 | 6 | while left < right: 7 | result = max(result, (right - left) * min(heights[left], heights[right])) 8 | 9 | if heights[left] < heights[right]: 10 | left += 1 11 | else: 12 | right -= 1 13 | 14 | return result 15 | -------------------------------------------------------------------------------- /l33tcode/contains-duplicate-iii.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from collections import deque 3 | 4 | 5 | class Solution: 6 | def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: 7 | if t == 0 and len(nums) == len(set(nums)): 8 | return False 9 | 10 | for left in range(len(nums)): 11 | for right in range(left + 1, min(len(nums), left + 1 + k)): 12 | if abs(nums[left] - nums[right]) <= t: 13 | return True 14 | 15 | return False 16 | -------------------------------------------------------------------------------- /l33tcode/contiguous-array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findMaxLength(self, nums: List[int]) -> int: 6 | diff = 0 7 | diff_to_pos = {0: -1} 8 | result = 0 9 | 10 | for pos, num in enumerate(nums): 11 | diff += 1 if num else -1 12 | 13 | if diff not in diff_to_pos: 14 | diff_to_pos[diff] = pos 15 | else: 16 | result = max(result, pos - diff_to_pos[diff]) 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /l33tcode/convert-binary-number-in-a-linked-list-to-integer.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 | 8 | class Solution: 9 | def getDecimalValue(self, head: ListNode) -> int: 10 | number = 0 11 | 12 | node = head 13 | while node: 14 | number <<= 1 15 | number |= node.val 16 | node = node.next 17 | 18 | return number 19 | -------------------------------------------------------------------------------- /l33tcode/count-nice-pairs-in-an-array.py: -------------------------------------------------------------------------------- 1 | from typing import List, Counter 2 | 3 | MOD = 10 ** 9 + 7 4 | 5 | 6 | class Solution: 7 | def countNicePairs(self, nums: List[int]) -> int: 8 | def rev(num: int) -> int: 9 | res = 0 10 | while num > 0: 11 | res *= 10 12 | res += num % 10 13 | num //= 10 14 | return res 15 | 16 | counter: Counter[int] = Counter() 17 | 18 | for num in nums: 19 | counter[num - rev(num)] += 1 20 | 21 | return sum((c - 1) * c // 2 for c in counter.values()) % MOD 22 | -------------------------------------------------------------------------------- /l33tcode/count-number-of-bad-pairs.py: -------------------------------------------------------------------------------- 1 | from typing import Counter, List 2 | 3 | 4 | class Solution: 5 | def countBadPairs(self, nums: List[int]) -> int: 6 | counter: Counter[int] = Counter() 7 | bad = len(nums) * (len(nums) - 1) // 2 8 | 9 | for pos, num in enumerate(nums): 10 | bad -= counter[num - pos] 11 | counter[num - pos] += 1 12 | 13 | return bad 14 | 15 | def countBadPairsBruteForce(self, nums: List[int]) -> int: 16 | bad = 0 17 | 18 | for left in range(len(nums)): 19 | for right in range(left + 1, len(nums)): 20 | if right - left != nums[right] - nums[left]: 21 | bad += 1 22 | 23 | return bad 24 | -------------------------------------------------------------------------------- /l33tcode/count-number-of-homogenous-substrings.py: -------------------------------------------------------------------------------- 1 | from functools import cache 2 | 3 | MOD = 10 ** 9 + 7 4 | 5 | 6 | class Solution: 7 | def countHomogenous(self, s: str) -> int: 8 | @cache 9 | def dp(pos: int) -> int: 10 | count = 1 11 | 12 | if pos + 1 < len(s) and s[pos] == s[pos + 1]: 13 | count += dp(pos + 1) 14 | 15 | return count % MOD 16 | 17 | return sum([dp(pos) for pos in range(len(s))]) % MOD 18 | -------------------------------------------------------------------------------- /l33tcode/count-number-of-teams.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numTeams(rating []int) int { 4 | teams := 0 5 | for middle := 1; middle < len(rating)-1; middle++ { 6 | left_less, left_more := 0, 0 7 | right_less, right_more := 0, 0 8 | for pos, _ := range make([]int, len(rating)) { 9 | if rating[pos] < rating[middle] { 10 | if pos < middle { 11 | left_less++ 12 | } else { 13 | right_less++ 14 | } 15 | } else if rating[pos] > rating[middle] { 16 | if pos < middle { 17 | left_more++ 18 | } else { 19 | right_more++ 20 | } 21 | } 22 | } 23 | teams += left_less*right_more + left_more*right_less 24 | } 25 | return teams 26 | } 27 | -------------------------------------------------------------------------------- /l33tcode/count-numbers-with-unique-digits.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | class Solution: 5 | def countNumbersWithUniqueDigits(self, n: int) -> int: 6 | comb = lambda n, k: math.factorial(n) // math.factorial(n - k) // math.factorial(k) 7 | perm = lambda n, k: math.factorial(n) // math.factorial(n - k) 8 | 9 | result = 1 10 | for digits in range(1, n + 1): 11 | result += perm(10, digits) - perm(9, digits - 1) 12 | 13 | return result 14 | -------------------------------------------------------------------------------- /l33tcode/count-odd-numbers-in-an-interval-range.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countOdds(self, low: int, high: int) -> int: 3 | if (high - low + 1) % 2 == 0: 4 | return (high - low + 1) // 2 5 | else: 6 | return (high - low) // 2 + high % 2 7 | -------------------------------------------------------------------------------- /l33tcode/count-sorted-vowel-strings.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | class Solution: 5 | def countVowelStrings(self, count: int) -> int: 6 | def comb(n: int, k: int) -> int: 7 | return math.factorial(n) // math.factorial(n - k) // math.factorial(k) 8 | 9 | return comb(count + 4, count) 10 | -------------------------------------------------------------------------------- /l33tcode/count-vowels-permutation.py: -------------------------------------------------------------------------------- 1 | from functools import cache 2 | 3 | MOD = 10 ** 9 + 7 4 | 5 | 6 | class Solution: 7 | def countVowelPermutation(self, n: int) -> int: 8 | follow_map = { 9 | "a": {"e"}, 10 | "e": {"a", "i"}, 11 | "i": {"a", "e", "o", "u"}, 12 | "o": {"i", "u"}, 13 | "u": {"a"}, 14 | } 15 | 16 | @cache 17 | def dp(pos: int, vowel: str) -> int: 18 | if pos == n - 1: 19 | return 1 20 | 21 | count = 0 22 | 23 | for following_vowel in follow_map[vowel]: 24 | count += dp(pos + 1, following_vowel) % MOD 25 | 26 | return count % MOD 27 | 28 | return sum([dp(0, vowel) for vowel in follow_map.keys()]) % MOD 29 | -------------------------------------------------------------------------------- /l33tcode/counting_elements.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countElements(self, arr: List[int]) -> int: 3 | all_elements = set(arr) 4 | return len([None for a in arr if (a + 1) in all_elements]) 5 | -------------------------------------------------------------------------------- /l33tcode/daily-temperatures.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func dailyTemperatures(temperatures []int) []int { 4 | stack := []int{} 5 | answer := []int{} 6 | 7 | for pos, _ := range temperatures { 8 | posBack := len(temperatures) - pos - 1 9 | 10 | for len(stack) > 0 && temperatures[stack[len(stack)-1]] <= temperatures[posBack] { 11 | stack = stack[:len(stack)-1] 12 | } 13 | 14 | if len(stack) > 0 { 15 | answer = append(answer, stack[len(stack)-1]-posBack) 16 | } else { 17 | answer = append(answer, 0) 18 | } 19 | 20 | stack = append(stack, posBack) 21 | } 22 | 23 | for pos, _ := range make([]int, len(answer)/2) { 24 | posBack := len(answer) - pos - 1 25 | 26 | answer[pos], answer[posBack] = answer[posBack], answer[pos] 27 | } 28 | 29 | return answer 30 | } 31 | -------------------------------------------------------------------------------- /l33tcode/deepest-leaves-sum.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func deepestLeavesSum(root *TreeNode) int { 10 | cur_max := 0 11 | cur_sum := 0 12 | 13 | var dfs func(node *TreeNode, depth int) 14 | dfs = func(node *TreeNode, depth int) { 15 | if node == nil { 16 | return 17 | } 18 | if depth > cur_max { 19 | cur_max = depth 20 | cur_sum = node.Val 21 | } else if depth == cur_max { 22 | cur_sum += node.Val 23 | } 24 | dfs(node.Left, depth+1) 25 | dfs(node.Right, depth+1) 26 | } 27 | 28 | dfs(root, 0) 29 | return cur_sum 30 | } 31 | -------------------------------------------------------------------------------- /l33tcode/defuse-the-bomb.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def decrypt(self, code: List[int], k: int) -> List[int]: 6 | def sum_next_k(pos: int) -> int: 7 | total = 0 8 | for next_pos in range(pos + 1, pos + abs(k) + 1): 9 | real_pos = next_pos % len(code) 10 | total += code[real_pos] 11 | 12 | return total 13 | 14 | decrypted = [0] * len(code) 15 | 16 | for pos in range(len(code)): 17 | if k > 0: 18 | decrypted[pos] = sum_next_k(pos) 19 | elif k < 0: 20 | decrypted[pos] = sum_next_k(pos + k - 1) 21 | 22 | return decrypted 23 | -------------------------------------------------------------------------------- /l33tcode/delete-node-in-a-linked-list.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func deleteNode(node *ListNode) { 9 | for curNode := node; curNode.Next != nil; curNode = curNode.Next { 10 | curNode.Val = curNode.Next.Val 11 | if curNode.Next.Next == nil { 12 | curNode.Next = nil 13 | break 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /l33tcode/design-parking-system.py: -------------------------------------------------------------------------------- 1 | class ParkingSystem: 2 | def __init__(self, big: int, medium: int, small: int): 3 | self._spots = [0, big, medium, small] 4 | 5 | def addCar(self, carType: int) -> bool: 6 | if self._spots[carType] > 0: 7 | self._spots[carType] -= 1 8 | return True 9 | 10 | return False 11 | 12 | 13 | # Your ParkingSystem object will be instantiated and called as such: 14 | # obj = ParkingSystem(big, medium, small) 15 | # param_1 = obj.addCar(carType) 16 | -------------------------------------------------------------------------------- /l33tcode/destroy-sequential-targets.py: -------------------------------------------------------------------------------- 1 | from typing import Counter 2 | 3 | 4 | class Solution: 5 | def destroyTargets(self, nums: list[int], space: int) -> int: 6 | counter = Counter([num % space for num in nums]) 7 | max_count = max(counter.values()) 8 | 9 | min_num = max(nums) 10 | 11 | for pos in range(len(nums)): 12 | if counter[nums[pos] % space] == max_count: 13 | min_num = min(min_num, nums[pos]) 14 | 15 | return min_num 16 | -------------------------------------------------------------------------------- /l33tcode/determine-if-a-cell-is-reachable-at-a-given-time.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isReachableAtTime( 3 | self, 4 | sx: int, 5 | sy: int, 6 | fx: int, 7 | fy: int, 8 | t: int, 9 | ) -> bool: 10 | if (sx, sy) == (fx, fy): 11 | return t != 1 12 | 13 | return max(abs(sx - fx), abs(sy - fy)) <= t 14 | -------------------------------------------------------------------------------- /l33tcode/determine-if-string-halves-are-alike.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func vowelsCount(arr string) int { 4 | vowels := map[rune]bool{ 5 | 'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'A': true, 'E': true, 'I': true, 'O': true, 'U': true, 6 | } 7 | 8 | result := 0 9 | 10 | for _, char := range arr { 11 | if _, ok := vowels[char]; ok { 12 | result += 1 13 | } 14 | } 15 | 16 | return result 17 | } 18 | 19 | func halvesAreAlike(s string) bool { 20 | countLeft := vowelsCount(s[:(len(s) / 2)]) 21 | countRight := vowelsCount(s[(len(s) / 2):]) 22 | 23 | return countLeft == countRight 24 | } 25 | -------------------------------------------------------------------------------- /l33tcode/determine-if-two-strings-are-close.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | def closeStrings(self, word1: str, word2: str) -> bool: 6 | counter1, counter2 = Counter(word1), Counter(word2) 7 | 8 | if set(counter1.keys()) != set(counter2.keys()): 9 | return False 10 | 11 | if Counter(counter1.values()) != Counter(counter2.values()): 12 | return False 13 | 14 | return True 15 | -------------------------------------------------------------------------------- /l33tcode/diagonal-traverse-ii.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import DefaultDict, List 3 | 4 | 5 | class Solution: 6 | def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]: 7 | result: List[int] = [] 8 | 9 | diagonals: DefaultDict[int, List[int]] = defaultdict(list) 10 | 11 | for row in enumerate(len(nums)): 12 | for col in range(len(nums[row])): 13 | diagonals[col + row].append(nums[row][col]) 14 | 15 | diagonal = 0 16 | 17 | while diagonal in diagonals: 18 | result.extend(reversed(diagonals[diagonal])) 19 | diagonal += 1 20 | 21 | return result 22 | -------------------------------------------------------------------------------- /l33tcode/dice-roll-simulation.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from functools import lru_cache 3 | 4 | 5 | class Solution: 6 | def dieSimulator(self, n: int, roll_max: List[int]) -> int: 7 | MOD = 10 ** 9 + 7 8 | 9 | @lru_cache(None) 10 | def dp(pos: int, rolls: int) -> int: 11 | if pos == 0: 12 | return 1 13 | 14 | count = 0 15 | for dice in range(6): 16 | roll = (rolls >> (dice * 4)) & 0x0F 17 | if roll < roll_max[dice]: 18 | count += dp(pos - 1, (roll + 1) << (dice * 4)) % MOD 19 | 20 | return count % MOD 21 | 22 | return dp(n, 0) 23 | -------------------------------------------------------------------------------- /l33tcode/distinct-numbers-in-each-subarray.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | def distinctNumbers(self, nums: list[int], k: int) -> list[int]: 6 | counter = Counter(nums[:k]) 7 | 8 | result: list[int] = [] 9 | 10 | for pos in range(len(nums) - k + 1): 11 | result.append(len(counter)) 12 | 13 | if counter[nums[pos]] > 0: 14 | counter[nums[pos]] -= 1 15 | if counter[nums[pos]] == 0: 16 | del counter[nums[pos]] 17 | 18 | if pos + k < len(nums): 19 | counter[nums[pos + k]] += 1 20 | 21 | return result 22 | -------------------------------------------------------------------------------- /l33tcode/distinct-subsequences.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | 4 | class Solution: 5 | def numDistinct(self, source: str, target: str) -> int: 6 | @lru_cache(None) 7 | def dp(source_pos: int, target_pos: int) -> int: 8 | if target_pos == len(target): 9 | return 1 10 | 11 | if source_pos == len(source): 12 | return 0 13 | 14 | ways = 0 15 | 16 | if source[source_pos] == target[target_pos]: 17 | ways += dp(source_pos + 1, target_pos + 1) 18 | 19 | ways += dp(source_pos + 1, target_pos) 20 | 21 | return ways 22 | 23 | return dp(0, 0) 24 | -------------------------------------------------------------------------------- /l33tcode/distribute-candies.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def distributeCandies(self, candyType: List[int]) -> int: 6 | candy_types = set(candyType) 7 | 8 | return min(len(candyType) // 2, len(candy_types)) 9 | -------------------------------------------------------------------------------- /l33tcode/divisor-game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def divisors(self, num): 3 | for cand in range(1, int(num ** 0.5) + 1, 1 if num % 2 == 0 else 2): 4 | if num % cand == 0: 5 | yield cand 6 | 7 | def divisorGame(self, N): 8 | return N % 2 == 0 9 | 10 | def divisorGameStraightForwardSolution(self, N): 11 | dp = [False] * (N + 1) 12 | 13 | for start in range(2, N + 1): 14 | for divisor in self.divisors(start): 15 | if not dp[start - divisor]: 16 | dp[start] = True 17 | 18 | return dp[N] 19 | -------------------------------------------------------------------------------- /l33tcode/eliminate-maximum-number-of-monsters.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: 6 | times = [dist[i] / speed[i] for i in range(len(dist))] 7 | 8 | times.sort() 9 | 10 | eliminated = 0 11 | 12 | for time in times: 13 | if time <= eliminated: 14 | break 15 | eliminated += 1 16 | 17 | return eliminated 18 | -------------------------------------------------------------------------------- /l33tcode/excel-sheet-column-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def titleToNumber(self, s: str) -> int: 3 | def char_to_int(s: str) -> int: 4 | return ord(s) - ord("A") + 1 5 | 6 | def number_of_letters() -> int: 7 | return char_to_int("Z") 8 | 9 | result = 0 10 | 11 | for char in s: 12 | result *= number_of_letters() 13 | result += char_to_int(char) 14 | 15 | return result 16 | -------------------------------------------------------------------------------- /l33tcode/excel-sheet-column-title.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def convertToTitle(self, num: int) -> str: 6 | column: List[int] = [] 7 | 8 | while num: 9 | column.append((num - 1) % 26) 10 | num = (num - 1) // 26 11 | 12 | return "".join(reversed(list(map(lambda c: chr(ord("A") + c), column)))) 13 | -------------------------------------------------------------------------------- /l33tcode/extra-characters-in-a-string.py: -------------------------------------------------------------------------------- 1 | from functools import cache 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def minExtraChar(self, string: str, words: List[str]) -> int: 7 | @cache 8 | def dp(pos: int) -> int: 9 | if pos == len(string): 10 | return 0 11 | 12 | # Skip symbol 13 | min_skip = dp(pos + 1) + 1 14 | 15 | for word in words: 16 | if string[pos : pos + len(word)] == word: 17 | # Use word 18 | min_skip = min(min_skip, dp(pos + len(word))) 19 | 20 | return min_skip 21 | 22 | return dp(0) 23 | -------------------------------------------------------------------------------- /l33tcode/find-all-anagrams-in-a-string.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findAnagrams(s string, p string) []int { 4 | counter := map[byte]int{} 5 | 6 | for pos := range p { 7 | counter[p[pos]]++ 8 | } 9 | 10 | left, right := 0, 0 11 | 12 | result := []int{} 13 | 14 | for right < len(s) { 15 | count, right_count_ok := counter[s[right]] 16 | if right_count_ok && count > 0 { 17 | counter[s[right]]-- 18 | right++ 19 | } else { 20 | _, left_count_ok := counter[s[left]] 21 | if left_count_ok { 22 | counter[s[left]]++ 23 | } 24 | left++ 25 | if left > right { 26 | right = left 27 | } 28 | } 29 | if right-left == len(p) { 30 | result = append(result, left) 31 | } 32 | } 33 | 34 | return result 35 | } 36 | -------------------------------------------------------------------------------- /l33tcode/find-all-duplicates-in-an-array.go: -------------------------------------------------------------------------------- 1 | func findDuplicates(nums []int) []int { 2 | result := []int{} 3 | for pos := range nums { 4 | num := nums[pos] 5 | if num < 0 { 6 | num *= -1 7 | } 8 | if nums[num-1] < 0 { 9 | result = append(result, num) 10 | } 11 | nums[num-1] *= -1 12 | } 13 | 14 | return result 15 | } 16 | -------------------------------------------------------------------------------- /l33tcode/find-and-replace-in-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str: 3 | index_map = {indexes[i]: {"source": sources[i], "target": targets[i]} for i in range(len(indexes))} 4 | 5 | pos = 0 6 | result = "" 7 | 8 | while pos < len(S): 9 | if pos in index_map and S[pos:].startswith(index_map[pos]["source"]): 10 | result += index_map[pos]["target"] 11 | pos += len(index_map[pos]["source"]) 12 | else: 13 | result += S[pos] 14 | pos += 1 15 | 16 | return result 17 | -------------------------------------------------------------------------------- /l33tcode/find-and-replace-pattern.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findAndReplacePattern(words []string, pattern string) []string { 4 | result := []string{} 5 | 6 | for _, word := range words { 7 | pat_to_word := map[byte]byte{} 8 | word_to_pat := map[byte]byte{} 9 | for pos, _ := range word { 10 | var ok bool 11 | _, ok = pat_to_word[pattern[pos]] 12 | if ok && word[pos] != pat_to_word[pattern[pos]] { 13 | break 14 | } 15 | 16 | _, ok = word_to_pat[word[pos]] 17 | if ok && pattern[pos] != word_to_pat[word[pos]] { 18 | break 19 | } 20 | 21 | pat_to_word[pattern[pos]] = word[pos] 22 | word_to_pat[word[pos]] = pattern[pos] 23 | 24 | if pos == len(word)-1 { 25 | result = append(result, word) 26 | } 27 | } 28 | } 29 | 30 | return result 31 | } 32 | -------------------------------------------------------------------------------- /l33tcode/find-k-length-substrings-with-no-repeated-characters.py: -------------------------------------------------------------------------------- 1 | from typing import Set 2 | 3 | 4 | class Solution: 5 | def numKLenSubstrNoRepeats(self, S: str, K: int) -> int: 6 | left, right = 0, 0 7 | 8 | count = 0 9 | seen: Set[str] = set() 10 | 11 | while right < len(S): 12 | while S[right] in seen: 13 | seen.discard(S[left]) 14 | left += 1 15 | 16 | seen.add(S[right]) 17 | 18 | right += 1 19 | 20 | if right - left >= K: 21 | count += 1 22 | 23 | return count 24 | -------------------------------------------------------------------------------- /l33tcode/find-minimum-in-rotated-sorted-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMin(self, nums: List[int]) -> int: 3 | left, right = 0, len(nums) 4 | 5 | while left < right: 6 | mid = (left + right) // 2 7 | 8 | if nums[mid] >= nums[0]: 9 | left = mid + 1 10 | else: 11 | right = mid 12 | 13 | return nums[left % len(nums)] 14 | -------------------------------------------------------------------------------- /l33tcode/find-peak-element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findPeakElement(self, nums: List[int]) -> int: 3 | left, right = 0, len(nums) - 1 4 | 5 | while left < right: 6 | mid = (left + right) // 2 7 | 8 | if nums[mid] < nums[mid + 1]: 9 | left = mid + 1 10 | else: 11 | right = mid 12 | 13 | return left 14 | -------------------------------------------------------------------------------- /l33tcode/find-the-difference.py: -------------------------------------------------------------------------------- 1 | from itertools import chain 2 | from collections import Counter 3 | 4 | 5 | class Solution: 6 | def findTheDifference(self, s: str, t: str) -> str: 7 | xor = 0 8 | 9 | for char in chain(s, t): 10 | xor ^= ord(char) 11 | 12 | return chr(xor) 13 | 14 | def findTheDifferenceHasMap(self, s: str, t: str) -> str: 15 | count = Counter() 16 | 17 | for char in t: 18 | count[char] += 1 19 | 20 | for char in s: 21 | count[char] -= 1 22 | 23 | for char, char_count in count.items(): 24 | if char_count > 0: 25 | return char 26 | -------------------------------------------------------------------------------- /l33tcode/find-the-duplicate-number.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findDuplicate(nums []int) int { 4 | ptrSlow, ptrFast := nums[0], nums[nums[0]] 5 | 6 | for ptrSlow != ptrFast { 7 | ptrSlow = nums[ptrSlow] 8 | ptrFast = nums[ptrFast] 9 | ptrFast = nums[ptrFast] 10 | } 11 | 12 | ptrSlow = 0 13 | for ptrSlow != ptrFast { 14 | ptrSlow = nums[ptrSlow] 15 | ptrFast = nums[ptrFast] 16 | } 17 | 18 | return ptrSlow 19 | } 20 | -------------------------------------------------------------------------------- /l33tcode/find-the-original-array-of-prefix-xor.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findArray(self, pref: List[int]) -> List[int]: 6 | return [pref[0]] + [pref[i - 1] ^ pref[i] for i in range(1, len(pref))] 7 | -------------------------------------------------------------------------------- /l33tcode/find-the-smallest-divisor-given-a-threshold.py: -------------------------------------------------------------------------------- 1 | import math 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def smallestDivisor(self, nums: List[int], threshold: int) -> int: 7 | def calc_sum(divisor: int) -> int: 8 | return sum(map(lambda num: math.ceil(num / divisor), nums)) 9 | 10 | total = sum(nums) 11 | left, right = max(1, total // threshold), max(nums) 12 | 13 | while left < right: 14 | middle = left + (right - left) // 2 15 | 16 | if calc_sum(middle) > threshold: 17 | left = middle + 1 18 | else: 19 | right = middle 20 | 21 | return right 22 | -------------------------------------------------------------------------------- /l33tcode/find-the-town-judge.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findJudge(N int, trust [][]int) int { 4 | if N == 1 && len(trust) == 0 { 5 | return 1 6 | } 7 | 8 | exempted := map[int]bool{} 9 | possible_judges := map[int]int{} 10 | 11 | for _, connection := range trust { 12 | from, to := connection[0], connection[1] 13 | exempted[from] = true 14 | delete(possible_judges, from) 15 | _, ok := exempted[to] 16 | 17 | if !ok { 18 | possible_judges[to] += 1 19 | } 20 | } 21 | 22 | if len(possible_judges) == 1 { 23 | for judge, count := range possible_judges { 24 | if count == N - 1 { 25 | return judge 26 | } 27 | } 28 | } 29 | 30 | return -1 31 | } 32 | -------------------------------------------------------------------------------- /l33tcode/first-bad-version.py: -------------------------------------------------------------------------------- 1 | # The isBadVersion API is already defined for you. 2 | # @param version, an integer 3 | # @return a bool 4 | # def isBadVersion(version): 5 | 6 | class Solution: 7 | def firstBadVersion(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | left, right = 0, n + 1 13 | 14 | while left < right: 15 | mid = (left + right) // 2 16 | 17 | bad = isBadVersion(mid) 18 | 19 | if bad: 20 | right = mid 21 | else: 22 | left = mid + 1 23 | 24 | if left < n + 1: 25 | return left 26 | 27 | return -1 28 | -------------------------------------------------------------------------------- /l33tcode/first-unique-character-in-a-string.go: -------------------------------------------------------------------------------- 1 | func firstUniqChar(s string) int { 2 | count := map[rune]int{} 3 | 4 | for _, char := range s { 5 | count[char] += 1 6 | } 7 | 8 | for pos, char := range s { 9 | if count[char] == 1 { 10 | return pos 11 | } 12 | } 13 | 14 | return -1 15 | } 16 | -------------------------------------------------------------------------------- /l33tcode/fizz-buzz.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fizzBuzz(self, n: int) -> List[str]: 3 | result = [] 4 | 5 | for number in range(1, n + 1): 6 | string = "" 7 | 8 | if number % 3 == 0: 9 | string += "Fizz" 10 | if number % 5 == 0: 11 | string += "Buzz" 12 | 13 | string = string or str(number) 14 | 15 | result.append(string) 16 | 17 | return result 18 | -------------------------------------------------------------------------------- /l33tcode/flipping-an-image.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: 6 | rows, cols = len(A), len(A[0]) if A else 0 7 | 8 | def flip(row: List[int]) -> None: 9 | left, right = 0, cols - 1 10 | 11 | while left < right: 12 | row[left], row[right] = row[right], row[left] 13 | left += 1 14 | right -= 1 15 | 16 | def inverse(row: List[int]) -> None: 17 | for col in range(cols): 18 | row[col] = 1 - row[col] 19 | 20 | for row in range(rows): 21 | flip(A[row]) 22 | inverse(A[row]) 23 | 24 | return A 25 | -------------------------------------------------------------------------------- /l33tcode/generate-random-point-in-a-circle.py: -------------------------------------------------------------------------------- 1 | import random 2 | import math 3 | from typing import List 4 | 5 | 6 | class Solution: 7 | def __init__(self, radius: float, x_center: float, y_center: float): 8 | self._radius = radius 9 | self._x, self._y = x_center, y_center 10 | 11 | def randPoint(self) -> List[float]: 12 | angle = random.uniform(0.0, 2 * math.pi) 13 | distance = math.sqrt(random.uniform(0.0, 1.0)) * self._radius 14 | 15 | x = self._x + distance * math.sin(angle) 16 | y = self._y + distance * math.cos(angle) 17 | 18 | return [x, y] 19 | 20 | 21 | # Your Solution object will be instantiated and called as such: 22 | # obj = Solution(radius, x_center, y_center) 23 | # param_1 = obj.randPoint() 24 | -------------------------------------------------------------------------------- /l33tcode/get-maximum-in-generated-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getMaximumGenerated(self, n: int) -> int: 3 | if n == 0: 4 | return 0 5 | 6 | nums = [0] * (n + 1) 7 | nums[1] = 1 8 | 9 | for pos in range(2, len(nums)): 10 | if pos % 2 == 0: 11 | nums[pos] = nums[pos // 2] 12 | else: 13 | nums[pos] = nums[pos // 2] + nums[pos // 2 + 1] 14 | 15 | return max(nums) 16 | -------------------------------------------------------------------------------- /l33tcode/goat-latin.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def toGoatLatin(self, S: str) -> str: 3 | words = [] 4 | vowels = set("aeiou") 5 | 6 | for pos, word in enumerate(S.split(" ")): 7 | if word[0].lower() not in vowels: 8 | word = word[1:] + word[0] 9 | 10 | word = word + "ma" + "a" * (pos + 1) 11 | words.append(word) 12 | 13 | return " ".join(words) 14 | -------------------------------------------------------------------------------- /l33tcode/group-the-people-given-the-group-size-they-belong-to.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func groupThePeople(groupSizes []int) [][]int { 4 | groups := map[int][]int{} 5 | 6 | result := [][]int{} 7 | 8 | for pos, size := range groupSizes { 9 | _, ok := groups[size] 10 | if !ok { 11 | groups[size] = []int{} 12 | } 13 | groups[size] = append(groups[size], pos) 14 | if len(groups[size]) == size { 15 | result = append(result, groups[size]) 16 | groups[size] = []int{} 17 | } 18 | } 19 | 20 | return result 21 | } 22 | -------------------------------------------------------------------------------- /l33tcode/guess-number-higher-or-lower.py: -------------------------------------------------------------------------------- 1 | # The guess API is already defined for you. 2 | # @param num, your guess 3 | # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 4 | # def guess(num): 5 | 6 | class Solution(object): 7 | def guessNumber(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | left, right = 0, n 13 | 14 | while left <= right: 15 | mid = (left + right) // 2 16 | guess_mid = guess(mid) 17 | 18 | if guess_mid == 0: 19 | return mid 20 | elif guess_mid > 0: 21 | left = mid + 1 22 | else: 23 | right = mid - 1 24 | -------------------------------------------------------------------------------- /l33tcode/h-index.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | 4 | class Solution: 5 | def hIndex(self, citations: List[int]) -> int: 6 | heap = [] 7 | 8 | for number in citations: 9 | heapq.heappush(heap, number) 10 | if heap[0] < len(heap): 11 | heapq.heappop(heap) 12 | 13 | return len(heap) 14 | -------------------------------------------------------------------------------- /l33tcode/hamming-distance.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingDistance(self, x: int, y: int) -> int: 3 | num = x ^ y 4 | 5 | distance = 0 6 | 7 | while num: 8 | distance += 1 9 | num &= num - 1 10 | 11 | return distance 12 | -------------------------------------------------------------------------------- /l33tcode/height-checker.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def heightChecker(self, heights: List[int]) -> int: 3 | result = 0 4 | for pos, h in enumerate(sorted(heights)): 5 | if heights[pos] != h: 6 | result += 1 7 | 8 | return result 9 | -------------------------------------------------------------------------------- /l33tcode/house-robber-iii.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, val=0, left=None, right=None): 7 | # self.val = val 8 | # self.left = left 9 | # self.right = right 10 | 11 | 12 | class Solution: 13 | def rob(self, root: TreeNode) -> int: 14 | @lru_cache(None) 15 | def dfs(node: TreeNode, can_take: bool) -> int: 16 | if not node: 17 | return 0 18 | 19 | return max( 20 | node.val + dfs(node.left, False) + dfs(node.right, False) 21 | if can_take 22 | else 0, 23 | dfs(node.left, True) + dfs(node.right, True), 24 | ) 25 | 26 | return dfs(root, True) 27 | -------------------------------------------------------------------------------- /l33tcode/implement-stack-using-queues.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | from typing import Deque 3 | 4 | 5 | class MyStack: 6 | _queue: Deque[int] 7 | 8 | def __init__(self): 9 | self._queue: Deque[int] = deque() 10 | 11 | def push(self, x: int) -> None: 12 | self._queue.append(x) 13 | 14 | def pop(self) -> int: 15 | self._queue.rotate(-(len(self._queue) - 1)) 16 | 17 | return self._queue.popleft() 18 | 19 | def top(self) -> int: 20 | result = self.pop() 21 | self.push(result) 22 | 23 | return result 24 | 25 | def empty(self) -> bool: 26 | return len(self._queue) == 0 27 | -------------------------------------------------------------------------------- /l33tcode/inorder-successor-in-bst-ii.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | # Definition for a Node. 5 | class Node: 6 | def __init__(self, val): 7 | self.val = val 8 | self.left = None 9 | self.right = None 10 | self.parent = None 11 | 12 | 13 | class Solution: 14 | def inorderSuccessor(self, node: Optional[Node]) -> Optional[Node]: 15 | if not node: 16 | return None 17 | 18 | if node.right: 19 | node = node.right 20 | while node.left: 21 | node = node.left 22 | 23 | return node 24 | else: 25 | while node.parent and node.parent.right == node: 26 | node = node.parent 27 | 28 | return node.parent 29 | -------------------------------------------------------------------------------- /l33tcode/inorder-successor-in-bst.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 inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': 10 | successor = None 11 | 12 | node = root 13 | 14 | while node: 15 | if node.val <= p.val: 16 | node = node.right 17 | else: 18 | successor = node 19 | node = node.left 20 | 21 | return successor 22 | -------------------------------------------------------------------------------- /l33tcode/insufficient-nodes-in-root-to-leaf-paths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode: 3 | if root is None: 4 | return root 5 | 6 | def dfs(node, sum_before): 7 | if node is None: 8 | return sum_before < limit 9 | 10 | left = dfs(node.left, node.val + sum_before) 11 | 12 | right = dfs(node.right, node.val + sum_before) 13 | 14 | if left: 15 | node.left = None 16 | 17 | if right: 18 | node.right = None 19 | 20 | return left and right 21 | 22 | delete = dfs(root, 0) 23 | 24 | return None if delete else root 25 | -------------------------------------------------------------------------------- /l33tcode/interleaving-string.py: -------------------------------------------------------------------------------- 1 | from functools import cache 2 | 3 | 4 | class Solution: 5 | def isInterleave(self, s1: str, s2: str, s3: str) -> bool: 6 | @cache 7 | def dp(ptr1: int, ptr2: int, ptr3: int) -> bool: 8 | if ptr3 == len(s3): 9 | return ptr1 == len(s1) and ptr2 == len(s2) 10 | 11 | result = False 12 | 13 | if ptr1 < len(s1) and s1[ptr1] == s3[ptr3]: 14 | result = result or dp(ptr1 + 1, ptr2, ptr3 + 1) 15 | 16 | if ptr2 < len(s2) and s2[ptr2] == s3[ptr3]: 17 | result = result or dp(ptr1, ptr2 + 1, ptr3 + 1) 18 | 19 | return result 20 | 21 | return dp(0, 0, 0) 22 | -------------------------------------------------------------------------------- /l33tcode/invert-binary-tree.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func invertTree(root *TreeNode) *TreeNode { 10 | var dfs func(node *TreeNode) *TreeNode 11 | dfs = func(node *TreeNode) *TreeNode { 12 | if node != nil { 13 | node.Left, node.Right = dfs(node.Right), dfs(node.Left) 14 | } 15 | 16 | return node 17 | } 18 | 19 | return dfs(root) 20 | } 21 | -------------------------------------------------------------------------------- /l33tcode/isomorphic-strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isIsomorphic(self, s: str, t: str) -> bool: 3 | mutation_fwd = {} 4 | mutation_back = {} 5 | 6 | for pos in range(len(s)): 7 | mutation_fwd.setdefault(s[pos], t[pos]) 8 | mutation_back.setdefault(t[pos], s[pos]) 9 | if mutation_fwd[s[pos]] != t[pos]: 10 | return False 11 | if mutation_back[t[pos]] != s[pos]: 12 | return False 13 | 14 | return True 15 | -------------------------------------------------------------------------------- /l33tcode/jump-game-iii.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from functools import lru_cache 3 | 4 | 5 | class Solution: 6 | def canReach(self, arr: List[int], start: int) -> bool: 7 | visited = set() 8 | 9 | @lru_cache(None) 10 | def dp(pos: int) -> bool: 11 | if pos in visited: 12 | return False 13 | 14 | if pos < 0 or pos >= len(arr): 15 | return False 16 | 17 | if arr[pos] == 0: 18 | return True 19 | 20 | visited.add(pos) 21 | 22 | return dp(pos + arr[pos]) or dp(pos - arr[pos]) 23 | 24 | return dp(start) 25 | -------------------------------------------------------------------------------- /l33tcode/jump-game.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func canJump(nums []int) bool { 4 | lastReachable := 0 5 | 6 | for pos, num := range nums { 7 | if pos <= lastReachable { 8 | if pos+num > lastReachable { 9 | lastReachable = pos + num 10 | } 11 | } else { 12 | return false 13 | } 14 | } 15 | return true 16 | } 17 | -------------------------------------------------------------------------------- /l33tcode/keys-and-rooms.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func open(room int, unlocked []bool, rooms [][]int) { 4 | unlocked[room] = true 5 | 6 | for _, key := range rooms[room] { 7 | if !unlocked[key] { 8 | open(key, unlocked, rooms) 9 | } 10 | } 11 | } 12 | 13 | func canVisitAllRooms(rooms [][]int) bool { 14 | unlocked := make([]bool, len(rooms)) 15 | 16 | for pos, _ := range unlocked { 17 | unlocked[pos] = false 18 | } 19 | 20 | open(0, unlocked, rooms) 21 | 22 | for pos, _ := range unlocked { 23 | if !unlocked[pos] { 24 | return false 25 | } 26 | } 27 | 28 | return true 29 | } 30 | -------------------------------------------------------------------------------- /l33tcode/largest-submatrix-with-rearrangements.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def largestSubmatrix(self, matrix: List[List[int]]) -> int: 6 | rows, cols = len(matrix), len(matrix[0]) 7 | 8 | cache: List[List[int]] = [matrix[row].copy() for row in range(rows)] 9 | 10 | for col in range(cols): 11 | for row in range(1, rows): 12 | if matrix[row][col] == 1: 13 | cache[row][col] = cache[row - 1][col] + 1 14 | 15 | max_area = 0 16 | 17 | for row in range(rows): 18 | cache[row].sort(reverse=True) 19 | 20 | for col in range(cols): 21 | max_area = max(max_area, (col + 1) * cache[row][col]) 22 | 23 | return max_area 24 | -------------------------------------------------------------------------------- /l33tcode/last-moment-before-all-ants-fall-out-of-a-plank.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int: 6 | return max(max(left) if left else 0, (n - min(right)) if right else 0) 7 | -------------------------------------------------------------------------------- /l33tcode/leaf-similar-trees.py: -------------------------------------------------------------------------------- 1 | from itertools import chain, zip_longest 2 | 3 | 4 | class Solution: 5 | def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: 6 | def dfs(node): 7 | if node: 8 | if not node.left and not node.right: 9 | yield node.val 10 | yield from chain(dfs(node.left), dfs(node.right)) 11 | 12 | return all(l == r for l, r in zip_longest(dfs(root1), dfs(root2))) 13 | -------------------------------------------------------------------------------- /l33tcode/length-of-last-word.py: -------------------------------------------------------------------------------- 1 | from typing import Tuple 2 | 3 | 4 | class Solution: 5 | def lengthOfLastWord(self, s: str) -> int: 6 | def get_word(pos: int) -> Tuple[int, int]: 7 | word_length = 0 8 | while pos < len(s) and s[pos] != " ": 9 | pos += 1 10 | word_length += 1 11 | 12 | return word_length, pos 13 | 14 | pos = 0 15 | last_word_length = 0 16 | 17 | while pos < len(s): 18 | if s[pos] == " ": 19 | pos += 1 20 | else: 21 | last_word_length, pos = get_word(pos) 22 | 23 | return last_word_length 24 | -------------------------------------------------------------------------------- /l33tcode/length-of-longest-fibonacci-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lenLongestFibSubseq(self, arr: list[int]) -> int: 3 | num_to_prev_length: dict[int, dict[int, int]] = {n: {} for n in arr} 4 | 5 | arr.sort() 6 | 7 | longest = 0 8 | 9 | for i in range(len(arr)): 10 | for j in range(i): 11 | if arr[i] - arr[j] in num_to_prev_length[arr[j]]: 12 | length = num_to_prev_length[arr[j]][arr[i] - arr[j]] + 1 13 | num_to_prev_length[arr[i]][arr[j]] = length 14 | longest = max(longest, length) 15 | else: 16 | num_to_prev_length[arr[i]][arr[j]] = 2 17 | 18 | return longest 19 | -------------------------------------------------------------------------------- /l33tcode/letter-case-permutation.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def letterCasePermutation(self, S: str) -> List[str]: 6 | result: List[str] = [] 7 | 8 | def backtrack(pos: int, path: List[str]) -> None: 9 | if pos == len(S): 10 | result.append("".join(path)) 11 | return 12 | 13 | for char in {S[pos].lower(), S[pos].upper()}: 14 | path.append(char) 15 | backtrack(pos + 1, path) 16 | path.pop() 17 | 18 | backtrack(0, []) 19 | 20 | return result 21 | -------------------------------------------------------------------------------- /l33tcode/license-key-formatting.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def licenseKeyFormatting(self, S: str, K: int) -> str: 3 | pos = len(S) - 1 4 | actual_pos = 0 5 | 6 | alphanum = set(x for x in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789") 7 | output = [] 8 | 9 | while pos >= 0: 10 | if S[pos] in alphanum: 11 | if actual_pos > 0 and actual_pos % K == 0: 12 | output += ["-"] 13 | output += [S[pos].upper()] 14 | actual_pos += 1 15 | 16 | pos -= 1 17 | 18 | return "".join(reversed(output)) 19 | -------------------------------------------------------------------------------- /l33tcode/linked-list-cycle.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from dataclasses import dataclass 4 | from typing import Optional 5 | 6 | 7 | @dataclass 8 | class ListNode: 9 | val: int 10 | next: Optional[ListNode] 11 | 12 | 13 | class Solution: 14 | def hasCycle(self, head: ListNode) -> bool: 15 | fast, slow = head, head 16 | 17 | while fast: 18 | slow = slow.next # type: ignore 19 | if fast.next: 20 | fast = fast.next.next 21 | else: 22 | fast = None 23 | 24 | if slow and slow == fast: 25 | return True 26 | 27 | return False 28 | -------------------------------------------------------------------------------- /l33tcode/longest-arithmetic-sequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestArithSeqLength(self, A: List[int]) -> int: 3 | dp = defaultdict(lambda: defaultdict(lambda: 1)) 4 | result = 0 5 | 6 | for pos in range(len(A)): 7 | for prev_pos in range(pos): 8 | diff = A[pos] - A[prev_pos] 9 | dp[pos][diff] = dp[prev_pos][diff] + 1 10 | result = max(result, dp[pos][diff]) 11 | 12 | return result 13 | -------------------------------------------------------------------------------- /l33tcode/longest-arithmetic-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestArithSeqLength(self, A: List[int]) -> int: 3 | dp = [] 4 | 5 | for pos_right in range(len(A)): 6 | dp.append({0: 1}) 7 | for pos_left in range(pos_right): 8 | diff = A[pos_left] - A[pos_right] 9 | dp[pos_right][diff] = max( 10 | dp[pos_right].get(diff, 1), 11 | dp[pos_left].get(diff, 1) + 1 12 | ) 13 | 14 | return max(dp[-1].values()) 15 | -------------------------------------------------------------------------------- /l33tcode/longest-harmonious-subsequence.py: -------------------------------------------------------------------------------- 1 | from typing import Counter, List 2 | 3 | 4 | class Solution: 5 | def findLHS(self, nums: List[int]) -> int: 6 | counter = Counter(nums) 7 | longest_harmonious_subsequence = 0 8 | 9 | for num in nums: 10 | for count in (counter[num + 1], counter[num - 1]): 11 | if count: 12 | longest_harmonious_subsequence = max( 13 | longest_harmonious_subsequence, 14 | counter[num] + count, 15 | ) 16 | 17 | return longest_harmonious_subsequence 18 | -------------------------------------------------------------------------------- /l33tcode/longest-palindrome.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | def longestPalindrome(self, s: str) -> int: 6 | even, odd = 0, 0 7 | 8 | char_count = Counter() 9 | 10 | for char in s: 11 | char_count[char] += 1 12 | if char_count[char] % 2 == 0: 13 | odd -= 1 14 | even += 1 15 | else: 16 | odd += 1 17 | 18 | return even * 2 + int(odd > 0) 19 | -------------------------------------------------------------------------------- /l33tcode/majority-element.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func majorityElement(nums []int) int { 4 | candidate, count := 0, 0 5 | 6 | for _, num := range nums { 7 | if count == 0 { 8 | candidate = num 9 | count += 1 10 | } else if num == candidate { 11 | count += 1 12 | } else { 13 | count -= 1 14 | } 15 | } 16 | 17 | return candidate 18 | } 19 | -------------------------------------------------------------------------------- /l33tcode/make-the-prefix-sum-non-negative.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | 4 | class Solution: 5 | def makePrefSumNonNegative(self, nums: list[int]) -> int: 6 | heap: list[int] = [] 7 | prefix_sum = 0 8 | swaps = 0 9 | 10 | for num in nums: 11 | if num < 0: 12 | heapq.heappush(heap, num) 13 | 14 | prefix_sum += num 15 | 16 | if prefix_sum < 0: 17 | prefix_sum -= heapq.heappop(heap) 18 | swaps += 1 19 | 20 | return swaps 21 | -------------------------------------------------------------------------------- /l33tcode/managers-with-at-least-5-direct-reports.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | b.name 3 | FROM 4 | Employee a 5 | JOIN Employee b ON a.managerId = b.id 6 | GROUP BY 7 | a.managerId 8 | HAVING 9 | count(*) >= 5 10 | -------------------------------------------------------------------------------- /l33tcode/max-consecutive-ones-ii.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findMaxConsecutiveOnes(nums []int) int { 4 | prevZeroOffset := 0 5 | maxCount, count := 0, 0 6 | 7 | for _, num := range nums { 8 | prevZeroOffset += 1 9 | 10 | if num == 1 { 11 | count += 1 12 | } else { 13 | count = prevZeroOffset 14 | prevZeroOffset = 0 15 | } 16 | 17 | if count > maxCount { 18 | maxCount = count 19 | } 20 | } 21 | 22 | return maxCount 23 | } 24 | -------------------------------------------------------------------------------- /l33tcode/max-consecutive-ones-iii.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def longestOnes(self, A: List[int], K: int) -> int: 6 | zeroes = 0 7 | longest_subsequence = 0 8 | 9 | left = 0 10 | 11 | for right in range(len(A)): 12 | if A[right] == 0: 13 | zeroes += 1 14 | 15 | while zeroes > K: 16 | if A[left] == 0: 17 | zeroes -= 1 18 | left += 1 19 | 20 | right += 1 21 | 22 | longest_subsequence = max(longest_subsequence, right - left) 23 | 24 | return longest_subsequence 25 | -------------------------------------------------------------------------------- /l33tcode/max-number-of-k-sum-pairs.py: -------------------------------------------------------------------------------- 1 | from typing import List, Dict, Counter 2 | 3 | 4 | class Solution: 5 | def maxOperations(self, nums: List[int], k: int) -> int: 6 | counter: Counter[int] = Counter(nums) 7 | 8 | operations = 0 9 | 10 | for num in nums: 11 | if counter[num] > 0: 12 | counter[num] -= 1 13 | 14 | if counter[k - num] > 0: 15 | operations += 1 16 | counter[k - num] -= 1 17 | 18 | return operations 19 | -------------------------------------------------------------------------------- /l33tcode/max-sum-of-a-pair-with-equal-sum-of-digits.go: -------------------------------------------------------------------------------- 1 | func maximumSum(nums []int) int { 2 | result := -1 3 | maxPrev := map[int]int{} 4 | 5 | for _, num := range nums { 6 | numCopy := num 7 | sumDigits := 0 8 | 9 | for numCopy > 0 { 10 | sumDigits = sumDigits + numCopy % 10 11 | numCopy = numCopy / 10 12 | } 13 | 14 | if prevNum, ok := maxPrev[sumDigits]; ok { 15 | if result < prevNum + num { 16 | result = prevNum + num 17 | } 18 | if prevNum < num { 19 | maxPrev[sumDigits] = num 20 | } 21 | } else { 22 | maxPrev[sumDigits] = num 23 | } 24 | } 25 | 26 | return result 27 | } 28 | -------------------------------------------------------------------------------- /l33tcode/max-sum-of-a-pair-with-equal-sum-of-digits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumSum(self, nums: list[int]) -> int: 3 | result = -1 4 | max_prev: dict[int, int] = {} 5 | 6 | for num in nums: 7 | sum_digits = 0 8 | num_copy = num 9 | while num_copy: 10 | sum_digits += num_copy % 10 11 | num_copy //= 10 12 | 13 | if prev_num := max_prev.get(sum_digits): 14 | result = max(result, prev_num + num) 15 | 16 | max_prev[sum_digits] = max(max_prev.get(sum_digits, 0), num) 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /l33tcode/maximize-distance-to-closest-person.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maxDistToClosest(self, seats: List[int]) -> int: 6 | start = -1 7 | 8 | max_distance = 0 9 | 10 | for pos in range(len(seats)): 11 | if seats[pos] == 1: 12 | if start == -1: 13 | start = -pos 14 | max_distance = max(max_distance, (pos - start) // 2) 15 | start = pos 16 | 17 | max_distance = max(max_distance, len(seats) - 1 - start) 18 | 19 | return max_distance 20 | -------------------------------------------------------------------------------- /l33tcode/maximum-absolute-sum-of-any-subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxAbsoluteSum(self, nums: list[int]) -> int: 3 | prev, prev_negative = 0, 0 4 | max_absolute_sum = 0 5 | 6 | for num in nums: 7 | prev += num 8 | prev_negative += num 9 | 10 | max_absolute_sum = max(max_absolute_sum, prev, -prev_negative) 11 | 12 | if prev < 0: 13 | prev = 0 14 | 15 | if prev_negative > 0: 16 | prev_negative = 0 17 | 18 | return max_absolute_sum 19 | -------------------------------------------------------------------------------- /l33tcode/maximum-bags-with-full-capacity-of-rocks.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func maximumBags(capacity []int, rocks []int, additionalRocks int) int { 6 | missing := make([]int, len(capacity)) 7 | 8 | for pos := range capacity { 9 | missing[pos] = capacity[pos] - rocks[pos] 10 | } 11 | 12 | sort.Ints(missing) 13 | 14 | result := 0 15 | 16 | for pos := range missing { 17 | if missing[pos] <= additionalRocks { 18 | result += 1 19 | additionalRocks -= missing[pos] 20 | } 21 | } 22 | 23 | return result 24 | } 25 | -------------------------------------------------------------------------------- /l33tcode/maximum-binary-string-after-change.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumBinaryString(self, binary: str) -> str: 3 | array = [0] * len(binary) 4 | ones = binary.count("1") 5 | if ones == len(binary): 6 | return binary 7 | 8 | for pos in range(len(array)): 9 | if binary[pos] == "1": 10 | ones -= 1 11 | else: 12 | break 13 | 14 | for pos in range(ones): 15 | array[-pos - 1] = 1 16 | 17 | for pos in range(len(array) - ones - 1): 18 | array[pos] = 1 19 | 20 | return "".join(map(str, array)) 21 | -------------------------------------------------------------------------------- /l33tcode/maximum-number-of-balloons.py: -------------------------------------------------------------------------------- 1 | from typing import Counter 2 | 3 | 4 | class Solution: 5 | def maxNumberOfBalloons(self, text: str) -> int: 6 | counter: Counter[str] = Counter(text) 7 | counter_baloon: Counter[str] = Counter("balloon") 8 | 9 | return min( 10 | counter[char] // counter_baloon[char] for char in counter_baloon.keys() 11 | ) 12 | -------------------------------------------------------------------------------- /l33tcode/maximum-number-of-coins-you-can-get.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maxCoins(self, piles: List[int]) -> int: 6 | piles.sort() 7 | 8 | left, right = 0, len(piles) - 2 9 | 10 | result = 0 11 | 12 | while left < right: 13 | result += piles[right] 14 | left += 1 15 | right -= 2 16 | 17 | return result 18 | -------------------------------------------------------------------------------- /l33tcode/maximum-number-of-vowels-in-a-substring-of-given-length.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxVowels(self, s: str, k: int) -> int: 3 | vowels_count = 0 4 | max_vowels_count = 0 5 | vowels = {"a", "e", "i", "o", "u"} 6 | 7 | for pos in range(len(s)): 8 | if pos >= k: 9 | if s[pos - k] in vowels: 10 | vowels_count -= 1 11 | 12 | if s[pos] in vowels: 13 | vowels_count += 1 14 | 15 | max_vowels_count = max(max_vowels_count, vowels_count) 16 | 17 | return max_vowels_count 18 | 19 | 20 | -------------------------------------------------------------------------------- /l33tcode/maximum-product-subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, nums): 3 | if not nums: 4 | return 0 5 | 6 | dp = set([nums[0]]) 7 | result = nums[0] 8 | 9 | for pos in range(1, len(nums)): 10 | old_dp = dp 11 | dp = set([nums[pos]] + [res * nums[pos] for res in dp]) 12 | result = max(result, max(dp)) 13 | 14 | return result 15 | -------------------------------------------------------------------------------- /l33tcode/maximum-repeating-substring.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxRepeating(self, sequence: str, word: str) -> int: 3 | def match(pos: int) -> bool: 4 | return sequence[pos : (pos + len(word))] == word 5 | 6 | max_repeats = 0 7 | for pos in range(len(sequence)): 8 | repeats = 0 9 | 10 | start = pos 11 | while match(start): 12 | start += len(word) 13 | repeats += 1 14 | 15 | max_repeats = max(repeats, max_repeats) 16 | 17 | return max_repeats 18 | -------------------------------------------------------------------------------- /l33tcode/maximum-running-time-of-n-computers.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | from typing import List 3 | 4 | class Solution: 5 | def maxRunTime(self, n: int, batteries: List[int]) -> int: 6 | heap = [-battery for battery in batteries] 7 | heapq.heapify(heap) 8 | 9 | running_time = 0 10 | 11 | while len(heap) >= n: 12 | running_on = [] 13 | 14 | for _ in range(n): 15 | running_on.append(-heapq.heappop(heap)) 16 | 17 | for battery in running_on: 18 | if battery > 1: 19 | heapq.heappush(heap, -(battery - 1)) 20 | 21 | running_time += 1 22 | 23 | return running_time 24 | -------------------------------------------------------------------------------- /l33tcode/maximum-sum-circular-subarray.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | func maxSubarraySumCircular(A []int) int { 8 | total := 0.0 9 | curMax, curMin := 0.0, 0.0 10 | overallMax, overallMin := float64(A[0]), 0.0 11 | 12 | for pos, _ := range A { 13 | num := float64(A[pos]) 14 | total += num 15 | if num+curMax >= 0 { 16 | curMax = num+curMax 17 | overallMax = math.Max(curMax, overallMax) 18 | } else { 19 | curMax = 0 20 | overallMax = math.Max(num, overallMax) 21 | } 22 | } 23 | 24 | for pos, _ := range A[:len(A)-1] { 25 | num := float64(A[pos]) 26 | curMin = math.Min(num+curMin, 0) 27 | overallMin = math.Min(curMin, overallMin) 28 | } 29 | 30 | return int(math.Max(overallMax, total-overallMin)) 31 | } 32 | -------------------------------------------------------------------------------- /l33tcode/mean-of-array-after-removing-some-elements.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def trimMean(self, arr: List[int]) -> float: 6 | arr.sort() 7 | 8 | cut_arr = arr[int(len(arr) * 0.05):int(len(arr) * 0.95)] 9 | 10 | return sum(cut_arr) / len(cut_arr) 11 | -------------------------------------------------------------------------------- /l33tcode/meeting-rooms.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canAttendMeetings(self, intervals: List[List[int]]) -> bool: 3 | intervals.sort() 4 | 5 | prev_end = -1 6 | 7 | for start, end in intervals: 8 | if start < prev_end: 9 | return False 10 | prev_end = end 11 | 12 | return True 13 | -------------------------------------------------------------------------------- /l33tcode/middle-of-the-linked-list.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func middleNode(head *ListNode) *ListNode { 9 | slow := head 10 | fast := head 11 | 12 | for fast.Next != nil && fast.Next.Next != nil { 13 | slow = slow.Next 14 | fast = fast.Next.Next 15 | } 16 | 17 | if fast.Next == nil { 18 | return slow 19 | } 20 | 21 | return slow.Next 22 | } 23 | -------------------------------------------------------------------------------- /l33tcode/middle-of-the-linked-list.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 | 8 | class Solution: 9 | def middleNode(self, head: ListNode) -> ListNode: 10 | if not head: 11 | return None 12 | 13 | middle, tail = head, head 14 | 15 | while tail: 16 | if tail and tail.next and tail.next.next: 17 | tail = tail.next.next 18 | elif tail and tail.next: 19 | return middle.next 20 | elif tail: 21 | return middle 22 | 23 | middle = middle.next 24 | -------------------------------------------------------------------------------- /l33tcode/min-cost-climbing-stairs.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from functools import lru_cache 3 | 4 | 5 | class Solution: 6 | def minCostClimbingStairs(self, cost: List[int]) -> int: 7 | @lru_cache(None) 8 | def dp(pos: int) -> int: 9 | if pos >= len(cost): 10 | return 0 11 | 12 | return min(dp(pos + 1) + cost[pos], dp(pos + 2) + cost[pos],) 13 | 14 | return min(dp(0), dp(1)) 15 | -------------------------------------------------------------------------------- /l33tcode/minimum-cost-for-tickets.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | 4 | MAX_PRICE = float("+inf") 5 | 6 | 7 | class Solution: 8 | def mincostTickets(self, days: List[int], costs: List[int]) -> int: 9 | @lru_cache 10 | def dfs(day: int) -> int: 11 | if day == len(days): 12 | return 0 13 | 14 | result = MAX_PRICE 15 | 16 | 17 | for valid_for, cost in zip([1, 7, 30], costs): 18 | next_day = day + 1 19 | while next_day < len(days) and (days[next_day] - days[day]) < valid_for: 20 | next_day += 1 21 | 22 | result = min(result, dfs(next_day) + cost) 23 | 24 | return result 25 | 26 | return dfs(0) 27 | -------------------------------------------------------------------------------- /l33tcode/minimum-cost-to-move-chips-to-the-same-position.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minCostToMoveChips(self, position: List[int]) -> int: 6 | return min( 7 | sum(map(lambda pos: pos % 2, position)), 8 | sum(map(lambda pos: (pos + 1) % 2, position)), 9 | ) 10 | -------------------------------------------------------------------------------- /l33tcode/minimum-deletions-to-make-character-frequencies-unique.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | from typing import Counter 3 | 4 | 5 | class Solution: 6 | def minDeletions(self, s: str) -> int: 7 | counts = Counter(Counter(s).values()) 8 | heap = [-num for num in counts.keys()] 9 | heapq.heapify(heap) 10 | 11 | deletions = 0 12 | 13 | while heap: 14 | num = -heapq.heappop(heap) 15 | count = counts[num] 16 | 17 | if count > 1: 18 | deletions += count - 1 19 | counts[num] -= count - 1 20 | if num - 1 > 0: 21 | counts[num - 1] += count - 1 22 | heapq.heappush(heap, -num + 1) 23 | 24 | return deletions 25 | -------------------------------------------------------------------------------- /l33tcode/minimum-difference-between-largest-and-smallest-value-in-three-moves.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minDifference(self, nums: List[int]) -> int: 3 | if len(nums) < 4: 4 | return 0 5 | 6 | nums.sort() 7 | 8 | partial_max = [] 9 | 10 | cur_max = float("-inf") 11 | 12 | for num in nums: 13 | cur_max = max(num, cur_max) 14 | partial_max.append(cur_max) 15 | 16 | result = float("+inf") 17 | 18 | for shift in range(4): 19 | result = min( 20 | result, 21 | partial_max[-1 - shift] - partial_max[3 - shift], 22 | ) 23 | 24 | return result 25 | -------------------------------------------------------------------------------- /l33tcode/minimum-moves-to-equal-array-elements-ii.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minMoves2(self, nums: List[int]) -> int: 6 | nums.sort() 7 | 8 | moves = sum(nums) - min(nums) * len(nums) 9 | 10 | min_moves = moves 11 | 12 | for pos in range(1, len(nums)): 13 | diff = nums[pos] - nums[pos - 1] 14 | moves -= diff * (len(nums) - pos) 15 | moves += diff * pos 16 | 17 | min_moves = min(min_moves, moves) 18 | 19 | return min_moves 20 | -------------------------------------------------------------------------------- /l33tcode/minimum-number-of-arrows-to-burst-balloons.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findMinArrowShots(self, points: List[List[int]]) -> int: 6 | points.sort() 7 | 8 | pos = 0 9 | arrows = 0 10 | while pos < len(points): 11 | arrows += 1 12 | start, end = points[pos] 13 | 14 | while pos < len(points) and points[pos][0] <= end: 15 | start = points[pos][0] 16 | end = min(end, points[pos][1]) 17 | 18 | pos += 1 19 | 20 | return arrows 21 | -------------------------------------------------------------------------------- /l33tcode/minimum-number-of-increments-on-subarrays-to-form-a-target-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minNumberOperations(self, target: List[int]) -> int: 3 | prev = 0 4 | result = 0 5 | 6 | for num in target: 7 | if num > prev: 8 | result += (num - prev) 9 | prev = num 10 | 11 | return result 12 | -------------------------------------------------------------------------------- /l33tcode/minimum-number-of-operations-to-make-array-continuous.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minOperations(self, nums: List[int]) -> int: 6 | total_len = len(nums) 7 | nums = sorted(set(nums)) 8 | 9 | min_ops = total_len 10 | 11 | right = 0 12 | 13 | for left in range(len(nums)): 14 | while right < len(nums) and nums[right] < nums[left] + total_len: 15 | right += 1 16 | 17 | min_ops = min(min_ops, total_len - (right - left)) 18 | 19 | return min_ops 20 | -------------------------------------------------------------------------------- /l33tcode/minimum-number-of-operations-to-make-array-empty.py: -------------------------------------------------------------------------------- 1 | from typing import Counter, List 2 | 3 | 4 | class Solution: 5 | def minOperations(self, nums: List[int]) -> int: 6 | counts = Counter(nums) 7 | 8 | ops = 0 9 | 10 | for count in counts.values(): 11 | if count == 1: 12 | return -1 13 | 14 | ops += count // 3 15 | 16 | if count % 3 != 0: 17 | ops += 1 18 | 19 | return ops 20 | -------------------------------------------------------------------------------- /l33tcode/minimum-operations-to-exceed-threshold-value-ii.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | 4 | class Solution: 5 | def minOperations(self, nums: list[int], k: int) -> int: 6 | heapq.heapify(nums) 7 | 8 | ops = 0 9 | 10 | while (first := heapq.heappop(nums)) < k: 11 | second = heapq.heappop(nums) 12 | heapq.heappush(nums, min(first, second) * 2 + max(first, second)) 13 | ops += 1 14 | 15 | return ops 16 | -------------------------------------------------------------------------------- /l33tcode/minimum-penalty-for-a-shop.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bestClosingTime(self, customers: str) -> int: 3 | penalty = customers.count("Y") # When we're always closed 4 | 5 | min_closing_time = 0 6 | min_penalty = penalty 7 | 8 | for closing_time in range(len(customers)): 9 | if customers[closing_time] == "Y": 10 | penalty -= 1 11 | else: 12 | penalty += 1 13 | 14 | if penalty < min_penalty: 15 | # `closing_time` 0 means we actually are still open and will 16 | # only close at the next timestamp 17 | min_closing_time = closing_time + 1 18 | min_penalty = penalty 19 | 20 | return min_closing_time 21 | -------------------------------------------------------------------------------- /l33tcode/minimum-swaps-to-group-all-1s-together.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minSwaps(self, data: List[int]) -> int: 6 | ones = data.count(1) 7 | 8 | zeroes = data[:ones].count(0) 9 | 10 | min_swaps = len(data) 11 | 12 | for right in range(ones, len(data)): 13 | min_swaps = min(min_swaps, zeroes) 14 | 15 | zeroes += 1 - data[right] 16 | zeroes -= 1 - data[right - ones] 17 | 18 | min_swaps = min(min_swaps, zeroes) 19 | 20 | return min_swaps 21 | -------------------------------------------------------------------------------- /l33tcode/minimum-swaps-to-make-sequences-increasing.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func minSwap(A []int, B []int) int { 4 | swapsRev, swapsSame := 1, 0 5 | 6 | for pos := 1; pos < len(A); pos++ { 7 | if A[pos-1] >= B[pos] || B[pos-1] >= A[pos] { 8 | swapsRev++ 9 | } else if A[pos-1] >= A[pos] || B[pos-1] >= B[pos] { 10 | swapsRev, swapsSame = swapsSame+1, swapsRev 11 | } else { 12 | if swapsRev < swapsSame { 13 | swapsRev, swapsSame = swapsRev+1, swapsRev 14 | } else { 15 | swapsRev, swapsSame = swapsSame+1, swapsSame 16 | } 17 | } 18 | } 19 | 20 | result := 0 21 | 22 | if swapsRev < swapsSame { 23 | result = swapsRev 24 | } else { 25 | result = swapsSame 26 | } 27 | 28 | return result 29 | } 30 | -------------------------------------------------------------------------------- /l33tcode/minimum-swaps-to-make-sequences-increasing.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSwap(self, A: List[int], B: List[int]) -> int: 3 | swaps_rev, swaps_same = 1, 0 4 | 5 | for pos in range(1, len(A)): 6 | if A[pos - 1] >= B[pos] or B[pos - 1] >= A[pos]: 7 | swaps_rev += 1 8 | elif A[pos - 1] >= A[pos] or B[pos - 1] >= B[pos]: 9 | swaps_rev, swaps_same = swaps_same + 1, swaps_rev 10 | else: 11 | swaps_same = min(swaps_rev, swaps_same) 12 | swaps_rev = swaps_same + 1 13 | 14 | return min(swaps_rev, swaps_same) 15 | -------------------------------------------------------------------------------- /l33tcode/minimum-value-to-get-positive-step-by-step-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minStartValue(self, nums: List[int]) -> int: 3 | minimum_value = float("+inf") 4 | total = 0 5 | 6 | for num in nums: 7 | total += num 8 | minimum_value = min(minimum_value, total) 9 | 10 | return max(1, 1 - minimum_value) 11 | -------------------------------------------------------------------------------- /l33tcode/missing-number.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def missingNumber(self, nums: List[int]) -> int: 6 | xor = 0 7 | 8 | for num in nums: 9 | xor ^= num 10 | 11 | for num in range(len(nums) + 1): 12 | xor ^= num 13 | 14 | return xor 15 | -------------------------------------------------------------------------------- /l33tcode/missing-ranges.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]: 3 | nums.insert(0, lower - 1) 4 | nums.append(upper + 1) 5 | result = [] 6 | 7 | for pos in range(len(nums) - 1): 8 | distance = nums[pos + 1] - nums[pos] 9 | if distance > 2: 10 | result.append("{}->{}".format(nums[pos] + 1, nums[pos + 1] - 1)) 11 | elif distance == 2: 12 | result.append(str(nums[pos] + 1)) 13 | 14 | return result 15 | -------------------------------------------------------------------------------- /l33tcode/moving-average-from-data-stream.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class MovingAverage: 4 | def __init__(self, size: int): 5 | """ 6 | Initialize your data structure here. 7 | """ 8 | self._size = size 9 | self._window = deque() 10 | self._moving_average = 0 11 | 12 | def next(self, val: int) -> float: 13 | left = self._window.popleft() if len(self._window) == self._size else self._moving_average 14 | self._window.append(val) 15 | self._moving_average += (val - left) / len(self._window) 16 | 17 | return self._moving_average 18 | 19 | 20 | # Your MovingAverage object will be instantiated and called as such: 21 | # obj = MovingAverage(size) 22 | # param_1 = obj.next(val) 23 | -------------------------------------------------------------------------------- /l33tcode/n-repeated-element-in-size-2n-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def repeatedNTimes(self, A): 3 | """ 4 | :type A: List[int] 5 | :rtype: int 6 | """ 7 | elem_hash_map = {} 8 | for elem in A: 9 | if elem in elem_hash_map: 10 | return elem 11 | else: 12 | elem_hash_map[elem] = None 13 | 14 | # No testing because it is quite obvious 15 | -------------------------------------------------------------------------------- /l33tcode/n-th-tribonacci-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def tribonacci(self, n: int) -> int: 3 | if n == 0: 4 | return 0 5 | 6 | if n < 3: 7 | return 1 8 | 9 | first, second, third = 0, 1, 1 10 | 11 | for _ in range(2, n): 12 | first, second, third = second, third, first + second + third 13 | 14 | return third 15 | -------------------------------------------------------------------------------- /l33tcode/nested-list-weight-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def depthSum(self, nestedList: List[NestedInteger]) -> int: 3 | def dfs(node: List[NestedInteger], depth: int) -> int: 4 | result = 0 5 | 6 | for next_node in node: 7 | if next_node.isInteger(): 8 | result += depth * next_node.getInteger() 9 | else: 10 | result += dfs(next_node.getList(), depth + 1) 11 | 12 | return result 13 | 14 | return dfs(nestedList, 1) 15 | -------------------------------------------------------------------------------- /l33tcode/next-greater-element-i.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: 6 | ans = [-1] * len(nums1) 7 | for i in range(len(nums1)): 8 | for j in range(len(nums2)): 9 | if nums1[i] == nums2[j]: 10 | for k in range(j + 1, len(nums2)): 11 | if nums2[j] < nums2[k]: 12 | ans[i] = nums2[k] 13 | break 14 | 15 | return ans 16 | -------------------------------------------------------------------------------- /l33tcode/number-complement.go: -------------------------------------------------------------------------------- 1 | func findComplement(num int) int { 2 | x := 1 3 | for x < num { 4 | x = x << 1 5 | x += 1 6 | } 7 | return ^num & x 8 | } 9 | -------------------------------------------------------------------------------- /l33tcode/number-of-1-bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, num: int) -> int: 3 | count = 0 4 | while num: 5 | count += num & 1 6 | num >>= 1 7 | 8 | return count 9 | -------------------------------------------------------------------------------- /l33tcode/number-of-dice-rolls-with-target-sum.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | 4 | class Solution: 5 | def numRollsToTarget(self, throws: int, faces: int, target: int) -> int: 6 | MOD = 10 ** 9 + 7 7 | 8 | @lru_cache(None) 9 | def dp(left: int, num: int) -> int: 10 | if num < 0: 11 | return 0 12 | 13 | if left == 0: 14 | return int(num == 0) 15 | 16 | count = 0 17 | for face in range(1, faces + 1): 18 | count += dp(left - 1, num - face) 19 | 20 | return count % MOD 21 | 22 | return dp(throws, target) 23 | -------------------------------------------------------------------------------- /l33tcode/number-of-good-pairs.py: -------------------------------------------------------------------------------- 1 | from typing import Counter, List 2 | 3 | 4 | class Solution: 5 | def numIdenticalPairs(self, nums: List[int]) -> int: 6 | counter: Counter[int] = Counter() 7 | 8 | result = 0 9 | 10 | for num in nums: 11 | result += counter[num] 12 | counter[num] += 1 13 | 14 | return result 15 | -------------------------------------------------------------------------------- /l33tcode/number-of-good-ways-to-split-a-string.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | def numSplits(self, s: str) -> int: 6 | counter_left, counter_right = Counter(), Counter(s) 7 | 8 | num_splits = 0 9 | 10 | for char in s: 11 | counter_left[char] += 1 12 | 13 | if counter_right[char] > 1: 14 | counter_right[char] -= 1 15 | else: 16 | del counter_right[char] 17 | 18 | if len(counter_left) == len(counter_right): 19 | num_splits += 1 20 | 21 | return num_splits 22 | -------------------------------------------------------------------------------- /l33tcode/number-of-music-playlists.py: -------------------------------------------------------------------------------- 1 | import math 2 | from functools import cache 3 | 4 | 5 | class Solution: 6 | def numMusicPlaylists(self, n: int, goal: int, k: int) -> int: 7 | if k > n: 8 | return 0 9 | 10 | @cache 11 | def dp(songs: int) -> int: 12 | count = 1 13 | 14 | for song in range(goal): 15 | count *= songs - min(song, k) 16 | 17 | for song in range(songs): 18 | count -= math.comb(songs, song) * dp(song) 19 | 20 | return count 21 | 22 | return dp(n) % (10 ** 9 + 7) 23 | -------------------------------------------------------------------------------- /l33tcode/number-of-sets-of-k-non-overlapping-line-segments.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfSets(self, n: int, k: int) -> int: 3 | result = 1 4 | 5 | # C = N! / (K! * (N - K)!) 6 | # N = n + k - 1 7 | # K = 2 * k 8 | # C = (n + k - 1)! / ((2 * k)! * (n + k - 1 - 2 * k)!) 9 | # C = ((n - k) * ... * (n + k - 1)) / (1 * ... * (2 * k)) 10 | 11 | numerator = 1 12 | for num in range(n - k, n + k): 13 | numerator *= num 14 | 15 | denominator = 1 16 | 17 | for num in range(1, 2 * k + 1): 18 | denominator *= num 19 | 20 | return (numerator // denominator) % (10 ** 9 + 7) 21 | -------------------------------------------------------------------------------- /l33tcode/number-of-steps-to-reduce-a-number-to-zero.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfSteps (self, num: int) -> int: 3 | steps = 0 4 | while num > 1: 5 | steps += (num & 1) + 1 6 | num >>= 1 7 | 8 | return steps + num 9 | -------------------------------------------------------------------------------- /l33tcode/number-of-students-doing-homework-at-a-given-time.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def busyStudent( 3 | self, startTime: List[int], endTime: List[int], queryTime: int 4 | ) -> int: 5 | return sum(s <= queryTime <= e for s, e in zip(startTime, endTime)) 6 | -------------------------------------------------------------------------------- /l33tcode/number-of-students-unable-to-eat-lunch.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | from typing import List, Deque, Counter 3 | 4 | 5 | class Solution: 6 | def countStudents(self, students: List[int], sandwiches: List[int]) -> int: 7 | count: Counter[int] = Counter(students) 8 | 9 | for sandwich in sandwiches: 10 | if count[sandwich] == 0: 11 | break 12 | count[sandwich] -= 1 13 | 14 | return sum(count.values()) 15 | -------------------------------------------------------------------------------- /l33tcode/number-of-ways-to-buy-pens-and-pencils.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def waysToBuyPensPencils(self, total: int, cost_pen: int, cost_pencil: int) -> int: 3 | count = 0 4 | 5 | for pens in range(total // cost_pen + 1): 6 | left = total - pens * cost_pen 7 | 8 | count += 1 9 | 10 | if left > 0: 11 | count += left // cost_pencil 12 | 13 | return count 14 | -------------------------------------------------------------------------------- /l33tcode/number-of-ways-to-divide-a-long-corridor.py: -------------------------------------------------------------------------------- 1 | MOD = 10 ** 9 + 7 2 | 3 | 4 | class Solution: 5 | def numberOfWays(self, corridor: str) -> int: 6 | if corridor.count("S") % 2 or corridor.count("S") == 0: 7 | return 0 8 | 9 | ways = 1 10 | seats = 0 11 | plants = 0 12 | 13 | for pos in range(corridor.index("S"), len(corridor)): 14 | char = corridor[pos] 15 | if char == "S": 16 | seats += 1 17 | seats %= 2 18 | 19 | if seats == 1: 20 | ways *= plants + 1 21 | ways %= MOD 22 | 23 | plants = 0 24 | else: 25 | plants += 1 26 | 27 | return ways 28 | -------------------------------------------------------------------------------- /l33tcode/odd-even-linked-list.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func oddEvenList(head *ListNode) *ListNode { 9 | var odd_end *ListNode 10 | var even_begin, even_end *ListNode 11 | node := head 12 | for count := 1; node != nil; count++ { 13 | node_next := node.Next 14 | if count%2 == 1 { 15 | if odd_end != nil { 16 | odd_end.Next = node 17 | } 18 | odd_end = node 19 | if even_begin != nil { 20 | odd_end.Next = even_begin 21 | } 22 | } else { 23 | if even_end == nil { 24 | even_begin = node 25 | } else { 26 | even_end.Next = node 27 | } 28 | even_end = node 29 | node.Next = nil 30 | } 31 | node = node_next 32 | } 33 | 34 | return head 35 | } 36 | -------------------------------------------------------------------------------- /l33tcode/online-stock-span.py: -------------------------------------------------------------------------------- 1 | class StockSpanner: 2 | def __init__(self): 3 | self._stack = [] 4 | 5 | def next(self, price: int) -> int: 6 | weight = 1 7 | 8 | while self._stack and self._stack[-1][0] <= price: 9 | weight += self._stack.pop()[1] 10 | 11 | self._stack.append((price, weight)) 12 | 13 | return weight 14 | 15 | 16 | # Your StockSpanner object will be instantiated and called as such: 17 | # obj = StockSpanner() 18 | # param_1 = obj.next(price) 19 | -------------------------------------------------------------------------------- /l33tcode/painting-the-walls.py: -------------------------------------------------------------------------------- 1 | from functools import cache 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def paintWalls(self, cost: List[int], time: List[int]) -> int: 7 | max_cost = sum(cost) + 1 8 | 9 | @cache 10 | def dp(pos: int, occupied_time: int) -> int: 11 | if pos == len(cost): 12 | return 0 if occupied_time >= 0 else max_cost + 1 13 | 14 | return min( 15 | # Paint using the paid painter 16 | dp(pos + 1, min(occupied_time + time[pos], len(cost) - pos - 1)) 17 | + cost[pos], 18 | # Paint for free 19 | dp(pos + 1, occupied_time - 1), 20 | ) 21 | 22 | return dp(0, 0) 23 | -------------------------------------------------------------------------------- /l33tcode/palindrome-permutation.py: -------------------------------------------------------------------------------- 1 | from typing import Counter 2 | 3 | 4 | class Solution: 5 | def canPermutePalindrome(self, s: str) -> bool: 6 | counter: Counter[str] = Counter() 7 | odd = 0 8 | 9 | for char in s: 10 | counter[char] += 1 11 | if counter[char] % 2 == 1: 12 | odd += 1 13 | else: 14 | odd -= 1 15 | 16 | return odd < 2 17 | -------------------------------------------------------------------------------- /l33tcode/pancake-sorting.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def pancakeSort(self, A: List[int]) -> List[int]: 6 | result = [] 7 | 8 | for n in reversed(range(1, len(A))): 9 | max_pos = A.index(n + 1) 10 | 11 | result.append(max_pos + 1) 12 | result.append(n + 1) 13 | 14 | for i in range((max_pos + 1) // 2): 15 | A[i], A[max_pos - i] = A[max_pos - i], A[i] 16 | 17 | for i in range((n + 1) // 2): 18 | A[i], A[n - i] = A[n - i], A[i] 19 | 20 | return result 21 | -------------------------------------------------------------------------------- /l33tcode/peak-index-in-a-mountain-array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def peakIndexInMountainArray(self, A: List[int]) -> int: 5 | left, right = 1, len(A) - 1 6 | 7 | def uphill(pos: int) -> bool: 8 | # `pos` will never be the last element, because 9 | # the only way to achieve it is to have 10 | # `left == right`, which is guaranteed to be 11 | # impossible by the loop condition `left < right` 12 | return A[pos] < A[pos + 1] 13 | 14 | while left < right: 15 | mid = left + (right - left) // 2 16 | 17 | if uphill(mid): 18 | left = mid + 1 19 | else: 20 | right = mid 21 | 22 | return left 23 | -------------------------------------------------------------------------------- /l33tcode/perform-string-shifts.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def stringShift(self, s: str, shift: List[List[int]]) -> str: 3 | final_shift = sum((-1) ** d * c for d, c in shift) % len(s) 4 | 5 | return "".join([s[(p + final_shift) % len(s)] for p in range(len(s))]) 6 | -------------------------------------------------------------------------------- /l33tcode/permutations-ii.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def permuteUnique(self, nums: List[int]) -> List[List[int]]: 6 | result = [] 7 | 8 | def permutations(bitmask: int, path: List[int]) -> int: 9 | if len(path) == len(nums): 10 | result.append(path.copy()) 11 | 12 | seen = set() 13 | for pos in range(len(nums)): 14 | if nums[pos] not in seen and bitmask & (1 << pos) == 0: 15 | path.append(nums[pos]) 16 | permutations(bitmask | (1 << pos), path) 17 | path.pop() 18 | seen.add(nums[pos]) 19 | 20 | permutations(0, []) 21 | 22 | return result 23 | -------------------------------------------------------------------------------- /l33tcode/permutations.py: -------------------------------------------------------------------------------- 1 | from typing import List, Set 2 | 3 | 4 | class Solution: 5 | def permute(self, nums: List[int]) -> List[List[int]]: 6 | nums_set: Set[int] = set(nums) 7 | stack: List[int] = [] 8 | result: List[List[int]] = [] 9 | 10 | def permutations(): 11 | if not nums_set: 12 | result.append(stack.copy()) 13 | return 14 | 15 | for num in list(nums_set): 16 | nums_set.discard(num) 17 | stack.append(num) 18 | permutations() 19 | nums_set.add(num) 20 | stack.pop() 21 | 22 | permutations() 23 | 24 | return result 25 | -------------------------------------------------------------------------------- /l33tcode/plus-one.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func plusOne(digits []int) []int { 4 | remain := 1 5 | revResult := []int{} 6 | 7 | for pos := range digits { 8 | revPos := len(digits) - pos - 1 9 | newNum := digits[revPos] + remain 10 | 11 | revResult = append(revResult, newNum%10) 12 | remain = newNum / 10 13 | } 14 | 15 | if remain == 1 { 16 | revResult = append(revResult, remain) 17 | } 18 | 19 | result := []int{} 20 | for pos := range revResult { 21 | revPos := len(revResult) - pos - 1 22 | result = append(result, revResult[revPos]) 23 | } 24 | 25 | return result 26 | } 27 | -------------------------------------------------------------------------------- /l33tcode/plus-one.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def plusOne(self, digits: List[int]) -> List[int]: 3 | if not digits: 4 | return [] 5 | 6 | overflow = 1 7 | 8 | for pos in reversed(range(len(digits))): 9 | digits[pos] += overflow 10 | overflow = 0 11 | if digits[pos] > 9: 12 | digits[pos] = 0 13 | overflow = 1 14 | 15 | if overflow == 1: 16 | digits.insert(0, 1) 17 | 18 | return digits 19 | -------------------------------------------------------------------------------- /l33tcode/poor-pigs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def poorPigs(self, buckets: int, minutes_to_die: int, minutes_to_test: int) -> int: 3 | pigs = 0 4 | can_find = 1 5 | 6 | while can_find < buckets: 7 | can_find *= minutes_to_test // minutes_to_die + 1 8 | pigs += 1 9 | 10 | return pigs 11 | -------------------------------------------------------------------------------- /l33tcode/populating-next-right-pointers-in-each-node.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val, left, right, next): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | self.next = next 9 | """ 10 | class Solution: 11 | def connect(self, node): 12 | if node is None or not node.left and not node.right: 13 | return node 14 | if node.next: 15 | node.right.next = node.next.left 16 | node.left.next = node.right 17 | self.connect(node.left) 18 | self.connect(node.right) 19 | 20 | return node 21 | 22 | # TODO: come with non-recursive approach 23 | -------------------------------------------------------------------------------- /l33tcode/power-of-four.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func isPowerOfFour(num int) bool { 4 | return num > 0 && ((num^(num-1))&num) == num && (num & 0xAAAAAAAA) == 0 5 | } 6 | -------------------------------------------------------------------------------- /l33tcode/power-of-two.go: -------------------------------------------------------------------------------- 1 | func isPowerOfTwo(n int) bool { 2 | for num := float64(n); num > 0; num /= 2 { 3 | if num == 1 { 4 | return true 5 | } 6 | } 7 | return false 8 | } 9 | -------------------------------------------------------------------------------- /l33tcode/powx-n.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func myPow(x float64, n int) float64 { 4 | cache := map[int]float64{0: 1, 1: x, -1: 1/x} 5 | 6 | var dfs func(val float64, pow int) float64 7 | dfs = func(val float64, pow int) float64 { 8 | if _, ok := cache[pow]; !ok { 9 | cache[pow] = dfs(val, pow/2) * dfs(val, pow/2) * dfs(val, pow%2) 10 | } 11 | 12 | return cache[pow] 13 | } 14 | 15 | return dfs(x, n) 16 | } 17 | -------------------------------------------------------------------------------- /l33tcode/previous-permutation-with-one-swap.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def prevPermOpt1(self, A: List[int]) -> List[int]: 3 | for pos in reversed(range(len(A) - 1)): 4 | if A[pos] > A[pos + 1]: 5 | replace_pos = pos + 1 6 | while replace_pos + 1 < len(A) and A[replace_pos + 1] < A[pos]: 7 | replace_pos += 1 8 | A[pos], A[replace_pos] = A[replace_pos], A[pos] 9 | return A[:pos + 1] + sorted(A[pos + 1:]) 10 | 11 | return A 12 | -------------------------------------------------------------------------------- /l33tcode/print-immutable-linked-list-in-reverse.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type ImmutableListNode struct { 4 | } 5 | 6 | func (this *ImmutableListNode) getNext() ImmutableListNode { 7 | return *this 8 | } 9 | 10 | func (this *ImmutableListNode) printValue() { 11 | return 12 | } 13 | 14 | func printLinkedListInReverse(head ImmutableListNode) { 15 | stack := []ImmutableListNode{} 16 | 17 | for node := head; node != nil; node = node.getNext() { 18 | stack = append(stack, node) 19 | } 20 | 21 | for len(stack) > 0 { 22 | stack[len(stack) - 1].printValue() 23 | stack = stack[:len(stack) - 1] 24 | } 25 | 26 | return 27 | } 28 | -------------------------------------------------------------------------------- /l33tcode/product-of-the-last-k-numbers.py: -------------------------------------------------------------------------------- 1 | class ProductOfNumbers: 2 | _prefix_product: list[int] 3 | 4 | def __init__(self) -> None: 5 | self._prefix_product = [1] 6 | 7 | def add(self, num: int) -> None: 8 | if num: 9 | self._prefix_product.append(self._prefix_product[-1] * num) 10 | else: 11 | self._prefix_product = [1] 12 | 13 | def getProduct(self, k: int) -> int: 14 | if len(self._prefix_product) <= k: 15 | return 0 16 | 17 | return self._prefix_product[-1] // self._prefix_product[-k - 1] 18 | -------------------------------------------------------------------------------- /l33tcode/rabbits-in-forest.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numRabbits(answers []int) int { 4 | counts := map[int]int{} 5 | 6 | for _, answer := range answers { 7 | if _, ok := counts[answer+1]; !ok { 8 | counts[answer+1] = 0 9 | } 10 | counts[answer+1] += 1 11 | } 12 | 13 | result := 0 14 | 15 | for rabbits, count := range counts { 16 | tmp := count / rabbits 17 | if count % rabbits > 0 { 18 | tmp += 1 19 | } 20 | result += tmp * rabbits 21 | } 22 | 23 | return result 24 | } 25 | -------------------------------------------------------------------------------- /l33tcode/random-pick-with-weight.py: -------------------------------------------------------------------------------- 1 | import random 2 | import bisect 3 | 4 | 5 | class Solution: 6 | def __init__(self, w: List[int]): 7 | self._partial = [] 8 | partial_sum = 0 9 | for num in w: 10 | partial_sum += num 11 | self._partial.append(partial_sum) 12 | 13 | @property 14 | def _total(self): 15 | return self._partial[-1] 16 | 17 | def pickIndex(self) -> int: 18 | return bisect.bisect_left(self._partial, random.randint(1, self._total)) 19 | 20 | 21 | # Your Solution object will be instantiated and called as such: 22 | # obj = Solution(w) 23 | # param_1 = obj.pickIndex() 24 | -------------------------------------------------------------------------------- /l33tcode/range-sum-of-sorted-subarray-sums.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int: 3 | sums = [] 4 | 5 | count = 0 6 | 7 | for pos_left in range(len(nums)): 8 | partial_sum = 0 9 | for pos_right in range(pos_left, len(nums)): 10 | partial_sum += nums[pos_right] 11 | sums.append(partial_sum) 12 | count += 1 13 | 14 | sums.sort() 15 | 16 | return sum(sums[left - 1:right]) % (10 ** 9 + 7) 17 | -------------------------------------------------------------------------------- /l33tcode/range-sum-query-immutable.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class NumArray: 5 | def __init__(self, nums: List[int]): 6 | self._partial_sum = [0] 7 | 8 | for num in nums: 9 | self._partial_sum.append(self._partial_sum[-1] + num) 10 | 11 | def sumRange(self, left: int, right: int) -> int: 12 | return self._partial_sum[right + 1] - self._partial_sum[left] 13 | 14 | 15 | # Your NumArray object will be instantiated and called as such: 16 | # obj = NumArray(nums) 17 | # param_1 = obj.sumRange(i,j) 18 | -------------------------------------------------------------------------------- /l33tcode/ransom-note.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func canConstruct(ransomNote string, magazine string) bool { 4 | counter := map[rune]int{} 5 | 6 | for _, letter := range magazine { 7 | counter[letter] += 1 8 | } 9 | 10 | for _, letter := range ransomNote { 11 | if counter[letter] > 0 { 12 | counter[letter] -= 1 13 | } else { 14 | return false 15 | } 16 | } 17 | 18 | return true 19 | } 20 | -------------------------------------------------------------------------------- /l33tcode/read-n-characters-given-read4-ii-call-multiple-times.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | int_buf = [None] * 4 3 | int_ptr = 0 4 | int_bytes = 0 5 | 6 | def read4(self): 7 | if self.int_bytes == self.int_ptr: 8 | self.int_bytes = read4(self.int_buf) 9 | self.int_ptr = 0 10 | 11 | def read(self, buf, n): 12 | buf_pos = 0 13 | self.read4() 14 | 15 | while n - buf_pos > 0 and self.int_bytes > self.int_ptr: 16 | can_read = min(self.int_bytes - self.int_ptr, n - buf_pos) 17 | buf[buf_pos:buf_pos + can_read] = self.int_buf[self.int_ptr:self.int_ptr + can_read] 18 | 19 | buf_pos += can_read 20 | self.int_ptr += can_read 21 | 22 | self.read4() 23 | 24 | return buf_pos 25 | -------------------------------------------------------------------------------- /l33tcode/read-n-characters-given-read4.py: -------------------------------------------------------------------------------- 1 | read-n-characters-given-read4-ii-call-multiple-times.py -------------------------------------------------------------------------------- /l33tcode/recyclable-and-low-fat-products.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | product_id 3 | FROM 4 | Products 5 | WHERE 6 | low_fats = 'Y' 7 | AND recyclable = 'Y' 8 | -------------------------------------------------------------------------------- /l33tcode/reduction-operations-to-make-the-array-elements-equal.py: -------------------------------------------------------------------------------- 1 | from typing import List, Set 2 | 3 | 4 | class Solution: 5 | def reductionOperations(self, nums: List[int]) -> int: 6 | nums.sort() 7 | 8 | seen: Set[int] = set() 9 | 10 | ops = 0 11 | 12 | for num in nums: 13 | seen.add(num) 14 | 15 | ops += len(seen) - 1 16 | 17 | return ops 18 | -------------------------------------------------------------------------------- /l33tcode/remove-all-adjacent-duplicates-in-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, S: str) -> str: 3 | stack = [] 4 | 5 | for char in S: 6 | if stack and stack[-1] == char: 7 | stack.pop() 8 | else: 9 | stack.append(char) 10 | 11 | return "".join(stack) 12 | -------------------------------------------------------------------------------- /l33tcode/remove-colored-pieces-if-both-neighbors-are-the-same-color.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def winnerOfGame(self, colors: str) -> bool: 3 | count_a = count_b = 0 4 | 5 | for pos in range(1, len(colors) - 1): 6 | if colors[pos - 1] == colors[pos] == colors[pos + 1]: 7 | if colors[pos] == "A": 8 | count_a += 1 9 | else: 10 | count_b += 1 11 | 12 | return count_a > count_b 13 | -------------------------------------------------------------------------------- /l33tcode/remove-duplicates-from-sorted-array-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums: List[int]) -> int: 3 | length = 0 4 | count = 0 5 | 6 | for pos in range(len(nums)): 7 | if count < 2 and (pos < 1 or nums[pos] == nums[pos - 1]): 8 | nums[length] = nums[pos] 9 | length += 1 10 | count += 1 11 | elif nums[pos] != nums[pos - 1]: 12 | nums[length] = nums[pos] 13 | length += 1 14 | count = 1 15 | 16 | return length 17 | -------------------------------------------------------------------------------- /l33tcode/remove-duplicates-from-sorted-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def deleteDuplicates(self, head): 9 | if not head: 10 | return 11 | 12 | node = head 13 | prev_node = None 14 | 15 | while node: 16 | if prev_node and prev_node.val == node.val: 17 | prev_node.next = node.next 18 | else: 19 | prev_node = node 20 | 21 | node = node.next 22 | 23 | return head 24 | -------------------------------------------------------------------------------- /l33tcode/remove-k-digits.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strings" 5 | ) 6 | 7 | func removeKdigits(num string, k int) string { 8 | stack := []rune{} 9 | removed := 0 10 | for _, digit := range num { 11 | for removed < k && len(stack) > 0 && digit < stack[len(stack) - 1] { 12 | stack = stack[:len(stack) - 1] 13 | removed += 1 14 | } 15 | stack = append(stack, digit) 16 | } 17 | result := strings.TrimLeft(string(stack[:len(num)-k]), "0") 18 | if result == "" { 19 | return "0" 20 | } 21 | return result 22 | } 23 | -------------------------------------------------------------------------------- /l33tcode/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: ListNode, val: int) -> ListNode: 8 | cur, prev = head, None 9 | new_head = None 10 | 11 | while cur: 12 | if cur.val == val: 13 | if prev: 14 | prev.next = cur.next 15 | else: 16 | if not new_head: 17 | new_head = cur 18 | prev = cur 19 | cur = cur.next 20 | 21 | return new_head 22 | -------------------------------------------------------------------------------- /l33tcode/remove-nth-node-from-end-of-list.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 | 8 | class Solution: 9 | def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 10 | if not head: 11 | return 12 | 13 | pre_head = ListNode(None) 14 | pre_head.next = head 15 | 16 | left, right = pre_head, head 17 | 18 | pos = 1 19 | 20 | while right.next: 21 | if pos >= n: 22 | left = left.next 23 | 24 | right = right.next 25 | pos += 1 26 | 27 | left.next = left.next.next 28 | 29 | return pre_head.next 30 | -------------------------------------------------------------------------------- /l33tcode/reordered-power-of-2.py: -------------------------------------------------------------------------------- 1 | from typing import Set, Tuple 2 | 3 | 4 | class Solution: 5 | def reorderedPowerOf2(self, N: int) -> bool: 6 | def get_combinations() -> Set[Tuple[str]]: 7 | result: Set[Tuple[str]] = set() 8 | 9 | n = 1 10 | for _ in range(32): 11 | result.add(tuple(sorted(str(int(n))))) 12 | n <<= 1 13 | 14 | return result 15 | 16 | combinations = get_combinations() 17 | 18 | sorted_number = tuple(sorted(str(N))) 19 | 20 | return sorted_number in combinations 21 | -------------------------------------------------------------------------------- /l33tcode/repeated-substring-pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def repeatedSubstringPattern(self, s: str) -> bool: 3 | for substring_length in range(1, len(s) // 2 + 1): 4 | if len(s) % substring_length != 0: 5 | continue 6 | 7 | first_part = s[0:substring_length] 8 | 9 | for part in range(len(s) // substring_length): 10 | start = substring_length * part 11 | end = substring_length * (part + 1) 12 | if first_part != s[start:end]: 13 | break 14 | else: 15 | return True 16 | 17 | return False 18 | -------------------------------------------------------------------------------- /l33tcode/requirements.txt: -------------------------------------------------------------------------------- 1 | black 2 | mypy 3 | pylint 4 | -------------------------------------------------------------------------------- /l33tcode/reverse-bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseBits(self, n: int) -> int: 3 | result = 0 4 | for _ in range(32): 5 | result ^= (n & 1) 6 | result <<= 1 7 | n >>= 1 8 | 9 | return result >> 1 10 | -------------------------------------------------------------------------------- /l33tcode/reverse-integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x: int) -> int: 3 | if x == abs(x): 4 | sign = 1 5 | else: 6 | sign = -1 7 | 8 | integer_part = abs(x) 9 | 10 | result = 0 11 | 12 | while integer_part != 0: 13 | tmp_var = integer_part 14 | integer_part = tmp_var // 10 15 | remains = tmp_var % 10 16 | result = result * 10 + remains 17 | 18 | if abs(result) > 0x7FFFFFFF: 19 | return 0 20 | else: 21 | return result * sign 22 | -------------------------------------------------------------------------------- /l33tcode/richest-customer-wealth.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maximumWealth(self, accounts: List[List[int]]) -> int: 6 | return max(map(sum, accounts)) 7 | -------------------------------------------------------------------------------- /l33tcode/rotate-image.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, matrix: List[List[int]]) -> None: 3 | """ 4 | Do not return anything, modify matrix in-place instead. 5 | """ 6 | for row in range(len(matrix)): 7 | for col in range(row, len(matrix[0])): 8 | matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col] 9 | 10 | for row in range(len(matrix)): 11 | for col in range(len(matrix[0]) // 2): 12 | matrix[row][col], matrix[row][- col - 1] = matrix[row][- col - 1], matrix[row][col] 13 | -------------------------------------------------------------------------------- /l33tcode/rotate-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 rotateRight(self, head: ListNode, k: int) -> ListNode: 8 | if not head: 9 | return head 10 | 11 | nodes = 1 12 | node = head 13 | while node.next: 14 | nodes += 1 15 | node = node.next 16 | 17 | node.next = head 18 | skip = (nodes - k) % nodes 19 | 20 | for _ in range(skip): 21 | node = node.next 22 | 23 | node_next = node.next 24 | 25 | node.next = None 26 | 27 | return node_next 28 | -------------------------------------------------------------------------------- /l33tcode/running-sum-of-1d-array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def runningSum(self, nums: List[int]) -> List[int]: 6 | result: List[int] = [] 7 | total = 0 8 | 9 | for num in nums: 10 | total += num 11 | result.append(total) 12 | 13 | return result 14 | -------------------------------------------------------------------------------- /l33tcode/same-tree.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func isSameTree(p *TreeNode, q *TreeNode) bool { 10 | var dfs func(nodeLeft *TreeNode, nodeRight *TreeNode) bool 11 | dfs = func(nodeLeft *TreeNode, nodeRight *TreeNode) bool { 12 | if nodeLeft == nil && nodeRight == nil { 13 | return true 14 | } 15 | 16 | if nodeLeft == nil || nodeRight == nil { 17 | return false 18 | } 19 | 20 | if nodeLeft.Val != nodeRight.Val { 21 | return false 22 | } 23 | 24 | return dfs(nodeLeft.Left, nodeRight.Left) && dfs(nodeLeft.Right, nodeRight.Right) 25 | } 26 | 27 | return dfs(p, q) 28 | } 29 | -------------------------------------------------------------------------------- /l33tcode/score-after-flipping-matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def matrixScore(self, A: List[List[int]]) -> int: 3 | for row in range(len(A)): 4 | if A[row][0] == 0: 5 | for col in range(len(A[row])): 6 | A[row][col] = 1 if A[row][col] == 0 else 0 7 | 8 | num = 0 9 | for col in range(len(A[0])): 10 | ones = sum(A[row][col] for row in range(len(A))) 11 | num = max(ones, len(A) - ones) + num * 2 12 | 13 | return num 14 | -------------------------------------------------------------------------------- /l33tcode/score-of-parentheses.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def scoreOfParentheses(self, S: str) -> int: 6 | stack: List[int] = [0] 7 | 8 | for char in S: 9 | if char == "(": 10 | stack.append(0) 11 | else: 12 | top = stack.pop() 13 | 14 | stack[-1] += max(top * 2, 1) 15 | 16 | return stack[-1] 17 | -------------------------------------------------------------------------------- /l33tcode/search-a-2d-matrix-ii.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | 3 | class Solution: 4 | def searchMatrix(self, matrix, target): 5 | """ 6 | :type matrix: List[List[int]] 7 | :type target: int 8 | :rtype: bool 9 | """ 10 | 11 | if not matrix: 12 | return False 13 | 14 | right = len(matrix[0]) 15 | 16 | for row in range(len(matrix)): 17 | right = bisect.bisect_left(matrix[row], target, 0, right) 18 | 19 | if right < len(matrix[0]) and matrix[row][right] == target: 20 | return True 21 | 22 | return False 23 | -------------------------------------------------------------------------------- /l33tcode/search-a-2d-matrix.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: 6 | if not matrix: 7 | return False 8 | 9 | def get_value(pos: int): 10 | row, col = pos // len(matrix[0]), pos % len(matrix[0]) 11 | return matrix[row][col] 12 | 13 | left, right = 0, len(matrix) * len(matrix[0]) - 1 14 | 15 | while left < right: 16 | mid = left + (right - left) // 2 17 | 18 | if get_value(mid) < target: 19 | left = mid + 1 20 | elif get_value(mid) >= target: 21 | right = mid 22 | 23 | return get_value(left) == target 24 | -------------------------------------------------------------------------------- /l33tcode/search-in-a-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchBST(self, root, val): 3 | """ 4 | :type root: TreeNode 5 | :type val: int 6 | :rtype: TreeNode 7 | """ 8 | prev = None 9 | current = root 10 | 11 | while current is not None: 12 | if current.val < val: 13 | prev = current 14 | current = current.right 15 | elif current.val > val: 16 | prev = current 17 | current = current.left 18 | else: 19 | return current 20 | 21 | return current 22 | 23 | # No tests here because tested by CLRS binary tree structure 24 | -------------------------------------------------------------------------------- /l33tcode/search-in-rotated-sorted-array.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func search(nums []int, target int) int { 4 | left, right := 0, len(nums) 5 | 6 | for left < right { 7 | mid := left + (right-left)/2 8 | 9 | if nums[mid] >= nums[0] { 10 | left = mid + 1 11 | } else { 12 | right = mid 13 | } 14 | } 15 | 16 | rotatedStart := left % len(nums) 17 | 18 | left, right = 0, len(nums)-1 19 | 20 | for left < right { 21 | mid := left + (right-left)/2 22 | 23 | if nums[(mid+rotatedStart)%len(nums)] < target { 24 | left = mid + 1 25 | } else { 26 | right = mid 27 | } 28 | } 29 | 30 | if pos := (left + rotatedStart) % len(nums); nums[pos] == target { 31 | return pos 32 | } 33 | 34 | return -1 35 | } 36 | -------------------------------------------------------------------------------- /l33tcode/search-insert-position.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func searchInsert(nums []int, target int) int { 4 | left, right := -1, len(nums) 5 | 6 | for middle := (left + right) / 2; left+1 < right; middle = (left + right) / 2 { 7 | if nums[middle] >= target { 8 | right = middle 9 | } else { 10 | left = middle 11 | } 12 | } 13 | 14 | return right 15 | } 16 | -------------------------------------------------------------------------------- /l33tcode/seat-reservation-manager.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | from typing import List 3 | 4 | 5 | class SeatManager: 6 | def __init__(self, n: int): 7 | self._unreserved: List[int] = list(range(1, n + 1)) 8 | heapq.heapify(self._unreserved) 9 | 10 | def reserve(self) -> int: 11 | return heapq.heappop(self._unreserved) 12 | 13 | def unreserve(self, seatNumber: int) -> None: 14 | heapq.heappush(self._unreserved, seatNumber) 15 | -------------------------------------------------------------------------------- /l33tcode/sentence-screen-fitting.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int: 3 | sentence_str = " ".join(sentence) + " " 4 | sentence_str_len = len(sentence_str) 5 | ptr = 0 6 | 7 | for row in range(rows): 8 | ptr += cols - 1 9 | if sentence_str[ptr % sentence_str_len] == " ": 10 | ptr += 1 11 | elif sentence_str[(ptr + 1) % sentence_str_len] == " ": 12 | ptr += 2 13 | else: 14 | while ptr > 0 and sentence_str[(ptr - 1) % sentence_str_len] != " ": 15 | ptr -= 1 16 | 17 | return ptr // sentence_str_len 18 | -------------------------------------------------------------------------------- /l33tcode/shortest-distance-to-a-character.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from itertools import chain 3 | 4 | 5 | class Solution: 6 | def shortestToChar(self, S: str, C: str) -> List[int]: 7 | dp, prev = [float("+inf")] * len(S), float("-inf") 8 | 9 | for pos in chain(range(len(S)), reversed(range(len(S)))): 10 | prev = pos if S[pos] == C else prev 11 | 12 | dp[pos] = min(abs(pos - prev), dp[pos]) 13 | 14 | return dp 15 | 16 | 17 | class TestSolution: 18 | def setup(self): 19 | self.sol = Solution() 20 | 21 | def test_empty(self): 22 | assert self.sol.shortestToChar("x", "x") == [0] 23 | 24 | def test_case1(self): 25 | assert self.sol.shortestToChar("loveleetcode", "e") == [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] 26 | -------------------------------------------------------------------------------- /l33tcode/shortest-unsorted-continuous-subarray.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findUnsortedSubarray(self, nums: List[int]) -> int: 6 | stack: List[int] = [] 7 | first, last = len(nums), -1 8 | 9 | for pos in range(len(nums)): 10 | while stack and nums[stack[-1]] > nums[pos]: 11 | first = min(first, stack.pop()) 12 | 13 | stack.append(pos) 14 | 15 | stack = [] 16 | 17 | for pos in reversed(range(len(nums))): 18 | while stack and nums[stack[-1]] < nums[pos]: 19 | last = max(last, stack.pop()) 20 | 21 | stack.append(pos) 22 | 23 | if first > last: 24 | return 0 25 | 26 | return last - first + 1 27 | -------------------------------------------------------------------------------- /l33tcode/shortest-word-distance.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def shortestDistance(self, words: List[str], word1: str, word2: str) -> int: 6 | word1_pos, word2_pos = 0, 0 7 | word1_seen, word2_seen = False, False 8 | 9 | shortest_distance = len(words) + 1 10 | 11 | for pos in range(len(words)): 12 | if words[pos] == word1: 13 | word1_pos = pos 14 | word1_seen = True 15 | elif words[pos] == word2: 16 | word2_pos = pos 17 | word2_seen = True 18 | 19 | if word1_seen and word2_seen: 20 | shortest_distance = min(shortest_distance, abs(word1_pos - word2_pos)) 21 | 22 | return shortest_distance 23 | -------------------------------------------------------------------------------- /l33tcode/simplify-path.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def simplifyPath(self, path: str) -> str: 3 | stack = [] 4 | 5 | for f in path.split("/"): 6 | if f in [".", ""]: 7 | pass 8 | elif f == "..": 9 | if stack: 10 | stack.pop() 11 | else: 12 | stack.append(f) 13 | 14 | return "/" + "/".join(stack) 15 | -------------------------------------------------------------------------------- /l33tcode/single-element-in-a-sorted-array.py: -------------------------------------------------------------------------------- 1 | func singleNonDuplicate(nums []int) int { 2 | for pos, _ := range make([]int, len(nums) / 2) { 3 | if nums[pos * 2] != nums[pos * 2 + 1] { 4 | return nums[pos * 2] 5 | } 6 | } 7 | return nums[len(nums) - 1] 8 | } 9 | -------------------------------------------------------------------------------- /l33tcode/single-number-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: List[int]) -> int: 3 | counter1 = 0 4 | counter2 = 0 5 | 6 | for num in nums: 7 | counter2 ^= (counter1 & num) 8 | counter1 ^= counter1 ^ num 9 | 10 | mask = ~ (counter1 & counter2) 11 | 12 | counter1 &= mask 13 | counter2 &= mask 14 | 15 | return counter1 16 | -------------------------------------------------------------------------------- /l33tcode/single-number-iii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: List[int]) -> List[int]: 3 | xor = 0 # a ^ b 4 | for num in nums: 5 | xor ^= num 6 | 7 | diff = xor & (-xor) 8 | 9 | num1, num2 = 0, 0 10 | for num in nums: 11 | if num & diff > 0: 12 | num1 ^= num 13 | else: 14 | num2 ^= num 15 | 16 | return [num1, num2] 17 | -------------------------------------------------------------------------------- /l33tcode/single-number.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def singleNumber(self, nums: List[int]) -> int: 7 | return next(k for k, v in Counter(nums).items() if v == 1) 8 | 9 | 10 | class TestSolution: 11 | def setup(self): 12 | self.sol = Solution() 13 | 14 | def test_case1(self): 15 | assert self.sol.singleNumber([2, 2, 1]) == 1 16 | 17 | def test_case2(self): 18 | assert self.sol.singleNumber([4, 1, 2, 1, 2]) == 4 19 | -------------------------------------------------------------------------------- /l33tcode/single-row-keyboard.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func calculateTime(keyboard string, word string) int { 6 | cursor := 0 7 | 8 | keyToPos := map[rune]int{} 9 | 10 | for pos, char := range keyboard { 11 | keyToPos[char] = pos 12 | } 13 | 14 | distance := 0 15 | 16 | for _, char := range word { 17 | distance += int(math.Abs(float64(keyToPos[char]) - float64(cursor))) 18 | 19 | cursor = keyToPos[char] 20 | } 21 | 22 | return distance 23 | } 24 | -------------------------------------------------------------------------------- /l33tcode/single-row-keyboard.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | 4 | class Solution: 5 | def calculateTime(self, keyboard: str, word: str) -> int: 6 | def get_positions(keyboard: str) -> Dict[str, int]: 7 | positions = {} 8 | 9 | for pos, char in enumerate(keyboard): 10 | positions[char] = pos 11 | 12 | return positions 13 | 14 | 15 | moves = 0 16 | positions = get_positions(keyboard) 17 | prev_pos = 0 18 | 19 | for char in word: 20 | cur_pos = positions[char] 21 | 22 | moves += abs(cur_pos - prev_pos) 23 | 24 | prev_pos = cur_pos 25 | 26 | return moves 27 | -------------------------------------------------------------------------------- /l33tcode/slowest-key.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def slowestKey(self, release_times: List[int], keys_pressed: str) -> str: 6 | prev_time = 0 7 | 8 | max_time_key = (0, "") 9 | 10 | for pos in range(len(release_times)): 11 | duration = release_times[pos] - prev_time 12 | key = keys_pressed[pos] 13 | 14 | prev_time = release_times[pos] 15 | 16 | max_time_key = max(max_time_key, (duration, key)) 17 | 18 | return max_time_key[1] 19 | -------------------------------------------------------------------------------- /l33tcode/smallest-integer-divisible-by-k.py: -------------------------------------------------------------------------------- 1 | from typing import Set, Tuple 2 | 3 | 4 | class Solution: 5 | def smallestRepunitDivByK(self, K: int) -> int: 6 | # O(K^2) solution. We can do better with O(K) 7 | mod = 1 % K 8 | mod_total = mod 9 | count = 1 10 | 11 | seen: Set[Tuple[int, int]] = set() 12 | 13 | while mod_total != 0: 14 | mod = (mod * 10) % K 15 | mod_total = (mod_total + mod) % K 16 | 17 | if (mod, mod_total) in seen: 18 | return -1 19 | seen.add((mod, mod_total)) 20 | 21 | count += 1 22 | 23 | return count 24 | -------------------------------------------------------------------------------- /l33tcode/sort-array-by-increasing-frequency.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from collections import Counter 3 | 4 | 5 | class Solution: 6 | def frequencySort(self, nums: List[int]) -> List[int]: 7 | counter = Counter(nums) 8 | 9 | return list(sorted(nums, key=lambda num: (counter[num], -num))) 10 | -------------------------------------------------------------------------------- /l33tcode/sort-array-by-parity.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def sortArrayByParity(self, A: List[int]) -> List[int]: 6 | sorted_pos = 0 7 | 8 | for cur_pos in range(len(A)): 9 | if A[cur_pos] & 1 == 0: 10 | A[sorted_pos], A[cur_pos] = A[cur_pos], A[sorted_pos] 11 | sorted_pos += 1 12 | 13 | return A 14 | -------------------------------------------------------------------------------- /l33tcode/sort-characters-by-frequency.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | def frequencySort(self, s: str) -> str: 6 | return "".join( 7 | reversed(sorted([k * v for k, v in Counter(s).items()], key=len)) 8 | ) 9 | -------------------------------------------------------------------------------- /l33tcode/sort-colors.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortColors(self, nums: List[int]) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | left, right = 0, len(nums) - 1 7 | 8 | for pos in range(len(nums)): 9 | if pos > right: 10 | break 11 | 12 | while (nums[pos] == 0 and left < pos) or \ 13 | (nums[pos] == 2 and right > pos): 14 | if nums[pos] == 0 and left < pos: 15 | nums[pos], nums[left] = nums[left], nums[pos] 16 | left += 1 17 | 18 | if nums[pos] == 2 and right > pos: 19 | nums[pos], nums[right] = nums[right], nums[pos] 20 | right -= 1 21 | -------------------------------------------------------------------------------- /l33tcode/sort-integers-by-the-number-of-1-bits.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def sortByBits(self, arr: List[int]) -> List[int]: 6 | def count_one_bits(num: int) -> int: 7 | count = 0 8 | while num: 9 | count += num & 1 10 | num >>= 1 11 | return count 12 | 13 | return sorted(arr, key=lambda x: (count_one_bits(x), x)) 14 | -------------------------------------------------------------------------------- /l33tcode/spiral-matrix-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateMatrix(self, n): 3 | matrix = [[-1 for _ in range(n)] for _ in range(n)] 4 | val = 0 5 | 6 | row, col = 0, 0 7 | vec = (0, 1) 8 | 9 | while row != n and matrix[row][col] == -1: 10 | val += 1 11 | matrix[row][col] = val 12 | 13 | row, col = tuple(map(lambda x, y: x + y, (row, col), vec)) 14 | 15 | if row == n or col == n or matrix[row][col] > 0: 16 | row, col = tuple(map(lambda x, y: x - y, (row, col), vec)) 17 | vec = (vec[1], - vec[0]) 18 | row, col = tuple(map(lambda x, y: x + y, (row, col), vec)) 19 | 20 | return matrix 21 | -------------------------------------------------------------------------------- /l33tcode/sqrtx.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mySqrt(self, x: int) -> int: 3 | left, right = 0, x 4 | 5 | while left <= right: 6 | mid = (left + right) // 2 7 | squared = mid * mid 8 | 9 | if squared - x == 0: 10 | return mid 11 | elif squared - x < 0: 12 | left = mid + 1 13 | else: 14 | right = mid - 1 15 | 16 | return min(left, right) 17 | -------------------------------------------------------------------------------- /l33tcode/stone-game-iv.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | 4 | class Solution: 5 | def winnerSquareGame(self, n: int) -> bool: 6 | squares = [] 7 | 8 | for count in range(1, n + 1): 9 | square = count ** 2 10 | if square > n: 11 | break 12 | squares.append(square) 13 | 14 | @lru_cache(None) 15 | def dp(stones: int) -> bool: 16 | for square in squares: 17 | if square > stones: 18 | break 19 | if not dp(stones - square): 20 | return True 21 | 22 | return False 23 | 24 | return dp(n) 25 | -------------------------------------------------------------------------------- /l33tcode/student-attendance-record-i.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkRecord(self, s: str) -> bool: 3 | def check_absent(count): 4 | return count <= 1 5 | 6 | def check_late(count): 7 | return count <= 2 8 | 9 | absent_count, late_count = 0, 0 10 | 11 | for char in s: 12 | if char == "A": # absent 13 | absent_count += 1 14 | 15 | if char == "L": # late 16 | late_count += 1 17 | else: 18 | late_count = 0 19 | 20 | if not check_absent(absent_count): 21 | return False 22 | 23 | if not check_late(late_count): 24 | return False 25 | 26 | return True 27 | -------------------------------------------------------------------------------- /l33tcode/subarray-sums-divisible-by-k.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def subarraysDivByK(self, A: List[int], K: int) -> int: 5 | sums = [0] 6 | 7 | for num in A: 8 | sums.append((sums[-1] + num) % K) 9 | 10 | counter = Counter(sums) 11 | 12 | return int(sum(n * (n - 1) / 2 for n in counter.values())) 13 | -------------------------------------------------------------------------------- /l33tcode/subdomain-visit-count.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def subdomainVisits(self, cpdomains: List[str]) -> List[str]: 5 | counter = Counter() 6 | 7 | for cpdomain in cpdomains: 8 | count, domain = cpdomain.split(" ") 9 | cur_domain = None 10 | 11 | for subdomain in reversed(domain.split(".")): 12 | if cur_domain is None: 13 | cur_domain = subdomain 14 | else: 15 | cur_domain = subdomain + "." + cur_domain 16 | 17 | counter[cur_domain] += int(count) 18 | 19 | return [str(v) + " " + k for k, v in counter.items()] 20 | -------------------------------------------------------------------------------- /l33tcode/subsets.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func subsets(nums []int) [][]int { 4 | results := [][]int{} 5 | 6 | results = append(results, []int{}) 7 | 8 | for _, num := range nums { 9 | for pos := range make([]bool, len(results)) { 10 | new_result := make([]int, len(results[pos])) 11 | copy(new_result, results[pos]) 12 | new_result = append(new_result, num) 13 | results = append(results, new_result) 14 | } 15 | } 16 | 17 | return results 18 | } 19 | -------------------------------------------------------------------------------- /l33tcode/sum-of-absolute-differences-in-a-sorted-array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]: 6 | nums.sort() # so the absolute diff is calculated correctly 7 | 8 | result: List[int] = [0] * len(nums) 9 | 10 | # left->right 11 | diff = 0 12 | for pos in range(len(nums)): 13 | diff += (nums[pos] - nums[pos - 1]) * pos 14 | result[pos] += diff 15 | 16 | # right->left 17 | diff = 0 18 | for pos in range(len(nums)): 19 | diff += (nums[-pos] - nums[-pos - 1]) * pos 20 | result[-pos - 1] += diff 21 | 22 | return result 23 | -------------------------------------------------------------------------------- /l33tcode/sum-of-nodes-with-even-valued-grandparent.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func sumEvenGrandparent(root *TreeNode) int { 10 | var dfs func(node *TreeNode, parent int, grandparent int) int 11 | dfs = func(node *TreeNode, parent int, grandparent int) int { 12 | if node == nil { 13 | return 0 14 | } 15 | result := 0 16 | if grandparent%2 == 0 { 17 | result = node.Val 18 | } 19 | result += dfs(node.Left, node.Val, parent) 20 | result += dfs(node.Right, node.Val, parent) 21 | 22 | return result 23 | } 24 | return dfs(root, 1, 1) 25 | } 26 | -------------------------------------------------------------------------------- /l33tcode/summary-ranges.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def summaryRanges(self, nums: List[int]) -> List[str]: 3 | left, right = 0, 0 4 | 5 | result = [] 6 | 7 | for pos in range(1, len(nums) + 1): 8 | if pos < len(nums) and nums[pos] - nums[pos - 1] < 2: 9 | right += 1 10 | else: 11 | if left == right: 12 | result.append(str(nums[left])) 13 | else: 14 | result.append(str(nums[left]) + "->" + str(nums[right])) 15 | left = right = right + 1 16 | 17 | return result 18 | -------------------------------------------------------------------------------- /l33tcode/target-sum.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findTargetSumWays(nums []int, S int) int { 4 | if len(nums) == 0 { 5 | return 0 6 | } 7 | 8 | total := 0 9 | for _, num := range nums { 10 | total += num 11 | } 12 | 13 | if (total+S)%2 != 0 { 14 | return 0 15 | } 16 | 17 | sumTarget := (total + S) / 2 18 | dp := map[int]int{0: 1} 19 | 20 | for pos := 0; pos < len(nums); pos++ { 21 | dp_new := map[int]int{} 22 | for capacity, count := range dp { 23 | dp_new[capacity] += count 24 | if capacity+nums[pos] <= sumTarget { 25 | dp_new[capacity+nums[pos]] += count 26 | } 27 | } 28 | dp = dp_new 29 | } 30 | 31 | if _, ok := dp[sumTarget]; !ok { 32 | return 0 33 | } 34 | 35 | return dp[sumTarget] 36 | } 37 | -------------------------------------------------------------------------------- /l33tcode/teemo-attacking.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int: 6 | poisoned = 0 7 | begin, end = -1, -1 8 | 9 | for cur_begin in timeSeries: 10 | cur_end = cur_begin + duration 11 | 12 | if cur_begin > end: 13 | poisoned += end - begin 14 | begin = cur_begin 15 | 16 | end = cur_end 17 | 18 | return poisoned + (end - begin) 19 | -------------------------------------------------------------------------------- /l33tcode/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getHappyString(self, n: int, k: int) -> str: 3 | count = 0 4 | result: list[str] = [] 5 | 6 | def dfs(pos: int, prev: str) -> bool: 7 | if pos == n: 8 | nonlocal count 9 | 10 | count += 1 11 | return count == k 12 | 13 | for char in ("a", "b", "c"): 14 | if char != prev: 15 | result.append(char) 16 | if dfs(pos + 1, char): 17 | return True 18 | result.pop() 19 | 20 | return False 21 | 22 | dfs(0, "") 23 | 24 | return "".join(result) 25 | -------------------------------------------------------------------------------- /l33tcode/the-kth-factor-of-n.py: -------------------------------------------------------------------------------- 1 | import math 2 | import heapq 3 | 4 | 5 | class Solution: 6 | def kthFactor(self, n: int, k: int) -> int: 7 | heap = [] 8 | for num in range(1, int(math.sqrt(n)) + 1): 9 | if n % num == 0: 10 | div = n // num 11 | 12 | heapq.heappush(heap, num) 13 | 14 | if div != num: 15 | heapq.heappush(heap, div) 16 | 17 | 18 | for _ in range(k - 1): 19 | if not heap: 20 | return -1 21 | heapq.heappop(heap) 22 | 23 | if not heap: 24 | return -1 25 | 26 | return heap[0] 27 | -------------------------------------------------------------------------------- /l33tcode/thousand-separator.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def thousandSeparator(self, n: int) -> str: 3 | result = [] 4 | 5 | numbers = 0 6 | 7 | while n > 0: 8 | new_number = n % 10 9 | n //= 10 10 | 11 | if numbers > 0 and numbers % 3 == 0: 12 | result.append(".") 13 | 14 | result.append(str(new_number)) 15 | numbers += 1 16 | 17 | return "".join(reversed(result)) or "0" 18 | -------------------------------------------------------------------------------- /l33tcode/time-needed-to-inform-all-employees.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int: 3 | result = 0 4 | 5 | dp = [0] * n 6 | 7 | for employee in range(n): 8 | cur_time = 0 9 | while employee != headID: 10 | cur_time += informTime[manager[employee]] 11 | if cur_time > dp[manager[employee]]: 12 | dp[manager[employee]] = cur_time 13 | employee = manager[employee] 14 | else: 15 | break 16 | 17 | result = max(result, cur_time) 18 | 19 | return result 20 | -------------------------------------------------------------------------------- /l33tcode/to-lower-case.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def toLowerCase(self, string: 'str') -> 'str': 3 | out_str = "" 4 | 5 | for symbol in string: 6 | symbol_number = ord(symbol) 7 | if symbol_number > 64 and symbol_number < 91: 8 | out_str += chr(symbol_number + 32) 9 | else: 10 | out_str += symbol 11 | 12 | return out_str 13 | -------------------------------------------------------------------------------- /l33tcode/toss-strange-coins.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from functools import lru_cache 3 | 4 | 5 | class Solution: 6 | def probabilityOfHeads(self, prob: List[float], target: int) -> float: 7 | @lru_cache(None) 8 | def dp(coin: int, value: int) -> float: 9 | if coin == len(prob): 10 | return int(value == 0) 11 | 12 | return ( 13 | ((dp(coin + 1, value - 1) * prob[coin]) if value > 0 else 0) 14 | + dp(coin + 1, value) * (1 - prob[coin]) 15 | ) 16 | 17 | return dp(0, target) 18 | -------------------------------------------------------------------------------- /l33tcode/triangle.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minimumTotal(self, triangle: List[List[int]]) -> int: 6 | if not triangle: 7 | return 0 8 | 9 | dp = [0] * (len(triangle) + 1) 10 | 11 | for row in reversed(range(len(triangle))): 12 | dp_old = dp 13 | dp = [float("+inf")] * (row + 1) 14 | 15 | for col in range(row + 1): 16 | dp[col] = min(dp_old[col], dp_old[col + 1],) + triangle[row][col] 17 | 18 | return dp[0] 19 | -------------------------------------------------------------------------------- /l33tcode/two-city-scheduling.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoCitySchedCost(self, costs: List[List[int]]) -> int: 3 | costs.sort(key=lambda x: x[0] - x[1]) 4 | 5 | return sum(c[n // (len(costs) // 2)] for n, c in enumerate(costs)) 6 | -------------------------------------------------------------------------------- /l33tcode/two-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: list[int], target: int) -> tuple[int, int]: 3 | num_to_pos = {} 4 | for i, num in enumerate(nums): 5 | second = target - num 6 | if second in num_to_pos: 7 | return i, num_to_pos[second] 8 | 9 | num_to_pos[num] = i 10 | 11 | raise ValueError("Not found") 12 | -------------------------------------------------------------------------------- /l33tcode/ugly-number-ii.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class Solution: 4 | def nthUglyNumber(self, n: int) -> int: 5 | factors = [2, 3, 5] 6 | 7 | seen = {1} 8 | heap = [1] 9 | count = 0 10 | result = 0 11 | 12 | while count < n: 13 | num = heapq.heappop(heap) 14 | count += 1 15 | result = num 16 | 17 | for factor in factors: 18 | new_num = num * factor 19 | 20 | if new_num not in seen: 21 | heapq.heappush(heap, new_num) 22 | 23 | seen.add(new_num) 24 | 25 | return result 26 | -------------------------------------------------------------------------------- /l33tcode/unique-binary-search-trees.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numTrees(n int) int { 4 | dp := make([]int, n+1) 5 | dp[0] = 1 6 | 7 | for num := range make([]int, n) { 8 | elements := num + 1 9 | for split := range make([]int, elements) { 10 | dp[elements] += dp[split] * dp[elements-split-1] 11 | } 12 | } 13 | 14 | return dp[n] 15 | } 16 | -------------------------------------------------------------------------------- /l33tcode/unique-binary-search-trees.py: -------------------------------------------------------------------------------- 1 | from functools import cache 2 | 3 | 4 | class Solution: 5 | def numTrees(self, n: int) -> int: 6 | @cache 7 | def dfs(nodes: int) -> int: 8 | if nodes == 0: 9 | return 1 10 | 11 | count = 0 12 | for split in range(nodes): 13 | left_subtrees = dfs(split) 14 | right_subtrees = dfs(nodes - split - 1) 15 | count += left_subtrees * right_subtrees 16 | 17 | return count 18 | 19 | return dfs(n) 20 | -------------------------------------------------------------------------------- /l33tcode/unique-email-addresses.py: -------------------------------------------------------------------------------- 1 | # FIXME: speed it up 2 | # TODO: add some tests 3 | 4 | class Solution: 5 | def numUniqueEmails(self, emails: List[str]) -> int: 6 | result_set = set() 7 | 8 | for email in emails: 9 | pos = 0 10 | parsed_email = "" 11 | while email[pos] not in ["+", "@"]: 12 | if email[pos] != ".": 13 | parsed_email += email[pos] 14 | pos += 1 15 | while email[pos] != "@": 16 | pos += 1 17 | parsed_email += email[pos:] 18 | result_set.add(parsed_email) 19 | 20 | return len(result_set) 21 | -------------------------------------------------------------------------------- /l33tcode/unique-number-of-occurrences.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func uniqueOccurrences(arr []int) bool { 4 | occurences := map[int]int{} 5 | 6 | for _, num := range arr { 7 | if _, ok := occurences[num]; ok { 8 | occurences[num]++ 9 | } else { 10 | occurences[num] = 1 11 | } 12 | } 13 | 14 | hashMap := map[int]bool{} 15 | 16 | for _, num := range occurences { 17 | if _, ok := hashMap[num]; ok { 18 | return false 19 | } else { 20 | hashMap[num] = true 21 | } 22 | } 23 | 24 | return true 25 | } 26 | -------------------------------------------------------------------------------- /l33tcode/unique-paths-ii.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def uniquePathsWithObstacles(self, obstacles: List[List[int]]) -> int: 6 | rows, cols = len(obstacles), len(obstacles[0]) if obstacles else 0 7 | 8 | # We don't need to store data for all the previous rows, becauce we 9 | # only look the `row - 1` 10 | dp = [0] * cols 11 | dp[0] = 1 12 | 13 | for row in range(rows): 14 | for col in range(cols): 15 | if obstacles[row][col]: 16 | dp[col] = 0 17 | else: 18 | dp[col] += dp[col - 1] if col > 0 else 0 19 | 20 | return dp[-1] 21 | -------------------------------------------------------------------------------- /l33tcode/unique-paths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m: int, n: int) -> int: 3 | rows, cols = n, m 4 | 5 | dp = [0] * (cols + 1) 6 | # Can always get to the initial cell (row, cols > 0) 7 | dp[1] = 1 8 | 9 | for _ in range(rows): 10 | dp_old = dp 11 | dp = [0] * (cols + 1) 12 | for col in range(1, cols + 1): 13 | dp[col] = dp_old[col] + dp[col - 1] 14 | 15 | return dp[-1] 16 | -------------------------------------------------------------------------------- /l33tcode/valid-anagram.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAnagram(self, s: str, t: str) -> bool: 3 | return Counter(s) == Counter(t) 4 | -------------------------------------------------------------------------------- /l33tcode/valid-mountain-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validMountainArray(self, arr: List[int]) -> bool: 3 | if len(arr) < 3: 4 | return False 5 | 6 | up = True 7 | 8 | for pos in range(1, len(arr)): 9 | if arr[pos - 1] < arr[pos]: 10 | if not up: 11 | return False 12 | elif arr[pos - 1] > arr[pos]: 13 | if up: 14 | up = False 15 | else: 16 | return False 17 | 18 | return arr[0] < arr[1] and arr[-2] > arr[-1] 19 | -------------------------------------------------------------------------------- /l33tcode/valid-palindrome-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validPalindrome(self, s: str) -> bool: 3 | def search(left: int, right: int, deleted: int) -> bool: 4 | if left >= right: 5 | return True 6 | elif s[left] == s[right]: 7 | return search(left + 1, right - 1, deleted) 8 | elif deleted == 0: 9 | return search(left + 1, right, deleted + 1) or search(left, right - 1, deleted + 1) 10 | else: 11 | return False 12 | 13 | return search(0, len(s) - 1, 0) 14 | -------------------------------------------------------------------------------- /l33tcode/valid-parenthesis-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkValidString(self, s: str) -> bool: 3 | stars, open_parens, close_parens = 0, 0, 0 4 | 5 | for char in s: 6 | if char == "(": 7 | open_parens += 1 8 | elif char == ")": 9 | close_parens += 1 10 | else: 11 | stars += 1 12 | 13 | return open_parens - stars <= close_parens <= open_parens + stars 14 | -------------------------------------------------------------------------------- /l33tcode/widest-vertical-area-between-two-points-containing-no-points.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: 6 | points.sort() 7 | 8 | widest_area = 0 9 | 10 | prev_x = float("+inf") 11 | for x, _ in points: 12 | widest_area = max(widest_area, x - prev_x) 13 | prev_x = x 14 | 15 | return widest_area 16 | -------------------------------------------------------------------------------- /l33tcode_rs/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 4 4 | 5 | [[package]] 6 | name = "l33tcode_rs" 7 | version = "0.1.0" 8 | -------------------------------------------------------------------------------- /l33tcode_rs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "l33tcode_rs" 3 | version = "0.1.0" 4 | edition = "2024" 5 | 6 | [dependencies] 7 | -------------------------------------------------------------------------------- /l33tcode_rs/src/divide_array_into_equal_pairs.rs: -------------------------------------------------------------------------------- 1 | #[allow(dead_code)] 2 | struct Solution; 3 | 4 | use std::collections::HashMap; 5 | 6 | impl Solution { 7 | #[allow(dead_code)] 8 | pub fn divide_array(nums: Vec) -> bool { 9 | let mut hash_map = HashMap::new(); 10 | for num in nums { 11 | hash_map.entry(num).and_modify(|v| *v += 1).or_insert(1); 12 | } 13 | 14 | for v in hash_map.values() { 15 | if v % 2 != 0 { 16 | return false; 17 | } 18 | } 19 | true 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /l33tcode_rs/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod divide_array_into_equal_pairs; 2 | mod partition_array_according_to_given_pivot; 3 | mod longest_nice_subarray; 4 | mod minimum_number_of_operations_to_make_elements_in_array_distinct; 5 | -------------------------------------------------------------------------------- /l33tcode_rs/src/minimum_number_of_operations_to_make_elements_in_array_distinct.rs: -------------------------------------------------------------------------------- 1 | #[allow(dead_code)] 2 | struct Solution; 3 | 4 | use std::collections::HashSet; 5 | 6 | impl Solution { 7 | #[allow(dead_code)] 8 | #[allow(clippy::needless_pass_by_value)] 9 | pub fn minimum_operations(nums: Vec) -> i32 { 10 | let mut set = HashSet::new(); 11 | let mut unique_len = 0; 12 | 13 | for (i, num) in nums.iter().enumerate().rev() { 14 | if !set.insert(num) { 15 | break; 16 | } 17 | unique_len = i; 18 | } 19 | 20 | (unique_len / 3 + usize::from(unique_len % 3 > 0)).try_into().unwrap() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /pramp/array-index-and-element-equality.py: -------------------------------------------------------------------------------- 1 | def index_equals_value_search(arr): 2 | left, right = 0, len(arr) - 1 3 | result = -1 4 | 5 | while left <= right: 6 | middle = (left + right) // 2 7 | if middle > arr[middle]: 8 | left = middle + 1 9 | elif middle < arr[middle]: 10 | right = middle - 1 11 | else: 12 | right = middle - 1 13 | result = middle 14 | 15 | return result 16 | -------------------------------------------------------------------------------- /presentations/faang_learning_group/quicksort/k-select.md: -------------------------------------------------------------------------------- 1 | * Same approach as quicksort, but recurses only into 1 branch 2 | * Average time complexity is O(n) 3 | * Worst time complexity is O(n^2) 4 | * Same optimizations are applicable as for quicksort 5 | -------------------------------------------------------------------------------- /presentations/faang_learning_group/quicksort/links.md: -------------------------------------------------------------------------------- 1 | * [Wikipedia: Quicksort](https://en.wikipedia.org/wiki/Quicksort) 2 | * [Wikipedia: Las Vegas Quicksort](https://en.wikipedia.org/wiki/Las_Vegas_algorithm#Randomized_QuickSort) 3 | * [Wikipedia: Master theorem](https://en.wikipedia.org/wiki/Master_theorem_(analysis_of_algorithms)) 4 | * [Wikipedia: Median O(n) selection algorithm](https://en.wikipedia.org/wiki/Median_of_medians) 5 | * [Wikipedia: Quickselect](https://en.wikipedia.org/wiki/Quickselect) 6 | * [Youtube: MIT Lecture on randomized algorithms (quicksort included)](https://www.youtube.com/watch?v=cNB2lADK3_s) 7 | -------------------------------------------------------------------------------- /presentations/faang_learning_group/quicksort/problems.md: -------------------------------------------------------------------------------- 1 | * [Move zeroes (Easy)](https://leetcode.com/problems/move-zeroes/) - good practice of partition step of quick sort, which effectively does the same 2 | * [Sort an array (Medium)](https://leetcode.com/problems/sort-an-array/) - Task to verify correctness of your algorithm (TLE is fine for basic algorithm, unless there are no failed simple test cases) 3 | * [Kth Largest Element in an Array (Medium)](https://leetcode.com/problems/kth-largest-element-in-an-array/) - quickselect algorithm implementation 4 | * [Sort Colors (Medium)](https://leetcode.com/problems/sort-colors/) - Allegedly a problem to practice Hoare partition scheme (not verified) 5 | -------------------------------------------------------------------------------- /presentations/faang_learning_group/quicksort/quicksort.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def quicksort(array: List[int], left: int, right: int) -> None: 5 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [pydocstyle] 2 | ignore = D100, D101, D102 3 | -------------------------------------------------------------------------------- /yandex/qualification-for-mentors/component-path_1.input: -------------------------------------------------------------------------------- 1 | 6 7 2 | 2 2 6 10 7 8 3 | 1 2 4 | 2 3 5 | 1 3 6 | 3 5 7 | 5 6 8 | 5 6 9 | 3 4 10 | -------------------------------------------------------------------------------- /yandex/qualification-for-mentors/component-path_2.input: -------------------------------------------------------------------------------- 1 | 7 8 2 | 2 2 2 4 4 4 3 3 | 1 2 4 | 2 3 5 | 1 3 6 | 4 5 7 | 5 6 8 | 4 6 9 | 3 5 10 | 3 7 11 | -------------------------------------------------------------------------------- /yandex/qualification-for-mentors/component-path_3.input: -------------------------------------------------------------------------------- 1 | 13 10 2 | 523 75 368 246 21 163 219 605 140 751 265 828 956 3 | 10 13 4 | 13 1 5 | 7 11 6 | 3 12 7 | 8 5 8 | 13 12 9 | 12 9 10 | 8 11 11 | 13 9 12 | 7 6 13 | -------------------------------------------------------------------------------- /yandex/qualification-for-mentors/matrix-multiplication_1.input: -------------------------------------------------------------------------------- 1 | 3 2 | 1 2 3 | 2 8 4 | 8 4 5 | -------------------------------------------------------------------------------- /yandex/qualification-for-mentors/matrix-multiplication_2.input: -------------------------------------------------------------------------------- 1 | 1 2 | 10 100 3 | -------------------------------------------------------------------------------- /yandex/qualification-for-mentors/matrix-multiplication_3.input: -------------------------------------------------------------------------------- 1 | 4 2 | 3 2 3 | 2 4 4 | 4 1 5 | 1 5 6 | -------------------------------------------------------------------------------- /yandex/qualification-for-mentors/matrix-multiplication_4.input: -------------------------------------------------------------------------------- 1 | 4 2 | 1 1 3 | 1 1 4 | 1 1 5 | 1 1 6 | -------------------------------------------------------------------------------- /yandex/qualification-for-mentors/palindrome-concatenation_1.input: -------------------------------------------------------------------------------- 1 | 4 2 | a 3 | abbaa 4 | bba 5 | abb 6 | -------------------------------------------------------------------------------- /yandex/qualification-for-mentors/palindrome-concatenation_2.input: -------------------------------------------------------------------------------- 1 | 10 2 | rysqrfgh 3 | zvevzazdc 4 | ynzcxlrqwjs 5 | ynzcxlrqwj 6 | hgfrqsyrdzdzd 7 | cdza 8 | jwqrlxczny 9 | hgfrqsyru 10 | gazdc 11 | ynzcxlrqwjww 12 | --------------------------------------------------------------------------------