From 0f09cea26dfb062c2dda61dcb5f9f725d4c8b968 Mon Sep 17 00:00:00 2001 From: Vaibhav Nirmal Date: Mon, 10 Oct 2022 15:23:49 +0530 Subject: [PATCH] added new problems Added c++ Solutions of leetcode Co-Authored-By: Vaibhav Nirmal <70758433+vaibhavnirmal2001@users.noreply.github.com> --- 01-matrix/README.md | 29 +++ 1's Complement - GFG/1s-complement.cpp | 42 ++++ 1's Complement - GFG/README.md | 43 ++++ 1-two-sum/1-two-sum.cpp | 22 ++ 1-two-sum/NOTES.md | 1 + 1-two-sum/README.md | 38 +++ 100-same-tree/NOTES.md | 1 + 100-same-tree/README.md | 31 +++ .../1009-complement-of-base-10-integer.cpp | 7 + 1009-complement-of-base-10-integer/NOTES.md | 1 + 1009-complement-of-base-10-integer/README.md | 40 ++++ ...s-with-total-durations-divisible-by-60.cpp | 12 + .../NOTES.md | 1 + .../README.md | 30 +++ ...apacity-to-ship-packages-within-d-days.cpp | 51 ++++ .../NOTES.md | 1 + .../README.md | 49 ++++ .../102-binary-tree-level-order-traversal.cpp | 40 ++++ .../NOTES.md | 1 + .../README.md | 29 +++ ...022-sum-of-root-to-leaf-binary-numbers.cpp | 36 +++ .../NOTES.md | 1 + .../README.md | 32 +++ .../1029-two-city-scheduling.cpp | 35 +++ 1029-two-city-scheduling/NOTES.md | 1 + 1029-two-city-scheduling/README.md | 40 ++++ .../NOTES.md | 1 + .../README.md | 29 +++ .../104-maximum-depth-of-binary-tree.cpp | 23 ++ 104-maximum-depth-of-binary-tree/NOTES.md | 1 + 104-maximum-depth-of-binary-tree/README.md | 25 ++ .../1041-robot-bounded-in-circle.cpp | 23 ++ 1041-robot-bounded-in-circle/NOTES.md | 1 + 1041-robot-bounded-in-circle/README.md | 40 ++++ .../1049-last-stone-weight-ii.cpp | 36 +++ 1049-last-stone-weight-ii/NOTES.md | 1 + 1049-last-stone-weight-ii/README.md | 39 ++++ ...ee-from-preorder-and-inorder-traversal.cpp | 57 +++++ .../NOTES.md | 1 + .../README.md | 28 +++ ...ert-sorted-array-to-binary-search-tree.cpp | 38 +++ .../NOTES.md | 1 + .../README.md | 29 +++ 1094-car-pooling/1094-car-pooling.cpp | 10 + 1094-car-pooling/NOTES.md | 1 + 1094-car-pooling/README.md | 30 +++ .../11-container-with-most-water.cpp | 17 ++ 11-container-with-most-water/NOTES.md | 1 + 11-container-with-most-water/README.md | 31 +++ .../110-balanced-binary-tree.cpp | 35 +++ 110-balanced-binary-tree/NOTES.md | 1 + 110-balanced-binary-tree/README.md | 35 +++ .../NOTES.md | 1 + .../README.md | 46 ++++ ...114-flatten-binary-tree-to-linked-list.cpp | 37 +++ .../NOTES.md | 1 + .../README.md | 36 +++ .../115-distinct-subsequences.cpp | 27 +++ 115-distinct-subsequences/NOTES.md | 1 + 115-distinct-subsequences/README.md | 38 +++ .../NOTES.md | 1 + .../README.md | 44 ++++ 118-pascals-triangle/NOTES.md | 1 + 118-pascals-triangle/README.md | 19 ++ 120-triangle/120-triangle.cpp | 32 +++ 120-triangle/NOTES.md | 1 + 120-triangle/README.md | 35 +++ .../121-best-time-to-buy-and-sell-stock.cpp | 21 ++ 121-best-time-to-buy-and-sell-stock/NOTES.md | 1 + 121-best-time-to-buy-and-sell-stock/README.md | 30 +++ ...122-best-time-to-buy-and-sell-stock-ii.cpp | 14 ++ .../NOTES.md | 1 + .../README.md | 39 ++++ .../1220-count-vowels-permutation.cpp | 37 +++ 1220-count-vowels-permutation/NOTES.md | 1 + 1220-count-vowels-permutation/README.md | 40 ++++ ...23-best-time-to-buy-and-sell-stock-iii.cpp | 22 ++ .../NOTES.md | 1 + .../README.md | 37 +++ ...nimum-remove-to-make-valid-parentheses.cpp | 19 ++ .../README.md | 41 ++++ 126-word-ladder-ii/126-word-ladder-ii.cpp | 68 ++++++ 126-word-ladder-ii/NOTES.md | 1 + 126-word-ladder-ii/README.md | 40 ++++ 127-word-ladder/127-word-ladder.cpp | 32 +++ 127-word-ladder/NOTES.md | 1 + 127-word-ladder/README.md | 38 +++ ...the-smallest-divisor-given-a-threshold.cpp | 39 ++++ .../NOTES.md | 1 + .../README.md | 30 +++ .../1288-remove-covered-intervals.cpp | 33 +++ 1288-remove-covered-intervals/NOTES.md | 1 + 1288-remove-covered-intervals/README.md | 30 +++ .../1291-sequential-digits.cpp | 24 ++ 1291-sequential-digits/NOTES.md | 1 + 1291-sequential-digits/README.md | 19 ++ 13-Roman-to-Integer/13-roman-to-integer.cpp | 28 +++ 13-Roman-to-Integer/NOTES.md | 1 + ...ll-elements-in-two-binary-search-trees.cpp | 60 +++++ .../NOTES.md | 1 + .../README.md | 23 ++ .../131-palindrome-partitioning.cpp | 44 ++++ 131-palindrome-partitioning/NOTES.md | 1 + 131-palindrome-partitioning/README.md | 20 ++ 133-clone-graph/NOTES.md | 1 + 133-clone-graph/README.md | 59 +++++ .../1337-the-k-weakest-rows-in-a-matrix.cpp | 38 +++ 1337-the-k-weakest-rows-in-a-matrix/NOTES.md | 1 + 1337-the-k-weakest-rows-in-a-matrix/README.md | 61 +++++ 134-gas-station/NOTES.md | 1 + 134-gas-station/README.md | 44 ++++ ...-all-valid-pickup-and-delivery-options.cpp | 14 ++ .../README.md | 36 +++ 136-single-number/136-single-number.cpp | 9 + 136-single-number/README.md | 24 ++ .../138-copy-list-with-random-pointer.cpp | 61 +++++ 138-copy-list-with-random-pointer/NOTES.md | 1 + 138-copy-list-with-random-pointer/README.md | 47 ++++ .../NOTES.md | 1 + .../README.md | 46 ++++ 139-word-break/README.md | 37 +++ .../141-linked-list-cycle.cpp | 28 +++ 141-linked-list-cycle/NOTES.md | 1 + 141-linked-list-cycle/README.md | 40 ++++ .../142-linked-list-cycle-ii.cpp | 38 +++ 142-linked-list-cycle-ii/NOTES.md | 1 + 142-linked-list-cycle-ii/README.md | 40 ++++ ...ximum-points-you-can-obtain-from-cards.cpp | 46 ++++ .../NOTES.md | 1 + .../README.md | 39 ++++ 144-binary-tree-preorder-traversal/NOTES.md | 1 + 144-binary-tree-preorder-traversal/README.md | 32 +++ 146-lru-cache/146-lru-cache.cpp | 70 ++++++ 146-lru-cache/NOTES.md | 1 + 146-lru-cache/README.md | 44 ++++ ...ake-after-horizontal-and-vertical-cuts.cpp | 21 ++ .../NOTES.md | 1 + .../README.md | 43 ++++ .../1472-design-browser-history.cpp | 27 +++ 1472-design-browser-history/NOTES.md | 1 + 1472-design-browser-history/README.md | 45 ++++ 148-sort-list/148-sort-list.cpp | 50 ++++ 148-sort-list/NOTES.md | 1 + 148-sort-list/README.md | 32 +++ 1510-stone-game-iv/1510-stone-game-iv.cpp | 15 ++ 1510-stone-game-iv/NOTES.md | 1 + 1510-stone-game-iv/README.md | 36 +++ ...3-find-minimum-in-rotated-sorted-array.cpp | 22 ++ .../NOTES.md | 1 + .../README.md | 46 ++++ ...ind-minimum-in-rotated-sorted-array-ii.cpp | 26 +++ .../NOTES.md | 1 + .../README.md | 36 +++ 155-min-stack/155-min-stack.cpp | 82 +++++++ 155-min-stack/NOTES.md | 1 + 155-min-stack/README.md | 44 ++++ .../1552-magnetic-force-between-two-balls.cpp | 52 +++++ .../NOTES.md | 1 + .../README.md | 32 +++ 16-3sum-closest/16-3sum-closest.cpp | 34 +++ 16-3sum-closest/NOTES.md | 1 + .../160-intersection-of-two-linked-lists.cpp | 24 ++ .../README.md | 63 +++++ .../162-find-peak-element.cpp | 20 ++ 162-find-peak-element/NOTES.md | 1 + 162-find-peak-element/README.md | 30 +++ 165-compare-version-numbers/README.md | 49 ++++ .../1672-richest-customer-wealth.cpp | 15 ++ 1672-richest-customer-wealth/NOTES.md | 1 + 1672-richest-customer-wealth/README.md | 41 ++++ 1675-minimize-deviation-in-array/NOTES.md | 1 + 1675-minimize-deviation-in-array/README.md | 52 +++++ 169-majority-element/169-majority-element.cpp | 21 ++ 169-majority-element/NOTES.md | 1 + 169-majority-element/README.md | 23 ++ .../171-excel-sheet-column-number.cpp | 15 ++ 171-excel-sheet-column-number/NOTES.md | 1 + 171-excel-sheet-column-number/README.md | 42 ++++ .../1760-minimum-limit-of-balls-in-a-bag.cpp | 38 +++ 1760-minimum-limit-of-balls-in-a-bag/NOTES.md | 1 + .../README.md | 54 +++++ 179-largest-number/179-largest-number.cpp | 49 ++++ 179-largest-number/NOTES.md | 1 + 179-largest-number/README.md | 25 ++ 18-4sum/18-4sum.cpp | 44 ++++ 18-4sum/NOTES.md | 1 + 18-4sum/README.md | 32 +++ ...3-find-the-winner-of-the-circular-game.cpp | 9 + .../NOTES.md | 1 + .../README.md | 43 ++++ 189-rotate-array/NOTES.md | 1 + 189-rotate-array/README.md | 39 ++++ 2-add-two-numbers/2-add-two-numbers.cpp | 58 +++++ 2-add-two-numbers/NOTES.md | 1 + 2-add-two-numbers/README.md | 33 +++ 20-valid-parentheses/20-valid-parentheses.cpp | 53 +++++ 20-valid-parentheses/NOTES.md | 1 + 20-valid-parentheses/README.md | 36 +++ .../203-remove-linked-list-elements.cpp | 35 +++ 203-remove-linked-list-elements/NOTES.md | 1 + 203-remove-linked-list-elements/README.md | 30 +++ .../206-reverse-linked-list.cpp | 23 ++ 206-reverse-linked-list/NOTES.md | 1 + 206-reverse-linked-list/README.md | 32 +++ .../209-minimum-size-subarray-sum.cpp | 64 ++++++ 209-minimum-size-subarray-sum/NOTES.md | 1 + 209-minimum-size-subarray-sum/README.md | 33 +++ .../21-merge-two-sorted-lists.cpp | 46 ++++ 21-merge-two-sorted-lists/NOTES.md | 1 + 21-merge-two-sorted-lists/README.md | 34 +++ .../2145-count-the-hidden-sequences.cpp | 12 + 2145-count-the-hidden-sequences/NOTES.md | 1 + 2145-count-the-hidden-sequences/README.md | 57 +++++ .../NOTES.md | 1 + .../README.md | 44 ++++ ...ize-number-of-subsequences-in-a-string.cpp | 45 ++++ .../NOTES.md | 1 + .../README.md | 37 +++ 221-maximal-square/NOTES.md | 1 + 221-maximal-square/README.md | 31 +++ .../225-implement-stack-using-queues.cpp | 40 ++++ 225-implement-stack-using-queues/NOTES.md | 1 + 225-implement-stack-using-queues/README.md | 48 ++++ .../229-majority-element-ii.cpp | 47 ++++ 229-majority-element-ii/NOTES.md | 1 + 229-majority-element-ii/README.md | 32 +++ .../23-merge-k-sorted-lists.cpp | 59 +++++ 23-merge-k-sorted-lists/NOTES.md | 1 + 23-merge-k-sorted-lists/README.md | 43 ++++ 231-power-of-two/231-power-of-two.cpp | 14 ++ 231-power-of-two/NOTES.md | 1 + 231-power-of-two/README.md | 34 +++ .../232-implement-queue-using-stacks.cpp | 44 ++++ 232-implement-queue-using-stacks/NOTES.md | 1 + 232-implement-queue-using-stacks/README.md | 48 ++++ .../234-palindrome-linked-list.cpp | 55 +++++ 234-palindrome-linked-list/NOTES.md | 1 + ...owest-common-ancestor-of-a-binary-tree.cpp | 27 +++ .../NOTES.md | 1 + .../README.md | 36 +++ .../237-delete-node-in-a-linked-list.cpp | 17 ++ 237-delete-node-in-a-linked-list/NOTES.md | 1 + 237-delete-node-in-a-linked-list/README.md | 29 +++ .../238-product-of-array-except-self.cpp | 17 ++ 238-product-of-array-except-self/NOTES.md | 1 + 238-product-of-array-except-self/README.md | 26 +++ 239-sliding-window-maximum/NOTES.md | 1 + 239-sliding-window-maximum/README.md | 35 +++ .../24-swap-nodes-in-pairs.cpp | 29 +++ 24-swap-nodes-in-pairs/NOTES.md | 1 + 24-swap-nodes-in-pairs/README.md | 29 +++ 242-valid-anagram/242-valid-anagram.cpp | 8 + 242-valid-anagram/NOTES.md | 1 + 242-valid-anagram/README.md | 23 ++ 25-reverse-nodes-in-k-group/NOTES.md | 1 + 25-reverse-nodes-in-k-group/README.md | 31 +++ 258-add-digits/258-add-digits.cpp | 16 ++ 258-add-digits/NOTES.md | 1 + 258-add-digits/README.md | 29 +++ .../NOTES.md | 1 + .../README.md | 51 ++++ 283-move-zeroes/283-move-zeroes.cpp | 22 ++ 283-move-zeroes/NOTES.md | 1 + 283-move-zeroes/README.md | 22 ++ .../287-find-the-duplicate-number.cpp | 21 ++ 287-find-the-duplicate-number/NOTES.md | 1 + 287-find-the-duplicate-number/README.md | 37 +++ ...string-with-concatenation-of-all-words.cpp | 39 ++++ .../NOTES.md | 1 + .../README.md | 35 +++ 300-longest-increasing-subsequence/NOTES.md | 1 + 307-range-sum-query-mutable/NOTES.md | 1 + 307-range-sum-query-mutable/README.md | 43 ++++ 31-next-permutation/31-next-permutation.cpp | 37 +++ 31-next-permutation/NOTES.md | 1 + .../316-remove-duplicate-letters.cpp | 21 ++ 316-remove-duplicate-letters/NOTES.md | 1 + 316-remove-duplicate-letters/README.md | 26 +++ 326-power-of-three/326-power-of-three.cpp | 11 + 326-power-of-three/NOTES.md | 1 + 326-power-of-three/README.md | 32 +++ .../33-search-in-rotated-sorted-array.cpp | 30 +++ 33-search-in-rotated-sorted-array/NOTES.md | 1 + 33-search-in-rotated-sorted-array/README.md | 30 +++ ...st-position-of-element-in-sorted-array.cpp | 60 +++++ .../README.md | 27 +++ 342-power-of-four/342-power-of-four.cpp | 11 + 342-power-of-four/NOTES.md | 1 + 342-power-of-four/README.md | 24 ++ 344-reverse-string/NOTES.md | 1 + 344-reverse-string/README.md | 20 ++ .../345-reverse-vowels-of-a-string.cpp | 25 ++ 345-reverse-vowels-of-a-string/NOTES.md | 1 + 345-reverse-vowels-of-a-string/README.md | 20 ++ .../347-top-k-frequent-elements.cpp | 25 ++ 347-top-k-frequent-elements/NOTES.md | 1 + 347-top-k-frequent-elements/README.md | 22 ++ .../35-search-insert-position.cpp | 24 ++ 35-search-insert-position/NOTES.md | 1 + 35-search-insert-position/README.md | 33 +++ 37-sudoku-solver/NOTES.md | 1 + 37-sudoku-solver/README.md | 32 +++ 38-count-and-say/38-count-and-say.cpp | 20 ++ 38-count-and-say/NOTES.md | 1 + 38-count-and-say/README.md | 39 ++++ .../382-linked-list-random-node.cpp | 20 ++ 382-linked-list-random-node/NOTES.md | 1 + 382-linked-list-random-node/README.md | 45 ++++ .../389-find-the-difference.cpp | 9 + 389-find-the-difference/NOTES.md | 1 + 39-combination-sum/39-combination-sum.cpp | 29 +++ 39-combination-sum/NOTES.md | 1 + 39-combination-sum/README.md | 39 ++++ 394-decode-string/NOTES.md | 1 + 394-decode-string/README.md | 37 +++ .../397-integer-replacement.cpp | 28 +++ 397-integer-replacement/NOTES.md | 1 + 397-integer-replacement/README.md | 38 +++ 3sum-closest/3sum-closest.cpp | 31 +++ 3sum-closest/README.md | 19 ++ 3sum/3sum.cpp | 50 ++++ 3sum/README.md | 23 ++ .../4-median-of-two-sorted-arrays.cpp | 47 ++++ 4-median-of-two-sorted-arrays/NOTES.md | 1 + 4-median-of-two-sorted-arrays/README.md | 31 +++ .../40-combination-sum-ii.cpp | 30 +++ 40-combination-sum-ii/NOTES.md | 1 + 40-combination-sum-ii/README.md | 38 +++ 402-remove-k-digits/402-remove-k-digits.cpp | 19 ++ 402-remove-k-digits/NOTES.md | 1 + 402-remove-k-digits/README.md | 33 +++ .../410-split-array-largest-sum.cpp | 53 +++++ 410-split-array-largest-sum/NOTES.md | 1 + 410-split-array-largest-sum/README.md | 36 +++ 415-add-strings/NOTES.md | 1 + 415-add-strings/README.md | 32 +++ .../416-partition-equal-subset-sum.cpp | 38 +++ 416-partition-equal-subset-sum/NOTES.md | 1 + 416-partition-equal-subset-sum/README.md | 25 ++ .../42-trapping-rain-water.cpp | 24 ++ 42-trapping-rain-water/NOTES.md | 1 + ...maximum-xor-of-two-numbers-in-an-array.cpp | 22 ++ .../NOTES.md | 1 + .../438-find-all-anagrams-in-a-string.cpp | 29 +++ 438-find-all-anagrams-in-a-string/NOTES.md | 1 + 438-find-all-anagrams-in-a-string/README.md | 32 +++ .../442-find-all-duplicates-in-an-array.cpp | 16 ++ 442-find-all-duplicates-in-an-array/NOTES.md | 1 + 442-find-all-duplicates-in-an-array/README.md | 25 ++ 45-jump-game-ii/45-jump-game-ii.cpp | 25 ++ 45-jump-game-ii/NOTES.md | 1 + 45-jump-game-ii/README.md | 30 +++ 454-4sum-ii/454-4sum-ii.cpp | 23 ++ 454-4sum-ii/NOTES.md | 1 + 454-4sum-ii/README.md | 36 +++ 458-poor-pigs/NOTES.md | 1 + 458-poor-pigs/README.md | 33 +++ 46-permutations/46-permutations.cpp | 27 +++ 46-permutations/NOTES.md | 1 + 46-permutations/README.md | 22 ++ .../472-concatenated-words.cpp | 32 +++ 472-concatenated-words/NOTES.md | 1 + 472-concatenated-words/README.md | 30 +++ 48-rotate-image/48-rotate-image.cpp | 19 ++ 48-rotate-image/NOTES.md | 1 + 48-rotate-image/README.md | 26 +++ .../485-max-consecutive-ones.cpp | 21 ++ 485-max-consecutive-ones/README.md | 24 ++ 49-group-anagrams/49-group-anagrams.cpp | 20 ++ 49-group-anagrams/NOTES.md | 1 + 49-group-anagrams/README.md | 24 ++ 494-target-sum/494-target-sum.cpp | 79 +++++++ 494-target-sum/NOTES.md | 1 + 494-target-sum/README.md | 39 ++++ .../496-next-greater-element-i.cpp | 39 ++++ 496-next-greater-element-i/NOTES.md | 1 + 496-next-greater-element-i/README.md | 40 ++++ 4sum-ii/4sum-ii.cpp | 23 ++ 4sum-ii/README.md | 36 +++ 4sum/4sum.cpp | 54 +++++ 4sum/README.md | 32 +++ 50-powx-n/50-powx-n.cpp | 28 +++ 50-powx-n/NOTES.md | 1 + 50-powx-n/README.md | 31 +++ .../503-next-greater-element-ii.cpp | 27 +++ 503-next-greater-element-ii/NOTES.md | 1 + 503-next-greater-element-ii/README.md | 28 +++ 509-fibonacci-number/509-fibonacci-number.cpp | 8 + 509-fibonacci-number/NOTES.md | 1 + 509-fibonacci-number/README.md | 37 +++ 51-n-queens/51-n-queens.cpp | 70 ++++++ 51-n-queens/NOTES.md | 1 + 51-n-queens/README.md | 27 +++ 52-n-queens-ii/52-n-queens-ii.cpp | 46 ++++ 52-n-queens-ii/NOTES.md | 1 + 52-n-queens-ii/README.md | 25 ++ 520-detect-capital/520-detect-capital.cpp | 10 + 520-detect-capital/NOTES.md | 1 + 520-detect-capital/README.md | 26 +++ 525-contiguous-array/525-contiguous-array.cpp | 14 ++ 525-contiguous-array/NOTES.md | 1 + 525-contiguous-array/README.md | 25 ++ 53-maximum-subarray/53-maximum-subarray.cpp | 16 ++ 53-maximum-subarray/NOTES.md | 1 + 53-maximum-subarray/README.md | 35 +++ .../532-k-diff-pairs-in-an-array.cpp | 23 ++ 532-k-diff-pairs-in-an-array/NOTES.md | 1 + 532-k-diff-pairs-in-an-array/README.md | 43 ++++ 54-spiral-matrix/54-spiral-matrix.cpp | 37 +++ 54-spiral-matrix/NOTES.md | 1 + 54-spiral-matrix/README.md | 25 ++ .../540-single-element-in-a-sorted-array.cpp | 16 ++ 540-single-element-in-a-sorted-array/NOTES.md | 1 + .../README.md | 22 ++ 543-diameter-of-binary-tree/NOTES.md | 1 + 543-diameter-of-binary-tree/README.md | 28 +++ 55-jump-game/55-jump-game.cpp | 42 ++++ 55-jump-game/NOTES.md | 1 + 55-jump-game/README.md | 27 +++ .../556-next-greater-element-iii.cpp | 9 + 556-next-greater-element-iii/NOTES.md | 1 + 556-next-greater-element-iii/README.md | 19 ++ .../560-subarray-sum-equals-k.cpp | 15 ++ 567-permutation-in-string/NOTES.md | 1 + 567-permutation-in-string/README.md | 26 +++ .../576-out-of-boundary-paths.cpp | 29 +++ 576-out-of-boundary-paths/README.md | 27 +++ .../60-permutation-sequence.cpp | 17 ++ 60-permutation-sequence/NOTES.md | 1 + 60-permutation-sequence/README.md | 34 +++ .../605-can-place-flowers.cpp | 14 ++ 605-can-place-flowers/NOTES.md | 1 + 605-can-place-flowers/README.md | 22 ++ 61-rotate-list/NOTES.md | 1 + 61-rotate-list/README.md | 24 ++ 62-unique-paths/NOTES.md | 1 + 62-unique-paths/README.md | 30 +++ 63-unique-paths-ii/NOTES.md | 1 + 63-unique-paths-ii/README.md | 35 +++ 64-minimum-path-sum/64-minimum-path-sum.cpp | 24 ++ 64-minimum-path-sum/NOTES.md | 1 + 64-minimum-path-sum/README.md | 28 +++ 650-2-keys-keyboard/650-2-keys-keyboard.cpp | 24 ++ 650-2-keys-keyboard/NOTES.md | 1 + 650-2-keys-keyboard/README.md | 33 +++ 66-plus-one/NOTES.md | 1 + .../662-maximum-width-of-binary-tree.cpp | 40 ++++ 662-maximum-width-of-binary-tree/NOTES.md | 1 + 662-maximum-width-of-binary-tree/README.md | 38 +++ 67-add-binary/NOTES.md | 1 + 67-add-binary/README.md | 19 ++ .../NOTES.md | 1 + .../README.md | 28 +++ 7 Segment Display - GFG/7-segment-display.cpp | 71 ++++++ 7 Segment Display - GFG/README.md | 51 ++++ 70-climbing-stairs/NOTES.md | 1 + .../700-search-in-a-binary-search-tree.cpp | 17 ++ 700-search-in-a-binary-search-tree/NOTES.md | 1 + 700-search-in-a-binary-search-tree/README.md | 27 +++ .../701-insert-into-a-binary-search-tree.cpp | 33 +++ 701-insert-into-a-binary-search-tree/NOTES.md | 1 + .../README.md | 36 +++ 704-binary-search/704-binary-search.cpp | 28 +++ 704-binary-search/NOTES.md | 1 + 704-binary-search/README.md | 29 +++ 71-simplify-path/71-simplify-path.cpp | 40 ++++ 71-simplify-path/NOTES.md | 1 + 71-simplify-path/README.md | 46 ++++ 724-find-pivot-index/724-find-pivot-index.cpp | 18 ++ 724-find-pivot-index/NOTES.md | 1 + 724-find-pivot-index/README.md | 47 ++++ .../74-search-a-2d-matrix.cpp | 24 ++ 74-search-a-2d-matrix/NOTES.md | 1 + 74-search-a-2d-matrix/README.md | 30 +++ 740-delete-and-earn/740-delete-and-earn.cpp | 18 ++ 740-delete-and-earn/NOTES.md | 1 + 740-delete-and-earn/README.md | 37 +++ .../746-min-cost-climbing-stairs.cpp | 17 ++ 75-sort-colors/75-sort-colors.cpp | 24 ++ 75-sort-colors/NOTES.md | 1 + 75-sort-colors/README.md | 31 +++ 763-partition-labels/763-partition-labels.cpp | 23 ++ 763-partition-labels/NOTES.md | 1 + 763-partition-labels/README.md | 31 +++ 78-subsets/78-subsets.cpp | 19 ++ 78-subsets/NOTES.md | 1 + 78-subsets/README.md | 26 +++ 79-word-search/79-word-search.cpp | 38 +++ 79-word-search/NOTES.md | 1 + 79-word-search/README.md | 37 +++ .../8-string-to-integer-atoi.cpp | 34 +++ 8-string-to-integer-atoi/NOTES.md | 1 + 8-string-to-integer-atoi/README.md | 74 ++++++ ...remove-duplicates-from-sorted-array-ii.cpp | 10 + .../NOTES.md | 1 + .../README.md | 51 ++++ 804-unique-morse-code-words/NOTES.md | 1 + 804-unique-morse-code-words/README.md | 48 ++++ ...-remove-duplicates-from-sorted-list-ii.cpp | 42 ++++ .../NOTES.md | 1 + .../README.md | 24 ++ 823-binary-trees-with-factors/NOTES.md | 1 + 823-binary-trees-with-factors/README.md | 28 +++ .../84-largest-rectangle-in-histogram.cpp | 72 ++++++ 84-largest-rectangle-in-histogram/NOTES.md | 1 + 84-largest-rectangle-in-histogram/README.md | 25 ++ 847-shortest-path-visiting-all-nodes/NOTES.md | 1 + .../README.md | 31 +++ .../856-score-of-parentheses.cpp | 21 ++ 856-score-of-parentheses/NOTES.md | 1 + 856-score-of-parentheses/README.md | 38 +++ 858-mirror-reflection/NOTES.md | 1 + 858-mirror-reflection/README.md | 29 +++ .../875-koko-eating-bananas.cpp | 22 ++ .../876-middle-of-the-linked-list.cpp | 26 +++ .../881-boats-to-save-people.cpp | 27 +++ 881-boats-to-save-people/NOTES.md | 1 + 881-boats-to-save-people/README.md | 34 +++ .../890-find-and-replace-pattern.cpp | 18 ++ 890-find-and-replace-pattern/NOTES.md | 1 + 890-find-and-replace-pattern/README.md | 31 +++ .../895-maximum-frequency-stack.cpp | 23 ++ 895-maximum-frequency-stack/NOTES.md | 1 + 895-maximum-frequency-stack/README.md | 46 ++++ 90-subsets-ii/90-subsets-ii.cpp | 28 +++ 90-subsets-ii/NOTES.md | 1 + 90-subsets-ii/README.md | 20 ++ 916-word-subsets/NOTES.md | 1 + 916-word-subsets/README.md | 35 +++ .../NOTES.md | 1 + .../README.md | 37 +++ .../946-validate-stack-sequences.cpp | 15 ++ 946-validate-stack-sequences/NOTES.md | 1 + 946-validate-stack-sequences/README.md | 32 +++ .../977-squares-of-a-sorted-array.cpp | 23 ++ 977-squares-of-a-sorted-array/NOTES.md | 1 + 977-squares-of-a-sorted-array/README.md | 28 +++ .../98-validate-binary-search-tree.cpp | 31 +++ 98-validate-binary-search-tree/NOTES.md | 1 + 98-validate-binary-search-tree/README.md | 32 +++ .../981-time-based-key-value-store.cpp | 37 +++ 983-minimum-cost-for-tickets/NOTES.md | 1 + 983-minimum-cost-for-tickets/README.md | 51 ++++ .../991-broken-calculator.cpp | 21 ++ 991-broken-calculator/NOTES.md | 1 + 991-broken-calculator/README.md | 38 +++ 994-rotting-oranges/994-rotting-oranges.cpp | 48 ++++ 994-rotting-oranges/NOTES.md | 1 + 994-rotting-oranges/README.md | 43 ++++ .../README.md | 29 +++ ...to-a-number-represented-as-linked-list.cpp | 119 ++++++++++ .../README.md | 55 +++++ .../allocate-minimum-number-of-pages.cpp | 89 +++++++ Anagram of String - GFG/README.md | 34 +++ Anagram of String - GFG/anagram-of-string.cpp | 37 +++ Array to BST - GFG/README.md | 50 ++++ Array to BST - GFG/array-to-bst.cpp | 46 ++++ Biconnected Graph - GFG/README.md | 53 +++++ Biconnected Graph - GFG/biconnected-graph.cpp | 47 ++++ Binary Array Sorting - GFG/README.md | 47 ++++ .../binary-array-sorting.cpp | 79 +++++++ .../README.md | 32 +++ .../binary-number-to-decimal-number.cpp | 31 +++ Bitwise AND of the Array - GFG/README.md | 40 ++++ .../bitwise-and-of-the-array.cpp | 64 ++++++ Can Make Triangle - GFG/README.md | 50 ++++ Can Make Triangle - GFG/can-make-triangle.cpp | 52 +++++ Check Mirror in N-ary tree - GFG/README.md | 50 ++++ .../check-mirror-in-nary-tree.cpp | 52 +++++ Check if subtree - GFG/README.md | 49 ++++ Check if subtree - GFG/check-if-subtree.cpp | 160 +++++++++++++ .../README.md | 30 +++ ...lone-a-stack-without-using-extra-space.cpp | 87 +++++++ .../README.md | 30 +++ ...one-a-stack-without-usinig-extra-space.cpp | 62 +++++ Coins of Geekland - GFG/README.md | 40 ++++ Coins of Geekland - GFG/coins-of-geekland.cpp | 70 ++++++ Compute Before Matrix - GFG/README.md | 54 +++++ .../compute-before-matrix.cpp | 52 +++++ Concatenate two numbers - GFG/README.md | 46 ++++ .../concatenate-two-numbers.cpp | 62 +++++ Corona Vaccine - GFG/README.md | 52 +++++ Corona Vaccine - GFG/corona-vaccine.cpp | 155 +++++++++++++ Counts Zeros Xor Pairs - GFG/README.md | 43 ++++ .../counts-zeros-xor-pairs.cpp | 48 ++++ Cousins of a given node - GFG/README.md | 51 ++++ .../cousins-of-a-given-node.cpp | 217 ++++++++++++++++++ .../README.md | 41 ++++ .../cyclically-rotate-an-array-by-one.cpp | 39 ++++ Escape the Forbidden Forest - GFG/README.md | 42 ++++ .../escape-the-forbidden-forest.cpp | 53 +++++ Even and Odd - GFG/README.md | 44 ++++ Even and Odd - GFG/even-and-odd.cpp | 75 ++++++ Excel Sheet _ Part - 1 - GFG/README.md | 25 ++ .../excel-sheet-part-1.cpp | 50 ++++ Find Missing And Repeating - GFG/README.md | 36 +++ .../find-missing-and-repeating.cpp | 56 +++++ Find Nth root of M - GFG/README.md | 36 +++ .../find-nth-root-of-m.cpp | 40 ++++ Find Prime numbers in a range - GFG/README.md | 38 +++ .../find-prime-numbers-in-a-range.cpp | 49 ++++ Find position of set bit - GFG/README.md | 39 ++++ .../find-position-of-set-bit.cpp | 38 +++ .../README.md | 39 ++++ .../find-rectangle-with-corners-as-1.cpp | 69 ++++++ .../README.md | 50 ++++ .../find-the-closest-element-in-bst.cpp | 135 +++++++++++ Find the Maximum Flow - GFG/README.md | 51 ++++ .../find-the-maximum-flow.cpp | 126 ++++++++++ Find the number of islands - GFG/README.md | 50 ++++ .../find-the-number-of-islands.cpp | 57 +++++ Form a palindrome - GFG/README.md | 40 ++++ Form a palindrome - GFG/form-a-palindrome.cpp | 50 ++++ Fraction Trouble - GFG/README.md | 32 +++ Fraction Trouble - GFG/fraction-trouble.cpp | 38 +++ Gadgets of Doraland - GFG/README.md | 41 ++++ .../gadgets-of-doraland.py | 38 +++ Handshakes - GFG/README.md | 51 ++++ Handshakes - GFG/handshakes.cpp | 31 +++ Height Using Parent Array - GFG/README.md | 33 +++ .../height-using-parent-array.cpp | 50 ++++ Help Classmates - GFG/README.md | 44 ++++ Help Classmates - GFG/help-classmates.cpp | 60 +++++ Hit most Balloons - GFG/README.md | 42 ++++ Hit most Balloons - GFG/hit-most-balloons.cpp | 85 +++++++ Implement stack using array - GFG/README.md | 43 ++++ .../implement-stack-using-array.cpp | 68 ++++++ .../README.md | 58 +++++ .../implementing-dijkstra-algorithm.cpp | 76 ++++++ .../README.md | 41 ++++ .../insertion-sort-for-singly-linked-list.cpp | 105 +++++++++ .../README.md | 48 ++++ .../kth-element-of-two-sorted-arrays.cpp | 69 ++++++ Kadane's Algorithm - GFG/README.md | 44 ++++ .../kadanes-algorithm.cpp | 56 +++++ Kth smallest element - GFG/README.md | 46 ++++ .../kth-smallest-element.cpp | 45 ++++ Largest subarray with 0 sum - GFG/README.md | 25 ++ .../largest-subarray-with-0-sum.cpp | 56 +++++ Largest value in each level - GFG/README.md | 51 ++++ .../largest-value-in-each-level.cpp | 142 ++++++++++++ Leaves to DLL - GFG/README.md | 61 +++++ Leaves to DLL - GFG/leaves-to-dll.cpp | 169 ++++++++++++++ Left View of Binary Tree - GFG/README.md | 42 ++++ .../left-view-of-binary-tree.cpp | 148 ++++++++++++ .../README.md | 41 ++++ .../longest-common-prefix-in-an-array.cpp | 56 +++++ .../README.md | 44 ++++ ...longest-substring-to-form-a-palindrome.cpp | 43 ++++ M-Coloring Problem - GFG/README.md | 39 ++++ .../mcoloring-problem.cpp | 66 ++++++ Matrix Operations - GFG/README.md | 49 ++++ Matrix Operations - GFG/matrix-operations.cpp | 83 +++++++ Maximum Winning score - GFG/README.md | 53 +++++ .../maximum-winning-score.cpp | 137 +++++++++++ Maximum average subarray - GFG/README.md | 39 ++++ .../maximum-average-subarray.cpp | 53 +++++ ...-number-of-events-that-can-be-attended.cpp | 55 +++++ Maximum selections - GFG/README.md | 68 ++++++ .../maximum-selections.cpp | 53 +++++ .../README.md | 34 +++ ...ncreasing-order-elements-from-n-arrays.cpp | 62 +++++ .../README.md | 45 ++++ .../median-in-a-rowwise-sorted-matrix.cpp | 69 ++++++ Merge K sorted linked lists - GFG/README.md | 51 ++++ .../merge-k-sorted-linked-lists.cpp | 134 +++++++++++ Min Coin - GFG/README.md | 39 ++++ Min Coin - GFG/min-coin.cpp | 61 +++++ Minimum Swaps to Sort - GFG/README.md | 38 +++ .../minimum-swaps-to-sort.cpp | 47 ++++ .../README.md | 30 +++ ...-zeros-to-the-front-of-the-linked-list.cpp | 87 +++++++ .../README.md | 37 +++ ...umbers-with-digits-in-increasing-order.cpp | 56 +++++ Negative weight cycle - GFG/README.md | 40 ++++ .../negative-weight-cycle.cpp | 44 ++++ Next Permutation - GFG/README.md | 32 +++ Next Permutation - GFG/next-permutation.cpp | 67 ++++++ Nodes at even distance - GFG/README.md | 44 ++++ .../nodes-at-even-distance.cpp | 64 ++++++ .../README.md | 49 ++++ ...words-with-k-maximum-contiguous-vowels.cpp | 86 +++++++ Optimal binary search tree - GFG/README.md | 56 +++++ .../optimal-binary-search-tree.cpp | 58 +++++ Partition Equal Subset Sum - GFG/README.md | 36 +++ .../partition-equal-subset-sum.cpp | 57 +++++ Positive Negative Pair - GFG/README.md | 40 ++++ .../positive-negative-pair.cpp | 69 ++++++ Predecessor and Successor - GFG/README.md | 33 +++ .../predecessor-and-successor.cpp | 134 +++++++++++ Queries on Strings - GFG/README.md | 35 +++ .../queries-on-strings.cpp | 48 ++++ Queue using two Stacks - GFG/README.md | 57 +++++ .../queue-using-two-stacks.cpp | 82 +++++++ Rank The Permutations - GFG/README.md | 44 ++++ .../rank-the-permutations.cpp | 49 ++++ Rat in a Maze Problem - I - GFG/README.md | 47 ++++ .../rat-in-a-maze-problem-i.cpp | 97 ++++++++ .../README.md | 46 ++++ .../rearrange-geek-and-his-classmates.cpp | 49 ++++ .../README.md | 38 +++ ...emove-leading-zeros-from-an-ip-address.cpp | 58 +++++ Return two prime numbers - GFG/README.md | 33 +++ .../return-two-prime-numbers.cpp | 46 ++++ .../README.md | 57 +++++ .../reverse-first-k-elements-of-queue.cpp | 55 +++++ .../README.md | 41 ++++ .../reverse-words-in-a-given-string.cpp | 48 ++++ Rotate by 90 degree - GFG/README.md | 31 +++ .../rotate-by-90-degree.cpp | 67 ++++++ Search Pattern (Z-algorithm) - GFG/README.md | 39 ++++ .../search-pattern-zalgorithm.cpp | 56 +++++ Search a node in BST - GFG/README.md | 49 ++++ .../search-a-node-in-bst.cpp | 68 ++++++ Shortest Path between Cities - GFG/README.md | 51 ++++ .../shortest-path-between-cities.cpp | 35 +++ .../README.md | 47 ++++ .../shortest-unique-prefix-for-every-word.cpp | 106 +++++++++ Smallest Absolute Difference - GFG/README.md | 47 ++++ .../smallest-absolute-difference.cpp | 52 +++++ .../README.md | 43 ++++ ...allest-greater-elements-in-whole-array.cpp | 52 +++++ .../README.md | 39 ++++ .../smallest-window-containing-0-1-and-2.cpp | 52 +++++ Sort a stack - GFG/README.md | 30 +++ Sort a stack - GFG/sort-a-stack.cpp | 74 ++++++ .../README.md | 42 ++++ .../sort-an-array-of-0s-1s-and-2s.cpp | 48 ++++ Sort by Set Bit Count - GFG/README.md | 63 +++++ .../sort-by-set-bit-count.cpp | 54 +++++ Special Matrix - GFG/README.md | 40 ++++ Special Matrix - GFG/special-matrix.cpp | 53 +++++ Spidey Sense - GFG/README.md | 52 +++++ Spidey Sense - GFG/spidey-sense.cpp | 78 +++++++ Stack using two queues - GFG/README.md | 44 ++++ .../stack-using-two-queues.cpp | 79 +++++++ Subset Sums - GFG/README.md | 43 ++++ Subset Sums - GFG/subset-sums.cpp | 52 +++++ Subsets - GFG/README.md | 54 +++++ Subsets - GFG/subsets.cpp | 76 ++++++ Swap Kth nodes from ends - GFG/README.md | 50 ++++ .../swap-kth-nodes-from-ends.cpp | 138 +++++++++++ .../README.md | 49 ++++ .../the-painters-partition-problem-ii.cpp | 83 +++++++ Transfiguration - GFG/README.md | 46 ++++ Triangle and Square - GFG/README.md | 45 ++++ .../triangle-and-square.cpp | 29 +++ Union of two arrays - GFG/README.md | 45 ++++ .../union-of-two-arrays.cpp | 50 ++++ Word Break - Part 2 - GFG/README.md | 36 +++ .../word-break-part-2.cpp | 83 +++++++ XOR Game - GFG/README.md | 33 +++ XOR Game - GFG/xor-game.cpp | 36 +++ accounts-merge/README.md | 35 +++ accounts-merge/accounts-merge.cpp | 29 +++ add-digits/README.md | 29 +++ add-digits/add-digits.cpp | 16 ++ add-strings/README.md | 32 +++ add-strings/add-strings.cpp | 20 ++ add-two-numbers/README.md | 33 +++ add-two-numbers/add-two-numbers.cpp | 58 +++++ .../README.md | 43 ++++ ...ll-elements-in-two-binary-search-trees.cpp | 60 +++++ all-paths-from-source-to-target/README.md | 48 ++++ .../all-paths-from-source-to-target.cpp | 19 ++ all-possible-full-binary-trees/README.md | 26 +++ .../all-possible-full-binary-trees.cpp | 36 +++ arranging-coins/README.md | 26 +++ arranging-coins/arranging-coins.cpp | 20 ++ array-of-doubled-pairs/README.md | 37 +++ balance-a-binary-search-tree/README.md | 26 +++ balanced-binary-tree/README.md | 35 +++ balanced-binary-tree/balanced-binary-tree.cpp | 37 +++ best-sightseeing-pair/README.md | 28 +++ .../best-sightseeing-pair.cpp | 12 + best-time-to-buy-and-sell-stock-ii/README.md | 38 +++ .../best-time-to-buy-and-sell-stock-ii.cpp | 9 + best-time-to-buy-and-sell-stock-iii/README.md | 37 +++ best-time-to-buy-and-sell-stock-iv/README.md | 30 +++ .../best-time-to-buy-and-sell-stock-iv.cpp | 42 ++++ .../README.md | 32 +++ ...me-to-buy-and-sell-stock-with-cooldown.cpp | 18 ++ best-time-to-buy-and-sell-stock/README.md | 30 +++ .../best-time-to-buy-and-sell-stock.cpp | 12 + .../README.md | 46 ++++ ...binary-search-tree-to-greater-sum-tree.cpp | 16 ++ binary-search/README.md | 29 +++ binary-search/binary-search.cpp | 19 ++ binary-tree-inorder-traversal/README.md | 43 ++++ .../binary-tree-inorder-traversal.cpp | 27 +++ binary-tree-level-order-traversal/README.md | 29 +++ .../binary-tree-level-order-traversal.cpp | 81 +++++++ binary-tree-maximum-path-sum/README.md | 29 +++ .../binary-tree-maximum-path-sum.cpp | 17 ++ binary-tree-paths/README.md | 25 ++ binary-tree-paths/binary-tree-paths.cpp | 41 ++++ binary-tree-postorder-traversal/README.md | 43 ++++ binary-tree-preorder-traversal/README.md | 44 ++++ .../binary-tree-preorder-traversal.cpp | 28 +++ binary-tree-pruning/README.md | 34 +++ binary-tree-right-side-view/README.md | 29 +++ .../binary-tree-right-side-view.cpp | 41 ++++ .../README.md | 29 +++ ...nary-tree-zigzag-level-order-traversal.cpp | 53 +++++ binary-watch/README.md | 37 +++ binary-watch/binary-watch.cpp | 25 ++ build-array-from-permutation/README.md | 35 +++ .../build-array-from-permutation.cpp | 13 ++ burst-balloons/README.md | 30 +++ burst-balloons/burst-balloons.cpp | 29 +++ climbing-stairs/README.md | 31 +++ climbing-stairs/climbing-stairs.cpp | 13 ++ clone-graph/README.md | 65 ++++++ coin-change-2/README.md | 43 ++++ coin-change-2/coin-change-2.cpp | 38 +++ coin-change/README.md | 35 +++ coin-change/coin-change.cpp | 17 ++ combination-sum-iv/README.md | 40 ++++ combination-sum-iv/combination-sum-iv.cpp | 12 + combination-sum/README.md | 51 ++++ combination-sum/combination-sum.cpp | 26 +++ combine-two-tables/README.md | 32 +++ combine-two-tables/combine-two-tables.sql | 4 + consecutive-characters/README.md | 45 ++++ .../consecutive-characters.cpp | 27 +++ .../README.md | 28 +++ ...e-from-inorder-and-postorder-traversal.cpp | 51 ++++ .../README.md | 28 +++ ...ee-from-preorder-and-inorder-traversal.cpp | 51 ++++ contains-duplicate-ii/README.md | 30 +++ .../contains-duplicate-ii.cpp | 14 ++ contains-duplicate/README.md | 21 ++ contains-duplicate/contains-duplicate.cpp | 22 ++ .../README.md | 44 ++++ ...ary-number-in-a-linked-list-to-integer.cpp | 22 ++ .../README.md | 29 +++ ...ert-sorted-array-to-binary-search-tree.cpp | 38 +++ copy-list-with-random-pointer/README.md | 54 +++++ .../copy-list-with-random-pointer.cpp | 61 +++++ count-number-of-teams/README.md | 42 ++++ count-sorted-vowel-strings/README.md | 34 +++ .../README.md | 52 +++++ ...ubstrings-that-differ-by-one-character.cpp | 54 +++++ .../README.md | 54 +++++ course-schedule-ii/README.md | 42 ++++ course-schedule-ii/course-schedule-ii.cpp | 37 +++ course-schedule/README.md | 36 +++ custom-sort-string/README.md | 26 +++ custom-sort-string/custom-sort-string.cpp | 19 ++ daily-temperatures/README.md | 21 ++ daily-temperatures/daily-temperatures.cpp | 16 ++ decode-ways-ii/README.md | 59 +++++ decode-ways/README.md | 60 +++++ decode-ways/decode-ways.cpp | 26 +++ deepest-leaves-sum/README.md | 22 ++ deepest-leaves-sum/deepest-leaves-sum.cpp | 31 +++ delete-and-earn/README.md | 37 +++ delete-leaves-with-a-given-value/README.md | 53 +++++ delete-node-in-a-bst/README.md | 47 ++++ delete-node-in-a-bst/delete-node-in-a-bst.cpp | 65 ++++++ delete-node-in-a-linked-list/README.md | 47 ++++ .../delete-node-in-a-linked-list.cpp | 17 ++ destination-city/README.md | 41 ++++ detonate-the-maximum-bombs/README.md | 49 ++++ .../detonate-the-maximum-bombs.cpp | 38 +++ di-string-match/README.md | 28 +++ di-string-match/di-string-match.cpp | 9 + diameter-of-binary-tree/README.md | 28 +++ .../diameter-of-binary-tree.cpp | 40 ++++ different-ways-to-add-parentheses/README.md | 33 +++ divide-two-integers/README.md | 43 ++++ edit-distance/README.md | 41 ++++ encode-and-decode-tinyurl/README.md | 34 +++ .../encode-and-decode-tinyurl.cpp | 13 ++ excel-sheet-column-title/README.md | 45 ++++ .../excel-sheet-column-title.cpp | 24 ++ fibonacci-number/README.md | 37 +++ fibonacci-number/fibonacci-number.cpp | 7 + .../README.md | 52 +++++ ...-a-binary-tree-in-a-clone-of-that-tree.cpp | 18 ++ .../README.md | 22 ++ ...nd-all-numbers-disappeared-in-an-array.cpp | 15 ++ find-center-of-star-graph/README.md | 30 +++ .../find-center-of-star-graph.cpp | 22 ++ .../README.md | 27 +++ ...st-position-of-element-in-sorted-array.cpp | 23 ++ find-median-from-data-stream/README.md | 50 ++++ .../find-median-from-data-stream.cpp | 26 +++ .../README.md | 36 +++ ...ind-minimum-in-rotated-sorted-array-ii.cpp | 29 +++ .../README.md | 46 ++++ .../find-minimum-in-rotated-sorted-array.cpp | 21 ++ find-peak-element/README.md | 30 +++ find-peak-element/find-peak-element.cpp | 15 ++ .../README.md | 60 +++++ find-the-duplicate-number/README.md | 38 +++ .../find-the-duplicate-number.cpp | 21 ++ find-the-town-judge/README.md | 57 +++++ find-the-town-judge/find-the-town-judge.cpp | 37 +++ .../README.md | 43 ++++ finding-the-users-active-minutes/README.md | 42 ++++ first-bad-version/README.md | 31 +++ first-bad-version/first-bad-version.cpp | 12 + .../README.md | 77 +++++++ ...latten-a-multilevel-doubly-linked-list.cpp | 25 ++ flatten-binary-tree-to-linked-list/README.md | 36 +++ .../flatten-binary-tree-to-linked-list.cpp | 37 +++ .../README.md | 38 +++ flip-string-to-monotone-increasing/README.md | 36 +++ .../flip-string-to-monotone-increasing.cpp | 14 ++ flood-fill/README.md | 35 +++ flood-fill/flood-fill.cpp | 36 +++ fruit-into-baskets/README.md | 51 ++++ generate-parentheses/README.md | 17 ++ generate-parentheses/generate-parentheses.cpp | 19 ++ group-anagrams/README.md | 24 ++ group-anagrams/group-anagrams.cpp | 26 +++ .../README.md | 35 +++ ...le-given-the-group-size-they-belong-to.cpp | 14 ++ hamming-distance/README.md | 29 +++ hamming-distance/hamming-distance.cpp | 29 +++ house-robber-ii/README.md | 34 +++ house-robber-iii/README.md | 29 +++ house-robber-iii/house-robber-iii.cpp | 18 ++ house-robber/README.md | 29 +++ house-robber/house-robber.cpp | 21 ++ increasing-order-search-tree/README.md | 22 ++ insert-into-a-binary-search-tree/README.md | 36 +++ .../insert-into-a-binary-search-tree.cpp | 33 +++ insertion-sort-list/README.md | 33 +++ insertion-sort-list/insertion-sort-list.cpp | 20 ++ integer-break/README.md | 26 +++ integer-break/integer-break.cpp | 22 ++ intersection-of-two-arrays/README.md | 24 ++ .../intersection-of-two-arrays.cpp | 39 ++++ intersection-of-two-linked-lists/README.md | 63 +++++ .../intersection-of-two-linked-lists.cpp | 39 ++++ interval-list-intersections/README.md | 45 ++++ .../interval-list-intersections.cpp | 15 ++ .../README.md | 43 ++++ invert-binary-tree/README.md | 29 +++ invert-binary-tree/invert-binary-tree.cpp | 27 +++ is-graph-bipartite/README.md | 39 ++++ is-graph-bipartite/is-graph-bipartite.cpp | 53 +++++ is-subsequence/README.md | 23 ++ is-subsequence/is-subsequence.cpp | 27 +++ isomorphic-strings/README.md | 26 +++ isomorphic-strings/isomorphic-strings.cpp | 12 + iterator-for-combination/README.md | 37 +++ .../iterator-for-combination.cpp | 24 ++ jewels-and-stones/README.md | 21 ++ jewels-and-stones/jewels-and-stones.cpp | 24 ++ jump-game-ii/README.md | 30 +++ jump-game-ii/jump-game-ii.cpp | 17 ++ jump-game/README.md | 27 +++ k-closest-points-to-origin/README.md | 33 +++ .../k-closest-points-to-origin.cpp | 12 + koko-eating-bananas/README.md | 36 +++ kth-largest-element-in-an-array/README.md | 20 ++ kth-smallest-element-in-a-bst/README.md | 27 +++ .../kth-smallest-element-in-a-bst.cpp | 60 +++++ .../README.md | 30 +++ ...th-smallest-element-in-a-sorted-matrix.cpp | 29 +++ .../README.md | 37 +++ ...argest-component-size-by-common-factor.cpp | 45 ++++ .../README.md | 33 +++ .../letter-combinations-of-a-phone-number.cpp | 24 ++ linked-list-cycle-ii/README.md | 40 ++++ linked-list-cycle/README.md | 40 ++++ linked-list-cycle/linked-list-cycle.cpp | 27 +++ longest-common-subsequence/README.md | 40 ++++ .../longest-common-subsequence.cpp | 11 + longest-consecutive-sequence/README.md | 26 +++ .../longest-consecutive-sequence.cpp | 39 ++++ longest-increasing-subsequence/README.md | 35 +++ .../longest-increasing-subsequence.cpp | 12 + longest-palindromic-subsequence/README.md | 27 +++ longest-palindromic-substring/README.md | 24 ++ .../longest-palindromic-substring.cpp | 18 ++ .../README.md | 29 +++ .../README.md | 39 ++++ ...substring-without-repeating-characters.cpp | 36 +++ longest-uncommon-subsequence-ii/README.md | 27 +++ .../README.md | 36 +++ ...ommon-ancestor-of-a-binary-search-tree.cpp | 29 +++ .../README.md | 36 +++ ...owest-common-ancestor-of-a-binary-tree.cpp | 30 +++ majority-element-ii/README.md | 32 +++ majority-element-ii/majority-element-ii.cpp | 59 +++++ majority-element/README.md | 23 ++ majority-element/majority-element.cpp | 19 ++ make-the-string-great/README.md | 45 ++++ .../make-the-string-great.cpp | 12 + matrix-block-sum/README.md | 31 +++ matrix-block-sum/matrix-block-sum.cpp | 81 +++++++ max-area-of-island/README.md | 30 +++ max-area-of-island/max-area-of-island.cpp | 19 ++ max-consecutive-ones-iii/README.md | 27 +++ .../max-consecutive-ones-iii.cpp | 28 +++ max-consecutive-ones/README.md | 24 ++ max-consecutive-ones/max-consecutive-ones.cpp | 29 +++ maximal-rectangle/README.md | 44 ++++ maximal-rectangle/maximal-rectangle.cpp | 30 +++ maximal-square/README.md | 31 +++ maximal-square/maximal-square.cpp | 23 ++ maximum-69-number/README.md | 36 +++ maximum-average-subarray-i/README.md | 27 +++ .../maximum-average-subarray-i.cpp | 23 ++ maximum-binary-tree/README.md | 42 ++++ maximum-depth-of-binary-tree/README.md | 37 +++ .../maximum-depth-of-binary-tree.cpp | 22 ++ .../README.md | 30 +++ ...m-difference-between-node-and-ancestor.cpp | 19 ++ .../README.md | 52 +++++ maximum-length-of-repeated-subarray/README.md | 24 ++ .../README.md | 48 ++++ maximum-product-subarray/README.md | 30 +++ .../maximum-product-subarray.cpp | 23 ++ maximum-profit-in-job-scheduling/README.md | 44 ++++ .../maximum-profit-in-job-scheduling.cpp | 16 ++ maximum-score-from-removing-stones/README.md | 49 ++++ maximum-subarray/README.md | 32 +++ maximum-subarray/maximum-subarray.cpp | 14 ++ maximum-sum-circular-subarray/README.md | 51 ++++ .../maximum-sum-circular-subarray.cpp | 22 ++ maximum-units-on-a-truck/README.md | 39 ++++ .../maximum-units-on-a-truck.cpp | 19 ++ median-of-two-sorted-arrays/README.md | 49 ++++ .../median-of-two-sorted-arrays.cpp | 29 +++ merge-intervals/README.md | 26 +++ merge-intervals/merge-intervals.cpp | 22 ++ merge-k-sorted-lists/README.md | 43 ++++ merge-k-sorted-lists/merge-k-sorted-lists.cpp | 59 +++++ merge-sorted-array/README.md | 46 ++++ merge-sorted-array/merge-sorted-array.cpp | 32 +++ merge-two-binary-trees/README.md | 29 +++ .../merge-two-binary-trees.cpp | 29 +++ merge-two-sorted-lists/README.md | 30 +++ .../merge-two-sorted-lists.cpp | 54 +++++ middle-of-the-linked-list/README.md | 27 +++ .../middle-of-the-linked-list.cpp | 26 +++ min-cost-climbing-stairs/README.md | 38 +++ .../min-cost-climbing-stairs.cpp | 18 ++ minimum-absolute-difference-in-bst/README.md | 26 +++ .../minimum-absolute-difference-in-bst.cpp | 41 ++++ .../README.md | 42 ++++ ...ost-to-move-chips-to-the-same-position.cpp | 9 + minimum-depth-of-binary-tree/README.md | 27 +++ .../minimum-depth-of-binary-tree.cpp | 44 ++++ minimum-distance-between-bst-nodes/README.md | 26 +++ .../minimum-distance-between-bst-nodes.cpp | 38 +++ minimum-falling-path-sum/README.md | 28 +++ .../minimum-falling-path-sum.cpp | 29 +++ minimum-height-trees/README.md | 46 ++++ .../README.md | 64 ++++++ .../README.md | 49 ++++ ...r-of-steps-to-make-two-strings-anagram.cpp | 16 ++ .../README.md | 28 +++ .../README.md | 61 +++++ ...rations-to-make-the-array-k-increasing.cpp | 25 ++ minimum-path-sum/README.md | 28 +++ minimum-path-sum/minimum-path-sum.cpp | 29 +++ minimum-size-subarray-sum/README.md | 33 +++ .../minimum-size-subarray-sum.cpp | 23 ++ .../README.md | 41 ++++ ...value-to-get-positive-step-by-step-sum.cpp | 12 + minimum-window-substring/README.md | 41 ++++ .../minimum-window-substring.cpp | 52 +++++ move-zeroes/README.md | 22 ++ move-zeroes/move-zeroes.cpp | 18 ++ multiply-strings/README.md | 21 ++ multiply-strings/multiply-strings.cpp | 23 ++ n-ary-tree-level-order-traversal/README.md | 29 +++ .../n-ary-tree-level-order-traversal.cpp | 18 ++ n-ary-tree-preorder-traversal/README.md | 33 +++ .../n-ary-tree-preorder-traversal.cpp | 41 ++++ n-th-tribonacci-number/README.md | 29 +++ .../n-th-tribonacci-number.cpp | 14 ++ nCr mod M _ Part 1 - GFG/README.md | 34 +++ .../n-cr-mod-m-part-1.cpp | 69 ++++++ next-greater-element-i/README.md | 40 ++++ .../next-greater-element-i.cpp | 51 ++++ next-greater-element-ii/README.md | 28 +++ .../next-greater-element-ii.cpp | 29 +++ next-permutation/README.md | 28 +++ next-permutation/next-permutation.cpp | 36 +++ number-of-1-bits/README.md | 40 ++++ number-of-islands/README.md | 37 +++ number-of-islands/number-of-islands.cpp | 33 +++ number-of-provinces/README.md | 33 +++ number-of-provinces/number-of-provinces.cpp | 37 +++ .../README.md | 43 ++++ odd-even-linked-list/README.md | 30 +++ odd-even-linked-list/odd-even-linked-list.cpp | 41 ++++ .../README.md | 30 +++ ...s-with-total-durations-divisible-by-60.cpp | 13 ++ palindrome-linked-list/README.md | 25 ++ .../palindrome-linked-list.cpp | 60 +++++ palindrome-partitioning-ii/README.md | 32 +++ partition-array-for-maximum-sum/README.md | 33 +++ .../partition-array-for-maximum-sum.cpp | 12 + .../README.md | 42 ++++ ...artition-array-into-disjoint-intervals.cpp | 16 ++ pascals-triangle-ii/README.md | 25 ++ pascals-triangle/README.md | 19 ++ pascals-triangle/pascals-triangle.cpp | 38 +++ patching-array/README.md | 39 ++++ patching-array/patching-array.cpp | 15 ++ path-sum-ii/README.md | 35 +++ path-sum-ii/path-sum-ii.cpp | 30 +++ path-sum/README.md | 32 +++ path-sum/path-sum.cpp | 23 ++ perfect-squares/README.md | 26 +++ perfect-squares/perfect-squares.cpp | 27 +++ permutations-ii/README.md | 26 +++ permutations-ii/permutations-ii.cpp | 21 ++ .../README.md | 44 ++++ ...ating-next-right-pointers-in-each-node.cpp | 34 +++ ...ting-next-right-pointers-in-each-node.java | 18 ++ power-of-four/README.md | 24 ++ power-of-four/power-of-four.cpp | 12 + power-of-three/README.md | 27 +++ power-of-three/power-of-three.cpp | 19 ++ power-of-two/README.md | 46 ++++ power-of-two/power-of-two.cpp | 18 ++ powx-n/README.md | 31 +++ powx-n/powx-n.cpp | 18 ++ product-of-array-except-self/README.md | 26 +++ .../product-of-array-except-self.cpp | 26 +++ product-of-the-last-k-numbers/README.md | 46 ++++ push-dominoes/README.md | 41 ++++ push-dominoes/push-dominoes.cpp | 37 +++ range-addition-ii/README.md | 35 +++ range-addition-ii/range-addition-ii.cpp | 10 + range-sum-of-bst/README.md | 27 +++ range-sum-of-bst/range-sum-of-bst.cpp | 32 +++ range-sum-query-2d-immutable/README.md | 42 ++++ .../range-sum-query-2d-immutable.cpp | 26 +++ range-sum-query-immutable/README.md | 39 ++++ rank-transform-of-a-matrix/README.md | 58 +++++ .../rank-transform-of-a-matrix.cpp | 124 ++++++++++ remove-boxes/README.md | 39 ++++ remove-duplicates-from-sorted-array/README.md | 51 ++++ .../remove-duplicates-from-sorted-array.cpp | 26 +++ remove-linked-list-elements/README.md | 30 +++ .../remove-linked-list-elements.cpp | 38 +++ remove-nth-node-from-end-of-list/README.md | 34 +++ .../remove-nth-node-from-end-of-list.cpp | 39 ++++ reorder-list/README.md | 33 +++ reverse-linked-list/README.md | 32 +++ reverse-linked-list/reverse-linked-list.cpp | 22 ++ reverse-nodes-in-k-group/README.md | 43 ++++ .../reverse-nodes-in-k-group.cpp | 25 ++ reverse-pairs/README.md | 20 ++ reverse-pairs/reverse-pairs.cpp | 130 +++++++++++ reverse-words-in-a-string-iii/README.md | 21 ++ robot-return-to-origin/README.md | 41 ++++ .../robot-return-to-origin.cpp | 16 ++ roman-to-integer/README.md | 65 ++++++ roman-to-integer/roman-to-integer.cpp | 28 +++ rotate-array/README.md | 39 ++++ rotate-array/rotate-array.cpp | 13 ++ rotate-image/README.md | 39 ++++ rotate-image/rotate-image.cpp | 26 +++ rotate-list/README.md | 24 ++ rotate-list/rotate-list.cpp | 53 +++++ rotated-digits/README.md | 20 ++ rotated-digits/rotated-digits.cpp | 20 ++ rotting-oranges/README.md | 43 ++++ rotting-oranges/rotting-oranges.cpp | 49 ++++ same-tree/README.md | 31 +++ same-tree/same-tree.cpp | 27 +++ search-a-2d-matrix-ii/README.md | 33 +++ .../search-a-2d-matrix-ii.cpp | 26 +++ search-a-2d-matrix/README.md | 30 +++ search-a-2d-matrix/search-a-2d-matrix.cpp | 36 +++ search-in-rotated-sorted-array/README.md | 30 +++ .../search-in-rotated-sorted-array.cpp | 33 +++ search-insert-position/README.md | 31 +++ .../search-insert-position.cpp | 6 + second-highest-salary/README.md | 20 ++ .../second-highest-salary.sql | 3 + set-matrix-zeroes/README.md | 36 +++ set-matrix-zeroes/set-matrix-zeroes.cpp | 35 +++ shuffle-an-array/README.md | 39 ++++ shuffle-an-array/shuffle-an-array.cpp | 22 ++ single-element-in-a-sorted-array/README.md | 22 ++ .../single-element-in-a-sorted-array.cpp | 58 +++++ single-number-iii/README.md | 33 +++ single-number-iii/single-number-iii.cpp | 33 +++ slowest-key/README.md | 48 ++++ slowest-key/slowest-key.cpp | 15 ++ smallest-integer-divisible-by-k/README.md | 35 +++ .../smallest-integer-divisible-by-k.cpp | 9 + sort-an-array/README.md | 18 ++ sort-an-array/sort-an-array.cpp | 8 + sort-characters-by-frequency/README.md | 37 +++ .../sort-characters-by-frequency.cpp | 12 + sort-colors/README.md | 32 +++ sort-colors/sort-colors.cpp | 32 +++ .../README.md | 49 ++++ spiral-matrix/README.md | 25 ++ spiral-matrix/spiral-matrix.cpp | 35 +++ sqrtx/README.md | 26 +++ sqrtx/sqrtx.cpp | 6 + squares-of-a-sorted-array/README.md | 28 +++ .../squares-of-a-sorted-array.cpp | 13 ++ stone-game/README.md | 31 +++ stone-game/stone-game.cpp | 10 + subsets/README.md | 26 +++ subsets/subsets.cpp | 35 +++ sum-of-left-leaves/README.md | 24 ++ sum-of-left-leaves/sum-of-left-leaves.cpp | 28 +++ .../README.md | 21 ++ ...-of-nodes-with-even-valued-grandparent.cpp | 16 ++ sum-of-square-numbers/README.md | 41 ++++ .../sum-of-square-numbers.cpp | 20 ++ sum-root-to-leaf-numbers/README.md | 43 ++++ surrounded-regions/README.md | 28 +++ surrounded-regions/surrounded-regions.cpp | 42 ++++ symmetric-tree/README.md | 25 ++ three-equal-parts/README.md | 34 +++ three-equal-parts/three-equal-parts.cpp | 19 ++ total-hamming-distance/README.md | 30 +++ trapping-rain-water/README.md | 25 ++ trapping-rain-water/trapping-rain-water.cpp | 32 +++ triangle/README.md | 35 +++ trim-a-binary-search-tree/README.md | 46 ++++ .../trim-a-binary-search-tree.cpp | 11 + two-sum-ii-input-array-is-sorted/README.md | 39 ++++ .../two-sum-ii-input-array-is-sorted.cpp | 18 ++ two-sum-iv-input-is-a-bst/README.md | 43 ++++ .../two-sum-iv-input-is-a-bst.cpp | 12 + two-sum/README.md | 38 +++ two-sum/two-sum.cpp | 22 ++ ugly-number-ii/README.md | 26 +++ ugly-number-ii/ugly-number-ii.cpp | 15 ++ unique-binary-search-trees-ii/README.md | 22 ++ unique-binary-search-trees/README.md | 22 ++ .../unique-binary-search-trees.cpp | 21 ++ unique-paths-ii/README.md | 35 +++ unique-paths-iii/README.md | 52 +++++ unique-paths-iii/unique-paths-iii.cpp | 35 +++ unique-paths/README.md | 44 ++++ unique-paths/unique-paths.cpp | 12 + valid-palindrome/README.md | 25 ++ valid-palindrome/valid-palindrome.cpp | 17 ++ valid-parentheses/README.md | 48 ++++ valid-parentheses/valid-parentheses.cpp | 53 +++++ valid-sudoku/README.md | 56 +++++ valid-sudoku/valid-sudoku.cpp | 20 ++ valid-triangle-number/README.md | 27 +++ .../valid-triangle-number.cpp | 21 ++ validate-binary-search-tree/README.md | 32 +++ .../validate-binary-search-tree.cpp | 43 ++++ .../README.md | 35 +++ ...reorder-serialization-of-a-binary-tree.cpp | 16 ++ walking-robot-simulation-ii/README.md | 55 +++++ .../walking-robot-simulation-ii.cpp | 28 +++ wiggle-subsequence/README.md | 44 ++++ wiggle-subsequence/wiggle-subsequence.cpp | 15 ++ wildcard-matching/README.md | 40 ++++ word-break/README.md | 37 +++ word-break/word-break.cpp | 16 ++ word-ladder/README.md | 38 +++ word-search/README.md | 37 +++ xor-queries-of-a-subarray/README.md | 35 +++ 1267 files changed, 40117 insertions(+) create mode 100644 01-matrix/README.md create mode 100644 1's Complement - GFG/1s-complement.cpp create mode 100644 1's Complement - GFG/README.md create mode 100644 1-two-sum/1-two-sum.cpp create mode 100644 1-two-sum/NOTES.md create mode 100644 1-two-sum/README.md create mode 100644 100-same-tree/NOTES.md create mode 100644 100-same-tree/README.md create mode 100644 1009-complement-of-base-10-integer/1009-complement-of-base-10-integer.cpp create mode 100644 1009-complement-of-base-10-integer/NOTES.md create mode 100644 1009-complement-of-base-10-integer/README.md create mode 100644 1010-pairs-of-songs-with-total-durations-divisible-by-60/1010-pairs-of-songs-with-total-durations-divisible-by-60.cpp create mode 100644 1010-pairs-of-songs-with-total-durations-divisible-by-60/NOTES.md create mode 100644 1010-pairs-of-songs-with-total-durations-divisible-by-60/README.md create mode 100644 1011-capacity-to-ship-packages-within-d-days/1011-capacity-to-ship-packages-within-d-days.cpp create mode 100644 1011-capacity-to-ship-packages-within-d-days/NOTES.md create mode 100644 1011-capacity-to-ship-packages-within-d-days/README.md create mode 100644 102-binary-tree-level-order-traversal/102-binary-tree-level-order-traversal.cpp create mode 100644 102-binary-tree-level-order-traversal/NOTES.md create mode 100644 102-binary-tree-level-order-traversal/README.md create mode 100644 1022-sum-of-root-to-leaf-binary-numbers/1022-sum-of-root-to-leaf-binary-numbers.cpp create mode 100644 1022-sum-of-root-to-leaf-binary-numbers/NOTES.md create mode 100644 1022-sum-of-root-to-leaf-binary-numbers/README.md create mode 100644 1029-two-city-scheduling/1029-two-city-scheduling.cpp create mode 100644 1029-two-city-scheduling/NOTES.md create mode 100644 1029-two-city-scheduling/README.md create mode 100644 103-binary-tree-zigzag-level-order-traversal/NOTES.md create mode 100644 103-binary-tree-zigzag-level-order-traversal/README.md create mode 100644 104-maximum-depth-of-binary-tree/104-maximum-depth-of-binary-tree.cpp create mode 100644 104-maximum-depth-of-binary-tree/NOTES.md create mode 100644 104-maximum-depth-of-binary-tree/README.md create mode 100644 1041-robot-bounded-in-circle/1041-robot-bounded-in-circle.cpp create mode 100644 1041-robot-bounded-in-circle/NOTES.md create mode 100644 1041-robot-bounded-in-circle/README.md create mode 100644 1049-last-stone-weight-ii/1049-last-stone-weight-ii.cpp create mode 100644 1049-last-stone-weight-ii/NOTES.md create mode 100644 1049-last-stone-weight-ii/README.md create mode 100644 105-construct-binary-tree-from-preorder-and-inorder-traversal/105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp create mode 100644 105-construct-binary-tree-from-preorder-and-inorder-traversal/NOTES.md create mode 100644 105-construct-binary-tree-from-preorder-and-inorder-traversal/README.md create mode 100644 108-convert-sorted-array-to-binary-search-tree/108-convert-sorted-array-to-binary-search-tree.cpp create mode 100644 108-convert-sorted-array-to-binary-search-tree/NOTES.md create mode 100644 108-convert-sorted-array-to-binary-search-tree/README.md create mode 100644 1094-car-pooling/1094-car-pooling.cpp create mode 100644 1094-car-pooling/NOTES.md create mode 100644 1094-car-pooling/README.md create mode 100644 11-container-with-most-water/11-container-with-most-water.cpp create mode 100644 11-container-with-most-water/NOTES.md create mode 100644 11-container-with-most-water/README.md create mode 100644 110-balanced-binary-tree/110-balanced-binary-tree.cpp create mode 100644 110-balanced-binary-tree/NOTES.md create mode 100644 110-balanced-binary-tree/README.md create mode 100644 1111-maximum-nesting-depth-of-two-valid-parentheses-strings/NOTES.md create mode 100644 1111-maximum-nesting-depth-of-two-valid-parentheses-strings/README.md create mode 100644 114-flatten-binary-tree-to-linked-list/114-flatten-binary-tree-to-linked-list.cpp create mode 100644 114-flatten-binary-tree-to-linked-list/NOTES.md create mode 100644 114-flatten-binary-tree-to-linked-list/README.md create mode 100644 115-distinct-subsequences/115-distinct-subsequences.cpp create mode 100644 115-distinct-subsequences/NOTES.md create mode 100644 115-distinct-subsequences/README.md create mode 100644 116-populating-next-right-pointers-in-each-node/NOTES.md create mode 100644 116-populating-next-right-pointers-in-each-node/README.md create mode 100644 118-pascals-triangle/NOTES.md create mode 100644 118-pascals-triangle/README.md create mode 100644 120-triangle/120-triangle.cpp create mode 100644 120-triangle/NOTES.md create mode 100644 120-triangle/README.md create mode 100644 121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.cpp create mode 100644 121-best-time-to-buy-and-sell-stock/NOTES.md create mode 100644 121-best-time-to-buy-and-sell-stock/README.md create mode 100644 122-best-time-to-buy-and-sell-stock-ii/122-best-time-to-buy-and-sell-stock-ii.cpp create mode 100644 122-best-time-to-buy-and-sell-stock-ii/NOTES.md create mode 100644 122-best-time-to-buy-and-sell-stock-ii/README.md create mode 100644 1220-count-vowels-permutation/1220-count-vowels-permutation.cpp create mode 100644 1220-count-vowels-permutation/NOTES.md create mode 100644 1220-count-vowels-permutation/README.md create mode 100644 123-best-time-to-buy-and-sell-stock-iii/123-best-time-to-buy-and-sell-stock-iii.cpp create mode 100644 123-best-time-to-buy-and-sell-stock-iii/NOTES.md create mode 100644 123-best-time-to-buy-and-sell-stock-iii/README.md create mode 100644 1249-minimum-remove-to-make-valid-parentheses/1249-minimum-remove-to-make-valid-parentheses.cpp create mode 100644 1249-minimum-remove-to-make-valid-parentheses/README.md create mode 100644 126-word-ladder-ii/126-word-ladder-ii.cpp create mode 100644 126-word-ladder-ii/NOTES.md create mode 100644 126-word-ladder-ii/README.md create mode 100644 127-word-ladder/127-word-ladder.cpp create mode 100644 127-word-ladder/NOTES.md create mode 100644 127-word-ladder/README.md create mode 100644 1283-find-the-smallest-divisor-given-a-threshold/1283-find-the-smallest-divisor-given-a-threshold.cpp create mode 100644 1283-find-the-smallest-divisor-given-a-threshold/NOTES.md create mode 100644 1283-find-the-smallest-divisor-given-a-threshold/README.md create mode 100644 1288-remove-covered-intervals/1288-remove-covered-intervals.cpp create mode 100644 1288-remove-covered-intervals/NOTES.md create mode 100644 1288-remove-covered-intervals/README.md create mode 100644 1291-sequential-digits/1291-sequential-digits.cpp create mode 100644 1291-sequential-digits/NOTES.md create mode 100644 1291-sequential-digits/README.md create mode 100644 13-Roman-to-Integer/13-roman-to-integer.cpp create mode 100644 13-Roman-to-Integer/NOTES.md create mode 100644 1305-all-elements-in-two-binary-search-trees/1305-all-elements-in-two-binary-search-trees.cpp create mode 100644 1305-all-elements-in-two-binary-search-trees/NOTES.md create mode 100644 1305-all-elements-in-two-binary-search-trees/README.md create mode 100644 131-palindrome-partitioning/131-palindrome-partitioning.cpp create mode 100644 131-palindrome-partitioning/NOTES.md create mode 100644 131-palindrome-partitioning/README.md create mode 100644 133-clone-graph/NOTES.md create mode 100644 133-clone-graph/README.md create mode 100644 1337-the-k-weakest-rows-in-a-matrix/1337-the-k-weakest-rows-in-a-matrix.cpp create mode 100644 1337-the-k-weakest-rows-in-a-matrix/NOTES.md create mode 100644 1337-the-k-weakest-rows-in-a-matrix/README.md create mode 100644 134-gas-station/NOTES.md create mode 100644 134-gas-station/README.md create mode 100644 1359-count-all-valid-pickup-and-delivery-options/1359-count-all-valid-pickup-and-delivery-options.cpp create mode 100644 1359-count-all-valid-pickup-and-delivery-options/README.md create mode 100644 136-single-number/136-single-number.cpp create mode 100644 136-single-number/README.md create mode 100644 138-copy-list-with-random-pointer/138-copy-list-with-random-pointer.cpp create mode 100644 138-copy-list-with-random-pointer/NOTES.md create mode 100644 138-copy-list-with-random-pointer/README.md create mode 100644 1381-design-a-stack-with-increment-operation/NOTES.md create mode 100644 1381-design-a-stack-with-increment-operation/README.md create mode 100644 139-word-break/README.md create mode 100644 141-linked-list-cycle/141-linked-list-cycle.cpp create mode 100644 141-linked-list-cycle/NOTES.md create mode 100644 141-linked-list-cycle/README.md create mode 100644 142-linked-list-cycle-ii/142-linked-list-cycle-ii.cpp create mode 100644 142-linked-list-cycle-ii/NOTES.md create mode 100644 142-linked-list-cycle-ii/README.md create mode 100644 1423-maximum-points-you-can-obtain-from-cards/1423-maximum-points-you-can-obtain-from-cards.cpp create mode 100644 1423-maximum-points-you-can-obtain-from-cards/NOTES.md create mode 100644 1423-maximum-points-you-can-obtain-from-cards/README.md create mode 100644 144-binary-tree-preorder-traversal/NOTES.md create mode 100644 144-binary-tree-preorder-traversal/README.md create mode 100644 146-lru-cache/146-lru-cache.cpp create mode 100644 146-lru-cache/NOTES.md create mode 100644 146-lru-cache/README.md create mode 100644 1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.cpp create mode 100644 1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/NOTES.md create mode 100644 1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/README.md create mode 100644 1472-design-browser-history/1472-design-browser-history.cpp create mode 100644 1472-design-browser-history/NOTES.md create mode 100644 1472-design-browser-history/README.md create mode 100644 148-sort-list/148-sort-list.cpp create mode 100644 148-sort-list/NOTES.md create mode 100644 148-sort-list/README.md create mode 100644 1510-stone-game-iv/1510-stone-game-iv.cpp create mode 100644 1510-stone-game-iv/NOTES.md create mode 100644 1510-stone-game-iv/README.md create mode 100644 153-find-minimum-in-rotated-sorted-array/153-find-minimum-in-rotated-sorted-array.cpp create mode 100644 153-find-minimum-in-rotated-sorted-array/NOTES.md create mode 100644 153-find-minimum-in-rotated-sorted-array/README.md create mode 100644 154-find-minimum-in-rotated-sorted-array-ii/154-find-minimum-in-rotated-sorted-array-ii.cpp create mode 100644 154-find-minimum-in-rotated-sorted-array-ii/NOTES.md create mode 100644 154-find-minimum-in-rotated-sorted-array-ii/README.md create mode 100644 155-min-stack/155-min-stack.cpp create mode 100644 155-min-stack/NOTES.md create mode 100644 155-min-stack/README.md create mode 100644 1552-magnetic-force-between-two-balls/1552-magnetic-force-between-two-balls.cpp create mode 100644 1552-magnetic-force-between-two-balls/NOTES.md create mode 100644 1552-magnetic-force-between-two-balls/README.md create mode 100644 16-3sum-closest/16-3sum-closest.cpp create mode 100644 16-3sum-closest/NOTES.md create mode 100644 160-intersection-of-two-linked-lists/160-intersection-of-two-linked-lists.cpp create mode 100644 160-intersection-of-two-linked-lists/README.md create mode 100644 162-find-peak-element/162-find-peak-element.cpp create mode 100644 162-find-peak-element/NOTES.md create mode 100644 162-find-peak-element/README.md create mode 100644 165-compare-version-numbers/README.md create mode 100644 1672-richest-customer-wealth/1672-richest-customer-wealth.cpp create mode 100644 1672-richest-customer-wealth/NOTES.md create mode 100644 1672-richest-customer-wealth/README.md create mode 100644 1675-minimize-deviation-in-array/NOTES.md create mode 100644 1675-minimize-deviation-in-array/README.md create mode 100644 169-majority-element/169-majority-element.cpp create mode 100644 169-majority-element/NOTES.md create mode 100644 169-majority-element/README.md create mode 100644 171-excel-sheet-column-number/171-excel-sheet-column-number.cpp create mode 100644 171-excel-sheet-column-number/NOTES.md create mode 100644 171-excel-sheet-column-number/README.md create mode 100644 1760-minimum-limit-of-balls-in-a-bag/1760-minimum-limit-of-balls-in-a-bag.cpp create mode 100644 1760-minimum-limit-of-balls-in-a-bag/NOTES.md create mode 100644 1760-minimum-limit-of-balls-in-a-bag/README.md create mode 100644 179-largest-number/179-largest-number.cpp create mode 100644 179-largest-number/NOTES.md create mode 100644 179-largest-number/README.md create mode 100644 18-4sum/18-4sum.cpp create mode 100644 18-4sum/NOTES.md create mode 100644 18-4sum/README.md create mode 100644 1823-find-the-winner-of-the-circular-game/1823-find-the-winner-of-the-circular-game.cpp create mode 100644 1823-find-the-winner-of-the-circular-game/NOTES.md create mode 100644 1823-find-the-winner-of-the-circular-game/README.md create mode 100644 189-rotate-array/NOTES.md create mode 100644 189-rotate-array/README.md create mode 100644 2-add-two-numbers/2-add-two-numbers.cpp create mode 100644 2-add-two-numbers/NOTES.md create mode 100644 2-add-two-numbers/README.md create mode 100644 20-valid-parentheses/20-valid-parentheses.cpp create mode 100644 20-valid-parentheses/NOTES.md create mode 100644 20-valid-parentheses/README.md create mode 100644 203-remove-linked-list-elements/203-remove-linked-list-elements.cpp create mode 100644 203-remove-linked-list-elements/NOTES.md create mode 100644 203-remove-linked-list-elements/README.md create mode 100644 206-reverse-linked-list/206-reverse-linked-list.cpp create mode 100644 206-reverse-linked-list/NOTES.md create mode 100644 206-reverse-linked-list/README.md create mode 100644 209-minimum-size-subarray-sum/209-minimum-size-subarray-sum.cpp create mode 100644 209-minimum-size-subarray-sum/NOTES.md create mode 100644 209-minimum-size-subarray-sum/README.md create mode 100644 21-merge-two-sorted-lists/21-merge-two-sorted-lists.cpp create mode 100644 21-merge-two-sorted-lists/NOTES.md create mode 100644 21-merge-two-sorted-lists/README.md create mode 100644 2145-count-the-hidden-sequences/2145-count-the-hidden-sequences.cpp create mode 100644 2145-count-the-hidden-sequences/NOTES.md create mode 100644 2145-count-the-hidden-sequences/README.md create mode 100644 2202-maximize-the-topmost-element-after-k-moves/NOTES.md create mode 100644 2202-maximize-the-topmost-element-after-k-moves/README.md create mode 100644 2207-maximize-number-of-subsequences-in-a-string/2207-maximize-number-of-subsequences-in-a-string.cpp create mode 100644 2207-maximize-number-of-subsequences-in-a-string/NOTES.md create mode 100644 2207-maximize-number-of-subsequences-in-a-string/README.md create mode 100644 221-maximal-square/NOTES.md create mode 100644 221-maximal-square/README.md create mode 100644 225-implement-stack-using-queues/225-implement-stack-using-queues.cpp create mode 100644 225-implement-stack-using-queues/NOTES.md create mode 100644 225-implement-stack-using-queues/README.md create mode 100644 229-majority-element-ii/229-majority-element-ii.cpp create mode 100644 229-majority-element-ii/NOTES.md create mode 100644 229-majority-element-ii/README.md create mode 100644 23-merge-k-sorted-lists/23-merge-k-sorted-lists.cpp create mode 100644 23-merge-k-sorted-lists/NOTES.md create mode 100644 23-merge-k-sorted-lists/README.md create mode 100644 231-power-of-two/231-power-of-two.cpp create mode 100644 231-power-of-two/NOTES.md create mode 100644 231-power-of-two/README.md create mode 100644 232-implement-queue-using-stacks/232-implement-queue-using-stacks.cpp create mode 100644 232-implement-queue-using-stacks/NOTES.md create mode 100644 232-implement-queue-using-stacks/README.md create mode 100644 234-palindrome-linked-list/234-palindrome-linked-list.cpp create mode 100644 234-palindrome-linked-list/NOTES.md create mode 100644 236-lowest-common-ancestor-of-a-binary-tree/236-lowest-common-ancestor-of-a-binary-tree.cpp create mode 100644 236-lowest-common-ancestor-of-a-binary-tree/NOTES.md create mode 100644 236-lowest-common-ancestor-of-a-binary-tree/README.md create mode 100644 237-delete-node-in-a-linked-list/237-delete-node-in-a-linked-list.cpp create mode 100644 237-delete-node-in-a-linked-list/NOTES.md create mode 100644 237-delete-node-in-a-linked-list/README.md create mode 100644 238-product-of-array-except-self/238-product-of-array-except-self.cpp create mode 100644 238-product-of-array-except-self/NOTES.md create mode 100644 238-product-of-array-except-self/README.md create mode 100644 239-sliding-window-maximum/NOTES.md create mode 100644 239-sliding-window-maximum/README.md create mode 100644 24-swap-nodes-in-pairs/24-swap-nodes-in-pairs.cpp create mode 100644 24-swap-nodes-in-pairs/NOTES.md create mode 100644 24-swap-nodes-in-pairs/README.md create mode 100644 242-valid-anagram/242-valid-anagram.cpp create mode 100644 242-valid-anagram/NOTES.md create mode 100644 242-valid-anagram/README.md create mode 100644 25-reverse-nodes-in-k-group/NOTES.md create mode 100644 25-reverse-nodes-in-k-group/README.md create mode 100644 258-add-digits/258-add-digits.cpp create mode 100644 258-add-digits/NOTES.md create mode 100644 258-add-digits/README.md create mode 100644 26-remove-duplicates-from-sorted-array/NOTES.md create mode 100644 26-remove-duplicates-from-sorted-array/README.md create mode 100644 283-move-zeroes/283-move-zeroes.cpp create mode 100644 283-move-zeroes/NOTES.md create mode 100644 283-move-zeroes/README.md create mode 100644 287-find-the-duplicate-number/287-find-the-duplicate-number.cpp create mode 100644 287-find-the-duplicate-number/NOTES.md create mode 100644 287-find-the-duplicate-number/README.md create mode 100644 30-substring-with-concatenation-of-all-words/30-substring-with-concatenation-of-all-words.cpp create mode 100644 30-substring-with-concatenation-of-all-words/NOTES.md create mode 100644 30-substring-with-concatenation-of-all-words/README.md create mode 100644 300-longest-increasing-subsequence/NOTES.md create mode 100644 307-range-sum-query-mutable/NOTES.md create mode 100644 307-range-sum-query-mutable/README.md create mode 100644 31-next-permutation/31-next-permutation.cpp create mode 100644 31-next-permutation/NOTES.md create mode 100644 316-remove-duplicate-letters/316-remove-duplicate-letters.cpp create mode 100644 316-remove-duplicate-letters/NOTES.md create mode 100644 316-remove-duplicate-letters/README.md create mode 100644 326-power-of-three/326-power-of-three.cpp create mode 100644 326-power-of-three/NOTES.md create mode 100644 326-power-of-three/README.md create mode 100644 33-search-in-rotated-sorted-array/33-search-in-rotated-sorted-array.cpp create mode 100644 33-search-in-rotated-sorted-array/NOTES.md create mode 100644 33-search-in-rotated-sorted-array/README.md create mode 100644 34-find-first-and-last-position-of-element-in-sorted-array/34-find-first-and-last-position-of-element-in-sorted-array.cpp create mode 100644 34-find-first-and-last-position-of-element-in-sorted-array/README.md create mode 100644 342-power-of-four/342-power-of-four.cpp create mode 100644 342-power-of-four/NOTES.md create mode 100644 342-power-of-four/README.md create mode 100644 344-reverse-string/NOTES.md create mode 100644 344-reverse-string/README.md create mode 100644 345-reverse-vowels-of-a-string/345-reverse-vowels-of-a-string.cpp create mode 100644 345-reverse-vowels-of-a-string/NOTES.md create mode 100644 345-reverse-vowels-of-a-string/README.md create mode 100644 347-top-k-frequent-elements/347-top-k-frequent-elements.cpp create mode 100644 347-top-k-frequent-elements/NOTES.md create mode 100644 347-top-k-frequent-elements/README.md create mode 100644 35-search-insert-position/35-search-insert-position.cpp create mode 100644 35-search-insert-position/NOTES.md create mode 100644 35-search-insert-position/README.md create mode 100644 37-sudoku-solver/NOTES.md create mode 100644 37-sudoku-solver/README.md create mode 100644 38-count-and-say/38-count-and-say.cpp create mode 100644 38-count-and-say/NOTES.md create mode 100644 38-count-and-say/README.md create mode 100644 382-linked-list-random-node/382-linked-list-random-node.cpp create mode 100644 382-linked-list-random-node/NOTES.md create mode 100644 382-linked-list-random-node/README.md create mode 100644 389-find-the-difference/389-find-the-difference.cpp create mode 100644 389-find-the-difference/NOTES.md create mode 100644 39-combination-sum/39-combination-sum.cpp create mode 100644 39-combination-sum/NOTES.md create mode 100644 39-combination-sum/README.md create mode 100644 394-decode-string/NOTES.md create mode 100644 394-decode-string/README.md create mode 100644 397-integer-replacement/397-integer-replacement.cpp create mode 100644 397-integer-replacement/NOTES.md create mode 100644 397-integer-replacement/README.md create mode 100644 3sum-closest/3sum-closest.cpp create mode 100644 3sum-closest/README.md create mode 100644 3sum/3sum.cpp create mode 100644 3sum/README.md create mode 100644 4-median-of-two-sorted-arrays/4-median-of-two-sorted-arrays.cpp create mode 100644 4-median-of-two-sorted-arrays/NOTES.md create mode 100644 4-median-of-two-sorted-arrays/README.md create mode 100644 40-combination-sum-ii/40-combination-sum-ii.cpp create mode 100644 40-combination-sum-ii/NOTES.md create mode 100644 40-combination-sum-ii/README.md create mode 100644 402-remove-k-digits/402-remove-k-digits.cpp create mode 100644 402-remove-k-digits/NOTES.md create mode 100644 402-remove-k-digits/README.md create mode 100644 410-split-array-largest-sum/410-split-array-largest-sum.cpp create mode 100644 410-split-array-largest-sum/NOTES.md create mode 100644 410-split-array-largest-sum/README.md create mode 100644 415-add-strings/NOTES.md create mode 100644 415-add-strings/README.md create mode 100644 416-partition-equal-subset-sum/416-partition-equal-subset-sum.cpp create mode 100644 416-partition-equal-subset-sum/NOTES.md create mode 100644 416-partition-equal-subset-sum/README.md create mode 100644 42-trapping-rain-water/42-trapping-rain-water.cpp create mode 100644 42-trapping-rain-water/NOTES.md create mode 100644 421-maximum-xor-of-two-numbers-in-an-array/421-maximum-xor-of-two-numbers-in-an-array.cpp create mode 100644 421-maximum-xor-of-two-numbers-in-an-array/NOTES.md create mode 100644 438-find-all-anagrams-in-a-string/438-find-all-anagrams-in-a-string.cpp create mode 100644 438-find-all-anagrams-in-a-string/NOTES.md create mode 100644 438-find-all-anagrams-in-a-string/README.md create mode 100644 442-find-all-duplicates-in-an-array/442-find-all-duplicates-in-an-array.cpp create mode 100644 442-find-all-duplicates-in-an-array/NOTES.md create mode 100644 442-find-all-duplicates-in-an-array/README.md create mode 100644 45-jump-game-ii/45-jump-game-ii.cpp create mode 100644 45-jump-game-ii/NOTES.md create mode 100644 45-jump-game-ii/README.md create mode 100644 454-4sum-ii/454-4sum-ii.cpp create mode 100644 454-4sum-ii/NOTES.md create mode 100644 454-4sum-ii/README.md create mode 100644 458-poor-pigs/NOTES.md create mode 100644 458-poor-pigs/README.md create mode 100644 46-permutations/46-permutations.cpp create mode 100644 46-permutations/NOTES.md create mode 100644 46-permutations/README.md create mode 100644 472-concatenated-words/472-concatenated-words.cpp create mode 100644 472-concatenated-words/NOTES.md create mode 100644 472-concatenated-words/README.md create mode 100644 48-rotate-image/48-rotate-image.cpp create mode 100644 48-rotate-image/NOTES.md create mode 100644 48-rotate-image/README.md create mode 100644 485-max-consecutive-ones/485-max-consecutive-ones.cpp create mode 100644 485-max-consecutive-ones/README.md create mode 100644 49-group-anagrams/49-group-anagrams.cpp create mode 100644 49-group-anagrams/NOTES.md create mode 100644 49-group-anagrams/README.md create mode 100644 494-target-sum/494-target-sum.cpp create mode 100644 494-target-sum/NOTES.md create mode 100644 494-target-sum/README.md create mode 100644 496-next-greater-element-i/496-next-greater-element-i.cpp create mode 100644 496-next-greater-element-i/NOTES.md create mode 100644 496-next-greater-element-i/README.md create mode 100644 4sum-ii/4sum-ii.cpp create mode 100644 4sum-ii/README.md create mode 100644 4sum/4sum.cpp create mode 100644 4sum/README.md create mode 100644 50-powx-n/50-powx-n.cpp create mode 100644 50-powx-n/NOTES.md create mode 100644 50-powx-n/README.md create mode 100644 503-next-greater-element-ii/503-next-greater-element-ii.cpp create mode 100644 503-next-greater-element-ii/NOTES.md create mode 100644 503-next-greater-element-ii/README.md create mode 100644 509-fibonacci-number/509-fibonacci-number.cpp create mode 100644 509-fibonacci-number/NOTES.md create mode 100644 509-fibonacci-number/README.md create mode 100644 51-n-queens/51-n-queens.cpp create mode 100644 51-n-queens/NOTES.md create mode 100644 51-n-queens/README.md create mode 100644 52-n-queens-ii/52-n-queens-ii.cpp create mode 100644 52-n-queens-ii/NOTES.md create mode 100644 52-n-queens-ii/README.md create mode 100644 520-detect-capital/520-detect-capital.cpp create mode 100644 520-detect-capital/NOTES.md create mode 100644 520-detect-capital/README.md create mode 100644 525-contiguous-array/525-contiguous-array.cpp create mode 100644 525-contiguous-array/NOTES.md create mode 100644 525-contiguous-array/README.md create mode 100644 53-maximum-subarray/53-maximum-subarray.cpp create mode 100644 53-maximum-subarray/NOTES.md create mode 100644 53-maximum-subarray/README.md create mode 100644 532-k-diff-pairs-in-an-array/532-k-diff-pairs-in-an-array.cpp create mode 100644 532-k-diff-pairs-in-an-array/NOTES.md create mode 100644 532-k-diff-pairs-in-an-array/README.md create mode 100644 54-spiral-matrix/54-spiral-matrix.cpp create mode 100644 54-spiral-matrix/NOTES.md create mode 100644 54-spiral-matrix/README.md create mode 100644 540-single-element-in-a-sorted-array/540-single-element-in-a-sorted-array.cpp create mode 100644 540-single-element-in-a-sorted-array/NOTES.md create mode 100644 540-single-element-in-a-sorted-array/README.md create mode 100644 543-diameter-of-binary-tree/NOTES.md create mode 100644 543-diameter-of-binary-tree/README.md create mode 100644 55-jump-game/55-jump-game.cpp create mode 100644 55-jump-game/NOTES.md create mode 100644 55-jump-game/README.md create mode 100644 556-next-greater-element-iii/556-next-greater-element-iii.cpp create mode 100644 556-next-greater-element-iii/NOTES.md create mode 100644 556-next-greater-element-iii/README.md create mode 100644 560-subarray-sum-equals-k/560-subarray-sum-equals-k.cpp create mode 100644 567-permutation-in-string/NOTES.md create mode 100644 567-permutation-in-string/README.md create mode 100644 576-out-of-boundary-paths/576-out-of-boundary-paths.cpp create mode 100644 576-out-of-boundary-paths/README.md create mode 100644 60-permutation-sequence/60-permutation-sequence.cpp create mode 100644 60-permutation-sequence/NOTES.md create mode 100644 60-permutation-sequence/README.md create mode 100644 605-can-place-flowers/605-can-place-flowers.cpp create mode 100644 605-can-place-flowers/NOTES.md create mode 100644 605-can-place-flowers/README.md create mode 100644 61-rotate-list/NOTES.md create mode 100644 61-rotate-list/README.md create mode 100644 62-unique-paths/NOTES.md create mode 100644 62-unique-paths/README.md create mode 100644 63-unique-paths-ii/NOTES.md create mode 100644 63-unique-paths-ii/README.md create mode 100644 64-minimum-path-sum/64-minimum-path-sum.cpp create mode 100644 64-minimum-path-sum/NOTES.md create mode 100644 64-minimum-path-sum/README.md create mode 100644 650-2-keys-keyboard/650-2-keys-keyboard.cpp create mode 100644 650-2-keys-keyboard/NOTES.md create mode 100644 650-2-keys-keyboard/README.md create mode 100644 66-plus-one/NOTES.md create mode 100644 662-maximum-width-of-binary-tree/662-maximum-width-of-binary-tree.cpp create mode 100644 662-maximum-width-of-binary-tree/NOTES.md create mode 100644 662-maximum-width-of-binary-tree/README.md create mode 100644 67-add-binary/NOTES.md create mode 100644 67-add-binary/README.md create mode 100644 673-number-of-longest-increasing-subsequence/NOTES.md create mode 100644 673-number-of-longest-increasing-subsequence/README.md create mode 100644 7 Segment Display - GFG/7-segment-display.cpp create mode 100644 7 Segment Display - GFG/README.md create mode 100644 70-climbing-stairs/NOTES.md create mode 100644 700-search-in-a-binary-search-tree/700-search-in-a-binary-search-tree.cpp create mode 100644 700-search-in-a-binary-search-tree/NOTES.md create mode 100644 700-search-in-a-binary-search-tree/README.md create mode 100644 701-insert-into-a-binary-search-tree/701-insert-into-a-binary-search-tree.cpp create mode 100644 701-insert-into-a-binary-search-tree/NOTES.md create mode 100644 701-insert-into-a-binary-search-tree/README.md create mode 100644 704-binary-search/704-binary-search.cpp create mode 100644 704-binary-search/NOTES.md create mode 100644 704-binary-search/README.md create mode 100644 71-simplify-path/71-simplify-path.cpp create mode 100644 71-simplify-path/NOTES.md create mode 100644 71-simplify-path/README.md create mode 100644 724-find-pivot-index/724-find-pivot-index.cpp create mode 100644 724-find-pivot-index/NOTES.md create mode 100644 724-find-pivot-index/README.md create mode 100644 74-search-a-2d-matrix/74-search-a-2d-matrix.cpp create mode 100644 74-search-a-2d-matrix/NOTES.md create mode 100644 74-search-a-2d-matrix/README.md create mode 100644 740-delete-and-earn/740-delete-and-earn.cpp create mode 100644 740-delete-and-earn/NOTES.md create mode 100644 740-delete-and-earn/README.md create mode 100644 746-min-cost-climbing-stairs/746-min-cost-climbing-stairs.cpp create mode 100644 75-sort-colors/75-sort-colors.cpp create mode 100644 75-sort-colors/NOTES.md create mode 100644 75-sort-colors/README.md create mode 100644 763-partition-labels/763-partition-labels.cpp create mode 100644 763-partition-labels/NOTES.md create mode 100644 763-partition-labels/README.md create mode 100644 78-subsets/78-subsets.cpp create mode 100644 78-subsets/NOTES.md create mode 100644 78-subsets/README.md create mode 100644 79-word-search/79-word-search.cpp create mode 100644 79-word-search/NOTES.md create mode 100644 79-word-search/README.md create mode 100644 8-string-to-integer-atoi/8-string-to-integer-atoi.cpp create mode 100644 8-string-to-integer-atoi/NOTES.md create mode 100644 8-string-to-integer-atoi/README.md create mode 100644 80-remove-duplicates-from-sorted-array-ii/80-remove-duplicates-from-sorted-array-ii.cpp create mode 100644 80-remove-duplicates-from-sorted-array-ii/NOTES.md create mode 100644 80-remove-duplicates-from-sorted-array-ii/README.md create mode 100644 804-unique-morse-code-words/NOTES.md create mode 100644 804-unique-morse-code-words/README.md create mode 100644 82-remove-duplicates-from-sorted-list-ii/82-remove-duplicates-from-sorted-list-ii.cpp create mode 100644 82-remove-duplicates-from-sorted-list-ii/NOTES.md create mode 100644 82-remove-duplicates-from-sorted-list-ii/README.md create mode 100644 823-binary-trees-with-factors/NOTES.md create mode 100644 823-binary-trees-with-factors/README.md create mode 100644 84-largest-rectangle-in-histogram/84-largest-rectangle-in-histogram.cpp create mode 100644 84-largest-rectangle-in-histogram/NOTES.md create mode 100644 84-largest-rectangle-in-histogram/README.md create mode 100644 847-shortest-path-visiting-all-nodes/NOTES.md create mode 100644 847-shortest-path-visiting-all-nodes/README.md create mode 100644 856-score-of-parentheses/856-score-of-parentheses.cpp create mode 100644 856-score-of-parentheses/NOTES.md create mode 100644 856-score-of-parentheses/README.md create mode 100644 858-mirror-reflection/NOTES.md create mode 100644 858-mirror-reflection/README.md create mode 100644 875-koko-eating-bananas/875-koko-eating-bananas.cpp create mode 100644 876-middle-of-the-linked-list/876-middle-of-the-linked-list.cpp create mode 100644 881-boats-to-save-people/881-boats-to-save-people.cpp create mode 100644 881-boats-to-save-people/NOTES.md create mode 100644 881-boats-to-save-people/README.md create mode 100644 890-find-and-replace-pattern/890-find-and-replace-pattern.cpp create mode 100644 890-find-and-replace-pattern/NOTES.md create mode 100644 890-find-and-replace-pattern/README.md create mode 100644 895-maximum-frequency-stack/895-maximum-frequency-stack.cpp create mode 100644 895-maximum-frequency-stack/NOTES.md create mode 100644 895-maximum-frequency-stack/README.md create mode 100644 90-subsets-ii/90-subsets-ii.cpp create mode 100644 90-subsets-ii/NOTES.md create mode 100644 90-subsets-ii/README.md create mode 100644 916-word-subsets/NOTES.md create mode 100644 916-word-subsets/README.md create mode 100644 921-minimum-add-to-make-parentheses-valid/NOTES.md create mode 100644 921-minimum-add-to-make-parentheses-valid/README.md create mode 100644 946-validate-stack-sequences/946-validate-stack-sequences.cpp create mode 100644 946-validate-stack-sequences/NOTES.md create mode 100644 946-validate-stack-sequences/README.md create mode 100644 977-squares-of-a-sorted-array/977-squares-of-a-sorted-array.cpp create mode 100644 977-squares-of-a-sorted-array/NOTES.md create mode 100644 977-squares-of-a-sorted-array/README.md create mode 100644 98-validate-binary-search-tree/98-validate-binary-search-tree.cpp create mode 100644 98-validate-binary-search-tree/NOTES.md create mode 100644 98-validate-binary-search-tree/README.md create mode 100644 981-time-based-key-value-store/981-time-based-key-value-store.cpp create mode 100644 983-minimum-cost-for-tickets/NOTES.md create mode 100644 983-minimum-cost-for-tickets/README.md create mode 100644 991-broken-calculator/991-broken-calculator.cpp create mode 100644 991-broken-calculator/NOTES.md create mode 100644 991-broken-calculator/README.md create mode 100644 994-rotting-oranges/994-rotting-oranges.cpp create mode 100644 994-rotting-oranges/NOTES.md create mode 100644 994-rotting-oranges/README.md create mode 100644 Add 1 to a number represented as linked list - GFG/README.md create mode 100644 Add 1 to a number represented as linked list - GFG/add-1-to-a-number-represented-as-linked-list.cpp create mode 100644 Allocate minimum number of pages - GFG/README.md create mode 100644 Allocate minimum number of pages - GFG/allocate-minimum-number-of-pages.cpp create mode 100644 Anagram of String - GFG/README.md create mode 100644 Anagram of String - GFG/anagram-of-string.cpp create mode 100644 Array to BST - GFG/README.md create mode 100644 Array to BST - GFG/array-to-bst.cpp create mode 100644 Biconnected Graph - GFG/README.md create mode 100644 Biconnected Graph - GFG/biconnected-graph.cpp create mode 100644 Binary Array Sorting - GFG/README.md create mode 100644 Binary Array Sorting - GFG/binary-array-sorting.cpp create mode 100644 Binary number to decimal number - GFG/README.md create mode 100644 Binary number to decimal number - GFG/binary-number-to-decimal-number.cpp create mode 100644 Bitwise AND of the Array - GFG/README.md create mode 100644 Bitwise AND of the Array - GFG/bitwise-and-of-the-array.cpp create mode 100644 Can Make Triangle - GFG/README.md create mode 100644 Can Make Triangle - GFG/can-make-triangle.cpp create mode 100644 Check Mirror in N-ary tree - GFG/README.md create mode 100644 Check Mirror in N-ary tree - GFG/check-mirror-in-nary-tree.cpp create mode 100644 Check if subtree - GFG/README.md create mode 100644 Check if subtree - GFG/check-if-subtree.cpp create mode 100644 Clone a stack without using extra space - GFG/README.md create mode 100644 Clone a stack without using extra space - GFG/clone-a-stack-without-using-extra-space.cpp create mode 100644 Clone a stack without usinig extra space - GFG/README.md create mode 100644 Clone a stack without usinig extra space - GFG/clone-a-stack-without-usinig-extra-space.cpp create mode 100644 Coins of Geekland - GFG/README.md create mode 100644 Coins of Geekland - GFG/coins-of-geekland.cpp create mode 100644 Compute Before Matrix - GFG/README.md create mode 100644 Compute Before Matrix - GFG/compute-before-matrix.cpp create mode 100644 Concatenate two numbers - GFG/README.md create mode 100644 Concatenate two numbers - GFG/concatenate-two-numbers.cpp create mode 100644 Corona Vaccine - GFG/README.md create mode 100644 Corona Vaccine - GFG/corona-vaccine.cpp create mode 100644 Counts Zeros Xor Pairs - GFG/README.md create mode 100644 Counts Zeros Xor Pairs - GFG/counts-zeros-xor-pairs.cpp create mode 100644 Cousins of a given node - GFG/README.md create mode 100644 Cousins of a given node - GFG/cousins-of-a-given-node.cpp create mode 100644 Cyclically rotate an array by one - GFG/README.md create mode 100644 Cyclically rotate an array by one - GFG/cyclically-rotate-an-array-by-one.cpp create mode 100644 Escape the Forbidden Forest - GFG/README.md create mode 100644 Escape the Forbidden Forest - GFG/escape-the-forbidden-forest.cpp create mode 100644 Even and Odd - GFG/README.md create mode 100644 Even and Odd - GFG/even-and-odd.cpp create mode 100644 Excel Sheet _ Part - 1 - GFG/README.md create mode 100644 Excel Sheet _ Part - 1 - GFG/excel-sheet-part-1.cpp create mode 100644 Find Missing And Repeating - GFG/README.md create mode 100644 Find Missing And Repeating - GFG/find-missing-and-repeating.cpp create mode 100644 Find Nth root of M - GFG/README.md create mode 100644 Find Nth root of M - GFG/find-nth-root-of-m.cpp create mode 100644 Find Prime numbers in a range - GFG/README.md create mode 100644 Find Prime numbers in a range - GFG/find-prime-numbers-in-a-range.cpp create mode 100644 Find position of set bit - GFG/README.md create mode 100644 Find position of set bit - GFG/find-position-of-set-bit.cpp create mode 100644 Find rectangle with corners as 1 - GFG/README.md create mode 100644 Find rectangle with corners as 1 - GFG/find-rectangle-with-corners-as-1.cpp create mode 100644 Find the Closest Element in BST - GFG/README.md create mode 100644 Find the Closest Element in BST - GFG/find-the-closest-element-in-bst.cpp create mode 100644 Find the Maximum Flow - GFG/README.md create mode 100644 Find the Maximum Flow - GFG/find-the-maximum-flow.cpp create mode 100644 Find the number of islands - GFG/README.md create mode 100644 Find the number of islands - GFG/find-the-number-of-islands.cpp create mode 100644 Form a palindrome - GFG/README.md create mode 100644 Form a palindrome - GFG/form-a-palindrome.cpp create mode 100644 Fraction Trouble - GFG/README.md create mode 100644 Fraction Trouble - GFG/fraction-trouble.cpp create mode 100644 Gadgets of Doraland - GFG/README.md create mode 100644 Gadgets of Doraland - GFG/gadgets-of-doraland.py create mode 100644 Handshakes - GFG/README.md create mode 100644 Handshakes - GFG/handshakes.cpp create mode 100644 Height Using Parent Array - GFG/README.md create mode 100644 Height Using Parent Array - GFG/height-using-parent-array.cpp create mode 100644 Help Classmates - GFG/README.md create mode 100644 Help Classmates - GFG/help-classmates.cpp create mode 100644 Hit most Balloons - GFG/README.md create mode 100644 Hit most Balloons - GFG/hit-most-balloons.cpp create mode 100644 Implement stack using array - GFG/README.md create mode 100644 Implement stack using array - GFG/implement-stack-using-array.cpp create mode 100644 Implementing Dijkstra Algorithm - GFG/README.md create mode 100644 Implementing Dijkstra Algorithm - GFG/implementing-dijkstra-algorithm.cpp create mode 100644 Insertion Sort for Singly Linked List - GFG/README.md create mode 100644 Insertion Sort for Singly Linked List - GFG/insertion-sort-for-singly-linked-list.cpp create mode 100644 K-th element of two sorted Arrays - GFG/README.md create mode 100644 K-th element of two sorted Arrays - GFG/kth-element-of-two-sorted-arrays.cpp create mode 100644 Kadane's Algorithm - GFG/README.md create mode 100644 Kadane's Algorithm - GFG/kadanes-algorithm.cpp create mode 100644 Kth smallest element - GFG/README.md create mode 100644 Kth smallest element - GFG/kth-smallest-element.cpp create mode 100644 Largest subarray with 0 sum - GFG/README.md create mode 100644 Largest subarray with 0 sum - GFG/largest-subarray-with-0-sum.cpp create mode 100644 Largest value in each level - GFG/README.md create mode 100644 Largest value in each level - GFG/largest-value-in-each-level.cpp create mode 100644 Leaves to DLL - GFG/README.md create mode 100644 Leaves to DLL - GFG/leaves-to-dll.cpp create mode 100644 Left View of Binary Tree - GFG/README.md create mode 100644 Left View of Binary Tree - GFG/left-view-of-binary-tree.cpp create mode 100644 Longest Common Prefix in an Array - GFG/README.md create mode 100644 Longest Common Prefix in an Array - GFG/longest-common-prefix-in-an-array.cpp create mode 100644 Longest substring to form a Palindrome - GFG/README.md create mode 100644 Longest substring to form a Palindrome - GFG/longest-substring-to-form-a-palindrome.cpp create mode 100644 M-Coloring Problem - GFG/README.md create mode 100644 M-Coloring Problem - GFG/mcoloring-problem.cpp create mode 100644 Matrix Operations - GFG/README.md create mode 100644 Matrix Operations - GFG/matrix-operations.cpp create mode 100644 Maximum Winning score - GFG/README.md create mode 100644 Maximum Winning score - GFG/maximum-winning-score.cpp create mode 100644 Maximum average subarray - GFG/README.md create mode 100644 Maximum average subarray - GFG/maximum-average-subarray.cpp create mode 100644 Maximum number of events that can be attended - GFG/maximum-number-of-events-that-can-be-attended.cpp create mode 100644 Maximum selections - GFG/README.md create mode 100644 Maximum selections - GFG/maximum-selections.cpp create mode 100644 Maximum sum of increasing order elements from n arrays - GFG/README.md create mode 100644 Maximum sum of increasing order elements from n arrays - GFG/maximum-sum-of-increasing-order-elements-from-n-arrays.cpp create mode 100644 Median in a row-wise sorted Matrix - GFG/README.md create mode 100644 Median in a row-wise sorted Matrix - GFG/median-in-a-rowwise-sorted-matrix.cpp create mode 100644 Merge K sorted linked lists - GFG/README.md create mode 100644 Merge K sorted linked lists - GFG/merge-k-sorted-linked-lists.cpp create mode 100644 Min Coin - GFG/README.md create mode 100644 Min Coin - GFG/min-coin.cpp create mode 100644 Minimum Swaps to Sort - GFG/README.md create mode 100644 Minimum Swaps to Sort - GFG/minimum-swaps-to-sort.cpp create mode 100644 Move all zeros to the front of the linked list - GFG/README.md create mode 100644 Move all zeros to the front of the linked list - GFG/move-all-zeros-to-the-front-of-the-linked-list.cpp create mode 100644 N Digit numbers with digits in increasing order - GFG/README.md create mode 100644 N Digit numbers with digits in increasing order - GFG/n-digit-numbers-with-digits-in-increasing-order.cpp create mode 100644 Negative weight cycle - GFG/README.md create mode 100644 Negative weight cycle - GFG/negative-weight-cycle.cpp create mode 100644 Next Permutation - GFG/README.md create mode 100644 Next Permutation - GFG/next-permutation.cpp create mode 100644 Nodes at even distance - GFG/README.md create mode 100644 Nodes at even distance - GFG/nodes-at-even-distance.cpp create mode 100644 Number of distinct Words with k maximum contiguous vowels - GFG/README.md create mode 100644 Number of distinct Words with k maximum contiguous vowels - GFG/number-of-distinct-words-with-k-maximum-contiguous-vowels.cpp create mode 100644 Optimal binary search tree - GFG/README.md create mode 100644 Optimal binary search tree - GFG/optimal-binary-search-tree.cpp create mode 100644 Partition Equal Subset Sum - GFG/README.md create mode 100644 Partition Equal Subset Sum - GFG/partition-equal-subset-sum.cpp create mode 100644 Positive Negative Pair - GFG/README.md create mode 100644 Positive Negative Pair - GFG/positive-negative-pair.cpp create mode 100644 Predecessor and Successor - GFG/README.md create mode 100644 Predecessor and Successor - GFG/predecessor-and-successor.cpp create mode 100644 Queries on Strings - GFG/README.md create mode 100644 Queries on Strings - GFG/queries-on-strings.cpp create mode 100644 Queue using two Stacks - GFG/README.md create mode 100644 Queue using two Stacks - GFG/queue-using-two-stacks.cpp create mode 100644 Rank The Permutations - GFG/README.md create mode 100644 Rank The Permutations - GFG/rank-the-permutations.cpp create mode 100644 Rat in a Maze Problem - I - GFG/README.md create mode 100644 Rat in a Maze Problem - I - GFG/rat-in-a-maze-problem-i.cpp create mode 100644 Rearrange Geek and his Classmates - GFG/README.md create mode 100644 Rearrange Geek and his Classmates - GFG/rearrange-geek-and-his-classmates.cpp create mode 100644 Remove leading zeros from an IP address - GFG/README.md create mode 100644 Remove leading zeros from an IP address - GFG/remove-leading-zeros-from-an-ip-address.cpp create mode 100644 Return two prime numbers - GFG/README.md create mode 100644 Return two prime numbers - GFG/return-two-prime-numbers.cpp create mode 100644 Reverse First K elements of Queue - GFG/README.md create mode 100644 Reverse First K elements of Queue - GFG/reverse-first-k-elements-of-queue.cpp create mode 100644 Reverse words in a given string - GFG/README.md create mode 100644 Reverse words in a given string - GFG/reverse-words-in-a-given-string.cpp create mode 100644 Rotate by 90 degree - GFG/README.md create mode 100644 Rotate by 90 degree - GFG/rotate-by-90-degree.cpp create mode 100644 Search Pattern (Z-algorithm) - GFG/README.md create mode 100644 Search Pattern (Z-algorithm) - GFG/search-pattern-zalgorithm.cpp create mode 100644 Search a node in BST - GFG/README.md create mode 100644 Search a node in BST - GFG/search-a-node-in-bst.cpp create mode 100644 Shortest Path between Cities - GFG/README.md create mode 100644 Shortest Path between Cities - GFG/shortest-path-between-cities.cpp create mode 100644 Shortest Unique prefix for every word - GFG/README.md create mode 100644 Shortest Unique prefix for every word - GFG/shortest-unique-prefix-for-every-word.cpp create mode 100644 Smallest Absolute Difference - GFG/README.md create mode 100644 Smallest Absolute Difference - GFG/smallest-absolute-difference.cpp create mode 100644 Smallest greater elements in whole array - GFG/README.md create mode 100644 Smallest greater elements in whole array - GFG/smallest-greater-elements-in-whole-array.cpp create mode 100644 Smallest window containing 0, 1 and 2 - GFG/README.md create mode 100644 Smallest window containing 0, 1 and 2 - GFG/smallest-window-containing-0-1-and-2.cpp create mode 100644 Sort a stack - GFG/README.md create mode 100644 Sort a stack - GFG/sort-a-stack.cpp create mode 100644 Sort an array of 0s, 1s and 2s - GFG/README.md create mode 100644 Sort an array of 0s, 1s and 2s - GFG/sort-an-array-of-0s-1s-and-2s.cpp create mode 100644 Sort by Set Bit Count - GFG/README.md create mode 100644 Sort by Set Bit Count - GFG/sort-by-set-bit-count.cpp create mode 100644 Special Matrix - GFG/README.md create mode 100644 Special Matrix - GFG/special-matrix.cpp create mode 100644 Spidey Sense - GFG/README.md create mode 100644 Spidey Sense - GFG/spidey-sense.cpp create mode 100644 Stack using two queues - GFG/README.md create mode 100644 Stack using two queues - GFG/stack-using-two-queues.cpp create mode 100644 Subset Sums - GFG/README.md create mode 100644 Subset Sums - GFG/subset-sums.cpp create mode 100644 Subsets - GFG/README.md create mode 100644 Subsets - GFG/subsets.cpp create mode 100644 Swap Kth nodes from ends - GFG/README.md create mode 100644 Swap Kth nodes from ends - GFG/swap-kth-nodes-from-ends.cpp create mode 100644 The Painter's Partition Problem-II - GFG/README.md create mode 100644 The Painter's Partition Problem-II - GFG/the-painters-partition-problem-ii.cpp create mode 100644 Transfiguration - GFG/README.md create mode 100644 Triangle and Square - GFG/README.md create mode 100644 Triangle and Square - GFG/triangle-and-square.cpp create mode 100644 Union of two arrays - GFG/README.md create mode 100644 Union of two arrays - GFG/union-of-two-arrays.cpp create mode 100644 Word Break - Part 2 - GFG/README.md create mode 100644 Word Break - Part 2 - GFG/word-break-part-2.cpp create mode 100644 XOR Game - GFG/README.md create mode 100644 XOR Game - GFG/xor-game.cpp create mode 100644 accounts-merge/README.md create mode 100644 accounts-merge/accounts-merge.cpp create mode 100644 add-digits/README.md create mode 100644 add-digits/add-digits.cpp create mode 100644 add-strings/README.md create mode 100644 add-strings/add-strings.cpp create mode 100644 add-two-numbers/README.md create mode 100644 add-two-numbers/add-two-numbers.cpp create mode 100644 all-elements-in-two-binary-search-trees/README.md create mode 100644 all-elements-in-two-binary-search-trees/all-elements-in-two-binary-search-trees.cpp create mode 100644 all-paths-from-source-to-target/README.md create mode 100644 all-paths-from-source-to-target/all-paths-from-source-to-target.cpp create mode 100644 all-possible-full-binary-trees/README.md create mode 100644 all-possible-full-binary-trees/all-possible-full-binary-trees.cpp create mode 100644 arranging-coins/README.md create mode 100644 arranging-coins/arranging-coins.cpp create mode 100644 array-of-doubled-pairs/README.md create mode 100644 balance-a-binary-search-tree/README.md create mode 100644 balanced-binary-tree/README.md create mode 100644 balanced-binary-tree/balanced-binary-tree.cpp create mode 100644 best-sightseeing-pair/README.md create mode 100644 best-sightseeing-pair/best-sightseeing-pair.cpp create mode 100644 best-time-to-buy-and-sell-stock-ii/README.md create mode 100644 best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.cpp create mode 100644 best-time-to-buy-and-sell-stock-iii/README.md create mode 100644 best-time-to-buy-and-sell-stock-iv/README.md create mode 100644 best-time-to-buy-and-sell-stock-iv/best-time-to-buy-and-sell-stock-iv.cpp create mode 100644 best-time-to-buy-and-sell-stock-with-cooldown/README.md create mode 100644 best-time-to-buy-and-sell-stock-with-cooldown/best-time-to-buy-and-sell-stock-with-cooldown.cpp create mode 100644 best-time-to-buy-and-sell-stock/README.md create mode 100644 best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.cpp create mode 100644 binary-search-tree-to-greater-sum-tree/README.md create mode 100644 binary-search-tree-to-greater-sum-tree/binary-search-tree-to-greater-sum-tree.cpp create mode 100644 binary-search/README.md create mode 100644 binary-search/binary-search.cpp create mode 100644 binary-tree-inorder-traversal/README.md create mode 100644 binary-tree-inorder-traversal/binary-tree-inorder-traversal.cpp create mode 100644 binary-tree-level-order-traversal/README.md create mode 100644 binary-tree-level-order-traversal/binary-tree-level-order-traversal.cpp create mode 100644 binary-tree-maximum-path-sum/README.md create mode 100644 binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.cpp create mode 100644 binary-tree-paths/README.md create mode 100644 binary-tree-paths/binary-tree-paths.cpp create mode 100644 binary-tree-postorder-traversal/README.md create mode 100644 binary-tree-preorder-traversal/README.md create mode 100644 binary-tree-preorder-traversal/binary-tree-preorder-traversal.cpp create mode 100644 binary-tree-pruning/README.md create mode 100644 binary-tree-right-side-view/README.md create mode 100644 binary-tree-right-side-view/binary-tree-right-side-view.cpp create mode 100644 binary-tree-zigzag-level-order-traversal/README.md create mode 100644 binary-tree-zigzag-level-order-traversal/binary-tree-zigzag-level-order-traversal.cpp create mode 100644 binary-watch/README.md create mode 100644 binary-watch/binary-watch.cpp create mode 100644 build-array-from-permutation/README.md create mode 100644 build-array-from-permutation/build-array-from-permutation.cpp create mode 100644 burst-balloons/README.md create mode 100644 burst-balloons/burst-balloons.cpp create mode 100644 climbing-stairs/README.md create mode 100644 climbing-stairs/climbing-stairs.cpp create mode 100644 clone-graph/README.md create mode 100644 coin-change-2/README.md create mode 100644 coin-change-2/coin-change-2.cpp create mode 100644 coin-change/README.md create mode 100644 coin-change/coin-change.cpp create mode 100644 combination-sum-iv/README.md create mode 100644 combination-sum-iv/combination-sum-iv.cpp create mode 100644 combination-sum/README.md create mode 100644 combination-sum/combination-sum.cpp create mode 100644 combine-two-tables/README.md create mode 100644 combine-two-tables/combine-two-tables.sql create mode 100644 consecutive-characters/README.md create mode 100644 consecutive-characters/consecutive-characters.cpp create mode 100644 construct-binary-tree-from-inorder-and-postorder-traversal/README.md create mode 100644 construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.cpp create mode 100644 construct-binary-tree-from-preorder-and-inorder-traversal/README.md create mode 100644 construct-binary-tree-from-preorder-and-inorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal.cpp create mode 100644 contains-duplicate-ii/README.md create mode 100644 contains-duplicate-ii/contains-duplicate-ii.cpp create mode 100644 contains-duplicate/README.md create mode 100644 contains-duplicate/contains-duplicate.cpp create mode 100644 convert-binary-number-in-a-linked-list-to-integer/README.md create mode 100644 convert-binary-number-in-a-linked-list-to-integer/convert-binary-number-in-a-linked-list-to-integer.cpp create mode 100644 convert-sorted-array-to-binary-search-tree/README.md create mode 100644 convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.cpp create mode 100644 copy-list-with-random-pointer/README.md create mode 100644 copy-list-with-random-pointer/copy-list-with-random-pointer.cpp create mode 100644 count-number-of-teams/README.md create mode 100644 count-sorted-vowel-strings/README.md create mode 100644 count-substrings-that-differ-by-one-character/README.md create mode 100644 count-substrings-that-differ-by-one-character/count-substrings-that-differ-by-one-character.cpp create mode 100644 count-triplets-that-can-form-two-arrays-of-equal-xor/README.md create mode 100644 course-schedule-ii/README.md create mode 100644 course-schedule-ii/course-schedule-ii.cpp create mode 100644 course-schedule/README.md create mode 100644 custom-sort-string/README.md create mode 100644 custom-sort-string/custom-sort-string.cpp create mode 100644 daily-temperatures/README.md create mode 100644 daily-temperatures/daily-temperatures.cpp create mode 100644 decode-ways-ii/README.md create mode 100644 decode-ways/README.md create mode 100644 decode-ways/decode-ways.cpp create mode 100644 deepest-leaves-sum/README.md create mode 100644 deepest-leaves-sum/deepest-leaves-sum.cpp create mode 100644 delete-and-earn/README.md create mode 100644 delete-leaves-with-a-given-value/README.md create mode 100644 delete-node-in-a-bst/README.md create mode 100644 delete-node-in-a-bst/delete-node-in-a-bst.cpp create mode 100644 delete-node-in-a-linked-list/README.md create mode 100644 delete-node-in-a-linked-list/delete-node-in-a-linked-list.cpp create mode 100644 destination-city/README.md create mode 100644 detonate-the-maximum-bombs/README.md create mode 100644 detonate-the-maximum-bombs/detonate-the-maximum-bombs.cpp create mode 100644 di-string-match/README.md create mode 100644 di-string-match/di-string-match.cpp create mode 100644 diameter-of-binary-tree/README.md create mode 100644 diameter-of-binary-tree/diameter-of-binary-tree.cpp create mode 100644 different-ways-to-add-parentheses/README.md create mode 100644 divide-two-integers/README.md create mode 100644 edit-distance/README.md create mode 100644 encode-and-decode-tinyurl/README.md create mode 100644 encode-and-decode-tinyurl/encode-and-decode-tinyurl.cpp create mode 100644 excel-sheet-column-title/README.md create mode 100644 excel-sheet-column-title/excel-sheet-column-title.cpp create mode 100644 fibonacci-number/README.md create mode 100644 fibonacci-number/fibonacci-number.cpp create mode 100644 find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/README.md create mode 100644 find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.cpp create mode 100644 find-all-numbers-disappeared-in-an-array/README.md create mode 100644 find-all-numbers-disappeared-in-an-array/find-all-numbers-disappeared-in-an-array.cpp create mode 100644 find-center-of-star-graph/README.md create mode 100644 find-center-of-star-graph/find-center-of-star-graph.cpp create mode 100644 find-first-and-last-position-of-element-in-sorted-array/README.md create mode 100644 find-first-and-last-position-of-element-in-sorted-array/find-first-and-last-position-of-element-in-sorted-array.cpp create mode 100644 find-median-from-data-stream/README.md create mode 100644 find-median-from-data-stream/find-median-from-data-stream.cpp create mode 100644 find-minimum-in-rotated-sorted-array-ii/README.md create mode 100644 find-minimum-in-rotated-sorted-array-ii/find-minimum-in-rotated-sorted-array-ii.cpp create mode 100644 find-minimum-in-rotated-sorted-array/README.md create mode 100644 find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.cpp create mode 100644 find-peak-element/README.md create mode 100644 find-peak-element/find-peak-element.cpp create mode 100644 find-positive-integer-solution-for-a-given-equation/README.md create mode 100644 find-the-duplicate-number/README.md create mode 100644 find-the-duplicate-number/find-the-duplicate-number.cpp create mode 100644 find-the-town-judge/README.md create mode 100644 find-the-town-judge/find-the-town-judge.cpp create mode 100644 find-the-winner-of-the-circular-game/README.md create mode 100644 finding-the-users-active-minutes/README.md create mode 100644 first-bad-version/README.md create mode 100644 first-bad-version/first-bad-version.cpp create mode 100644 flatten-a-multilevel-doubly-linked-list/README.md create mode 100644 flatten-a-multilevel-doubly-linked-list/flatten-a-multilevel-doubly-linked-list.cpp create mode 100644 flatten-binary-tree-to-linked-list/README.md create mode 100644 flatten-binary-tree-to-linked-list/flatten-binary-tree-to-linked-list.cpp create mode 100644 flip-columns-for-maximum-number-of-equal-rows/README.md create mode 100644 flip-string-to-monotone-increasing/README.md create mode 100644 flip-string-to-monotone-increasing/flip-string-to-monotone-increasing.cpp create mode 100644 flood-fill/README.md create mode 100644 flood-fill/flood-fill.cpp create mode 100644 fruit-into-baskets/README.md create mode 100644 generate-parentheses/README.md create mode 100644 generate-parentheses/generate-parentheses.cpp create mode 100644 group-anagrams/README.md create mode 100644 group-anagrams/group-anagrams.cpp create mode 100644 group-the-people-given-the-group-size-they-belong-to/README.md create mode 100644 group-the-people-given-the-group-size-they-belong-to/group-the-people-given-the-group-size-they-belong-to.cpp create mode 100644 hamming-distance/README.md create mode 100644 hamming-distance/hamming-distance.cpp create mode 100644 house-robber-ii/README.md create mode 100644 house-robber-iii/README.md create mode 100644 house-robber-iii/house-robber-iii.cpp create mode 100644 house-robber/README.md create mode 100644 house-robber/house-robber.cpp create mode 100644 increasing-order-search-tree/README.md create mode 100644 insert-into-a-binary-search-tree/README.md create mode 100644 insert-into-a-binary-search-tree/insert-into-a-binary-search-tree.cpp create mode 100644 insertion-sort-list/README.md create mode 100644 insertion-sort-list/insertion-sort-list.cpp create mode 100644 integer-break/README.md create mode 100644 integer-break/integer-break.cpp create mode 100644 intersection-of-two-arrays/README.md create mode 100644 intersection-of-two-arrays/intersection-of-two-arrays.cpp create mode 100644 intersection-of-two-linked-lists/README.md create mode 100644 intersection-of-two-linked-lists/intersection-of-two-linked-lists.cpp create mode 100644 interval-list-intersections/README.md create mode 100644 interval-list-intersections/interval-list-intersections.cpp create mode 100644 intervals-between-identical-elements/README.md create mode 100644 invert-binary-tree/README.md create mode 100644 invert-binary-tree/invert-binary-tree.cpp create mode 100644 is-graph-bipartite/README.md create mode 100644 is-graph-bipartite/is-graph-bipartite.cpp create mode 100644 is-subsequence/README.md create mode 100644 is-subsequence/is-subsequence.cpp create mode 100644 isomorphic-strings/README.md create mode 100644 isomorphic-strings/isomorphic-strings.cpp create mode 100644 iterator-for-combination/README.md create mode 100644 iterator-for-combination/iterator-for-combination.cpp create mode 100644 jewels-and-stones/README.md create mode 100644 jewels-and-stones/jewels-and-stones.cpp create mode 100644 jump-game-ii/README.md create mode 100644 jump-game-ii/jump-game-ii.cpp create mode 100644 jump-game/README.md create mode 100644 k-closest-points-to-origin/README.md create mode 100644 k-closest-points-to-origin/k-closest-points-to-origin.cpp create mode 100644 koko-eating-bananas/README.md create mode 100644 kth-largest-element-in-an-array/README.md create mode 100644 kth-smallest-element-in-a-bst/README.md create mode 100644 kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst.cpp create mode 100644 kth-smallest-element-in-a-sorted-matrix/README.md create mode 100644 kth-smallest-element-in-a-sorted-matrix/kth-smallest-element-in-a-sorted-matrix.cpp create mode 100644 largest-component-size-by-common-factor/README.md create mode 100644 largest-component-size-by-common-factor/largest-component-size-by-common-factor.cpp create mode 100644 letter-combinations-of-a-phone-number/README.md create mode 100644 letter-combinations-of-a-phone-number/letter-combinations-of-a-phone-number.cpp create mode 100644 linked-list-cycle-ii/README.md create mode 100644 linked-list-cycle/README.md create mode 100644 linked-list-cycle/linked-list-cycle.cpp create mode 100644 longest-common-subsequence/README.md create mode 100644 longest-common-subsequence/longest-common-subsequence.cpp create mode 100644 longest-consecutive-sequence/README.md create mode 100644 longest-consecutive-sequence/longest-consecutive-sequence.cpp create mode 100644 longest-increasing-subsequence/README.md create mode 100644 longest-increasing-subsequence/longest-increasing-subsequence.cpp create mode 100644 longest-palindromic-subsequence/README.md create mode 100644 longest-palindromic-substring/README.md create mode 100644 longest-palindromic-substring/longest-palindromic-substring.cpp create mode 100644 longest-repeating-character-replacement/README.md create mode 100644 longest-substring-without-repeating-characters/README.md create mode 100644 longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.cpp create mode 100644 longest-uncommon-subsequence-ii/README.md create mode 100644 lowest-common-ancestor-of-a-binary-search-tree/README.md create mode 100644 lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.cpp create mode 100644 lowest-common-ancestor-of-a-binary-tree/README.md create mode 100644 lowest-common-ancestor-of-a-binary-tree/lowest-common-ancestor-of-a-binary-tree.cpp create mode 100644 majority-element-ii/README.md create mode 100644 majority-element-ii/majority-element-ii.cpp create mode 100644 majority-element/README.md create mode 100644 majority-element/majority-element.cpp create mode 100644 make-the-string-great/README.md create mode 100644 make-the-string-great/make-the-string-great.cpp create mode 100644 matrix-block-sum/README.md create mode 100644 matrix-block-sum/matrix-block-sum.cpp create mode 100644 max-area-of-island/README.md create mode 100644 max-area-of-island/max-area-of-island.cpp create mode 100644 max-consecutive-ones-iii/README.md create mode 100644 max-consecutive-ones-iii/max-consecutive-ones-iii.cpp create mode 100644 max-consecutive-ones/README.md create mode 100644 max-consecutive-ones/max-consecutive-ones.cpp create mode 100644 maximal-rectangle/README.md create mode 100644 maximal-rectangle/maximal-rectangle.cpp create mode 100644 maximal-square/README.md create mode 100644 maximal-square/maximal-square.cpp create mode 100644 maximum-69-number/README.md create mode 100644 maximum-average-subarray-i/README.md create mode 100644 maximum-average-subarray-i/maximum-average-subarray-i.cpp create mode 100644 maximum-binary-tree/README.md create mode 100644 maximum-depth-of-binary-tree/README.md create mode 100644 maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.cpp create mode 100644 maximum-difference-between-node-and-ancestor/README.md create mode 100644 maximum-difference-between-node-and-ancestor/maximum-difference-between-node-and-ancestor.cpp create mode 100644 maximum-employees-to-be-invited-to-a-meeting/README.md create mode 100644 maximum-length-of-repeated-subarray/README.md create mode 100644 maximum-length-of-subarray-with-positive-product/README.md create mode 100644 maximum-product-subarray/README.md create mode 100644 maximum-product-subarray/maximum-product-subarray.cpp create mode 100644 maximum-profit-in-job-scheduling/README.md create mode 100644 maximum-profit-in-job-scheduling/maximum-profit-in-job-scheduling.cpp create mode 100644 maximum-score-from-removing-stones/README.md create mode 100644 maximum-subarray/README.md create mode 100644 maximum-subarray/maximum-subarray.cpp create mode 100644 maximum-sum-circular-subarray/README.md create mode 100644 maximum-sum-circular-subarray/maximum-sum-circular-subarray.cpp create mode 100644 maximum-units-on-a-truck/README.md create mode 100644 maximum-units-on-a-truck/maximum-units-on-a-truck.cpp create mode 100644 median-of-two-sorted-arrays/README.md create mode 100644 median-of-two-sorted-arrays/median-of-two-sorted-arrays.cpp create mode 100644 merge-intervals/README.md create mode 100644 merge-intervals/merge-intervals.cpp create mode 100644 merge-k-sorted-lists/README.md create mode 100644 merge-k-sorted-lists/merge-k-sorted-lists.cpp create mode 100644 merge-sorted-array/README.md create mode 100644 merge-sorted-array/merge-sorted-array.cpp create mode 100644 merge-two-binary-trees/README.md create mode 100644 merge-two-binary-trees/merge-two-binary-trees.cpp create mode 100644 merge-two-sorted-lists/README.md create mode 100644 merge-two-sorted-lists/merge-two-sorted-lists.cpp create mode 100644 middle-of-the-linked-list/README.md create mode 100644 middle-of-the-linked-list/middle-of-the-linked-list.cpp create mode 100644 min-cost-climbing-stairs/README.md create mode 100644 min-cost-climbing-stairs/min-cost-climbing-stairs.cpp create mode 100644 minimum-absolute-difference-in-bst/README.md create mode 100644 minimum-absolute-difference-in-bst/minimum-absolute-difference-in-bst.cpp create mode 100644 minimum-cost-to-move-chips-to-the-same-position/README.md create mode 100644 minimum-cost-to-move-chips-to-the-same-position/minimum-cost-to-move-chips-to-the-same-position.cpp create mode 100644 minimum-depth-of-binary-tree/README.md create mode 100644 minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.cpp create mode 100644 minimum-distance-between-bst-nodes/README.md create mode 100644 minimum-distance-between-bst-nodes/minimum-distance-between-bst-nodes.cpp create mode 100644 minimum-falling-path-sum/README.md create mode 100644 minimum-falling-path-sum/minimum-falling-path-sum.cpp create mode 100644 minimum-height-trees/README.md create mode 100644 minimum-number-of-buckets-required-to-collect-rainwater-from-houses/README.md create mode 100644 minimum-number-of-steps-to-make-two-strings-anagram/README.md create mode 100644 minimum-number-of-steps-to-make-two-strings-anagram/minimum-number-of-steps-to-make-two-strings-anagram.cpp create mode 100644 minimum-operations-to-make-array-equal/README.md create mode 100644 minimum-operations-to-make-the-array-k-increasing/README.md create mode 100644 minimum-operations-to-make-the-array-k-increasing/minimum-operations-to-make-the-array-k-increasing.cpp create mode 100644 minimum-path-sum/README.md create mode 100644 minimum-path-sum/minimum-path-sum.cpp create mode 100644 minimum-size-subarray-sum/README.md create mode 100644 minimum-size-subarray-sum/minimum-size-subarray-sum.cpp create mode 100644 minimum-value-to-get-positive-step-by-step-sum/README.md create mode 100644 minimum-value-to-get-positive-step-by-step-sum/minimum-value-to-get-positive-step-by-step-sum.cpp create mode 100644 minimum-window-substring/README.md create mode 100644 minimum-window-substring/minimum-window-substring.cpp create mode 100644 move-zeroes/README.md create mode 100644 move-zeroes/move-zeroes.cpp create mode 100644 multiply-strings/README.md create mode 100644 multiply-strings/multiply-strings.cpp create mode 100644 n-ary-tree-level-order-traversal/README.md create mode 100644 n-ary-tree-level-order-traversal/n-ary-tree-level-order-traversal.cpp create mode 100644 n-ary-tree-preorder-traversal/README.md create mode 100644 n-ary-tree-preorder-traversal/n-ary-tree-preorder-traversal.cpp create mode 100644 n-th-tribonacci-number/README.md create mode 100644 n-th-tribonacci-number/n-th-tribonacci-number.cpp create mode 100644 nCr mod M _ Part 1 - GFG/README.md create mode 100644 nCr mod M _ Part 1 - GFG/n-cr-mod-m-part-1.cpp create mode 100644 next-greater-element-i/README.md create mode 100644 next-greater-element-i/next-greater-element-i.cpp create mode 100644 next-greater-element-ii/README.md create mode 100644 next-greater-element-ii/next-greater-element-ii.cpp create mode 100644 next-permutation/README.md create mode 100644 next-permutation/next-permutation.cpp create mode 100644 number-of-1-bits/README.md create mode 100644 number-of-islands/README.md create mode 100644 number-of-islands/number-of-islands.cpp create mode 100644 number-of-provinces/README.md create mode 100644 number-of-provinces/number-of-provinces.cpp create mode 100644 number-of-valid-words-for-each-puzzle/README.md create mode 100644 odd-even-linked-list/README.md create mode 100644 odd-even-linked-list/odd-even-linked-list.cpp create mode 100644 pairs-of-songs-with-total-durations-divisible-by-60/README.md create mode 100644 pairs-of-songs-with-total-durations-divisible-by-60/pairs-of-songs-with-total-durations-divisible-by-60.cpp create mode 100644 palindrome-linked-list/README.md create mode 100644 palindrome-linked-list/palindrome-linked-list.cpp create mode 100644 palindrome-partitioning-ii/README.md create mode 100644 partition-array-for-maximum-sum/README.md create mode 100644 partition-array-for-maximum-sum/partition-array-for-maximum-sum.cpp create mode 100644 partition-array-into-disjoint-intervals/README.md create mode 100644 partition-array-into-disjoint-intervals/partition-array-into-disjoint-intervals.cpp create mode 100644 pascals-triangle-ii/README.md create mode 100644 pascals-triangle/README.md create mode 100644 pascals-triangle/pascals-triangle.cpp create mode 100644 patching-array/README.md create mode 100644 patching-array/patching-array.cpp create mode 100644 path-sum-ii/README.md create mode 100644 path-sum-ii/path-sum-ii.cpp create mode 100644 path-sum/README.md create mode 100644 path-sum/path-sum.cpp create mode 100644 perfect-squares/README.md create mode 100644 perfect-squares/perfect-squares.cpp create mode 100644 permutations-ii/README.md create mode 100644 permutations-ii/permutations-ii.cpp create mode 100644 populating-next-right-pointers-in-each-node/README.md create mode 100644 populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.cpp create mode 100644 populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.java create mode 100644 power-of-four/README.md create mode 100644 power-of-four/power-of-four.cpp create mode 100644 power-of-three/README.md create mode 100644 power-of-three/power-of-three.cpp create mode 100644 power-of-two/README.md create mode 100644 power-of-two/power-of-two.cpp create mode 100644 powx-n/README.md create mode 100644 powx-n/powx-n.cpp create mode 100644 product-of-array-except-self/README.md create mode 100644 product-of-array-except-self/product-of-array-except-self.cpp create mode 100644 product-of-the-last-k-numbers/README.md create mode 100644 push-dominoes/README.md create mode 100644 push-dominoes/push-dominoes.cpp create mode 100644 range-addition-ii/README.md create mode 100644 range-addition-ii/range-addition-ii.cpp create mode 100644 range-sum-of-bst/README.md create mode 100644 range-sum-of-bst/range-sum-of-bst.cpp create mode 100644 range-sum-query-2d-immutable/README.md create mode 100644 range-sum-query-2d-immutable/range-sum-query-2d-immutable.cpp create mode 100644 range-sum-query-immutable/README.md create mode 100644 rank-transform-of-a-matrix/README.md create mode 100644 rank-transform-of-a-matrix/rank-transform-of-a-matrix.cpp create mode 100644 remove-boxes/README.md create mode 100644 remove-duplicates-from-sorted-array/README.md create mode 100644 remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.cpp create mode 100644 remove-linked-list-elements/README.md create mode 100644 remove-linked-list-elements/remove-linked-list-elements.cpp create mode 100644 remove-nth-node-from-end-of-list/README.md create mode 100644 remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.cpp create mode 100644 reorder-list/README.md create mode 100644 reverse-linked-list/README.md create mode 100644 reverse-linked-list/reverse-linked-list.cpp create mode 100644 reverse-nodes-in-k-group/README.md create mode 100644 reverse-nodes-in-k-group/reverse-nodes-in-k-group.cpp create mode 100644 reverse-pairs/README.md create mode 100644 reverse-pairs/reverse-pairs.cpp create mode 100644 reverse-words-in-a-string-iii/README.md create mode 100644 robot-return-to-origin/README.md create mode 100644 robot-return-to-origin/robot-return-to-origin.cpp create mode 100644 roman-to-integer/README.md create mode 100644 roman-to-integer/roman-to-integer.cpp create mode 100644 rotate-array/README.md create mode 100644 rotate-array/rotate-array.cpp create mode 100644 rotate-image/README.md create mode 100644 rotate-image/rotate-image.cpp create mode 100644 rotate-list/README.md create mode 100644 rotate-list/rotate-list.cpp create mode 100644 rotated-digits/README.md create mode 100644 rotated-digits/rotated-digits.cpp create mode 100644 rotting-oranges/README.md create mode 100644 rotting-oranges/rotting-oranges.cpp create mode 100644 same-tree/README.md create mode 100644 same-tree/same-tree.cpp create mode 100644 search-a-2d-matrix-ii/README.md create mode 100644 search-a-2d-matrix-ii/search-a-2d-matrix-ii.cpp create mode 100644 search-a-2d-matrix/README.md create mode 100644 search-a-2d-matrix/search-a-2d-matrix.cpp create mode 100644 search-in-rotated-sorted-array/README.md create mode 100644 search-in-rotated-sorted-array/search-in-rotated-sorted-array.cpp create mode 100644 search-insert-position/README.md create mode 100644 search-insert-position/search-insert-position.cpp create mode 100644 second-highest-salary/README.md create mode 100644 second-highest-salary/second-highest-salary.sql create mode 100644 set-matrix-zeroes/README.md create mode 100644 set-matrix-zeroes/set-matrix-zeroes.cpp create mode 100644 shuffle-an-array/README.md create mode 100644 shuffle-an-array/shuffle-an-array.cpp create mode 100644 single-element-in-a-sorted-array/README.md create mode 100644 single-element-in-a-sorted-array/single-element-in-a-sorted-array.cpp create mode 100644 single-number-iii/README.md create mode 100644 single-number-iii/single-number-iii.cpp create mode 100644 slowest-key/README.md create mode 100644 slowest-key/slowest-key.cpp create mode 100644 smallest-integer-divisible-by-k/README.md create mode 100644 smallest-integer-divisible-by-k/smallest-integer-divisible-by-k.cpp create mode 100644 sort-an-array/README.md create mode 100644 sort-an-array/sort-an-array.cpp create mode 100644 sort-characters-by-frequency/README.md create mode 100644 sort-characters-by-frequency/sort-characters-by-frequency.cpp create mode 100644 sort-colors/README.md create mode 100644 sort-colors/sort-colors.cpp create mode 100644 sort-integers-by-the-number-of-1-bits/README.md create mode 100644 spiral-matrix/README.md create mode 100644 spiral-matrix/spiral-matrix.cpp create mode 100644 sqrtx/README.md create mode 100644 sqrtx/sqrtx.cpp create mode 100644 squares-of-a-sorted-array/README.md create mode 100644 squares-of-a-sorted-array/squares-of-a-sorted-array.cpp create mode 100644 stone-game/README.md create mode 100644 stone-game/stone-game.cpp create mode 100644 subsets/README.md create mode 100644 subsets/subsets.cpp create mode 100644 sum-of-left-leaves/README.md create mode 100644 sum-of-left-leaves/sum-of-left-leaves.cpp create mode 100644 sum-of-nodes-with-even-valued-grandparent/README.md create mode 100644 sum-of-nodes-with-even-valued-grandparent/sum-of-nodes-with-even-valued-grandparent.cpp create mode 100644 sum-of-square-numbers/README.md create mode 100644 sum-of-square-numbers/sum-of-square-numbers.cpp create mode 100644 sum-root-to-leaf-numbers/README.md create mode 100644 surrounded-regions/README.md create mode 100644 surrounded-regions/surrounded-regions.cpp create mode 100644 symmetric-tree/README.md create mode 100644 three-equal-parts/README.md create mode 100644 three-equal-parts/three-equal-parts.cpp create mode 100644 total-hamming-distance/README.md create mode 100644 trapping-rain-water/README.md create mode 100644 trapping-rain-water/trapping-rain-water.cpp create mode 100644 triangle/README.md create mode 100644 trim-a-binary-search-tree/README.md create mode 100644 trim-a-binary-search-tree/trim-a-binary-search-tree.cpp create mode 100644 two-sum-ii-input-array-is-sorted/README.md create mode 100644 two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.cpp create mode 100644 two-sum-iv-input-is-a-bst/README.md create mode 100644 two-sum-iv-input-is-a-bst/two-sum-iv-input-is-a-bst.cpp create mode 100644 two-sum/README.md create mode 100644 two-sum/two-sum.cpp create mode 100644 ugly-number-ii/README.md create mode 100644 ugly-number-ii/ugly-number-ii.cpp create mode 100644 unique-binary-search-trees-ii/README.md create mode 100644 unique-binary-search-trees/README.md create mode 100644 unique-binary-search-trees/unique-binary-search-trees.cpp create mode 100644 unique-paths-ii/README.md create mode 100644 unique-paths-iii/README.md create mode 100644 unique-paths-iii/unique-paths-iii.cpp create mode 100644 unique-paths/README.md create mode 100644 unique-paths/unique-paths.cpp create mode 100644 valid-palindrome/README.md create mode 100644 valid-palindrome/valid-palindrome.cpp create mode 100644 valid-parentheses/README.md create mode 100644 valid-parentheses/valid-parentheses.cpp create mode 100644 valid-sudoku/README.md create mode 100644 valid-sudoku/valid-sudoku.cpp create mode 100644 valid-triangle-number/README.md create mode 100644 valid-triangle-number/valid-triangle-number.cpp create mode 100644 validate-binary-search-tree/README.md create mode 100644 validate-binary-search-tree/validate-binary-search-tree.cpp create mode 100644 verify-preorder-serialization-of-a-binary-tree/README.md create mode 100644 verify-preorder-serialization-of-a-binary-tree/verify-preorder-serialization-of-a-binary-tree.cpp create mode 100644 walking-robot-simulation-ii/README.md create mode 100644 walking-robot-simulation-ii/walking-robot-simulation-ii.cpp create mode 100644 wiggle-subsequence/README.md create mode 100644 wiggle-subsequence/wiggle-subsequence.cpp create mode 100644 wildcard-matching/README.md create mode 100644 word-break/README.md create mode 100644 word-break/word-break.cpp create mode 100644 word-ladder/README.md create mode 100644 word-search/README.md create mode 100644 xor-queries-of-a-subarray/README.md diff --git a/01-matrix/README.md b/01-matrix/README.md new file mode 100644 index 0000000..ec1fbc2 --- /dev/null +++ b/01-matrix/README.md @@ -0,0 +1,29 @@ +

542. 01 Matrix

Medium


Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

+ +

The distance between two adjacent cells is 1.

+ +

 

+

Example 1:

+ +
Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
+Output: [[0,0,0],[0,1,0],[0,0,0]]
+
+ +

Example 2:

+ +
Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
+Output: [[0,0,0],[0,1,0],[1,2,1]]
+
+ +

 

+

Constraints:

+ + +
\ No newline at end of file diff --git a/1's Complement - GFG/1s-complement.cpp b/1's Complement - GFG/1s-complement.cpp new file mode 100644 index 0000000..c17c0dd --- /dev/null +++ b/1's Complement - GFG/1s-complement.cpp @@ -0,0 +1,42 @@ +// { Driver Code Starts + +#include +using namespace std; + + // } Driver Code Ends + +class Solution{ +public: + string onesComplement(string S,int N){ + //code here + int i=0; + string result=""; + while(i>t; + while(t--) + { + int n; + cin>>n; + string s; + cin>>s; + Solution ob; + cout< +

Given an N bit binary number, find the 1's complement of the number. The ones' complement of a binary number is defined as the value obtained by inverting all the bits in the binary representation of the number (swapping 0s for 1s and vice versa).

+ +

Example 1:

+ +
Input:
+N = 3
+S = 101
+Output:
+010
+Explanation:
+We get the output by converting 1's in S
+to 0 and 0s to 1
+
+ +

Example 2:

+ +
Input:
+N = 2
+S = 10
+Output:
+01
+Explanation:
+We get the output by converting 1's in S
+to 0 and 0s to 1
+
+ +


+Your Task:  
+You don't need to read input or print anything. Your task is to complete the function onesComplement() which takes the binary string S, its size N as input parameters and returns 1's complement of S of size N.

+ +

Expected Time Complexity: O(N)
+Expected Space Complexity: O(N)

+ +

Constraints:
+1<=N<=100

+

+ \ No newline at end of file diff --git a/1-two-sum/1-two-sum.cpp b/1-two-sum/1-two-sum.cpp new file mode 100644 index 0000000..1222072 --- /dev/null +++ b/1-two-sum/1-two-sum.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector twoSum(vector& nums, int target) { + unordered_map m; + vector v; + + for(int i=0;i1. Two Sum

Easy


Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

+ +

You may assume that each input would have exactly one solution, and you may not use the same element twice.

+ +

You can return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: nums = [2,7,11,15], target = 9
+Output: [0,1]
+Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
+
+ +

Example 2:

+ +
Input: nums = [3,2,4], target = 6
+Output: [1,2]
+
+ +

Example 3:

+ +
Input: nums = [3,3], target = 6
+Output: [0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 104
  • +
  • -109 <= nums[i] <= 109
  • +
  • -109 <= target <= 109
  • +
  • Only one valid answer exists.
  • +
+ +

 

+Follow-up: Can you come up with an algorithm that is less than O(n2time complexity?
\ No newline at end of file diff --git a/100-same-tree/NOTES.md b/100-same-tree/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/100-same-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/100-same-tree/README.md b/100-same-tree/README.md new file mode 100644 index 0000000..149d655 --- /dev/null +++ b/100-same-tree/README.md @@ -0,0 +1,31 @@ +

100. Same Tree

Easy


Given the roots of two binary trees p and q, write a function to check if they are the same or not.

+ +

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

+ +

 

+

Example 1:

+ +
Input: p = [1,2,3], q = [1,2,3]
+Output: true
+
+ +

Example 2:

+ +
Input: p = [1,2], q = [1,null,2]
+Output: false
+
+ +

Example 3:

+ +
Input: p = [1,2,1], q = [1,1,2]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in both trees is in the range [0, 100].
  • +
  • -104 <= Node.val <= 104
  • +
+
\ No newline at end of file diff --git a/1009-complement-of-base-10-integer/1009-complement-of-base-10-integer.cpp b/1009-complement-of-base-10-integer/1009-complement-of-base-10-integer.cpp new file mode 100644 index 0000000..f31ac59 --- /dev/null +++ b/1009-complement-of-base-10-integer/1009-complement-of-base-10-integer.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + int bitwiseComplement(int N, int c = 1) { + while (c < N) c = (c << 1) + 1; + return N ^ c; +} +}; \ No newline at end of file diff --git a/1009-complement-of-base-10-integer/NOTES.md b/1009-complement-of-base-10-integer/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1009-complement-of-base-10-integer/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1009-complement-of-base-10-integer/README.md b/1009-complement-of-base-10-integer/README.md new file mode 100644 index 0000000..428c4b9 --- /dev/null +++ b/1009-complement-of-base-10-integer/README.md @@ -0,0 +1,40 @@ +

1009. Complement of Base 10 Integer

Easy


The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.

+ +
    +
  • For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
  • +
+ +

Given an integer n, return its complement.

+ +

 

+

Example 1:

+ +
Input: n = 5
+Output: 2
+Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
+
+ +

Example 2:

+ +
Input: n = 7
+Output: 0
+Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
+
+ +

Example 3:

+ +
Input: n = 10
+Output: 5
+Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n < 109
  • +
+ +

 

+

Note: This question is the same as 476: https://leetcode.com/problems/number-complement/

+
\ No newline at end of file diff --git a/1010-pairs-of-songs-with-total-durations-divisible-by-60/1010-pairs-of-songs-with-total-durations-divisible-by-60.cpp b/1010-pairs-of-songs-with-total-durations-divisible-by-60/1010-pairs-of-songs-with-total-durations-divisible-by-60.cpp new file mode 100644 index 0000000..30300e8 --- /dev/null +++ b/1010-pairs-of-songs-with-total-durations-divisible-by-60/1010-pairs-of-songs-with-total-durations-divisible-by-60.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int numPairsDivisibleBy60(vector& time) { + vector modd(60); + long long int total = 0; + for(auto a:time) modd[a%60]++; + for(int i=1;i<=29;i++) total += (modd[i] * modd[60-i]); + total = total + modd[30]*(modd[30]-1)/2 ; + total += modd[0]*(modd[0]-1)/2; + return total; + } +}; \ No newline at end of file diff --git a/1010-pairs-of-songs-with-total-durations-divisible-by-60/NOTES.md b/1010-pairs-of-songs-with-total-durations-divisible-by-60/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1010-pairs-of-songs-with-total-durations-divisible-by-60/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1010-pairs-of-songs-with-total-durations-divisible-by-60/README.md b/1010-pairs-of-songs-with-total-durations-divisible-by-60/README.md new file mode 100644 index 0000000..2cc6399 --- /dev/null +++ b/1010-pairs-of-songs-with-total-durations-divisible-by-60/README.md @@ -0,0 +1,30 @@ +

1010. Pairs of Songs With Total Durations Divisible by 60

Medium


You are given a list of songs where the ith song has a duration of time[i] seconds.

+ +

Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.

+ +

 

+

Example 1:

+ +
Input: time = [30,20,150,100,40]
+Output: 3
+Explanation: Three pairs have a total duration divisible by 60:
+(time[0] = 30, time[2] = 150): total duration 180
+(time[1] = 20, time[3] = 100): total duration 120
+(time[1] = 20, time[4] = 40): total duration 60
+
+ +

Example 2:

+ +
Input: time = [60,60,60]
+Output: 3
+Explanation: All three pairs have a total duration of 120, which is divisible by 60.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= time.length <= 6 * 104
  • +
  • 1 <= time[i] <= 500
  • +
+
\ No newline at end of file diff --git a/1011-capacity-to-ship-packages-within-d-days/1011-capacity-to-ship-packages-within-d-days.cpp b/1011-capacity-to-ship-packages-within-d-days/1011-capacity-to-ship-packages-within-d-days.cpp new file mode 100644 index 0000000..30ecdc1 --- /dev/null +++ b/1011-capacity-to-ship-packages-within-d-days/1011-capacity-to-ship-packages-within-d-days.cpp @@ -0,0 +1,51 @@ +class Solution { +public: + bool isPossible(int mid, vector& nums, int days) + { + int count = 1; + int curr_sum = 0; + for(int i=0;i mid) + { + count++; + if(count > days) + return false; + + curr_sum = nums[i]; + } + else + { + curr_sum += nums[i]; + } + } + cout<<"count mid "<& nums, int days) { + + int low = 0; + int high = 0; + + for(int i=0;i>1; + //cout<1011. Capacity To Ship Packages Within D Days

Medium


A conveyor belt has packages that must be shipped from one port to another within days days.

+ +

The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.

+ +

Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.

+ +

 

+

Example 1:

+ +
Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
+Output: 15
+Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
+1st day: 1, 2, 3, 4, 5
+2nd day: 6, 7
+3rd day: 8
+4th day: 9
+5th day: 10
+
+Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
+
+ +

Example 2:

+ +
Input: weights = [3,2,2,4,1,4], days = 3
+Output: 6
+Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
+1st day: 3, 2
+2nd day: 2, 4
+3rd day: 1, 4
+
+ +

Example 3:

+ +
Input: weights = [1,2,3,1,1], days = 4
+Output: 3
+Explanation:
+1st day: 1
+2nd day: 2
+3rd day: 3
+4th day: 1, 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= days <= weights.length <= 5 * 104
  • +
  • 1 <= weights[i] <= 500
  • +
\ No newline at end of file diff --git a/102-binary-tree-level-order-traversal/102-binary-tree-level-order-traversal.cpp b/102-binary-tree-level-order-traversal/102-binary-tree-level-order-traversal.cpp new file mode 100644 index 0000000..efb4163 --- /dev/null +++ b/102-binary-tree-level-order-traversal/102-binary-tree-level-order-traversal.cpp @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> levelOrder(TreeNode* root) { + vector> ans; + if(root == NULL)return ans; + + queue q; + q.push(root); + + while(!q.empty()) + { + int size = q.size(); + vector temp; + while(size--) + { + TreeNode * front = q.front(); + q.pop(); + + temp.push_back(front->val); + if(front->left) + q.push(front->left); + if(front->right) + q.push(front->right); + } + ans.push_back(temp); + } + return ans; + } +}; \ No newline at end of file diff --git a/102-binary-tree-level-order-traversal/NOTES.md b/102-binary-tree-level-order-traversal/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/102-binary-tree-level-order-traversal/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/102-binary-tree-level-order-traversal/README.md b/102-binary-tree-level-order-traversal/README.md new file mode 100644 index 0000000..f7470bf --- /dev/null +++ b/102-binary-tree-level-order-traversal/README.md @@ -0,0 +1,29 @@ +

102. Binary Tree Level Order Traversal

Medium


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

+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: [[3],[9,20],[15,7]]
+
+ +

Example 2:

+ +
Input: root = [1]
+Output: [[1]]
+
+ +

Example 3:

+ +
Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 2000].
  • +
  • -1000 <= Node.val <= 1000
  • +
+
\ No newline at end of file diff --git a/1022-sum-of-root-to-leaf-binary-numbers/1022-sum-of-root-to-leaf-binary-numbers.cpp b/1022-sum-of-root-to-leaf-binary-numbers/1022-sum-of-root-to-leaf-binary-numbers.cpp new file mode 100644 index 0000000..e0aa904 --- /dev/null +++ b/1022-sum-of-root-to-leaf-binary-numbers/1022-sum-of-root-to-leaf-binary-numbers.cpp @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int ans=0; + int convert_decimal(vector v) + { + int n=0; + for(int i=0;i t) + { + if(!root)return; + t.push_back(root->val); + if(!root->left && !root->right)ans+=convert_decimal(t); + findpath(root->left,t); + findpath(root->right,t); + } + int sumRootToLeaf(TreeNode* root) { + if(!root)return 0; + vector t; + findpath(root,t); + return ans; + } +}; \ No newline at end of file diff --git a/1022-sum-of-root-to-leaf-binary-numbers/NOTES.md b/1022-sum-of-root-to-leaf-binary-numbers/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1022-sum-of-root-to-leaf-binary-numbers/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1022-sum-of-root-to-leaf-binary-numbers/README.md b/1022-sum-of-root-to-leaf-binary-numbers/README.md new file mode 100644 index 0000000..5f1c1ad --- /dev/null +++ b/1022-sum-of-root-to-leaf-binary-numbers/README.md @@ -0,0 +1,32 @@ +

1022. Sum of Root To Leaf Binary Numbers

Easy


You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit.

+ +
    +
  • For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.
  • +
+ +

For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers.

+ +

The test cases are generated so that the answer fits in a 32-bits integer.

+ +

 

+

Example 1:

+ +
Input: root = [1,0,1,0,1,0,1]
+Output: 22
+Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
+
+ +

Example 2:

+ +
Input: root = [0]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • Node.val is 0 or 1.
  • +
+
\ No newline at end of file diff --git a/1029-two-city-scheduling/1029-two-city-scheduling.cpp b/1029-two-city-scheduling/1029-two-city-scheduling.cpp new file mode 100644 index 0000000..5aa6001 --- /dev/null +++ b/1029-two-city-scheduling/1029-two-city-scheduling.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + static bool comp(vector &v1, vector &v2) + { + return ( abs(v1[0]-v1[1]) > abs(v2[0]-v2[1]) ); + } + int twoCitySchedCost(vector>& costs) { + int a = costs.size()/2; + int b = costs.size()/2; + int m = 0; + sort(costs.begin(), costs.end(), comp); + + for(int i=0;i1029. Two City Scheduling

Medium


A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.

+ +

Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.

+ +

 

+

Example 1:

+ +
Input: costs = [[10,20],[30,200],[400,50],[30,20]]
+Output: 110
+Explanation: 
+The first person goes to city A for a cost of 10.
+The second person goes to city A for a cost of 30.
+The third person goes to city B for a cost of 50.
+The fourth person goes to city B for a cost of 20.
+
+The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
+
+ +

Example 2:

+ +
Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
+Output: 1859
+
+ +

Example 3:

+ +
Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
+Output: 3086
+
+ +

 

+

Constraints:

+ +
    +
  • 2 * n == costs.length
  • +
  • 2 <= costs.length <= 100
  • +
  • costs.length is even.
  • +
  • 1 <= aCosti, bCosti <= 1000
  • +
+
\ No newline at end of file diff --git a/103-binary-tree-zigzag-level-order-traversal/NOTES.md b/103-binary-tree-zigzag-level-order-traversal/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/103-binary-tree-zigzag-level-order-traversal/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/103-binary-tree-zigzag-level-order-traversal/README.md b/103-binary-tree-zigzag-level-order-traversal/README.md new file mode 100644 index 0000000..d5e31c0 --- /dev/null +++ b/103-binary-tree-zigzag-level-order-traversal/README.md @@ -0,0 +1,29 @@ +

103. Binary Tree Zigzag Level Order Traversal

Medium


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

+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: [[3],[20,9],[15,7]]
+
+ +

Example 2:

+ +
Input: root = [1]
+Output: [[1]]
+
+ +

Example 3:

+ +
Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 2000].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/104-maximum-depth-of-binary-tree/104-maximum-depth-of-binary-tree.cpp b/104-maximum-depth-of-binary-tree/104-maximum-depth-of-binary-tree.cpp new file mode 100644 index 0000000..ea7915a --- /dev/null +++ b/104-maximum-depth-of-binary-tree/104-maximum-depth-of-binary-tree.cpp @@ -0,0 +1,23 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxi = 0; + int maxDepth(TreeNode* root) { + if(root == NULL)return 0; + + int l = maxDepth(root->left); + int r = maxDepth(root->right); + + return 1 + max(l,r); + } +}; \ No newline at end of file diff --git a/104-maximum-depth-of-binary-tree/NOTES.md b/104-maximum-depth-of-binary-tree/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/104-maximum-depth-of-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/104-maximum-depth-of-binary-tree/README.md b/104-maximum-depth-of-binary-tree/README.md new file mode 100644 index 0000000..48ceddf --- /dev/null +++ b/104-maximum-depth-of-binary-tree/README.md @@ -0,0 +1,25 @@ +

104. Maximum Depth of Binary Tree

Easy


Given the root of a binary tree, return its maximum depth.

+ +

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: 3
+
+ +

Example 2:

+ +
Input: root = [1,null,2]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/1041-robot-bounded-in-circle/1041-robot-bounded-in-circle.cpp b/1041-robot-bounded-in-circle/1041-robot-bounded-in-circle.cpp new file mode 100644 index 0000000..a2f2b45 --- /dev/null +++ b/1041-robot-bounded-in-circle/1041-robot-bounded-in-circle.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + bool isRobotBounded(string instructions) + { + vector position = {0, 0}, direction = {0, 1}; + + for (size_t i = 0; i < instructions.length(); i++) + { + switch(instructions[i]) + { + case 'L': + direction = {-direction[1], direction[0]}; + break; + case 'R': + direction = {direction[1], -direction[0]}; + break; + default: + position = {position[0] + direction[0], position[1] + direction[1]}; + } + } + return (position[0] == 0 && position[1] == 0) || (direction[0] != 0 || direction[1] != 1) ? true : false; + } +}; \ No newline at end of file diff --git a/1041-robot-bounded-in-circle/NOTES.md b/1041-robot-bounded-in-circle/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1041-robot-bounded-in-circle/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1041-robot-bounded-in-circle/README.md b/1041-robot-bounded-in-circle/README.md new file mode 100644 index 0000000..f29c0dd --- /dev/null +++ b/1041-robot-bounded-in-circle/README.md @@ -0,0 +1,40 @@ +

1041. Robot Bounded In Circle

Medium


On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:

+ +
    +
  • "G": go straight 1 unit;
  • +
  • "L": turn 90 degrees to the left;
  • +
  • "R": turn 90 degrees to the right.
  • +
+ +

The robot performs the instructions given in order, and repeats them forever.

+ +

Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.

+ +

 

+

Example 1:

+ +
Input: instructions = "GGLLGG"
+Output: true
+Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0).
+When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.
+ +

Example 2:

+ +
Input: instructions = "GG"
+Output: false
+Explanation: The robot moves north indefinitely.
+ +

Example 3:

+ +
Input: instructions = "GL"
+Output: true
+Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...
+ +

 

+

Constraints:

+ +
    +
  • 1 <= instructions.length <= 100
  • +
  • instructions[i] is 'G', 'L' or, 'R'.
  • +
+
\ No newline at end of file diff --git a/1049-last-stone-weight-ii/1049-last-stone-weight-ii.cpp b/1049-last-stone-weight-ii/1049-last-stone-weight-ii.cpp new file mode 100644 index 0000000..c81e856 --- /dev/null +++ b/1049-last-stone-weight-ii/1049-last-stone-weight-ii.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int lastStoneWeightII(vector& stones) { + + int n = stones.size(); + if(n == 1)return stones[0]; + int sum = 0; + for(auto i:stones)sum+=i; + vector> dp(stones.size(),vector (sum+1,0)); + + dp[0][stones[0]] = 1; + for(int i=0;i1049. Last Stone Weight II

Medium


You are given an array of integers stones where stones[i] is the weight of the ith stone.

+ +

We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:

+ +
    +
  • If x == y, both stones are destroyed, and
  • +
  • If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.
  • +
+ +

At the end of the game, there is at most one stone left.

+ +

Return the smallest possible weight of the left stone. If there are no stones left, return 0.

+ +

 

+

Example 1:

+ +
Input: stones = [2,7,4,1,8,1]
+Output: 1
+Explanation:
+We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then,
+we can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then,
+we can combine 2 and 1 to get 1, so the array converts to [1,1,1] then,
+we can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value.
+
+ +

Example 2:

+ +
Input: stones = [31,26,33,21,40]
+Output: 5
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= stones.length <= 30
  • +
  • 1 <= stones[i] <= 100
  • +
+
\ No newline at end of file diff --git a/105-construct-binary-tree-from-preorder-and-inorder-traversal/105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp b/105-construct-binary-tree-from-preorder-and-inorder-traversal/105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp new file mode 100644 index 0000000..9c0a134 --- /dev/null +++ b/105-construct-binary-tree-from-preorder-and-inorder-traversal/105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp @@ -0,0 +1,57 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode * helper(vector& preorder, vector& inorder,int pres,int pree,int ins,int ine) + { + + if(ins > ine) + return NULL; + + int rootIndex = -1; + int rootData = preorder[pres]; + + for(int i=ins;i<=ine;i++) + { + if(inorder[i] == rootData) + { + rootIndex = i; + break; + } + } + + int lins = ins; + int line = rootIndex-1; + int lpres = pres+1; + int lpree = line - lins + lpres; + int rins = rootIndex+1; + int rine = ine; + int rpree = pree; + int rpres = lpree + 1; ; + + + TreeNode * root = new TreeNode(rootData); + TreeNode * leftChild = helper(preorder,inorder,lpres,lpres,lins,line); + TreeNode * rightChild = helper(preorder,inorder,rpres,rpree,rins,rine); + + root->left = leftChild; + root->right = rightChild; + + return root; + + } + + TreeNode* buildTree(vector& preorder, vector& inorder) { + + return helper(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1); + } +}; \ No newline at end of file diff --git a/105-construct-binary-tree-from-preorder-and-inorder-traversal/NOTES.md b/105-construct-binary-tree-from-preorder-and-inorder-traversal/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/105-construct-binary-tree-from-preorder-and-inorder-traversal/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/105-construct-binary-tree-from-preorder-and-inorder-traversal/README.md b/105-construct-binary-tree-from-preorder-and-inorder-traversal/README.md new file mode 100644 index 0000000..050dde7 --- /dev/null +++ b/105-construct-binary-tree-from-preorder-and-inorder-traversal/README.md @@ -0,0 +1,28 @@ +

105. Construct Binary Tree from Preorder and Inorder Traversal

Medium


Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

+ +

 

+

Example 1:

+ +
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
+Output: [3,9,20,null,null,15,7]
+
+ +

Example 2:

+ +
Input: preorder = [-1], inorder = [-1]
+Output: [-1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= preorder.length <= 3000
  • +
  • inorder.length == preorder.length
  • +
  • -3000 <= preorder[i], inorder[i] <= 3000
  • +
  • preorder and inorder consist of unique values.
  • +
  • Each value of inorder also appears in preorder.
  • +
  • preorder is guaranteed to be the preorder traversal of the tree.
  • +
  • inorder is guaranteed to be the inorder traversal of the tree.
  • +
+
\ No newline at end of file diff --git a/108-convert-sorted-array-to-binary-search-tree/108-convert-sorted-array-to-binary-search-tree.cpp b/108-convert-sorted-array-to-binary-search-tree/108-convert-sorted-array-to-binary-search-tree.cpp new file mode 100644 index 0000000..e4bb3bb --- /dev/null +++ b/108-convert-sorted-array-to-binary-search-tree/108-convert-sorted-array-to-binary-search-tree.cpp @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + TreeNode* helper(vector& nums,int start,int end) + { + if(start<= end) + { + int mid = (start+end)/2; + TreeNode * root = new TreeNode(nums[mid]); + TreeNode * left = helper(nums,start,mid-1); + TreeNode * right = helper(nums,mid+1,end); + root->left = left; + root->right = right; + return root; + } + return NULL; + } + + TreeNode* sortedArrayToBST(vector& nums) { + + if(nums.size()==0) + return NULL; + + return helper(nums,0,nums.size()-1); + + } +}; \ No newline at end of file diff --git a/108-convert-sorted-array-to-binary-search-tree/NOTES.md b/108-convert-sorted-array-to-binary-search-tree/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/108-convert-sorted-array-to-binary-search-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/108-convert-sorted-array-to-binary-search-tree/README.md b/108-convert-sorted-array-to-binary-search-tree/README.md new file mode 100644 index 0000000..fad3656 --- /dev/null +++ b/108-convert-sorted-array-to-binary-search-tree/README.md @@ -0,0 +1,29 @@ +

108. Convert Sorted Array to Binary Search Tree

Easy


Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

+ +

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

+ +

 

+

Example 1:

+ +
Input: nums = [-10,-3,0,5,9]
+Output: [0,-3,9,-10,null,5]
+Explanation: [0,-10,5,null,-3,null,9] is also accepted:
+
+
+ +

Example 2:

+ +
Input: nums = [1,3]
+Output: [3,1]
+Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums is sorted in a strictly increasing order.
  • +
+
\ No newline at end of file diff --git a/1094-car-pooling/1094-car-pooling.cpp b/1094-car-pooling/1094-car-pooling.cpp new file mode 100644 index 0000000..fcc2979 --- /dev/null +++ b/1094-car-pooling/1094-car-pooling.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + + bool carPooling(vector>& trips, int capacity) { + int stops[1001] = {}; + for (auto t : trips) stops[t[1]] += t[0], stops[t[2]] -= t[0]; + for (auto i = 0; capacity >= 0 && i < 1001; ++i) capacity -= stops[i]; + return capacity >= 0; +} +}; \ No newline at end of file diff --git a/1094-car-pooling/NOTES.md b/1094-car-pooling/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1094-car-pooling/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1094-car-pooling/README.md b/1094-car-pooling/README.md new file mode 100644 index 0000000..a51c026 --- /dev/null +++ b/1094-car-pooling/README.md @@ -0,0 +1,30 @@ +

1094. Car Pooling

Medium


There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).

+ +

You are given the integer capacity and an array trips where trip[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location.

+ +

Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
+Output: false
+
+ +

Example 2:

+ +
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= trips.length <= 1000
  • +
  • trips[i].length == 3
  • +
  • 1 <= numPassengersi <= 100
  • +
  • 0 <= fromi < toi <= 1000
  • +
  • 1 <= capacity <= 105
  • +
+
\ No newline at end of file diff --git a/11-container-with-most-water/11-container-with-most-water.cpp b/11-container-with-most-water/11-container-with-most-water.cpp new file mode 100644 index 0000000..c321884 --- /dev/null +++ b/11-container-with-most-water/11-container-with-most-water.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int maxArea(vector& height) { + int i = 0; + int j = height.size() - 1; + int ans = 0; + while(j>i) + { + ans = max(ans,(j-i)*( min(height[i],height[j]) ) ); + if(height[i]<= height[j]) + i++; + else + j--; + } + return ans; + } +}; \ No newline at end of file diff --git a/11-container-with-most-water/NOTES.md b/11-container-with-most-water/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/11-container-with-most-water/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/11-container-with-most-water/README.md b/11-container-with-most-water/README.md new file mode 100644 index 0000000..fcf8ccc --- /dev/null +++ b/11-container-with-most-water/README.md @@ -0,0 +1,31 @@ +

11. Container With Most Water

Medium


You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

+ +

Find two lines that together with the x-axis form a container, such that the container contains the most water.

+ +

Return the maximum amount of water a container can store.

+ +

Notice that you may not slant the container.

+ +

 

+

Example 1:

+ +
Input: height = [1,8,6,2,5,4,8,3,7]
+Output: 49
+Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
+
+ +

Example 2:

+ +
Input: height = [1,1]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • n == height.length
  • +
  • 2 <= n <= 105
  • +
  • 0 <= height[i] <= 104
  • +
+
\ No newline at end of file diff --git a/110-balanced-binary-tree/110-balanced-binary-tree.cpp b/110-balanced-binary-tree/110-balanced-binary-tree.cpp new file mode 100644 index 0000000..b13df18 --- /dev/null +++ b/110-balanced-binary-tree/110-balanced-binary-tree.cpp @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + int isBalHelper(TreeNode * root) + { + if(root == NULL)return 0; + + int l = isBalHelper(root->left); + int r = isBalHelper(root->right); + + if(l != -1 && r != -1 && abs(l-r) <= 1) + return 1 + max(l,r); + return -1; + } + + bool isBalanced(TreeNode* root) { + if(root == NULL )return true; + int ans = isBalHelper(root); + + if(ans == -1) + return false; + return true; + } +}; \ No newline at end of file diff --git a/110-balanced-binary-tree/NOTES.md b/110-balanced-binary-tree/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/110-balanced-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/110-balanced-binary-tree/README.md b/110-balanced-binary-tree/README.md new file mode 100644 index 0000000..ef9bb64 --- /dev/null +++ b/110-balanced-binary-tree/README.md @@ -0,0 +1,35 @@ +

110. Balanced Binary Tree

Easy


Given a binary tree, determine if it is height-balanced.

+ +

For this problem, a height-balanced binary tree is defined as:

+ +
+

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

+
+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: true
+
+ +

Example 2:

+ +
Input: root = [1,2,2,3,3,null,null,4,4]
+Output: false
+
+ +

Example 3:

+ +
Input: root = []
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 5000].
  • +
  • -104 <= Node.val <= 104
  • +
+
\ No newline at end of file diff --git a/1111-maximum-nesting-depth-of-two-valid-parentheses-strings/NOTES.md b/1111-maximum-nesting-depth-of-two-valid-parentheses-strings/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1111-maximum-nesting-depth-of-two-valid-parentheses-strings/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1111-maximum-nesting-depth-of-two-valid-parentheses-strings/README.md b/1111-maximum-nesting-depth-of-two-valid-parentheses-strings/README.md new file mode 100644 index 0000000..f4f367a --- /dev/null +++ b/1111-maximum-nesting-depth-of-two-valid-parentheses-strings/README.md @@ -0,0 +1,46 @@ +

1111. Maximum Nesting Depth of Two Valid Parentheses Strings

Medium


A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" characters only, and:

+ +
    +
  • It is the empty string, or
  • +
  • It can be written as AB (A concatenated with B), where A and B are VPS's, or
  • +
  • It can be written as (A), where A is a VPS.
  • +
+ +

We can similarly define the nesting depth depth(S) of any VPS S as follows:

+ +
    +
  • depth("") = 0
  • +
  • depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's
  • +
  • depth("(" + A + ")") = 1 + depth(A), where A is a VPS.
  • +
+ +

For example,  """()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.

+ +

 

+ +

Given a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length).

+ +

Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value.

+ +

Return an answer array (of length seq.length) that encodes such a choice of A and Banswer[i] = 0 if seq[i] is part of A, else answer[i] = 1.  Note that even though multiple answers may exist, you may return any of them.

+ +

 

+

Example 1:

+ +
Input: seq = "(()())"
+Output: [0,1,1,1,1,0]
+
+ +

Example 2:

+ +
Input: seq = "()(())()"
+Output: [0,0,0,1,1,0,1,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= seq.size <= 10000
  • +
+
\ No newline at end of file diff --git a/114-flatten-binary-tree-to-linked-list/114-flatten-binary-tree-to-linked-list.cpp b/114-flatten-binary-tree-to-linked-list/114-flatten-binary-tree-to-linked-list.cpp new file mode 100644 index 0000000..4784c06 --- /dev/null +++ b/114-flatten-binary-tree-to-linked-list/114-flatten-binary-tree-to-linked-list.cpp @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + void flatten(TreeNode* root) { + + TreeNode * curr = root; + while(curr != NULL) + { + if(curr->left) + { + TreeNode * prev = curr->left; + while(prev->right) + { + prev = prev->right; + } + prev->right = curr->right; + curr->right = curr->left; + curr->left = NULL; + + } + curr = curr->right; + + } + + return ; + } +}; \ No newline at end of file diff --git a/114-flatten-binary-tree-to-linked-list/NOTES.md b/114-flatten-binary-tree-to-linked-list/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/114-flatten-binary-tree-to-linked-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/114-flatten-binary-tree-to-linked-list/README.md b/114-flatten-binary-tree-to-linked-list/README.md new file mode 100644 index 0000000..03e1f9d --- /dev/null +++ b/114-flatten-binary-tree-to-linked-list/README.md @@ -0,0 +1,36 @@ +

114. Flatten Binary Tree to Linked List

Medium


Given the root of a binary tree, flatten the tree into a "linked list":

+ +
    +
  • The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
  • +
  • The "linked list" should be in the same order as a pre-order traversal of the binary tree.
  • +
+ +

 

+

Example 1:

+ +
Input: root = [1,2,5,3,4,null,6]
+Output: [1,null,2,null,3,null,4,null,5,null,6]
+
+ +

Example 2:

+ +
Input: root = []
+Output: []
+
+ +

Example 3:

+ +
Input: root = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 2000].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+Follow up: Can you flatten the tree in-place (with O(1) extra space)?
\ No newline at end of file diff --git a/115-distinct-subsequences/115-distinct-subsequences.cpp b/115-distinct-subsequences/115-distinct-subsequences.cpp new file mode 100644 index 0000000..592d334 --- /dev/null +++ b/115-distinct-subsequences/115-distinct-subsequences.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + +int count(string &s, string &t, int i, int j,vector>& dp) +{ + if( j < 0) + { + return 1; + } + if(i < 0) + return 0; + if(dp[i][j] != -1)return dp[i][j]; + + if(s[i] == t[j]) + { + return dp[i][j] = (count(s,t,i-1,j-1,dp) + count(s,t,i-1,j,dp)); + } + else + return dp[i][j] = count(s,t,i-1,j,dp); +} + int numDistinct(string s, string t) { + int ls = s.size(); + int lt = t.size(); + vector> dp(ls+1,vector (lt+1,-1)); + return count(s,t,ls-1,lt-1,dp); + } +}; \ No newline at end of file diff --git a/115-distinct-subsequences/NOTES.md b/115-distinct-subsequences/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/115-distinct-subsequences/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/115-distinct-subsequences/README.md b/115-distinct-subsequences/README.md new file mode 100644 index 0000000..b48c71b --- /dev/null +++ b/115-distinct-subsequences/README.md @@ -0,0 +1,38 @@ +

115. Distinct Subsequences

Hard


Given two strings s and t, return the number of distinct subsequences of s which equals t.

+ +

A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., "ACE" is a subsequence of "ABCDE" while "AEC" is not).

+ +

The test cases are generated so that the answer fits on a 32-bit signed integer.

+ +

 

+

Example 1:

+ +
Input: s = "rabbbit", t = "rabbit"
+Output: 3
+Explanation:
+As shown below, there are 3 ways you can generate "rabbit" from S.
+rabbbit
+rabbbit
+rabbbit
+
+ +

Example 2:

+ +
Input: s = "babgbag", t = "bag"
+Output: 5
+Explanation:
+As shown below, there are 5 ways you can generate "bag" from S.
+babgbag
+babgbag
+babgbag
+babgbag
+babgbag
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length, t.length <= 1000
  • +
  • s and t consist of English letters.
  • +
+
\ No newline at end of file diff --git a/116-populating-next-right-pointers-in-each-node/NOTES.md b/116-populating-next-right-pointers-in-each-node/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/116-populating-next-right-pointers-in-each-node/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/116-populating-next-right-pointers-in-each-node/README.md b/116-populating-next-right-pointers-in-each-node/README.md new file mode 100644 index 0000000..99d6a63 --- /dev/null +++ b/116-populating-next-right-pointers-in-each-node/README.md @@ -0,0 +1,44 @@ +

116. Populating Next Right Pointers in Each Node

Medium


You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

+ +
struct Node {
+  int val;
+  Node *left;
+  Node *right;
+  Node *next;
+}
+
+ +

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

+ +

Initially, all next pointers are set to NULL.

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3,4,5,6,7]
+Output: [1,#,2,3,#,4,5,6,7,#]
+Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
+
+ +

Example 2:

+ +
Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 212 - 1].
  • +
  • -1000 <= Node.val <= 1000
  • +
+ +

 

+

Follow-up:

+ +
    +
  • You may only use constant extra space.
  • +
  • The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
  • +
+
\ No newline at end of file diff --git a/118-pascals-triangle/NOTES.md b/118-pascals-triangle/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/118-pascals-triangle/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/118-pascals-triangle/README.md b/118-pascals-triangle/README.md new file mode 100644 index 0000000..9750c83 --- /dev/null +++ b/118-pascals-triangle/README.md @@ -0,0 +1,19 @@ +

118. Pascal's Triangle

Easy


Given an integer numRows, return the first numRows of Pascal's triangle.

+ +

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

+ +

 

+

Example 1:

+
Input: numRows = 5
+Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
+

Example 2:

+
Input: numRows = 1
+Output: [[1]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= numRows <= 30
  • +
+
\ No newline at end of file diff --git a/120-triangle/120-triangle.cpp b/120-triangle/120-triangle.cpp new file mode 100644 index 0000000..a3db30e --- /dev/null +++ b/120-triangle/120-triangle.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int minimumTotal(vector>& triangle) { + int n = triangle.size(); + + vector> dp(n,vector (n,0)); + int ans = INT_MAX; + for(int i=0;i120. Triangle

Medium


Given a triangle array, return the minimum path sum from top to bottom.

+ +

For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.

+ +

 

+

Example 1:

+ +
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
+Output: 11
+Explanation: The triangle looks like:
+   2
+  3 4
+ 6 5 7
+4 1 8 3
+The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
+
+ +

Example 2:

+ +
Input: triangle = [[-10]]
+Output: -10
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= triangle.length <= 200
  • +
  • triangle[0].length == 1
  • +
  • triangle[i].length == triangle[i - 1].length + 1
  • +
  • -104 <= triangle[i][j] <= 104
  • +
+ +

 

+Follow up: Could you do this using only O(n) extra space, where n is the total number of rows in the triangle?
\ No newline at end of file diff --git a/121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.cpp b/121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.cpp new file mode 100644 index 0000000..64fe2cf --- /dev/null +++ b/121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int maxProfit(vector& prices) { + + int lsf = INT_MAX; // least so far + int op = 0; // overall profit + int pist = 0; // profit if sold today + + for(int i = 0; i < prices.size(); i++){ + if(prices[i] < lsf){ // if we found new buy value which is more smaller then previous one + lsf = prices[i]; // update our least so far + } + pist = prices[i] - lsf; // calculating profit if sold today by, Buy - sell + if(op < pist){ // if pist is more then our previous overall profit + op = pist; // update overall profit + } + } + return op; // return op + + } +}; \ No newline at end of file diff --git a/121-best-time-to-buy-and-sell-stock/NOTES.md b/121-best-time-to-buy-and-sell-stock/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/121-best-time-to-buy-and-sell-stock/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/121-best-time-to-buy-and-sell-stock/README.md b/121-best-time-to-buy-and-sell-stock/README.md new file mode 100644 index 0000000..9350a49 --- /dev/null +++ b/121-best-time-to-buy-and-sell-stock/README.md @@ -0,0 +1,30 @@ +

121. Best Time to Buy and Sell Stock

Easy


You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

+ +

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

+ +

 

+

Example 1:

+ +
Input: prices = [7,1,5,3,6,4]
+Output: 5
+Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
+Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
+
+ +

Example 2:

+ +
Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: In this case, no transactions are done and the max profit = 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 105
  • +
  • 0 <= prices[i] <= 104
  • +
+
\ No newline at end of file diff --git a/122-best-time-to-buy-and-sell-stock-ii/122-best-time-to-buy-and-sell-stock-ii.cpp b/122-best-time-to-buy-and-sell-stock-ii/122-best-time-to-buy-and-sell-stock-ii.cpp new file mode 100644 index 0000000..9262fa7 --- /dev/null +++ b/122-best-time-to-buy-and-sell-stock-ii/122-best-time-to-buy-and-sell-stock-ii.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int maxProfit(vector& prices) { + int ans = 0; + for(int i=1;i=0) + { + ans += prices[i]-prices[i-1]; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/122-best-time-to-buy-and-sell-stock-ii/NOTES.md b/122-best-time-to-buy-and-sell-stock-ii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/122-best-time-to-buy-and-sell-stock-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/122-best-time-to-buy-and-sell-stock-ii/README.md b/122-best-time-to-buy-and-sell-stock-ii/README.md new file mode 100644 index 0000000..1627b40 --- /dev/null +++ b/122-best-time-to-buy-and-sell-stock-ii/README.md @@ -0,0 +1,39 @@ +

122. Best Time to Buy and Sell Stock II

Medium


You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

+ +

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

+ +

Find and return the maximum profit you can achieve.

+ +

 

+

Example 1:

+ +
Input: prices = [7,1,5,3,6,4]
+Output: 7
+Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
+Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
+Total profit is 4 + 3 = 7.
+
+ +

Example 2:

+ +
Input: prices = [1,2,3,4,5]
+Output: 4
+Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
+Total profit is 4.
+
+ +

Example 3:

+ +
Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 3 * 104
  • +
  • 0 <= prices[i] <= 104
  • +
+
\ No newline at end of file diff --git a/1220-count-vowels-permutation/1220-count-vowels-permutation.cpp b/1220-count-vowels-permutation/1220-count-vowels-permutation.cpp new file mode 100644 index 0000000..56b5a68 --- /dev/null +++ b/1220-count-vowels-permutation/1220-count-vowels-permutation.cpp @@ -0,0 +1,37 @@ +//Matrix exponentiation. +class Solution { +public: + int MOD=1e9+7; + vector> Multiply(vector> &l,vector> &r) + { + vector> result(l.size(),vector(r[0].size(),0)); + for(int i=0;i> M={ {0,1,0,0,0}, + {1,0,1,0,0}, + {1,1,0,1,1}, + {0,0,1,0,1}, + {1,0,0,0,0}},result(5,vector(5)); + for(int i=0;i<5;i++) + result[i][i]=1; + int sum=0; + n--; + while(n) + { + if(n&1) + result=Multiply(M,result); + n>>=1; + M=Multiply(M,M); + } + for(vector &i:result) + for(int &j:i) + sum+=j,sum%=MOD; + return sum; + } +}; \ No newline at end of file diff --git a/1220-count-vowels-permutation/NOTES.md b/1220-count-vowels-permutation/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1220-count-vowels-permutation/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1220-count-vowels-permutation/README.md b/1220-count-vowels-permutation/README.md new file mode 100644 index 0000000..6e959cb --- /dev/null +++ b/1220-count-vowels-permutation/README.md @@ -0,0 +1,40 @@ +

1220. Count Vowels Permutation

Hard


Given an integer n, your task is to count how many strings of length n can be formed under the following rules:

+ +
    +
  • Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u')
  • +
  • Each vowel 'a' may only be followed by an 'e'.
  • +
  • Each vowel 'e' may only be followed by an 'a' or an 'i'.
  • +
  • Each vowel 'i' may not be followed by another 'i'.
  • +
  • Each vowel 'o' may only be followed by an 'i' or a 'u'.
  • +
  • Each vowel 'u' may only be followed by an 'a'.
  • +
+ +

Since the answer may be too large, return it modulo 10^9 + 7.

+ +

 

+

Example 1:

+ +
Input: n = 1
+Output: 5
+Explanation: All possible strings are: "a", "e", "i" , "o" and "u".
+
+ +

Example 2:

+ +
Input: n = 2
+Output: 10
+Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua".
+
+ +

Example 3: 

+ +
Input: n = 5
+Output: 68
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 2 * 10^4
  • +
+
\ No newline at end of file diff --git a/123-best-time-to-buy-and-sell-stock-iii/123-best-time-to-buy-and-sell-stock-iii.cpp b/123-best-time-to-buy-and-sell-stock-iii/123-best-time-to-buy-and-sell-stock-iii.cpp new file mode 100644 index 0000000..7068a8b --- /dev/null +++ b/123-best-time-to-buy-and-sell-stock-iii/123-best-time-to-buy-and-sell-stock-iii.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + + int rec(vector& prices,int transactions,int buy,int i,vector>> & dp) + { + if(transactions == 0 || i == prices.size())return 0; + if(dp[i][buy][transactions] != -1 )return dp[i][buy][transactions]; + if(buy) + { + return dp[i][buy][transactions] = max(-prices[i] + rec(prices,transactions,0,i+1,dp) , rec(prices,transactions,1,i+1,dp)); + } + else + { + return dp[i][buy][transactions] = max(prices[i]+rec(prices,transactions-1,1,i+1,dp) , rec(prices,transactions,0,i+1,dp)); + } + } + + int maxProfit(vector& prices) { + vector>> dp(prices.size(), vector> (2,vector (3,-1))); + return rec(prices,2,1,0,dp); + } +}; \ No newline at end of file diff --git a/123-best-time-to-buy-and-sell-stock-iii/NOTES.md b/123-best-time-to-buy-and-sell-stock-iii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/123-best-time-to-buy-and-sell-stock-iii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/123-best-time-to-buy-and-sell-stock-iii/README.md b/123-best-time-to-buy-and-sell-stock-iii/README.md new file mode 100644 index 0000000..6303c52 --- /dev/null +++ b/123-best-time-to-buy-and-sell-stock-iii/README.md @@ -0,0 +1,37 @@ +

123. Best Time to Buy and Sell Stock III

Hard


You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

Find the maximum profit you can achieve. You may complete at most two transactions.

+ +

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

+ +

 

+

Example 1:

+ +
Input: prices = [3,3,5,0,0,3,1,4]
+Output: 6
+Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
+Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
+ +

Example 2:

+ +
Input: prices = [1,2,3,4,5]
+Output: 4
+Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
+Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
+
+ +

Example 3:

+ +
Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: In this case, no transaction is done, i.e. max profit = 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 105
  • +
  • 0 <= prices[i] <= 105
  • +
+
\ No newline at end of file diff --git a/1249-minimum-remove-to-make-valid-parentheses/1249-minimum-remove-to-make-valid-parentheses.cpp b/1249-minimum-remove-to-make-valid-parentheses/1249-minimum-remove-to-make-valid-parentheses.cpp new file mode 100644 index 0000000..625d73c --- /dev/null +++ b/1249-minimum-remove-to-make-valid-parentheses/1249-minimum-remove-to-make-valid-parentheses.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + string minRemoveToMakeValid(string s) { + stack st; + for (auto i = 0; i < s.size(); ++i) { + if (s[i] == '(') st.push(i); + if (s[i] == ')') { + if (!st.empty()) st.pop(); + else s[i] = '*'; + } + } + while (!st.empty()) { + s[st.top()] = '*'; + st.pop(); + } + s.erase(remove(s.begin(), s.end(), '*'), s.end()); + return s; +} +}; \ No newline at end of file diff --git a/1249-minimum-remove-to-make-valid-parentheses/README.md b/1249-minimum-remove-to-make-valid-parentheses/README.md new file mode 100644 index 0000000..a7562ff --- /dev/null +++ b/1249-minimum-remove-to-make-valid-parentheses/README.md @@ -0,0 +1,41 @@ +

1249. Minimum Remove to Make Valid Parentheses

Medium


Given a string s of '(' , ')' and lowercase English characters.

+ +

Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.

+ +

Formally, a parentheses string is valid if and only if:

+ +
    +
  • It is the empty string, contains only lowercase characters, or
  • +
  • It can be written as AB (A concatenated with B), where A and B are valid strings, or
  • +
  • It can be written as (A), where A is a valid string.
  • +
+ +

 

+

Example 1:

+ +
Input: s = "lee(t(c)o)de)"
+Output: "lee(t(c)o)de"
+Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.
+
+ +

Example 2:

+ +
Input: s = "a)b(c)d"
+Output: "ab(c)d"
+
+ +

Example 3:

+ +
Input: s = "))(("
+Output: ""
+Explanation: An empty string is also valid.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s[i] is either'(' , ')', or lowercase English letter.
  • +
+
\ No newline at end of file diff --git a/126-word-ladder-ii/126-word-ladder-ii.cpp b/126-word-ladder-ii/126-word-ladder-ii.cpp new file mode 100644 index 0000000..8124bc1 --- /dev/null +++ b/126-word-ladder-ii/126-word-ladder-ii.cpp @@ -0,0 +1,68 @@ +class Solution { +public: + vector> findLadders(string beginWord, string endWord, vector& wordList) { + unordered_set dict(wordList.begin(), wordList.end()); + if(!dict.count(endWord)) return {}; + dict.erase(beginWord); + dict.erase(endWord); + unordered_map steps; + steps[beginWord] = 0; + unordered_map > parents; + const int len = beginWord.size(); + int step = 0; + bool found = false; + queue q; + q.push(beginWord); + while(!q.empty() && !found){ + ++step; + for(int size = q.size(); size > 0; size--){ + const string p = q.front(); q.pop(); + string word = p; + for(int j = 0; j < len; j++){ + const char ch = word[j]; + for(int i = 'a'; i <= 'z'; i++){ + if(i == ch) continue; + word[j] = i; + if(word == endWord){ + found = true; + parents[word].push_back(p); + }else{ + if(steps.count(word) && step == steps.at(word) - 1) + parents[word].push_back(p); + } + if(!dict.count(word)) continue; + dict.erase(word); + q.push(word); + steps[word] = step + 1; + parents[word].push_back(p); + } + word[j] = ch; + } + } + } + + vector> ans; + if(found){ + vector path; path.push_back(endWord); + genPath(parents, endWord, beginWord, path, ans); + } + return ans; + } + + void genPath(const unordered_map >& parents, + const string& currWord, + const string& beginWord, + vector path, + vector>& ans){ + if(currWord == beginWord){ + ans.push_back(vector (path.rbegin(), path.rend())); + return; + } + + for(const auto p: parents.at(currWord)){ + path.push_back(p); + genPath(parents, p, beginWord, path, ans); + path.pop_back(); + } + } +}; \ No newline at end of file diff --git a/126-word-ladder-ii/NOTES.md b/126-word-ladder-ii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/126-word-ladder-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/126-word-ladder-ii/README.md b/126-word-ladder-ii/README.md new file mode 100644 index 0000000..0f47ef8 --- /dev/null +++ b/126-word-ladder-ii/README.md @@ -0,0 +1,40 @@ +

126. Word Ladder II

Hard


A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:

+ +
    +
  • Every adjacent pair of words differs by a single letter.
  • +
  • Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
  • +
  • sk == endWord
  • +
+ +

Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].

+ +

 

+

Example 1:

+ +
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
+Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
+Explanation: There are 2 shortest transformation sequences:
+"hit" -> "hot" -> "dot" -> "dog" -> "cog"
+"hit" -> "hot" -> "lot" -> "log" -> "cog"
+
+ +

Example 2:

+ +
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
+Output: []
+Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= beginWord.length <= 5
  • +
  • endWord.length == beginWord.length
  • +
  • 1 <= wordList.length <= 500
  • +
  • wordList[i].length == beginWord.length
  • +
  • beginWord, endWord, and wordList[i] consist of lowercase English letters.
  • +
  • beginWord != endWord
  • +
  • All the words in wordList are unique.
  • +
+
\ No newline at end of file diff --git a/127-word-ladder/127-word-ladder.cpp b/127-word-ladder/127-word-ladder.cpp new file mode 100644 index 0000000..77e1755 --- /dev/null +++ b/127-word-ladder/127-word-ladder.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + unordered_set dict(wordList.begin(), wordList.end()); + queue todo; + todo.push(beginWord); + int ladder = 1; + while (!todo.empty()) { + int n = todo.size(); + for (int i = 0; i < n; i++) { + string word = todo.front(); + todo.pop(); + if (word == endWord) { + return ladder; + } + dict.erase(word); + for (int j = 0; j < word.size(); j++) { + char c = word[j]; + for (int k = 0; k < 26; k++) { + word[j] = 'a' + k; + if (dict.find(word) != dict.end()) { + todo.push(word); + } + } + word[j] = c; + } + } + ladder++; + } + return 0; + } +}; \ No newline at end of file diff --git a/127-word-ladder/NOTES.md b/127-word-ladder/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/127-word-ladder/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/127-word-ladder/README.md b/127-word-ladder/README.md new file mode 100644 index 0000000..b7bf23a --- /dev/null +++ b/127-word-ladder/README.md @@ -0,0 +1,38 @@ +

127. Word Ladder

Hard


A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:

+ +
    +
  • Every adjacent pair of words differs by a single letter.
  • +
  • Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
  • +
  • sk == endWord
  • +
+ +

Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.

+ +

 

+

Example 1:

+ +
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
+Output: 5
+Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.
+
+ +

Example 2:

+ +
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
+Output: 0
+Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= beginWord.length <= 10
  • +
  • endWord.length == beginWord.length
  • +
  • 1 <= wordList.length <= 5000
  • +
  • wordList[i].length == beginWord.length
  • +
  • beginWord, endWord, and wordList[i] consist of lowercase English letters.
  • +
  • beginWord != endWord
  • +
  • All the words in wordList are unique.
  • +
+
\ No newline at end of file diff --git a/1283-find-the-smallest-divisor-given-a-threshold/1283-find-the-smallest-divisor-given-a-threshold.cpp b/1283-find-the-smallest-divisor-given-a-threshold/1283-find-the-smallest-divisor-given-a-threshold.cpp new file mode 100644 index 0000000..a00416c --- /dev/null +++ b/1283-find-the-smallest-divisor-given-a-threshold/1283-find-the-smallest-divisor-given-a-threshold.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int sum(vector& nums,int num) + { + int ans = 0; + for(int i=0;i& nums, int threshold) { + + int maxi = INT_MIN; + + for(auto a:nums){ + if(a>maxi) + maxi = a; + } + + int low =1; + int high = maxi; + + while(low1283. Find the Smallest Divisor Given a Threshold

Medium


Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.

+ +

Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).

+ +

The test cases are generated so that there will be an answer.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,5,9], threshold = 6
+Output: 5
+Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. 
+If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). 
+
+ +

Example 2:

+ +
Input: nums = [44,22,33,11,1], threshold = 5
+Output: 44
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • 1 <= nums[i] <= 106
  • +
  • nums.length <= threshold <= 106
  • +
+
\ No newline at end of file diff --git a/1288-remove-covered-intervals/1288-remove-covered-intervals.cpp b/1288-remove-covered-intervals/1288-remove-covered-intervals.cpp new file mode 100644 index 0000000..3cc152e --- /dev/null +++ b/1288-remove-covered-intervals/1288-remove-covered-intervals.cpp @@ -0,0 +1,33 @@ + // \U0001f609\U0001f609\U0001f609\U0001f609Please upvote if it helps \U0001f609\U0001f609\U0001f609\U0001f609 +class Solution { +public: + int removeCoveredIntervals(vector>& intervals) { + + // sorting the intervals(vector) + sort(intervals.begin(),intervals.end()); + + int x1 = intervals[0][0]; + int x2 = intervals[0][1]; + + int res = 1; //one for x1 and x2; + + // ifa[i][0] && a[i][1] both greater than a[i-1][0] && a[i-1][1] + // increase the cnt. + for(int i= 1; i x1 && intervals[i][1] > x2) + ++res; + + // updating x1 & x2 with next intervals + //as we are comparing from upcoming ones. + if(intervals[i][1] > x2) + { + x1 = intervals[i][0]; + x2 = intervals [i][1]; + } + } + + return res; // return cnt + } + +}; \ No newline at end of file diff --git a/1288-remove-covered-intervals/NOTES.md b/1288-remove-covered-intervals/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1288-remove-covered-intervals/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1288-remove-covered-intervals/README.md b/1288-remove-covered-intervals/README.md new file mode 100644 index 0000000..4f6dd99 --- /dev/null +++ b/1288-remove-covered-intervals/README.md @@ -0,0 +1,30 @@ +

1288. Remove Covered Intervals

Medium


Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.

+ +

The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.

+ +

Return the number of remaining intervals.

+ +

 

+

Example 1:

+ +
Input: intervals = [[1,4],[3,6],[2,8]]
+Output: 2
+Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
+
+ +

Example 2:

+ +
Input: intervals = [[1,4],[2,3]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= intervals.length <= 1000
  • +
  • intervals[i].length == 2
  • +
  • 0 <= li <= ri <= 105
  • +
  • All the given intervals are unique.
  • +
+
\ No newline at end of file diff --git a/1291-sequential-digits/1291-sequential-digits.cpp b/1291-sequential-digits/1291-sequential-digits.cpp new file mode 100644 index 0000000..0ae06ac --- /dev/null +++ b/1291-sequential-digits/1291-sequential-digits.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector sequentialDigits(int l, int h) { + queue q; + for(int i = 1; i <= 9; i++) { + q.push(i); + } + vector ret; + while(!q.empty()) { + int f = q.front(); + q.pop(); + if(f <= h && f >= l) { + ret.push_back(f); + } + if(f > h) + break; + int num = f % 10; + if(num < 9) { + q.push(f * 10 + (num + 1)); + } + } + return ret; + } +}; \ No newline at end of file diff --git a/1291-sequential-digits/NOTES.md b/1291-sequential-digits/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1291-sequential-digits/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1291-sequential-digits/README.md b/1291-sequential-digits/README.md new file mode 100644 index 0000000..c3dc79c --- /dev/null +++ b/1291-sequential-digits/README.md @@ -0,0 +1,19 @@ +

1291. Sequential Digits

Medium


An integer has sequential digits if and only if each digit in the number is one more than the previous digit.

+ +

Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.

+ +

 

+

Example 1:

+
Input: low = 100, high = 300
+Output: [123,234]
+

Example 2:

+
Input: low = 1000, high = 13000
+Output: [1234,2345,3456,4567,5678,6789,12345]
+
+

 

+

Constraints:

+ +
    +
  • 10 <= low <= high <= 10^9
  • +
+
\ No newline at end of file diff --git a/13-Roman-to-Integer/13-roman-to-integer.cpp b/13-Roman-to-Integer/13-roman-to-integer.cpp new file mode 100644 index 0000000..e982b04 --- /dev/null +++ b/13-Roman-to-Integer/13-roman-to-integer.cpp @@ -0,0 +1,28 @@ +class Solution { +public: +int romanToInt(string s) +{ + unordered_map T = { { 'I' , 1 }, + { 'V' , 5 }, + { 'X' , 10 }, + { 'L' , 50 }, + { 'C' , 100 }, + { 'D' , 500 }, + { 'M' , 1000 } }; + + int sum = T[s.back()]; + for (int i = s.length() - 2; i >= 0; --i) + { + if (T[s[i]] < T[s[i + 1]]) + { + sum -= T[s[i]]; + } + else + { + sum += T[s[i]]; + } + } + + return sum; +} +}; \ No newline at end of file diff --git a/13-Roman-to-Integer/NOTES.md b/13-Roman-to-Integer/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/13-Roman-to-Integer/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1305-all-elements-in-two-binary-search-trees/1305-all-elements-in-two-binary-search-trees.cpp b/1305-all-elements-in-two-binary-search-trees/1305-all-elements-in-two-binary-search-trees.cpp new file mode 100644 index 0000000..2d2ead2 --- /dev/null +++ b/1305-all-elements-in-two-binary-search-trees/1305-all-elements-in-two-binary-search-trees.cpp @@ -0,0 +1,60 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + void inOrderTraverse(TreeNode *root, vector& vec) + { + if(root) + { + inOrderTraverse(root->left, vec); + vec.push_back(root->val); + inOrderTraverse(root->right, vec); + + } + } + void mergeVectors(vector vec1, vector vec2, vector& mergedVectors) + { + int i = 0, j = 0, k = 0; + + // Traverse both array + while (i < vec1.size() && j < vec2.size()) + { + + if (vec1[i] < vec2[j]) + mergedVectors[k++] = vec1[i++]; + else + mergedVectors[k++] = vec2[j++]; + } + + + while (i < vec1.size()) + mergedVectors[k++] = vec1[i++]; + + + while (j < vec2.size()) + mergedVectors[k++] = vec2[j++]; + + + } + + vector getAllElements(TreeNode* root1, TreeNode* root2) { + vector v1; + vector v2; + inOrderTraverse(root1, v1); + inOrderTraverse(root2, v2); + + vector mergedVectors(v1.size() + v2.size()); + + mergeVectors(v1, v2, mergedVectors); + return mergedVectors; + } +}; \ No newline at end of file diff --git a/1305-all-elements-in-two-binary-search-trees/NOTES.md b/1305-all-elements-in-two-binary-search-trees/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1305-all-elements-in-two-binary-search-trees/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1305-all-elements-in-two-binary-search-trees/README.md b/1305-all-elements-in-two-binary-search-trees/README.md new file mode 100644 index 0000000..b199713 --- /dev/null +++ b/1305-all-elements-in-two-binary-search-trees/README.md @@ -0,0 +1,23 @@ +

1305. All Elements in Two Binary Search Trees

Medium


Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.

+ +

 

+

Example 1:

+ +
Input: root1 = [2,1,4], root2 = [1,0,3]
+Output: [0,1,1,2,3,4]
+
+ +

Example 2:

+ +
Input: root1 = [1,null,8], root2 = [8,1]
+Output: [1,1,8,8]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in each tree is in the range [0, 5000].
  • +
  • -105 <= Node.val <= 105
  • +
+
\ No newline at end of file diff --git a/131-palindrome-partitioning/131-palindrome-partitioning.cpp b/131-palindrome-partitioning/131-palindrome-partitioning.cpp new file mode 100644 index 0000000..31604cf --- /dev/null +++ b/131-palindrome-partitioning/131-palindrome-partitioning.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + + bool isPalindrome(string s, int start, int end) { + while(start <= end) { + if(s[start++] != s[end--]) + return false; + } + return true; + } + + void solve( vector> & ans,vector& temp,int index,string s) + { + if(index == s.size()) + { + ans.push_back(temp); + return; + } + + + for(int i=index;i "<> partition(string s) { + vector> ans; + vector temp; + solve(ans,temp,0,s); + return ans; + } +}; \ No newline at end of file diff --git a/131-palindrome-partitioning/NOTES.md b/131-palindrome-partitioning/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/131-palindrome-partitioning/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/131-palindrome-partitioning/README.md b/131-palindrome-partitioning/README.md new file mode 100644 index 0000000..0ab9fa3 --- /dev/null +++ b/131-palindrome-partitioning/README.md @@ -0,0 +1,20 @@ +

131. Palindrome Partitioning

Medium


Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

+ +

A palindrome string is a string that reads the same backward as forward.

+ +

 

+

Example 1:

+
Input: s = "aab"
+Output: [["a","a","b"],["aa","b"]]
+

Example 2:

+
Input: s = "a"
+Output: [["a"]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 16
  • +
  • s contains only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/133-clone-graph/NOTES.md b/133-clone-graph/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/133-clone-graph/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/133-clone-graph/README.md b/133-clone-graph/README.md new file mode 100644 index 0000000..65ef7c6 --- /dev/null +++ b/133-clone-graph/README.md @@ -0,0 +1,59 @@ +

133. Clone Graph

Medium


Given a reference of a node in a connected undirected graph.

+ +

Return a deep copy (clone) of the graph.

+ +

Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.

+ +
class Node {
+    public int val;
+    public List<Node> neighbors;
+}
+
+ +

 

+ +

Test case format:

+ +

For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.

+ +

An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.

+ +

The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.

+ +

 

+

Example 1:

+ +
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
+Output: [[2,4],[1,3],[2,4],[1,3]]
+Explanation: There are 4 nodes in the graph.
+1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
+2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
+3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
+4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
+
+ +

Example 2:

+ +
Input: adjList = [[]]
+Output: [[]]
+Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
+
+ +

Example 3:

+ +
Input: adjList = []
+Output: []
+Explanation: This an empty graph, it does not have any nodes.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the graph is in the range [0, 100].
  • +
  • 1 <= Node.val <= 100
  • +
  • Node.val is unique for each node.
  • +
  • There are no repeated edges and no self-loops in the graph.
  • +
  • The Graph is connected and all nodes can be visited starting from the given node.
  • +
+
\ No newline at end of file diff --git a/1337-the-k-weakest-rows-in-a-matrix/1337-the-k-weakest-rows-in-a-matrix.cpp b/1337-the-k-weakest-rows-in-a-matrix/1337-the-k-weakest-rows-in-a-matrix.cpp new file mode 100644 index 0000000..7c0993f --- /dev/null +++ b/1337-the-k-weakest-rows-in-a-matrix/1337-the-k-weakest-rows-in-a-matrix.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + vector kWeakestRows(vector>& mat, int k) { + + int n = mat.size(); + int col = mat[0].size(); + map> m; + for(int i=0;i ans; + for(auto it = m.begin();it != m.end(); it++) + { + if(k >= it->second.size()) + { + for(int i=0;isecond.size();i++) + ans.push_back(it->second[i]); + } + else + { + for(int i=0;isecond[i]); + } + break; + } + k = k - it->second.size(); + } + return ans; + } +}; \ No newline at end of file diff --git a/1337-the-k-weakest-rows-in-a-matrix/NOTES.md b/1337-the-k-weakest-rows-in-a-matrix/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1337-the-k-weakest-rows-in-a-matrix/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1337-the-k-weakest-rows-in-a-matrix/README.md b/1337-the-k-weakest-rows-in-a-matrix/README.md new file mode 100644 index 0000000..38d0c1e --- /dev/null +++ b/1337-the-k-weakest-rows-in-a-matrix/README.md @@ -0,0 +1,61 @@ +

1337. The K Weakest Rows in a Matrix

Easy


You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.

+ +

A row i is weaker than a row j if one of the following is true:

+ +
    +
  • The number of soldiers in row i is less than the number of soldiers in row j.
  • +
  • Both rows have the same number of soldiers and i < j.
  • +
+ +

Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.

+ +

 

+

Example 1:

+ +
Input: mat = 
+[[1,1,0,0,0],
+ [1,1,1,1,0],
+ [1,0,0,0,0],
+ [1,1,0,0,0],
+ [1,1,1,1,1]], 
+k = 3
+Output: [2,0,3]
+Explanation: 
+The number of soldiers in each row is: 
+- Row 0: 2 
+- Row 1: 4 
+- Row 2: 1 
+- Row 3: 2 
+- Row 4: 5 
+The rows ordered from weakest to strongest are [2,0,3,1,4].
+
+ +

Example 2:

+ +
Input: mat = 
+[[1,0,0,0],
+ [1,1,1,1],
+ [1,0,0,0],
+ [1,0,0,0]], 
+k = 2
+Output: [0,2]
+Explanation: 
+The number of soldiers in each row is: 
+- Row 0: 1 
+- Row 1: 4 
+- Row 2: 1 
+- Row 3: 1 
+The rows ordered from weakest to strongest are [0,2,3,1].
+
+ +

 

+

Constraints:

+ +
    +
  • m == mat.length
  • +
  • n == mat[i].length
  • +
  • 2 <= n, m <= 100
  • +
  • 1 <= k <= m
  • +
  • matrix[i][j] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/134-gas-station/NOTES.md b/134-gas-station/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/134-gas-station/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/134-gas-station/README.md b/134-gas-station/README.md new file mode 100644 index 0000000..0969b0a --- /dev/null +++ b/134-gas-station/README.md @@ -0,0 +1,44 @@ +

134. Gas Station

Medium


There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].

+ +

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.

+ +

Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique

+ +

 

+

Example 1:

+ +
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
+Output: 3
+Explanation:
+Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
+Travel to station 4. Your tank = 4 - 1 + 5 = 8
+Travel to station 0. Your tank = 8 - 2 + 1 = 7
+Travel to station 1. Your tank = 7 - 3 + 2 = 6
+Travel to station 2. Your tank = 6 - 4 + 3 = 5
+Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
+Therefore, return 3 as the starting index.
+
+ +

Example 2:

+ +
Input: gas = [2,3,4], cost = [3,4,3]
+Output: -1
+Explanation:
+You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
+Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
+Travel to station 0. Your tank = 4 - 3 + 2 = 3
+Travel to station 1. Your tank = 3 - 3 + 3 = 3
+You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
+Therefore, you can't travel around the circuit once no matter where you start.
+
+ +

 

+

Constraints:

+ +
    +
  • gas.length == n
  • +
  • cost.length == n
  • +
  • 1 <= n <= 105
  • +
  • 0 <= gas[i], cost[i] <= 104
  • +
+
\ No newline at end of file diff --git a/1359-count-all-valid-pickup-and-delivery-options/1359-count-all-valid-pickup-and-delivery-options.cpp b/1359-count-all-valid-pickup-and-delivery-options/1359-count-all-valid-pickup-and-delivery-options.cpp new file mode 100644 index 0000000..a0e6047 --- /dev/null +++ b/1359-count-all-valid-pickup-and-delivery-options/1359-count-all-valid-pickup-and-delivery-options.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int countOrders(int n) { + long res = 1, mod = 1000000007; + for(int i = 1; i <=n; ++i) + { + res *= i; + res %= mod; + res *= (2*i-1); + res %= mod; + } + return res % mod; + } +}; \ No newline at end of file diff --git a/1359-count-all-valid-pickup-and-delivery-options/README.md b/1359-count-all-valid-pickup-and-delivery-options/README.md new file mode 100644 index 0000000..5124350 --- /dev/null +++ b/1359-count-all-valid-pickup-and-delivery-options/README.md @@ -0,0 +1,36 @@ +

1359. Count All Valid Pickup and Delivery Options

Hard


Given n orders, each order consist in pickup and delivery services. 

+ +

Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). 

+ +

Since the answer may be too large, return it modulo 10^9 + 7.

+ +

 

+

Example 1:

+ +
Input: n = 1
+Output: 1
+Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
+
+ +

Example 2:

+ +
Input: n = 2
+Output: 6
+Explanation: All possible orders: 
+(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
+This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
+
+ +

Example 3:

+ +
Input: n = 3
+Output: 90
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 500
  • +
+
\ No newline at end of file diff --git a/136-single-number/136-single-number.cpp b/136-single-number/136-single-number.cpp new file mode 100644 index 0000000..865a287 --- /dev/null +++ b/136-single-number/136-single-number.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int singleNumber(vector& nums) { + int a = 0; + for(auto d:nums) + a^=d; + return a; + } +}; \ No newline at end of file diff --git a/136-single-number/README.md b/136-single-number/README.md new file mode 100644 index 0000000..6ca2f18 --- /dev/null +++ b/136-single-number/README.md @@ -0,0 +1,24 @@ +

136. Single Number

Easy


Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

+ +

You must implement a solution with a linear runtime complexity and use only constant extra space.

+ +

 

+

Example 1:

+
Input: nums = [2,2,1]
+Output: 1
+

Example 2:

+
Input: nums = [4,1,2,1,2]
+Output: 4
+

Example 3:

+
Input: nums = [1]
+Output: 1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -3 * 104 <= nums[i] <= 3 * 104
  • +
  • Each element in the array appears twice except for one element which appears only once.
  • +
+
\ No newline at end of file diff --git a/138-copy-list-with-random-pointer/138-copy-list-with-random-pointer.cpp b/138-copy-list-with-random-pointer/138-copy-list-with-random-pointer.cpp new file mode 100644 index 0000000..a2c1b70 --- /dev/null +++ b/138-copy-list-with-random-pointer/138-copy-list-with-random-pointer.cpp @@ -0,0 +1,61 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; + + Node(int _val) { + val = _val; + next = NULL; + random = NULL; + } +}; +*/ + +class Solution { +public: + Node* copyRandomList(Node* head) { + + if(head == NULL)return NULL; + + Node * it = head; + Node * front = head; + + while(it != NULL) + { + front = it->next; + Node * newNode = new Node(it->val); + it->next = newNode; + newNode->next = front; + it = front; + } + + it = head; + front = NULL; + while(it != NULL) + { + if(it->random) + { + it->next->random = it->random->next; + } + it = it->next->next; + } + + Node * dummy = new Node(0); + Node * temp = dummy; + + it = head; + while(it != NULL) + { + front = it->next->next; + temp->next = it->next; + it->next = front; + it = front; + temp = temp->next; + } + + return dummy->next; + } +}; \ No newline at end of file diff --git a/138-copy-list-with-random-pointer/NOTES.md b/138-copy-list-with-random-pointer/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/138-copy-list-with-random-pointer/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/138-copy-list-with-random-pointer/README.md b/138-copy-list-with-random-pointer/README.md new file mode 100644 index 0000000..b60daa2 --- /dev/null +++ b/138-copy-list-with-random-pointer/README.md @@ -0,0 +1,47 @@ +

138. Copy List with Random Pointer

Medium


A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.

+ +

Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.

+ +

For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.

+ +

Return the head of the copied linked list.

+ +

The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:

+ +
    +
  • val: an integer representing Node.val
  • +
  • random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.
  • +
+ +

Your code will only be given the head of the original linked list.

+ +

 

+

Example 1:

+ +
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
+Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
+
+ +

Example 2:

+ +
Input: head = [[1,1],[2,1]]
+Output: [[1,1],[2,1]]
+
+ +

Example 3:

+ +

+ +
Input: head = [[3,null],[3,0],[3,null]]
+Output: [[3,null],[3,0],[3,null]]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 1000
  • +
  • -104 <= Node.val <= 104
  • +
  • Node.random is null or is pointing to some node in the linked list.
  • +
+
\ No newline at end of file diff --git a/1381-design-a-stack-with-increment-operation/NOTES.md b/1381-design-a-stack-with-increment-operation/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1381-design-a-stack-with-increment-operation/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1381-design-a-stack-with-increment-operation/README.md b/1381-design-a-stack-with-increment-operation/README.md new file mode 100644 index 0000000..5e2500e --- /dev/null +++ b/1381-design-a-stack-with-increment-operation/README.md @@ -0,0 +1,46 @@ +

1381. Design a Stack With Increment Operation

Medium


Design a stack which supports the following operations.

+ +

Implement the CustomStack class:

+ +
    +
  • CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize.
  • +
  • void push(int x) Adds x to the top of the stack if the stack hasn't reached the maxSize.
  • +
  • int pop() Pops and returns the top of stack or -1 if the stack is empty.
  • +
  • void inc(int k, int val) Increments the bottom k elements of the stack by val. If there are less than k elements in the stack, just increment all the elements in the stack.
  • +
+ +

 

+

Example 1:

+ +
Input
+["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"]
+[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]
+Output
+[null,null,null,2,null,null,null,null,null,103,202,201,-1]
+Explanation
+CustomStack customStack = new CustomStack(3); // Stack is Empty []
+customStack.push(1);                          // stack becomes [1]
+customStack.push(2);                          // stack becomes [1, 2]
+customStack.pop();                            // return 2 --> Return top of the stack 2, stack becomes [1]
+customStack.push(2);                          // stack becomes [1, 2]
+customStack.push(3);                          // stack becomes [1, 2, 3]
+customStack.push(4);                          // stack still [1, 2, 3], Don't add another elements as size is 4
+customStack.increment(5, 100);                // stack becomes [101, 102, 103]
+customStack.increment(2, 100);                // stack becomes [201, 202, 103]
+customStack.pop();                            // return 103 --> Return top of the stack 103, stack becomes [201, 202]
+customStack.pop();                            // return 202 --> Return top of the stack 102, stack becomes [201]
+customStack.pop();                            // return 201 --> Return top of the stack 101, stack becomes []
+customStack.pop();                            // return -1 --> Stack is empty return -1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= maxSize <= 1000
  • +
  • 1 <= x <= 1000
  • +
  • 1 <= k <= 1000
  • +
  • 0 <= val <= 100
  • +
  • At most 1000 calls will be made to each method of increment, push and pop each separately.
  • +
+
\ No newline at end of file diff --git a/139-word-break/README.md b/139-word-break/README.md new file mode 100644 index 0000000..ccdcdbe --- /dev/null +++ b/139-word-break/README.md @@ -0,0 +1,37 @@ +

139. Word Break

Medium


Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

+ +

Note that the same word in the dictionary may be reused multiple times in the segmentation.

+ +

 

+

Example 1:

+ +
Input: s = "leetcode", wordDict = ["leet","code"]
+Output: true
+Explanation: Return true because "leetcode" can be segmented as "leet code".
+
+ +

Example 2:

+ +
Input: s = "applepenapple", wordDict = ["apple","pen"]
+Output: true
+Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
+Note that you are allowed to reuse a dictionary word.
+
+ +

Example 3:

+ +
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 300
  • +
  • 1 <= wordDict.length <= 1000
  • +
  • 1 <= wordDict[i].length <= 20
  • +
  • s and wordDict[i] consist of only lowercase English letters.
  • +
  • All the strings of wordDict are unique.
  • +
+
\ No newline at end of file diff --git a/141-linked-list-cycle/141-linked-list-cycle.cpp b/141-linked-list-cycle/141-linked-list-cycle.cpp new file mode 100644 index 0000000..880570b --- /dev/null +++ b/141-linked-list-cycle/141-linked-list-cycle.cpp @@ -0,0 +1,28 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool hasCycle(ListNode *head) { + if(head == NULL || head->next == NULL ) + return false; + + ListNode * slow = head; + ListNode * fast = head; + + do{ + slow = slow->next; + fast = fast->next->next; + }while(fast && fast->next && slow != fast); + + if(fast == NULL || fast->next == NULL) + return false; + + return true; + } +}; \ No newline at end of file diff --git a/141-linked-list-cycle/NOTES.md b/141-linked-list-cycle/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/141-linked-list-cycle/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/141-linked-list-cycle/README.md b/141-linked-list-cycle/README.md new file mode 100644 index 0000000..73491c5 --- /dev/null +++ b/141-linked-list-cycle/README.md @@ -0,0 +1,40 @@ +

141. Linked List Cycle

Easy


Given head, the head of a linked list, determine if the linked list has a cycle in it.

+ +

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

+ +

Return true if there is a cycle in the linked list. Otherwise, return false.

+ +

 

+

Example 1:

+ +
Input: head = [3,2,0,-4], pos = 1
+Output: true
+Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
+
+ +

Example 2:

+ +
Input: head = [1,2], pos = 0
+Output: true
+Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
+
+ +

Example 3:

+ +
Input: head = [1], pos = -1
+Output: false
+Explanation: There is no cycle in the linked list.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the list is in the range [0, 104].
  • +
  • -105 <= Node.val <= 105
  • +
  • pos is -1 or a valid index in the linked-list.
  • +
+ +

 

+

Follow up: Can you solve it using O(1) (i.e. constant) memory?

+
\ No newline at end of file diff --git a/142-linked-list-cycle-ii/142-linked-list-cycle-ii.cpp b/142-linked-list-cycle-ii/142-linked-list-cycle-ii.cpp new file mode 100644 index 0000000..b3b6d06 --- /dev/null +++ b/142-linked-list-cycle-ii/142-linked-list-cycle-ii.cpp @@ -0,0 +1,38 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *detectCycle(ListNode *head) { + if(head == NULL || head->next == NULL) + return NULL; + ListNode * slow = head; + ListNode * fast = head; + + do{ + slow = slow->next; + fast = fast->next->next; + }while(slow != fast && fast && fast->next); + + if(slow == fast) + { + fast = head; + + while(slow != fast) + { + slow = slow->next; + fast = fast->next; + } + + return fast; + } + else + return NULL; + + } +}; \ No newline at end of file diff --git a/142-linked-list-cycle-ii/NOTES.md b/142-linked-list-cycle-ii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/142-linked-list-cycle-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/142-linked-list-cycle-ii/README.md b/142-linked-list-cycle-ii/README.md new file mode 100644 index 0000000..25cb254 --- /dev/null +++ b/142-linked-list-cycle-ii/README.md @@ -0,0 +1,40 @@ +

142. Linked List Cycle II

Medium


Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.

+ +

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.

+ +

Do not modify the linked list.

+ +

 

+

Example 1:

+ +
Input: head = [3,2,0,-4], pos = 1
+Output: tail connects to node index 1
+Explanation: There is a cycle in the linked list, where tail connects to the second node.
+
+ +

Example 2:

+ +
Input: head = [1,2], pos = 0
+Output: tail connects to node index 0
+Explanation: There is a cycle in the linked list, where tail connects to the first node.
+
+ +

Example 3:

+ +
Input: head = [1], pos = -1
+Output: no cycle
+Explanation: There is no cycle in the linked list.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the list is in the range [0, 104].
  • +
  • -105 <= Node.val <= 105
  • +
  • pos is -1 or a valid index in the linked-list.
  • +
+ +

 

+

Follow up: Can you solve it using O(1) (i.e. constant) memory?

+
\ No newline at end of file diff --git a/1423-maximum-points-you-can-obtain-from-cards/1423-maximum-points-you-can-obtain-from-cards.cpp b/1423-maximum-points-you-can-obtain-from-cards/1423-maximum-points-you-can-obtain-from-cards.cpp new file mode 100644 index 0000000..e90ce5d --- /dev/null +++ b/1423-maximum-points-you-can-obtain-from-cards/1423-maximum-points-you-can-obtain-from-cards.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + +// int solve(vector& nums, int k,int i,int j,vector>& dp) +// { +// if(i>=j) +// return dp[i][j] = 0; +// if(k == 0) +// return dp[i][j] = 0; +// if(dp[i][j] != -1)return dp[i][j]; + +// int poss1 = nums[i] + solve(nums,k-1,i+1,j,dp); +// int poss2 = nums[j] + solve(nums,k-1,i,j-1,dp); + +// return dp[i][j] = max(poss1,poss2); +// } + + int maxScore(vector& nums, int k) { + if(k == nums.size()) + { int ans = 0; + for(auto a:nums)ans+=a; + return ans; + } + // vector> dp(nums.size(),vector (nums.size(),-1)); + // int ans = solve(nums,k,0,nums.size()-1,dp); + // return ans; + + int rem = nums.size() - k; + int ans = 0; + for(int i=0;i1423. Maximum Points You Can Obtain from Cards

Medium


There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.

+ +

In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.

+ +

Your score is the sum of the points of the cards you have taken.

+ +

Given the integer array cardPoints and the integer k, return the maximum score you can obtain.

+ +

 

+

Example 1:

+ +
Input: cardPoints = [1,2,3,4,5,6,1], k = 3
+Output: 12
+Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.
+
+ +

Example 2:

+ +
Input: cardPoints = [2,2,2], k = 2
+Output: 4
+Explanation: Regardless of which two cards you take, your score will always be 4.
+
+ +

Example 3:

+ +
Input: cardPoints = [9,7,7,9,7,7,9], k = 7
+Output: 55
+Explanation: You have to take all the cards. Your score is the sum of points of all cards.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= cardPoints.length <= 105
  • +
  • 1 <= cardPoints[i] <= 104
  • +
  • 1 <= k <= cardPoints.length
  • +
+
\ No newline at end of file diff --git a/144-binary-tree-preorder-traversal/NOTES.md b/144-binary-tree-preorder-traversal/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/144-binary-tree-preorder-traversal/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/144-binary-tree-preorder-traversal/README.md b/144-binary-tree-preorder-traversal/README.md new file mode 100644 index 0000000..5c5308e --- /dev/null +++ b/144-binary-tree-preorder-traversal/README.md @@ -0,0 +1,32 @@ +

144. Binary Tree Preorder Traversal

Easy


Given the root of a binary tree, return the preorder traversal of its nodes' values.

+ +

 

+

Example 1:

+ +
Input: root = [1,null,2,3]
+Output: [1,2,3]
+
+ +

Example 2:

+ +
Input: root = []
+Output: []
+
+ +

Example 3:

+ +
Input: root = [1]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+

Follow up: Recursive solution is trivial, could you do it iteratively?

+
\ No newline at end of file diff --git a/146-lru-cache/146-lru-cache.cpp b/146-lru-cache/146-lru-cache.cpp new file mode 100644 index 0000000..c58c40d --- /dev/null +++ b/146-lru-cache/146-lru-cache.cpp @@ -0,0 +1,70 @@ +class LRUCache { + public: + class node { + public: + int key; + int val; + node * next; + node * prev; + node(int _key, int _val) { + key = _key; + val = _val; + } + }; + + node * head = new node(-1, -1); + node * tail = new node(-1, -1); + + int cap; + unordered_map < int, node * > m; + + LRUCache(int capacity) { + cap = capacity; + head -> next = tail; + tail -> prev = head; + } + + void addnode(node * newnode) { + node * temp = head -> next; + newnode -> next = temp; + newnode -> prev = head; + head -> next = newnode; + temp -> prev = newnode; + } + + void deletenode(node * delnode) { + node * delprev = delnode -> prev; + node * delnext = delnode -> next; + delprev -> next = delnext; + delnext -> prev = delprev; + } + + int get(int key_) { + if (m.find(key_) != m.end()) { + node * resnode = m[key_]; + int res = resnode -> val; + m.erase(key_); + deletenode(resnode); + addnode(resnode); + m[key_] = head -> next; + return res; + } + + return -1; + } + + void put(int key_, int value) { + if (m.find(key_) != m.end()) { + node * existingnode = m[key_]; + m.erase(key_); + deletenode(existingnode); + } + if (m.size() == cap) { + m.erase(tail -> prev -> key); + deletenode(tail -> prev); + } + + addnode(new node(key_, value)); + m[key_] = head -> next; + } +}; \ No newline at end of file diff --git a/146-lru-cache/NOTES.md b/146-lru-cache/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/146-lru-cache/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/146-lru-cache/README.md b/146-lru-cache/README.md new file mode 100644 index 0000000..dbe2bbe --- /dev/null +++ b/146-lru-cache/README.md @@ -0,0 +1,44 @@ +

146. LRU Cache

Medium


Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

+ +

Implement the LRUCache class:

+ +
    +
  • LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
  • +
  • int get(int key) Return the value of the key if the key exists, otherwise return -1.
  • +
  • void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.
  • +
+ +

The functions get and put must each run in O(1) average time complexity.

+ +

 

+

Example 1:

+ +
Input
+["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
+[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
+Output
+[null, null, null, 1, null, -1, null, -1, 3, 4]
+
+Explanation
+LRUCache lRUCache = new LRUCache(2);
+lRUCache.put(1, 1); // cache is {1=1}
+lRUCache.put(2, 2); // cache is {1=1, 2=2}
+lRUCache.get(1);    // return 1
+lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
+lRUCache.get(2);    // returns -1 (not found)
+lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
+lRUCache.get(1);    // return -1 (not found)
+lRUCache.get(3);    // return 3
+lRUCache.get(4);    // return 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= capacity <= 3000
  • +
  • 0 <= key <= 104
  • +
  • 0 <= value <= 105
  • +
  • At most 2 * 105 calls will be made to get and put.
  • +
+
\ No newline at end of file diff --git a/1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.cpp b/1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.cpp new file mode 100644 index 0000000..62edb7b --- /dev/null +++ b/1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + long long int maxArea(int h, int w, vector& a, vector& b) { + sort(a.begin(),a.end()); + sort(b.begin(),b.end()); + a.insert(a.begin(),0); + a.push_back(h); + b.insert(b.begin(),0); + b.push_back(w); + + long long int p = a[1]-a[0]; + for(int i=1;i1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts

Medium


You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where:

+ +
    +
  • horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, and
  • +
  • verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.
  • +
+ +

Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, return this modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]
+Output: 4 
+Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.
+
+ +

Example 2:

+ +
Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]
+Output: 6
+Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.
+
+ +

Example 3:

+ +
Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]
+Output: 9
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= h, w <= 109
  • +
  • 1 <= horizontalCuts.length <= min(h - 1, 105)
  • +
  • 1 <= verticalCuts.length <= min(w - 1, 105)
  • +
  • 1 <= horizontalCuts[i] < h
  • +
  • 1 <= verticalCuts[i] < w
  • +
  • All the elements in horizontalCuts are distinct.
  • +
  • All the elements in verticalCuts are distinct.
  • +
+
\ No newline at end of file diff --git a/1472-design-browser-history/1472-design-browser-history.cpp b/1472-design-browser-history/1472-design-browser-history.cpp new file mode 100644 index 0000000..c562100 --- /dev/null +++ b/1472-design-browser-history/1472-design-browser-history.cpp @@ -0,0 +1,27 @@ +class BrowserHistory { +public: + vector history; +int pos =0; +BrowserHistory(string homepage) { history.push_back(homepage); } +void visit(string url) { + ++pos; + history.resize(pos); + history.push_back(url); +} +string back(int steps) { + pos = max(0, pos - steps); + return history[pos]; +} +string forward(int steps) { + pos = min((int)history.size() -1, pos + steps); + return history[pos]; +} +}; + +/** + * Your BrowserHistory object will be instantiated and called as such: + * BrowserHistory* obj = new BrowserHistory(homepage); + * obj->visit(url); + * string param_2 = obj->back(steps); + * string param_3 = obj->forward(steps); + */ \ No newline at end of file diff --git a/1472-design-browser-history/NOTES.md b/1472-design-browser-history/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1472-design-browser-history/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1472-design-browser-history/README.md b/1472-design-browser-history/README.md new file mode 100644 index 0000000..de385f5 --- /dev/null +++ b/1472-design-browser-history/README.md @@ -0,0 +1,45 @@ +

1472. Design Browser History

Medium


You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps.

+ +

Implement the BrowserHistory class:

+ +
    +
  • BrowserHistory(string homepage) Initializes the object with the homepage of the browser.
  • +
  • void visit(string url) Visits url from the current page. It clears up all the forward history.
  • +
  • string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps.
  • +
  • string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.
  • +
+ +

 

+

Example:

+ +
Input:
+["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]
+[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]
+Output:
+[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]
+
+Explanation:
+BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
+browserHistory.visit("google.com");       // You are in "leetcode.com". Visit "google.com"
+browserHistory.visit("facebook.com");     // You are in "google.com". Visit "facebook.com"
+browserHistory.visit("youtube.com");      // You are in "facebook.com". Visit "youtube.com"
+browserHistory.back(1);                   // You are in "youtube.com", move back to "facebook.com" return "facebook.com"
+browserHistory.back(1);                   // You are in "facebook.com", move back to "google.com" return "google.com"
+browserHistory.forward(1);                // You are in "google.com", move forward to "facebook.com" return "facebook.com"
+browserHistory.visit("linkedin.com");     // You are in "facebook.com". Visit "linkedin.com"
+browserHistory.forward(2);                // You are in "linkedin.com", you cannot move forward any steps.
+browserHistory.back(2);                   // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com"
+browserHistory.back(7);                   // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= homepage.length <= 20
  • +
  • 1 <= url.length <= 20
  • +
  • 1 <= steps <= 100
  • +
  • homepage and url consist of  '.' or lower case English letters.
  • +
  • At most 5000 calls will be made to visit, back, and forward.
  • +
+
\ No newline at end of file diff --git a/148-sort-list/148-sort-list.cpp b/148-sort-list/148-sort-list.cpp new file mode 100644 index 0000000..8eb36f5 --- /dev/null +++ b/148-sort-list/148-sort-list.cpp @@ -0,0 +1,50 @@ +class Solution { +public: + ListNode* sortList(ListNode* head) { + if (head == NULL || head->next == NULL) + return head; + + ListNode* slow = head; + ListNode* fast = head->next; + + while (fast != NULL && fast->next != NULL) + { + slow = slow->next; + fast = fast->next->next; + } + //divide the list into two parts + fast = slow->next; + slow->next = NULL; + + return merge(sortList(head), sortList(fast)); + } + + ListNode* merge(ListNode* l1, ListNode* l2) + { + ListNode dump(0); + ListNode* cur = &dump; + + while (l1 != NULL && l2 != NULL) + { + if (l1->val < l2->val) + { + cur->next = l1; + l1 = l1->next; + } + else + { + cur->next = l2; + l2 = l2->next; + } + + cur = cur->next; + } + + if (l1 != NULL) + cur->next = l1; + else + cur->next = l2; + + return dump.next; + } +}; \ No newline at end of file diff --git a/148-sort-list/NOTES.md b/148-sort-list/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/148-sort-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/148-sort-list/README.md b/148-sort-list/README.md new file mode 100644 index 0000000..1446549 --- /dev/null +++ b/148-sort-list/README.md @@ -0,0 +1,32 @@ +

148. Sort List

Medium


Given the head of a linked list, return the list after sorting it in ascending order.

+ +

 

+

Example 1:

+ +
Input: head = [4,2,1,3]
+Output: [1,2,3,4]
+
+ +

Example 2:

+ +
Input: head = [-1,5,3,4,0]
+Output: [-1,0,3,4,5]
+
+ +

Example 3:

+ +
Input: head = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 5 * 104].
  • +
  • -105 <= Node.val <= 105
  • +
+ +

 

+

Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?

+
\ No newline at end of file diff --git a/1510-stone-game-iv/1510-stone-game-iv.cpp b/1510-stone-game-iv/1510-stone-game-iv.cpp new file mode 100644 index 0000000..be84b4c --- /dev/null +++ b/1510-stone-game-iv/1510-stone-game-iv.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + bool winnerSquareGame(int n) { + vector dp(n + 1, false); + for (int i = 1; i <= n; ++i) { + for (int k = 1; k * k <= i; ++k) { + if (!dp[i - k * k]) { + dp[i] = true; + break; + } + } + } + return dp[n]; + } +}; \ No newline at end of file diff --git a/1510-stone-game-iv/NOTES.md b/1510-stone-game-iv/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1510-stone-game-iv/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1510-stone-game-iv/README.md b/1510-stone-game-iv/README.md new file mode 100644 index 0000000..63f9fb5 --- /dev/null +++ b/1510-stone-game-iv/README.md @@ -0,0 +1,36 @@ +

1510. Stone Game IV

Hard


Alice and Bob take turns playing a game, with Alice starting first.

+ +

Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.

+ +

Also, if a player cannot make a move, he/she loses the game.

+ +

Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.

+ +

 

+

Example 1:

+ +
Input: n = 1
+Output: true
+Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.
+ +

Example 2:

+ +
Input: n = 2
+Output: false
+Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).
+
+ +

Example 3:

+ +
Input: n = 4
+Output: true
+Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
+
\ No newline at end of file diff --git a/153-find-minimum-in-rotated-sorted-array/153-find-minimum-in-rotated-sorted-array.cpp b/153-find-minimum-in-rotated-sorted-array/153-find-minimum-in-rotated-sorted-array.cpp new file mode 100644 index 0000000..c115bdb --- /dev/null +++ b/153-find-minimum-in-rotated-sorted-array/153-find-minimum-in-rotated-sorted-array.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int findMin(vector& nums) { + int s = 0; + int e = nums.size() - 1; + + while (s < e) + { + int mid = (s + e) / 2; + + if (nums[mid] < nums[e]) + { + e = mid; + } + else + { + s = mid + 1; + } + } + return nums[s]; + } +}; \ No newline at end of file diff --git a/153-find-minimum-in-rotated-sorted-array/NOTES.md b/153-find-minimum-in-rotated-sorted-array/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/153-find-minimum-in-rotated-sorted-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/153-find-minimum-in-rotated-sorted-array/README.md b/153-find-minimum-in-rotated-sorted-array/README.md new file mode 100644 index 0000000..946447e --- /dev/null +++ b/153-find-minimum-in-rotated-sorted-array/README.md @@ -0,0 +1,46 @@ +

153. Find Minimum in Rotated Sorted Array

Medium


Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:

+ +
    +
  • [4,5,6,7,0,1,2] if it was rotated 4 times.
  • +
  • [0,1,2,4,5,6,7] if it was rotated 7 times.
  • +
+ +

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

+ +

Given the sorted rotated array nums of unique elements, return the minimum element of this array.

+ +

You must write an algorithm that runs in O(log n) time.

+ +

 

+

Example 1:

+ +
Input: nums = [3,4,5,1,2]
+Output: 1
+Explanation: The original array was [1,2,3,4,5] rotated 3 times.
+
+ +

Example 2:

+ +
Input: nums = [4,5,6,7,0,1,2]
+Output: 0
+Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.
+
+ +

Example 3:

+ +
Input: nums = [11,13,15,17]
+Output: 11
+Explanation: The original array was [11,13,15,17] and it was rotated 4 times. 
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 5000
  • +
  • -5000 <= nums[i] <= 5000
  • +
  • All the integers of nums are unique.
  • +
  • nums is sorted and rotated between 1 and n times.
  • +
+
\ No newline at end of file diff --git a/154-find-minimum-in-rotated-sorted-array-ii/154-find-minimum-in-rotated-sorted-array-ii.cpp b/154-find-minimum-in-rotated-sorted-array-ii/154-find-minimum-in-rotated-sorted-array-ii.cpp new file mode 100644 index 0000000..7e50e74 --- /dev/null +++ b/154-find-minimum-in-rotated-sorted-array-ii/154-find-minimum-in-rotated-sorted-array-ii.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int findMin(vector& nums) { + int s = 0; + int e = nums.size() - 1; + + while (s < e) + { + int mid = (s + e) / 2; + + if (nums[mid] < nums[e]) + { + e = mid; + } + else if(nums[mid] > nums[e]) + { + s = mid + 1; + } + else + { + e--; + } + } + return nums[s]; + } +}; \ No newline at end of file diff --git a/154-find-minimum-in-rotated-sorted-array-ii/NOTES.md b/154-find-minimum-in-rotated-sorted-array-ii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/154-find-minimum-in-rotated-sorted-array-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/154-find-minimum-in-rotated-sorted-array-ii/README.md b/154-find-minimum-in-rotated-sorted-array-ii/README.md new file mode 100644 index 0000000..17832ad --- /dev/null +++ b/154-find-minimum-in-rotated-sorted-array-ii/README.md @@ -0,0 +1,36 @@ +

154. Find Minimum in Rotated Sorted Array II

Hard


Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:

+ +
    +
  • [4,5,6,7,0,1,4] if it was rotated 4 times.
  • +
  • [0,1,4,4,5,6,7] if it was rotated 7 times.
  • +
+ +

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

+ +

Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array.

+ +

You must decrease the overall operation steps as much as possible.

+ +

 

+

Example 1:

+
Input: nums = [1,3,5]
+Output: 1
+

Example 2:

+
Input: nums = [2,2,2,0,1]
+Output: 0
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 5000
  • +
  • -5000 <= nums[i] <= 5000
  • +
  • nums is sorted and rotated between 1 and n times.
  • +
+ +

 

+

Follow up: This problem is similar to Find Minimum in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why?

+ +

 

+
\ No newline at end of file diff --git a/155-min-stack/155-min-stack.cpp b/155-min-stack/155-min-stack.cpp new file mode 100644 index 0000000..84a4248 --- /dev/null +++ b/155-min-stack/155-min-stack.cpp @@ -0,0 +1,82 @@ +class MinStack { +public: + stacks; + + long long int min = 0; + + void push(int val) { + + if(s.size()==0) + { + s.push(val); + + min = val; + } + + else if(val>=min) + { + s.push(val); + } + + else + { + long long int p = 2*(long long)val-min; + + s.push(p); + + min = val; + } + } + + void pop() { + if(s.size()==0) return; + + else + { + if(s.top()>=min) + { + s.pop(); + } + + else + { + int ov = min; + + min = 2*min-s.top(); + + s.pop(); + } + } + } + + int top() { + if(s.size()==0) return -1; + + else + { + if(s.top()>=min) + { + return s.top(); + } + + else + { + return min; + } + } + } + + int getMin() { + return min; + } +}; + + +/** + * Your MinStack object will be instantiated and called as such: + * MinStack* obj = new MinStack(); + * obj->push(val); + * obj->pop(); + * int param_3 = obj->top(); + * int param_4 = obj->getMin(); + */ \ No newline at end of file diff --git a/155-min-stack/NOTES.md b/155-min-stack/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/155-min-stack/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/155-min-stack/README.md b/155-min-stack/README.md new file mode 100644 index 0000000..ca1a124 --- /dev/null +++ b/155-min-stack/README.md @@ -0,0 +1,44 @@ +

155. Min Stack

Medium


Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

+ +

Implement the MinStack class:

+ +
    +
  • MinStack() initializes the stack object.
  • +
  • void push(int val) pushes the element val onto the stack.
  • +
  • void pop() removes the element on the top of the stack.
  • +
  • int top() gets the top element of the stack.
  • +
  • int getMin() retrieves the minimum element in the stack.
  • +
+ +

You must implement a solution with O(1) time complexity for each function.

+ +

 

+

Example 1:

+ +
Input
+["MinStack","push","push","push","getMin","pop","top","getMin"]
+[[],[-2],[0],[-3],[],[],[],[]]
+
+Output
+[null,null,null,null,-3,null,0,-2]
+
+Explanation
+MinStack minStack = new MinStack();
+minStack.push(-2);
+minStack.push(0);
+minStack.push(-3);
+minStack.getMin(); // return -3
+minStack.pop();
+minStack.top();    // return 0
+minStack.getMin(); // return -2
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= val <= 231 - 1
  • +
  • Methods pop, top and getMin operations will always be called on non-empty stacks.
  • +
  • At most 3 * 104 calls will be made to push, pop, top, and getMin.
  • +
+
\ No newline at end of file diff --git a/1552-magnetic-force-between-two-balls/1552-magnetic-force-between-two-balls.cpp b/1552-magnetic-force-between-two-balls/1552-magnetic-force-between-two-balls.cpp new file mode 100644 index 0000000..8887412 --- /dev/null +++ b/1552-magnetic-force-between-two-balls/1552-magnetic-force-between-two-balls.cpp @@ -0,0 +1,52 @@ +class Solution { + bool isPossible(vector& nums, int mid,int m) + { + int count = 1; + int sum = 0; + + for(int i=0;i= mid ) + { + count++; + sum = 0; + if(count >= m) + return true; + } + else + sum += (nums[i+1] - nums[i]); + } + // cout<& nums, int m) { + + sort(nums.begin(),nums.end()); + int low = nums[1] - nums[0] ; + int high = low; + + for(int i=1;i1552. Magnetic Force Between Two Balls

Medium


In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.

+ +

Rick stated that magnetic force between two different balls at positions x and y is |x - y|.

+ +

Given the integer array position and the integer m. Return the required force.

+ +

 

+

Example 1:

+ +
Input: position = [1,2,3,4,7], m = 3
+Output: 3
+Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
+
+ +

Example 2:

+ +
Input: position = [5,4,3,2,1,1000000000], m = 2
+Output: 999999999
+Explanation: We can use baskets 1 and 1000000000.
+
+ +

 

+

Constraints:

+ +
    +
  • n == position.length
  • +
  • 2 <= n <= 105
  • +
  • 1 <= position[i] <= 109
  • +
  • All integers in position are distinct.
  • +
  • 2 <= m <= position.length
  • +
+
\ No newline at end of file diff --git a/16-3sum-closest/16-3sum-closest.cpp b/16-3sum-closest/16-3sum-closest.cpp new file mode 100644 index 0000000..5c0c5ca --- /dev/null +++ b/16-3sum-closest/16-3sum-closest.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int threeSumClosest(vector& nums, int target) { + + int closest = nums[0]+nums[1]+nums[2]; + sort(nums.begin(),nums.end()); + for(int i=0;i sum ) + { + j++; + } + else + k--; + } + } + } + return closest; + + } +}; \ No newline at end of file diff --git a/16-3sum-closest/NOTES.md b/16-3sum-closest/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/16-3sum-closest/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/160-intersection-of-two-linked-lists/160-intersection-of-two-linked-lists.cpp b/160-intersection-of-two-linked-lists/160-intersection-of-two-linked-lists.cpp new file mode 100644 index 0000000..2a2f03c --- /dev/null +++ b/160-intersection-of-two-linked-lists/160-intersection-of-two-linked-lists.cpp @@ -0,0 +1,24 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + + if(headA == NULL || headB == NULL)return NULL; + ListNode * a = headA; + ListNode * b = headB; + while(headA != headB) + { + headA = headA == NULL ? b : headA->next; + headB = headB == NULL ? a : headB->next; + } + return headA; + + } +}; \ No newline at end of file diff --git a/160-intersection-of-two-linked-lists/README.md b/160-intersection-of-two-linked-lists/README.md new file mode 100644 index 0000000..085d444 --- /dev/null +++ b/160-intersection-of-two-linked-lists/README.md @@ -0,0 +1,63 @@ +

160. Intersection of Two Linked Lists

Easy


Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

+ +

For example, the following two linked lists begin to intersect at node c1:

+ +

The test cases are generated such that there are no cycles anywhere in the entire linked structure.

+ +

Note that the linked lists must retain their original structure after the function returns.

+ +

Custom Judge:

+ +

The inputs to the judge are given as follows (your program is not given these inputs):

+ +
    +
  • intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.
  • +
  • listA - The first linked list.
  • +
  • listB - The second linked list.
  • +
  • skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.
  • +
  • skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node.
  • +
+ +

The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted.

+ +

 

+

Example 1:

+ +
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
+Output: Intersected at '8'
+Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
+From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
+
+ +

Example 2:

+ +
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
+Output: Intersected at '2'
+Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
+From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
+
+ +

Example 3:

+ +
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
+Output: No intersection
+Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
+Explanation: The two lists do not intersect, so return null.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes of listA is in the m.
  • +
  • The number of nodes of listB is in the n.
  • +
  • 1 <= m, n <= 3 * 104
  • +
  • 1 <= Node.val <= 105
  • +
  • 0 <= skipA < m
  • +
  • 0 <= skipB < n
  • +
  • intersectVal is 0 if listA and listB do not intersect.
  • +
  • intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.
  • +
+ +

 

+Follow up: Could you write a solution that runs in O(m + n) time and use only O(1) memory?
\ No newline at end of file diff --git a/162-find-peak-element/162-find-peak-element.cpp b/162-find-peak-element/162-find-peak-element.cpp new file mode 100644 index 0000000..73769fd --- /dev/null +++ b/162-find-peak-element/162-find-peak-element.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int findPeakElement(vector& nums) { + + + int low = 0; + int high = nums.size()-1; + + while(low162. Find Peak Element

Medium


A peak element is an element that is strictly greater than its neighbors.

+ +

Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

+ +

You may imagine that nums[-1] = nums[n] = -∞.

+ +

You must write an algorithm that runs in O(log n) time.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,1]
+Output: 2
+Explanation: 3 is a peak element and your function should return the index number 2.
+ +

Example 2:

+ +
Input: nums = [1,2,1,3,5,6,4]
+Output: 5
+Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • nums[i] != nums[i + 1] for all valid i.
  • +
+
\ No newline at end of file diff --git a/165-compare-version-numbers/README.md b/165-compare-version-numbers/README.md new file mode 100644 index 0000000..8b228e8 --- /dev/null +++ b/165-compare-version-numbers/README.md @@ -0,0 +1,49 @@ +

165. Compare Version Numbers

Medium


Given two version numbers, version1 and version2, compare them.

+ +
    +
+ +

Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.

+ +

To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.

+ +

Return the following:

+ +
    +
  • If version1 < version2, return -1.
  • +
  • If version1 > version2, return 1.
  • +
  • Otherwise, return 0.
  • +
+ +

 

+

Example 1:

+ +
Input: version1 = "1.01", version2 = "1.001"
+Output: 0
+Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1".
+
+ +

Example 2:

+ +
Input: version1 = "1.0", version2 = "1.0.0"
+Output: 0
+Explanation: version1 does not specify revision 2, which means it is treated as "0".
+
+ +

Example 3:

+ +
Input: version1 = "0.1", version2 = "1.1"
+Output: -1
+Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= version1.length, version2.length <= 500
  • +
  • version1 and version2 only contain digits and '.'.
  • +
  • version1 and version2 are valid version numbers.
  • +
  • All the given revisions in version1 and version2 can be stored in a 32-bit integer.
  • +
+
\ No newline at end of file diff --git a/1672-richest-customer-wealth/1672-richest-customer-wealth.cpp b/1672-richest-customer-wealth/1672-richest-customer-wealth.cpp new file mode 100644 index 0000000..84a707a --- /dev/null +++ b/1672-richest-customer-wealth/1672-richest-customer-wealth.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int maximumWealth(vector>& accounts) { + int ans = 0; + for(int i=0;ians) + ans = count; + } + return ans; + } +}; \ No newline at end of file diff --git a/1672-richest-customer-wealth/NOTES.md b/1672-richest-customer-wealth/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1672-richest-customer-wealth/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1672-richest-customer-wealth/README.md b/1672-richest-customer-wealth/README.md new file mode 100644 index 0000000..e75b70d --- /dev/null +++ b/1672-richest-customer-wealth/README.md @@ -0,0 +1,41 @@ +

1672. Richest Customer Wealth

Easy


You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has.

+ +

A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.

+ +

 

+

Example 1:

+ +
Input: accounts = [[1,2,3],[3,2,1]]
+Output: 6
+Explanation:
+1st customer has wealth = 1 + 2 + 3 = 6
+2nd customer has wealth = 3 + 2 + 1 = 6
+Both customers are considered the richest with a wealth of 6 each, so return 6.
+
+ +

Example 2:

+ +
Input: accounts = [[1,5],[7,3],[3,5]]
+Output: 10
+Explanation: 
+1st customer has wealth = 6
+2nd customer has wealth = 10 
+3rd customer has wealth = 8
+The 2nd customer is the richest with a wealth of 10.
+ +

Example 3:

+ +
Input: accounts = [[2,8,7],[7,1,3],[1,9,5]]
+Output: 17
+
+ +

 

+

Constraints:

+ +
    +
  • m == accounts.length
  • +
  • n == accounts[i].length
  • +
  • 1 <= m, n <= 50
  • +
  • 1 <= accounts[i][j] <= 100
  • +
+
\ No newline at end of file diff --git a/1675-minimize-deviation-in-array/NOTES.md b/1675-minimize-deviation-in-array/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1675-minimize-deviation-in-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1675-minimize-deviation-in-array/README.md b/1675-minimize-deviation-in-array/README.md new file mode 100644 index 0000000..9728ab1 --- /dev/null +++ b/1675-minimize-deviation-in-array/README.md @@ -0,0 +1,52 @@ +

1675. Minimize Deviation in Array

Hard


You are given an array nums of n positive integers.

+ +

You can perform two types of operations on any element of the array any number of times:

+ +
    +
  • If the element is even, divide it by 2. + +
      +
    • For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].
    • +
    +
  • +
  • If the element is odd, multiply it by 2. +
      +
    • For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4].
    • +
    +
  • +
+ +

The deviation of the array is the maximum difference between any two elements in the array.

+ +

Return the minimum deviation the array can have after performing some number of operations.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,4]
+Output: 1
+Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.
+
+ +

Example 2:

+ +
Input: nums = [4,1,5,20,3]
+Output: 3
+Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.
+
+ +

Example 3:

+ +
Input: nums = [2,10,8]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 2 <= n <= 105
  • +
  • 1 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/169-majority-element/169-majority-element.cpp b/169-majority-element/169-majority-element.cpp new file mode 100644 index 0000000..383b252 --- /dev/null +++ b/169-majority-element/169-majority-element.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int majorityElement(vector& nums) { + + int count = 1; + int major = nums[0]; + + for(int i=1;i169. Majority Element

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [3,2,3]
+Output: 3
+

Example 2:

+
Input: nums = [2,2,1,1,1,2,2]
+Output: 2
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 5 * 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+ +

 

+Follow-up: Could you solve the problem in linear time and in O(1) space?
\ No newline at end of file diff --git a/171-excel-sheet-column-number/171-excel-sheet-column-number.cpp b/171-excel-sheet-column-number/171-excel-sheet-column-number.cpp new file mode 100644 index 0000000..cc0818f --- /dev/null +++ b/171-excel-sheet-column-number/171-excel-sheet-column-number.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int titleToNumber(string s) { + long ans = 0; + long poww = 1; + while(s.size()) + { + char last = s[s.size()-1]; + ans += (poww*(last - 'A' + 1)); + poww *= 26; + s.pop_back(); + } + return ans; + } +}; \ No newline at end of file diff --git a/171-excel-sheet-column-number/NOTES.md b/171-excel-sheet-column-number/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/171-excel-sheet-column-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/171-excel-sheet-column-number/README.md b/171-excel-sheet-column-number/README.md new file mode 100644 index 0000000..d46ff97 --- /dev/null +++ b/171-excel-sheet-column-number/README.md @@ -0,0 +1,42 @@ +

171. Excel Sheet Column Number

Easy


Given a string columnTitle that represents the column title as appear in an Excel sheet, return its corresponding column number.

+ +

For example:

+ +
A -> 1
+B -> 2
+C -> 3
+...
+Z -> 26
+AA -> 27
+AB -> 28 
+...
+
+ +

 

+

Example 1:

+ +
Input: columnTitle = "A"
+Output: 1
+
+ +

Example 2:

+ +
Input: columnTitle = "AB"
+Output: 28
+
+ +

Example 3:

+ +
Input: columnTitle = "ZY"
+Output: 701
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= columnTitle.length <= 7
  • +
  • columnTitle consists only of uppercase English letters.
  • +
  • columnTitle is in the range ["A", "FXSHRXW"].
  • +
+
\ No newline at end of file diff --git a/1760-minimum-limit-of-balls-in-a-bag/1760-minimum-limit-of-balls-in-a-bag.cpp b/1760-minimum-limit-of-balls-in-a-bag/1760-minimum-limit-of-balls-in-a-bag.cpp new file mode 100644 index 0000000..059618a --- /dev/null +++ b/1760-minimum-limit-of-balls-in-a-bag/1760-minimum-limit-of-balls-in-a-bag.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + + bool isPossible(int mid,vector& nums, int maxOperations) + { + int count = 0; + + for(int i=0;i= count) + return true; + return false; + } + int minimumSize(vector& nums, int maxOperations) { + + int low = 1; + int high = 1e9; + int ans = 0; + while(low<=high) + { + int mid = (low+high)>>1; + + if(isPossible(mid,nums,maxOperations)) + { + ans = mid; + high = mid - 1; + } + else + { + low = mid + 1; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/1760-minimum-limit-of-balls-in-a-bag/NOTES.md b/1760-minimum-limit-of-balls-in-a-bag/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1760-minimum-limit-of-balls-in-a-bag/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1760-minimum-limit-of-balls-in-a-bag/README.md b/1760-minimum-limit-of-balls-in-a-bag/README.md new file mode 100644 index 0000000..d102e9e --- /dev/null +++ b/1760-minimum-limit-of-balls-in-a-bag/README.md @@ -0,0 +1,54 @@ +

1760. Minimum Limit of Balls in a Bag

Medium


You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations.

+ +

You can perform the following operation at most maxOperations times:

+ +
    +
  • Take any bag of balls and divide it into two new bags with a positive number of balls. + +
      +
    • For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.
    • +
    +
  • +
+ +

Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.

+ +

Return the minimum possible penalty after performing the operations.

+ +

 

+

Example 1:

+ +
Input: nums = [9], maxOperations = 2
+Output: 3
+Explanation: 
+- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].
+- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].
+The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.
+
+ +

Example 2:

+ +
Input: nums = [2,4,8,2], maxOperations = 4
+Output: 2
+Explanation:
+- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].
+- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].
+- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].
+- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].
+The bag with the most number of balls has 2 balls, so your penalty is 2 an you should return 2.
+
+ +

Example 3:

+ +
Input: nums = [7,17], maxOperations = 2
+Output: 7
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= maxOperations, nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/179-largest-number/179-largest-number.cpp b/179-largest-number/179-largest-number.cpp new file mode 100644 index 0000000..c34f89a --- /dev/null +++ b/179-largest-number/179-largest-number.cpp @@ -0,0 +1,49 @@ +class Solution { +public: + + static bool comp(string a,string b) + { + return (a+b)>(b+a); + } + + string largestNumber(vector& nums) { + + vector num(nums.size()); + + for(int i=0;i(b+a); +// } + +// string largestNumber(vector& nums) { +// string s = ""; +// vector str; +// for(auto& x:nums){ +// str.push_back(to_string(x)); +// } +// sort(str.begin(),str.end(),myCmp); +// if(str[0]=="0") return "0"; +// for(auto& x:str){ +// s += x; +// } +// return s; +// } +// }; \ No newline at end of file diff --git a/179-largest-number/NOTES.md b/179-largest-number/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/179-largest-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/179-largest-number/README.md b/179-largest-number/README.md new file mode 100644 index 0000000..f292471 --- /dev/null +++ b/179-largest-number/README.md @@ -0,0 +1,25 @@ +

179. Largest Number

Medium


Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.

+ +

Since the result may be very large, so you need to return a string instead of an integer.

+ +

 

+

Example 1:

+ +
Input: nums = [10,2]
+Output: "210"
+
+ +

Example 2:

+ +
Input: nums = [3,30,34,5,9]
+Output: "9534330"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 0 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/18-4sum/18-4sum.cpp b/18-4sum/18-4sum.cpp new file mode 100644 index 0000000..4d23c36 --- /dev/null +++ b/18-4sum/18-4sum.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + vector> fourSum(vector& nums, int target) { + vector> ans; + if(nums.size()<4)return ans; + sort(nums.begin(),nums.end()); + for(int i=0;i target) + { + l--; + } + else + k++; + } + } + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/18-4sum/NOTES.md b/18-4sum/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/18-4sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/18-4sum/README.md b/18-4sum/README.md new file mode 100644 index 0000000..5c92452 --- /dev/null +++ b/18-4sum/README.md @@ -0,0 +1,32 @@ +

18. 4Sum

Medium


Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

+ +
    +
  • 0 <= a, b, c, d < n
  • +
  • a, b, c, and d are distinct.
  • +
  • nums[a] + nums[b] + nums[c] + nums[d] == target
  • +
+ +

You may return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: nums = [1,0,-1,0,-2,2], target = 0
+Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
+
+ +

Example 2:

+ +
Input: nums = [2,2,2,2,2], target = 8
+Output: [[2,2,2,2]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 200
  • +
  • -109 <= nums[i] <= 109
  • +
  • -109 <= target <= 109
  • +
+
\ No newline at end of file diff --git a/1823-find-the-winner-of-the-circular-game/1823-find-the-winner-of-the-circular-game.cpp b/1823-find-the-winner-of-the-circular-game/1823-find-the-winner-of-the-circular-game.cpp new file mode 100644 index 0000000..4064c06 --- /dev/null +++ b/1823-find-the-winner-of-the-circular-game/1823-find-the-winner-of-the-circular-game.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int findTheWinner(int n, int k) { + int res = 0; + for (int i = 1; i <= n; ++i) + res = (res + k) % i; + return res+1; + } +}; \ No newline at end of file diff --git a/1823-find-the-winner-of-the-circular-game/NOTES.md b/1823-find-the-winner-of-the-circular-game/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/1823-find-the-winner-of-the-circular-game/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1823-find-the-winner-of-the-circular-game/README.md b/1823-find-the-winner-of-the-circular-game/README.md new file mode 100644 index 0000000..42e9370 --- /dev/null +++ b/1823-find-the-winner-of-the-circular-game/README.md @@ -0,0 +1,43 @@ +

1823. Find the Winner of the Circular Game

Medium


There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.

+ +

The rules of the game are as follows:

+ +
    +
  1. Start at the 1st friend.
  2. +
  3. Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once.
  4. +
  5. The last friend you counted leaves the circle and loses the game.
  6. +
  7. If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat.
  8. +
  9. Else, the last friend in the circle wins the game.
  10. +
+ +

Given the number of friends, n, and an integer k, return the winner of the game.

+ +

 

+

Example 1:

+ +
Input: n = 5, k = 2
+Output: 3
+Explanation: Here are the steps of the game:
+1) Start at friend 1.
+2) Count 2 friends clockwise, which are friends 1 and 2.
+3) Friend 2 leaves the circle. Next start is friend 3.
+4) Count 2 friends clockwise, which are friends 3 and 4.
+5) Friend 4 leaves the circle. Next start is friend 5.
+6) Count 2 friends clockwise, which are friends 5 and 1.
+7) Friend 1 leaves the circle. Next start is friend 3.
+8) Count 2 friends clockwise, which are friends 3 and 5.
+9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.
+ +

Example 2:

+ +
Input: n = 6, k = 5
+Output: 1
+Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= n <= 500
  • +
\ No newline at end of file diff --git a/189-rotate-array/NOTES.md b/189-rotate-array/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/189-rotate-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/189-rotate-array/README.md b/189-rotate-array/README.md new file mode 100644 index 0000000..7164839 --- /dev/null +++ b/189-rotate-array/README.md @@ -0,0 +1,39 @@ +

189. Rotate Array

Medium


Given an array, rotate the array to the right by k steps, where k is non-negative.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,4,5,6,7], k = 3
+Output: [5,6,7,1,2,3,4]
+Explanation:
+rotate 1 steps to the right: [7,1,2,3,4,5,6]
+rotate 2 steps to the right: [6,7,1,2,3,4,5]
+rotate 3 steps to the right: [5,6,7,1,2,3,4]
+
+ +

Example 2:

+ +
Input: nums = [-1,-100,3,99], k = 2
+Output: [3,99,-1,-100]
+Explanation: 
+rotate 1 steps to the right: [99,-1,-100,3]
+rotate 2 steps to the right: [3,99,-1,-100]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • 0 <= k <= 105
  • +
+ +

 

+

Follow up:

+ +
    +
  • Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
  • +
  • Could you do it in-place with O(1) extra space?
  • +
+
\ No newline at end of file diff --git a/2-add-two-numbers/2-add-two-numbers.cpp b/2-add-two-numbers/2-add-two-numbers.cpp new file mode 100644 index 0000000..85a5c8e --- /dev/null +++ b/2-add-two-numbers/2-add-two-numbers.cpp @@ -0,0 +1,58 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: +// ListNode * reverse(ListNode * l1) +// { +// if(!l1 || l1->next == NULL) +// return l1; + +// ListNode * nextnode=l1->next; +// ListNode * reversed = reverse(l1->next); +// l1->next = NULL; +// nextnode->next = l1; +// return reversed; +// } + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + // l1 = reverse(l1); + // l2 = reverse(l2); + int carry = 0; + ListNode * dummy = new ListNode(0); + ListNode * temp = dummy; + while(l1 != NULL || l2 !=NULL) + { + int sum = carry; + if(l1) + sum+=l1->val; + if(l2) + sum+=l2->val; + + int value = sum%10; + carry = sum/10; + ListNode * newNode = new ListNode(value); + temp->next = newNode; + temp = temp->next; + if(l1) + l1 = l1->next; + if(l2) + l2 = l2->next; + } + + if(carry) + { + ListNode * newNode = new ListNode(carry); + temp->next = newNode; + temp = temp->next; + } + return dummy->next; + + } +}; \ No newline at end of file diff --git a/2-add-two-numbers/NOTES.md b/2-add-two-numbers/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/2-add-two-numbers/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2-add-two-numbers/README.md b/2-add-two-numbers/README.md new file mode 100644 index 0000000..23f654a --- /dev/null +++ b/2-add-two-numbers/README.md @@ -0,0 +1,33 @@ +

2. Add Two Numbers

Medium


You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

+ +

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

+ +

 

+

Example 1:

+ +
Input: l1 = [2,4,3], l2 = [5,6,4]
+Output: [7,0,8]
+Explanation: 342 + 465 = 807.
+
+ +

Example 2:

+ +
Input: l1 = [0], l2 = [0]
+Output: [0]
+
+ +

Example 3:

+ +
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
+Output: [8,9,9,9,0,0,0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in each linked list is in the range [1, 100].
  • +
  • 0 <= Node.val <= 9
  • +
  • It is guaranteed that the list represents a number that does not have leading zeros.
  • +
+
\ No newline at end of file diff --git a/20-valid-parentheses/20-valid-parentheses.cpp b/20-valid-parentheses/20-valid-parentheses.cpp new file mode 100644 index 0000000..d8d9095 --- /dev/null +++ b/20-valid-parentheses/20-valid-parentheses.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + bool isValid(string s) { + stack sc; + + for(int i=0;i20. Valid Parentheses

Easy


Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

+ +

An input string is valid if:

+ +
    +
  1. Open brackets must be closed by the same type of brackets.
  2. +
  3. Open brackets must be closed in the correct order.
  4. +
+ +

 

+

Example 1:

+ +
Input: s = "()"
+Output: true
+
+ +

Example 2:

+ +
Input: s = "()[]{}"
+Output: true
+
+ +

Example 3:

+ +
Input: s = "(]"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of parentheses only '()[]{}'.
  • +
+
\ No newline at end of file diff --git a/203-remove-linked-list-elements/203-remove-linked-list-elements.cpp b/203-remove-linked-list-elements/203-remove-linked-list-elements.cpp new file mode 100644 index 0000000..c6ffda7 --- /dev/null +++ b/203-remove-linked-list-elements/203-remove-linked-list-elements.cpp @@ -0,0 +1,35 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + + ListNode* solve(ListNode* head, int val) + { + if(head == NULL)return head; + if(head->val == val) + { + return solve(head->next,val); + } + else + { + head->next = solve(head->next,val); + return head; + } + return NULL; + } + + ListNode* removeElements(ListNode* head, int val) { + ListNode * dummy = new ListNode(-1); + dummy->next = head; + dummy = solve(dummy,val); + return dummy->next; + } +}; \ No newline at end of file diff --git a/203-remove-linked-list-elements/NOTES.md b/203-remove-linked-list-elements/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/203-remove-linked-list-elements/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/203-remove-linked-list-elements/README.md b/203-remove-linked-list-elements/README.md new file mode 100644 index 0000000..7548824 --- /dev/null +++ b/203-remove-linked-list-elements/README.md @@ -0,0 +1,30 @@ +

203. Remove Linked List Elements

Easy


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

+ +

 

+

Example 1:

+ +
Input: head = [1,2,6,3,4,5,6], val = 6
+Output: [1,2,3,4,5]
+
+ +

Example 2:

+ +
Input: head = [], val = 1
+Output: []
+
+ +

Example 3:

+ +
Input: head = [7,7,7,7], val = 7
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 104].
  • +
  • 1 <= Node.val <= 50
  • +
  • 0 <= val <= 50
  • +
+
\ No newline at end of file diff --git a/206-reverse-linked-list/206-reverse-linked-list.cpp b/206-reverse-linked-list/206-reverse-linked-list.cpp new file mode 100644 index 0000000..029d188 --- /dev/null +++ b/206-reverse-linked-list/206-reverse-linked-list.cpp @@ -0,0 +1,23 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + if(head == NULL || head->next == NULL) + return head; + + ListNode* nextNode = head->next; + ListNode * reversed = reverseList(nextNode); + nextNode->next = head; + head->next = NULL; + return reversed; + } +}; \ No newline at end of file diff --git a/206-reverse-linked-list/NOTES.md b/206-reverse-linked-list/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/206-reverse-linked-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/206-reverse-linked-list/README.md b/206-reverse-linked-list/README.md new file mode 100644 index 0000000..8343480 --- /dev/null +++ b/206-reverse-linked-list/README.md @@ -0,0 +1,32 @@ +

206. Reverse Linked List

Easy


Given the head of a singly linked list, reverse the list, and return the reversed list.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5]
+Output: [5,4,3,2,1]
+
+ +

Example 2:

+ +
Input: head = [1,2]
+Output: [2,1]
+
+ +

Example 3:

+ +
Input: head = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is the range [0, 5000].
  • +
  • -5000 <= Node.val <= 5000
  • +
+ +

 

+

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

+
\ No newline at end of file diff --git a/209-minimum-size-subarray-sum/209-minimum-size-subarray-sum.cpp b/209-minimum-size-subarray-sum/209-minimum-size-subarray-sum.cpp new file mode 100644 index 0000000..699e4a8 --- /dev/null +++ b/209-minimum-size-subarray-sum/209-minimum-size-subarray-sum.cpp @@ -0,0 +1,64 @@ +class Solution { +public: + + int maxSumOfSizeK(vector &nums,int k) + { + int maxi = INT_MIN; + int sum = 0; + for(int i=0;i& nums) +{ + int n = nums.size(); + int ans = INT_MAX; + int left = 0; + int sum = 0; + for (int i = 0; i < n; i++) { + sum += nums[i]; + while (sum >= s) { + ans = min(ans, i + 1 - left); + sum -= nums[left++]; + } + } + return (ans != INT_MAX) ? ans : 0; +} +}; + + + + + + + + // int low = 1; +// int high = nums.size(); + +// while(low < high) +// { +// int mid = low + (high-low)/2; + +// if(maxSumOfSizeK(nums,mid) >= target) +// { +// high = mid; +// } +// else if(maxSumOfSizeK(nums,mid) < target) +// { +// low = mid+1; +// } +// } +// if(maxSumOfSizeK(nums,low) >= target) +// return low; +// else +// return 0; \ No newline at end of file diff --git a/209-minimum-size-subarray-sum/NOTES.md b/209-minimum-size-subarray-sum/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/209-minimum-size-subarray-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/209-minimum-size-subarray-sum/README.md b/209-minimum-size-subarray-sum/README.md new file mode 100644 index 0000000..4b03299 --- /dev/null +++ b/209-minimum-size-subarray-sum/README.md @@ -0,0 +1,33 @@ +

209. Minimum Size Subarray Sum

Medium


Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.

+ +

 

+

Example 1:

+ +
Input: target = 7, nums = [2,3,1,2,4,3]
+Output: 2
+Explanation: The subarray [4,3] has the minimal length under the problem constraint.
+
+ +

Example 2:

+ +
Input: target = 4, nums = [1,4,4]
+Output: 1
+
+ +

Example 3:

+ +
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= target <= 109
  • +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 105
  • +
+ +

 

+Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)).
\ No newline at end of file diff --git a/21-merge-two-sorted-lists/21-merge-two-sorted-lists.cpp b/21-merge-two-sorted-lists/21-merge-two-sorted-lists.cpp new file mode 100644 index 0000000..a8a0fd3 --- /dev/null +++ b/21-merge-two-sorted-lists/21-merge-two-sorted-lists.cpp @@ -0,0 +1,46 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + + if(list1 == NULL)return list2; + if(list2 == NULL)return list1; + + ListNode * dummy = new ListNode; + ListNode * head = dummy; + + while(list1 && list2) + { + if(list1->val <= list2->val) + { + head->next = list1; + list1 = list1->next; + } + else + { + head->next = list2; + list2 = list2->next; + } + head = head->next; + } + + if(list1) + { + head->next = list1; + } + if(list2) + { + head->next = list2; + } + return dummy->next; + } +}; \ No newline at end of file diff --git a/21-merge-two-sorted-lists/NOTES.md b/21-merge-two-sorted-lists/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/21-merge-two-sorted-lists/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/21-merge-two-sorted-lists/README.md b/21-merge-two-sorted-lists/README.md new file mode 100644 index 0000000..b5058a6 --- /dev/null +++ b/21-merge-two-sorted-lists/README.md @@ -0,0 +1,34 @@ +

21. Merge Two Sorted Lists

Easy


You are given the heads of two sorted linked lists list1 and list2.

+ +

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

+ +

Return the head of the merged linked list.

+ +

 

+

Example 1:

+ +
Input: list1 = [1,2,4], list2 = [1,3,4]
+Output: [1,1,2,3,4,4]
+
+ +

Example 2:

+ +
Input: list1 = [], list2 = []
+Output: []
+
+ +

Example 3:

+ +
Input: list1 = [], list2 = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in both lists is in the range [0, 50].
  • +
  • -100 <= Node.val <= 100
  • +
  • Both list1 and list2 are sorted in non-decreasing order.
  • +
+
\ No newline at end of file diff --git a/2145-count-the-hidden-sequences/2145-count-the-hidden-sequences.cpp b/2145-count-the-hidden-sequences/2145-count-the-hidden-sequences.cpp new file mode 100644 index 0000000..24d2c7d --- /dev/null +++ b/2145-count-the-hidden-sequences/2145-count-the-hidden-sequences.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int numberOfArrays(vector& diff, int lower, int upper) { + long a = 0, ma = 0, mi = 0; + for (int d: diff) { + a += d; + ma = max(ma, a); + mi = min(mi, a); + } + return max(0L, (upper - lower) - (ma - mi) + 1); + } +}; \ No newline at end of file diff --git a/2145-count-the-hidden-sequences/NOTES.md b/2145-count-the-hidden-sequences/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/2145-count-the-hidden-sequences/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2145-count-the-hidden-sequences/README.md b/2145-count-the-hidden-sequences/README.md new file mode 100644 index 0000000..dc0188a --- /dev/null +++ b/2145-count-the-hidden-sequences/README.md @@ -0,0 +1,57 @@ +

2145. Count the Hidden Sequences

Medium


You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i].

+ +

You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain.

+ +
    +
  • For example, given differences = [1, -3, 4], lower = 1, upper = 6, the hidden sequence is a sequence of length 4 whose elements are in between 1 and 6 (inclusive). + +
      +
    • [3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences.
    • +
    • [5, 6, 3, 7] is not possible since it contains an element greater than 6.
    • +
    • [1, 2, 3, 4] is not possible since the differences are not correct.
    • +
    +
  • +
+ +

Return the number of possible hidden sequences there are. If there are no possible sequences, return 0.

+ +

 

+

Example 1:

+ +
Input: differences = [1,-3,4], lower = 1, upper = 6
+Output: 2
+Explanation: The possible hidden sequences are:
+- [3, 4, 1, 5]
+- [4, 5, 2, 6]
+Thus, we return 2.
+
+ +

Example 2:

+ +
Input: differences = [3,-4,5,1,-2], lower = -4, upper = 5
+Output: 4
+Explanation: The possible hidden sequences are:
+- [-3, 0, -4, 1, 2, 0]
+- [-2, 1, -3, 2, 3, 1]
+- [-1, 2, -2, 3, 4, 2]
+- [0, 3, -1, 4, 5, 3]
+Thus, we return 4.
+
+ +

Example 3:

+ +
Input: differences = [4,-7,2], lower = 3, upper = 6
+Output: 0
+Explanation: There are no possible hidden sequences. Thus, we return 0.
+
+ +

 

+

Constraints:

+ +
    +
  • n == differences.length
  • +
  • 1 <= n <= 105
  • +
  • -105 <= differences[i] <= 105
  • +
  • -105 <= lower <= upper <= 105
  • +
+
\ No newline at end of file diff --git a/2202-maximize-the-topmost-element-after-k-moves/NOTES.md b/2202-maximize-the-topmost-element-after-k-moves/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/2202-maximize-the-topmost-element-after-k-moves/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2202-maximize-the-topmost-element-after-k-moves/README.md b/2202-maximize-the-topmost-element-after-k-moves/README.md new file mode 100644 index 0000000..d268f84 --- /dev/null +++ b/2202-maximize-the-topmost-element-after-k-moves/README.md @@ -0,0 +1,44 @@ +

2202. Maximize the Topmost Element After K Moves

Medium


You are given a 0-indexed integer array nums representing the contents of a pile, where nums[0] is the topmost element of the pile.

+ +

In one move, you can perform either of the following:

+ +
    +
  • If the pile is not empty, remove the topmost element of the pile.
  • +
  • If there are one or more removed elements, add any one of them back onto the pile. This element becomes the new topmost element.
  • +
+ +

You are also given an integer k, which denotes the total number of moves to be made.

+ +

Return the maximum value of the topmost element of the pile possible after exactly k moves. In case it is not possible to obtain a non-empty pile after k moves, return -1.

+ +

 

+

Example 1:

+ +
Input: nums = [5,2,2,4,0,6], k = 4
+Output: 5
+Explanation:
+One of the ways we can end with 5 at the top of the pile after 4 moves is as follows:
+- Step 1: Remove the topmost element = 5. The pile becomes [2,2,4,0,6].
+- Step 2: Remove the topmost element = 2. The pile becomes [2,4,0,6].
+- Step 3: Remove the topmost element = 2. The pile becomes [4,0,6].
+- Step 4: Add 5 back onto the pile. The pile becomes [5,4,0,6].
+Note that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves.
+
+ +

Example 2:

+ +
Input: nums = [2], k = 1
+Output: -1
+Explanation: 
+In the first move, our only option is to pop the topmost element of the pile.
+Since it is not possible to obtain a non-empty pile after one move, we return -1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 0 <= nums[i], k <= 109
  • +
+
\ No newline at end of file diff --git a/2207-maximize-number-of-subsequences-in-a-string/2207-maximize-number-of-subsequences-in-a-string.cpp b/2207-maximize-number-of-subsequences-in-a-string/2207-maximize-number-of-subsequences-in-a-string.cpp new file mode 100644 index 0000000..095e3cf --- /dev/null +++ b/2207-maximize-number-of-subsequences-in-a-string/2207-maximize-number-of-subsequences-in-a-string.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + + long long maximumSubsequenceCount(string text, string pattern) { + long long ans = 0; + int a = 0; + int b = 0; + + for(int i=0;ib) + { + b++; + text += pattern[1]; + } + else + { + a++; + text = pattern[0] + text; + } + + for(int i=0;i2207. Maximize Number of Subsequences in a String

Medium


You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters.

+ +

You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text.

+ +

Return the maximum number of times pattern can occur as a subsequence of the modified text.

+ +

A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.

+ +

 

+

Example 1:

+ +
Input: text = "abdcdbc", pattern = "ac"
+Output: 4
+Explanation:
+If we add pattern[0] = 'a' in between text[1] and text[2], we get "abadcdbc". Now, the number of times "ac" occurs as a subsequence is 4.
+Some other strings which have 4 subsequences "ac" after adding a character to text are "aabdcdbc" and "abdacdbc".
+However, strings such as "abdcadbc", "abdccdbc", and "abdcdbcc", although obtainable, have only 3 subsequences "ac" and are thus suboptimal.
+It can be shown that it is not possible to get more than 4 subsequences "ac" by adding only one character.
+
+ +

Example 2:

+ +
Input: text = "aabb", pattern = "ab"
+Output: 6
+Explanation:
+Some of the strings which can be obtained from text and have 6 subsequences "ab" are "aaabb", "aaabb", and "aabbb".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= text.length <= 105
  • +
  • pattern.length == 2
  • +
  • text and pattern consist only of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/221-maximal-square/NOTES.md b/221-maximal-square/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/221-maximal-square/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/221-maximal-square/README.md b/221-maximal-square/README.md new file mode 100644 index 0000000..e221710 --- /dev/null +++ b/221-maximal-square/README.md @@ -0,0 +1,31 @@ +

221. Maximal Square

Medium


Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

+ +

 

+

Example 1:

+ +
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
+Output: 4
+
+ +

Example 2:

+ +
Input: matrix = [["0","1"],["1","0"]]
+Output: 1
+
+ +

Example 3:

+ +
Input: matrix = [["0"]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 300
  • +
  • matrix[i][j] is '0' or '1'.
  • +
+
\ No newline at end of file diff --git a/225-implement-stack-using-queues/225-implement-stack-using-queues.cpp b/225-implement-stack-using-queues/225-implement-stack-using-queues.cpp new file mode 100644 index 0000000..e776d15 --- /dev/null +++ b/225-implement-stack-using-queues/225-implement-stack-using-queues.cpp @@ -0,0 +1,40 @@ +class MyStack { +public: queue q; + MyStack() { + + } + + void push(int x) { + q.push(x); + int size = q.size(); + for(int i=1;ipush(x); + * int param_2 = obj->pop(); + * int param_3 = obj->top(); + * bool param_4 = obj->empty(); + */ \ No newline at end of file diff --git a/225-implement-stack-using-queues/NOTES.md b/225-implement-stack-using-queues/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/225-implement-stack-using-queues/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/225-implement-stack-using-queues/README.md b/225-implement-stack-using-queues/README.md new file mode 100644 index 0000000..451a9a8 --- /dev/null +++ b/225-implement-stack-using-queues/README.md @@ -0,0 +1,48 @@ +

225. Implement Stack using Queues

Easy


Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).

+ +

Implement the MyStack class:

+ +
    +
  • void push(int x) Pushes element x to the top of the stack.
  • +
  • int pop() Removes the element on the top of the stack and returns it.
  • +
  • int top() Returns the element on the top of the stack.
  • +
  • boolean empty() Returns true if the stack is empty, false otherwise.
  • +
+ +

Notes:

+ +
    +
  • You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.
  • +
  • Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.
  • +
+ +

 

+

Example 1:

+ +
Input
+["MyStack", "push", "push", "top", "pop", "empty"]
+[[], [1], [2], [], [], []]
+Output
+[null, null, null, 2, 2, false]
+
+Explanation
+MyStack myStack = new MyStack();
+myStack.push(1);
+myStack.push(2);
+myStack.top(); // return 2
+myStack.pop(); // return 2
+myStack.empty(); // return False
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= x <= 9
  • +
  • At most 100 calls will be made to push, pop, top, and empty.
  • +
  • All the calls to pop and top are valid.
  • +
+ +

 

+

Follow-up: Can you implement the stack using only one queue?

+
\ No newline at end of file diff --git a/229-majority-element-ii/229-majority-element-ii.cpp b/229-majority-element-ii/229-majority-element-ii.cpp new file mode 100644 index 0000000..9a59502 --- /dev/null +++ b/229-majority-element-ii/229-majority-element-ii.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + vector majorityElement(vector& nums) { + int freq1 = 0; + int freq2 = 0; + int num1 = 0; + int num2 = 1; + + for(int i=0;i ans; + if(count1 > nums.size()/3) + ans.push_back(num1); + if(count2> nums.size()/3) + ans.push_back(num2); + cout<229. Majority Element II

Medium


Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

+ +

 

+

Example 1:

+ +
Input: nums = [3,2,3]
+Output: [3]
+
+ +

Example 2:

+ +
Input: nums = [1]
+Output: [1]
+
+ +

Example 3:

+ +
Input: nums = [1,2]
+Output: [1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • -109 <= nums[i] <= 109
  • +
+ +

 

+

Follow up: Could you solve the problem in linear time and in O(1) space?

+
\ No newline at end of file diff --git a/23-merge-k-sorted-lists/23-merge-k-sorted-lists.cpp b/23-merge-k-sorted-lists/23-merge-k-sorted-lists.cpp new file mode 100644 index 0000000..271d541 --- /dev/null +++ b/23-merge-k-sorted-lists/23-merge-k-sorted-lists.cpp @@ -0,0 +1,59 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + + if(l1 == NULL) + return l2; + if(l2 == NULL) + return l1; + + if(l1->val >= l2->val) + { + ListNode * temp = l1; + l1 = l2; + l2 = temp; + } + + ListNode* res = l1; + + while(l2 != NULL && l1 != NULL) + { + ListNode * temp = NULL; + while(l1 != NULL && l2->val >= l1->val) + { + temp = l1; + l1 = l1->next; + } + temp -> next = l2; + + ListNode * tem = l1; + l1 = l2; + l2 = tem; + + } + return res; + + } + ListNode* mergeKLists(vector& lists) { + + if (lists.size() == 0) return NULL; + + ListNode* head = lists[0]; + + for (int i = 1; i < lists.size(); i++) + head = mergeTwoLists(head, lists[i]); + + return head; + } +}; \ No newline at end of file diff --git a/23-merge-k-sorted-lists/NOTES.md b/23-merge-k-sorted-lists/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/23-merge-k-sorted-lists/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/23-merge-k-sorted-lists/README.md b/23-merge-k-sorted-lists/README.md new file mode 100644 index 0000000..b6d6e1e --- /dev/null +++ b/23-merge-k-sorted-lists/README.md @@ -0,0 +1,43 @@ +

23. Merge k Sorted Lists

Hard


You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

+ +

Merge all the linked-lists into one sorted linked-list and return it.

+ +

 

+

Example 1:

+ +
Input: lists = [[1,4,5],[1,3,4],[2,6]]
+Output: [1,1,2,3,4,4,5,6]
+Explanation: The linked-lists are:
+[
+  1->4->5,
+  1->3->4,
+  2->6
+]
+merging them into one sorted list:
+1->1->2->3->4->4->5->6
+
+ +

Example 2:

+ +
Input: lists = []
+Output: []
+
+ +

Example 3:

+ +
Input: lists = [[]]
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • k == lists.length
  • +
  • 0 <= k <= 10^4
  • +
  • 0 <= lists[i].length <= 500
  • +
  • -10^4 <= lists[i][j] <= 10^4
  • +
  • lists[i] is sorted in ascending order.
  • +
  • The sum of lists[i].length won't exceed 10^4.
  • +
+
\ No newline at end of file diff --git a/231-power-of-two/231-power-of-two.cpp b/231-power-of-two/231-power-of-two.cpp new file mode 100644 index 0000000..8a4c971 --- /dev/null +++ b/231-power-of-two/231-power-of-two.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + bool isPowerOfTwo(int n) { + + if(n==1)return true; + if(n<=0)return false; + + if(n % 2 == 0 && isPowerOfTwo(n/2)) + return true; + else return false; + + + } +}; \ No newline at end of file diff --git a/231-power-of-two/NOTES.md b/231-power-of-two/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/231-power-of-two/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/231-power-of-two/README.md b/231-power-of-two/README.md new file mode 100644 index 0000000..66e316d --- /dev/null +++ b/231-power-of-two/README.md @@ -0,0 +1,34 @@ +

231. Power of Two

Easy


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: n = 1
+Output: true
+Explanation: 20 = 1
+
+ +

Example 2:

+ +
Input: n = 16
+Output: true
+Explanation: 24 = 16
+
+ +

Example 3:

+ +
Input: n = 3
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without loops/recursion?
\ No newline at end of file diff --git a/232-implement-queue-using-stacks/232-implement-queue-using-stacks.cpp b/232-implement-queue-using-stacks/232-implement-queue-using-stacks.cpp new file mode 100644 index 0000000..cbb540a --- /dev/null +++ b/232-implement-queue-using-stacks/232-implement-queue-using-stacks.cpp @@ -0,0 +1,44 @@ +class MyQueue { +public: + MyQueue() { + + } + stack s1; + stack s2; + void push(int x) { + while(s1.size()) + { + s2.push(s1.top()); + s1.pop(); + } + s1.push(x); + while(s2.size()) + { + s1.push(s2.top()); + s2.pop(); + } + } + + int pop() { + int ans = s1.top(); + s1.pop(); + return ans; + } + + int peek() { + return s1.top(); + } + + bool empty() { + return s1.size() == 0 ; + } +}; + +/** + * Your MyQueue object will be instantiated and called as such: + * MyQueue* obj = new MyQueue(); + * obj->push(x); + * int param_2 = obj->pop(); + * int param_3 = obj->peek(); + * bool param_4 = obj->empty(); + */ \ No newline at end of file diff --git a/232-implement-queue-using-stacks/NOTES.md b/232-implement-queue-using-stacks/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/232-implement-queue-using-stacks/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/232-implement-queue-using-stacks/README.md b/232-implement-queue-using-stacks/README.md new file mode 100644 index 0000000..5268042 --- /dev/null +++ b/232-implement-queue-using-stacks/README.md @@ -0,0 +1,48 @@ +

232. Implement Queue using Stacks

Easy


Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

+ +

Implement the MyQueue class:

+ +
    +
  • void push(int x) Pushes element x to the back of the queue.
  • +
  • int pop() Removes the element from the front of the queue and returns it.
  • +
  • int peek() Returns the element at the front of the queue.
  • +
  • boolean empty() Returns true if the queue is empty, false otherwise.
  • +
+ +

Notes:

+ +
    +
  • You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • +
  • Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
  • +
+ +

 

+

Example 1:

+ +
Input
+["MyQueue", "push", "push", "peek", "pop", "empty"]
+[[], [1], [2], [], [], []]
+Output
+[null, null, null, 1, 1, false]
+
+Explanation
+MyQueue myQueue = new MyQueue();
+myQueue.push(1); // queue is: [1]
+myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
+myQueue.peek(); // return 1
+myQueue.pop(); // return 1, queue is [2]
+myQueue.empty(); // return false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= x <= 9
  • +
  • At most 100 calls will be made to push, pop, peek, and empty.
  • +
  • All the calls to pop and peek are valid.
  • +
+ +

 

+

Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.

+
\ No newline at end of file diff --git a/234-palindrome-linked-list/234-palindrome-linked-list.cpp b/234-palindrome-linked-list/234-palindrome-linked-list.cpp new file mode 100644 index 0000000..766188f --- /dev/null +++ b/234-palindrome-linked-list/234-palindrome-linked-list.cpp @@ -0,0 +1,55 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode * reverse(ListNode * head) + { + if(head == NULL || head->next == NULL) + return head; + ListNode * curr = head; + ListNode * pre = NULL; + ListNode * nex = NULL; + + while(curr != NULL) + { + nex = curr->next; + curr->next = pre; + pre = curr; + curr = nex; + } + + return pre; + } + bool isPalindrome(ListNode* head) { + + if(head == NULL || head->next == NULL) + return true; + ListNode * slow = head; + ListNode * fast = head; + while(fast->next != NULL && fast->next->next != NULL) + { + slow = slow->next; + fast = fast->next->next; + } + slow->next = reverse(slow->next); + slow = slow->next; + ListNode * start = head; + while(slow != NULL) + { + if(slow->val != start->val) + return false; + + slow = slow->next; + start = start->next; + } + return true; + } +}; \ No newline at end of file diff --git a/234-palindrome-linked-list/NOTES.md b/234-palindrome-linked-list/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/234-palindrome-linked-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/236-lowest-common-ancestor-of-a-binary-tree/236-lowest-common-ancestor-of-a-binary-tree.cpp b/236-lowest-common-ancestor-of-a-binary-tree/236-lowest-common-ancestor-of-a-binary-tree.cpp new file mode 100644 index 0000000..af1466e --- /dev/null +++ b/236-lowest-common-ancestor-of-a-binary-tree/236-lowest-common-ancestor-of-a-binary-tree.cpp @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if(root == NULL || p == NULL || q == NULL) + return NULL; + + if(root == p || root == q) + return root; + + TreeNode * leftLCA = lowestCommonAncestor(root->left,p,q); + TreeNode * rightLCA = lowestCommonAncestor(root->right,p,q); + + if(leftLCA == NULL)return rightLCA; + else if(rightLCA == NULL)return leftLCA; + else + return root; + } +}; \ No newline at end of file diff --git a/236-lowest-common-ancestor-of-a-binary-tree/NOTES.md b/236-lowest-common-ancestor-of-a-binary-tree/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/236-lowest-common-ancestor-of-a-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/236-lowest-common-ancestor-of-a-binary-tree/README.md b/236-lowest-common-ancestor-of-a-binary-tree/README.md new file mode 100644 index 0000000..3261cce --- /dev/null +++ b/236-lowest-common-ancestor-of-a-binary-tree/README.md @@ -0,0 +1,36 @@ +

236. Lowest Common Ancestor of a Binary Tree

Medium


Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

+ +

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

+ +

 

+

Example 1:

+ +
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
+Output: 3
+Explanation: The LCA of nodes 5 and 1 is 3.
+
+ +

Example 2:

+ +
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
+Output: 5
+Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
+
+ +

Example 3:

+ +
Input: root = [1,2], p = 1, q = 2
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 105].
  • +
  • -109 <= Node.val <= 109
  • +
  • All Node.val are unique.
  • +
  • p != q
  • +
  • p and q will exist in the tree.
  • +
+
\ No newline at end of file diff --git a/237-delete-node-in-a-linked-list/237-delete-node-in-a-linked-list.cpp b/237-delete-node-in-a-linked-list/237-delete-node-in-a-linked-list.cpp new file mode 100644 index 0000000..99361c5 --- /dev/null +++ b/237-delete-node-in-a-linked-list/237-delete-node-in-a-linked-list.cpp @@ -0,0 +1,17 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + void deleteNode(ListNode* node) { + node->val = node->next->val; + ListNode * nextNode = node->next; + node->next = node->next->next ; + delete nextNode; + } +}; \ No newline at end of file diff --git a/237-delete-node-in-a-linked-list/NOTES.md b/237-delete-node-in-a-linked-list/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/237-delete-node-in-a-linked-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/237-delete-node-in-a-linked-list/README.md b/237-delete-node-in-a-linked-list/README.md new file mode 100644 index 0000000..797f85a --- /dev/null +++ b/237-delete-node-in-a-linked-list/README.md @@ -0,0 +1,29 @@ +

237. Delete Node in a Linked List

Easy


Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.

+ +

It is guaranteed that the node to be deleted is not a tail node in the list.

+ +

 

+

Example 1:

+ +
Input: head = [4,5,1,9], node = 5
+Output: [4,1,9]
+Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
+
+ +

Example 2:

+ +
Input: head = [4,5,1,9], node = 1
+Output: [4,5,9]
+Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the given list is in the range [2, 1000].
  • +
  • -1000 <= Node.val <= 1000
  • +
  • The value of each node in the list is unique.
  • +
  • The node to be deleted is in the list and is not a tail node
  • +
+
\ No newline at end of file diff --git a/238-product-of-array-except-self/238-product-of-array-except-self.cpp b/238-product-of-array-except-self/238-product-of-array-except-self.cpp new file mode 100644 index 0000000..d35747c --- /dev/null +++ b/238-product-of-array-except-self/238-product-of-array-except-self.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector productExceptSelf(vector& nums) { + int n=nums.size(); + int fromBegin=1; + int fromLast=1; + vector res(n,1); + + for(int i=0;i238. Product of Array Except Self

Medium


Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

+ +

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

+ +

You must write an algorithm that runs in O(n) time and without using the division operation.

+ +

 

+

Example 1:

+
Input: nums = [1,2,3,4]
+Output: [24,12,8,6]
+

Example 2:

+
Input: nums = [-1,1,0,-3,3]
+Output: [0,0,9,0,0]
+
+

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 105
  • +
  • -30 <= nums[i] <= 30
  • +
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
  • +
+ +

 

+

Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

+
\ No newline at end of file diff --git a/239-sliding-window-maximum/NOTES.md b/239-sliding-window-maximum/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/239-sliding-window-maximum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/239-sliding-window-maximum/README.md b/239-sliding-window-maximum/README.md new file mode 100644 index 0000000..b5410d4 --- /dev/null +++ b/239-sliding-window-maximum/README.md @@ -0,0 +1,35 @@ +

239. Sliding Window Maximum

Hard


You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

+ +

Return the max sliding window.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
+Output: [3,3,5,5,6,7]
+Explanation: 
+Window position                Max
+---------------               -----
+[1  3  -1] -3  5  3  6  7       3
+ 1 [3  -1  -3] 5  3  6  7       3
+ 1  3 [-1  -3  5] 3  6  7       5
+ 1  3  -1 [-3  5  3] 6  7       5
+ 1  3  -1  -3 [5  3  6] 7       6
+ 1  3  -1  -3  5 [3  6  7]      7
+
+ +

Example 2:

+ +
Input: nums = [1], k = 1
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -104 <= nums[i] <= 104
  • +
  • 1 <= k <= nums.length
  • +
+
\ No newline at end of file diff --git a/24-swap-nodes-in-pairs/24-swap-nodes-in-pairs.cpp b/24-swap-nodes-in-pairs/24-swap-nodes-in-pairs.cpp new file mode 100644 index 0000000..becf0ed --- /dev/null +++ b/24-swap-nodes-in-pairs/24-swap-nodes-in-pairs.cpp @@ -0,0 +1,29 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + + if(head == NULL || head->next == NULL) + return head; + + ListNode * newNode = swapPairs(head->next->next); + + int temp = head->val; + head->val = head->next->val; + head->next->val = temp; + + head->next->next = newNode; + + return head; + + } +}; \ No newline at end of file diff --git a/24-swap-nodes-in-pairs/NOTES.md b/24-swap-nodes-in-pairs/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/24-swap-nodes-in-pairs/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/24-swap-nodes-in-pairs/README.md b/24-swap-nodes-in-pairs/README.md new file mode 100644 index 0000000..562c353 --- /dev/null +++ b/24-swap-nodes-in-pairs/README.md @@ -0,0 +1,29 @@ +

24. Swap Nodes in Pairs

Medium


Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4]
+Output: [2,1,4,3]
+
+ +

Example 2:

+ +
Input: head = []
+Output: []
+
+ +

Example 3:

+ +
Input: head = [1]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 100].
  • +
  • 0 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/242-valid-anagram/242-valid-anagram.cpp b/242-valid-anagram/242-valid-anagram.cpp new file mode 100644 index 0000000..8550839 --- /dev/null +++ b/242-valid-anagram/242-valid-anagram.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + bool isAnagram(string s, string t) { + sort(s.begin(), s.end()); + sort(t.begin(), t.end()); + return s == t; + } +}; \ No newline at end of file diff --git a/242-valid-anagram/NOTES.md b/242-valid-anagram/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/242-valid-anagram/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/242-valid-anagram/README.md b/242-valid-anagram/README.md new file mode 100644 index 0000000..d1bed75 --- /dev/null +++ b/242-valid-anagram/README.md @@ -0,0 +1,23 @@ +

242. Valid Anagram

Easy


Given two strings s and t, return true if t is an anagram of s, and false otherwise.

+ +

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

+ +

 

+

Example 1:

+
Input: s = "anagram", t = "nagaram"
+Output: true
+

Example 2:

+
Input: s = "rat", t = "car"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length, t.length <= 5 * 104
  • +
  • s and t consist of lowercase English letters.
  • +
+ +

 

+

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

+
\ No newline at end of file diff --git a/25-reverse-nodes-in-k-group/NOTES.md b/25-reverse-nodes-in-k-group/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/25-reverse-nodes-in-k-group/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/25-reverse-nodes-in-k-group/README.md b/25-reverse-nodes-in-k-group/README.md new file mode 100644 index 0000000..f173eb6 --- /dev/null +++ b/25-reverse-nodes-in-k-group/README.md @@ -0,0 +1,31 @@ +

25. Reverse Nodes in k-Group

Hard


Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.

+ +

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

+ +

You may not alter the values in the list's nodes, only nodes themselves may be changed.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5], k = 2
+Output: [2,1,4,3,5]
+
+ +

Example 2:

+ +
Input: head = [1,2,3,4,5], k = 3
+Output: [3,2,1,4,5]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is n.
  • +
  • 1 <= k <= n <= 5000
  • +
  • 0 <= Node.val <= 1000
  • +
+ +

 

+

Follow-up: Can you solve the problem in O(1) extra memory space?

+
\ No newline at end of file diff --git a/258-add-digits/258-add-digits.cpp b/258-add-digits/258-add-digits.cpp new file mode 100644 index 0000000..a66bf59 --- /dev/null +++ b/258-add-digits/258-add-digits.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int addDigits(int num) { + if(num ==0)return 0; + + if(num % 9) + { + return num % 9; + } + else + { + return 9; + } + + } +}; \ No newline at end of file diff --git a/258-add-digits/NOTES.md b/258-add-digits/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/258-add-digits/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/258-add-digits/README.md b/258-add-digits/README.md new file mode 100644 index 0000000..4aba281 --- /dev/null +++ b/258-add-digits/README.md @@ -0,0 +1,29 @@ +

258. Add Digits

Easy


Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

+ +

 

+

Example 1:

+ +
Input: num = 38
+Output: 2
+Explanation: The process is
+38 --> 3 + 8 --> 11
+11 --> 1 + 1 --> 2 
+Since 2 has only one digit, return it.
+
+ +

Example 2:

+ +
Input: num = 0
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= num <= 231 - 1
  • +
+ +

 

+

Follow up: Could you do it without any loop/recursion in O(1) runtime?

+
\ No newline at end of file diff --git a/26-remove-duplicates-from-sorted-array/NOTES.md b/26-remove-duplicates-from-sorted-array/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/26-remove-duplicates-from-sorted-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/26-remove-duplicates-from-sorted-array/README.md b/26-remove-duplicates-from-sorted-array/README.md new file mode 100644 index 0000000..d22a6d4 --- /dev/null +++ b/26-remove-duplicates-from-sorted-array/README.md @@ -0,0 +1,51 @@ +

26. Remove Duplicates from Sorted Array

Easy


Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

+ +

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

+ +

Return k after placing the final result in the first k slots of nums.

+ +

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

+ +

Custom Judge:

+ +

The judge will test your solution with the following code:

+ +
int[] nums = [...]; // Input array
+int[] expectedNums = [...]; // The expected answer with correct length
+
+int k = removeDuplicates(nums); // Calls your implementation
+
+assert k == expectedNums.length;
+for (int i = 0; i < k; i++) {
+    assert nums[i] == expectedNums[i];
+}
+
+ +

If all assertions pass, then your solution will be accepted.

+ +

 

+

Example 1:

+ +
Input: nums = [1,1,2]
+Output: 2, nums = [1,2,_]
+Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
+It does not matter what you leave beyond the returned k (hence they are underscores).
+
+ +

Example 2:

+ +
Input: nums = [0,0,1,1,1,2,2,3,3,4]
+Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
+Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
+It does not matter what you leave beyond the returned k (hence they are underscores).
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -100 <= nums[i] <= 100
  • +
  • nums is sorted in non-decreasing order.
  • +
+
\ No newline at end of file diff --git a/283-move-zeroes/283-move-zeroes.cpp b/283-move-zeroes/283-move-zeroes.cpp new file mode 100644 index 0000000..213f6df --- /dev/null +++ b/283-move-zeroes/283-move-zeroes.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + void moveZeroes(vector& nums) { + int i=0; + int j=0; + + while(j283. Move Zeroes

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [0,1,0,3,12]
+Output: [1,3,12,0,0]
+

Example 2:

+
Input: nums = [0]
+Output: [0]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+ +

 

+Follow up: Could you minimize the total number of operations done?
\ No newline at end of file diff --git a/287-find-the-duplicate-number/287-find-the-duplicate-number.cpp b/287-find-the-duplicate-number/287-find-the-duplicate-number.cpp new file mode 100644 index 0000000..af87c52 --- /dev/null +++ b/287-find-the-duplicate-number/287-find-the-duplicate-number.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int findDuplicate(vector& nums) { + int slow = nums[0]; + int fast = nums[0]; + + do{ + slow = nums[slow]; + fast = nums[nums[fast]]; + }while(slow != fast); + + fast = nums[0]; + while(slow != fast) + { + slow = nums[slow]; + fast = nums[fast]; + } + + return fast; + } +}; \ No newline at end of file diff --git a/287-find-the-duplicate-number/NOTES.md b/287-find-the-duplicate-number/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/287-find-the-duplicate-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/287-find-the-duplicate-number/README.md b/287-find-the-duplicate-number/README.md new file mode 100644 index 0000000..7e26c34 --- /dev/null +++ b/287-find-the-duplicate-number/README.md @@ -0,0 +1,37 @@ +

287. Find the Duplicate Number

Medium


Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

+ +

There is only one repeated number in nums, return this repeated number.

+ +

You must solve the problem without modifying the array nums and uses only constant extra space.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,4,2,2]
+Output: 2
+
+ +

Example 2:

+ +
Input: nums = [3,1,3,4,2]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • nums.length == n + 1
  • +
  • 1 <= nums[i] <= n
  • +
  • All the integers in nums appear only once except for precisely one integer which appears two or more times.
  • +
+ +

 

+

Follow up:

+ +
    +
  • How can we prove that at least one duplicate number must exist in nums?
  • +
  • Can you solve the problem in linear runtime complexity?
  • +
+
\ No newline at end of file diff --git a/30-substring-with-concatenation-of-all-words/30-substring-with-concatenation-of-all-words.cpp b/30-substring-with-concatenation-of-all-words/30-substring-with-concatenation-of-all-words.cpp new file mode 100644 index 0000000..19c628a --- /dev/null +++ b/30-substring-with-concatenation-of-all-words/30-substring-with-concatenation-of-all-words.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + vector findSubstring(string s, vector& words) { + int len = words[0].size(), n = words.size(), ssize = s.size(), left, found; + vector res; + + unordered_map freq, tmp; + for (auto word : words) freq[word]++; + + for (int i = 0; i < len; i++) { + tmp.clear(); + left = i, found = 0; + + for (int j = i; j <= ssize - len; j += len) { + string curr = s.substr(j, len); + + if (freq.find(curr) != freq.end()) { + tmp[curr]++; + found++; + + while (freq[curr] < tmp[curr]) { + tmp[s.substr(left, len)]--; + found--; + left += len; + } + + if (found == n) res.push_back(left); + } + + else { + tmp.clear(); + found = 0; + left = j + len; + } + } + } + return res; + } +}; \ No newline at end of file diff --git a/30-substring-with-concatenation-of-all-words/NOTES.md b/30-substring-with-concatenation-of-all-words/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/30-substring-with-concatenation-of-all-words/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/30-substring-with-concatenation-of-all-words/README.md b/30-substring-with-concatenation-of-all-words/README.md new file mode 100644 index 0000000..8799313 --- /dev/null +++ b/30-substring-with-concatenation-of-all-words/README.md @@ -0,0 +1,35 @@ +

30. Substring with Concatenation of All Words

Hard


You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters.

+ +

You can return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: s = "barfoothefoobarman", words = ["foo","bar"]
+Output: [0,9]
+Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
+The output order does not matter, returning [9,0] is fine too.
+
+ +

Example 2:

+ +
Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
+Output: []
+
+ +

Example 3:

+ +
Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
+Output: [6,9,12]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • 1 <= words.length <= 5000
  • +
  • 1 <= words[i].length <= 30
  • +
  • s and words[i] consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/300-longest-increasing-subsequence/NOTES.md b/300-longest-increasing-subsequence/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/300-longest-increasing-subsequence/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/307-range-sum-query-mutable/NOTES.md b/307-range-sum-query-mutable/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/307-range-sum-query-mutable/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/307-range-sum-query-mutable/README.md b/307-range-sum-query-mutable/README.md new file mode 100644 index 0000000..8a476a2 --- /dev/null +++ b/307-range-sum-query-mutable/README.md @@ -0,0 +1,43 @@ +

307. Range Sum Query - Mutable

Medium


Given an integer array nums, handle multiple queries of the following types:

+ +
    +
  1. Update the value of an element in nums.
  2. +
  3. Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
  4. +
+ +

Implement the NumArray class:

+ +
    +
  • NumArray(int[] nums) Initializes the object with the integer array nums.
  • +
  • void update(int index, int val) Updates the value of nums[index] to be val.
  • +
  • int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).
  • +
+ +

 

+

Example 1:

+ +
Input
+["NumArray", "sumRange", "update", "sumRange"]
+[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
+Output
+[null, 9, null, 8]
+
+Explanation
+NumArray numArray = new NumArray([1, 3, 5]);
+numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9
+numArray.update(1, 2);   // nums = [1, 2, 5]
+numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -100 <= nums[i] <= 100
  • +
  • 0 <= index < nums.length
  • +
  • -100 <= val <= 100
  • +
  • 0 <= left <= right < nums.length
  • +
  • At most 3 * 104 calls will be made to update and sumRange.
  • +
+
\ No newline at end of file diff --git a/31-next-permutation/31-next-permutation.cpp b/31-next-permutation/31-next-permutation.cpp new file mode 100644 index 0000000..248c0d7 --- /dev/null +++ b/31-next-permutation/31-next-permutation.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + void nextPermutation(vector& nums) { + + int idx1; + int i; + for(i=nums.size()-2;i>=0;i--) + { + if(nums[i]=idx1;i--) + { + if(nums[idx1] < nums[i]) + { + idx2 = i; + break; + } + } + + swap(nums[idx1],nums[idx2]); + reverse(nums.begin()+idx1+1,nums.end()); + + + } + } +}; \ No newline at end of file diff --git a/31-next-permutation/NOTES.md b/31-next-permutation/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/31-next-permutation/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/316-remove-duplicate-letters/316-remove-duplicate-letters.cpp b/316-remove-duplicate-letters/316-remove-duplicate-letters.cpp new file mode 100644 index 0000000..2a0141b --- /dev/null +++ b/316-remove-duplicate-letters/316-remove-duplicate-letters.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + string removeDuplicateLetters(string s) { + vector cand(256, 0); + vector visited(256, false); + for (char c : s) + cand[c]++; + string result = "0"; + for (char c : s) { + cand[c]--; + if (visited[c]) continue; + while (c < result.back() && cand[result.back()]) { + visited[result.back()] = false; + result.pop_back(); + } + result += c; + visited[c] = true; + } + return result.substr(1); + } +}; \ No newline at end of file diff --git a/316-remove-duplicate-letters/NOTES.md b/316-remove-duplicate-letters/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/316-remove-duplicate-letters/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/316-remove-duplicate-letters/README.md b/316-remove-duplicate-letters/README.md new file mode 100644 index 0000000..52507ca --- /dev/null +++ b/316-remove-duplicate-letters/README.md @@ -0,0 +1,26 @@ +

316. Remove Duplicate Letters

Medium


Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

+ +

 

+

Example 1:

+ +
Input: s = "bcabc"
+Output: "abc"
+
+ +

Example 2:

+ +
Input: s = "cbacdcbc"
+Output: "acdb"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of lowercase English letters.
  • +
+ +

 

+

Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

+
\ No newline at end of file diff --git a/326-power-of-three/326-power-of-three.cpp b/326-power-of-three/326-power-of-three.cpp new file mode 100644 index 0000000..8d18cec --- /dev/null +++ b/326-power-of-three/326-power-of-three.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + bool isPowerOfThree(int n) { + + if(n==1)return true; + if(n<=0)return false; + + if(n % 3 == 0 && isPowerOfThree(n/3))return true; + return false; + } +}; \ No newline at end of file diff --git a/326-power-of-three/NOTES.md b/326-power-of-three/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/326-power-of-three/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/326-power-of-three/README.md b/326-power-of-three/README.md new file mode 100644 index 0000000..5d967bb --- /dev/null +++ b/326-power-of-three/README.md @@ -0,0 +1,32 @@ +

326. Power of Three

Easy


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: n = 27
+Output: true
+
+ +

Example 2:

+ +
Input: n = 0
+Output: false
+
+ +

Example 3:

+ +
Input: n = 9
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without loops/recursion?
\ No newline at end of file diff --git a/33-search-in-rotated-sorted-array/33-search-in-rotated-sorted-array.cpp b/33-search-in-rotated-sorted-array/33-search-in-rotated-sorted-array.cpp new file mode 100644 index 0000000..1145ebc --- /dev/null +++ b/33-search-in-rotated-sorted-array/33-search-in-rotated-sorted-array.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int search(vector& nums, int x) { + int low = 0; + int high = nums.size()-1; + int ans = -1; + while(low<=high) + { + int mid = low + (high-low)/2; + + if(nums[mid] == x) + return mid; + else if(nums[low] <= nums[mid]) + { + if(nums[low]<= x && x <= nums[mid]) + high = mid-1; + else + low = mid+1; + } + else + { + if(nums[mid]<= x && x <= nums[high]) + low = mid+1; + else + high = mid-1; + } + } + return -1; + } +}; \ No newline at end of file diff --git a/33-search-in-rotated-sorted-array/NOTES.md b/33-search-in-rotated-sorted-array/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/33-search-in-rotated-sorted-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/33-search-in-rotated-sorted-array/README.md b/33-search-in-rotated-sorted-array/README.md new file mode 100644 index 0000000..2fc6903 --- /dev/null +++ b/33-search-in-rotated-sorted-array/README.md @@ -0,0 +1,30 @@ +

33. Search in Rotated Sorted Array

Medium


There is an integer array nums sorted in ascending order (with distinct values).

+ +

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

+ +

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

+ +

You must write an algorithm with O(log n) runtime complexity.

+ +

 

+

Example 1:

+
Input: nums = [4,5,6,7,0,1,2], target = 0
+Output: 4
+

Example 2:

+
Input: nums = [4,5,6,7,0,1,2], target = 3
+Output: -1
+

Example 3:

+
Input: nums = [1], target = 0
+Output: -1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5000
  • +
  • -104 <= nums[i] <= 104
  • +
  • All values of nums are unique.
  • +
  • nums is an ascending array that is possibly rotated.
  • +
  • -104 <= target <= 104
  • +
+
\ No newline at end of file diff --git a/34-find-first-and-last-position-of-element-in-sorted-array/34-find-first-and-last-position-of-element-in-sorted-array.cpp b/34-find-first-and-last-position-of-element-in-sorted-array/34-find-first-and-last-position-of-element-in-sorted-array.cpp new file mode 100644 index 0000000..1ef48dd --- /dev/null +++ b/34-find-first-and-last-position-of-element-in-sorted-array/34-find-first-and-last-position-of-element-in-sorted-array.cpp @@ -0,0 +1,60 @@ +class Solution { +public: + + int lower(vector& nums, int target) + { + int low = 0; + int high = nums.size()-1; + int ans = -1; + + while(low<=high) + { + int mid = (low+high)>>1; + + if(nums[mid] == target) + { + ans = mid; + high = mid-1; + } + else if(nums[mid] > target) + high = mid - 1; + else + low = mid + 1; + } + return ans; + } + + int higher(vector& nums, int target) + { + int low = 0; + int high = nums.size()-1; + int ans = -1; + + while(low<=high) + { + int mid = (low+high)>>1; + + if(nums[mid] == target) + { + ans = mid; + low = mid+1; + } + else if(nums[mid] > target) + high = mid-1; + else + low = mid + 1; + } + return ans; + } + + vector searchRange(vector& nums, int target) { + + vector v(2); + + v[0] = lower(nums,target); + v[1] = higher(nums,target); + + return v; + + } +}; \ No newline at end of file diff --git a/34-find-first-and-last-position-of-element-in-sorted-array/README.md b/34-find-first-and-last-position-of-element-in-sorted-array/README.md new file mode 100644 index 0000000..84af2cc --- /dev/null +++ b/34-find-first-and-last-position-of-element-in-sorted-array/README.md @@ -0,0 +1,27 @@ +

34. Find First and Last Position of Element in Sorted Array

Medium


Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

+ +

If target is not found in the array, return [-1, -1].

+ +

You must write an algorithm with O(log n) runtime complexity.

+ +

 

+

Example 1:

+
Input: nums = [5,7,7,8,8,10], target = 8
+Output: [3,4]
+

Example 2:

+
Input: nums = [5,7,7,8,8,10], target = 6
+Output: [-1,-1]
+

Example 3:

+
Input: nums = [], target = 0
+Output: [-1,-1]
+
+

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
  • nums is a non-decreasing array.
  • +
  • -109 <= target <= 109
  • +
+
\ No newline at end of file diff --git a/342-power-of-four/342-power-of-four.cpp b/342-power-of-four/342-power-of-four.cpp new file mode 100644 index 0000000..da9d55a --- /dev/null +++ b/342-power-of-four/342-power-of-four.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + bool isPowerOfFour(int n) { + + if(n==1)return true; + if(n<=0)return false; + + if(n % 4 == 0 && isPowerOfFour(n/4))return true; + return false; + } +}; \ No newline at end of file diff --git a/342-power-of-four/NOTES.md b/342-power-of-four/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/342-power-of-four/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/342-power-of-four/README.md b/342-power-of-four/README.md new file mode 100644 index 0000000..c54783d --- /dev/null +++ b/342-power-of-four/README.md @@ -0,0 +1,24 @@ +

342. Power of Four

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: n = 16
+Output: true
+

Example 2:

+
Input: n = 5
+Output: false
+

Example 3:

+
Input: n = 1
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without loops/recursion?
\ No newline at end of file diff --git a/344-reverse-string/NOTES.md b/344-reverse-string/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/344-reverse-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/344-reverse-string/README.md b/344-reverse-string/README.md new file mode 100644 index 0000000..15ad161 --- /dev/null +++ b/344-reverse-string/README.md @@ -0,0 +1,20 @@ +

344. Reverse String

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: s = ["h","e","l","l","o"]
+Output: ["o","l","l","e","h"]
+

Example 2:

+
Input: s = ["H","a","n","n","a","h"]
+Output: ["h","a","n","n","a","H"]
+
+

 

+

Constraints:

+ + +
\ No newline at end of file diff --git a/345-reverse-vowels-of-a-string/345-reverse-vowels-of-a-string.cpp b/345-reverse-vowels-of-a-string/345-reverse-vowels-of-a-string.cpp new file mode 100644 index 0000000..8b0f51e --- /dev/null +++ b/345-reverse-vowels-of-a-string/345-reverse-vowels-of-a-string.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + + bool isvowel(char a) + { + if(a == 'a' || a=='A' || a == 'e'|| a == 'E'|| a == 'i' ||a == 'I'||a == 'O' ||a == 'o' || a== 'u' || a== 'U') + return true; + return false; + } + string reverseVowels(string s) { + int i = 0; + int j = s.size()-1; + while(i345. Reverse Vowels of a String

Easy


Given a string s, reverse only all the vowels in the string and return it.

+ +

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.

+ +

 

+

Example 1:

+
Input: s = "hello"
+Output: "holle"
+

Example 2:

+
Input: s = "leetcode"
+Output: "leotcede"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 3 * 105
  • +
  • s consist of printable ASCII characters.
  • +
+
\ No newline at end of file diff --git a/347-top-k-frequent-elements/347-top-k-frequent-elements.cpp b/347-top-k-frequent-elements/347-top-k-frequent-elements.cpp new file mode 100644 index 0000000..620978a --- /dev/null +++ b/347-top-k-frequent-elements/347-top-k-frequent-elements.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + unordered_map counts; + for(auto i : nums) ++counts[i]; + + // 1->3 + // 2->2 + // 3->1 + + vector> buckets(nums.size() + 1); + for(auto p : counts) + buckets[p.second].push_back(p.first); + reverse(begin(buckets), end(buckets)); + + vector res; + for(auto & bucket: buckets) + for(auto i : bucket) { + res.push_back(i); + if(res.size() == k) return res; + } + + return res; + } +}; \ No newline at end of file diff --git a/347-top-k-frequent-elements/NOTES.md b/347-top-k-frequent-elements/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/347-top-k-frequent-elements/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/347-top-k-frequent-elements/README.md b/347-top-k-frequent-elements/README.md new file mode 100644 index 0000000..8ae3d88 --- /dev/null +++ b/347-top-k-frequent-elements/README.md @@ -0,0 +1,22 @@ +

347. Top K Frequent Elements

Medium


Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

+ +

 

+

Example 1:

+
Input: nums = [1,1,1,2,2,3], k = 2
+Output: [1,2]
+

Example 2:

+
Input: nums = [1], k = 1
+Output: [1]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • k is in the range [1, the number of unique elements in the array].
  • +
  • It is guaranteed that the answer is unique.
  • +
+ +

 

+

Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

+
\ No newline at end of file diff --git a/35-search-insert-position/35-search-insert-position.cpp b/35-search-insert-position/35-search-insert-position.cpp new file mode 100644 index 0000000..e6f9aa4 --- /dev/null +++ b/35-search-insert-position/35-search-insert-position.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int searchInsert(vector& nums, int x) { + + int low = 0; + int high = nums.size(); + + while(lowx) + { + high = mid; + } + else + low = mid+1; + } + return low; + + } +}; \ No newline at end of file diff --git a/35-search-insert-position/NOTES.md b/35-search-insert-position/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/35-search-insert-position/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/35-search-insert-position/README.md b/35-search-insert-position/README.md new file mode 100644 index 0000000..2aebf3d --- /dev/null +++ b/35-search-insert-position/README.md @@ -0,0 +1,33 @@ +

35. Search Insert Position

Easy


Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

+ +

You must write an algorithm with O(log n) runtime complexity.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,5,6], target = 5
+Output: 2
+
+ +

Example 2:

+ +
Input: nums = [1,3,5,6], target = 2
+Output: 1
+
+ +

Example 3:

+ +
Input: nums = [1,3,5,6], target = 7
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums contains distinct values sorted in ascending order.
  • +
  • -104 <= target <= 104
  • +
+
\ No newline at end of file diff --git a/37-sudoku-solver/NOTES.md b/37-sudoku-solver/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/37-sudoku-solver/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/37-sudoku-solver/README.md b/37-sudoku-solver/README.md new file mode 100644 index 0000000..93d9b28 --- /dev/null +++ b/37-sudoku-solver/README.md @@ -0,0 +1,32 @@ +

37. Sudoku Solver

Hard


Write a program to solve a Sudoku puzzle by filling the empty cells.

+ +

A sudoku solution must satisfy all of the following rules:

+ +
    +
  1. Each of the digits 1-9 must occur exactly once in each row.
  2. +
  3. Each of the digits 1-9 must occur exactly once in each column.
  4. +
  5. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
  6. +
+ +

The '.' character indicates empty cells.

+ +

 

+

Example 1:

+ +
Input: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
+Output: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
+Explanation: The input board is shown above and the only valid solution is shown below:
+
+
+
+ +

 

+

Constraints:

+ +
    +
  • board.length == 9
  • +
  • board[i].length == 9
  • +
  • board[i][j] is a digit or '.'.
  • +
  • It is guaranteed that the input board has only one solution.
  • +
+
\ No newline at end of file diff --git a/38-count-and-say/38-count-and-say.cpp b/38-count-and-say/38-count-and-say.cpp new file mode 100644 index 0000000..4b2b3d6 --- /dev/null +++ b/38-count-and-say/38-count-and-say.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + string countAndSay(int n) { + if (n == 0) return ""; + string res = "1"; + while (--n) { + string cur = ""; + for (int i = 0; i < res.size(); i++) { + int count = 1; + while ((i + 1 < res.size()) && (res[i] == res[i + 1])){ + count++; + i++; + } + cur += to_string(count) + res[i]; + } + res = cur; + } + return res; +} +}; \ No newline at end of file diff --git a/38-count-and-say/NOTES.md b/38-count-and-say/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/38-count-and-say/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/38-count-and-say/README.md b/38-count-and-say/README.md new file mode 100644 index 0000000..41f82ca --- /dev/null +++ b/38-count-and-say/README.md @@ -0,0 +1,39 @@ +

38. Count and Say

Medium


The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

+ +
    +
  • countAndSay(1) = "1"
  • +
  • countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string.
  • +
+ +

To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.

+ +

For example, the saying and conversion for digit string "3322251":

+ +

Given a positive integer n, return the nth term of the count-and-say sequence.

+ +

 

+

Example 1:

+ +
Input: n = 1
+Output: "1"
+Explanation: This is the base case.
+
+ +

Example 2:

+ +
Input: n = 4
+Output: "1211"
+Explanation:
+countAndSay(1) = "1"
+countAndSay(2) = say "1" = one 1 = "11"
+countAndSay(3) = say "11" = two 1's = "21"
+countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 30
  • +
+
\ No newline at end of file diff --git a/382-linked-list-random-node/382-linked-list-random-node.cpp b/382-linked-list-random-node/382-linked-list-random-node.cpp new file mode 100644 index 0000000..2937a60 --- /dev/null +++ b/382-linked-list-random-node/382-linked-list-random-node.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + map mp; + Solution(ListNode* head) + { + ListNode *temp = head; + int i=0; + while(temp) + { + mp[i++]=temp; + temp=temp->next; + } + } + + int getRandom() + { + int n = mp.size(); + return mp[rand()%n]->val; + } +}; \ No newline at end of file diff --git a/382-linked-list-random-node/NOTES.md b/382-linked-list-random-node/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/382-linked-list-random-node/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/382-linked-list-random-node/README.md b/382-linked-list-random-node/README.md new file mode 100644 index 0000000..c9cf37e --- /dev/null +++ b/382-linked-list-random-node/README.md @@ -0,0 +1,45 @@ +

382. Linked List Random Node

Medium


Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.

+ +

Implement the Solution class:

+ +
    +
  • Solution(ListNode head) Initializes the object with the integer array nums.
  • +
  • int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be choosen.
  • +
+ +

 

+

Example 1:

+ +
Input
+["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
+[[[1, 2, 3]], [], [], [], [], []]
+Output
+[null, 1, 3, 2, 2, 3]
+
+Explanation
+Solution solution = new Solution([1, 2, 3]);
+solution.getRandom(); // return 1
+solution.getRandom(); // return 3
+solution.getRandom(); // return 2
+solution.getRandom(); // return 2
+solution.getRandom(); // return 3
+// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the linked list will be in the range [1, 104].
  • +
  • -104 <= Node.val <= 104
  • +
  • At most 104 calls will be made to getRandom.
  • +
+ +

 

+

Follow up:

+ +
    +
  • What if the linked list is extremely large and its length is unknown to you?
  • +
  • Could you solve this efficiently without using extra space?
  • +
+
\ No newline at end of file diff --git a/389-find-the-difference/389-find-the-difference.cpp b/389-find-the-difference/389-find-the-difference.cpp new file mode 100644 index 0000000..323cf4c --- /dev/null +++ b/389-find-the-difference/389-find-the-difference.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + char findTheDifference(string s, string t) { + char r=0,g=8; + for(char c:s) r ^=c; + for(char c:t) r ^=c; + return r; + } +}; \ No newline at end of file diff --git a/389-find-the-difference/NOTES.md b/389-find-the-difference/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/389-find-the-difference/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/39-combination-sum/39-combination-sum.cpp b/39-combination-sum/39-combination-sum.cpp new file mode 100644 index 0000000..5f366b7 --- /dev/null +++ b/39-combination-sum/39-combination-sum.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + + void solve(vector> & ans, vector& combi,vector& candidates, int target,int idx) + { + if(idx == candidates.size()) + { + if(target == 0) + ans.push_back(combi); + return ; + } + if(target >= candidates[idx]) + { + combi.push_back(candidates[idx]); + solve(ans,combi,candidates,target-candidates[idx],idx); + combi.pop_back(); + } + solve(ans,combi,candidates,target,idx+1); + return ; + + } + + vector> combinationSum(vector& candidates, int target) { + vector> ans; + vector combi; + solve(ans,combi,candidates,target,0); + return ans; + } +}; \ No newline at end of file diff --git a/39-combination-sum/NOTES.md b/39-combination-sum/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/39-combination-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/39-combination-sum/README.md b/39-combination-sum/README.md new file mode 100644 index 0000000..29193a3 --- /dev/null +++ b/39-combination-sum/README.md @@ -0,0 +1,39 @@ +

39. Combination Sum

Medium


Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

+ +

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

+ +

It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

+ +

 

+

Example 1:

+ +
Input: candidates = [2,3,6,7], target = 7
+Output: [[2,2,3],[7]]
+Explanation:
+2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
+7 is a candidate, and 7 = 7.
+These are the only two combinations.
+
+ +

Example 2:

+ +
Input: candidates = [2,3,5], target = 8
+Output: [[2,2,2,2],[2,3,3],[3,5]]
+
+ +

Example 3:

+ +
Input: candidates = [2], target = 1
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= candidates.length <= 30
  • +
  • 1 <= candidates[i] <= 200
  • +
  • All elements of candidates are distinct.
  • +
  • 1 <= target <= 500
  • +
+
\ No newline at end of file diff --git a/394-decode-string/NOTES.md b/394-decode-string/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/394-decode-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/394-decode-string/README.md b/394-decode-string/README.md new file mode 100644 index 0000000..da6322f --- /dev/null +++ b/394-decode-string/README.md @@ -0,0 +1,37 @@ +

394. Decode String

Medium


Given an encoded string, return its decoded string.

+ +

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

+ +

You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4].

+ +

The test cases are generated so that the length of the output will never exceed 105.

+ +

 

+

Example 1:

+ +
Input: s = "3[a]2[bc]"
+Output: "aaabcbc"
+
+ +

Example 2:

+ +
Input: s = "3[a2[c]]"
+Output: "accaccacc"
+
+ +

Example 3:

+ +
Input: s = "2[abc]3[cd]ef"
+Output: "abcabccdcdcdef"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 30
  • +
  • s consists of lowercase English letters, digits, and square brackets '[]'.
  • +
  • s is guaranteed to be a valid input.
  • +
  • All the integers in s are in the range [1, 300].
  • +
+
\ No newline at end of file diff --git a/397-integer-replacement/397-integer-replacement.cpp b/397-integer-replacement/397-integer-replacement.cpp new file mode 100644 index 0000000..847936f --- /dev/null +++ b/397-integer-replacement/397-integer-replacement.cpp @@ -0,0 +1,28 @@ +class Solution +{ + int res = 0; +public: + int integerReplacement(int n) + { + if (n == 1) + return res; + if (n == 3) + { + res += 2; + return res; + } + if (n == INT_MAX) + return 32; + + res ++; + if (n & 1) + if ((n + 1) % 4 == 0) + integerReplacement(n + 1); + else + integerReplacement(n - 1); + else + integerReplacement(n / 2); + + return res; + } +}; \ No newline at end of file diff --git a/397-integer-replacement/NOTES.md b/397-integer-replacement/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/397-integer-replacement/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/397-integer-replacement/README.md b/397-integer-replacement/README.md new file mode 100644 index 0000000..a3b6f96 --- /dev/null +++ b/397-integer-replacement/README.md @@ -0,0 +1,38 @@ +

397. Integer Replacement

Medium


Given a positive integer n, you can apply one of the following operations:

+ +
    +
  1. If n is even, replace n with n / 2.
  2. +
  3. If n is odd, replace n with either n + 1 or n - 1.
  4. +
+ +

Return the minimum number of operations needed for n to become 1.

+ +

 

+

Example 1:

+ +
Input: n = 8
+Output: 3
+Explanation: 8 -> 4 -> 2 -> 1
+
+ +

Example 2:

+ +
Input: n = 7
+Output: 4
+Explanation: 7 -> 8 -> 4 -> 2 -> 1
+or 7 -> 6 -> 3 -> 2 -> 1
+
+ +

Example 3:

+ +
Input: n = 4
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/3sum-closest/3sum-closest.cpp b/3sum-closest/3sum-closest.cpp new file mode 100644 index 0000000..79ba3ab --- /dev/null +++ b/3sum-closest/3sum-closest.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + + int threeSumClosest(vector& nums, int target) { + + sort(nums.begin(), nums.end()); + + int fix = 0 ; + int tmp = nums[0]+nums[1]+nums[2] ; + + while( fix < nums.size() - 2 ){ + + int left = fix + 1; + int right = nums.size() - 1 ; + + while ( left < right ){ + + int sum = nums[fix] + nums[left] + nums[right]; + if ( abs(sum-target) < abs(tmp-target) ) tmp = sum; + if ( sum > target ) right -= 1; + else if ( sum < target ) left += 1; + else return target; + + } + + fix += 1; + + } + return tmp; + } +}; \ No newline at end of file diff --git a/3sum-closest/README.md b/3sum-closest/README.md new file mode 100644 index 0000000..8508c79 --- /dev/null +++ b/3sum-closest/README.md @@ -0,0 +1,19 @@ +

16. 3Sum Closest

Medium


Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

+ +

 

+

Example 1:

+ +
Input: nums = [-1,2,1,-4], target = 1
+Output: 2
+Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= nums.length <= 10^3
  • +
  • -10^3 <= nums[i] <= 10^3
  • +
  • -10^4 <= target <= 10^4
  • +
+
\ No newline at end of file diff --git a/3sum/3sum.cpp b/3sum/3sum.cpp new file mode 100644 index 0000000..bbf3fe3 --- /dev/null +++ b/3sum/3sum.cpp @@ -0,0 +1,50 @@ +class Solution { +public: + vector> threeSum(vector& nums) { + + vector> ans; + if(nums.size() <=2)return ans; + + sort(nums.begin(),nums.end()); + + for(int i=0;i temp(3); + temp[0] = nums[i]; + temp[1]= nums[low]; + temp[2]= nums[high]; + ans.push_back(temp); + + + while(high>low && nums[low] == nums[low+1])low++; + while(high>low && nums[high] == nums[high-1])high--; + + low++; + high--; + } + else if(currsum>sum) + { + high--; + } + else + { + low++; + } + + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/3sum/README.md b/3sum/README.md new file mode 100644 index 0000000..daa2f94 --- /dev/null +++ b/3sum/README.md @@ -0,0 +1,23 @@ +

15. 3Sum

Medium


Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

+ +

Notice that the solution set must not contain duplicate triplets.

+ +

 

+

Example 1:

+
Input: nums = [-1,0,1,2,-1,-4]
+Output: [[-1,-1,2],[-1,0,1]]
+

Example 2:

+
Input: nums = []
+Output: []
+

Example 3:

+
Input: nums = [0]
+Output: []
+
+

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 3000
  • +
  • -105 <= nums[i] <= 105
  • +
+
\ No newline at end of file diff --git a/4-median-of-two-sorted-arrays/4-median-of-two-sorted-arrays.cpp b/4-median-of-two-sorted-arrays/4-median-of-two-sorted-arrays.cpp new file mode 100644 index 0000000..4395d47 --- /dev/null +++ b/4-median-of-two-sorted-arrays/4-median-of-two-sorted-arrays.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + + if(nums1.size()>nums2.size()) + { + return findMedianSortedArrays(nums2,nums1); + } + int n = nums1.size(); + int m = nums2.size(); + + int mid = (n+m+1)/2; + int low = 0; + int high = n; + + + + while(low<=high) + { + int cut1 = (low+high)/2; + int cut2 = (n+m+1)/2 - cut1; + + int l1 = cut1 == 0 ? INT_MIN : nums1[cut1-1]; + int l2 = cut2 == 0 ? INT_MIN : nums2[cut2-1]; + + int r1 = cut1 == n ? INT_MAX : nums1[cut1]; + int r2 = cut2 == m ? INT_MAX : nums2[cut2]; + + if(l1<=r2 && l2<=r1) + { + if((n + m) % 2 == 0) + return (max(l1,l2) + min(r1,r2) )/ 2.0; + else + return max(l1,l2); + } + else if(l1>r2) + { + high = cut1 - 1; + } + else + low = cut1 + 1; + + } + return 0.0; + + } +}; \ No newline at end of file diff --git a/4-median-of-two-sorted-arrays/NOTES.md b/4-median-of-two-sorted-arrays/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/4-median-of-two-sorted-arrays/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/4-median-of-two-sorted-arrays/README.md b/4-median-of-two-sorted-arrays/README.md new file mode 100644 index 0000000..c5835f0 --- /dev/null +++ b/4-median-of-two-sorted-arrays/README.md @@ -0,0 +1,31 @@ +

4. Median of Two Sorted Arrays

Hard


Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

+ +

The overall run time complexity should be O(log (m+n)).

+ +

 

+

Example 1:

+ +
Input: nums1 = [1,3], nums2 = [2]
+Output: 2.00000
+Explanation: merged array = [1,2,3] and median is 2.
+
+ +

Example 2:

+ +
Input: nums1 = [1,2], nums2 = [3,4]
+Output: 2.50000
+Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
+
+ +

 

+

Constraints:

+ +
    +
  • nums1.length == m
  • +
  • nums2.length == n
  • +
  • 0 <= m <= 1000
  • +
  • 0 <= n <= 1000
  • +
  • 1 <= m + n <= 2000
  • +
  • -106 <= nums1[i], nums2[i] <= 106
  • +
+
\ No newline at end of file diff --git a/40-combination-sum-ii/40-combination-sum-ii.cpp b/40-combination-sum-ii/40-combination-sum-ii.cpp new file mode 100644 index 0000000..57c66ef --- /dev/null +++ b/40-combination-sum-ii/40-combination-sum-ii.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + + void helper(vector& candidates, int target,vector> & ans,vector &temp,int i) + { + if(target == 0) + { + ans.push_back(temp); + return; + } + + for(int j = i;ji && candidates[j] == candidates[j-1])continue; + if(candidates[j]>target)break; + temp.push_back(candidates[j]); + helper(candidates,target-candidates[j],ans,temp,j+1); + temp.pop_back(); + } + } + + vector> combinationSum2(vector& candidates, int target) { + sort(candidates.begin(),candidates.end()); + vector> ans; + vector temp; + helper(candidates,target,ans,temp,0); + return ans; + + } +}; \ No newline at end of file diff --git a/40-combination-sum-ii/NOTES.md b/40-combination-sum-ii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/40-combination-sum-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/40-combination-sum-ii/README.md b/40-combination-sum-ii/README.md new file mode 100644 index 0000000..74334e9 --- /dev/null +++ b/40-combination-sum-ii/README.md @@ -0,0 +1,38 @@ +

40. Combination Sum II

Medium


Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

+ +

Each number in candidates may only be used once in the combination.

+ +

Note: The solution set must not contain duplicate combinations.

+ +

 

+

Example 1:

+ +
Input: candidates = [10,1,2,7,6,1,5], target = 8
+Output: 
+[
+[1,1,6],
+[1,2,5],
+[1,7],
+[2,6]
+]
+
+ +

Example 2:

+ +
Input: candidates = [2,5,2,1,2], target = 5
+Output: 
+[
+[1,2,2],
+[5]
+]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= candidates.length <= 100
  • +
  • 1 <= candidates[i] <= 50
  • +
  • 1 <= target <= 30
  • +
+
\ No newline at end of file diff --git a/402-remove-k-digits/402-remove-k-digits.cpp b/402-remove-k-digits/402-remove-k-digits.cpp new file mode 100644 index 0000000..9acfdbb --- /dev/null +++ b/402-remove-k-digits/402-remove-k-digits.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + string removeKdigits(string num, int k) { + string ans = ""; // treat ans as a stack in below for loop + + for (char c : num) { + while (ans.length() && ans.back() > c && k) { + ans.pop_back(); // make sure digits in ans are in ascending order + k--; // remove one char + } + + if (ans.length() || c != '0') { ans.push_back(c); } // can't have leading '0' + } + + while (ans.length() && k--) { ans.pop_back(); } // make sure remove k digits in total + + return ans.empty() ? "0" : ans; + } +}; \ No newline at end of file diff --git a/402-remove-k-digits/NOTES.md b/402-remove-k-digits/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/402-remove-k-digits/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/402-remove-k-digits/README.md b/402-remove-k-digits/README.md new file mode 100644 index 0000000..e341214 --- /dev/null +++ b/402-remove-k-digits/README.md @@ -0,0 +1,33 @@ +

402. Remove K Digits

Medium


Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.

+ +

 

+

Example 1:

+ +
Input: num = "1432219", k = 3
+Output: "1219"
+Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
+
+ +

Example 2:

+ +
Input: num = "10200", k = 1
+Output: "200"
+Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
+
+ +

Example 3:

+ +
Input: num = "10", k = 2
+Output: "0"
+Explanation: Remove all the digits from the number and it is left with nothing which is 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= num.length <= 105
  • +
  • num consists of only digits.
  • +
  • num does not have any leading zeros except for the zero itself.
  • +
+
\ No newline at end of file diff --git a/410-split-array-largest-sum/410-split-array-largest-sum.cpp b/410-split-array-largest-sum/410-split-array-largest-sum.cpp new file mode 100644 index 0000000..3aa6cda --- /dev/null +++ b/410-split-array-largest-sum/410-split-array-largest-sum.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + int minimumSubarraysRequired(vector& nums, int maxSumAllowed) { + int currentSum = 0; + int splitsRequired = 0; + + for (int element : nums) { + // Add element only if the sum doesn't exceed maxSumAllowed + if (currentSum + element <= maxSumAllowed) { + currentSum += element; + } else { + // If the element addition makes sum more than maxSumAllowed + // Increment the splits required and reset sum + currentSum = element; + splitsRequired++; + } + } + + // Return the number of subarrays, which is the number of splits + 1 + return splitsRequired + 1; + } + + int splitArray(vector& nums, int m) { + // Find the sum of all elements and the maximum element + int sum = 0; + int maxElement = INT_MIN; + for (int element : nums) { + sum += element; + maxElement = max(maxElement, element); + } + + // Define the left and right boundary of binary search + int left = maxElement; + int right = sum; + int minimumLargestSplitSum = 0; + while (left <= right) { + // Find the mid value + int maxSumAllowed = (left + right) / 2; + + // Find the minimum splits. If splitsRequired is less than + // or equal to m move towards left i.e., smaller values + if (minimumSubarraysRequired(nums, maxSumAllowed) <= m) { + right = maxSumAllowed - 1; + minimumLargestSplitSum = maxSumAllowed; + } else { + // Move towards right if splitsRequired is more than m + left = maxSumAllowed + 1; + } + } + + return minimumLargestSplitSum; + } +}; \ No newline at end of file diff --git a/410-split-array-largest-sum/NOTES.md b/410-split-array-largest-sum/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/410-split-array-largest-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/410-split-array-largest-sum/README.md b/410-split-array-largest-sum/README.md new file mode 100644 index 0000000..e7a820a --- /dev/null +++ b/410-split-array-largest-sum/README.md @@ -0,0 +1,36 @@ +

410. Split Array Largest Sum

Hard


Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.

+ +

Write an algorithm to minimize the largest sum among these m subarrays.

+ +

 

+

Example 1:

+ +
Input: nums = [7,2,5,10,8], m = 2
+Output: 18
+Explanation:
+There are four ways to split nums into two subarrays.
+The best way is to split it into [7,2,5] and [10,8],
+where the largest sum among the two subarrays is only 18.
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,4,5], m = 2
+Output: 9
+
+ +

Example 3:

+ +
Input: nums = [1,4,4], m = 3
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 0 <= nums[i] <= 106
  • +
  • 1 <= m <= min(50, nums.length)
  • +
+
\ No newline at end of file diff --git a/415-add-strings/NOTES.md b/415-add-strings/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/415-add-strings/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/415-add-strings/README.md b/415-add-strings/README.md new file mode 100644 index 0000000..19e7bff --- /dev/null +++ b/415-add-strings/README.md @@ -0,0 +1,32 @@ +

415. Add Strings

Easy


Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

+ +

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

+ +

 

+

Example 1:

+ +
Input: num1 = "11", num2 = "123"
+Output: "134"
+
+ +

Example 2:

+ +
Input: num1 = "456", num2 = "77"
+Output: "533"
+
+ +

Example 3:

+ +
Input: num1 = "0", num2 = "0"
+Output: "0"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= num1.length, num2.length <= 104
  • +
  • num1 and num2 consist of only digits.
  • +
  • num1 and num2 don't have any leading zeros except for the zero itself.
  • +
+
\ No newline at end of file diff --git a/416-partition-equal-subset-sum/416-partition-equal-subset-sum.cpp b/416-partition-equal-subset-sum/416-partition-equal-subset-sum.cpp new file mode 100644 index 0000000..ab23d9f --- /dev/null +++ b/416-partition-equal-subset-sum/416-partition-equal-subset-sum.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + + bool canMakeSubset(vector& nums,int target) + { + int n = nums.size(); + vector> dp(n,vector (target+1,0)); + + for(int i=0;i= nums[0]) dp[0][nums[0]] = 1; + + for(int i=1;i& nums) { + int sum = 0; + for(auto a:nums) sum += a; + if(sum % 2 == 1 )return false; + + sum /= 2; + + return canMakeSubset(nums,sum); + } +}; \ No newline at end of file diff --git a/416-partition-equal-subset-sum/NOTES.md b/416-partition-equal-subset-sum/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/416-partition-equal-subset-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/416-partition-equal-subset-sum/README.md b/416-partition-equal-subset-sum/README.md new file mode 100644 index 0000000..4da8a6d --- /dev/null +++ b/416-partition-equal-subset-sum/README.md @@ -0,0 +1,25 @@ +

416. Partition Equal Subset Sum

Medium


Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

+ +

 

+

Example 1:

+ +
Input: nums = [1,5,11,5]
+Output: true
+Explanation: The array can be partitioned as [1, 5, 5] and [11].
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,5]
+Output: false
+Explanation: The array cannot be partitioned into equal sum subsets.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 200
  • +
  • 1 <= nums[i] <= 100
  • +
+
\ No newline at end of file diff --git a/42-trapping-rain-water/42-trapping-rain-water.cpp b/42-trapping-rain-water/42-trapping-rain-water.cpp new file mode 100644 index 0000000..0a12e9b --- /dev/null +++ b/42-trapping-rain-water/42-trapping-rain-water.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int trap(vector& nums) { + + int ans = 0; + int n = nums.size(); + vector left(n); + vector right(n); + int lmaxi = 0; + int rmaxi = 0; + for(int i=0;i& nums, int lb, int le, int rb, int re, int val, int bit){ + if(lb==le || re==rb) return 0; + if(bit==-1) return val; + int mask = 1 << bit, j = lb, k = rb; + // quicksort-like partition according to current bit + for(int i=lb; i0? ret: helper(nums, lb, le, rb, re, val<<1, bit-1); + } +public: + int findMaximumXOR(vector& nums) { + return helper(nums, 0, nums.size(), 0, nums.size(), 0, 30); + } +}; \ No newline at end of file diff --git a/421-maximum-xor-of-two-numbers-in-an-array/NOTES.md b/421-maximum-xor-of-two-numbers-in-an-array/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/421-maximum-xor-of-two-numbers-in-an-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/438-find-all-anagrams-in-a-string/438-find-all-anagrams-in-a-string.cpp b/438-find-all-anagrams-in-a-string/438-find-all-anagrams-in-a-string.cpp new file mode 100644 index 0000000..d0cc24f --- /dev/null +++ b/438-find-all-anagrams-in-a-string/438-find-all-anagrams-in-a-string.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector findAnagrams(string s, string p) { + int s_len = s.length(); + int p_len = p.length(); + + if(s.size() < p.size()) return {}; + + vector freq_p(26,0); + vector window(26,0); + + //first window + for(int i=0;i ans; + if(freq_p == window) ans.push_back(0); + + for(int i=p_len;i438. Find All Anagrams in a String

Medium


Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

+ +

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

+ +

 

+

Example 1:

+ +
Input: s = "cbaebabacd", p = "abc"
+Output: [0,6]
+Explanation:
+The substring with start index = 0 is "cba", which is an anagram of "abc".
+The substring with start index = 6 is "bac", which is an anagram of "abc".
+
+ +

Example 2:

+ +
Input: s = "abab", p = "ab"
+Output: [0,1,2]
+Explanation:
+The substring with start index = 0 is "ab", which is an anagram of "ab".
+The substring with start index = 1 is "ba", which is an anagram of "ab".
+The substring with start index = 2 is "ab", which is an anagram of "ab".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length, p.length <= 3 * 104
  • +
  • s and p consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/442-find-all-duplicates-in-an-array/442-find-all-duplicates-in-an-array.cpp b/442-find-all-duplicates-in-an-array/442-find-all-duplicates-in-an-array.cpp new file mode 100644 index 0000000..1670e74 --- /dev/null +++ b/442-find-all-duplicates-in-an-array/442-find-all-duplicates-in-an-array.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector findDuplicates(vector& nums) { + vector ans; + + for(int i=0;i442. Find All Duplicates in an Array

Medium


Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [4,3,2,7,8,2,3,1]
+Output: [2,3]
+

Example 2:

+
Input: nums = [1,1,2]
+Output: [1]
+

Example 3:

+
Input: nums = [1]
+Output: []
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 105
  • +
  • 1 <= nums[i] <= n
  • +
  • Each element in nums appears once or twice.
  • +
+
\ No newline at end of file diff --git a/45-jump-game-ii/45-jump-game-ii.cpp b/45-jump-game-ii/45-jump-game-ii.cpp new file mode 100644 index 0000000..754547a --- /dev/null +++ b/45-jump-game-ii/45-jump-game-ii.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + long long int solve(vector& nums,int i,vector& dp) + { + if(i >= (nums.size()-1)) + { + return dp[i] = 0; + } + + if(dp[i] != -1)return dp[i]; + + long long int ans = INT_MAX; + for(int j=1;j<=nums[i];j++) + if(i+j& nums) { + + vector dp(nums.size(),-1); + long long int ans = solve(nums,0.,dp); + return ans; + } +}; \ No newline at end of file diff --git a/45-jump-game-ii/NOTES.md b/45-jump-game-ii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/45-jump-game-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/45-jump-game-ii/README.md b/45-jump-game-ii/README.md new file mode 100644 index 0000000..6bfdc0c --- /dev/null +++ b/45-jump-game-ii/README.md @@ -0,0 +1,30 @@ +

45. Jump Game II

Medium


Given an array of non-negative integers nums, you are initially positioned at the first index of the array.

+ +

Each element in the array represents your maximum jump length at that position.

+ +

Your goal is to reach the last index in the minimum number of jumps.

+ +

You can assume that you can always reach the last index.

+ +

 

+

Example 1:

+ +
Input: nums = [2,3,1,1,4]
+Output: 2
+Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
+
+ +

Example 2:

+ +
Input: nums = [2,3,0,1,4]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • 0 <= nums[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/454-4sum-ii/454-4sum-ii.cpp b/454-4sum-ii/454-4sum-ii.cpp new file mode 100644 index 0000000..b86a1eb --- /dev/null +++ b/454-4sum-ii/454-4sum-ii.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int fourSumCount(vector& nums1, vector& nums2, vector& nums3, vector& nums4) { + + unordered_map ump; + int count=0; + + for(auto &x : nums1){ + for(auto &y: nums2){ + ump[x+y]++; + } + } + + for(auto &x : nums3){ + for(auto &y: nums4){ + int sum = (x+y)*-1; + if(ump.find(sum) != ump.end()) count+=ump[sum]; + } + } + + return count; + } +}; \ No newline at end of file diff --git a/454-4sum-ii/NOTES.md b/454-4sum-ii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/454-4sum-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/454-4sum-ii/README.md b/454-4sum-ii/README.md new file mode 100644 index 0000000..2ad6c2c --- /dev/null +++ b/454-4sum-ii/README.md @@ -0,0 +1,36 @@ +

454. 4Sum II

Medium


Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that:

+ +
    +
  • 0 <= i, j, k, l < n
  • +
  • nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
  • +
+ +

 

+

Example 1:

+ +
Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
+Output: 2
+Explanation:
+The two tuples are:
+1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
+2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
+
+ +

Example 2:

+ +
Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums1.length
  • +
  • n == nums2.length
  • +
  • n == nums3.length
  • +
  • n == nums4.length
  • +
  • 1 <= n <= 200
  • +
  • -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
  • +
+
\ No newline at end of file diff --git a/458-poor-pigs/NOTES.md b/458-poor-pigs/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/458-poor-pigs/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/458-poor-pigs/README.md b/458-poor-pigs/README.md new file mode 100644 index 0000000..4f1782e --- /dev/null +++ b/458-poor-pigs/README.md @@ -0,0 +1,33 @@ +

458. Poor Pigs

Hard


There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.

+ +

You can feed the pigs according to these steps:

+ +
    +
  1. Choose some live pigs to feed.
  2. +
  3. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.
  4. +
  5. Wait for minutesToDie minutes. You may not feed any other pigs during this time.
  6. +
  7. After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
  8. +
  9. Repeat this process until you run out of time.
  10. +
+ +

Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.

+ +

 

+

Example 1:

+
Input: buckets = 1000, minutesToDie = 15, minutesToTest = 60
+Output: 5
+

Example 2:

+
Input: buckets = 4, minutesToDie = 15, minutesToTest = 15
+Output: 2
+

Example 3:

+
Input: buckets = 4, minutesToDie = 15, minutesToTest = 30
+Output: 2
+
+

 

+

Constraints:

+ +
    +
  • 1 <= buckets <= 1000
  • +
  • 1 <= minutesToDie <= minutesToTest <= 100
  • +
+
\ No newline at end of file diff --git a/46-permutations/46-permutations.cpp b/46-permutations/46-permutations.cpp new file mode 100644 index 0000000..0ecac8e --- /dev/null +++ b/46-permutations/46-permutations.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + + + void helper(vector> & ans,vector& nums,int index) + { + if(index == nums.size()) + { + ans.push_back(nums); + return ; + } + + for(int i=index;i> permute(vector& nums) { + vector> ans; + helper(ans,nums,0); + return ans; + } +}; \ No newline at end of file diff --git a/46-permutations/NOTES.md b/46-permutations/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/46-permutations/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/46-permutations/README.md b/46-permutations/README.md new file mode 100644 index 0000000..975206f --- /dev/null +++ b/46-permutations/README.md @@ -0,0 +1,22 @@ +

46. Permutations

Medium


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

+ +

 

+

Example 1:

+
Input: nums = [1,2,3]
+Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
+

Example 2:

+
Input: nums = [0,1]
+Output: [[0,1],[1,0]]
+

Example 3:

+
Input: nums = [1]
+Output: [[1]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 6
  • +
  • -10 <= nums[i] <= 10
  • +
  • All the integers of nums are unique.
  • +
+
\ No newline at end of file diff --git a/472-concatenated-words/472-concatenated-words.cpp b/472-concatenated-words/472-concatenated-words.cpp new file mode 100644 index 0000000..f495697 --- /dev/null +++ b/472-concatenated-words/472-concatenated-words.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + + bool canform(string s,unordered_map & mp) + { + for(int i=1;i findAllConcatenatedWordsInADict(vector& words) { + vector ans; + unordered_map mp; + + for(int i=0;i472. Concatenated Words

Hard


Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.

+ +

A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.

+ +

 

+

Example 1:

+ +
Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
+Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
+Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; 
+"dogcatsdog" can be concatenated by "dog", "cats" and "dog"; 
+"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".
+ +

Example 2:

+ +
Input: words = ["cat","dog","catdog"]
+Output: ["catdog"]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 104
  • +
  • 1 <= words[i].length <= 30
  • +
  • words[i] consists of only lowercase English letters.
  • +
  • All the strings of words are unique.
  • +
  • 1 <= sum(words[i].length) <= 105
  • +
+
\ No newline at end of file diff --git a/48-rotate-image/48-rotate-image.cpp b/48-rotate-image/48-rotate-image.cpp new file mode 100644 index 0000000..59a87f7 --- /dev/null +++ b/48-rotate-image/48-rotate-image.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + void rotate(vector>& matrix) { + + for(int i=0;i48. Rotate Image

Medium


You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

+ +

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

+ +

 

+

Example 1:

+ +
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
+Output: [[7,4,1],[8,5,2],[9,6,3]]
+
+ +

Example 2:

+ +
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
+Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
+
+ +

 

+

Constraints:

+ +
    +
  • n == matrix.length == matrix[i].length
  • +
  • 1 <= n <= 20
  • +
  • -1000 <= matrix[i][j] <= 1000
  • +
+
\ No newline at end of file diff --git a/485-max-consecutive-ones/485-max-consecutive-ones.cpp b/485-max-consecutive-ones/485-max-consecutive-ones.cpp new file mode 100644 index 0000000..90f735c --- /dev/null +++ b/485-max-consecutive-ones/485-max-consecutive-ones.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + int maxi = 0; + int curr_max = 0; + + for(int i=0;i485. Max Consecutive Ones

Easy


Given a binary array nums, return the maximum number of consecutive 1's in the array.

+ +

 

+

Example 1:

+ +
Input: nums = [1,1,0,1,1,1]
+Output: 3
+Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
+
+ +

Example 2:

+ +
Input: nums = [1,0,1,1,0,1]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • nums[i] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/49-group-anagrams/49-group-anagrams.cpp b/49-group-anagrams/49-group-anagrams.cpp new file mode 100644 index 0000000..c08308c --- /dev/null +++ b/49-group-anagrams/49-group-anagrams.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> m; + string tmp_sorted; + + for (auto word : strs) { + tmp_sorted = word; + sort(tmp_sorted.begin(), tmp_sorted.end()); + m[tmp_sorted].push_back(word); + } + + vector> res; + for (auto [word, list] : m) { + res.push_back(list); + } + + return res; + } +}; \ No newline at end of file diff --git a/49-group-anagrams/NOTES.md b/49-group-anagrams/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/49-group-anagrams/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/49-group-anagrams/README.md b/49-group-anagrams/README.md new file mode 100644 index 0000000..63e431b --- /dev/null +++ b/49-group-anagrams/README.md @@ -0,0 +1,24 @@ +

49. Group Anagrams

Medium


Given an array of strings strs, group the anagrams together. You can return the answer in any order.

+ +

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

+ +

 

+

Example 1:

+
Input: strs = ["eat","tea","tan","ate","nat","bat"]
+Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
+

Example 2:

+
Input: strs = [""]
+Output: [[""]]
+

Example 3:

+
Input: strs = ["a"]
+Output: [["a"]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= strs.length <= 104
  • +
  • 0 <= strs[i].length <= 100
  • +
  • strs[i] consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/494-target-sum/494-target-sum.cpp b/494-target-sum/494-target-sum.cpp new file mode 100644 index 0000000..300089f --- /dev/null +++ b/494-target-sum/494-target-sum.cpp @@ -0,0 +1,79 @@ +class Solution { +public: +// int solve(vector& nums,int target) +// { +// int n = nums.size(); +// vector> dp(n,vector (target+1,0)); + +// for(int i=0;i= nums[0]) dp[0][nums[0]] = 1; + + +// for(int i=1;i 1) +// // ans++; +// // return ans; +// return dp[n-1][target]; +// } + int findWays(vector &num, int tar){ + int n = num.size(); + + vector> dp(n,vector(tar+1,0)); + + if(num[0] == 0) dp[0][0] =2; // 2 cases -pick and not pick + else dp[0][0] = 1; // 1 case - not pick + + if(num[0]!=0 && num[0]<=tar) dp[0][num[0]] = 1; // 1 case -pick + + for(int ind = 1; ind& nums, int target) { + int sum = 0; + for(auto a:nums)sum += a; + + int tar = (sum - target) /2 ; + + if((sum - target) % 2 == 1 || sum - target < 0 )return 0; + sort(nums.begin(),nums.end()); + return findWays(nums,tar); + } +}; \ No newline at end of file diff --git a/494-target-sum/NOTES.md b/494-target-sum/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/494-target-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/494-target-sum/README.md b/494-target-sum/README.md new file mode 100644 index 0000000..db8dbd4 --- /dev/null +++ b/494-target-sum/README.md @@ -0,0 +1,39 @@ +

494. Target Sum

Medium


You are given an integer array nums and an integer target.

+ +

You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.

+ +
    +
  • For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".
  • +
+ +

Return the number of different expressions that you can build, which evaluates to target.

+ +

 

+

Example 1:

+ +
Input: nums = [1,1,1,1,1], target = 3
+Output: 5
+Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3.
+-1 + 1 + 1 + 1 + 1 = 3
++1 - 1 + 1 + 1 + 1 = 3
++1 + 1 - 1 + 1 + 1 = 3
++1 + 1 + 1 - 1 + 1 = 3
++1 + 1 + 1 + 1 - 1 = 3
+
+ +

Example 2:

+ +
Input: nums = [1], target = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 20
  • +
  • 0 <= nums[i] <= 1000
  • +
  • 0 <= sum(nums[i]) <= 1000
  • +
  • -1000 <= target <= 1000
  • +
+
\ No newline at end of file diff --git a/496-next-greater-element-i/496-next-greater-element-i.cpp b/496-next-greater-element-i/496-next-greater-element-i.cpp new file mode 100644 index 0000000..5de3181 --- /dev/null +++ b/496-next-greater-element-i/496-next-greater-element-i.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + vector nextGreaterElement(vector& findNums, vector& nums) { + + unordered_map m; + stack s; + + for(int i=nums.size()-1;i>=0 ;i--) + { + while(!s.empty() && s.top() <= nums[i]) + s.pop(); + if(!s.empty()) + m[nums[i]] = s.top(); + else + m[nums[i]] = -1; + + s.push(nums[i]); + } + vector ans; + for(int i=0;i s; + // unordered_map m; + // for (int n : nums) { + // while (s.size() && s.top() < n) { + // m[s.top()] = n; + // s.pop(); + // } + // s.push(n); + // } + // vector ans; + // for (int n : findNums) ans.push_back(m.count(n) ? m[n] : -1); \ No newline at end of file diff --git a/496-next-greater-element-i/NOTES.md b/496-next-greater-element-i/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/496-next-greater-element-i/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/496-next-greater-element-i/README.md b/496-next-greater-element-i/README.md new file mode 100644 index 0000000..a947674 --- /dev/null +++ b/496-next-greater-element-i/README.md @@ -0,0 +1,40 @@ +

496. Next Greater Element I

Easy


The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.

+ +

You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.

+ +

For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.

+ +

Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.

+ +

 

+

Example 1:

+ +
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
+Output: [-1,3,-1]
+Explanation: The next greater element for each value of nums1 is as follows:
+- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
+- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.
+- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
+
+ +

Example 2:

+ +
Input: nums1 = [2,4], nums2 = [1,2,3,4]
+Output: [3,-1]
+Explanation: The next greater element for each value of nums1 is as follows:
+- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.
+- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length <= nums2.length <= 1000
  • +
  • 0 <= nums1[i], nums2[i] <= 104
  • +
  • All integers in nums1 and nums2 are unique.
  • +
  • All the integers of nums1 also appear in nums2.
  • +
+ +

 

+Follow up: Could you find an O(nums1.length + nums2.length) solution?
\ No newline at end of file diff --git a/4sum-ii/4sum-ii.cpp b/4sum-ii/4sum-ii.cpp new file mode 100644 index 0000000..b86a1eb --- /dev/null +++ b/4sum-ii/4sum-ii.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int fourSumCount(vector& nums1, vector& nums2, vector& nums3, vector& nums4) { + + unordered_map ump; + int count=0; + + for(auto &x : nums1){ + for(auto &y: nums2){ + ump[x+y]++; + } + } + + for(auto &x : nums3){ + for(auto &y: nums4){ + int sum = (x+y)*-1; + if(ump.find(sum) != ump.end()) count+=ump[sum]; + } + } + + return count; + } +}; \ No newline at end of file diff --git a/4sum-ii/README.md b/4sum-ii/README.md new file mode 100644 index 0000000..dbc11c9 --- /dev/null +++ b/4sum-ii/README.md @@ -0,0 +1,36 @@ +

454. 4Sum II

Medium


Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that:

+ +
    +
  • 0 <= i, j, k, l < n
  • +
  • nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
  • +
+ +

 

+

Example 1:

+ +
Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
+Output: 2
+Explanation:
+The two tuples are:
+1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
+2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
+
+ +

Example 2:

+ +
Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums1.length
  • +
  • n == nums2.length
  • +
  • n == nums3.length
  • +
  • n == nums4.length
  • +
  • 1 <= n <= 200
  • +
  • -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
  • +
+
\ No newline at end of file diff --git a/4sum/4sum.cpp b/4sum/4sum.cpp new file mode 100644 index 0000000..355061e --- /dev/null +++ b/4sum/4sum.cpp @@ -0,0 +1,54 @@ +class Solution { +public: + vector> fourSum(vector& nums, int target) { + vector> ans; + if(nums.size() == 0) + return ans; + + sort(nums.begin(),nums.end()); + int n = nums.size(); + + for(int i=0;ilow) + { + int two_sum = nums[low]+nums[high]; + if(two_sum == rem) + { + vector temp(4,0); + temp[0] = nums[i]; + temp[1] = nums[j]; + temp[2] = nums[low]; + temp[3] = nums[high]; + ans.push_back(temp); + + while(high>low && nums[low] == nums[low+1]) + low++; + while(high>low && nums[high] == nums[high-1]) + high--; + + low++; + high--; + } + else if(two_sum < rem) + { + low++; + } + else + high--; + + } + while(j + 1 < n && nums[j + 1] == nums[j]) ++j; + } + while (i + 1 < n && nums[i + 1] == nums[i]) ++i; + } + return ans; + } +}; \ No newline at end of file diff --git a/4sum/README.md b/4sum/README.md new file mode 100644 index 0000000..71e69fa --- /dev/null +++ b/4sum/README.md @@ -0,0 +1,32 @@ +

18. 4Sum

Medium


Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

+ +
    +
  • 0 <= a, b, c, d < n
  • +
  • a, b, c, and d are distinct.
  • +
  • nums[a] + nums[b] + nums[c] + nums[d] == target
  • +
+ +

You may return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: nums = [1,0,-1,0,-2,2], target = 0
+Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
+
+ +

Example 2:

+ +
Input: nums = [2,2,2,2,2], target = 8
+Output: [[2,2,2,2]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 200
  • +
  • -109 <= nums[i] <= 109
  • +
  • -109 <= target <= 109
  • +
+
\ No newline at end of file diff --git a/50-powx-n/50-powx-n.cpp b/50-powx-n/50-powx-n.cpp new file mode 100644 index 0000000..6c31fe4 --- /dev/null +++ b/50-powx-n/50-powx-n.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + double myPow(double x, int n) { + if(n==0) + return 1; + if(n>0) + { + if(n%2 == 0) + { + double sub = pow(x,n/2); + return sub*sub; + } + else + return x*pow(x,n-1); + } + else + { + if(n%2 == 0) + { + double sub = pow(x,abs(n/2)); + return 1/(sub*sub); + } + else + return (x*pow(x,n-1)); + } + return 1; + } +}; \ No newline at end of file diff --git a/50-powx-n/NOTES.md b/50-powx-n/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/50-powx-n/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/50-powx-n/README.md b/50-powx-n/README.md new file mode 100644 index 0000000..9790866 --- /dev/null +++ b/50-powx-n/README.md @@ -0,0 +1,31 @@ +

50. Pow(x, n)

Medium


Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

+ +

 

+

Example 1:

+ +
Input: x = 2.00000, n = 10
+Output: 1024.00000
+
+ +

Example 2:

+ +
Input: x = 2.10000, n = 3
+Output: 9.26100
+
+ +

Example 3:

+ +
Input: x = 2.00000, n = -2
+Output: 0.25000
+Explanation: 2-2 = 1/22 = 1/4 = 0.25
+
+ +

 

+

Constraints:

+ +
    +
  • -100.0 < x < 100.0
  • +
  • -231 <= n <= 231-1
  • +
  • -104 <= xn <= 104
  • +
+
\ No newline at end of file diff --git a/503-next-greater-element-ii/503-next-greater-element-ii.cpp b/503-next-greater-element-ii/503-next-greater-element-ii.cpp new file mode 100644 index 0000000..3871eb0 --- /dev/null +++ b/503-next-greater-element-ii/503-next-greater-element-ii.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector nextGreaterElements(vector& nums) { + vector ans(nums.size()); + stack s; + for(int i=2*nums.size()-1; i>=0;i--) + { + while(!s.empty() && s.top()<=nums[i%nums.size()] ) + s.pop(); + + if(i503. Next Greater Element II

Medium


Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.

+ +

The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,1]
+Output: [2,-1,2]
+Explanation: The first 1's next greater number is 2; 
+The number 2 can't find next greater number. 
+The second 1's next greater number needs to search circularly, which is also 2.
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,4,3]
+Output: [2,3,4,-1,4]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -109 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/509-fibonacci-number/509-fibonacci-number.cpp b/509-fibonacci-number/509-fibonacci-number.cpp new file mode 100644 index 0000000..f325e14 --- /dev/null +++ b/509-fibonacci-number/509-fibonacci-number.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + int fib(int n) { + if(n == 0 || n==1)return n; + + return fib(n-1)+fib(n-2); + } +}; \ No newline at end of file diff --git a/509-fibonacci-number/NOTES.md b/509-fibonacci-number/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/509-fibonacci-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/509-fibonacci-number/README.md b/509-fibonacci-number/README.md new file mode 100644 index 0000000..5c4b5ad --- /dev/null +++ b/509-fibonacci-number/README.md @@ -0,0 +1,37 @@ +

509. Fibonacci Number

Easy


The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

+ +
F(0) = 0, F(1) = 1
+F(n) = F(n - 1) + F(n - 2), for n > 1.
+
+ +

Given n, calculate F(n).

+ +

 

+

Example 1:

+ +
Input: n = 2
+Output: 1
+Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
+
+ +

Example 2:

+ +
Input: n = 3
+Output: 2
+Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
+
+ +

Example 3:

+ +
Input: n = 4
+Output: 3
+Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 30
  • +
+
\ No newline at end of file diff --git a/51-n-queens/51-n-queens.cpp b/51-n-queens/51-n-queens.cpp new file mode 100644 index 0000000..3d58028 --- /dev/null +++ b/51-n-queens/51-n-queens.cpp @@ -0,0 +1,70 @@ +class Solution { +public: +// bool isSafe(int row,int col,vector & board,int n) +// { + +// for(int i=0;i=0 && tempc>=0) +// { +// if(board[tempr--][tempc--] == 'Q') +// return false; +// } + +// tempr = row; +// tempc = col; +// while(tempr < n && tempc < n && tempr>=0 && tempc>=0) +// { +// if(board[tempr++][tempc--] == 'Q') +// return false; +// } +// return true; +// } + + + void solve(int col,vector> & ans,vector & board,int n,vector& rowHash,vector&upper,vector & down) + { + if(col == n) + { + ans.push_back(board); + return ; + } + + for(int row = 0;row> solveNQueens(int n) { + vector> ans; + vector board(n); + string s(n,'.'); + for(int i=0;i rowHash(n); + vector upper(2*n - 1,0); + vector down(2*n - 1,0); + solve(0,ans,board,n,rowHash,upper,down); + return ans; + + } +}; \ No newline at end of file diff --git a/51-n-queens/NOTES.md b/51-n-queens/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/51-n-queens/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/51-n-queens/README.md b/51-n-queens/README.md new file mode 100644 index 0000000..e2bebec --- /dev/null +++ b/51-n-queens/README.md @@ -0,0 +1,27 @@ +

51. N-Queens

Hard


The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

+ +

Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.

+ +

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.

+ +

 

+

Example 1:

+ +
Input: n = 4
+Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
+Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
+
+ +

Example 2:

+ +
Input: n = 1
+Output: [["Q"]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 9
  • +
+
\ No newline at end of file diff --git a/52-n-queens-ii/52-n-queens-ii.cpp b/52-n-queens-ii/52-n-queens-ii.cpp new file mode 100644 index 0000000..142f8ed --- /dev/null +++ b/52-n-queens-ii/52-n-queens-ii.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + + int solve(int col,vector>& ans,vector &board,int n,vector &right, vector& upper,vector &down) + { + if(n == col) + { + ans.push_back(board); + return 1; + } + int k = 0; + for(int row = 0;row> ans; + vector board(n); + string s(n,'.'); + for(int i=0;i right(n,0); + vector upper(2*n-1,0); + vector down(2*n-1,0); + + int a = solve(0,ans,board,n,right,upper,down); + return a; + } +}; \ No newline at end of file diff --git a/52-n-queens-ii/NOTES.md b/52-n-queens-ii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/52-n-queens-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/52-n-queens-ii/README.md b/52-n-queens-ii/README.md new file mode 100644 index 0000000..6ab4a13 --- /dev/null +++ b/52-n-queens-ii/README.md @@ -0,0 +1,25 @@ +

52. N-Queens II

Hard


The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

+ +

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

+ +

 

+

Example 1:

+ +
Input: n = 4
+Output: 2
+Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
+
+ +

Example 2:

+ +
Input: n = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 9
  • +
+
\ No newline at end of file diff --git a/520-detect-capital/520-detect-capital.cpp b/520-detect-capital/520-detect-capital.cpp new file mode 100644 index 0000000..4f5e07c --- /dev/null +++ b/520-detect-capital/520-detect-capital.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + bool detectCapitalUse(string word) { + for(int i = 1; i < word.size(); i++){ + if(isupper(word[1]) != isupper(word[i]) || + islower(word[0]) && isupper(word[i])) return false; + } + return true; +} +}; \ No newline at end of file diff --git a/520-detect-capital/NOTES.md b/520-detect-capital/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/520-detect-capital/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/520-detect-capital/README.md b/520-detect-capital/README.md new file mode 100644 index 0000000..29b46a9 --- /dev/null +++ b/520-detect-capital/README.md @@ -0,0 +1,26 @@ +

520. Detect Capital

Easy


We define the usage of capitals in a word to be right when one of the following cases holds:

+ +
    +
  • All letters in this word are capitals, like "USA".
  • +
  • All letters in this word are not capitals, like "leetcode".
  • +
  • Only the first letter in this word is capital, like "Google".
  • +
+ +

Given a string word, return true if the usage of capitals in it is right.

+ +

 

+

Example 1:

+
Input: word = "USA"
+Output: true
+

Example 2:

+
Input: word = "FlaG"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= word.length <= 100
  • +
  • word consists of lowercase and uppercase English letters.
  • +
+
\ No newline at end of file diff --git a/525-contiguous-array/525-contiguous-array.cpp b/525-contiguous-array/525-contiguous-array.cpp new file mode 100644 index 0000000..93629b2 --- /dev/null +++ b/525-contiguous-array/525-contiguous-array.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int findMaxLength(vector& nums) { + int sum=0, maxLen=0; + unordered_map seen{{0, -1}}; + + for(int i=0; i525. Contiguous Array

Medium


Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.

+ +

 

+

Example 1:

+ +
Input: nums = [0,1]
+Output: 2
+Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.
+
+ +

Example 2:

+ +
Input: nums = [0,1,0]
+Output: 2
+Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • nums[i] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/53-maximum-subarray/53-maximum-subarray.cpp b/53-maximum-subarray/53-maximum-subarray.cpp new file mode 100644 index 0000000..4ce0f0e --- /dev/null +++ b/53-maximum-subarray/53-maximum-subarray.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int maxSubArray(vector& nums) { + + int sum = 0; + int maxi = INT_MIN; + + for(int i=0;i53. Maximum Subarray

Medium


Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

+ +

A subarray is a contiguous part of an array.

+ +

 

+

Example 1:

+ +
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
+Output: 6
+Explanation: [4,-1,2,1] has the largest sum = 6.
+
+ +

Example 2:

+ +
Input: nums = [1]
+Output: 1
+
+ +

Example 3:

+ +
Input: nums = [5,4,-1,7,8]
+Output: 23
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -104 <= nums[i] <= 104
  • +
+ +

 

+

Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

+
\ No newline at end of file diff --git a/532-k-diff-pairs-in-an-array/532-k-diff-pairs-in-an-array.cpp b/532-k-diff-pairs-in-an-array/532-k-diff-pairs-in-an-array.cpp new file mode 100644 index 0000000..7da4c87 --- /dev/null +++ b/532-k-diff-pairs-in-an-array/532-k-diff-pairs-in-an-array.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int findPairs(vector& nums, int k) { + map m; + for(auto a:nums) + m[a]++; + int ans = 0; + for(auto it = m.begin();it != m.end();it++) + { + if(k == 0) + { + if(it->second > 1) + ans ++; + } + else + { + if(m.find(it->first + k) != m.end()) + ans++; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/532-k-diff-pairs-in-an-array/NOTES.md b/532-k-diff-pairs-in-an-array/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/532-k-diff-pairs-in-an-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/532-k-diff-pairs-in-an-array/README.md b/532-k-diff-pairs-in-an-array/README.md new file mode 100644 index 0000000..a153108 --- /dev/null +++ b/532-k-diff-pairs-in-an-array/README.md @@ -0,0 +1,43 @@ +

532. K-diff Pairs in an Array

Medium


Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.

+ +

A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:

+ +
    +
  • 0 <= i < j < nums.length
  • +
  • |nums[i] - nums[j]| == k
  • +
+ +

Notice that |val| denotes the absolute value of val.

+ +

 

+

Example 1:

+ +
Input: nums = [3,1,4,1,5], k = 2
+Output: 2
+Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
+Although we have two 1s in the input, we should only return the number of unique pairs.
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,4,5], k = 1
+Output: 4
+Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
+
+ +

Example 3:

+ +
Input: nums = [1,3,1,5,4], k = 0
+Output: 1
+Explanation: There is one 0-diff pair in the array, (1, 1).
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -107 <= nums[i] <= 107
  • +
  • 0 <= k <= 107
  • +
+
\ No newline at end of file diff --git a/54-spiral-matrix/54-spiral-matrix.cpp b/54-spiral-matrix/54-spiral-matrix.cpp new file mode 100644 index 0000000..b48b0ab --- /dev/null +++ b/54-spiral-matrix/54-spiral-matrix.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector spiralOrder(vector>& matrix) { + int m = matrix.size(); + int n = matrix[0].size(); + int u = 0, d = m - 1, l = 0, r = n - 1, p = 0; + vector order(m * n); + while (u <= d && l <= r) { + for (int col = l; col <= r; col++) { + order[p++] = matrix[u][col]; + } + if (++u > d) { + break; + } + for (int row = u; row <= d; row++) { + order[p++] = matrix[row][r]; + } + if (--r < l) { + break; + } + for (int col = r; col >= l; col--) { + order[p++] = matrix[d][col]; + } + if (--d < u) { + break; + } + for (int row = d; row >= u; row--) { + order[p++] = matrix[row][l]; + } + if (l++ > r) { + break; + } + } + //order.push_back(1); + return order; + } +}; \ No newline at end of file diff --git a/54-spiral-matrix/NOTES.md b/54-spiral-matrix/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/54-spiral-matrix/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/54-spiral-matrix/README.md b/54-spiral-matrix/README.md new file mode 100644 index 0000000..0390c03 --- /dev/null +++ b/54-spiral-matrix/README.md @@ -0,0 +1,25 @@ +

54. Spiral Matrix

Medium


Given an m x n matrix, return all elements of the matrix in spiral order.

+ +

 

+

Example 1:

+ +
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
+Output: [1,2,3,6,9,8,7,4,5]
+
+ +

Example 2:

+ +
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
+Output: [1,2,3,4,8,12,11,10,9,5,6,7]
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 10
  • +
  • -100 <= matrix[i][j] <= 100
  • +
+
\ No newline at end of file diff --git a/540-single-element-in-a-sorted-array/540-single-element-in-a-sorted-array.cpp b/540-single-element-in-a-sorted-array/540-single-element-in-a-sorted-array.cpp new file mode 100644 index 0000000..346ca4c --- /dev/null +++ b/540-single-element-in-a-sorted-array/540-single-element-in-a-sorted-array.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int singleNonDuplicate(vector& nums) { + int low = 0, high = nums.size() - 2; + while(low <= high) { + int mid = (low + high) >> 1; + if(nums[mid] == nums[mid^1]) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + return nums[low]; + } +}; \ No newline at end of file diff --git a/540-single-element-in-a-sorted-array/NOTES.md b/540-single-element-in-a-sorted-array/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/540-single-element-in-a-sorted-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/540-single-element-in-a-sorted-array/README.md b/540-single-element-in-a-sorted-array/README.md new file mode 100644 index 0000000..a25a5f4 --- /dev/null +++ b/540-single-element-in-a-sorted-array/README.md @@ -0,0 +1,22 @@ +

540. Single Element in a Sorted Array

Medium


You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.

+ +

Return the single element that appears only once.

+ +

Your solution must run in O(log n) time and O(1) space.

+ +

 

+

Example 1:

+
Input: nums = [1,1,2,3,3,4,4,8,8]
+Output: 2
+

Example 2:

+
Input: nums = [3,3,7,7,10,11,11]
+Output: 10
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 0 <= nums[i] <= 105
  • +
+
\ No newline at end of file diff --git a/543-diameter-of-binary-tree/NOTES.md b/543-diameter-of-binary-tree/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/543-diameter-of-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/543-diameter-of-binary-tree/README.md b/543-diameter-of-binary-tree/README.md new file mode 100644 index 0000000..b16809e --- /dev/null +++ b/543-diameter-of-binary-tree/README.md @@ -0,0 +1,28 @@ +

543. Diameter of Binary Tree

Easy


Given the root of a binary tree, return the length of the diameter of the tree.

+ +

The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

+ +

The length of a path between two nodes is represented by the number of edges between them.

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3,4,5]
+Output: 3
+Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
+
+ +

Example 2:

+ +
Input: root = [1,2]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/55-jump-game/55-jump-game.cpp b/55-jump-game/55-jump-game.cpp new file mode 100644 index 0000000..148d404 --- /dev/null +++ b/55-jump-game/55-jump-game.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + +// bool solve(vector & nums,int i,vector& dp) +// { +// if(i==nums.size()-1) +// { +// return dp[i] = true; +// } +// if(dp[i]!= -1)return dp[i]; + +// for(int j=1;j<=nums[i];j++) +// { +// if(i+j& nums) { + + if(nums.size()<2)return true; + + vector dp(nums.size(),false); + dp[nums.size()-1] = true; + for(int i=nums.size()-2;i>=0;i--) + { + bool flag = false; + for(int j = 1;j<=nums[i];j++) + { + if(i+j >= nums.size() || dp[i+j] == true) + { + flag = true; + break; + } + } + dp[i] = flag; + } + return dp[0]; + } +}; \ No newline at end of file diff --git a/55-jump-game/NOTES.md b/55-jump-game/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/55-jump-game/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/55-jump-game/README.md b/55-jump-game/README.md new file mode 100644 index 0000000..2789ae3 --- /dev/null +++ b/55-jump-game/README.md @@ -0,0 +1,27 @@ +

55. Jump Game

Medium


You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

+ +

Return true if you can reach the last index, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: nums = [2,3,1,1,4]
+Output: true
+Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
+
+ +

Example 2:

+ +
Input: nums = [3,2,1,0,4]
+Output: false
+Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • 0 <= nums[i] <= 105
  • +
+
\ No newline at end of file diff --git a/556-next-greater-element-iii/556-next-greater-element-iii.cpp b/556-next-greater-element-iii/556-next-greater-element-iii.cpp new file mode 100644 index 0000000..a455642 --- /dev/null +++ b/556-next-greater-element-iii/556-next-greater-element-iii.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int nextGreaterElement(int n) { + auto digits = to_string(n); + next_permutation(begin(digits), end(digits)); + auto res = stoll(digits); + return (res > INT_MAX || res <= n) ? -1 : res; +} +}; \ No newline at end of file diff --git a/556-next-greater-element-iii/NOTES.md b/556-next-greater-element-iii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/556-next-greater-element-iii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/556-next-greater-element-iii/README.md b/556-next-greater-element-iii/README.md new file mode 100644 index 0000000..7d36bf4 --- /dev/null +++ b/556-next-greater-element-iii/README.md @@ -0,0 +1,19 @@ +

556. Next Greater Element III

Medium


Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1.

+ +

Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.

+ +

 

+

Example 1:

+
Input: n = 12
+Output: 21
+

Example 2:

+
Input: n = 21
+Output: -1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/560-subarray-sum-equals-k/560-subarray-sum-equals-k.cpp b/560-subarray-sum-equals-k/560-subarray-sum-equals-k.cpp new file mode 100644 index 0000000..7b32586 --- /dev/null +++ b/560-subarray-sum-equals-k/560-subarray-sum-equals-k.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int subarraySum(vector& nums, int k) { + int cum=0; // cumulated sum + map rec; // prefix sum recorder + int cnt = 0; // number of found subarray + rec[0]++; // to take into account those subarrays that begin with index 0 + for(int i=0;i567. Permutation in String

Medium


Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

+ +

In other words, return true if one of s1's permutations is the substring of s2.

+ +

 

+

Example 1:

+ +
Input: s1 = "ab", s2 = "eidbaooo"
+Output: true
+Explanation: s2 contains one permutation of s1 ("ba").
+
+ +

Example 2:

+ +
Input: s1 = "ab", s2 = "eidboaoo"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s1.length, s2.length <= 104
  • +
  • s1 and s2 consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/576-out-of-boundary-paths/576-out-of-boundary-paths.cpp b/576-out-of-boundary-paths/576-out-of-boundary-paths.cpp new file mode 100644 index 0000000..321a7e6 --- /dev/null +++ b/576-out-of-boundary-paths/576-out-of-boundary-paths.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int mod = 1e9+7; + int solve(int n,int m,int move,int i,int j, vector>>& dp) + { + + + if(i<0 || j<0 || i>=n || j>=m)return 1; + + if(move == 0)return 0; + + if(dp[i][j][move] != -1)return dp[i][j][move]; + + int up = solve(n,m,move-1,i-1,j,dp) % mod; + + int down = solve(n,m,move-1,i+1,j,dp) % mod; + + int left = solve(n,m,move-1,i,j-1,dp) % mod; + + int right = solve(n,m,move-1,i,j+1,dp) % mod; + + return dp[i][j][move] = ((up+down) % mod+(right+left) % mod) % mod; + } + + int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { + vector>> dp(m,vector> (n,vector (maxMove+1,-1))); + return solve(m,n,maxMove,startRow,startColumn,dp) % mod; + } +}; \ No newline at end of file diff --git a/576-out-of-boundary-paths/README.md b/576-out-of-boundary-paths/README.md new file mode 100644 index 0000000..1174d49 --- /dev/null +++ b/576-out-of-boundary-paths/README.md @@ -0,0 +1,27 @@ +

576. Out of Boundary Paths

Medium


There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.

+ +

Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
+Output: 6
+
+ +

Example 2:

+ +
Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
+Output: 12
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= m, n <= 50
  • +
  • 0 <= maxMove <= 50
  • +
  • 0 <= startRow < m
  • +
  • 0 <= startColumn < n
  • +
+
\ No newline at end of file diff --git a/60-permutation-sequence/60-permutation-sequence.cpp b/60-permutation-sequence/60-permutation-sequence.cpp new file mode 100644 index 0000000..8942aba --- /dev/null +++ b/60-permutation-sequence/60-permutation-sequence.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + string getPermutation(int n, int k) { + string s; + for(int i=1;i<=n;i++) + s += to_string(i); + int i=1; + do { + i++; + } while (next_permutation(s.begin(),s.end()) && i !=k); + + return s; + + + + } +}; \ No newline at end of file diff --git a/60-permutation-sequence/NOTES.md b/60-permutation-sequence/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/60-permutation-sequence/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/60-permutation-sequence/README.md b/60-permutation-sequence/README.md new file mode 100644 index 0000000..e8a233f --- /dev/null +++ b/60-permutation-sequence/README.md @@ -0,0 +1,34 @@ +

60. Permutation Sequence

Hard


The set [1, 2, 3, ..., n] contains a total of n! unique permutations.

+ +

By listing and labeling all of the permutations in order, we get the following sequence for n = 3:

+ +
    +
  1. "123"
  2. +
  3. "132"
  4. +
  5. "213"
  6. +
  7. "231"
  8. +
  9. "312"
  10. +
  11. "321"
  12. +
+ +

Given n and k, return the kth permutation sequence.

+ +

 

+

Example 1:

+
Input: n = 3, k = 3
+Output: "213"
+

Example 2:

+
Input: n = 4, k = 9
+Output: "2314"
+

Example 3:

+
Input: n = 3, k = 1
+Output: "123"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 9
  • +
  • 1 <= k <= n!
  • +
+
\ No newline at end of file diff --git a/605-can-place-flowers/605-can-place-flowers.cpp b/605-can-place-flowers/605-can-place-flowers.cpp new file mode 100644 index 0000000..e5ec623 --- /dev/null +++ b/605-can-place-flowers/605-can-place-flowers.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + bool canPlaceFlowers(vector& flowerbed, int n) { + if (n == 0) return true; + for (int i = 0; i < flowerbed.size(); i ++) { + if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) { // can place? + -- n; + if (n == 0) return true; + flowerbed[i] = 1; // place! + } + } + return false; + } +}; \ No newline at end of file diff --git a/605-can-place-flowers/NOTES.md b/605-can-place-flowers/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/605-can-place-flowers/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/605-can-place-flowers/README.md b/605-can-place-flowers/README.md new file mode 100644 index 0000000..b98f56a --- /dev/null +++ b/605-can-place-flowers/README.md @@ -0,0 +1,22 @@ +

605. Can Place Flowers

Easy


You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.

+ +

Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.

+ +

 

+

Example 1:

+
Input: flowerbed = [1,0,0,0,1], n = 1
+Output: true
+

Example 2:

+
Input: flowerbed = [1,0,0,0,1], n = 2
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= flowerbed.length <= 2 * 104
  • +
  • flowerbed[i] is 0 or 1.
  • +
  • There are no two adjacent flowers in flowerbed.
  • +
  • 0 <= n <= flowerbed.length
  • +
+
\ No newline at end of file diff --git a/61-rotate-list/NOTES.md b/61-rotate-list/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/61-rotate-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/61-rotate-list/README.md b/61-rotate-list/README.md new file mode 100644 index 0000000..4f45cb2 --- /dev/null +++ b/61-rotate-list/README.md @@ -0,0 +1,24 @@ +

61. Rotate List

Medium


Given the head of a linked list, rotate the list to the right by k places.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5], k = 2
+Output: [4,5,1,2,3]
+
+ +

Example 2:

+ +
Input: head = [0,1,2], k = 4
+Output: [2,0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 500].
  • +
  • -100 <= Node.val <= 100
  • +
  • 0 <= k <= 2 * 109
  • +
+
\ No newline at end of file diff --git a/62-unique-paths/NOTES.md b/62-unique-paths/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/62-unique-paths/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/62-unique-paths/README.md b/62-unique-paths/README.md new file mode 100644 index 0000000..f5816d6 --- /dev/null +++ b/62-unique-paths/README.md @@ -0,0 +1,30 @@ +

62. Unique Paths

Medium


There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.

+ +

Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.

+ +

The test cases are generated so that the answer will be less than or equal to 2 * 109.

+ +

 

+

Example 1:

+ +
Input: m = 3, n = 7
+Output: 28
+
+ +

Example 2:

+ +
Input: m = 3, n = 2
+Output: 3
+Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
+1. Right -> Down -> Down
+2. Down -> Down -> Right
+3. Down -> Right -> Down
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= m, n <= 100
  • +
+
\ No newline at end of file diff --git a/63-unique-paths-ii/NOTES.md b/63-unique-paths-ii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/63-unique-paths-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/63-unique-paths-ii/README.md b/63-unique-paths-ii/README.md new file mode 100644 index 0000000..7fce5c7 --- /dev/null +++ b/63-unique-paths-ii/README.md @@ -0,0 +1,35 @@ +

63. Unique Paths II

Medium


A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

+ +

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

+ +

Now consider if some obstacles are added to the grids. How many unique paths would there be?

+ +

An obstacle and space is marked as 1 and 0 respectively in the grid.

+ +

 

+

Example 1:

+ +
Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
+Output: 2
+Explanation: There is one obstacle in the middle of the 3x3 grid above.
+There are two ways to reach the bottom-right corner:
+1. Right -> Right -> Down -> Down
+2. Down -> Down -> Right -> Right
+
+ +

Example 2:

+ +
Input: obstacleGrid = [[0,1],[0,0]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • m == obstacleGrid.length
  • +
  • n == obstacleGrid[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • obstacleGrid[i][j] is 0 or 1.
  • +
+
\ No newline at end of file diff --git a/64-minimum-path-sum/64-minimum-path-sum.cpp b/64-minimum-path-sum/64-minimum-path-sum.cpp new file mode 100644 index 0000000..7c79716 --- /dev/null +++ b/64-minimum-path-sum/64-minimum-path-sum.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int minPathSum(vector>& grid) { + int n = grid.size(); + int m = grid[0].size(); + vector> dp(n,vector (m,0)); + + for(int i=0;i64. Minimum Path Sum

Medium


Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.

+ +

Note: You can only move either down or right at any point in time.

+ +

 

+

Example 1:

+ +
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
+Output: 7
+Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
+
+ +

Example 2:

+ +
Input: grid = [[1,2,3],[4,5,6]]
+Output: 12
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • 0 <= grid[i][j] <= 100
  • +
+
\ No newline at end of file diff --git a/650-2-keys-keyboard/650-2-keys-keyboard.cpp b/650-2-keys-keyboard/650-2-keys-keyboard.cpp new file mode 100644 index 0000000..72aa60b --- /dev/null +++ b/650-2-keys-keyboard/650-2-keys-keyboard.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + + int f(int curr,int total ,int paste_len,vector>& dp) + { + if(curr>total)return 1e9; + + if(curr == total)return 0; + + if(dp[curr][paste_len] != -1)return dp[curr][paste_len]; + + int copy = 2 + f(curr*2,total,curr,dp); + + int paste = 1 + f(curr + paste_len , total , paste_len,dp); + + return dp[curr][paste_len] = min(copy,paste); + } + + int minSteps(int n) { + if(n==1)return 0; + vector> dp(n,vector (n,-1)); + return 1 + f(1,n,1,dp); + } +}; \ No newline at end of file diff --git a/650-2-keys-keyboard/NOTES.md b/650-2-keys-keyboard/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/650-2-keys-keyboard/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/650-2-keys-keyboard/README.md b/650-2-keys-keyboard/README.md new file mode 100644 index 0000000..3918e4f --- /dev/null +++ b/650-2-keys-keyboard/README.md @@ -0,0 +1,33 @@ +

650. 2 Keys Keyboard

Medium


There is only one character 'A' on the screen of a notepad. You can perform two operations on this notepad for each step:

+ +
    +
  • Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).
  • +
  • Paste: You can paste the characters which are copied last time.
  • +
+ +

Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.

+ +

 

+

Example 1:

+ +
Input: n = 3
+Output: 3
+Explanation: Intitally, we have one character 'A'.
+In step 1, we use Copy All operation.
+In step 2, we use Paste operation to get 'AA'.
+In step 3, we use Paste operation to get 'AAA'.
+
+ +

Example 2:

+ +
Input: n = 1
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 1000
  • +
+
\ No newline at end of file diff --git a/66-plus-one/NOTES.md b/66-plus-one/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/66-plus-one/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/662-maximum-width-of-binary-tree/662-maximum-width-of-binary-tree.cpp b/662-maximum-width-of-binary-tree/662-maximum-width-of-binary-tree.cpp new file mode 100644 index 0000000..3d1a992 --- /dev/null +++ b/662-maximum-width-of-binary-tree/662-maximum-width-of-binary-tree.cpp @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int widthOfBinaryTree(TreeNode* root) { + if(root == NULL)return 0; + int ans = 0; + queue> pd; + pd.push({root,0}); + + while(!pd.empty()) + { + int size = pd.size(); + int low,high; + int min = pd.front().second; + for(int i=0;i k = pd.front(); + TreeNode * front = k.first; + pd.pop(); + long long int num = k.second - min; + if(i==0)low = num; + if(i == size-1) high = num; + if(front->left)pd.push({front->left,2*num*1LL + 1}); + if(front->right)pd.push({front->right,2*num*1LL+2}); + } + ans = max(ans,(int)high-low+1); + } + return ans; + } +}; \ No newline at end of file diff --git a/662-maximum-width-of-binary-tree/NOTES.md b/662-maximum-width-of-binary-tree/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/662-maximum-width-of-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/662-maximum-width-of-binary-tree/README.md b/662-maximum-width-of-binary-tree/README.md new file mode 100644 index 0000000..6b09e1d --- /dev/null +++ b/662-maximum-width-of-binary-tree/README.md @@ -0,0 +1,38 @@ +

662. Maximum Width of Binary Tree

Medium


Given the root of a binary tree, return the maximum width of the given tree.

+ +

The maximum width of a tree is the maximum width among all levels.

+ +

The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes are also counted into the length calculation.

+ +

It is guaranteed that the answer will in the range of 32-bit signed integer.

+ +

 

+

Example 1:

+ +
Input: root = [1,3,2,5,3,null,9]
+Output: 4
+Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).
+
+ +

Example 2:

+ +
Input: root = [1,3,null,5,3]
+Output: 2
+Explanation: The maximum width existing in the third level with the length 2 (5,3).
+
+ +

Example 3:

+ +
Input: root = [1,3,2,5]
+Output: 2
+Explanation: The maximum width existing in the second level with the length 2 (3,2).
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 3000].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/67-add-binary/NOTES.md b/67-add-binary/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/67-add-binary/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/67-add-binary/README.md b/67-add-binary/README.md new file mode 100644 index 0000000..fc85c32 --- /dev/null +++ b/67-add-binary/README.md @@ -0,0 +1,19 @@ +

67. Add Binary

Easy


Given two binary strings a and b, return their sum as a binary string.

+ +

 

+

Example 1:

+
Input: a = "11", b = "1"
+Output: "100"
+

Example 2:

+
Input: a = "1010", b = "1011"
+Output: "10101"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= a.length, b.length <= 104
  • +
  • a and b consist only of '0' or '1' characters.
  • +
  • Each string does not contain leading zeros except for the zero itself.
  • +
+
\ No newline at end of file diff --git a/673-number-of-longest-increasing-subsequence/NOTES.md b/673-number-of-longest-increasing-subsequence/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/673-number-of-longest-increasing-subsequence/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/673-number-of-longest-increasing-subsequence/README.md b/673-number-of-longest-increasing-subsequence/README.md new file mode 100644 index 0000000..439471d --- /dev/null +++ b/673-number-of-longest-increasing-subsequence/README.md @@ -0,0 +1,28 @@ +

673. Number of Longest Increasing Subsequence

Medium


Given an integer array nums, return the number of longest increasing subsequences.

+ +

Notice that the sequence has to be strictly increasing.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,5,4,7]
+Output: 2
+Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
+
+ +

Example 2:

+ +
Input: nums = [2,2,2,2,2]
+Output: 5
+Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.
+
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2000
  • +
  • -106 <= nums[i] <= 106
  • +
+
\ No newline at end of file diff --git a/7 Segment Display - GFG/7-segment-display.cpp b/7 Segment Display - GFG/7-segment-display.cpp new file mode 100644 index 0000000..786560c --- /dev/null +++ b/7 Segment Display - GFG/7-segment-display.cpp @@ -0,0 +1,71 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends + +class Solution { + public: + string sevenSegments(string S, int N) { + string str=""; + unordered_map umap; + S=S.substr(0,N); + umap['0']=6; + umap['1']=2; + umap['2']=5; + umap['3']=5; + umap['4']=4; + umap['5']=5; + umap['6']=6; + umap['7']=3; + umap['8']=7; + umap['9']=5; + int count=0,k; + for(auto c:S) + count+=umap[c]; + int n=S.length(); + char c; + while(n>0) + { + c='0'; + while(c<='8') + { + if(n==1) + { + if(umap[c]==count) + {str+=c;n--;count=0;break;} + } + else + { + k=count-umap[c]; + if(k/(n-1)>1) + { + str+=c; + n--; + count-=umap[c]; + break; + } + } + c++; + } + } + return str; + } +}; + +// { Driver Code Starts. +int main() { + int t; + cin >> t; + while (t--) { + int N; + + cin>>N; + string S; + cin>>S; + + Solution ob; + cout << ob.sevenSegments(S,N) << endl; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/7 Segment Display - GFG/README.md b/7 Segment Display - GFG/README.md new file mode 100644 index 0000000..510742f --- /dev/null +++ b/7 Segment Display - GFG/README.md @@ -0,0 +1,51 @@ +# 7 Segment Display +## Medium +
+

Using seven segment display, you can write down any digit from 0 to 9 using at most seven segments. Given a positive number N and then a string S representing a number of N digits. You have to rearrange the segments in this N digit number to get the smallest possible N digit number. This number can have leading zeros. You can not waste any segment or add any segment from your own. You have to use all of the segments of the given N digits.

+ +

Note: You can refer this diagram for more details

+ +

+ +

Example 1:

+ +
Input:
+N = 6
+S = "234567"
+Output:
+000011
+Explanation:
+234567 has a total of 28 segments and
+we can rearrange them to form 000011
+which has 28 segments too. 000011 is the
+smallest possible number which can be
+formed on rearrangement.
+ +

Example 2:

+ +
Input:
+N = 3
+S = "011"
+Output:
+011
+Explanation:
+011 has a total of 10 segments and this
+is the smallest number with 10 segments.
+
+ +

 

+ +

Your Task:
+You don't need to read input or print anything. Your task is to complete the function sevenSegments() which takes an Integer N and a String S of length N as input and returns the smallest possible N digit number which can be made using all of the segments given.

+ +

 

+ +

Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(1)

+ +

 

+ +

Constraints:
+1 <= N <= 104

+

+
\ No newline at end of file diff --git a/70-climbing-stairs/NOTES.md b/70-climbing-stairs/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/70-climbing-stairs/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/700-search-in-a-binary-search-tree/700-search-in-a-binary-search-tree.cpp b/700-search-in-a-binary-search-tree/700-search-in-a-binary-search-tree.cpp new file mode 100644 index 0000000..daf492b --- /dev/null +++ b/700-search-in-a-binary-search-tree/700-search-in-a-binary-search-tree.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + TreeNode* searchBST(TreeNode* root, int val) { + + if(root == NULL || (root->val == val)) + return root; + + if(root->val > val) + return searchBST(root->left,val); + + return searchBST(root->right,val); + + } +}; + + + diff --git a/700-search-in-a-binary-search-tree/NOTES.md b/700-search-in-a-binary-search-tree/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/700-search-in-a-binary-search-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/700-search-in-a-binary-search-tree/README.md b/700-search-in-a-binary-search-tree/README.md new file mode 100644 index 0000000..08be87e --- /dev/null +++ b/700-search-in-a-binary-search-tree/README.md @@ -0,0 +1,27 @@ +

700. Search in a Binary Search Tree

Easy


You are given the root of a binary search tree (BST) and an integer val.

+ +

Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.

+ +

 

+

Example 1:

+ +
Input: root = [4,2,7,1,3], val = 2
+Output: [2,1,3]
+
+ +

Example 2:

+ +
Input: root = [4,2,7,1,3], val = 5
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 5000].
  • +
  • 1 <= Node.val <= 107
  • +
  • root is a binary search tree.
  • +
  • 1 <= val <= 107
  • +
+
\ No newline at end of file diff --git a/701-insert-into-a-binary-search-tree/701-insert-into-a-binary-search-tree.cpp b/701-insert-into-a-binary-search-tree/701-insert-into-a-binary-search-tree.cpp new file mode 100644 index 0000000..49e8df4 --- /dev/null +++ b/701-insert-into-a-binary-search-tree/701-insert-into-a-binary-search-tree.cpp @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* insertIntoBST(TreeNode* root, int val) { + if(root == NULL) + { + TreeNode* newNode = new TreeNode(val); + return newNode; + + } + if(root->val > val) + { + root->left = insertIntoBST(root->left,val); + return root; + } + if(root->val < val) + { + root->right = insertIntoBST(root->right,val); + return root; + } + return root; + } +}; \ No newline at end of file diff --git a/701-insert-into-a-binary-search-tree/NOTES.md b/701-insert-into-a-binary-search-tree/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/701-insert-into-a-binary-search-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/701-insert-into-a-binary-search-tree/README.md b/701-insert-into-a-binary-search-tree/README.md new file mode 100644 index 0000000..a5872f9 --- /dev/null +++ b/701-insert-into-a-binary-search-tree/README.md @@ -0,0 +1,36 @@ +

701. Insert into a Binary Search Tree

Medium


You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

+ +

Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

+ +

 

+

Example 1:

+ +
Input: root = [4,2,7,1,3], val = 5
+Output: [4,2,7,1,3,5]
+Explanation: Another accepted tree is:
+
+
+ +

Example 2:

+ +
Input: root = [40,20,60,10,30,50,70], val = 25
+Output: [40,20,60,10,30,50,70,null,null,25]
+
+ +

Example 3:

+ +
Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
+Output: [4,2,7,1,3,5]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree will be in the range [0, 104].
  • +
  • -108 <= Node.val <= 108
  • +
  • All the values Node.val are unique.
  • +
  • -108 <= val <= 108
  • +
  • It's guaranteed that val does not exist in the original BST.
  • +
+
\ No newline at end of file diff --git a/704-binary-search/704-binary-search.cpp b/704-binary-search/704-binary-search.cpp new file mode 100644 index 0000000..a84c443 --- /dev/null +++ b/704-binary-search/704-binary-search.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + + + int binary_search(int start,int end,int target,vector& nums) + { + if(start<=end) + { + int mid = start + (end-start)/2; + + if(nums[mid] == target)return mid; + + if(nums[mid]>target) + { + return binary_search(start,mid-1,target,nums); + } + else + { + return binary_search(mid+1,end,target,nums); + } + } + return -1; + } + + int search(vector& nums, int target) { + return binary_search(0,nums.size()-1,target,nums); + } +}; \ No newline at end of file diff --git a/704-binary-search/NOTES.md b/704-binary-search/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/704-binary-search/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/704-binary-search/README.md b/704-binary-search/README.md new file mode 100644 index 0000000..4ecd7d9 --- /dev/null +++ b/704-binary-search/README.md @@ -0,0 +1,29 @@ +

704. Binary Search

Easy


Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

+ +

You must write an algorithm with O(log n) runtime complexity.

+ +

 

+

Example 1:

+ +
Input: nums = [-1,0,3,5,9,12], target = 9
+Output: 4
+Explanation: 9 exists in nums and its index is 4
+
+ +

Example 2:

+ +
Input: nums = [-1,0,3,5,9,12], target = 2
+Output: -1
+Explanation: 2 does not exist in nums so return -1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -104 < nums[i], target < 104
  • +
  • All the integers in nums are unique.
  • +
  • nums is sorted in ascending order.
  • +
+
\ No newline at end of file diff --git a/71-simplify-path/71-simplify-path.cpp b/71-simplify-path/71-simplify-path.cpp new file mode 100644 index 0000000..4c357b5 --- /dev/null +++ b/71-simplify-path/71-simplify-path.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + string simplifyPath(string path) { + + stack st; + string res; + + for(int i = 0; i71. Simplify Path

Medium


Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.

+ +

In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.

+ +

The canonical path should have the following format:

+ +
    +
  • The path starts with a single slash '/'.
  • +
  • Any two directories are separated by a single slash '/'.
  • +
  • The path does not end with a trailing '/'.
  • +
  • The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')
  • +
+ +

Return the simplified canonical path.

+ +

 

+

Example 1:

+ +
Input: path = "/home/"
+Output: "/home"
+Explanation: Note that there is no trailing slash after the last directory name.
+
+ +

Example 2:

+ +
Input: path = "/../"
+Output: "/"
+Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
+
+ +

Example 3:

+ +
Input: path = "/home//foo/"
+Output: "/home/foo"
+Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= path.length <= 3000
  • +
  • path consists of English letters, digits, period '.', slash '/' or '_'.
  • +
  • path is a valid absolute Unix path.
  • +
+
\ No newline at end of file diff --git a/724-find-pivot-index/724-find-pivot-index.cpp b/724-find-pivot-index/724-find-pivot-index.cpp new file mode 100644 index 0000000..8c20b83 --- /dev/null +++ b/724-find-pivot-index/724-find-pivot-index.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int pivotIndex(vector& nums) { + int sum = 0; + for(int i=0;i724. Find Pivot Index

Easy


Given an array of integers nums, calculate the pivot index of this array.

+ +

The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.

+ +

If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

+ +

Return the leftmost pivot index. If no such index exists, return -1.

+ +

 

+

Example 1:

+ +
Input: nums = [1,7,3,6,5,6]
+Output: 3
+Explanation:
+The pivot index is 3.
+Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
+Right sum = nums[4] + nums[5] = 5 + 6 = 11
+
+ +

Example 2:

+ +
Input: nums = [1,2,3]
+Output: -1
+Explanation:
+There is no index that satisfies the conditions in the problem statement.
+ +

Example 3:

+ +
Input: nums = [2,1,-1]
+Output: 0
+Explanation:
+The pivot index is 0.
+Left sum = 0 (no elements to the left of index 0)
+Right sum = nums[1] + nums[2] = 1 + -1 = 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -1000 <= nums[i] <= 1000
  • +
+ +

 

+

Note: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/

+
\ No newline at end of file diff --git a/74-search-a-2d-matrix/74-search-a-2d-matrix.cpp b/74-search-a-2d-matrix/74-search-a-2d-matrix.cpp new file mode 100644 index 0000000..e853dd7 --- /dev/null +++ b/74-search-a-2d-matrix/74-search-a-2d-matrix.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + + int n = matrix.size(); + int m = matrix[0].size(); + int i = 0; + int j = (m*n) - 1; + + while(i<=j) + { + int mid = i + (j-i)/2; + + int num = matrix[mid / m][mid % m]; + if(num == target) + return true; + else if(num > target) + j = mid - 1; + else + i = mid + 1; + } + return false; + } +}; \ No newline at end of file diff --git a/74-search-a-2d-matrix/NOTES.md b/74-search-a-2d-matrix/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/74-search-a-2d-matrix/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/74-search-a-2d-matrix/README.md b/74-search-a-2d-matrix/README.md new file mode 100644 index 0000000..da1b358 --- /dev/null +++ b/74-search-a-2d-matrix/README.md @@ -0,0 +1,30 @@ +

74. Search a 2D Matrix

Medium


Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

+ +
    +
  • Integers in each row are sorted from left to right.
  • +
  • The first integer of each row is greater than the last integer of the previous row.
  • +
+ +

 

+

Example 1:

+ +
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
+Output: true
+
+ +

Example 2:

+ +
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • -104 <= matrix[i][j], target <= 104
  • +
+
\ No newline at end of file diff --git a/740-delete-and-earn/740-delete-and-earn.cpp b/740-delete-and-earn/740-delete-and-earn.cpp new file mode 100644 index 0000000..82a73ac --- /dev/null +++ b/740-delete-and-earn/740-delete-and-earn.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int deleteAndEarn(vector& nums) { + int n = 10001; + vector values(n, 0); + for (int num : nums) + values[num] += num; + + int take = 0, skip = 0; + for (int i = 0; i < n; i++) { + int takei = skip + values[i]; + int skipi = max(skip, take); + take = takei; + skip = skipi; + } + return max(take, skip); + } +}; \ No newline at end of file diff --git a/740-delete-and-earn/NOTES.md b/740-delete-and-earn/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/740-delete-and-earn/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/740-delete-and-earn/README.md b/740-delete-and-earn/README.md new file mode 100644 index 0000000..8cab44f --- /dev/null +++ b/740-delete-and-earn/README.md @@ -0,0 +1,37 @@ +

740. Delete and Earn

Medium


You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:

+ +
    +
  • Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.
  • +
+ +

Return the maximum number of points you can earn by applying the above operation some number of times.

+ +

 

+

Example 1:

+ +
Input: nums = [3,4,2]
+Output: 6
+Explanation: You can perform the following operations:
+- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].
+- Delete 2 to earn 2 points. nums = [].
+You earn a total of 6 points.
+
+ +

Example 2:

+ +
Input: nums = [2,2,3,3,3,4]
+Output: 9
+Explanation: You can perform the following operations:
+- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].
+- Delete a 3 again to earn 3 points. nums = [3].
+- Delete a 3 once more to earn 3 points. nums = [].
+You earn a total of 9 points.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2 * 104
  • +
  • 1 <= nums[i] <= 104
  • +
+
\ No newline at end of file diff --git a/746-min-cost-climbing-stairs/746-min-cost-climbing-stairs.cpp b/746-min-cost-climbing-stairs/746-min-cost-climbing-stairs.cpp new file mode 100644 index 0000000..d20cb68 --- /dev/null +++ b/746-min-cost-climbing-stairs/746-min-cost-climbing-stairs.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + vector dp(cost.size()); + int n = cost.size(); + dp[n-1] = cost[n-1]; + dp[n-2] = cost[n-2]; + + if(n == 2)return min(dp[n-1],dp[n-2]); + + for(int i=n-3;i>=0;i--) + { + dp[i] = min(dp[i+1],dp[i+2])+cost[i]; + } + return min(dp[1],dp[0]); + } +}; \ No newline at end of file diff --git a/75-sort-colors/75-sort-colors.cpp b/75-sort-colors/75-sort-colors.cpp new file mode 100644 index 0000000..cb8a529 --- /dev/null +++ b/75-sort-colors/75-sort-colors.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + void sortColors(vector& nums) { + + int zero = 0; + int one = 0; + int two = 0; + + for(int i=0;i75. Sort Colors

Medium


Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

+ +

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

+ +

You must solve this problem without using the library's sort function.

+ +

 

+

Example 1:

+ +
Input: nums = [2,0,2,1,1,0]
+Output: [0,0,1,1,2,2]
+
+ +

Example 2:

+ +
Input: nums = [2,0,1]
+Output: [0,1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 300
  • +
  • nums[i] is either 0, 1, or 2.
  • +
+ +

 

+

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

+
\ No newline at end of file diff --git a/763-partition-labels/763-partition-labels.cpp b/763-partition-labels/763-partition-labels.cpp new file mode 100644 index 0000000..b023fe5 --- /dev/null +++ b/763-partition-labels/763-partition-labels.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector partitionLabels(string s) { + vector ans; + unordered_map m; + for(int i=0;i763. Partition Labels

Medium


You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.

+ +

Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.

+ +

Return a list of integers representing the size of these parts.

+ +

 

+

Example 1:

+ +
Input: s = "ababcbacadefegdehijhklij"
+Output: [9,7,8]
+Explanation:
+The partition is "ababcbaca", "defegde", "hijhklij".
+This is a partition so that each letter appears in at most one part.
+A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.
+
+ +

Example 2:

+ +
Input: s = "eccbbbbdec"
+Output: [10]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 500
  • +
  • s consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/78-subsets/78-subsets.cpp b/78-subsets/78-subsets.cpp new file mode 100644 index 0000000..5c3cf6a --- /dev/null +++ b/78-subsets/78-subsets.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vector> subsets(vector& nums) { + vector> ans; + for(int num=0; num<(1< subset; + for(int bit=0;bit78. Subsets

Medium


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3]
+Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
+
+ +

Example 2:

+ +
Input: nums = [0]
+Output: [[],[0]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 10
  • +
  • -10 <= nums[i] <= 10
  • +
  • All the numbers of nums are unique.
  • +
+
\ No newline at end of file diff --git a/79-word-search/79-word-search.cpp b/79-word-search/79-word-search.cpp new file mode 100644 index 0000000..d8efd7d --- /dev/null +++ b/79-word-search/79-word-search.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + + bool doesExist(vector>& board, string word,int i,int j,int m,int n) + { + if(word.size() == 0) + return true; + + if(i>=n || i<0 || j>=m || j< 0 || word[0] != board[i][j]) + return false; + + char c = board[i][j]; + board[i][j] = '*'; + string s = word.substr(1); + bool top = doesExist(board,s,i,j+1,m,n); + bool bottom = doesExist(board,s,i,j-1,m,n); + bool left = doesExist(board,s,i-1,j,m,n); + bool right = doesExist(board,s,i+1,j,m,n); + board[i][j] = c; + return top || bottom || left || right; + } + + bool exist(vector>& board, string word) { + + int n = board.size(); + int m = board[0].size(); + + for(int i=0;i79. Word Search

Medium


Given an m x n grid of characters board and a string word, return true if word exists in the grid.

+ +

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

+ +

 

+

Example 1:

+ +
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
+Output: true
+
+ +

Example 2:

+ +
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
+Output: true
+
+ +

Example 3:

+ +
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • m == board.length
  • +
  • n = board[i].length
  • +
  • 1 <= m, n <= 6
  • +
  • 1 <= word.length <= 15
  • +
  • board and word consists of only lowercase and uppercase English letters.
  • +
+ +

 

+

Follow up: Could you use search pruning to make your solution faster with a larger board?

+
\ No newline at end of file diff --git a/8-string-to-integer-atoi/8-string-to-integer-atoi.cpp b/8-string-to-integer-atoi/8-string-to-integer-atoi.cpp new file mode 100644 index 0000000..3c01e82 --- /dev/null +++ b/8-string-to-integer-atoi/8-string-to-integer-atoi.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int myAtoi(string input) { + int sign = 1; + int result = 0; + int index = 0; + int n = input.size(); + + while (index < n && input[index] == ' ') { + index++; + } + + if (index < n && input[index] == '+') { + sign = 1; + index++; + } else if (index < n && input[index] == '-') { + sign = -1; + index++; + } + + while (index < n && isdigit(input[index])) { + int digit = input[index] - '0'; + + if ((result > INT_MAX / 10) || (result == INT_MAX / 10 && digit > INT_MAX % 10)) { + + return sign == 1 ? INT_MAX : INT_MIN; + } + result = 10 * result + digit; + index++; + } + + return sign * result; + } +}; \ No newline at end of file diff --git a/8-string-to-integer-atoi/NOTES.md b/8-string-to-integer-atoi/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/8-string-to-integer-atoi/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/8-string-to-integer-atoi/README.md b/8-string-to-integer-atoi/README.md new file mode 100644 index 0000000..3866ace --- /dev/null +++ b/8-string-to-integer-atoi/README.md @@ -0,0 +1,74 @@ +

8. String to Integer (atoi)

Medium


Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).

+ +

The algorithm for myAtoi(string s) is as follows:

+ +
    +
  1. Read in and ignore any leading whitespace.
  2. +
  3. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
  4. +
  5. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
  6. +
  7. Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
  8. +
  9. If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
  10. +
  11. Return the integer as the final result.
  12. +
+ +

Note:

+ +
    +
  • Only the space character ' ' is considered a whitespace character.
  • +
  • Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.
  • +
+ +

 

+

Example 1:

+ +
Input: s = "42"
+Output: 42
+Explanation: The underlined characters are what is read in, the caret is the current reader position.
+Step 1: "42" (no characters read because there is no leading whitespace)
+         ^
+Step 2: "42" (no characters read because there is neither a '-' nor '+')
+         ^
+Step 3: "42" ("42" is read in)
+           ^
+The parsed integer is 42.
+Since 42 is in the range [-231, 231 - 1], the final result is 42.
+
+ +

Example 2:

+ +
Input: s = "   -42"
+Output: -42
+Explanation:
+Step 1: "   -42" (leading whitespace is read and ignored)
+            ^
+Step 2: "   -42" ('-' is read, so the result should be negative)
+             ^
+Step 3: "   -42" ("42" is read in)
+               ^
+The parsed integer is -42.
+Since -42 is in the range [-231, 231 - 1], the final result is -42.
+
+ +

Example 3:

+ +
Input: s = "4193 with words"
+Output: 4193
+Explanation:
+Step 1: "4193 with words" (no characters read because there is no leading whitespace)
+         ^
+Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
+         ^
+Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
+             ^
+The parsed integer is 4193.
+Since 4193 is in the range [-231, 231 - 1], the final result is 4193.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 200
  • +
  • s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.
  • +
+
\ No newline at end of file diff --git a/80-remove-duplicates-from-sorted-array-ii/80-remove-duplicates-from-sorted-array-ii.cpp b/80-remove-duplicates-from-sorted-array-ii/80-remove-duplicates-from-sorted-array-ii.cpp new file mode 100644 index 0000000..4695f55 --- /dev/null +++ b/80-remove-duplicates-from-sorted-array-ii/80-remove-duplicates-from-sorted-array-ii.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int removeDuplicates(vector& nums) { + int n = nums.size(), count = 0; + for (int i = 2; i < n; i++) + if (nums[i] == nums[i - 2 - count]) count++; + else nums[i - count] = nums[i]; + return n - count; +} +}; \ No newline at end of file diff --git a/80-remove-duplicates-from-sorted-array-ii/NOTES.md b/80-remove-duplicates-from-sorted-array-ii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/80-remove-duplicates-from-sorted-array-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/80-remove-duplicates-from-sorted-array-ii/README.md b/80-remove-duplicates-from-sorted-array-ii/README.md new file mode 100644 index 0000000..a22298a --- /dev/null +++ b/80-remove-duplicates-from-sorted-array-ii/README.md @@ -0,0 +1,51 @@ +

80. Remove Duplicates from Sorted Array II

Medium


Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.

+ +

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

+ +

Return k after placing the final result in the first k slots of nums.

+ +

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

+ +

Custom Judge:

+ +

The judge will test your solution with the following code:

+ +
int[] nums = [...]; // Input array
+int[] expectedNums = [...]; // The expected answer with correct length
+
+int k = removeDuplicates(nums); // Calls your implementation
+
+assert k == expectedNums.length;
+for (int i = 0; i < k; i++) {
+    assert nums[i] == expectedNums[i];
+}
+
+ +

If all assertions pass, then your solution will be accepted.

+ +

 

+

Example 1:

+ +
Input: nums = [1,1,1,2,2,3]
+Output: 5, nums = [1,1,2,2,3,_]
+Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
+It does not matter what you leave beyond the returned k (hence they are underscores).
+
+ +

Example 2:

+ +
Input: nums = [0,0,1,1,1,1,2,3,3]
+Output: 7, nums = [0,0,1,1,2,3,3,_,_]
+Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
+It does not matter what you leave beyond the returned k (hence they are underscores).
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums is sorted in non-decreasing order.
  • +
+
\ No newline at end of file diff --git a/804-unique-morse-code-words/NOTES.md b/804-unique-morse-code-words/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/804-unique-morse-code-words/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/804-unique-morse-code-words/README.md b/804-unique-morse-code-words/README.md new file mode 100644 index 0000000..7999f9d --- /dev/null +++ b/804-unique-morse-code-words/README.md @@ -0,0 +1,48 @@ +

804. Unique Morse Code Words

Easy


International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:

+ +
    +
  • 'a' maps to ".-",
  • +
  • 'b' maps to "-...",
  • +
  • 'c' maps to "-.-.", and so on.
  • +
+ +

For convenience, the full table for the 26 letters of the English alphabet is given below:

+ +
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
+ +

Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter.

+ +
    +
  • For example, "cab" can be written as "-.-..--...", which is the concatenation of "-.-.", ".-", and "-...". We will call such a concatenation the transformation of a word.
  • +
+ +

Return the number of different transformations among all words we have.

+ +

 

+

Example 1:

+ +
Input: words = ["gin","zen","gig","msg"]
+Output: 2
+Explanation: The transformation of each word is:
+"gin" -> "--...-."
+"zen" -> "--...-."
+"gig" -> "--...--."
+"msg" -> "--...--."
+There are 2 different transformations: "--...-." and "--...--.".
+
+ +

Example 2:

+ +
Input: words = ["a"]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 100
  • +
  • 1 <= words[i].length <= 12
  • +
  • words[i] consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/82-remove-duplicates-from-sorted-list-ii/82-remove-duplicates-from-sorted-list-ii.cpp b/82-remove-duplicates-from-sorted-list-ii/82-remove-duplicates-from-sorted-list-ii.cpp new file mode 100644 index 0000000..fb70afb --- /dev/null +++ b/82-remove-duplicates-from-sorted-list-ii/82-remove-duplicates-from-sorted-list-ii.cpp @@ -0,0 +1,42 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + if(head == NULL || head->next == NULL)return head; + ListNode * ans = new ListNode(); + ListNode * temp = ans; + + if(head->next->val != head->val) + { + ans->next = head; + head = head->next; + ans = ans->next; + ans->next = deleteDuplicates(head); + return temp->next; + } + else + { + while(head->next != NULL && head->val == head->next->val) + head = head->next; + + if(head->next == NULL) + { + return temp->next; + } + else + { + head = head->next; + return deleteDuplicates(head); + } + } + } +}; \ No newline at end of file diff --git a/82-remove-duplicates-from-sorted-list-ii/NOTES.md b/82-remove-duplicates-from-sorted-list-ii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/82-remove-duplicates-from-sorted-list-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/82-remove-duplicates-from-sorted-list-ii/README.md b/82-remove-duplicates-from-sorted-list-ii/README.md new file mode 100644 index 0000000..f981c5f --- /dev/null +++ b/82-remove-duplicates-from-sorted-list-ii/README.md @@ -0,0 +1,24 @@ +

82. Remove Duplicates from Sorted List II

Medium


Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,3,4,4,5]
+Output: [1,2,5]
+
+ +

Example 2:

+ +
Input: head = [1,1,1,2,3]
+Output: [2,3]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 300].
  • +
  • -100 <= Node.val <= 100
  • +
  • The list is guaranteed to be sorted in ascending order.
  • +
+
\ No newline at end of file diff --git a/823-binary-trees-with-factors/NOTES.md b/823-binary-trees-with-factors/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/823-binary-trees-with-factors/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/823-binary-trees-with-factors/README.md b/823-binary-trees-with-factors/README.md new file mode 100644 index 0000000..64dd47c --- /dev/null +++ b/823-binary-trees-with-factors/README.md @@ -0,0 +1,28 @@ +

823. Binary Trees With Factors

Medium


Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.

+ +

We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.

+ +

Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: arr = [2,4]
+Output: 3
+Explanation: We can make these trees: [2], [4], [4, 2, 2]
+ +

Example 2:

+ +
Input: arr = [2,4,5,10]
+Output: 7
+Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 1000
  • +
  • 2 <= arr[i] <= 109
  • +
  • All the values of arr are unique.
  • +
+
\ No newline at end of file diff --git a/84-largest-rectangle-in-histogram/84-largest-rectangle-in-histogram.cpp b/84-largest-rectangle-in-histogram/84-largest-rectangle-in-histogram.cpp new file mode 100644 index 0000000..df44f3b --- /dev/null +++ b/84-largest-rectangle-in-histogram/84-largest-rectangle-in-histogram.cpp @@ -0,0 +1,72 @@ +class Solution { +public: + int largestRectangleArea(vector& heights) { + int n = heights.size(); + stack s; + int maxi = 0; + + for(int i=0;i<=n;i++) + { + while(!s.empty() && (i == n || heights[s.top()] >= heights[i])) + { + int height = heights[s.top()]; + s.pop(); + int w; + if(s.empty()) w = i; + else + { + w = i - s.top() - 1; + } + maxi = max(maxi,height*w); + } + s.push(i); + } + return maxi; + +// int n = heights.size(); +// stack s; +// vector left(n); +// vector right(n); + +// for(int i=0;i= heights[i] ) +// { +// s.pop(); +// } +// if(s.empty()) +// left[i] = 0; +// else +// left[i] = s.top()+1; + +// s.push(i); +// } +// while(!s.empty()) s.pop(); +// for(int i=n-1;i>=0;i--) +// { +// while(!s.empty() && heights[s.top()] >= heights[i]) +// { +// s.pop(); +// } +// if(s.empty()) +// { +// right[i] = n-1; +// } +// else +// { +// right[i] = s.top()-1; +// } + +// s.push(i); +// } +// int maxi = INT_MIN; +// for(int i=0;i84. Largest Rectangle in Histogram

Hard


Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

+ +

 

+

Example 1:

+ +
Input: heights = [2,1,5,6,2,3]
+Output: 10
+Explanation: The above is a histogram where width of each bar is 1.
+The largest rectangle is shown in the red area, which has an area = 10 units.
+
+ +

Example 2:

+ +
Input: heights = [2,4]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= heights.length <= 105
  • +
  • 0 <= heights[i] <= 104
  • +
+
\ No newline at end of file diff --git a/847-shortest-path-visiting-all-nodes/NOTES.md b/847-shortest-path-visiting-all-nodes/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/847-shortest-path-visiting-all-nodes/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/847-shortest-path-visiting-all-nodes/README.md b/847-shortest-path-visiting-all-nodes/README.md new file mode 100644 index 0000000..6b6a4b1 --- /dev/null +++ b/847-shortest-path-visiting-all-nodes/README.md @@ -0,0 +1,31 @@ +

847. Shortest Path Visiting All Nodes

Hard


You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge.

+ +

Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

+ +

 

+

Example 1:

+ +
Input: graph = [[1,2,3],[0],[0],[0]]
+Output: 4
+Explanation: One possible path is [1,0,2,0,3]
+
+ +

Example 2:

+ +
Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
+Output: 4
+Explanation: One possible path is [0,1,4,2,3]
+
+ +

 

+

Constraints:

+ +
    +
  • n == graph.length
  • +
  • 1 <= n <= 12
  • +
  • 0 <= graph[i].length < n
  • +
  • graph[i] does not contain i.
  • +
  • If graph[a] contains b, then graph[b] contains a.
  • +
  • The input graph is always connected.
  • +
+
\ No newline at end of file diff --git a/856-score-of-parentheses/856-score-of-parentheses.cpp b/856-score-of-parentheses/856-score-of-parentheses.cpp new file mode 100644 index 0000000..51744e5 --- /dev/null +++ b/856-score-of-parentheses/856-score-of-parentheses.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int scoreOfParentheses(string s) { + int depth = 0, res = 0; + char prev = '('; + + for (const char &ch: s) { + if (ch == '(') + depth++; + else { + depth--; + if (prev == '(') + res += pow(2, depth); + } + + prev = ch; + } + + return res; + } +}; \ No newline at end of file diff --git a/856-score-of-parentheses/NOTES.md b/856-score-of-parentheses/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/856-score-of-parentheses/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/856-score-of-parentheses/README.md b/856-score-of-parentheses/README.md new file mode 100644 index 0000000..365c40c --- /dev/null +++ b/856-score-of-parentheses/README.md @@ -0,0 +1,38 @@ +

856. Score of Parentheses

Medium


Given a balanced parentheses string s, return the score of the string.

+ +

The score of a balanced parentheses string is based on the following rule:

+ +
    +
  • "()" has score 1.
  • +
  • AB has score A + B, where A and B are balanced parentheses strings.
  • +
  • (A) has score 2 * A, where A is a balanced parentheses string.
  • +
+ +

 

+

Example 1:

+ +
Input: s = "()"
+Output: 1
+
+ +

Example 2:

+ +
Input: s = "(())"
+Output: 2
+
+ +

Example 3:

+ +
Input: s = "()()"
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= s.length <= 50
  • +
  • s consists of only '(' and ')'.
  • +
  • s is a balanced parentheses string.
  • +
+
\ No newline at end of file diff --git a/858-mirror-reflection/NOTES.md b/858-mirror-reflection/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/858-mirror-reflection/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/858-mirror-reflection/README.md b/858-mirror-reflection/README.md new file mode 100644 index 0000000..4d94fe5 --- /dev/null +++ b/858-mirror-reflection/README.md @@ -0,0 +1,29 @@ +

858. Mirror Reflection

Medium


There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.

+ +

The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.

+ +

Given the two integers p and q, return the number of the receptor that the ray meets first.

+ +

The test cases are guaranteed so that the ray will meet a receptor eventually.

+ +

 

+

Example 1:

+ +
Input: p = 2, q = 1
+Output: 2
+Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.
+
+ +

Example 2:

+ +
Input: p = 3, q = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= q <= p <= 1000
  • +
+
\ No newline at end of file diff --git a/875-koko-eating-bananas/875-koko-eating-bananas.cpp b/875-koko-eating-bananas/875-koko-eating-bananas.cpp new file mode 100644 index 0000000..bf8c68d --- /dev/null +++ b/875-koko-eating-bananas/875-koko-eating-bananas.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int minEatingSpeed(vector& piles, int h) { + int left = 1, right = *max_element(piles.begin(), piles.end()); + + while (left < right) { + int middle = (left + right) / 2; + int hourSpent = 0; + + for (int pile : piles) { + hourSpent += pile / middle + (pile % middle != 0); + } + if (hourSpent <= h) { + right = middle; + } else { + left = middle + 1; + } + } + + return right; + } +}; diff --git a/876-middle-of-the-linked-list/876-middle-of-the-linked-list.cpp b/876-middle-of-the-linked-list/876-middle-of-the-linked-list.cpp new file mode 100644 index 0000000..a0dac35 --- /dev/null +++ b/876-middle-of-the-linked-list/876-middle-of-the-linked-list.cpp @@ -0,0 +1,26 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* middleNode(ListNode* head) { + if(head == NULL || head->next == NULL)return head; + ListNode * slow = head; + ListNode * fast = head; + + while(fast != NULL && fast->next != NULL) + { + slow = slow->next; + fast = fast->next->next; + } + + return slow; + } +}; \ No newline at end of file diff --git a/881-boats-to-save-people/881-boats-to-save-people.cpp b/881-boats-to-save-people/881-boats-to-save-people.cpp new file mode 100644 index 0000000..1ebdae6 --- /dev/null +++ b/881-boats-to-save-people/881-boats-to-save-people.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int numRescueBoats(vector& people, int limit) { + sort(people.begin(),people.end()); + int i=0; + int j=people.size()-1; + int ans = 0; + while(ilimit) + { + ans+=1; + j--; + } + else + { + ans+=1; + i++; + j--; + } + } + + if(i==j)ans++; + + return ans; + } +}; \ No newline at end of file diff --git a/881-boats-to-save-people/NOTES.md b/881-boats-to-save-people/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/881-boats-to-save-people/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/881-boats-to-save-people/README.md b/881-boats-to-save-people/README.md new file mode 100644 index 0000000..919904d --- /dev/null +++ b/881-boats-to-save-people/README.md @@ -0,0 +1,34 @@ +

881. Boats to Save People

Medium


You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.

+ +

Return the minimum number of boats to carry every given person.

+ +

 

+

Example 1:

+ +
Input: people = [1,2], limit = 3
+Output: 1
+Explanation: 1 boat (1, 2)
+
+ +

Example 2:

+ +
Input: people = [3,2,2,1], limit = 3
+Output: 3
+Explanation: 3 boats (1, 2), (2) and (3)
+
+ +

Example 3:

+ +
Input: people = [3,5,3,4], limit = 5
+Output: 4
+Explanation: 4 boats (3), (3), (4), (5)
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= people.length <= 5 * 104
  • +
  • 1 <= people[i] <= limit <= 3 * 104
  • +
+
\ No newline at end of file diff --git a/890-find-and-replace-pattern/890-find-and-replace-pattern.cpp b/890-find-and-replace-pattern/890-find-and-replace-pattern.cpp new file mode 100644 index 0000000..0d59f4f --- /dev/null +++ b/890-find-and-replace-pattern/890-find-and-replace-pattern.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + vector findAndReplacePattern(vector& words, string& pattern) { + vector ans; + string p = normalise(pattern); + for(auto& w : words) + if(p == normalise(w)) ans.push_back(w); + return ans; +} +string normalise(string w) { + unordered_map mp; + char c = 'a'; + for(auto ch : w) + if(!mp.count(ch)) mp[ch] = c++; + for(auto& ch : w) ch = mp[ch]; + return w; +} +}; \ No newline at end of file diff --git a/890-find-and-replace-pattern/NOTES.md b/890-find-and-replace-pattern/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/890-find-and-replace-pattern/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/890-find-and-replace-pattern/README.md b/890-find-and-replace-pattern/README.md new file mode 100644 index 0000000..0866cb1 --- /dev/null +++ b/890-find-and-replace-pattern/README.md @@ -0,0 +1,31 @@ +

890. Find and Replace Pattern

Medium


Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.

+ +

A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.

+ +

Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.

+ +

 

+

Example 1:

+ +
Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
+Output: ["mee","aqq"]
+Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. 
+"ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.
+
+ +

Example 2:

+ +
Input: words = ["a","b","c"], pattern = "a"
+Output: ["a","b","c"]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= pattern.length <= 20
  • +
  • 1 <= words.length <= 50
  • +
  • words[i].length == pattern.length
  • +
  • pattern and words[i] are lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/895-maximum-frequency-stack/895-maximum-frequency-stack.cpp b/895-maximum-frequency-stack/895-maximum-frequency-stack.cpp new file mode 100644 index 0000000..c25895f --- /dev/null +++ b/895-maximum-frequency-stack/895-maximum-frequency-stack.cpp @@ -0,0 +1,23 @@ +class FreqStack { + priority_queue>> q; + unordered_map freq; + int pos = 0; +public: + void push(int x) { + q.emplace(++freq[x], make_pair(++pos, x)); + } + + int pop() { + auto val = q.top(); + q.pop(); + int x = val.second.second; + freq[x]--; + return x; + } +}; +/** + * Your FreqStack object will be instantiated and called as such: + * FreqStack* obj = new FreqStack(); + * obj->push(val); + * int param_2 = obj->pop(); + */ \ No newline at end of file diff --git a/895-maximum-frequency-stack/NOTES.md b/895-maximum-frequency-stack/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/895-maximum-frequency-stack/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/895-maximum-frequency-stack/README.md b/895-maximum-frequency-stack/README.md new file mode 100644 index 0000000..00870ce --- /dev/null +++ b/895-maximum-frequency-stack/README.md @@ -0,0 +1,46 @@ +

895. Maximum Frequency Stack

Hard


Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.

+ +

Implement the FreqStack class:

+ +
    +
  • FreqStack() constructs an empty frequency stack.
  • +
  • void push(int val) pushes an integer val onto the top of the stack.
  • +
  • int pop() removes and returns the most frequent element in the stack. +
      +
    • If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.
    • +
    +
  • +
+ +

 

+

Example 1:

+ +
Input
+["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"]
+[[], [5], [7], [5], [7], [4], [5], [], [], [], []]
+Output
+[null, null, null, null, null, null, null, 5, 7, 5, 4]
+
+Explanation
+FreqStack freqStack = new FreqStack();
+freqStack.push(5); // The stack is [5]
+freqStack.push(7); // The stack is [5,7]
+freqStack.push(5); // The stack is [5,7,5]
+freqStack.push(7); // The stack is [5,7,5,7]
+freqStack.push(4); // The stack is [5,7,5,7,4]
+freqStack.push(5); // The stack is [5,7,5,7,4,5]
+freqStack.pop();   // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].
+freqStack.pop();   // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].
+freqStack.pop();   // return 5, as 5 is the most frequent. The stack becomes [5,7,4].
+freqStack.pop();   // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= val <= 109
  • +
  • At most 2 * 104 calls will be made to push and pop.
  • +
  • It is guaranteed that there will be at least one element in the stack before calling pop.
  • +
+
\ No newline at end of file diff --git a/90-subsets-ii/90-subsets-ii.cpp b/90-subsets-ii/90-subsets-ii.cpp new file mode 100644 index 0000000..68ad33e --- /dev/null +++ b/90-subsets-ii/90-subsets-ii.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + void helper(vector& nums,vector>& ans,vector& temp,int ind) + { + ans.push_back(temp); + + for(int i=ind;i !=nums.size();i++) + { + if(i == ind || nums[i]!=nums[i-1]) + { + temp.push_back(nums[i]); + helper(nums,ans,temp,i+1); + temp.pop_back(); + } + + } + + } + + + vector> subsetsWithDup(vector& nums) { + sort(nums.begin(),nums.end()); + vector> ans; + vector temp; + helper(nums,ans,temp,0); + return ans; + } +}; \ No newline at end of file diff --git a/90-subsets-ii/NOTES.md b/90-subsets-ii/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/90-subsets-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/90-subsets-ii/README.md b/90-subsets-ii/README.md new file mode 100644 index 0000000..975b739 --- /dev/null +++ b/90-subsets-ii/README.md @@ -0,0 +1,20 @@ +

90. Subsets II

Medium


Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [1,2,2]
+Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
+

Example 2:

+
Input: nums = [0]
+Output: [[],[0]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 10
  • +
  • -10 <= nums[i] <= 10
  • +
+
\ No newline at end of file diff --git a/916-word-subsets/NOTES.md b/916-word-subsets/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/916-word-subsets/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/916-word-subsets/README.md b/916-word-subsets/README.md new file mode 100644 index 0000000..e09ef82 --- /dev/null +++ b/916-word-subsets/README.md @@ -0,0 +1,35 @@ +

916. Word Subsets

Medium


You are given two string arrays words1 and words2.

+ +

A string b is a subset of string a if every letter in b occurs in a including multiplicity.

+ +
    +
  • For example, "wrr" is a subset of "warrior" but is not a subset of "world".
  • +
+ +

A string a from words1 is universal if for every string b in words2, b is a subset of a.

+ +

Return an array of all the universal strings in words1. You may return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"]
+Output: ["facebook","google","leetcode"]
+
+ +

Example 2:

+ +
Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"]
+Output: ["apple","google","leetcode"]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words1.length, words2.length <= 104
  • +
  • 1 <= words1[i].length, words2[i].length <= 10
  • +
  • words1[i] and words2[i] consist only of lowercase English letters.
  • +
  • All the strings of words1 are unique.
  • +
+
\ No newline at end of file diff --git a/921-minimum-add-to-make-parentheses-valid/NOTES.md b/921-minimum-add-to-make-parentheses-valid/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/921-minimum-add-to-make-parentheses-valid/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/921-minimum-add-to-make-parentheses-valid/README.md b/921-minimum-add-to-make-parentheses-valid/README.md new file mode 100644 index 0000000..45c6664 --- /dev/null +++ b/921-minimum-add-to-make-parentheses-valid/README.md @@ -0,0 +1,37 @@ +

921. Minimum Add to Make Parentheses Valid

Medium


A parentheses string is valid if and only if:

+ +
    +
  • It is the empty string,
  • +
  • It can be written as AB (A concatenated with B), where A and B are valid strings, or
  • +
  • It can be written as (A), where A is a valid string.
  • +
+ +

You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.

+ +
    +
  • For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing parenthesis to be "())))".
  • +
+ +

Return the minimum number of moves required to make s valid.

+ +

 

+

Example 1:

+ +
Input: s = "())"
+Output: 1
+
+ +

Example 2:

+ +
Input: s = "((("
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s[i] is either '(' or ')'.
  • +
+
\ No newline at end of file diff --git a/946-validate-stack-sequences/946-validate-stack-sequences.cpp b/946-validate-stack-sequences/946-validate-stack-sequences.cpp new file mode 100644 index 0000000..56343be --- /dev/null +++ b/946-validate-stack-sequences/946-validate-stack-sequences.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + bool validateStackSequences(vector& pushed, vector& popped) { + stack stack; + int i = 0; + for (int x : pushed) { + stack.push(x); + while (stack.size() && stack.top() == popped[i]) { + stack.pop(); + i++; + } + } + return stack.size() ==0 ; + } +}; \ No newline at end of file diff --git a/946-validate-stack-sequences/NOTES.md b/946-validate-stack-sequences/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/946-validate-stack-sequences/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/946-validate-stack-sequences/README.md b/946-validate-stack-sequences/README.md new file mode 100644 index 0000000..7f03a3a --- /dev/null +++ b/946-validate-stack-sequences/README.md @@ -0,0 +1,32 @@ +

946. Validate Stack Sequences

Medium


Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
+Output: true
+Explanation: We might do the following sequence:
+push(1), push(2), push(3), push(4),
+pop() -> 4,
+push(5),
+pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
+
+ +

Example 2:

+ +
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
+Output: false
+Explanation: 1 cannot be popped before 2.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= pushed.length <= 1000
  • +
  • 0 <= pushed[i] <= 1000
  • +
  • All the elements of pushed are unique.
  • +
  • popped.length == pushed.length
  • +
  • popped is a permutation of pushed.
  • +
+
\ No newline at end of file diff --git a/977-squares-of-a-sorted-array/977-squares-of-a-sorted-array.cpp b/977-squares-of-a-sorted-array/977-squares-of-a-sorted-array.cpp new file mode 100644 index 0000000..9a60d78 --- /dev/null +++ b/977-squares-of-a-sorted-array/977-squares-of-a-sorted-array.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector sortedSquares(vector& nums) { + + + int i = 0; + int j = nums.size()-1; + int k = nums.size()-1; + vector ans(nums.size()); + while(j>=i) + { + if(nums[j]*nums[j] < nums[i]*nums[i]) + { + ans[k--] = pow(nums[i++],2); + } + else + { + ans[k--] = pow(nums[j--],2); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/977-squares-of-a-sorted-array/NOTES.md b/977-squares-of-a-sorted-array/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/977-squares-of-a-sorted-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/977-squares-of-a-sorted-array/README.md b/977-squares-of-a-sorted-array/README.md new file mode 100644 index 0000000..60339c0 --- /dev/null +++ b/977-squares-of-a-sorted-array/README.md @@ -0,0 +1,28 @@ +

977. Squares of a Sorted Array

Easy


Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

+ +

 

+

Example 1:

+ +
Input: nums = [-4,-1,0,3,10]
+Output: [0,1,9,16,100]
+Explanation: After squaring, the array becomes [16,1,0,9,100].
+After sorting, it becomes [0,1,9,16,100].
+
+ +

Example 2:

+ +
Input: nums = [-7,-3,2,3,11]
+Output: [4,9,9,49,121]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums is sorted in non-decreasing order.
  • +
+ +

 

+Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?
\ No newline at end of file diff --git a/98-validate-binary-search-tree/98-validate-binary-search-tree.cpp b/98-validate-binary-search-tree/98-validate-binary-search-tree.cpp new file mode 100644 index 0000000..8a1081d --- /dev/null +++ b/98-validate-binary-search-tree/98-validate-binary-search-tree.cpp @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + bool helper(TreeNode* root,TreeNode * min,TreeNode * max) + { + if(root == NULL) + return true; + + if(min && root->val <= min->val || max && root->val >= max->val ) + return false; + return helper(root->left,min,root) && helper(root->right,root,max); + } + + bool isValidBST(TreeNode* root) { + if(root == NULL) + return true; + + return helper(root,NULL,NULL); + } +}; \ No newline at end of file diff --git a/98-validate-binary-search-tree/NOTES.md b/98-validate-binary-search-tree/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/98-validate-binary-search-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/98-validate-binary-search-tree/README.md b/98-validate-binary-search-tree/README.md new file mode 100644 index 0000000..cf6bca1 --- /dev/null +++ b/98-validate-binary-search-tree/README.md @@ -0,0 +1,32 @@ +

98. Validate Binary Search Tree

Medium


Given the root of a binary tree, determine if it is a valid binary search tree (BST).

+ +

A valid BST is defined as follows:

+ +
    +
  • The left subtree of a node contains only nodes with keys less than the node's key.
  • +
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • +
  • Both the left and right subtrees must also be binary search trees.
  • +
+ +

 

+

Example 1:

+ +
Input: root = [2,1,3]
+Output: true
+
+ +

Example 2:

+ +
Input: root = [5,1,4,null,null,3,6]
+Output: false
+Explanation: The root node's value is 5 but its right child's value is 4.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -231 <= Node.val <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/981-time-based-key-value-store/981-time-based-key-value-store.cpp b/981-time-based-key-value-store/981-time-based-key-value-store.cpp new file mode 100644 index 0000000..5d8024b --- /dev/null +++ b/981-time-based-key-value-store/981-time-based-key-value-store.cpp @@ -0,0 +1,37 @@ +class TimeMap { +public: + map>> m; + TimeMap() { + + } + + void set(string key, string value, int timestamp) { + m[key].push_back({timestamp,value}); + } + + string get(string key, int timestamp) { + if(!m[key].size()) + return ""; + int low = 0; + int high = m[key].size()-1; + while(low<=high) + { + int mid = low + (high-low)/2; + if(m[key][mid].first == timestamp) + return m[key][mid].second; + else if(m[key][mid].first > timestamp) + high = mid-1; + else + low = mid + 1; + } + + return high >= 0 ? m[key][high].second : ""; + } +}; + +/** + * Your TimeMap object will be instantiated and called as such: + * TimeMap* obj = new TimeMap(); + * obj->set(key,value,timestamp); + * string param_2 = obj->get(key,timestamp); + */ \ No newline at end of file diff --git a/983-minimum-cost-for-tickets/NOTES.md b/983-minimum-cost-for-tickets/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/983-minimum-cost-for-tickets/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/983-minimum-cost-for-tickets/README.md b/983-minimum-cost-for-tickets/README.md new file mode 100644 index 0000000..9812fcc --- /dev/null +++ b/983-minimum-cost-for-tickets/README.md @@ -0,0 +1,51 @@ +

983. Minimum Cost For Tickets

Medium


You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365.

+ +

Train tickets are sold in three different ways:

+ +
    +
  • a 1-day pass is sold for costs[0] dollars,
  • +
  • a 7-day pass is sold for costs[1] dollars, and
  • +
  • a 30-day pass is sold for costs[2] dollars.
  • +
+ +

The passes allow that many days of consecutive travel.

+ +
    +
  • For example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8.
  • +
+ +

Return the minimum number of dollars you need to travel every day in the given list of days.

+ +

 

+

Example 1:

+ +
Input: days = [1,4,6,7,8,20], costs = [2,7,15]
+Output: 11
+Explanation: For example, here is one way to buy passes that lets you travel your travel plan:
+On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.
+On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.
+On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.
+In total, you spent $11 and covered all the days of your travel.
+
+ +

Example 2:

+ +
Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
+Output: 17
+Explanation: For example, here is one way to buy passes that lets you travel your travel plan:
+On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.
+On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.
+In total, you spent $17 and covered all the days of your travel.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= days.length <= 365
  • +
  • 1 <= days[i] <= 365
  • +
  • days is in strictly increasing order.
  • +
  • costs.length == 3
  • +
  • 1 <= costs[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/991-broken-calculator/991-broken-calculator.cpp b/991-broken-calculator/991-broken-calculator.cpp new file mode 100644 index 0000000..ec7ed73 --- /dev/null +++ b/991-broken-calculator/991-broken-calculator.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int brokenCalc(int startValue, int target) { + long long ans = 0; + long long tar = target; + while(startValue != tar){ + if(tar%2 == 0 and startValue < tar){ + tar /= 2; + } + else if(tar > startValue){ + tar +=1; + } + else{ + ans += abs(tar-startValue)-1; + tar = startValue; + } + ans++; + } + return ans; + } +}; \ No newline at end of file diff --git a/991-broken-calculator/NOTES.md b/991-broken-calculator/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/991-broken-calculator/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/991-broken-calculator/README.md b/991-broken-calculator/README.md new file mode 100644 index 0000000..c8f5264 --- /dev/null +++ b/991-broken-calculator/README.md @@ -0,0 +1,38 @@ +

991. Broken Calculator

Medium


There is a broken calculator that has the integer startValue on its display initially. In one operation, you can:

+ +
    +
  • multiply the number on display by 2, or
  • +
  • subtract 1 from the number on display.
  • +
+ +

Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator.

+ +

 

+

Example 1:

+ +
Input: startValue = 2, target = 3
+Output: 2
+Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
+
+ +

Example 2:

+ +
Input: startValue = 5, target = 8
+Output: 2
+Explanation: Use decrement and then double {5 -> 4 -> 8}.
+
+ +

Example 3:

+ +
Input: startValue = 3, target = 10
+Output: 3
+Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= x, y <= 109
  • +
+
\ No newline at end of file diff --git a/994-rotting-oranges/994-rotting-oranges.cpp b/994-rotting-oranges/994-rotting-oranges.cpp new file mode 100644 index 0000000..a01fbd8 --- /dev/null +++ b/994-rotting-oranges/994-rotting-oranges.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + int orangesRotting(vector>& grid) { + + int fresh = 0; + queue> q; + int dir[] = {-1,0,1,0,-1}; + int n = grid.size(); + int m = grid[0].size(); + for(int i=0;i p = q.front(); + q.pop(); + for(int i=0;i<4;i++) + { + int r = p.first+dir[i]; + int c = p.second+dir[i+1]; + + if(r>=0 && r=0 && c0)return -1; + if(ans == -1)return 0; + return ans; + } +}; \ No newline at end of file diff --git a/994-rotting-oranges/NOTES.md b/994-rotting-oranges/NOTES.md new file mode 100644 index 0000000..38c1374 --- /dev/null +++ b/994-rotting-oranges/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/994-rotting-oranges/README.md b/994-rotting-oranges/README.md new file mode 100644 index 0000000..75b7ad2 --- /dev/null +++ b/994-rotting-oranges/README.md @@ -0,0 +1,43 @@ +

994. Rotting Oranges

Medium


You are given an m x n grid where each cell can have one of three values:

+ +
    +
  • 0 representing an empty cell,
  • +
  • 1 representing a fresh orange, or
  • +
  • 2 representing a rotten orange.
  • +
+ +

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

+ +

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

+ +

 

+

Example 1:

+ +
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
+Output: 4
+
+ +

Example 2:

+ +
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
+Output: -1
+Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
+
+ +

Example 3:

+ +
Input: grid = [[0,2]]
+Output: 0
+Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 10
  • +
  • grid[i][j] is 0, 1, or 2.
  • +
+
\ No newline at end of file diff --git a/Add 1 to a number represented as linked list - GFG/README.md b/Add 1 to a number represented as linked list - GFG/README.md new file mode 100644 index 0000000..fe492ba --- /dev/null +++ b/Add 1 to a number represented as linked list - GFG/README.md @@ -0,0 +1,29 @@ +# Add 1 to a number represented as linked list +## Easy +
+

A number N is represented in Linked List such that each digit corresponds to a node in linked list. You need to add 1 to it.

+ +

Example 1:

+ +
Input:
+LinkedList: 4->5->6
+Output: 457 
+
+ +

Example 2:

+ +
Input:
+LinkedList: 1->2->3
+Output: 124 
+ +

Your Task:
+Your task is to complete the function addOne() which takes the head of the linked list as the only argument and returns the head of the modified linked list. The driver code prints the number.
+Note: The head represents the left-most digit of the number.

+ +

Expected Time Complexity: O(N).
+Expected Auxiliary Space: O(1).

+ +

Constraints:
+1 <= N <= 101000

+

+
\ No newline at end of file diff --git a/Add 1 to a number represented as linked list - GFG/add-1-to-a-number-represented-as-linked-list.cpp b/Add 1 to a number represented as linked list - GFG/add-1-to-a-number-represented-as-linked-list.cpp new file mode 100644 index 0000000..9c29053 --- /dev/null +++ b/Add 1 to a number represented as linked list - GFG/add-1-to-a-number-represented-as-linked-list.cpp @@ -0,0 +1,119 @@ +// { Driver Code Starts +//Initial template for C++ + +#include +using namespace std; + +struct Node +{ + int data; + struct Node* next; + + Node(int x){ + data = x; + next = NULL; + } +}; + +void printList(Node* node) +{ + while (node != NULL) { + cout << node->data; + node = node->next; + } + cout<<"\n"; +} + + + // } Driver Code Ends +//User function template for C++ + +/* + +struct Node +{ + int data; + struct Node* next; + + Node(int x){ + data = x; + next = NULL; + } +}; + +*/ + +class Solution +{ + public: + Node* reverse(Node *head) +{ + Node *p = NULL, + *c = head, + *n = head->next; + while(c!=NULL){ + c->next = p; + p = c; + c = n; + if(n!=NULL) n = n->next; + } + return p; +} +Node* addOne(Node *head) +{ + head = reverse(head); + Node *temp = head; + + while(temp!=NULL){ + //99999..... case + if(temp->next==NULL and + temp->data==9) + { + temp->data = 1; + Node * zeroNode = new Node(0); + zeroNode->next = head; + head = zeroNode; + temp = temp->next; + } + else if(temp->data==9){ + //9 case + temp->data = 0; + temp = temp->next; + } + else{ + //other all cases + temp->data++; + temp = temp->next; + break; + } + } + head = reverse(head); + return head; + } +}; + +// { Driver Code Starts. + +int main() +{ + int t; + cin>>t; + while(t--) + { + string s; + cin>>s; + + Node* head = new Node( s[0]-'0' ); + Node* tail = head; + for(int i=1; inext = new Node( s[i]-'0' ); + tail = tail->next; + } + Solution ob; + head = ob.addOne(head); + printList(head); + } + return 0; +} + // } Driver Code Ends \ No newline at end of file diff --git a/Allocate minimum number of pages - GFG/README.md b/Allocate minimum number of pages - GFG/README.md new file mode 100644 index 0000000..1dd3c40 --- /dev/null +++ b/Allocate minimum number of pages - GFG/README.md @@ -0,0 +1,55 @@ +# Allocate minimum number of pages +## Hard +
+

You are given N number of books. Every ith book has Ai number of pages and are arranged in sorted order.
+
+You have to allocate contagious books to M number of students. There can be many ways or permutations to do so. In each permutation, one of the M students will be allocated the maximum number of pages. Out of all these permutations, the task is to find that particular permutation in which the maximum number of pages allocated to a student is minimum of those in all the other permutations and print this minimum value.

+ +

Each book will be allocated to exactly one student. Each student has to be allocated at least one book.

+ +

Note: Return -1 if a valid assignment is not possible, and allotment should be in contiguous order (see the explanation for better understanding).

+ +

 

+ +

Example 1:

+ +
Input:
+N = 4
+A[] = {12,34,67,90}
+M = 2
+Output:113
+Explanation:Allocation can be done in 
+following ways:{12} and {34, 67, 90} 
+Maximum Pages = 191{12, 34} and {67, 90} 
+Maximum Pages = 157{12, 34, 67} and {90} 
+Maximum Pages =113. Therefore, the minimum 
+of these cases is 113, which is selected 
+as the output.
+ +


+Example 2:

+ +
Input:
+N = 3
+A[] = {15,17,20}
+M = 2
+Output:32
+Explanation: Allocation is done as
+{15,17} and {20}
+ +

Your Task:
+You don't need to read input or print anything. Your task is to complete the function findPages() which takes 2 Integers N, and m and an array A[] of length N as input and returns the expected answer.

+ +


+Expected Time Complexity: O(NlogN)
+Expected Auxilliary Space: O(1)

+ +


+Constraints:
+1 <= N <= 105
+1 <= A [ i ] <= 106
+1 <= M <= 105

+ +

 

+

+
\ No newline at end of file diff --git a/Allocate minimum number of pages - GFG/allocate-minimum-number-of-pages.cpp b/Allocate minimum number of pages - GFG/allocate-minimum-number-of-pages.cpp new file mode 100644 index 0000000..3f8c676 --- /dev/null +++ b/Allocate minimum number of pages - GFG/allocate-minimum-number-of-pages.cpp @@ -0,0 +1,89 @@ +// { Driver Code Starts +// Initial template for C++ + +#include +using namespace std; + + + // } Driver Code Ends +//User function template in C++ + +class Solution +{ + public: + bool CanMaxCanAllot(int mid,int A[], int N,int M) + { + int student=1; + int sum=0; + for(int i=0;imid) + { + student++; + sum=A[i]; + } + if(student>M) + return false; + } + return true; + } + //Function to find minimum number of pages. + int findPages(int A[], int N, int M) + { + //code here + int low = 0; + int high = 0; + for(int i=0;i>t; + while(t--){ + int n; + cin>>n; + int A[n]; + for(int i=0;i>A[i]; + } + int m; + cin>>m; + Solution ob; + cout << ob.findPages(A, n, m) << endl; + } + return 0; +} + // } Driver Code Ends \ No newline at end of file diff --git a/Anagram of String - GFG/README.md b/Anagram of String - GFG/README.md new file mode 100644 index 0000000..32b6e62 --- /dev/null +++ b/Anagram of String - GFG/README.md @@ -0,0 +1,34 @@ +# Anagram of String +## Easy +
+

Given two strings S1 and S2 in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find the minimum number of characters to be deleted to make both the strings anagram. Two strings are called anagram of each other if one of them can be converted into another by rearranging its letters.

+ +

Example 1:

+ +
Input:
+S1 = bcadeh
+S2 = hea
+Output: 3
+Explanation: We need to remove b, c
+and d from S1.
+
+ +

Example 2:

+ +
Input:
+S1 = cddgk
+S2 = gcd
+Output: 2
+Explanation: We need to remove d and
+k from S1.
+ +

Your Task:
+Complete the function remAnagram() which takes two strings S1, S2 as input parameter, and returns minimum characters needs to be deleted.

+ +

Expected Time Complexity: O(max(|S1|, |S2|)), where |S| = length of string S.
+Expected Auxiliary Space: O(26)

+ +

Constraints:
+1 <= |S1|, |S2| <= 105

+

+
\ No newline at end of file diff --git a/Anagram of String - GFG/anagram-of-string.cpp b/Anagram of String - GFG/anagram-of-string.cpp new file mode 100644 index 0000000..1caba68 --- /dev/null +++ b/Anagram of String - GFG/anagram-of-string.cpp @@ -0,0 +1,37 @@ +// { Driver Code Starts +#include +using namespace std; +const int CHARS = 26; + +// function to calculate minimum numbers of characters +// to be removed to make two strings anagram +int remAnagram(string str1, string str2); + +// Driver program to run the case +int main() +{ + int t; + cin>>t; + while(t--) + { + string str1,str2; + cin>>str1>>str2; + cout << remAnagram(str1, str2); + cout< freq(26, 0); + for(char &ch:str1) freq[ch-'a']++; + for(char &ch:str2) freq[ch-'a']--; + int res = 0; + for(int i=0; i<26; i++) + res += abs(freq[i]); + return res; +} \ No newline at end of file diff --git a/Array to BST - GFG/README.md b/Array to BST - GFG/README.md new file mode 100644 index 0000000..1990d04 --- /dev/null +++ b/Array to BST - GFG/README.md @@ -0,0 +1,50 @@ +# Array to BST +## Easy +
+

Given a sorted array. Convert it into a Height balanced Binary Search Tree (BST). Find the preorder traversal of height balanced BST. If there exist many such balanced BST consider the tree whose preorder is lexicographically smallest.
+Height balanced BST means a binary tree in which the depth of the left subtree and the right subtree of every node never differ by more than 1.

+ +

Example 1:

+ +
Input: nums = {1, 2, 3, 4}
+Output: {2, 1, 3, 4}
+Explanation: 
+The preorder traversal of the following 
+BST formed is {2, 1, 3, 4}:
+           2
+         /   \
+           1     3
+               \
+                4
+
+ +

 

+ +

Example 2:

+ +
Input: nums = {1,2,3,4,5,6,7}
+Ouput: {4,2,1,3,6,5,7}
+Explanation: 
+The preorder traversal of the following
+BST formed is {4,2,1,3,6,5,7} :
+        4
+       / \
+      2   6
+     / \  / \
+    1   3 5  7
+
+ +

 

+ +

Your Task:
+You don't need to read or print anything. Your task is to complete the function sortedArrayToBST() which takes the sorted array nums as input paramater and returns the preorder traversal of height balanced BST. If there exist many such balanced BST consider the tree whose preorder is lexicographically smallest.

+ +

Expected Time Complexity: O(n)
+Expected Space Complexity: O(n)

+ +

Constraints:
+1 ≤ |nums| ≤ 104
+-104 ≤ nums[i] ≤ 104

+

+
\ No newline at end of file diff --git a/Array to BST - GFG/array-to-bst.cpp b/Array to BST - GFG/array-to-bst.cpp new file mode 100644 index 0000000..896adbe --- /dev/null +++ b/Array to BST - GFG/array-to-bst.cpp @@ -0,0 +1,46 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution { +public: + void solve(vector &nums, vector &ans , int l, int h) + { + if(l>h) + return; + + int mid = (l+h) / 2; + int temp = nums[mid]; + ans.push_back(temp); + + solve(nums,ans,l,mid-1); + solve(nums,ans,mid+1,h); + } + vector sortedArrayToBST(vector& nums) { + + vectorans; + int l = 0; + int h = nums.size()-1; + solve(nums,ans,l,h); + return ans; + } +}; + +// { Driver Code Starts. +int main(){ + int tc; + cin >> tc; + while(tc--){ + int n; + cin >> n; + vectornums(n); + for(int i = 0; i < n; i++)cin >> nums[i]; + Solution obj; + vectorans = obj.sortedArrayToBST(nums); + for(auto i: ans) + cout << i <<" "; + cout << "\n"; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Biconnected Graph - GFG/README.md b/Biconnected Graph - GFG/README.md new file mode 100644 index 0000000..6efbce4 --- /dev/null +++ b/Biconnected Graph - GFG/README.md @@ -0,0 +1,53 @@ +# Biconnected Graph +## Medium +
+

Given a graph with n vertices, e edges and an array arr[] denoting the edges connected to each other, check whether it is Biconnected or not.
+Note: The given graph is Undirected.

+ +

 

+ +

Example 1:

+ +
Input:
+n = 2, e = 1
+arr = {0, 1}
+Output:
+1
+Explanation:
+       0
+      /
+     1
+The above graph is Biconnected.
+ +

Example 2:

+ +
Input:
+n = 3, e = 2
+arr = {0, 1, 1, 2}
+Output:
+0
+Explanation:
+       0
+      /
+     1
+      \
+       2
+The above graph is not Biconnected.
+ +

 

+ +

Your Task:
+You don't need to read input or print anything. Your task is to complete the function biGraph() which takes 2 Integers n, and e and an array arr of length 2*e as input and returns 1 if the graph is biconnected else returns 0.

+ +

 

+ +

Expected Time Complexity: O(n+e)
+Expected Auxiliary Space: O(n)

+ +

 

+ +

Constraints:
+1 <= e <= 100
+2 <= n <= 100

+

+
\ No newline at end of file diff --git a/Biconnected Graph - GFG/biconnected-graph.cpp b/Biconnected Graph - GFG/biconnected-graph.cpp new file mode 100644 index 0000000..0f7910a --- /dev/null +++ b/Biconnected Graph - GFG/biconnected-graph.cpp @@ -0,0 +1,47 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution { + public: + int biGraph(int arr[], int n, int e) { + // code here + unordered_map> m; + + int size = 2*e; + + if(n <= 2) + return true; + + for(int i = 0; i < size; i += 2){ + m[arr[i]].push_back(arr[i+1]); + m[arr[i+1]].push_back(arr[i]); + } + + for(auto x: m){ + if(x.second.size() <= 1) + return false; + } + + return true; + } +}; + +// { Driver Code Starts. +int main() { + int t; + cin >> t; + while (t--) { + int n,e; + cin>>n>>e; + + int arr[2*e]; + for(int i=0; i<2*e; i++) + cin>>arr[i]; + + Solution ob; + cout << ob.biGraph(arr,n,e) << endl; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Binary Array Sorting - GFG/README.md b/Binary Array Sorting - GFG/README.md new file mode 100644 index 0000000..b34c7ed --- /dev/null +++ b/Binary Array Sorting - GFG/README.md @@ -0,0 +1,47 @@ +# Binary Array Sorting +## Easy +
+

Given a binary array A[] of size N. The task is to arrange the array in increasing order.
+Note: The binary array contains only 0  and 1.

+ +

Example 1:

+ +
Input: 
+5
+1 0 1 1 0
+
+Output: 
+0 0 1 1 1
+
+Explanation: 
+After arranging the elements in 
+increasing order, elements will be as 
+0 0 1 1 1.
+ +

Example 2:

+ +
Input:
+10
+1 0 1 1 1 1 1 0 0 0
+
+Output: 
+0 0 0 0 1 1 1 1 1 1
+
+Explanation: 
+After arranging the elements in 
+increasing order, elements will be 
+0 0 0 0 1 1 1 1 1 1.
+
+
+ +

Your Task: This is a function problem. You only need to complete the function binSort() that takes the array A[] and it's size N as parameters and sorts the array. The printing is done automatically by the driver code.
+
+Expected Time Complexity: O(N)
+Expected Auxilliary Space: O(1)

+
+Constraints:
+1 <= N <= 106
+0 <= A[i] <= 1

+

+
\ No newline at end of file diff --git a/Binary Array Sorting - GFG/binary-array-sorting.cpp b/Binary Array Sorting - GFG/binary-array-sorting.cpp new file mode 100644 index 0000000..a5db672 --- /dev/null +++ b/Binary Array Sorting - GFG/binary-array-sorting.cpp @@ -0,0 +1,79 @@ +// { Driver Code Starts +// A Sample C++ program for beginners with Competitive Programming + +#include +using namespace std; + + // } Driver Code Ends +class Solution{ + public: + + // A[]: input array + // N: input array + //Function to sort the binary array. + void binSort(int A[], int N) + { + //Your code here + + /************** + * No need to print the array + * ************/ + int i=0; + int j = N-1; + while(j>i) + { + + while(i=0 && j>i) + { + if(A[j]==0) + break; + else + j--; + } + + swap(A[i],A[j]); + i++; + j--; + } + return; + + } +}; + +// { Driver Code Starts. +int main() { + int T; + cin>>T; + // Input the number of testcases + while(T--) + { + int N; + cin>>N; //Input size of array N + int A[N]; + + for(int i = 0; i < N; i++) + cin>>A[i]; + + Solution obj; + obj.binSort(A,N); + + for(int x:A) + cout< +

Given a Binary Number B, find its decimal equivalent.

+ +

Example 1:

+ +
Input: B = 10001000
+Output: 136
+
+ +

Example 2:

+ +
Input: B = 101100
+Output: 44
+
+ +

 

+ +

Your Task:
+You don't need to read or print anything. Your task is to complete the function binary_to_decimal() which takes the binary number as string input parameter and returns its decimal equivalent.

+ +

Expected Time Complexity: O(K * Log(K)) where K is number of bits in binary number.
+Expected Space Complexity: O(1)

+ +

Constraints:
+1 <= number of bits in binary number  <= 16

+

+ \ No newline at end of file diff --git a/Binary number to decimal number - GFG/binary-number-to-decimal-number.cpp b/Binary number to decimal number - GFG/binary-number-to-decimal-number.cpp new file mode 100644 index 0000000..970bd70 --- /dev/null +++ b/Binary number to decimal number - GFG/binary-number-to-decimal-number.cpp @@ -0,0 +1,31 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution +{ + public: + int binary_to_decimal(string str){ + int len = str.length(); + int ans=0; + for(int i=len-1;i>=0;i--) + ans+=(1<<(len-i-1))*(str[i]-'0'); + return ans; + }; +}; + +// { Driver Code Starts. +int main(){ + int T; + cin >> T; + while(T--) + { + string str; + cin >> str; + Solution ob; + int ans = ob.binary_to_decimal(str); + cout << ans <<"\n"; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Bitwise AND of the Array - GFG/README.md b/Bitwise AND of the Array - GFG/README.md new file mode 100644 index 0000000..5bc4707 --- /dev/null +++ b/Bitwise AND of the Array - GFG/README.md @@ -0,0 +1,40 @@ +# Bitwise AND of the Array +## Medium +
+

Given an array A[ ] of N integers and an integer X. In one operation, you can change the ith element of the array to any integer value where 1 ≤ i ≤ N. Calculate minimum number of such operations required such that the bitwise AND of all the elements of the array is strictly greater than X.

+ +

Example 1:

+ +
Input:
+N = 4, X = 2
+A[] = {3, 1, 2, 7}
+Output: 
+2
+Explanation: 
+After performing two operations:
+Modified array: {3, 3, 11, 7} 
+Now, Bitwise AND of all the elements
+is 3 & 3 & 11 & 7 = 3 
+
+ +

Example 2:

+ +
Input:
+N = 3, X = 1
+A[] = {2, 2, 2}
+Output: 
+0
+
+ +

Your Task:
+You don't need to read input or print anything. Your task is to complete the function count( ) which takes NA[ ] and X as input parameters and returns the minimum number of operations required.

+ +

Expected Time Complexity: O(N * Log(max(A[ ])))
+Expected Auxiliary Space: O(1)

+ +

Constraints:
+1 ≤ N ≤ 105
+1 ≤ A[i] ≤ 109
+1 ≤ X ≤ 109

+

+
\ No newline at end of file diff --git a/Bitwise AND of the Array - GFG/bitwise-and-of-the-array.cpp b/Bitwise AND of the Array - GFG/bitwise-and-of-the-array.cpp new file mode 100644 index 0000000..748651b --- /dev/null +++ b/Bitwise AND of the Array - GFG/bitwise-and-of-the-array.cpp @@ -0,0 +1,64 @@ +// { Driver Code Starts +//Initial Template for C++ +#include +using namespace std; + + // } Driver Code Ends +//User function Template for C++ +class Solution{ + public: + int count(int N, vector A,int X) + + { + + int ans=N; + + int mask=0; + + for(int i=31;i>=0;i--){ + + if((X>>i)&1){ + + mask^=(1<>t; + while(t--) + { + int N,X; + cin>>N>>X; + vector A(N); + for(auto &i:A) + cin>>i; + Solution obj; + int ans = obj.count(N, A, X); + cout< +

Given an array A[] of elements, You'd like to know how many triangles can be formed with side lengths equal to adjacent elements from A[].

+ +

Construct an array of integers of length N - 2 where ith element is equal to 1 if it is possible to form a triangle with side lengths A[i], A[i+1], and A[i+2]. otherwise 0.

+ +

Note: A triangle can be formed with side lengths a, b and c if a+b>c and a+c>b and b+c>a.

+ +

Example 1:

+ +
Input:
+N = 4
+A[] = {1, 2, 2, 4}
+Output:
+1 0
+Explanation:
+output[0] = 1 because we can form a 
+triangle with side lengths 1,2 and 2.
+output[1] = 0 because 2+2<4 so, we cannot 
+form a triangle with side lengths 2,2 and 4.
+
+ +

Example 2:

+ +
Input: 
+N = 5
+A[] = {2, 10, 2, 10, 2}
+Output:
+0 1 0
+Explanation:
+output[0] = 0 because 2+2<10 so, we cannot
+form a triangle with side lengths 2, 10 and 2. 
+output[1] = 1 we can form a triangle with 
+side lengths 10,2 and 10. 
+output[1] = 0 because 2+2<10 so, we can
+form a triangle with side lengths 2, 10 and 2. 
+
+ +

Your Task:
+You dont need to read input or print anything. Your task is to c
omplete the function canMakeTriangle() which takes the array A and the integer as the input parameters, and returns the array of answers.

+ +

Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(N)

+ +

Constraints:
+3 ≤ N ≤ 10
+1 ≤ arr[i] ≤ 109

+

+ \ No newline at end of file diff --git a/Can Make Triangle - GFG/can-make-triangle.cpp b/Can Make Triangle - GFG/can-make-triangle.cpp new file mode 100644 index 0000000..b052964 --- /dev/null +++ b/Can Make Triangle - GFG/can-make-triangle.cpp @@ -0,0 +1,52 @@ +// { Driver Code Starts +//Initial Template for C++ +#include +using namespace std; + + // } Driver Code Ends +//User function Template for C++ +class Solution{ + public: + bool check(int a,int b,int c) + { + if(a + b > c and a + c > b and b + c > a) + return true; + return false; + } + + vector canMakeTriangle(vector A, int N) + { + // code here + vector res; + for(int i = 0;i < A.size() - 2;i++) + { + if(check(A[i],A[i+1],A[i+2])) + res.push_back(1); + else + res.push_back(0); + } + return res; + } +}; + +// { Driver Code Starts. +int main() +{ + int t;cin>>t; + while(t--) + { + int N; + cin>>N; + vector A(N); + for(int i=0;i>A[i]; + Solution ob; + auto ans = ob.canMakeTriangle(A, N); + for(int i=0;i +

Given two n-ary trees. Check if they are mirror images of each other or not. You are also given e denoting the number of edges in both trees, and two arrays, A[] and B[]. Each array has 2*e space separated values u,v denoting an edge from u to v for the both trees.

+ +


+Example 1:

+ +
Input:
+n = 3, e = 2
+A[] = {1, 2, 1, 3}
+B[] = {1, 3, 1, 2}
+Output:
+1
+Explanation:
+   1          1
+ / \        /  \
+2   3      3    2 
+As we can clearly see, the second tree
+is mirror image of the first.
+
+ +

Example 2:

+ +
Input:
+n = 3, e = 2
+A[] = {1, 2, 1, 3}
+B[] = {1, 2, 1, 3}
+Output:
+0
+Explanation:
+   1          1
+ / \        /  \
+2   3      2    3 
+As we can clearly see, the second tree
+isn't mirror image of the first.
+ +


+Your Task:
+You don't need to read input or print anything. Your task is to complete the function checkMirrorTree() which takes 2 Integers n, and e;  and two arrays A[] and B[] of size 2*e as input and returns 1 if the trees are mirror images of each other and 0 if not.

+ +


+Expected Time Complexity: O(n)
+Expected Auxiliary Space: O(n)

+ +


+Constraints:
+1 <= n,e <= 105

+

+ \ No newline at end of file diff --git a/Check Mirror in N-ary tree - GFG/check-mirror-in-nary-tree.cpp b/Check Mirror in N-ary tree - GFG/check-mirror-in-nary-tree.cpp new file mode 100644 index 0000000..42e7edd --- /dev/null +++ b/Check Mirror in N-ary tree - GFG/check-mirror-in-nary-tree.cpp @@ -0,0 +1,52 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function Template for C++ + +class Solution { + public: + int checkMirrorTree(int n, int e, int A[], int B[]) { + vector> adjA(n+1),adjB(n+1); + for(int i=0;i<2*e;i+=2){ + adjA[A[i]].push_back(A[i+1]); + adjB[B[i]].push_back(B[i+1]); + } + + for(int i=1;i<=n;i++){ + int sizel = adjA[i].size(),sizer = adjB[i].size(); + if(sizel!=sizer)return false; + for(int j=0;j> t; + while (t--) { + int n,e; + + cin>>n>>e; + int A[2*e], B[2*e]; + + for(int i=0; i<2*e; i++) + cin>>A[i]; + + for(int i=0; i<2*e; i++) + cin>>B[i]; + + Solution ob; + cout << ob.checkMirrorTree(n,e,A,B) << endl; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Check if subtree - GFG/README.md b/Check if subtree - GFG/README.md new file mode 100644 index 0000000..bdc60f0 --- /dev/null +++ b/Check if subtree - GFG/README.md @@ -0,0 +1,49 @@ +# Check if subtree +## Medium +
+

Given two binary trees with head reference as T and S having at most N nodes. The task is to check if S is present as subtree in T.
+A subtree of a tree T1 is a tree T2 consisting of a node in T1 and all of its descendants in T1.

+ +

Example 1:

+ +
Input:
+T:      1          S:   3
+      /   \            /
+     2     3          4
+   /  \    /
+  N    N  4
+Output: 1 
+Explanation: S is present in T
+
+
+ +

Example 2:

+ +
Input:
+T:      26         S:   26
+       /   \           /  \
+     10     N        10    N
+   /    \           /  \
+   20    30        20  30
+  /  \            /  \
+ 40   60         40  60
+Output: 1 
+Explanation: 
+S and T are both same. Hence, 
+it can be said that S is a subtree 
+of T.
+
+ +

Your Task:
+You don't need to read input or print anything. Your task is to complete the function isSubtree() that takes root node of S and T as parameters and returns 1 if S is a subtree of T else 0.

+ +


+Expected Time Complexity: O(N).
+Expected Auxiliary Space: O(N).

+ +

Constraints:
+1 <= Number of nodes <= 105
+1 <= Value of nodes <= 104

+

+
\ No newline at end of file diff --git a/Check if subtree - GFG/check-if-subtree.cpp b/Check if subtree - GFG/check-if-subtree.cpp new file mode 100644 index 0000000..5e6de14 --- /dev/null +++ b/Check if subtree - GFG/check-if-subtree.cpp @@ -0,0 +1,160 @@ +// { Driver Code Starts +#include +using namespace std; + +// Tree Node +struct Node { + int data; + Node *left; + Node *right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; + +// Function to Build Tree +Node *buildTree(string str) { + // Corner Case + if (str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for (string str; iss >> str;) + ip.push_back(str); + + // Create the root of the tree + Node *root = new Node(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while (!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node *currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if (currVal != "N") { + + // Create the left child for the current node + currNode->left = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if (i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if (currVal != "N") { + + // Create the right child for the current node + currNode->right = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + + // } Driver Code Ends +/* A binary tree node + +struct Node +{ + int data; + struct Node* left; + struct Node* right; + + Node(int x){ + data = x; + left = right = NULL; + } +}; + */ + +class Solution +{ + public: + bool issame(Node* root1, Node* root2) + { + if(root1 == NULL && root2 == NULL) + return true; + + if(root1 == NULL && root2) + return false; + + if(root1 && root2 == NULL) + return false; + + if(root1 -> data != root2 -> data) + return false; + + else + { + bool x = issame(root1 -> left, root2 -> left); + + if(x == false) + return false; + + else + return issame(root1 -> right, root2 -> right); + } + } + + bool isSubTree(Node* root1, Node* root2) + { + if(root1 == NULL) + return false; + + bool x = issame(root1, root2); + + if(x) + return true; + + if(isSubTree(root1 -> left, root2)) + return true; + + else + return isSubTree(root1 -> right, root2); + } +}; + +// { Driver Code Starts. + +int main() { + int tc; + scanf("%d ", &tc); + while (tc--) { + string strT, strS; + getline(cin, strT); + Node *rootT = buildTree(strT); + getline(cin, strS); + Solution obj; + Node *rootS = buildTree(strS); + cout << obj.isSubTree(rootT, rootS) << "\n"; + + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Clone a stack without using extra space - GFG/README.md b/Clone a stack without using extra space - GFG/README.md new file mode 100644 index 0000000..8832ea9 --- /dev/null +++ b/Clone a stack without using extra space - GFG/README.md @@ -0,0 +1,30 @@ +# Clone a stack without using extra space +## Medium +
+

Given elements of a stack, clone the stack without using extra space.

+ +


+Example 1:

+ +
Input:
+N = 10
+st[] = {1, 1, 2, 2, 3, 4, 5, 5, 6, 7}
+Output:
+1 
+
+ +


+Your Task:  
+You don't need to read input or print anything. Your task is to complete the function clonestack() which takes the input stack st[], an empty stack cloned[], you have to clone the stack st into stack cloned.
+The driver code itself prints 1 in the output if the stack st is cloned properly and prints 0 otherwise.

+ +


+Expected Time Complexity: O(N*N)
+Expected Auxiliary Space: O(1)

+ +

Constraints:
+1 <= N <= 1000

+1<= st[i] <= 105

+

+
\ No newline at end of file diff --git a/Clone a stack without using extra space - GFG/clone-a-stack-without-using-extra-space.cpp b/Clone a stack without using extra space - GFG/clone-a-stack-without-using-extra-space.cpp new file mode 100644 index 0000000..a45a167 --- /dev/null +++ b/Clone a stack without using extra space - GFG/clone-a-stack-without-using-extra-space.cpp @@ -0,0 +1,87 @@ +// { Driver Code Starts +//Initial template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function Template for C++ + +class Solution{ + public: + void clonestack(stack st, stack& cloned) + { + int n =st.size(); + int k = 0; + + while(k+1 != n) + { + int var = st.top(); + st.pop(); + int p = n - k -1; + while(p--) + { + int a = st.top(); + st.pop(); + cloned.push(a); + } + st.push(var); + while(!cloned.empty()) + { + int a = cloned.top(); + cloned.pop(); + st.push(a); + } + k++; + + } + + while(!st.empty()) + { + int a = st.top(); + st.pop(); + cloned.push(a); + } + + } +}; + +// { Driver Code Starts. +int main() +{ + int t; + cin>>t; + while(t--) + { + int N; + cin >> N; + int arr[N]; + stack st; + vector copy; + for(int i = 0; i < N; i++){ + cin >> arr[i]; + st.push(arr[i]); + copy.push_back(arr[i]); + } + + reverse(copy.begin(), copy.end()); + + Solution ob; + stack cloned; + ob.clonestack(st,cloned); + vector check; + while(cloned.size()) + { + check.push_back(cloned.top()); + cloned.pop(); + } + + int flag = 0; + if(check!=copy) + flag = 1; + + cout<<1-flag< +

Given elements of a stack, clone the stack without using extra space.

+ +


+Example 1:

+ +
Input:
+N = 10
+st[] = {1, 1, 2, 2, 3, 4, 5, 5, 6, 7}
+Output:
+1 
+
+ +


+Your Task:  
+You don't need to read input or print anything. Your task is to complete the function clonestack() which takes the input stack st[], an empty stack cloned[], you have to clone the stack st into stack cloned.
+The driver code itself prints 1 in the output if the stack st is cloned properly and prints 0 otherwise.

+ +


+Expected Time Complexity: O(N*N)
+Expected Auxiliary Space: O(1)

+ +

Constraints:
+1 <= N <= 1000

+1<= st[i] <= 105

+

+ \ No newline at end of file diff --git a/Clone a stack without usinig extra space - GFG/clone-a-stack-without-usinig-extra-space.cpp b/Clone a stack without usinig extra space - GFG/clone-a-stack-without-usinig-extra-space.cpp new file mode 100644 index 0000000..cc7548e --- /dev/null +++ b/Clone a stack without usinig extra space - GFG/clone-a-stack-without-usinig-extra-space.cpp @@ -0,0 +1,62 @@ +// { Driver Code Starts +//Initial template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function Template for C++ + +class Solution{ + public: + void clonestack(stack st, stack& cloned) + { + if(st.empty()) return; + int topele=st.top(); + st.pop(); + + clonestack(st,cloned); + cloned.push(topele); + + } +}; + +// { Driver Code Starts. +int main() +{ + int t; + cin>>t; + while(t--) + { + int N; + cin >> N; + int arr[N]; + stack st; + vector copy; + for(int i = 0; i < N; i++){ + cin >> arr[i]; + st.push(arr[i]); + copy.push_back(arr[i]); + } + + reverse(copy.begin(), copy.end()); + + Solution ob; + stack cloned; + ob.clonestack(st,cloned); + vector check; + while(cloned.size()) + { + check.push_back(cloned.top()); + cloned.pop(); + } + + int flag = 0; + if(check!=copy) + flag = 1; + + cout<<1-flag< +

In Geekland there is a grid of coins of size N x N. You have to find the maximum sum of coins in any sub-grid of size K x K.
+Note: Coins of the negative denomination are also possible at Geekland.

+
+Example 1:

+ +
Input: N = 5, K = 3 
+mat[[]] = {1, 1, 1, 1, 1} 
+          {2, 2, 2, 2, 2} 
+          {3, 8, 6, 7, 3} 
+          {4, 4, 4, 4, 4} 
+          {5, 5, 5, 5, 5}
+Output: 48
+Explanation: {8, 6, 7}
+             {4, 4, 4}
+             {5, 5, 5}
+has the maximum sum
+
+ +


+Example 2:

+ +
Input: N = 1, K = 1
+mat[[]] = {{4}} 
+Output: 4
+
+ +

Your Task:  
+You don't need to read input or print anything. Complete the function Maximum_Sum() which takes the matrix mat[], size of Matrix N, and value K as input parameters and returns the maximum sum.

+ +

Expected Time Complexity: O(N2)
+Expected Auxiliary Space: O(N2)

+ +

Constraints:
+1 ≤ K ≤ N ≤ 103
+-5*105 ≤ mat[i][j] ≤ 5*105

+

+ \ No newline at end of file diff --git a/Coins of Geekland - GFG/coins-of-geekland.cpp b/Coins of Geekland - GFG/coins-of-geekland.cpp new file mode 100644 index 0000000..7b5f754 --- /dev/null +++ b/Coins of Geekland - GFG/coins-of-geekland.cpp @@ -0,0 +1,70 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution{ + + public: + int Maximum_Sum(vector> &mat,int N,int K){ + int dp[N+1][N+1]; + for(int i=0 ;i=0 && j-K>=0){ + sum= dp[i][j]-dp[i-K][j]-dp[i][j-K] + dp[i-K][j-K]; + maxcount=max(sum,maxcount); + } + + } + } + + return maxcount; + } +}; + +// { Driver Code Starts. + +int main() { + + int t; + cin >> t; + while(t--) + { + int N; + cin>>N; + vector> mat(N,vector(N,0)); + + for(int i=0;i>mat[i][j]; + } + } + + int k;cin>>k; + Solution obj; + cout << obj.Maximum_Sum(mat,N,k)<<"\n"; + } + + return 0; +} + // } Driver Code Ends \ No newline at end of file diff --git a/Compute Before Matrix - GFG/README.md b/Compute Before Matrix - GFG/README.md new file mode 100644 index 0000000..1967e47 --- /dev/null +++ b/Compute Before Matrix - GFG/README.md @@ -0,0 +1,54 @@ +# Compute Before Matrix +## Medium +
+

For a given 2D Matrix before, the corresponding cell (x, y) of the after matrix is calculated as follows: 

+ +
+
res = 0;
+for(i = 0; i <= x; i++){
+    for( j = 0; j <= y; j++){              
+        res += before(i,j);
+    }
+}
+after(x,y) = res;
+
+
+ +

Given an N*M 2D-Matrix after, your task is to find the corresponding before matrix for the given matrix.

+ +

 

+ +

Example 1:

+ +
Input:
+N = 2, M = 3
+after[][] = {{1, 3, 6},
+            {3, 7, 11}}
+Output:
+1 2 3
+2 2 1
+Explanation:
+The before matrix for the given after matrix
+matrix is {{1, 2, 3}, {2, 2, 1}}.
+ +

Example 2:

+ +
Input: 
+N = 1, M = 3
+after[][] = {{1, 3, 5}}
+Output:
+1 2 2
+Explanation: 
+The before matrix for the given after matrix
+is {{1, 2, 2}}.
+ +

Your Task:
+Complete the function computeBeforeMatrix() which takes the integers N, M, and the 2D Matrix after as the input parameters, and returns the before matrix of the given after matrix.

+ +

Expected Time Complexity: O(N*M)
+Expected Auxiliary Space: O(1)

+ +

Constraints:
+1 ≤ N, M, after[i][j]  ≤  109

+

+
\ No newline at end of file diff --git a/Compute Before Matrix - GFG/compute-before-matrix.cpp b/Compute Before Matrix - GFG/compute-before-matrix.cpp new file mode 100644 index 0000000..85748d8 --- /dev/null +++ b/Compute Before Matrix - GFG/compute-before-matrix.cpp @@ -0,0 +1,52 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function Template for C++ + +class Solution { + public: + vector> computeBeforeMatrix(int n, int m, vector> after) { + for (int i = n - 1; i >= 0; i--) { + for (int j = m - 1; j >= 0; j--) { + int top = 0; + int left = 0; + int diagonal = 0; + + if (i - 1 >= 0) top = after[i - 1][j]; + if (j - 1 >= 0) left = after[i][j - 1]; + if (i - 1 >= 0 and j - 1 >= 0) diagonal = after[i - 1][j - 1]; + + after[i][j] -= top + left - diagonal; + } + } + return after; + } +}; + +// { Driver Code Starts. +int main(){ + int t; + cin>>t; + while(t--){ + int N, M; + cin>>N>>M; + vector> after(N,vector(M)); + for(int i=0;i>after[i][j]; + } + } + Solution obj; + vector> before=obj.computeBeforeMatrix(N,M,after); + for(int i=0;i +

Given an array numbers[] of positive integers and a positive integer X, The task is to find the number of ways that X can be obtained by writing pair of integers in the array numbers[] next to each other. In other words, find the number of ordered pairs (i,j) such that i != j and X is the concatenation of numbers[i] and numbers[j]

+ +

Example 1:

+ +
Input:
+N = 4 
+numbers[] = {1, 212, 12, 12}
+X = 1212
+Output:
+3
+Explanation:
+We can obtain X=1212 by concatenating:
+numbers[0] = 1 with numbers[1] = 212
+numbers[2] = 12 with numbers[3] = 12
+numbers[3] = 12 with numbers[2] = 12
+
+ +

Example 2:

+ +
Input: 
+N = 3
+numbers[] = {11, 11, 110}
+X = 11011
+Output:
+2
+Explanation:
+We can obtain X=11011 by concatenating:
+numbers[2] = 110 with numbers[0] = 11
+numbers[2] = 110 with numbers[1] = 11
+
+ +

Your Task:
+You dont need to read input or print anything. Your task is to complete the function countPairs() which takes the integer N , the integer X, and the array numbers[] as the input parameters, and returns the number of pairs which satisfies the above condition.

+ +

Expected Time Complexity: O(N*Log10(A[i]) + (Log10X)2)
+Expected Auxiliary Space: O(N*Log10(A[i]))

+ +

Constraints:
+1 ≤ N ≤ 5*104 
+1 ≤ numbers[] ≤ 109
+1 ≤ X ≤ 109

+

+ \ No newline at end of file diff --git a/Concatenate two numbers - GFG/concatenate-two-numbers.cpp b/Concatenate two numbers - GFG/concatenate-two-numbers.cpp new file mode 100644 index 0000000..551e356 --- /dev/null +++ b/Concatenate two numbers - GFG/concatenate-two-numbers.cpp @@ -0,0 +1,62 @@ +// { Driver Code Starts +//Initial Template for C++ +#include +using namespace std; + + // } Driver Code Ends +//User function Template for C++ +class Solution{ + public: + long long countPairs(int N, int X, vector numbers){ + unordered_map suffixMap; + int n = X, suffix = 0, mul = 1; + while(n > 0) { + if(n % 10) { + suffix = n % 10 * mul + suffix; + for(auto num: numbers) suffixMap[suffix] += num == suffix; + } + n /= 10; + mul *= 10; + } + + int ans = 0; + mul /= 10; + while(mul > 0) { + int prefix = X / mul; + int suffix = X % mul; + + // Don't calculate if suffix starts with 0. + if(suffix >= mul / 10) { + int prefixCount = 0; + for(auto num: numbers) prefixCount += num == prefix; + + ans += prefixCount * suffixMap[suffix]; + if(prefix == suffix) ans -= prefixCount; + } + + mul /= 10; + } + + return ans; + } +}; + +// { Driver Code Starts. +int main() +{ + int t;cin>>t; + while(t--) + { + int N,X; + cin>>N>>X; + vector numbers(N); + for(int i=0;i>numbers[i]; + Solution ob; + long long ans = ob.countPairs(N, X, numbers); + cout< +

Geek has developed an effective vaccine for Corona virus and he wants each of the N houses in Geek Land to have access to it. Given a binary tree where each node represents a house in Geek Land, find the minimum number of houses that should be supplied with the vaccine kit if one vaccine kit is sufficient for that house, its parent house and it's immediate child nodes.  

+ +

 

+ +

Example 1:

+ +
Input:
+    1
+   / \
+  2   3 
+        \
+         4
+          \
+           5
+            \
+             6
+
+Output:
+2
+Explanation:
+The vaccine kits should be 
+supplied to house numbers 1 and 5. 
+
+ +

Example 2:

+ +
Input:
+    1
+   / \
+  2   3 
+Output:
+1
+Explanation:
+The vaccine kits should be 
+supplied to house number 1.
+ +


+Your Task:
+You don't need to read input or print anything. Complete the function supplyVaccine() which takes the root of the housing tree as input parameter and returns the minimum number of houses that should be supplied with the vaccine kit.

+ +


+Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(N)

+ +


+Constraints:
+1 ≤ N ≤ 105

+

+ \ No newline at end of file diff --git a/Corona Vaccine - GFG/corona-vaccine.cpp b/Corona Vaccine - GFG/corona-vaccine.cpp new file mode 100644 index 0000000..7d67af0 --- /dev/null +++ b/Corona Vaccine - GFG/corona-vaccine.cpp @@ -0,0 +1,155 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + +struct Node +{ + int data; + Node *left; + Node *right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; + +// Function to Build Tree +Node *buildTree(string str) +{ + // Corner Case + if (str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for (string str; iss >> str;) + ip.push_back(str); + + // Create the root of the tree + Node *root = new Node(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while (!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node *currNode = queue.front(); + queue.pop(); + + // Get the current Node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if (currVal != "N") { + + // Create the left child for the current Node + currNode->left = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if (i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if (currVal != "N") { + + // Create the right child for the current Node + currNode->right = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + // } Driver Code Ends +//User function Template for C++ + +/* +struct Node +{ + int data; + struct Node* left; + struct Node* right; + + Node(int x){ + data = x; + left = right = NULL; + } +}; +*/ +class Solution{ +public: + void solve(Node *par,Node *root,unordered_map &mp,int &cnt){ + if(root == nullptr){ + return; + } + mp[root] = 0;//unlike adjlist we cannot mark all nodes as unvisited atfirst, we need separate traversal for that + solve(root,root->left,mp,cnt); + solve(root,root->right,mp,cnt); + if((root->left && mp[root->left]==0) || (root->right && mp[root->right]==0)){ + mp[root] = 1; + if(root->left){ + mp[root->left] = 1; + } + if(root->right){ + mp[root->right] = 1; + } + mp[par] = 1; + //inc the cnt; + cnt += 1; + } + else{ + return; + } + } + int supplyVaccine(Node* root){ + // Your code goes here + unordered_map mp; + int cnt = 0; + solve(root,root,mp,cnt); + //lastly check for root, bcoz there is not parent for root to check root as any decendent + if(mp[root] == 0){ + cnt += 1; + mp[root] = 1; + } + return cnt; + } +}; + +// { Driver Code Starts. +int main() +{ + int t; + scanf("%d ", &t); + while (t--) { + string treeString; + getline(cin, treeString); + Node *root = buildTree(treeString); + Solution ob; + cout< +

Given an array A[] of size N. Find the number of pairs (i, j) such that
+AXOR Aj = 0, and 1 ≤ i < j ≤ N.

+ +

Example 1:

+ +
​Input : arr[ ] = {1, 3, 4, 1, 4}
+Output : 2
+Explanation:
+Index( 0, 3 ) and (2 , 4 ) are only pairs 
+whose xors is zero so count is 2.
+
+ +


+​Example 2:

+ +
Input : arr[ ] = {2, 2, 2} 
+Output :  3
+
+
+ +

 

+ +

Your Task:
+This is a function problem. The input is already taken care of by the driver code. You only need to complete the function calculate() that takes an array (arr), sizeOfArray (n), and return the count of Zeros Xor's Pairs. The driver code takes care of the printing.

+ +

Expected Time Complexity: O(N*Log(N)).
+Expected Auxiliary Space: O(1).

+ +


+
+Output:
+For each test case, output a single integer i.e counts of Zeros Xors Pairs

+ +

Constraints
+2 ≤ N ≤ 10^5
+1 ≤ A[i] ≤ 10^5

+ +

 

+

+ \ No newline at end of file diff --git a/Counts Zeros Xor Pairs - GFG/counts-zeros-xor-pairs.cpp b/Counts Zeros Xor Pairs - GFG/counts-zeros-xor-pairs.cpp new file mode 100644 index 0000000..777681d --- /dev/null +++ b/Counts Zeros Xor Pairs - GFG/counts-zeros-xor-pairs.cpp @@ -0,0 +1,48 @@ +// { Driver Code Starts +// C++ program to find number +// of pairs in an array such +// that their XOR is 0 +#include +using namespace std; + +// Function to calculate the +// count +long long int calculate(int a[], int n); + +// Driver Code +int main() +{ + + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + int arr[n+1]; + for( int i=0;i>arr[i]; + cout << calculate(arr, n)<mp; + for(int i=0;i +

Given a binary tree and a node, print all cousins of given node in order of their appearance. Note that siblings should not be printed.

+ +

Example 1:

+ +
Input : 
+             1
+           /   \
+          2     3
+        /   \  /  \
+       4    5  6   7
+
+Given node : 5
+Output : 6 7
+Explanation :
+Nodes 6 and 7 are on the same level 
+as 5 and have different parents.
+
+
+ +

Example 2 :

+ +
Input :
+         9
+        /
+       5
+Given node : 5
+Output : -1
+Explanation :
+There no other nodes than 5 in the same level.
+
+ +
Your task :
+ +
You don't have to read input or print anything. Your task is to complete the function printCousins() which takes the root node of the tree and the node whose cousins need to be found, as input and returns a list containing the cousins of the given node in order of their appearance in the tree. If there is no cousin of the given node, return -1 as the first element of the list.
+ +
 
+ +
Expected Time Complexity : O(n)
+ +
Expected Auxiliary Space : O(n)
+ +
 
+ +
Constraints :
+ +
1 <= n <=10^5
+

+ \ No newline at end of file diff --git a/Cousins of a given node - GFG/cousins-of-a-given-node.cpp b/Cousins of a given node - GFG/cousins-of-a-given-node.cpp new file mode 100644 index 0000000..4eca120 --- /dev/null +++ b/Cousins of a given node - GFG/cousins-of-a-given-node.cpp @@ -0,0 +1,217 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + +// A Binary Tree Node +struct Node +{ + int data; + Node* left; + Node* right; +}; + +// Utility function to create a new Tree Node +Node* newNode(int val) +{ + Node* temp = new Node; + temp->data = val; + temp->left = NULL; + temp->right = NULL; + + return temp; +} + +// Function to Build Tree +Node* buildTree(string str) +{ + // Corner Case + if (str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for (string str; iss >> str; ) + ip.push_back(str); + + // Create the root of the tree + Node* root = newNode(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while (!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if (currVal != "N") { + + // Create the left child for the current node + currNode->left = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if (i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if (currVal != "N") { + + // Create the right child for the current node + currNode->right = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + +Node* pointer(Node* root, int n) +{ + if (root == NULL) + return NULL; + + if (root->data == n) + return root; + + Node* l = pointer(root->left, n); + if (l != NULL && l->data == n) + return l; + + Node* r = pointer(root->right, n); + return r; + +} + + + // } Driver Code Ends +//User function Template for C++ + +/* +// A Binary Tree Node +struct Node +{ + int data; + Node* left; + Node* right; +};*/ + +class Solution +{ + private: + int finddepth(Node * data,Node *root ,int depth=1) + { + if(root==NULL) + { + return 0; + } + if(root==data) + { + return depth; + } + else + { + int height1=finddepth(data,root->right,depth+1); + int height2=finddepth(data,root->left,depth+1); + return max(height1,height2); + + } + + } + + private: + void printhelper(int depth,vector & ans,Node * root, Node * data) + { + if(root==NULL) + { + return; + } + if((root->left==data || root->right==data) and depth-1==1) + { + return; + } + if(depth==1 and root!=data) + { + ans.push_back(root->data); + } + else + { + printhelper(depth-1,ans,root->left,data); + printhelper(depth-1,ans,root->right,data); + } + return; + } + + public: + vector printCousins(Node* root, Node* node_to_find) + { + //code here + vector ans; + int depth=finddepth(node_to_find,root); + //cout<<"depth:"<> t; + getchar(); + while (t--) + { + int n; + cin >> n; + getchar(); + + string inp; + getline(cin, inp); + + struct Node* root = buildTree(inp); + + Node* p = pointer(root, n); + + Solution ob; + vector ans = ob.printCousins(root, p); + + for (int i = 0; i < ans.size(); i++) + cout << ans[i] << " "; + + cout << "\n"; + + + } + + return 0; +} + + // } Driver Code Ends \ No newline at end of file diff --git a/Cyclically rotate an array by one - GFG/README.md b/Cyclically rotate an array by one - GFG/README.md new file mode 100644 index 0000000..ba1b74b --- /dev/null +++ b/Cyclically rotate an array by one - GFG/README.md @@ -0,0 +1,41 @@ +# Cyclically rotate an array by one +## Easy +
+

Given an array, rotate the array by one position in clock-wise direction.

+ +

Example 1:

+ +
Input:
+N = 5
+A[] = {1, 2, 3, 4, 5}
+Output:
+5 1 2 3 4
+ +

 

+ +

Example 2:

+ +
Input:
+N = 8
+A[] = {9, 8, 7, 6, 4, 2, 1, 3}
+Output:
+3 9 8 7 6 4 2 1
+ +

 

+ +

Your Task:  
+You don't need to read input or print anything. Your task is to complete the function rotate() which takes the array A[] and its size N as inputs and modify the array.

+ +

 

+ +

Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(1)

+ +

 

+ +

Constraints:
+1<=N<=105
+0<=a[i]<=105

+

+
\ No newline at end of file diff --git a/Cyclically rotate an array by one - GFG/cyclically-rotate-an-array-by-one.cpp b/Cyclically rotate an array by one - GFG/cyclically-rotate-an-array-by-one.cpp new file mode 100644 index 0000000..1b011ba --- /dev/null +++ b/Cyclically rotate an array by one - GFG/cyclically-rotate-an-array-by-one.cpp @@ -0,0 +1,39 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; +void rotate(int arr[], int n); + +int main() +{ + int t; + scanf("%d",&t); + while(t--) + { + int n; + scanf("%d",&n); + int a[n] , i; + for(i=0;i=1;i--) + arr[i] = arr[i-1]; + + arr[0] = temp; + +} \ No newline at end of file diff --git a/Escape the Forbidden Forest - GFG/README.md b/Escape the Forbidden Forest - GFG/README.md new file mode 100644 index 0000000..6b086f9 --- /dev/null +++ b/Escape the Forbidden Forest - GFG/README.md @@ -0,0 +1,42 @@ +# Escape the Forbidden Forest +## Medium +
+

Penelope and her classmates are lost in the Forbidden Forest and the Devil is out to get them. But Penelope has magical powers that can build bridges across the dangerous river and take her friends to safety. The only bridges that can withstand the Devil's wrath are the ones built between two similar trees in the forest. 
+Given str1 and str2 denoting the order of trees on either side of the river, find the maximum number of bridges that Penelope can build and save everyone from the Devil. 

+Note: Each tree in the forest belongs to one of the 3 categories represented by * or # or @

+ +

Example 1:

+ +
Input:
+str1 = "*@#*" 
+str2 = "*#"
+Output:
+2
+Explanation:
+str1 = "*@#*" and str2 = "*#" 
+Two bridges can be built between the banks 
+of the river in the following manner. 
+* @ # *
+|      |
+*     #
+ +

Example 2:

+ +
Input:
+str1 = "***"
+str2 = "##"
+Output:
+0
+
+ +

Your Task:
+You don't need to read input or print anything. Complete the function build_bridges() that takes str1 and str2 as input parameters and returns the maximum number of bridges that can be built. 

+ +

Expected Time Complexity: O(N*M)
+Expected Auxiliary Space: O(N*M)

+ +

Constraints:
+1 ≤ N, M ≤ 100
+Where, N and M are the size of the string str1 and str2 respectively.

+

+
\ No newline at end of file diff --git a/Escape the Forbidden Forest - GFG/escape-the-forbidden-forest.cpp b/Escape the Forbidden Forest - GFG/escape-the-forbidden-forest.cpp new file mode 100644 index 0000000..9e8fcb1 --- /dev/null +++ b/Escape the Forbidden Forest - GFG/escape-the-forbidden-forest.cpp @@ -0,0 +1,53 @@ +// { Driver Code Starts +#include +using namespace std; + + + // } Driver Code Ends +class Solution +{ + public: + int build_bridges(string str1, string str2) + { + int dp[101][101]; + int x = str1.length(), y = str2.length(); + + for(int i=0; i<=x; i++) + { + for(int j=0; j<=y; j++) + { + if(i == 0 || j == 0) + dp[i][j] = 0; + + else if(str1[i-1] == str2[j-1]) + dp[i][j] = 1 + dp[i-1][j-1]; + + else + dp[i][j] = max(dp[i-1][j], dp[i][j-1]); + } + } + + return dp[x][y]; + } +}; + +// { Driver Code Starts. +int main() +{ + ios_base::sync_with_stdio(0); + cin.tie(NULL); + cout.tie(NULL); + + int t; + cin >> t; + + while(t--) + { + string str1,str2; + cin >> str1 >> str2; + Solution obj; + cout< +

Given an array arr[] of size N containing equal number of odd and even numbers. Arrange the numbers in such a way that all the even numbers get the even index and odd numbers get the odd index.
+Note: There are multiple possible solutions, Print any one of them. Also, 0-based indexing is considered.

+ +

 

+ +

Example 1:

+ +
Input:
+N = 6
+arr[] = {3, 6, 12, 1, 5, 8}
+Output:
+1
+Explanation:
+6 3 12 1 8 5 is a possible solution.
+The output will always be 1 if your
+rearrangement is correct.
+
+ +
Example 2:
+ +
Input:
+N = 4
+arr[] = {1, 2, 3, 4}
+Output :
+1
+
+ +


+Your Task:  
+You don't need to read input or print anything. Your task is to complete the function reArrange() which takes an integer N and an array arr of size N as input and reArranges the array in Place without any extra space.

+ +


+Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(1)

+ +


+Constraints:
+1 ≤ N ≤ 105
+1 ≤ arr[i] ≤ 105

+

+ \ No newline at end of file diff --git a/Even and Odd - GFG/even-and-odd.cpp b/Even and Odd - GFG/even-and-odd.cpp new file mode 100644 index 0000000..f7d27e2 --- /dev/null +++ b/Even and Odd - GFG/even-and-odd.cpp @@ -0,0 +1,75 @@ +// { Driver Code Starts +#include +using namespace std; + + + // } Driver Code Ends +//User function Template for C++ + +class Solution { + public: + +void reArrange(int arr[], int N){ + int i=0, j=1; + while(i> t; + while (t--) { + int N; + cin>>N; + + int arr[N]; + for(int i=0; i>arr[i]; + + Solution ob; + ob.reArrange(arr,N); + + cout< +

Given a positive integer N, return its corresponding column title as it would appear in an Excel sheet.
+For N =1 we have column A, for 27 we have AA and so on.

+ +

Note: The alphabets are all in uppercase.

+ +

Example 1:

+ +
Input:
+N = 51
+Output: AY
+
+ +

Your Task:
+Complete the function ExcelColumn() which takes N as input and returns output string.

+ +

Expected Time Complexity: O(Log(N))
+Expected Auxiliary Space: O(Log(N))

+ +

Constraints:
+1 ≤ N ≤ 107

+

+ \ No newline at end of file diff --git a/Excel Sheet _ Part - 1 - GFG/excel-sheet-part-1.cpp b/Excel Sheet _ Part - 1 - GFG/excel-sheet-part-1.cpp new file mode 100644 index 0000000..c41cacb --- /dev/null +++ b/Excel Sheet _ Part - 1 - GFG/excel-sheet-part-1.cpp @@ -0,0 +1,50 @@ +// { Driver Code Starts +//Initial template for C++ + + +#include +using namespace std; + + // } Driver Code Ends +//User function template for C++ + +class Solution{ + public: + string ExcelColumn(int N) + { + // Your code goes here + string ans = ""; + while(N != 0) + { + int h = (N%26); + if(h == 0) + { + h = 26; + } + h--; + ans += 'A' + h; + N = N/26; + if(N == 1 && h == 25) break; + if(h == 25) N--; + } + reverse(ans.begin(), ans.end()); + return ans; + } + +}; + +// { Driver Code Starts. +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + Solution ob; + cout< +

Given an unsorted array Arr of size N of positive integers. One number 'A' from set {1, 2, …N} is missing and one number 'B' occurs twice in array. Find these two numbers.

+ +

Example 1:

+ +
Input:
+N = 2
+Arr[] = {2, 2}
+Output: 2 1
+Explanation: Repeating number is 2 and 
+smallest positive missing number is 1.
+
+ +

Example 2:

+ +
Input:
+N = 3
+Arr[] = {1, 3, 3}
+Output: 3 2
+Explanation: Repeating number is 3 and 
+smallest positive missing number is 2.
+
+ +

Your Task:
+You don't need to read input or print anything. Your task is to complete the function findTwoElement() which takes the array of integers arr and as parameters and returns an array of integers of size 2 denoting the answer ( The first index contains and second index contains A.)

+ +

Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(1)

+ +

Constraints:
+1 ≤ N ≤ 105
+1 ≤ Arr[i] ≤ N

+

+ \ No newline at end of file diff --git a/Find Missing And Repeating - GFG/find-missing-and-repeating.cpp b/Find Missing And Repeating - GFG/find-missing-and-repeating.cpp new file mode 100644 index 0000000..3253253 --- /dev/null +++ b/Find Missing And Repeating - GFG/find-missing-and-repeating.cpp @@ -0,0 +1,56 @@ +// { Driver Code Starts +#include + +using namespace std; + + // } Driver Code Ends +class Solution{ +public: + //Using swap sort in O(n) + +int *findTwoElement(int *arr, int n) { + + int *arr1 = new int[2]; + + //unsorted arr 2 3 1 1 5 + int i=0; + while(i> t; + while (t--) { + int n; + cin >> n; + int a[n]; + for (int i = 0; i < n; i++) { + cin >> a[i]; + } + Solution ob; + auto ans = ob.findTwoElement(a, n); + cout << ans[0] << " " << ans[1] << "\n"; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Find Nth root of M - GFG/README.md b/Find Nth root of M - GFG/README.md new file mode 100644 index 0000000..7e689fb --- /dev/null +++ b/Find Nth root of M - GFG/README.md @@ -0,0 +1,36 @@ +# Find Nth root of M +## Easy +
+

You are given 2 numbers (n , m); the task is to find n√m (nth root of m).

+ +

Example 1:

+ +
Input: n = 2, m = 9
+Output: 3
+Explanation: 32 = 9
+
+ +

Example 2:

+ +
Input: n = 3, m = 9
+Output: -1
+Explanation: 3rd root of 9 is not
+integer.
+
+ +

 

+ +

Your Task:
+You don't need to read or print anyhting. Your task is to complete the function NthRoot() which takes n and m as input parameter and returns the nth root of m. If the root is not integer then returns -1.

+ +

Expected Time Complexity: O(n* log(m))
+Expected Space Complexity: O(1)

+ +

Constraints:
+1 <= n <= 30

+1 <= m <= 109

+

+
\ No newline at end of file diff --git a/Find Nth root of M - GFG/find-nth-root-of-m.cpp b/Find Nth root of M - GFG/find-nth-root-of-m.cpp new file mode 100644 index 0000000..c4cb07a --- /dev/null +++ b/Find Nth root of M - GFG/find-nth-root-of-m.cpp @@ -0,0 +1,40 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution{ + public: + int NthRoot(int n, int m) + { + int low = 1; + int high = m; + while(low<=high) + { + int mid = low + (high-low)/2; + + + if(pow(mid,n) == m ) + return mid; + else if(pow(mid,n) > m) + high = mid-1; + else + low = mid+1; + } + return -1; + } +}; + +// { Driver Code Starts. +int main(){ + int tc; + cin >> tc; + while(tc--){ + int n, m; + cin >> n >> m; + Solution ob; + int ans = ob.NthRoot(n, m); + cout << ans << "\n"; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Find Prime numbers in a range - GFG/README.md b/Find Prime numbers in a range - GFG/README.md new file mode 100644 index 0000000..41b3e94 --- /dev/null +++ b/Find Prime numbers in a range - GFG/README.md @@ -0,0 +1,38 @@ +# Find Prime numbers in a range +## Medium +
+

Given two integers M and N, generate all primes between M and N.

+ +

Example 1:

+ +
Input:
+M=1,N=10
+Output:
+2 3 5 7
+Explanation:
+The prime numbers between 1 and 10
+are 2,3,5 and 7.
+ +

Example 2:

+ +
Input:
+M=2, N=5
+Output:
+2,3,5
+Explanation:
+The prime numbers between 2 and 5 are 
+2,3 and 5.
+ +


+Your Task:
+You don't need to read input or print anything. Your task is to complete the function primeRange() which takes 2 integer inputs M and N and returns a list of all primes between M and N.

+ +


+Expected Time Complexity:O(N*sqrt(N))
+Expected Auxillary Space:O(1)

+ +


+Constraints:
+1<=M<=N<=106

+

+
\ No newline at end of file diff --git a/Find Prime numbers in a range - GFG/find-prime-numbers-in-a-range.cpp b/Find Prime numbers in a range - GFG/find-prime-numbers-in-a-range.cpp new file mode 100644 index 0000000..449dac7 --- /dev/null +++ b/Find Prime numbers in a range - GFG/find-prime-numbers-in-a-range.cpp @@ -0,0 +1,49 @@ +// { Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + + // } Driver Code Ends +// User function Template for C++ + +class Solution { + public: + bool isPrime(int n){ + if(n==1){ + return false; + } + for(int i=2;i<=sqrt(n);i++){ + if(n%i==0){ + return false; + } + } + return true; + } + + vector primeRange(int M, int N) { + // code here + vector v; + for(int i=M;i<=N;i++){ + if(isPrime(i)){ + v.push_back(i); + } + } + return v; + } +}; + +// { Driver Code Starts. + +int main() { + int t; + cin >> t; + while (t--) { + int N, M, K; + cin >> M >> N; + Solution ob; + vector ans = ob.primeRange(M, N); + for (auto u : ans) cout << u << " "; + cout << "\n"; + } +} // } Driver Code Ends \ No newline at end of file diff --git a/Find position of set bit - GFG/README.md b/Find position of set bit - GFG/README.md new file mode 100644 index 0000000..7ae3bc1 --- /dev/null +++ b/Find position of set bit - GFG/README.md @@ -0,0 +1,39 @@ +# Find position of set bit +## Easy +
+

Given a number N having only one ‘1’ and all other ’0’s in its binary representation, find position of the only set bit. If there are 0 or more than 1 set bit the answer should be -1. Position of  set bit '1' should be counted starting with 1 from LSB side in binary representation of the number.

+ +

Example 1:

+ +
Input:
+N = 2
+Output:
+2
+Explanation:
+2 is represented as "10" in Binary.
+As we see there's only one set bit
+and it's in Position 2 and thus the
+Output 2.
+ +

Example 2:

+ +
Input:
+N = 5
+Output:
+-1
+Explanation:
+5 is represented as "101" in Binary.
+As we see there's two set bits
+and thus the Output -1.
+
+ +

Your Task:
+You don't need to read input or print anything. Your task is to complete the function findPosition() which takes an integer N as input and returns the answer.

+ +

Expected Time Complexity: O(log(N))
+Expected Auxiliary Space: O(1)

+ +

Constraints:
+0 <= N <= 108

+

+
\ No newline at end of file diff --git a/Find position of set bit - GFG/find-position-of-set-bit.cpp b/Find position of set bit - GFG/find-position-of-set-bit.cpp new file mode 100644 index 0000000..caf60fc --- /dev/null +++ b/Find position of set bit - GFG/find-position-of-set-bit.cpp @@ -0,0 +1,38 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution { + public: + int findPosition(int N) { + if (N == 0) return -1; + if (N == 1 || N == 2) return N; + // if N is odd and > 1, it will have more than 1 set bits; + if (N & 1) return -1; + + int setBitPos = 2; + while (N > 2) { + setBitPos++; + N = N / 2; + if (!N & 1) continue; + if (N & 1) return -1; + } + return setBitPos; +} +}; + +// { Driver Code Starts. +int main() { + int t; + cin >> t; + while (t--) { + int N; + + cin>>N; + + Solution ob; + cout << ob.findPosition(N) << endl; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Find rectangle with corners as 1 - GFG/README.md b/Find rectangle with corners as 1 - GFG/README.md new file mode 100644 index 0000000..48d74a2 --- /dev/null +++ b/Find rectangle with corners as 1 - GFG/README.md @@ -0,0 +1,39 @@ +# Find rectangle with corners as 1 +## Medium +
+

Given a NxM binary matrix consisting of 0s and 1s. Find if there exists a rectangle/ square within the matrix whose all four corners are 1. 

+ +

Example 1:

+ +
Input:
+N = 4, M = 5
+matrix[][] = 
+{
+{1 0 0 1 0},
+{0 0 1 0 1},
+{0 0 0 1 0}, 
+{1 0 1 0 1}
+} 
+
+Output: Yes
+Explanation:
+Valid corners are at index (1,2), (1,4), (3,2), (3,4) 
+ +

Example 2:

+ +
Input:
+N = 3, M = 3
+matrix[][] = 
+{{0 0 0},
+{0 0 0},
+{0 0 0}}
+Output: No
+ +

Your Task:
+You don't need to take input or print anything. Complete the function ValidCorners() that takes the given matrix as input parameter and returns a boolean value.

+ +

Constraints:
+1 <= R, C <= 200
+0 <= A[i] <= 1

+

+
\ No newline at end of file diff --git a/Find rectangle with corners as 1 - GFG/find-rectangle-with-corners-as-1.cpp b/Find rectangle with corners as 1 - GFG/find-rectangle-with-corners-as-1.cpp new file mode 100644 index 0000000..df244e0 --- /dev/null +++ b/Find rectangle with corners as 1 - GFG/find-rectangle-with-corners-as-1.cpp @@ -0,0 +1,69 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +#include +#include +using namespace std; + + // } Driver Code Ends +//User function Template for C++ + +class Solution{ + public: + bool ValidCorner(const vector >& matrix) + { + // Your code goes here + int m = matrix.size(); + int n = matrix[0].size(); + unordered_map> temp; + + for(int i=0;i {col,(col+)} pair + } + } + } + } + return false; + } +}; + +// { Driver Code Starts. +int main() +{ + int t; + cin>>t; + while(t--) + { + int row, col; + cin>> row>> col; + + vector > matrix(row); + + for(int i=0; i>matrix[i][j]; + } + } + Solution ob; + if (ob.ValidCorner(matrix)) + cout << "Yes\n"; + else + cout << "No\n"; + } + + return 0; +} + + + // } Driver Code Ends \ No newline at end of file diff --git a/Find the Closest Element in BST - GFG/README.md b/Find the Closest Element in BST - GFG/README.md new file mode 100644 index 0000000..8a987d1 --- /dev/null +++ b/Find the Closest Element in BST - GFG/README.md @@ -0,0 +1,50 @@ +# Find the Closest Element in BST +## Medium +
+

Given a BST and an integer. Find the least absolute difference between any node value of the BST and the given integer.

+ +

Example 1:

+ +
Input:
+        10
+      /   \
+     2    11
+   /  \ 
+  1    5
+      /  \
+     3    6
+      \
+       4
+K = 13
+Output: 2
+Explanation: K=13. The node that has
+value nearest to K is 11. so the answer
+is 2
+
+ +

Example 2:

+ +
Input:
+      8
+    /   \
+   1     9
+    \     \
+     4    10
+    /
+   3
+K = 9
+Output: 0
+Explanation: K=9. The node that has
+value nearest to K is 9. so the answer
+is 0.
+ +

Your Task:
+You don't need to read input or print anything. Your task is to complete the function
minDiff() that takes the root of the BST and an integer K as its input and returns the minimum absolute difference between any node value of the BST and the integer K.

+ +

Expected Time Complexity: O(Height of the BST).
+Expected Auxiliary Space: O(Height of the BST).

+ +

Constraints:
+1 <= Number of nodes <= 100000

+

+
\ No newline at end of file diff --git a/Find the Closest Element in BST - GFG/find-the-closest-element-in-bst.cpp b/Find the Closest Element in BST - GFG/find-the-closest-element-in-bst.cpp new file mode 100644 index 0000000..09f3bd5 --- /dev/null +++ b/Find the Closest Element in BST - GFG/find-the-closest-element-in-bst.cpp @@ -0,0 +1,135 @@ +// { Driver Code Starts +#include +using namespace std; +#define MAX_HEIGHT 100000 + +// Tree Node +struct Node { + int data; + Node *left; + Node *right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; + + + + // } Driver Code Ends + + +class Solution +{ + public: + //Function to find the least absolute difference between any node + //value of the BST and the given integer. + int minDiff(Node *root, int K) + { + if(root){ + int d = abs(root->data - K); + if(K > root->data) + return min(d, minDiff(root->right, K)); + else if(K < root->data) + return min(d, minDiff(root->left, K)); + else + return 0; + }else + return INT_MAX; + } +}; + + +// { Driver Code Starts. + +// Function to Build Tree +Node* buildTree(string str) +{ + // Corner Case + if(str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for(string str; iss >> str; ) + ip.push_back(str); + + // Create the root of the tree + Node* root = new Node(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while(!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if(currVal != "N") { + + // Create the left child for the current node + currNode->left = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if(i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if(currVal != "N") { + + // Create the right child for the current node + currNode->right = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + + +int main() { + + int t; + string tc; + getline(cin, tc); + t=stoi(tc); + while(t--) + { + string s; + getline(cin, s); + Node* root1 = buildTree(s); + + getline(cin, s); + int k = stoi(s); + // getline(cin, s); + + Solution ob; + cout << ob.minDiff(root1, k); + cout << endl; + //cout<<"~"< +

Given a graph with N vertices numbered 1 to N and M edges, The task is to find the max flow from vertex 1 to vertex N.

+ +

In a flow network, the maximum flow of a path can't exceed the flow-capacity of an edge in the path.
+
+Example 1:

+ +
Input:
+N = 5, M =  4
+Edges[]= { {1, 2, 1} , {3, 2, 2}, {4, 2, 3}, {2, 5, 5} }
+Output:
+1 
+Explanation: 
+1 - 2 - 3
+   / \
+  4   5 
+1 unit can flow from 1 -> 2 - >5 
+
+ +

 

+ +

Example 2:

+ +
Input:
+N = 4 , M = 4
+Edges[] = { {1, 2, 8}, {1, 3, 10}, {4, 2, 2}, {3, 4, 3} }
+Output:
+5 
+Explanation:
+  1 - 2 
+  |   |
+  3 - 4
+3 unit can flow from 1 -> 3 -> 4
+2 unit can flow from 1 -> 2 -> 4
+Total max flow from 1 to N = 3+2=5
+ +

Your Task: 
+You don't need to read input or print anything. Your task is to complete the function solve() which takes the (the number of vertices) ,M (the number of Edges) and the array Edges[] (Where Edges[i] denoting an undirected edge between Edges[i][0] and Edges[i][1] with a flow capacity of Edges[i][2] ), and returns the integer denoting the maximum flow from 1 to N.

+ +

Expected Time Complexity: O( max_flow* M)
+Expected Auxiliary Space: O(N+M)

+ +

Where max_flow is the maximum flow from 1 to N

+ +

Constraints:
+1 <= N,M,Edges[i][2] <= 1000

+1 <= Edges[i][0],Edges[i][1] <= N

+

+ \ No newline at end of file diff --git a/Find the Maximum Flow - GFG/find-the-maximum-flow.cpp b/Find the Maximum Flow - GFG/find-the-maximum-flow.cpp new file mode 100644 index 0000000..301183d --- /dev/null +++ b/Find the Maximum Flow - GFG/find-the-maximum-flow.cpp @@ -0,0 +1,126 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution +{ +public: + int BFS(vector> &graph,vector &parent,int source,int sink,int N) + { + int min_cap=INT_MAX; + fill(parent.begin(), parent.end(), -1); + vector visited(N,false); + queue q; + + q.push(source); + visited[source]=true; + parent[source]=-1; + + while(q.empty()==false) + { + auto u=q.front(); + q.pop(); + + //adjacents + + for(int v=0;v> &graph,int source,int sink,int N) + { + vector parent(N,-1); + + int res=0; + + while(BFS(graph,parent,source,sink,N)!=0) + { + int min_cap=BFS(graph,parent,source,sink,N); + + res+=min_cap; + + //considering all the edged in this path. + + int v=sink; + while(v!=source) + { + int u=parent[v]; + graph[u][v]-=min_cap; + graph[v][u]+=min_cap; + v=parent[v]; + } + } + + return res; + } + + int solve(int N,int M,vector> Edges) + { + // code here + vector> graph; + + for(int i=0;i v1; + for(int j=0;j>t; + while(t--){ + int i,j,N,M,u,v,w; + int res; + scanf("%d %d",&N,&M); + vector> Edges; + for(i=0;i +

Given a grid of size n*m (n is number of rows and m is number of columns grid has) consisting of '0's(Water) and '1's(Land). Find the number of islands.
+Note: An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically or diagonally i.e., in all 8 directions.

+ +

Example 1:

+ +
Input:
+grid = {{0,1},{1,0},{1,1},{1,0}}
+Output:
+1
+Explanation:
+The grid is-
+0 1
+1 0
+1 1
+1 0
+All lands are connected.
+
+ +

Example 2:

+ +
Input:
+grid = {{0,1,1,1,0,0,0},{0,0,1,1,0,1,0}}
+Output:
+2
+Expanation:
+The grid is-
+0 1 1 1 0 0 0
+0 0 1 1 0 1 0 
+There are two islands one is colored in blue 
+and other in orange.
+
+ +

 

+ +

Your Task:
+You don't need to read or print anything. Your task is to complete the function numIslands() which takes grid as input parameter and returns the total number of islands.

+ +

Expected Time Compelxity: O(n*m)
+Expected Space Compelxity: O(n*m)

+ +

Constraints:
+1 ≤ n, m ≤ 500

+

+ \ No newline at end of file diff --git a/Find the number of islands - GFG/find-the-number-of-islands.cpp b/Find the number of islands - GFG/find-the-number-of-islands.cpp new file mode 100644 index 0000000..3eb234e --- /dev/null +++ b/Find the number of islands - GFG/find-the-number-of-islands.cpp @@ -0,0 +1,57 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution { + public: + // Function to find the number of islands. + int numIslands(vector>& grid) { + + int n = grid.size(); + int m = grid[0].size(); + + function dfs = [&] (int x, int y) { + if(x < 0 || x >= n || y < 0 || y >= m || grid[x][y] != '1') return; + // Mark current cell as visited. + grid[x][y] = '#'; + + // Traverse all 8 neighbors. + for(int i = -1; i <= 1; i++) for(int j = -1; j <= 1; j++) { + int nx = x + i; + int ny = y + j; + if(x == nx && y == ny) continue; // Why should I call myself ;) + dfs(nx, ny); + } + }; + + int ans = 0; + + for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) if(grid[i][j] == '1') { + ++ans; + dfs(i, j); + } + + return ans; + } +}; + +// { Driver Code Starts. +int main() { + int tc; + cin >> tc; + while (tc--) { + int n, m; + cin >> n >> m; + vector> grid(n, vector(m, '#')); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + cin >> grid[i][j]; + } + } + Solution obj; + int ans = obj.numIslands(grid); + cout << ans << '\n'; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Form a palindrome - GFG/README.md b/Form a palindrome - GFG/README.md new file mode 100644 index 0000000..2331b4e --- /dev/null +++ b/Form a palindrome - GFG/README.md @@ -0,0 +1,40 @@ +# Form a palindrome +## Medium +
+

Given a string, find the minimum number of characters to be inserted to convert it to palindrome.
+For Example:
+ab: Number of insertions required is 1. bab or aba
+aa: Number of insertions required is 0. aa
+abcd: Number of insertions required is 3. dcbabcd

+ +

Example 1:

+ +
Input:
+abcd
+Output:
+3
+Explanation:
+Here we can append 3 characters in the 
+beginning,and the resultant string will 
+be a palindrome ("dcbabcd").
+ +

Example 2:

+ +
Input:
+aba
+Output:
+0
+Explanation:
+Given string is already a pallindrome hence
+no insertions are required.
+ +

Your Task:  
+You don't need to read input or print anything. Your task is to complete the function findMinInsertions() which takes string S as input parameters and returns minimimum numser of insertions required.

+ +

Expected Time Complexity: O(|S|2)
+Expected Auxiliary Space: O(|S|2)

+ +

Constraints:
+1 ≤ |S| ≤ 500

+

+
\ No newline at end of file diff --git a/Form a palindrome - GFG/form-a-palindrome.cpp b/Form a palindrome - GFG/form-a-palindrome.cpp new file mode 100644 index 0000000..f06325d --- /dev/null +++ b/Form a palindrome - GFG/form-a-palindrome.cpp @@ -0,0 +1,50 @@ +// { Driver Code Starts +//Initial template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function template for C++ + + + +class Solution{ +public: + int findMinInsertions(string s){ + int n=s.length(); + string p=s; + reverse(s.begin(),s.end()); + int dp[n+1][n+1]; + for(int i=0;i<=n;i++) + { + for(int j=0;j<=n;j++) + { + if(i==0||j==0) + dp[i][j]=0; + else if(s[i-1]==p[j-1]) + dp[i][j]=1+dp[i-1][j-1]; + else + dp[i][j]=max(dp[i-1][j],dp[i][j-1]); + } + } + return n-dp[n][n]; + } +}; + +// { Driver Code Starts. + + + +int main(){ + int t; + cin>>t; + while(t--){ + string S; + cin>>S; + Solution ob; + cout< +

Consider the set of irreducible fractions A = {n/d | n≤d and d ≤ 10000 and gcd(n,d) = 1}.You are given a member of this set and your task is to find the largest fraction in this set less than the given fraction.
+Note : this is a set and all the members are unique.

+
+Example 1:

+ +
Input: n = 1, d = 4
+Output: {2499, 9997}  
+Explanation: 2499/9997 is the largest fraction.
+
+ +


+Example 2:

+ +
Input: n = 2, d = 4
+Output: {4999, 9999}
+Explanation: 4999/9999 is the largest fraction. 
+
+ +


+Your Task:  
+You dont need to read input or print anything. Complete the function numAndDen() which takes n and d as input parameter and returns the numerator and the denominator of the required irreducible fraction.
+
+Expected Time Complexity: O(n)
+Expected Auxiliary Space: O(1)
+
+Constraints:
+1 <= n <= d <=1000

+

+ \ No newline at end of file diff --git a/Fraction Trouble - GFG/fraction-trouble.cpp b/Fraction Trouble - GFG/fraction-trouble.cpp new file mode 100644 index 0000000..849f04e --- /dev/null +++ b/Fraction Trouble - GFG/fraction-trouble.cpp @@ -0,0 +1,38 @@ +// { Driver Code Starts +// Initial Template for C++ +#include +using namespace std; + + // } Driver Code Ends +// User function Template for C++ +class Solution { + public: + vector numAndDen(int n, int d) { + // code here + int numerator =-1, denominator =1; + for(int y=d+1; y<=10000; y++) { + int x = (n*y)/d; + if(__gcd(x,y) == 1) { + if(1.0*x/y > 1.0*numerator /denominator ) + numerator =x, denominator =y; + } + } + return {numerator , denominator }; + } +}; + +// { Driver Code Starts. +int main() { + int t; + cin >> t; + while (t--) { + int n,d; + cin >> n >> d; + Solution ob; + vectorans=ob.numAndDen(n,d); + for(int i=0;i +

In Doraland, people have unique Identity Numbers called D-id. Doraemon owns the most popular gadget shop in Doraland. Since his gadgets are in high demand and he has only K gadgets left he has decided to sell his gadgets to his most frequent customers only. N customers visit his shop and D-id of each customer is given in an array array[ ]. In case two or more people have visited his shop the same number of time he gives priority to the customer with higher D-id. Find the D-ids of people he sells his K gadgets to.

+ +

Example 1:

+ +
Input:
+N = 6
+array[] = {1, 1, 1, 2, 2, 3}
+K = 2
+Output: 
+1 2
+Explanation: 
+Customers with D-id 1 and 2 are most 
+frequent.
+
+ +

Example 2:

+ +
Input:
+N = 8
+array[] = {1, 1, 2, 2, 3, 3, 3, 4}
+K = 2
+Output: 
+3 2
+Explanation: People with D-id 1 and 2 have 
+visited shop 2 times Therefore, in this 
+case, the answer includes the D-id 2 as 2 > 1.
+ +

Your Task:
+You don't need to read input or print anything. Complete the function TopK() which takes array[ ] and integer K as input parameters and returns an array containing D-id of customers he has decided to sell his gadgets to.

+ +

Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(N)

+ +

Constraints:
+1 ≤ N ≤ 105
+1 ≤ D-id ≤ 104

+

+ \ No newline at end of file diff --git a/Gadgets of Doraland - GFG/gadgets-of-doraland.py b/Gadgets of Doraland - GFG/gadgets-of-doraland.py new file mode 100644 index 0000000..c7e8cad --- /dev/null +++ b/Gadgets of Doraland - GFG/gadgets-of-doraland.py @@ -0,0 +1,38 @@ +#User function Template for python3 + +class Solution: + def TopK(self, array, k): + # code here + d={} + x=[] + out=[] + for i in array: + if i in d: + d[i] += 1 + else: + d[i] = 1 + for i in d: + x.append([i,d[i]]) + x.sort(reverse=True,key=lambda x:(x[1],x[0])) + for i in range(k): + out.append(x[i][0]) + return out + + +#{ +# Driver Code Starts +#Initial Template for Python 3 + +if __name__ == '__main__': + t = int(input()) + for _ in range(t): + n = int(input()) + array = [int(x) for x in input().strip().split()] + k = int(input()) + obj = Solution() + res = obj.TopK(array, k) + for each in res: + print(each, end=' ') + print() + +# } Driver Code Ends \ No newline at end of file diff --git a/Handshakes - GFG/README.md b/Handshakes - GFG/README.md new file mode 100644 index 0000000..ca61dad --- /dev/null +++ b/Handshakes - GFG/README.md @@ -0,0 +1,51 @@ +# Handshakes +## Medium +
+

We have N persons sitting on a round table. Any person can do a handshake with any other person.

+ +

     1
+2         3
+     4

+ +

Handshake with 2-3 and 1-4 will cause cross.

+ +

In how many ways these N people can make handshakes so that no two handshakes cross each other. N would be even. 

+ +

Example 1:

+ +
Input:
+N = 2
+Output:
+1
+Explanation:
+{1,2} handshake is
+possible.
+
+ +

Example 2:

+ +
Input:
+N = 4
+Output:
+2
+Explanation:
+{{1, 2}, {3, 4}} are the
+two handshakes possible.
+{{1, 3}, {2, 4}} is another
+set of handshakes possible.
+
+ +


+Your Task:
+You don't need to read input or print anything. Your task is to complete the function count() which takes an integer N as input parameters and returns an integer, the total number of handshakes possible so that no two handshakes cross each other.

+ +

Expected Time Complexity: O(2N)
+Expected Space Complexity: O(1)

+ +

Constraints:
+1 <= N <= 30

+

+
\ No newline at end of file diff --git a/Handshakes - GFG/handshakes.cpp b/Handshakes - GFG/handshakes.cpp new file mode 100644 index 0000000..a3f4ad4 --- /dev/null +++ b/Handshakes - GFG/handshakes.cpp @@ -0,0 +1,31 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution{ +public: + int count(int N){ +// code here +int sum=0; +if(N==2 || N==0) +{ +return 1; +} +for(int i=0;i>t; + while(t--) + { + int N; + cin>>N; + Solution ob; + cout << ob.count(N) << endl; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Height Using Parent Array - GFG/README.md b/Height Using Parent Array - GFG/README.md new file mode 100644 index 0000000..8f70657 --- /dev/null +++ b/Height Using Parent Array - GFG/README.md @@ -0,0 +1,33 @@ +# Height Using Parent Array +## Medium +
+

Given a parent array arr[] of a binary tree of N nodes. Element at index i in the array arr[] represents the parent of ith node, i.e, arr[i] = parent(i). Find the height of this binary tree.
+Note: There will be a node in the array arr[], where arr[i] = -1, which means this node is the root of binary tree.

+ +

Example 1:

+ +
Input: N = 7
+arr = {-1, 0, 0, 1, 1, 3, 5}
+Output: 5
+Explanation: Tree formed is:
+                    0
+                   / \
+                  1   2
+                 / \
+                3   4
+               /
+              5
+             /
+            6      Height of the tree= 5
+ +

Your Task:
+You do not need to read input or print anything. Your task is to complete the function findHeight() which takes N and arr[] as input parameters and returns the height of the given binary tree.

+ +

Expected Time Complexity: O(N*N)
+Expected Auxiliary Space: O(1)

+ +

Constraints:
+1 ≤ N ≤ 104
+0 ≤ arr[i] ≤ 104   

+

+
\ No newline at end of file diff --git a/Height Using Parent Array - GFG/height-using-parent-array.cpp b/Height Using Parent Array - GFG/height-using-parent-array.cpp new file mode 100644 index 0000000..c5e25de --- /dev/null +++ b/Height Using Parent Array - GFG/height-using-parent-array.cpp @@ -0,0 +1,50 @@ +// { Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + + // } Driver Code Ends +// User function Template for C++ + +class Solution{ +public: + int findHeight(int N, int arr[]){ + // code here + + int ans = 1; + + for(int i=0; i= 0) + { + cur = arr[cur]; + cnt++; + } + + ans = max(ans, cnt); + } + + return ans; + } +}; + +// { Driver Code Starts. + +int main(){ + int t; + cin>>t; + while(t--){ + int N; + cin>>N; + int arr[N]; + for(int i = 0;i < N;i++) + cin>>arr[i]; + + Solution ob; + cout< +

Professor X wants his students to help each other in the chemistry lab. He suggests that every student should help out a classmate who scored less marks than him in chemistry and whose roll number appears after him. But the students are lazy and they don't want to search too far. They each pick the first roll number after them that fits the criteria. Find the marks of the classmate that each student picks.
+Note: one student may be selected by multiple classmates.

+ +

Example 1:

+ +
Input: N = 5, arr[] = {3, 8, 5, 2, 25}
+Output: 2 5 2 -1 -1
+Explanation: 
+1. Roll number 1 has 3 marks. The first person 
+who has less marks than him is roll number 4, 
+who has 2 marks.
+2. Roll number 2 has 8 marks, he helps student 
+with 5 marks.
+3. Roll number 3 has 5 marks, he helps student 
+with 2 marks.
+4. Roll number 4 and 5 can not pick anyone as 
+no student with higher roll number has lesser 
+marks than them. This is denoted by -1.
+Output shows the marks of the weaker student that 
+each roll number helps in order. ie- 2,5,2,-1,-1
+ +


+Example 2:

+ +
Input: N = 4, a[] = {1, 2, 3, 4}
+Output: -1 -1 -1 -1 
+Explanation: As the marks ars in increasing order. 
+None of the students can find a classmate who has 
+a higher roll number and less marks than them.
+
+ +

Your Task:  
+You don't need to read input or print anything. Complete the function help_classmate() which takes the array arr[] and size of array N as input parameters and returns a list of numbers. If a student is unable to find anyone then output is -1.

+ +

Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(N)

+ +

Constraints:
+1 ≤ N ≤ 5*105

+

+ \ No newline at end of file diff --git a/Help Classmates - GFG/help-classmates.cpp b/Help Classmates - GFG/help-classmates.cpp new file mode 100644 index 0000000..719a298 --- /dev/null +++ b/Help Classmates - GFG/help-classmates.cpp @@ -0,0 +1,60 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + + // } Driver Code Ends +//User function Template for C++ + +class Solution{ + + public: + vector help_classmate(vector arr, int n) + { + // Your code goes here + stack s; + vector res(n,-1); + for(int i=n-1;i>=0;i--) + { + while(!s.empty() && arr[i] <= s.top()) + s.pop(); + + if(!s.empty()) + { + res[i] = s.top(); + } + s.push(arr[i]); + } + return res; + } +}; + +// { Driver Code Starts. + +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + vector array(n); + for (int i = 0; i < n; ++i) + { + cin>>array[i]; + } + Solution obj; + vector result = obj.help_classmate(array,n); + for (int i = 0; i < n; ++i) + { + cout< +

You are given an infinite two-dimensional grid. There are N balloons placed at certain coordinates of the grid. You have an arrow with yourself, which you will be using to shoot the balloons. You can select any point on the grid as your starting point and any point on the grid as the target point. When you fire the arrow, all ballons lying on the shortest path between the starting point and target point will be burst. Given the coordinates of the N ballons in an array arr, your task is to find out the maximum number of balloons that you can fire in one arrow shot.

+ +

Example 1:

+ +
Input:
+N = 3
+arr[] = {{1, 2}, {2, 3}, {3, 4}}
+Output:
+3
+Explanation:
+If you position yourself at point (1,2)
+and fire the arrow aiming at the point (3,4).
+Then all the balloons will burst.
+ +

Example 2:

+ +
Input: 
+N = 3
+arr[] = {{2,2}, {0,0}, {1,2}} 
+Output:
+2
+Explanation: 
+If you position yourself at point (2,2)
+and fire the arrow aiming at the point (0,0).
+Then the two balloons present at the two points
+will burst.
+
+ +

Your Task:
+Complete the function mostBalloons() which takes the integers N and the array arr as the input parameters, and returns the maximum number of balloons that can be burst using one arrow.

+ +

Expected Time Complexity: O(N2)
+Expected Auxiliary Space: O(N)

+ +

Constraints:
+1 ≤ N ≤ 103

+-109 ≤ arr[i][j] ≤ 109

+

+ \ No newline at end of file diff --git a/Hit most Balloons - GFG/hit-most-balloons.cpp b/Hit most Balloons - GFG/hit-most-balloons.cpp new file mode 100644 index 0000000..ba3cd82 --- /dev/null +++ b/Hit most Balloons - GFG/hit-most-balloons.cpp @@ -0,0 +1,85 @@ +// { Driver Code Starts +// Initial Template for C++ +#include +using namespace std; + + // } Driver Code Ends +// User function Template for C++ + +class Fraction { + public: + int num, den; + + Fraction(int _a, int _b) { + if(_a == 0 || _b == 0) { + num = !_a; + den = !_b; + } else { + bool isNeg = _a > 0 != _b > 0; + _a = abs(_a); + _b = abs(_b); + int g = __gcd(_a, _b); + num = _a / g; + den = _b / g; + if(isNeg) num = -num; + } + } + + bool operator<(const Fraction& other) const { + if(num == other.num) return den < other.den; + return num < other.num; + } +}; + +class Solution { + public: + int mostBalloons(int N, pair arr[]) { + int ans = 0; + + // It's mandate to pop i'th balloon. + for(int i = 0; i < N; i++) { + int cur = 0, onSpot = 1; + map dp; + // Check max j'th balloons which can be popped. + for(int j = i + 1; j < N; j++) { + // Calculate slope beween i'th and j'th balloon. + // (y2 - y1) / (x2 - x1) + int num = arr[j].second - arr[i].second; + int den = arr[j].first - arr[i].first; + + if(!num && !den) { + ++onSpot; + continue; + } else { + Fraction ft(num, den); + cur = max(cur, ++dp[ft]); + } + } + + // include i'th balloon + ans = max(ans, cur + onSpot); + } + + return ans; + } +}; + +// { Driver Code Starts. + +int main() { + int t; + cin >> t; + while (t--) { + int N; + cin >> N; + pair arr[N]; + for (int i = 0; i < N; i++) { + cin >> arr[i].first; + } + for (int i = 0; i < N; i++) { + cin >> arr[i].second; + } + Solution ob; + cout << ob.mostBalloons(N, arr) << endl; + } +} // } Driver Code Ends \ No newline at end of file diff --git a/Implement stack using array - GFG/README.md b/Implement stack using array - GFG/README.md new file mode 100644 index 0000000..ca3dec8 --- /dev/null +++ b/Implement stack using array - GFG/README.md @@ -0,0 +1,43 @@ +# Implement stack using array +## Easy +
+

Write a program to implement a Stack using Array. Your task is to use the class as shown in the comments in the code editor and complete the functions push() and pop() to implement a stack. 

+ +

Example 1:

+ +
Input: 
+push(2)
+push(3)
+pop()
+push(4) 
+pop()
+Output: 3, 4
+Explanation: 
+push(2)    the stack will be {2}
+push(3)    the stack will be {2 3}
+pop()      poped element will be 3,
+           the stack will be {2}
+push(4)    the stack will be {2 4}
+pop()      poped element will be 4
+ +

Example 2:

+ +
Input: 
+pop()
+push(4)
+push(5)
+pop()
+Output: -1, 5
+
+ +

Your Task:
+You are required to complete two methods push() and pop(). The push() method takes one argument, an integer 'x' to be pushed into the stack and pop() which returns an integer present at the top and popped out from the stack. If the stack is empty then return -1 from the pop() method.

+ +

Expected Time Complexity : O(1) for both push() and pop().
+Expected Auixilliary Space : O(1) for both push() and pop().

+ +

Constraints:
+1 <= Q <= 100
+1 <= x <= 100

+

+
\ No newline at end of file diff --git a/Implement stack using array - GFG/implement-stack-using-array.cpp b/Implement stack using array - GFG/implement-stack-using-array.cpp new file mode 100644 index 0000000..7f5e685 --- /dev/null +++ b/Implement stack using array - GFG/implement-stack-using-array.cpp @@ -0,0 +1,68 @@ +// { Driver Code Starts +#include +using namespace std; + +class MyStack +{ +private: + int arr[1000]; + int top; +public: + MyStack(){top=-1;} + int pop(); + void push(int); +}; + + +int main() +{ + + int T; + cin>>T; + while(T--) + { + MyStack *sq = new MyStack(); + + int Q; + cin>>Q; + while(Q--){ + int QueryType=0; + cin>>QueryType; + if(QueryType==1) + { + int a; + cin>>a; + sq->push(a); + }else if(QueryType==2){ + cout<pop()<<" "; + + } + } + cout< +

Given a weighted, undirected and connected graph of V vertices and E edges, Find the shortest distance of all the vertex's from the source vertex S.
+Note: The Graph doesn't contain any negative weight cycle.

+ +

 

+ +

Example 1:

+ +
Input:
+
+S = 0
+Output:
+0 9
+Explanation:
+The source vertex is 0. Hence, the shortest 
+distance of node 0 is 0 and the shortest 
+distance from node 9 is 9 - 0 = 9.
+
+ +

 

+ +

Example 2:

+ +
Input:
+
+S = 2
+Output:
+4 3 0
+Explanation:
+For nodes 2 to 0, we can follow the path-
+2-1-0. This has a distance of 1+3 = 4,
+whereas the path 2-0 has a distance of 6. So,
+the Shortest path from 2 to 0 is 4.
+The other distances are pretty straight-forward.
+
+ +

 

+ +

Your Task:
+You don't need to read input or print anything. Your task is to complete the function dijkstra() 
which takes number of vertices V and an adjacency list adj as input parameters and returns a list of integers, where ith integer denotes the shortest distance of the ith node from Source node. Here adj[i] contains a list of lists containing two integers where the first integer j denotes that there is an edge between i and j and second integer w denotes that the weight between edge i and j is w.

+ +

 

+ +

Expected Time Complexity: O(V2).
+Expected Auxiliary Space: O(V2).

+ +

 

+ +
Constraints:
+1
V 1000
+0
adj[i][j] 1000
+ +
1 ≤ adj.size() ≤ [ (V*(V - 1)) / 2 ]
+0
S < V
+

+ \ No newline at end of file diff --git a/Implementing Dijkstra Algorithm - GFG/implementing-dijkstra-algorithm.cpp b/Implementing Dijkstra Algorithm - GFG/implementing-dijkstra-algorithm.cpp new file mode 100644 index 0000000..f9a7644 --- /dev/null +++ b/Implementing Dijkstra Algorithm - GFG/implementing-dijkstra-algorithm.cpp @@ -0,0 +1,76 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution +{ + public: + //Function to find the shortest distance of all the vertices + //from the source vertex S. + vector dijkstra(int V, vector> adj[], int S) + { + // Code here + vectordist(V,INT_MAX); + priority_queue>pq; + pq.push({0,S}); + dist[S]=0; + while(!pq.empty()) + { + pairp=pq.top(); + int a=p.second; + pq.pop(); + for(int i=0;i> t; + while (t--) { + int V, E; + cin >> V >> E; + vector> adj[V]; + int i=0; + while (i++> u >> v >> w; + vector t1,t2; + t1.push_back(v); + t1.push_back(w); + adj[u].push_back(t1); + t2.push_back(u); + t2.push_back(w); + adj[v].push_back(t2); + } + int S; + cin>>S; + + Solution obj; + vector res = obj.dijkstra(V, adj, S); + + for(int i=0; i +

Given a singly linked list, sort the list (in ascending order) using insertion sort algorithm.

+ +

Example 1:

+ +
Input:
+N = 10
+Linked List = 30->23->28->30->11->14->
+              19->16->21->25 
+Output : 11 14 16 19 21 23 25 28 30 30 
+Explanation :
+The resultant linked list is sorted.
+ +

Example 2:

+ +
Input : 
+N = 7
+Linked List=19->20->16->24->12->29->30 
+Output : 12 16 19 20 24 29 30 
+Explanation : 
+The resultant linked list is sorted.
+ +
Your task:
+ +
You don't need to read input or print anything. Your task is to complete the function insertionSort() which takes the head of the linked list, sorts the list using insertion sort algorithm and returns the head of the sorted linked list.
+ +
 
+ +
Expected Time Complexity : O(n2)
+ +
Expected Auxiliary Space : O(1)
+ +
 
+ +
Constraints:
+ +
1<=n<=10^5
+

+ \ No newline at end of file diff --git a/Insertion Sort for Singly Linked List - GFG/insertion-sort-for-singly-linked-list.cpp b/Insertion Sort for Singly Linked List - GFG/insertion-sort-for-singly-linked-list.cpp new file mode 100644 index 0000000..3895d1a --- /dev/null +++ b/Insertion Sort for Singly Linked List - GFG/insertion-sort-for-singly-linked-list.cpp @@ -0,0 +1,105 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + +/* Link list node */ +struct Node { + int data; + struct Node *next; + Node(int x) { + data = x; + next = NULL; + } +}; + +/* Function to print linked list */ +void printList(struct Node *head) +{ + struct Node *temp = head; + while (temp != NULL) + { + printf("%d ", temp->data); + temp = temp->next; + } +} + + + + + // } Driver Code Ends +//User function Template for C++ + +/*Link list node +struct Node { + int data; + struct Node *next; + Node(int x) { + data = x; + next = NULL; + } +};*/ + +class Solution +{ + public: + Node* insertionSort(struct Node* head) + { + Node *ans=new Node(0); + Node *h=head; + while(h!=NULL) + { + Node *curr=ans;Node *prev=NULL; + while(curr!=NULL&&(curr->data)<(h->data)) + { + prev=curr; + curr=curr->next; + } + Node *hnext=h->next; + Node *temp=curr;prev->next=h;h->next=temp; + h=hnext; + } + return ans->next; + } + +}; + +// { Driver Code Starts. +int main() +{ + int T; + cin >> T; + + while (T--) + { + int n; + cin >> n; + + Node *head = NULL; + Node *temp = head; + + for (int i = 0; i < n; i++) { + int data; + cin >> data; + if (head == NULL) + head = temp = new Node(data); + else + { + temp->next = new Node(data); + temp = temp->next; + } + } + + Solution ob; + + head = ob.insertionSort(head); + printList(head); + + cout << "\n"; + + + + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/K-th element of two sorted Arrays - GFG/README.md b/K-th element of two sorted Arrays - GFG/README.md new file mode 100644 index 0000000..7307caf --- /dev/null +++ b/K-th element of two sorted Arrays - GFG/README.md @@ -0,0 +1,48 @@ +# K-th element of two sorted Arrays +## Medium +
+

Given two sorted arrays arr1 and arr2 of size N and M respectively and an element K. The task is to find the element that would be at the k’th position of the final sorted array.

+ +

Example 1:

+ +
Input:
+arr1[] = {2, 3, 6, 7, 9}
+arr2[] = {1, 4, 8, 10}
+k = 5
+Output:
+6
+Explanation:
+The final sorted array would be -
+1, 2, 3, 4, 6, 7, 8, 9, 10
+The 5th element of this array is 6.
+
+ +
Example 2:
+ +
Input:
+arr1[] = {100, 112, 256, 349, 770}
+arr2[] = {72, 86, 113, 119, 265, 445, 892}
+k = 7
+Output:
+256
+Explanation:
+Final sorted array is - 72, 86, 100, 112,
+113, 119, 256, 265, 349, 445, 770, 892
+7th element of this array is 256.
+ +


+Your Task:  
+You don't need to read input or print anything. Your task is to complete the function kthElement() which takes the arrays arr1[]arr2[], its size N and M respectively and an integer K as inputs and returns the element at the Kth position.

+ +


+Expected Time Complexity: O(Log(N) + Log(M))
+Expected Auxiliary Space: O(Log (N))

+ +


+Constraints:
+1 <= N, M <= 106
+1 <= arr1i, arr2i < INT_MAX
+1 <= K <= N+M

+

+
\ No newline at end of file diff --git a/K-th element of two sorted Arrays - GFG/kth-element-of-two-sorted-arrays.cpp b/K-th element of two sorted Arrays - GFG/kth-element-of-two-sorted-arrays.cpp new file mode 100644 index 0000000..aa469aa --- /dev/null +++ b/K-th element of two sorted Arrays - GFG/kth-element-of-two-sorted-arrays.cpp @@ -0,0 +1,69 @@ +// { Driver Code Starts +#include +using namespace std; + + + // } Driver Code Ends +class Solution{ + public: + int kthElement(int arr1[], int arr2[], int n, int m, int k) + { + if(n>m) + { + return kthElement(arr2,arr1,m,n,k); + } + + int low = max(0,k-m), high = min(k,n); + + while(low<=high) + { + int cut1 = (low+high)/2; + int cut2 = k - cut1; + + int l1 = cut1 == 0 ? INT_MIN : arr1[cut1-1]; + int l2 = cut2 == 0 ? INT_MIN : arr2[cut2-1]; + + int r1 = cut1 == n ? INT_MAX : arr1[cut1]; + int r2 = cut2 == m ? INT_MAX : arr2[cut2]; + + // cout<<"l1 -> "< "< "< "<r2) + { + high = cut1-1; + } + else if(l2>r1) + { + low = cut1+1; + } + + + } + return 1; + } +}; + +// { Driver Code Starts. + +// Driver code +int main() +{ + int t; + cin>>t; + while(t--){ + int n,m,k; + cin>>n>>m>>k; + int arr1[n],arr2[m]; + for(int i=0;i>arr1[i]; + for(int i=0;i>arr2[i]; + + Solution ob; + cout << ob.kthElement(arr1, arr2, n, m, k)< +

Given an array Arr[] of N integers. Find the contiguous sub-array(containing at least one number) which has the maximum sum and return its sum.

+ +


+Example 1:

+ +
Input:
+N = 5
+Arr[] = {1,2,3,-2,5}
+Output:
+9
+Explanation:
+Max subarray sum is 9
+of elements (1, 2, 3, -2, 5) which 
+is a contiguous subarray.
+
+ +

Example 2:

+ +
Input:
+N = 4
+Arr[] = {-1,-2,-3,-4}
+Output:
+-1
+Explanation:
+Max subarray sum is -1 
+of element (-1)
+ +


+Your Task:
+You don't need to read input or print anything. The task is to complete the function maxSubarraySum() which takes Arr[] and N as input parameters and returns the sum of subarray with maximum sum.

+ +


+Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(1)

+ +


+Constraints:
+1 ≤ N ≤ 106
+-107 ≤ A[i] ≤ 107

+

+ \ No newline at end of file diff --git a/Kadane's Algorithm - GFG/kadanes-algorithm.cpp b/Kadane's Algorithm - GFG/kadanes-algorithm.cpp new file mode 100644 index 0000000..e90ffec --- /dev/null +++ b/Kadane's Algorithm - GFG/kadanes-algorithm.cpp @@ -0,0 +1,56 @@ +// { Driver Code Starts +#include +using namespace std; + + + // } Driver Code Ends +class Solution{ + public: + // arr: input array + // n: size of array + //Function to find the sum of contiguous subarray with maximum sum. + long long maxSubarraySum(int arr[], int n){ + + // Your code here + int max_so_far = INT_MIN; + int max_till_here = 0; + + for(int i=0;i max_so_far) + { + max_so_far = max_till_here; + } + + if(max_till_here < 0) + max_till_here = 0; + } + return max_so_far; + } +}; + +// { Driver Code Starts. + +int main() +{ + int t,n; + + cin>>t; //input testcases + while(t--) //while testcases exist + { + + cin>>n; //input size of array + + int a[n]; + + for(int i=0;i>a[i]; //inputting elements of array + + Solution ob; + + cout << ob.maxSubarraySum(a, n) << endl; + } +} + // } Driver Code Ends \ No newline at end of file diff --git a/Kth smallest element - GFG/README.md b/Kth smallest element - GFG/README.md new file mode 100644 index 0000000..4616178 --- /dev/null +++ b/Kth smallest element - GFG/README.md @@ -0,0 +1,46 @@ +# Kth smallest element +## Medium +
+

Given an array arr[] and an integer K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct.

+ +

Example 1:

+ +
Input:
+N = 6
+arr[] = 7 10 4 3 20 15
+K = 3
+Output : 7
+Explanation :
+3rd smallest element in the given 
+array is 7.
+
+ +

Example 2:

+ +
Input:
+N = 5
+arr[] = 7 10 4 20 15
+K = 4
+Output : 15
+Explanation :
+4th smallest element in the given 
+array is 15.
+ +
Your Task:
+You don't have to read input or print anything. Your task is to complete the function kthSmallest() which takes the array arr[], integers l and r denoting the starting and ending index of the array and an integer K as input and returns the Kth smallest element.
+ +
 
+ +
 
+ +
Expected Time Complexity: O(n)
+ +
Expected Auxiliary Space: O(1)
+ +

Constraints:
+1 <= N <= 105
+1 <= arr[i] <= 105
+1 <= K <= N

+

+
\ No newline at end of file diff --git a/Kth smallest element - GFG/kth-smallest-element.cpp b/Kth smallest element - GFG/kth-smallest-element.cpp new file mode 100644 index 0000000..56fdd85 --- /dev/null +++ b/Kth smallest element - GFG/kth-smallest-element.cpp @@ -0,0 +1,45 @@ +// { Driver Code Starts +//Initial function template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function template for C++ + +class Solution{ + public: + // arr : given array + // l : starting index of the array i.e 0 + // r : ending index of the array i.e size-1 + // k : find kth smallest element and return using this function + int kthSmallest(int arr[], int l, int r, int k) { + + sort(arr+l,arr+r+1); + return arr[l+k-1]; + + } +}; + +// { Driver Code Starts. + +int main() +{ + int test_case; + cin>>test_case; + while(test_case--) + { + int number_of_elements; + cin>>number_of_elements; + int a[number_of_elements]; + + for(int i=0;i>a[i]; + + int k; + cin>>k; + Solution ob; + cout< +

Given an array having both positive and negative integers. The task is to compute the length of the largest subarray with sum 0.

+ +

Example 1:

+ +
Input:
+N = 8
+A[] = {15,-2,2,-8,1,7,10,23}
+Output: 5
+Explanation: The largest subarray with
+sum 0 will be -2 2 -8 1 7.
+ +

Your Task:
+You just have to complete the function maxLen() which takes two arguments an array A and n, where n is the size of the array A and returns the length of the largest subarray with 0 sum.

+ +

Expected Time Complexity: O(N).
+Expected Auxiliary Space: O(N).

+ +

Constraints:
+1 <= N <= 105
+-1000 <= A[i] <= 1000, for each valid i

+

+ \ No newline at end of file diff --git a/Largest subarray with 0 sum - GFG/largest-subarray-with-0-sum.cpp b/Largest subarray with 0 sum - GFG/largest-subarray-with-0-sum.cpp new file mode 100644 index 0000000..0040df6 --- /dev/null +++ b/Largest subarray with 0 sum - GFG/largest-subarray-with-0-sum.cpp @@ -0,0 +1,56 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + + // } Driver Code Ends +/*You are required to complete this function*/ + +class Solution{ + public: + int maxLen(vector&A, int n) + { + // Your code here + unordered_map m; + int sum = 0; + int maxlen = 0; + m[0] = -1; + for(int i=0;i>t; + while(t--) + { + int m; + cin>>m; + vector array1(m); + for (int i = 0; i < m; ++i){ + cin>>array1[i]; + } + Solution ob; + cout< +

Given a binary tree, find the largest value in each level.

+ +

Example 1:

+ +
Input :
+        1
+       / \
+      2   3 
+
+Output : 1 3
+Explanation : 
+There are two levels in the tree :
+1. {1}, max = 1
+2. {2, 3}, max = 3
+ +

Example 2:

+ +
Input :
+        4
+       / \
+      9   2
+     / \   \
+    3   5   7 
+
+Output : 4 9 7
+Explanation : 
+There are three levels in the tree:
+1. {4}, max = 4
+2. {9, 2}, max = 9
+3. {3, 5, 7}, max=7
+ +
Your task :
+ +
You don't need to read input or print anything. Your task is to complete the function largestValues() which takes the root node of the tree as input and returns a vector containing the largest value in each level. 
+ +
 
+ +
Expected Time Complexity : O(n) , where n = number of nodes
+ +
Expected Auxiliary Space : O(n) , where n = number of nodes
+ +
 
+ +
Constraints : 
+ +
1 ≤ Number of nodes ≤ 10^5
+

+ \ No newline at end of file diff --git a/Largest value in each level - GFG/largest-value-in-each-level.cpp b/Largest value in each level - GFG/largest-value-in-each-level.cpp new file mode 100644 index 0000000..651411a --- /dev/null +++ b/Largest value in each level - GFG/largest-value-in-each-level.cpp @@ -0,0 +1,142 @@ +// { Driver Code Starts +//Initial Template for C++ + + +#include +using namespace std; + +// Tree Node +struct Node +{ + int data; + Node* left; + Node* right; +}; + +// Utility function to create a new Tree Node +Node* newNode(int val) +{ + Node* temp = new Node; + temp->data = val; + temp->left = NULL; + temp->right = NULL; + + return temp; +} + +// Function to Build Tree +Node* buildTree(string str) +{ + // Corner Case + if (str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for (string str; iss >> str; ) + ip.push_back(str); + + // Create the root of the tree + Node* root = newNode(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while (!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if (currVal != "N") { + + // Create the left child for the current node + currNode->left = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if (i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if (currVal != "N") { + + // Create the right child for the current node + currNode->right = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + + // } Driver Code Ends +//User function Template for C++ + +class Solution +{ + public: + vector largestValues(Node* root) + { + //code here + vector res; + queue q; + q.push(root); + while(!q.empty()){ + int sz=q.size(),mx=0; + while(sz--){ + auto x=q.front(); + q.pop(); + mx=max(mx,x->data); + if(x->left)q.push(x->left); + if(x->right)q.push(x->right); + } + res.push_back(mx); + } + return res; + } +}; + +// { Driver Code Starts. +int main() +{ + + int t; + cin >> t; + getchar(); + while (t--) + { + + string inp; + getline(cin, inp); + + struct Node* root = buildTree(inp); + Solution ob; + vector ans = ob.largestValues(root); + + for (int i = 0; i < ans.size(); i++) + cout << ans[i] << " "; + + cout << "\n"; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Leaves to DLL - GFG/README.md b/Leaves to DLL - GFG/README.md new file mode 100644 index 0000000..9355539 --- /dev/null +++ b/Leaves to DLL - GFG/README.md @@ -0,0 +1,61 @@ +# Leaves to DLL +## Medium +
+

Given a Binary Tree of size N, extract all its leaf nodes to form a Doubly Link List starting from the left most leaf. Modify the original tree to make the DLL thus removing the leaf nodes from the tree. Consider the left and right pointers of the tree to be the previous and next pointer of the DLL respectively.

+ +

Example 1:

+ +
Input :
+        1
+      /   \
+     2     3
+    / \   / \
+   4   5 6   7    
+
+Output: 
+Modified Tree :
+        1
+      /   \
+     2     3
+
+Doubly Link List :
+4 <-> 5 <-> 6 <-> 7
+
+Explanation:
+The leaf nodes are modified to form the DLL 
+in-place. Thus their links are removed from 
+the tree.
+ +

Example 2:

+ +
Input :
+        1
+      /   \
+     2     3
+    / \   
+   4   5 
+
+Output: 
+Modified Tree :
+        1
+      /   
+     2    
+
+Doubly Link List :
+4 <-> 5 <-> 3
+ +


+Your Task:  
+You dont need to read input or print anything. Complete the function convertToDLL() which takes root of the given tree as input parameter and returns the head of the doubly link list.

+ +

Note:
+The generated output will contain the inorder traversal of the modified tree, the DLL from left to right and the DLL from right to left.

+ +

Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(height of tree)

+ +


+Constraints:
+1 ≤ N ≤ 10^4

+

+
\ No newline at end of file diff --git a/Leaves to DLL - GFG/leaves-to-dll.cpp b/Leaves to DLL - GFG/leaves-to-dll.cpp new file mode 100644 index 0000000..c68b9bc --- /dev/null +++ b/Leaves to DLL - GFG/leaves-to-dll.cpp @@ -0,0 +1,169 @@ +// { Driver Code Starts +#include +using namespace std; + +// Tree Node +struct Node { + int data; + Node *left; + Node *right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; + +// Function to Build Tree +Node *buildTree(string str) { + // Corner Case + if (str.length() == 0 || str[0] == 'N') return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for (string str; iss >> str;) ip.push_back(str); + + // Create the root of the tree + Node *root = new Node(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while (!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node *currNode = queue.front(); + queue.pop(); + + // Get the current Node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if (currVal != "N") { + + // Create the left child for the current Node + currNode->left = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if (i >= ip.size()) break; + currVal = ip[i]; + + // If the right child is not null + if (currVal != "N") { + + // Create the right child for the current Node + currNode->right = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + +void inOrder(Node *root) { + if (!root) return; + inOrder(root->left); + cout << root->data << " "; + inOrder(root->right); +} + + + // } Driver Code Ends +/*Complete the function below +Node is as follows: +struct Node{ + int data; + Node *left,*right; + + Node(int x){ + data = x; + left = NULL; + right = NULL; + } +}; +*/ +// return the head of the DLL and remove those node from the tree as well. +Node*temp; +Node*head; +Node* preorder(Node*root) +{ + if(root==NULL)return root; + + if(root->left==NULL && root->right==NULL) + { + if(temp==NULL) + { + head=root; + temp=root; + } + else + { + temp->right=root; + root->left=temp; + temp=root; + } + return NULL; + } + + root->left=preorder(root->left); + root->right=preorder(root->right); + return root; + +} +Node * convertToDLL(Node *root) +{ + + temp=NULL; + head=NULL; + preorder(root); + return head; + + + + +} + +// { Driver Code Starts. + +int main() { + int tc; + scanf("%d ", &tc); + while (tc--) { + string treeString; + getline(cin, treeString); + Node* root = buildTree(treeString); + Node* head = convertToDLL(root); + inOrder(root); + cout << "\n"; + Node *curr = head, *last = head; + while (curr) { + cout << curr->data << " "; + last = curr; + curr = curr->right; + } + cout << "\n"; + curr = last; + while (curr) { + cout << curr->data << " "; + curr = curr->left; + } + cout << "\n"; + } + return 0; +} + + // } Driver Code Ends \ No newline at end of file diff --git a/Left View of Binary Tree - GFG/README.md b/Left View of Binary Tree - GFG/README.md new file mode 100644 index 0000000..d4fb5ae --- /dev/null +++ b/Left View of Binary Tree - GFG/README.md @@ -0,0 +1,42 @@ +# Left View of Binary Tree +## Easy +
+

Given a Binary Tree, print Left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from Left side. The task is to complete the function leftView(), which accepts root of the tree as argument.

+ +

Left view of following tree is 1 2 4 8.

+ +

          1
+       /     \
+     2        3
+   /     \    /    \
+  4     5   6    7
+   \
+     8   

+ +

Example 1:

+ +
Input:
+   1
+ /  \
+3    2
+Output: 1 3
+
+
+ +

Example 2:

+ +
Input:
+
+Output: 10 20 40
+
+ +

Your Task:
+You just have to complete the function leftView() that prints the left view. The newline is automatically appended by the driver code.

+Expected Time Complexity: O(N).
+Expected Auxiliary Space: O(Height of the Tree).

+ +

Constraints:
+0 <= Number of nodes <= 100
+1 <= Data of a node <= 1000

+

+
\ No newline at end of file diff --git a/Left View of Binary Tree - GFG/left-view-of-binary-tree.cpp b/Left View of Binary Tree - GFG/left-view-of-binary-tree.cpp new file mode 100644 index 0000000..94308b2 --- /dev/null +++ b/Left View of Binary Tree - GFG/left-view-of-binary-tree.cpp @@ -0,0 +1,148 @@ +// { Driver Code Starts +#include +using namespace std; + +// Tree Node +struct Node +{ + int data; + Node* left; + Node* right; +}; + +vector leftView(struct Node *root); + +// Utility function to create a new Tree Node +Node* newNode(int val) +{ + Node* temp = new Node; + temp->data = val; + temp->left = NULL; + temp->right = NULL; + + return temp; +} + + +// Function to Build Tree +Node* buildTree(string str) +{ + // Corner Case + if(str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for(string str; iss >> str; ) + ip.push_back(str); + + // for(string i:ip) + // cout< queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while(!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if(currVal != "N") { + + // Create the left child for the current node + currNode->left = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if(i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if(currVal != "N") { + + // Create the right child for the current node + currNode->right = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + +int main() { + int t; + scanf("%d ",&t); + while(t--) + { + string s; + getline(cin,s); + Node* root = buildTree(s); + vector vec = leftView(root); + for(int x : vec) + cout<& ans,int level) + { + if(root == NULL)return ; + + if(ans.size()data); + recur(root->left,ans,level+1); + recur(root->right,ans,level+1); + + } + +vector leftView(Node *root) +{ + // Your code here + vector ans; + + recur(root,ans,1); + return ans; +} diff --git a/Longest Common Prefix in an Array - GFG/README.md b/Longest Common Prefix in an Array - GFG/README.md new file mode 100644 index 0000000..27129ba --- /dev/null +++ b/Longest Common Prefix in an Array - GFG/README.md @@ -0,0 +1,41 @@ +# Longest Common Prefix in an Array +## Easy +
+

Given a array of N strings, find the longest common prefix among all strings present in the array.

+ +


+Example 1:

+ +
Input:
+N = 4
+arr[] = {geeksforgeeks, geeks, geek,
+         geezer}
+Output: gee
+Explanation: "gee" is the longest common
+prefix in all the given strings.
+
+ +

Example 2:

+ +
Input: 
+N = 2
+arr[] = {hello, world}
+Output: -1
+Explanation: There's no common prefix
+in the given strings.
+
+ +


+Your Task:
+You don't need to read input or print anything. Your task is to complete the function longestCommonPrefix() which takes the string array arr[] and its size N as inputs and returns the longest common prefix common in all the strings in the array. If there's no prefix common in all the strings, return "-1".

+ +


+Expected Time Complexity: O(N*max(|arri|)).
+Expected Auxiliary Space: O(max(|arri|)) for result.

+ +


+Constraints:
+1 ≤ N ≤ 103
+1 ≤ |arri| ≤ 103

+

+
\ No newline at end of file diff --git a/Longest Common Prefix in an Array - GFG/longest-common-prefix-in-an-array.cpp b/Longest Common Prefix in an Array - GFG/longest-common-prefix-in-an-array.cpp new file mode 100644 index 0000000..9f6bf21 --- /dev/null +++ b/Longest Common Prefix in an Array - GFG/longest-common-prefix-in-an-array.cpp @@ -0,0 +1,56 @@ +// { Driver Code Starts +//Initial template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function template for C++ + +class Solution{ + public: + + string longestCommonPrefix (string arr[], int N) + { + int mi=INT_MAX; + string first=arr[0];//store the first string + for(int i=1;i> t; + while (t--) + { + int n; cin >> n; + string arr[n]; + for (int i = 0; i < n; ++i) + cin >> arr[i]; + + Solution ob; + cout << ob.longestCommonPrefix (arr, n) << endl; + } +} + +// Contributed By: Pranay Bansal + // } Driver Code Ends \ No newline at end of file diff --git a/Longest substring to form a Palindrome - GFG/README.md b/Longest substring to form a Palindrome - GFG/README.md new file mode 100644 index 0000000..840427f --- /dev/null +++ b/Longest substring to form a Palindrome - GFG/README.md @@ -0,0 +1,44 @@ +# Longest substring to form a Palindrome +## Hard +
+

Given a string S which only contains lowercase alphabets. Find the length of the longest substring of S such that the characters in it can be rearranged to form a palindrome.

+ +


+Example 1:

+ +
Input:
+S = "aabe"
+Output:
+3
+Explanation:
+The substring "aab" can be rearranged to
+"aba" which is the longest palindrome
+possible for this String.
+
+ +
Example 2:
+ +
Input:
+S = "adbabd"
+Output:
+6
+Explanation:
+The whole string “adbabd” can be
+rearranged to form a palindromic substring.
+One possible arrangement is "abddba".
+Thus, output length of the string is 6. 
+
+ +


+Your Task:  
+You don't need to read input or print anything. Your task is to complete the function longestSubstring() which takes a String S as input and returns the length of largest possible Palindrome.

+ +


+Expected Time Complexity: O(|S|*26)
+Expected Auxiliary Space: O(|S|*26)

+ +


+Constraints:
+1 ≤ |S| ≤ 105

+

+
\ No newline at end of file diff --git a/Longest substring to form a Palindrome - GFG/longest-substring-to-form-a-palindrome.cpp b/Longest substring to form a Palindrome - GFG/longest-substring-to-form-a-palindrome.cpp new file mode 100644 index 0000000..09ee765 --- /dev/null +++ b/Longest substring to form a Palindrome - GFG/longest-substring-to-form-a-palindrome.cpp @@ -0,0 +1,43 @@ +// { Driver Code Starts +#include +using namespace std; + + + // } Driver Code Ends +//User function Template for C++ +class Solution { + public: + int longestSubstring(string S) { + unordered_map mp; + mp[0] = -1; + + int state = 0, res = 0; + for(int i=0; i> t; + while (t--) { + string S; + cin>>S; + + Solution ob; + cout << ob.longestSubstring(S) << endl; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/M-Coloring Problem - GFG/README.md b/M-Coloring Problem - GFG/README.md new file mode 100644 index 0000000..7672d8a --- /dev/null +++ b/M-Coloring Problem - GFG/README.md @@ -0,0 +1,39 @@ +# M-Coloring Problem +## Medium +
+

Given an undirected graph and an integer M. The task is to determine if the graph can be colored with at most M colors such that no two adjacent vertices of the graph are colored with the same color. Here coloring of a graph means the assignment of colors to all vertices. Print 1 if it is possible to colour vertices and 0 otherwise.

+ +

Example 1:

+ +
Input:
+N = 4
+M = 3
+E = 5
+Edges[] = {(0,1),(1,2),(2,3),(3,0),(0,2)}
+Output: 1
+Explanation: It is possible to colour the
+given graph using 3 colours.
+
+ +

Example 2:

+ +
Input:
+N = 3
+M = 2
+E = 3
+Edges[] = {(0,1),(1,2),(0,2)}
+Output: 0
+ +

Your Task:
+Your task is to complete the function graphColoring() which takes the 2d-array graph[], the number of colours and the number of nodes as inputs and returns true if answer exists otherwise false. 1 is printed if the returned value is true, 0 otherwise. The printing is done by the driver's code.
+Note: In Example there are Edges not the graph.Graph will be like, if there is an edge between vertex X and vertex Y graph[] will contain 1 at graph[X-1][Y-1], else 0. In 2d-array graph[ ], nodes are 0-based indexed, i.e. from 0 to N-1.Function will be contain 2-D graph not the edges.

+
+Expected Time Complexity: O(MN).
+Expected Auxiliary Space: O(N).

+ +

Constraints:
+1 ≤ N ≤ 20
+1 ≤ E ≤ (N*(N-1))/2
+1 ≤ M ≤ N

+

+
\ No newline at end of file diff --git a/M-Coloring Problem - GFG/mcoloring-problem.cpp b/M-Coloring Problem - GFG/mcoloring-problem.cpp new file mode 100644 index 0000000..763145c --- /dev/null +++ b/M-Coloring Problem - GFG/mcoloring-problem.cpp @@ -0,0 +1,66 @@ +// { Driver Code Starts +#include +using namespace std; + + + // } Driver Code Ends +//Function to determine if graph can be coloured with at most M colours such +//that no two adjacent vertices of graph are coloured with same colour. + +bool isPossible(int k,int n,int color[],bool graph[101][101], int V) +{ + for(int i=0;i> t; + while (t--) { + int n, m, e; + cin >> n >> m >> e; + int i; + bool graph[101][101]; + for (i = 0; i < n; i++) { + memset(graph[i], 0, sizeof(graph[i])); + } + for (i = 0; i < e; i++) { + int a, b; + cin >> a >> b; + graph[a - 1][b - 1] = 1; + graph[b - 1][a - 1] = 1; + } + cout << graphColoring(graph, m, n) << endl; + } + return 0; +} + // } Driver Code Ends \ No newline at end of file diff --git a/Matrix Operations - GFG/README.md b/Matrix Operations - GFG/README.md new file mode 100644 index 0000000..363c756 --- /dev/null +++ b/Matrix Operations - GFG/README.md @@ -0,0 +1,49 @@ +# Matrix Operations +## Easy +
+

Given a binary matrix of dimensions M * N. One can perform the given operation in the matrix.

+ +
    +
  • If the value of matrix[i][j] is 0, then traverse in the same direction and check the next value.
  • +
  • If the value of matrix[i][j] is 1, then update matrix[i][j] to 0 and change the current direction from uprightdown, or left to the directions rightdownleft, and up respectively.
  • +
+ +

Initially you start from cell(0, 0), moving in right direction.

+ +

The task is to find the first cell of the matrix  which leads to outside the matrix from the traversal of the given matrix from the cell (0, 0) by performing the operations.

+ +

Example 1:

+ +
Input:
+matrix[][] = {{0,1},
+              {1,0}}
+
+Output: (1,1)
+Explanation:
+
+
+
+
+
+ +

Example 2:

+ +
Input: 
+matrix[][] = {{0, 1, 1, 1, 0},
+                   {1, 0, 1, 0, 1},
+              {1, 1, 1, 0, 0}}
+
+Output: (2,0)
+ +

Your Task:
+You don't need to read input or print anything. Complete the function endPoints() that take the matrix as input parameter and output the last cell before the pointer gets outside of the matrix.

+ +

Constrains:
+1<= M, N <=1000
+0<= matrix[i][j] <=1

+ +

 

+ +

 

+

+
\ No newline at end of file diff --git a/Matrix Operations - GFG/matrix-operations.cpp b/Matrix Operations - GFG/matrix-operations.cpp new file mode 100644 index 0000000..308ea9e --- /dev/null +++ b/Matrix Operations - GFG/matrix-operations.cpp @@ -0,0 +1,83 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + + // } Driver Code Ends +//User function Template for C++ + +class Solution{ + public: + pair endPoints(vector> arr){ + //code here + int m = arr.size(); + int n = arr[0].size(); + + int a = 0, b = 1; + int i = 0, j = 0; + pair res = {0, 0}; + + while(true){ + if(arr[i][j] == 0){ + i = i + a; + j = j + b; + } + else{ + arr[i][j] = 0; + if(a==0 && b==1){ + a = 1; + b = 0; + } + else if(a==1 && b==0){ + a = 0; + b = -1; + } + else if(a==0 && b==-1){ + a = -1; + b = 0; + } + else if(a==-1 && b==0){ + a = 0; + b = 1; + } + i = i + a; + j = j + b; + } + if(i>=m || i<0 || j>=n || j<0){ + res.first = i-a; + res.second = j-b; + break; + } + } + return res; + } + +}; + +// { Driver Code Starts. + + +int main() +{ + int tc; + scanf("%d", &tc); + while(tc--){ + int row, col; + scanf("%d", &row); + scanf("%d", &col); + vector> matrix(row , vector (col)); + + for(int i = 0; i < row; i++){ + for(int j = 0; j < col; j++){ + cin>>matrix[i][j]; + } + } + Solution obj; + pair p = obj.endPoints(matrix); + + cout << "(" << p.first << ", " << p.second << ")" << endl; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Maximum Winning score - GFG/README.md b/Maximum Winning score - GFG/README.md new file mode 100644 index 0000000..423b1a6 --- /dev/null +++ b/Maximum Winning score - GFG/README.md @@ -0,0 +1,53 @@ +# Maximum Winning score +## Medium +
+

In an online game, N blocks are arranged in a hierarchical manner. All the blocks are connected together by a total of N-1 connections. Each block is given an ID from 1 to N. A block may be further connected to other blocks. Each block is also assigned a specific point value.

+ +

A player starts from Block 1. She must move forward from each block to a directly connected block until she reaches the final block, which has no further connection. When the player lands on a block, she collects the point value of that block. The players score is calculated as the product of point values that the player collects.
+Find the maximum score a player can achieve.
+Note: The answer can always be represented with 64 bits.

+ +


+Example 1:

+ +
Input:
+     4
+    / \
+   2   8
+  / \ / \
+ 2  1 3  4
+Output: 128
+Explanation: Path in the given tree 
+goes like 4, 8, 4 which gives the max
+score of 4x8x4 = 128.
+
+ +

Example 2:

+ +
Input:
+     10
+   /    \
+  7      5
+          \
+           1
+Output: 70
+Explanation: The path 10, 7 gives a 
+score of 70 which is the maximum possible.
+
+ +


+Your Task:
+You don't need to take input or print anything. Your task is to complete the function findMaxScore() that takes root as input and returns max score possible.

+ +


+Expected Time Complexity: O(N).
+Expected Auxiliary Space: O(Height of the Tree).

+ +

+Constraints:
+1 ≤ Number of nodes ≤ 103
+1 ≤ Data on node ≤ 10
+ +
It is guaranteed that the answer will always fit in the 64-bit Integer
+

+
\ No newline at end of file diff --git a/Maximum Winning score - GFG/maximum-winning-score.cpp b/Maximum Winning score - GFG/maximum-winning-score.cpp new file mode 100644 index 0000000..eb88f8a --- /dev/null +++ b/Maximum Winning score - GFG/maximum-winning-score.cpp @@ -0,0 +1,137 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + +// Tree Node +struct Node +{ + int data; + Node* left; + Node* right; +}; + +// Utility function to create a new Tree Node +Node* newNode(int val) +{ + Node* temp = new Node; + temp->data = val; + temp->left = NULL; + temp->right = NULL; + + return temp; +} + +// Function to Build Tree +Node* buildTree(string str) +{ + // Corner Case + if (str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for (string str; iss >> str; ) + ip.push_back(str); + + // Create the root of the tree + Node* root = newNode(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while (!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if (currVal != "N") { + + // Create the left child for the current node + currNode->left = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if (i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if (currVal != "N") { + + // Create the right child for the current node + currNode->right = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + + // } Driver Code Ends +//User function Template for C++ + +//Structure of node +/*struct Node { + int data; + Node *left; + Node *right; + + Node(int val) { + data = val; + left = right = NULL; + } +};*/ +class Solution { + public: + //Function to return maximum path product from any node in a tree. + long long findMaxScore(Node* root) + { + if(root == NULL) return 1; + + long long lScore = findMaxScore(root->left); + long long rScore = findMaxScore(root->right); + + + return max(lScore*root->data,rScore*root->data); + } +}; + +// { Driver Code Starts. + + +int main() { + int tc; + cin>>tc; + cin.ignore(256, '\n'); + while (tc--) { + string treeString; + getline(cin, treeString); + Solution ob; + Node *root = buildTree(treeString); + cout << ob.findMaxScore(root) << "\n"; + } + + + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Maximum average subarray - GFG/README.md b/Maximum average subarray - GFG/README.md new file mode 100644 index 0000000..bfd2b16 --- /dev/null +++ b/Maximum average subarray - GFG/README.md @@ -0,0 +1,39 @@ +# Maximum average subarray +## Easy +
+

Given an array Arr of size N and a positive integer K, find the sub-array of length K with the maximum average.

+ +


+Example 1:

+ +
Input:
+K = 4, N = 6
+Arr[] = {1, 12, -5, -6, 50, 3}
+Output: 12 -5 -6 50
+Explanation: Maximum average is 
+(12 - 5 - 6 + 50)/4 = 51/4.
+ +


+Example 2:

+ +
Input:
+K = 3, N = 7
+Arr[] = {3, -435, 335, 10, -50, 100, 20}
+Output: 335 10 -50
+Explanation: Maximum average is 
+(335 + 10 - 50)/3 = 295/3.
+
+ +


+Your Task:
+You don't need to read input or print anything. Your task is to complete the function findMaxAverage() which takes the array of integers arr, its size n and integer as input parameters and returns an integer denoting the starting index of the subarray.

+ +


+Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(1)
+
+Constraints
+1 <= N <= 105
+0 <= |Arr[i]| <= 103

+

+
\ No newline at end of file diff --git a/Maximum average subarray - GFG/maximum-average-subarray.cpp b/Maximum average subarray - GFG/maximum-average-subarray.cpp new file mode 100644 index 0000000..3b6fb37 --- /dev/null +++ b/Maximum average subarray - GFG/maximum-average-subarray.cpp @@ -0,0 +1,53 @@ +// { Driver Code Starts +//Initial template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function template for C++ + +class Solution{ +public: + int findMaxAverage(int arr[], int n, int k) { + if(n=ans){ + ans=sum; + idx=j-k+1; + } + } + return idx; + } +}; + +// { Driver Code Starts. +int main() { + int t; + cin >> t; + while (t--) { + int n, k; + cin >> k; + cin >> n; + int arr[n]; + for (int i = 0; i < n; i++) { + cin >> arr[i]; + } + Solution ob; + auto ans = ob.findMaxAverage(arr, n, k); + for (int i = ans; i < ans + k; i++) { + cout << arr[i] << " "; + } + cout << "\n"; + } + return 0; +} + // } Driver Code Ends \ No newline at end of file diff --git a/Maximum number of events that can be attended - GFG/maximum-number-of-events-that-can-be-attended.cpp b/Maximum number of events that can be attended - GFG/maximum-number-of-events-that-can-be-attended.cpp new file mode 100644 index 0000000..037cad4 --- /dev/null +++ b/Maximum number of events that can be attended - GFG/maximum-number-of-events-that-can-be-attended.cpp @@ -0,0 +1,55 @@ +// { Driver Code Starts +#include +using namespace std; + + + // } Driver Code Ends +//User function Template for C++ +class Solution { + public: + int maxEvents(int start[], int end[], int N) { + priority_queue , greater> pq; + vector> A(N); + for(int i=0; i 0 || i < N) { + if (pq.size() == 0) + d = A[i].first; + while (i < N && A[i].first <= d) + pq.push(A[i++].second); + pq.pop(); + ++res, ++d; + while (pq.size() > 0 && pq.top() < d) + pq.pop(); + + } + return res; + } +}; + +// { Driver Code Starts. + +int main() { + int t; + cin >> t; + while (t--) { + int N; + cin>>N; + + int start[N], end[N]; + for(int i=0; i>start[i]; + for(int i=0; i>end[i]; + + Solution ob; + cout << ob.maxEvents(start,end,N) << endl; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Maximum selections - GFG/README.md b/Maximum selections - GFG/README.md new file mode 100644 index 0000000..940e731 --- /dev/null +++ b/Maximum selections - GFG/README.md @@ -0,0 +1,68 @@ +# Maximum selections +## Medium +
+

Note: This POTD is a part of Geek Summer Carnival. Solve all POTD consecutively from 5th to 10th April and get a chance to win exclusive discount vouchers on our GfG courses.

+ +
+

Geek wants to select the maximum number of course bundles at the Geek Summer Carnival. 

+ +

You are given a finite number of courses and N range of numbers each depicting a bundle of courses. Select the maximum number of bundles such that no courses overlap in any of the bundle.

+ +

Note: The ending of a range being the same as start of another isn't considered as an overlap.

+ +


+Example 1:

+ +
Input:
+N = 4
+Bundles = 
+1 5
+2 3
+1 8
+3 5
+
+Output:
+2
+
+Explanation: 
+
+We can select 2 bundles at max while 
+staying true to the condition. For this, 
+we can pick the ranges (2,3) and (3,5) 
+without any overlap. 
+ +

 

+ +

Example 2:

+ +
Input:
+N = 5
+Bundles = 
+7 9 
+2 8 
+1 3 
+10 11 
+10 16
+
+Output:
+3
+
+Explanation: 
+
+We can pick the ranges (1,3), 
+(7,9) and (10,11) without any overlap.
+ +


+Your Task:
+You don't need to read input or print anything. Complete the function max_non_overlapping() that takes a 2D array representing N ranges as input parameter.  Return the maximum number of course bundles. 

+ +


+Expected time complexity: O(NlogN)
+Expected space complexity: O(1)

+ +


+Constraints:
+1 <= N <= 1000
+0 <= range[i][j] <= 1000

+

+
\ No newline at end of file diff --git a/Maximum selections - GFG/maximum-selections.cpp b/Maximum selections - GFG/maximum-selections.cpp new file mode 100644 index 0000000..1b03aac --- /dev/null +++ b/Maximum selections - GFG/maximum-selections.cpp @@ -0,0 +1,53 @@ +// { Driver Code Starts +#include +using namespace std; + + + // } Driver Code Ends +// ranges[i][0] is the start of ith range +// ranges[i][1] is the end of ith range + +class Solution{ +public: + static bool cmp(vector &a, vector &b){ + return a[1] < b[1]; + } + int max_non_overlapping( vector< vector >& ranges ) + { + // code here + sort(ranges.begin(), ranges.end(), cmp); + int n = ranges.size(); + int val = ranges[0][1]; + int count = 1; + + for(int i = 1;i < n;i++){ + if(ranges[i][0] >= val){ + val = ranges[i][1]; + count++; + } + } + return count; + } +}; +// { Driver Code Starts. + +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + + vector< vector > v(n,vector(2)); + for(int i=0; i> v[i][0] >> v[i][1]; + + Solution ob; + cout<< ob.max_non_overlapping(v) << endl; + } + return 1; +} + + // } Driver Code Ends \ No newline at end of file diff --git a/Maximum sum of increasing order elements from n arrays - GFG/README.md b/Maximum sum of increasing order elements from n arrays - GFG/README.md new file mode 100644 index 0000000..c721277 --- /dev/null +++ b/Maximum sum of increasing order elements from n arrays - GFG/README.md @@ -0,0 +1,34 @@ +# Maximum sum of increasing order elements from n arrays +## Easy +
+

Given n arrays of size m each. Find maximum sum obtained by selecting a number from each array such that the element selected from the i-th array is more than the element selected from (i-1)-th array. If maximum sum cannot be obtained then return 0.

+ +

Example 1:

+ +
​Input : arr[ ] = {{1,7,4,3}, {4,2,5,1}, {9,5,1,8}}
+Output : 18
+Explanation:
+We can select 4 from the first array,
+5 from second array and 9 from the third array.
+
+ +


+​Example 2:

+ +
Input : arr[ ] = {{9,8,7}, {6,5,4}, {3,2,1}} 
+Output :  0
+
+
+ +

Your Task:
+This is a function problem. The input is already taken care of by the driver code. You only need to complete the function maximumSum() that takes number of row N, a number of Column M, 2-d array (arr), and return the maximum sum if cannot be obtained then return 0. The driver code takes care of the printing.

+ +

Expected Time Complexity: O(N*M).
+Expected Auxiliary Space: O(1).

+ +

 

+ +

Constraints:
+1 ≤ N, M ≤ 500

+

+
\ No newline at end of file diff --git a/Maximum sum of increasing order elements from n arrays - GFG/maximum-sum-of-increasing-order-elements-from-n-arrays.cpp b/Maximum sum of increasing order elements from n arrays - GFG/maximum-sum-of-increasing-order-elements-from-n-arrays.cpp new file mode 100644 index 0000000..e8472a1 --- /dev/null +++ b/Maximum sum of increasing order elements from n arrays - GFG/maximum-sum-of-increasing-order-elements-from-n-arrays.cpp @@ -0,0 +1,62 @@ +// { Driver Code Starts +// CPP program to find maximum sum +// by selecting a element from n arrays +#include + +using namespace std; + +// To calculate maximum sum by +// selecting element from each array +int maximumSum( int n,int m, vector> &a); + + + +// Driver program to test maximumSum +int main() { + int t,n,m; + cin>>t; + while(t--) + { + cin>>n>>m; + vector> arr(n, vector(m,0)); + for(int i=0;i>arr[i][j]; + + cout << maximumSum(n,m,arr)<> &a) { + + for(int i=0;i=0;i--) + { + for(int j=m-1;j>=0;j--) + { + if(a[i][j] +

Given a row wise sorted matrix of size RxC where R and C are always odd, find the median of the matrix.

+ +

Example 1:

+ +
Input:
+R = 3, C = 3
+M = [[1, 3, 5], 
+     [2, 6, 9], 
+     [3, 6, 9]]
+
+Output: 5
+
+Explanation:
+Sorting matrix elements gives us 
+{1,2,3,3,5,6,6,9,9}. Hence, 5 is median. 
+
+ +

 

+ +

Example 2:

+ +
Input:
+R = 3, C = 1
+M = [[1], [2], [3]]
+Output: 2
+
+ +


+Your Task:  
+You don't need to read input or print anything. Your task is to complete the function median() which takes the integers R and C along with the 2D matrix as input parameters and returns the median of the matrix.
+
+Expected Time Complexity: O(32 * R * log(C))

+Expected Auxiliary Space: O(1)

+ +


+Constraints:
+1<= R,C <=150
+1<= matrix[i][j] <=2000

+

+

+ \ No newline at end of file diff --git a/Median in a row-wise sorted Matrix - GFG/median-in-a-rowwise-sorted-matrix.cpp b/Median in a row-wise sorted Matrix - GFG/median-in-a-rowwise-sorted-matrix.cpp new file mode 100644 index 0000000..f121336 --- /dev/null +++ b/Median in a row-wise sorted Matrix - GFG/median-in-a-rowwise-sorted-matrix.cpp @@ -0,0 +1,69 @@ +// { Driver Code Starts +//Initial template for C++ + +#include +using namespace std; + + + // } Driver Code Ends +//User function template for C++ + +class Solution{ +public: +int counter(int mid,vector> &matrix, int r, int c) +{ + int ans = 0; + for(int i=0;i> &matrix, int r, int c){ + // code here + int low = INT_MAX; + int high = INT_MIN; + for(int i = 0;ilow) + { + int mid = low +(high - low)/2; + int ans = counter(mid,matrix,r,c); + + if(ans < des) + low = mid+1; + else + high = mid; + + } + return low; + + } +}; + +// { Driver Code Starts. + +int main() +{ + int t; + cin>>t; + while(t--) + { + int r, c; + cin>>r>>c; + vector> matrix(r, vector(c)); + for(int i = 0; i < r; ++i) + for(int j = 0;j < c; ++j) + cin>>matrix[i][j]; + Solution obj; + cout< +

Given K sorted linked lists of different sizes. The task is to merge them in such a way that after merging they will be a single sorted linked list.

+ +

Example 1:

+ +
Input:
+K = 4
+value = {{1,2,3},{4 5},{5 6},{7,8}}
+Output: 1 2 3 4 5 5 6 7 8
+Explanation:
+The test case has 4 sorted linked 
+list of size 3, 2, 2, 2
+1st    list     1 -> 2-> 3
+2nd   list      4->5
+3rd    list      5->6
+4th    list      7->8
+The merged list will be
+1->2->3->4->5->5->6->7->8.
+
+ +

Example 2:

+ +
Input:
+K = 3
+value = {{1,3},{4,5,6},{8}}
+Output: 1 3 4 5 6 8
+Explanation:
+The test case has 3 sorted linked
+list of size 2, 3, 1.
+1st list 1 -> 3
+2nd list 4 -> 5 -> 6
+3rd list 8
+The merged list will be
+1->3->4->5->6->8.
+
+ +

Your Task:
+The task is to complete the function mergeKList() which merges the K given lists into a sorted one. The printing is done automatically by the driver code.

+ +

Expected Time Complexity: O(nk Logk)
+Expected Auxiliary Space: O(k)
+Note: n is the maximum size of all the k link list

+ +

Constraints
+1 <= K <= 103

+ +

 

+

+ \ No newline at end of file diff --git a/Merge K sorted linked lists - GFG/merge-k-sorted-linked-lists.cpp b/Merge K sorted linked lists - GFG/merge-k-sorted-linked-lists.cpp new file mode 100644 index 0000000..c715f96 --- /dev/null +++ b/Merge K sorted linked lists - GFG/merge-k-sorted-linked-lists.cpp @@ -0,0 +1,134 @@ +// { Driver Code Starts +// C++ program to merge k sorted arrays of size n each +#include +using namespace std; + +// A Linked List node +struct Node +{ + int data; + Node* next; + + Node(int x){ + data = x; + next = NULL; + } + +}; + +/* Function to print nodes in a given linked list */ +void printList(Node* node) +{ + while (node != NULL) + { + printf("%d ", node->data); + node = node->next; + } + cout< arr[i]->data) + { + minN = arr[i]->data; + minNode = i; + } + } + else + ++nodes; + } + + if (nodes == k) + break; + + if (!head) + { + head = new Node(minN); + ans = head; + } + else + { + head->next = new Node(minN); + head = head->next; + } + arr[minNode] = arr[minNode] ->next; + minN = INT_MAX; + } + return ans; + } +}; + + +// { Driver Code Starts. +// Driver program to test above functions +int main() +{ + int t; + cin>>t; + while(t--) + { + int N; + cin>>N; + struct Node *arr[N]; + for(int j=0;j>n; + + int x; + cin>>x; + arr[j]=new Node(x); + Node *curr = arr[j]; + n--; + + for(int i=0;i>x; + Node *temp = new Node(x); + curr->next =temp; + curr=temp; + } + } + Solution obj; + Node *res = obj.mergeKLists(arr,N); + printList(res); + + } + + return 0; +} + // } Driver Code Ends \ No newline at end of file diff --git a/Min Coin - GFG/README.md b/Min Coin - GFG/README.md new file mode 100644 index 0000000..7bd8c27 --- /dev/null +++ b/Min Coin - GFG/README.md @@ -0,0 +1,39 @@ +# Min Coin +## Medium +
+

Given a list of coins of distinct denominations and total amount of money. Find the minimum number of coins required to make up that amount. Output -1 if that money cannot be made up using given coins.
+You may assume that there are infinite numbers of coins of each type.

+ +

Example 1:

+ +
Input: arr = [1, 2, 5], amount = 11
+Output: 3
+Explanation: 2*5 + 1 = 11. So taking 2 
+denominations of 5 and 1 denomination of  
+1, one can make 11.
+
+ +

Example 2:

+ +
Input: arr = [2, 6], amount = 7
+Output: -1
+Explanation: Not possible to make 7 using 
+denominations 2 and 6.
+
+ +

 

+ +

Your Task:
+You don't need to read or print anything. Your task is to complete the function MinCoin() which takes list of denominations and amount as input parameter and returns miimum number of coins to make up amount. If not possible returns -1.

+ +

Expected Time Complexity: O(n*amount)
+Expected Space Complexity: O(amount)

+ +

Contstraints:
+1 <= number of distinct denominations <= 100

+1 <= amount <= 104

+

+
\ No newline at end of file diff --git a/Min Coin - GFG/min-coin.cpp b/Min Coin - GFG/min-coin.cpp new file mode 100644 index 0000000..50f5f23 --- /dev/null +++ b/Min Coin - GFG/min-coin.cpp @@ -0,0 +1,61 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends + +class Solution{ +public: +int min_coin(vectornums, int amount, int i, vector>&dp){ + if(amount==0) + return 0; + + if(i==0){ + if(amount>=nums[0] && amount%nums[0]==0) + return amount/nums[0]; + else + return 100001; + } + + if(dp[i][amount]!=-1) + return dp[i][amount]; + + int mini = INT_MAX; + + // not pick + mini = min(mini, min_coin(nums, amount, i-1, dp)); + + // pick + if(amount>=nums[i]) + mini = min(mini, min_coin(nums, amount-nums[i], i, dp) + 1); + + dp[i][amount] = mini; + return mini; +} +int MinCoin(vectornums, int amount) +{ + int n = nums.size(); + vector>dp(n, vector(amount+1, -1)); + int val = min_coin(nums, amount, n-1, dp); + if(val<=10000) + return val; + else + return -1; +} +}; +// { Driver Code Starts. +int main(){ + int tc; + cin >> tc; + while(tc--){ + int n, amount; + cin >> n >> amount; + vectornums(n); + for(int i = 0; i < n; i++) + cin >> nums[i]; + Solution ob; + int ans = ob.MinCoin(nums, amount); + cout << ans <<"\n"; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Minimum Swaps to Sort - GFG/README.md b/Minimum Swaps to Sort - GFG/README.md new file mode 100644 index 0000000..3f912b5 --- /dev/null +++ b/Minimum Swaps to Sort - GFG/README.md @@ -0,0 +1,38 @@ +# Minimum Swaps to Sort +## Medium +
+

Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.

+ +


+Example 1:

+ +
Input:
+nums = {2, 8, 5, 4}
+Output:
+1
+Explaination:
+swap 8 with 4.
+ +

Example 2:

+ +
Input:
+nums = {10, 19, 6, 3, 5}
+Output:
+2
+Explaination:
+swap 10 with 3 and swap 19 with 5.
+ +


+Your Task:
+You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0. 

+ +


+Expected Time Complexity: O(nlogn)
+Expected Auxiliary Space: O(n)

+ +


+Constraints:
+1 ≤ n ≤ 105
+1 ≤ numsi ≤ 106

+

+
\ No newline at end of file diff --git a/Minimum Swaps to Sort - GFG/minimum-swaps-to-sort.cpp b/Minimum Swaps to Sort - GFG/minimum-swaps-to-sort.cpp new file mode 100644 index 0000000..21e016b --- /dev/null +++ b/Minimum Swaps to Sort - GFG/minimum-swaps-to-sort.cpp @@ -0,0 +1,47 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends + + +class Solution +{ + public: + //Function to find the minimum number of swaps required to sort the array. + int minSwaps(vector&nums) + { + map mp; + for(int i=0;ifirst) + { + swap(nums[i],nums[it->second]); + mp[nums[it->second]]=it->second; + c++; + } + i++; + } + return c; + } +}; + +// { Driver Code Starts. +int main(){ + int tc; + cin >> tc; + while(tc--){ + int n; + cin >> n; + vectornums(n); + for(int i = 0; i < n; i++) + cin >> nums[i]; + Solution obj; + int ans = obj.minSwaps(nums); + cout << ans <<"\n"; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Move all zeros to the front of the linked list - GFG/README.md b/Move all zeros to the front of the linked list - GFG/README.md new file mode 100644 index 0000000..7610538 --- /dev/null +++ b/Move all zeros to the front of the linked list - GFG/README.md @@ -0,0 +1,30 @@ +# Move all zeros to the front of the linked list +## Easy +
+

Given a linked list, the task is to move all 0s to the front of the linked list. The order of all another element except 0 should be same after rearrangement.

+ +

Example 1:

+ +
Input:  0 -> 4 -> 0 -> 5 -> 0
+Output: 0 -> 0 -> 0 -> 4 -> 5
+Explanation: After moving all 0s of the given
+list to the front, the list is:
+0 -> 0 -> 0 -> 4 -> 5
+ +

Example 2:

+ +
Input: 0 -> 1 -> 0 -> 1 -> 2
+Output: 0 -> 0 -> 1 -> 1 -> 2
+ +

Your Task:
+You don't need to read input or print anything. Your task is to complete the function moveZeroes() which takes head node of the linked list as input parameter.

+ +

Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(1)

+ +

Constraints:
+1 <= N <= 50

+

+

+
\ No newline at end of file diff --git a/Move all zeros to the front of the linked list - GFG/move-all-zeros-to-the-front-of-the-linked-list.cpp b/Move all zeros to the front of the linked list - GFG/move-all-zeros-to-the-front-of-the-linked-list.cpp new file mode 100644 index 0000000..8643c39 --- /dev/null +++ b/Move all zeros to the front of the linked list - GFG/move-all-zeros-to-the-front-of-the-linked-list.cpp @@ -0,0 +1,87 @@ +// { Driver Code Starts +//Initial Template for C++ +#include +using namespace std; +struct Node +{ + int data; + struct Node* next; + + Node(int x){ + data = x; + next = NULL; + } + +}; + +void push(struct Node **head_ref, int new_data) { + struct Node *new_node = new Node(new_data); + new_node->next = (*head_ref); + (*head_ref) = new_node; +} + +void moveZeroes(struct Node **head); + +// function to displaying nodes +void display(struct Node *head) { + while (head != NULL) { + cout << head->data << " "; + head = head->next; + } + cout <>t; + while(t--) + { + int n; + cin>>n; + int q; + struct Node *Head=NULL; + for(int i=0;i>q; + push(&Head,q); + } + moveZeroes(&Head); + display(Head); + + } +} +// } Driver Code Ends + + +//User function Template for C++ +/* Linked List Node structure +struct Node +{ + int data; + struct Node* next; + + Node(int x){ + data = x; + next = NULL; + } + +}; +*/ +// Move Zeros to the front of the list +void moveZeroes(struct Node **head) +{ + //Your code here + Node * left = *head, *right = *head; + while(left && right){ + if(right->data == 0 && left != right){ + int temp = left->data; left->data = 0; left = left->next; Node* curr = left; + while(curr != right){ + swap(temp, curr->data); + curr = curr->next; + } + curr->data = temp; + } + right = right->next; + } +} \ No newline at end of file diff --git a/N Digit numbers with digits in increasing order - GFG/README.md b/N Digit numbers with digits in increasing order - GFG/README.md new file mode 100644 index 0000000..31ff826 --- /dev/null +++ b/N Digit numbers with digits in increasing order - GFG/README.md @@ -0,0 +1,37 @@ +# N Digit numbers with digits in increasing order +## Medium +
+

Given an integer N, print all the N digit numbers in increasing order, such that their digits are in strictly increasing order(from left to right).

+ +

Example 1:

+ +
Input:
+N = 1
+Output:
+0 1 2 3 4 5 6 7 8 9
+Explanation:
+Single digit numbers are considered to be 
+strictly increasing order.
+
+ +

Example 2:

+ +
Input:
+N = 2
+Output:
+12 13 14 15 16 17 18 19 23....79 89
+Explanation:
+For N = 2, the correct sequence is
+12 13 14 15 16 17 18 19 23 and so on 
+up to 89.
+ +

Your Task:  
+You don't need to read input or print anything. Your task is to complete the function increasingNumbers() which takes an integer N as an input parameter and return the list of numbers such that their digits are in strictly increasing order.

+ +

Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(N)

+ +

Constraints:
+1 <= N <= 9

+

+
\ No newline at end of file diff --git a/N Digit numbers with digits in increasing order - GFG/n-digit-numbers-with-digits-in-increasing-order.cpp b/N Digit numbers with digits in increasing order - GFG/n-digit-numbers-with-digits-in-increasing-order.cpp new file mode 100644 index 0000000..1b93818 --- /dev/null +++ b/N Digit numbers with digits in increasing order - GFG/n-digit-numbers-with-digits-in-increasing-order.cpp @@ -0,0 +1,56 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +//User function Template for C++ +class Solution +{ +public: + vector ans; + void solve(int s, int n, int str, int size) + { + if(size==n) + { + ans.push_back(str); + return; + } + + for(int i=s; i<=9; i++) + { + str = str * 10 + i; + size++; + solve(i+1, n, str, size); + size--; + str = (str - i)/10; + } + } + vector increasingNumbers(int N) + { + if(N==1) + solve(0, N, 0, 0); + else + solve(1, N, 0, 0); + return ans; + } +}; + +// { Driver Code Starts. +int main() +{ + int t; + cin >> t; + while (t--) + { + int N; + cin>>N; + Solution ob; + vector ans = ob.increasingNumbers(N); + for(auto num : ans){ + cout<< num <<" "; + } + cout< +

Given a weighted directed graph with n nodes and m edges. Nodes are labeled from 0 to n-1, the task is to check if it contains a negative weight cycle or not.
+Note: edges[i] is defined as u, v and weight.

+ +

Example 1:

+ +
Input: n = 3, edges = {{0,1,-1},{1,2,-2},
+{2,0,-3}}
+Output: 1
+Explanation: The graph contains negative weight
+cycle as 0->1->2->0 with weight -1,-2,-3.
+
+ +

Example 2:

+ +
Input: n = 3, edges = {{0,1,-1},{1,2,-2},
+{2,0,3}}
+Output: 0
+Explanation: The graph does not contain any
+negative weight cycle.
+
+ +

 

+ +

Your Task:
+You don't need to read or print anyhting. Your task is to complete the function isNegativeWeightCycle() which takes n and edges as input paramater and returns 1 if graph contains negative weight cycle otherwise returns 0.

+ +

Expected Time Complexity: O(n*m)
+Expected Space Compelxity: O(n)

+ +

Constraints:
+1 <= n <= 100
+1 <= m <= n*(n-1)
, where m is the total number of Edges in the directed graph.

+

+ \ No newline at end of file diff --git a/Negative weight cycle - GFG/negative-weight-cycle.cpp b/Negative weight cycle - GFG/negative-weight-cycle.cpp new file mode 100644 index 0000000..e03e9ef --- /dev/null +++ b/Negative weight cycle - GFG/negative-weight-cycle.cpp @@ -0,0 +1,44 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution { +public: + int isNegativeWeightCycle(int n, vector>edges){ + vector dis(n,1e6); + dis[0]=0; + for(int i=1;i> tc; + while(tc--){ + int n, m; + cin >> n >> m; + vector>edges; + for(int i = 0; i < m; i++){ + int x, y, z; + cin >> x >> y >> z; + edges.push_back({x,y,z}); + } + Solution obj; + int ans = obj.isNegativeWeightCycle(n, edges); + cout << ans <<"\n"; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Next Permutation - GFG/README.md b/Next Permutation - GFG/README.md new file mode 100644 index 0000000..381abbc --- /dev/null +++ b/Next Permutation - GFG/README.md @@ -0,0 +1,32 @@ +# Next Permutation +## Medium +
+

Implement the next permutation, which rearranges the list of numbers into Lexicographically next greater permutation of list of numbers. If such arrangement is not possible, it must be rearranged to the lowest possible order i.e. sorted in an ascending order. You are given an list of numbers arr[ ] of size N.

+ +

Example 1:

+ +
Input: N = 6
+arr = {1, 2, 3, 6, 5, 4}
+Output: {1, 2, 4, 3, 5, 6}
+Explaination: The next permutation of the 
+given array is {1, 2, 4, 3, 5, 6}.
+ +

Example 2:

+ +
Input: N = 3
+arr = {3, 2, 1}
+Output: {1, 2, 3}
+Explaination: As arr[] is the last 
+permutation. So, the next permutation 
+is the lowest one.
+ +

Your Task:
+You do not need to read input or print anything. Your task is to complete the function nextPermutation() which takes N and arr[ ] as input parameters and returns a list of numbers containing the next permutation.

+ +

Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(1)

+ +

Constraints:
+1 ≤ N ≤ 10000

+

+
\ No newline at end of file diff --git a/Next Permutation - GFG/next-permutation.cpp b/Next Permutation - GFG/next-permutation.cpp new file mode 100644 index 0000000..db7edf1 --- /dev/null +++ b/Next Permutation - GFG/next-permutation.cpp @@ -0,0 +1,67 @@ +// { Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + + // } Driver Code Ends +// User function Template for C++ + +class Solution{ +public: + vector nextPermutation(int n, vector number){ + int i, j; + + // I) Start from the right most digit and find the first digit that is + // smaller than the digit next to it. + for (i = n-1; i > 0; i--) + if (number[i] > number[i-1]) + break; + + // If no such digit is found, then all digits are in descending order + // means there cannot be a greater number with same set of digits + if (i==0) + { + sort(number.begin() , number.end()); + return number; + } + + // II) Find the smallest digit on right side of (i-1)'th digit that is + // greater than number[i-1] + int x = number[i-1], smallest = i; + for (j = i+1; j < n; j++) + if (number[j] > x && number[j] < number[smallest]) + smallest = j; + + // III) Swap the above found smallest digit with number[i-1] + swap(number[smallest], number[i-1]); + + // IV) Sort the digits after (i-1) in ascending order + sort(number.begin() + i, number.end() ); + + //cout << "Next number with same set of digits is " << number; + + return number; + } +}; + +// { Driver Code Starts. + +int main(){ + int t; + cin>>t; + while(t--){ + int N; + cin>>N; + vector arr(N); + for(int i = 0;i < N;i++) + cin>>arr[i]; + + Solution ob; + vector ans = ob.nextPermutation(N, arr); + for(int u: ans) + cout< +

Given a connected acyclic graph with n nodes and n-1 edges, count the pair of nodes that are at even distance(number of edges) from each other.

+ +


+Example 1:

+ +
Input:
+n = 3
+graph = {{}, {2}, {1, 3}, {2}}
+Output: 1
+Explaination: Here there are three pairs {1,2},{1,3}
+and {2,3} and only {1,3} has even distance between them.
+i.e           1
+             /
+            2
+           /
+          3
+ +


+Example 2:

+ +
Input:
+n = 5
+graph = {{}, {2,4}, {1,3}, {2}, {1,5}, {4}}
+Output: 4
+Explaination: There are four pairs {1,3},{1,5},{2,4}
+and {3,5} which has even distance.
+
+ +


+Your Task:
+You don't need to read input or print anything. Your task is to complete the function countOfNodes() which takes the array graph[] (given as Adjacency list
and its size as input parameters and returns the count of pair of nodes that are at even distance from each other

+ +


+Expected Time Complexity: O(V+E)
+Expected Auxiliary Space: O(V)

+ +


+Constraints:
+1 ≤ n ≤ 104

+

+ \ No newline at end of file diff --git a/Nodes at even distance - GFG/nodes-at-even-distance.cpp b/Nodes at even distance - GFG/nodes-at-even-distance.cpp new file mode 100644 index 0000000..0abe419 --- /dev/null +++ b/Nodes at even distance - GFG/nodes-at-even-distance.cpp @@ -0,0 +1,64 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function Template for C++ + +class Solution{ + public: + int countOfNodes(vector graph[], int n) + { + // code here + vectorvisited(n+1, 0); + queueq; + int red=0,black=0; + q.push(1); + visited[1]=true; + int level=0; + while(!q.empty()) + { + int sz=q.size(); + if(level%2==0)black+=sz; + else red+=sz; + while(sz--){ + int node=q.front(); + q.pop(); + for(int i=0; i>t; + while(t--) + { + int n; + cin >> n; + vectorgraph[n+1]; + for(int i=0;i> u >> v; + graph[u].push_back(v); + graph[v].push_back(u); + } + Solution ob; + cout< +

Find the number of unique words consisting of lowercase alphabets only of length N that can be formed with at-most K contiguous vowels. 

+ +


+Example 1:

+ +
Input:
+N = 2
+K = 0
+Output:
+441
+Explanation:
+Total of 441 unique words are possible
+of length 2 that will have K( =0) vowels
+together, e.g. "bc", "cd", "df", etc are
+valid words while "ab" (with 1 vowel) is
+not a valid word.
+
+
+ +

Example 2:

+ +
Input:
+N = 1
+K = 1
+Output:
+26
+Explanation:
+All the english alphabets including
+vowels and consonants; as atmost K( =1)
+vowel can be taken.
+
+ +


+Your Task:  
+You don't need to read input or print anything. Your task is to complete the function kvowelwords() which takes an Integer N, an intege K and returns the total number of words of size N with atmost K vowels. As the answer maybe to large please return answer modulo 1000000007.

+ +


+Expected Time Complexity: O(N*K)
+Expected Auxiliary Space: O(N*K)

+ +


+Constraints:
+1 ≤ N ≤ 1000

+0 ≤ K ≤ N

+

+ \ No newline at end of file diff --git a/Number of distinct Words with k maximum contiguous vowels - GFG/number-of-distinct-words-with-k-maximum-contiguous-vowels.cpp b/Number of distinct Words with k maximum contiguous vowels - GFG/number-of-distinct-words-with-k-maximum-contiguous-vowels.cpp new file mode 100644 index 0000000..0789e00 --- /dev/null +++ b/Number of distinct Words with k maximum contiguous vowels - GFG/number-of-distinct-words-with-k-maximum-contiguous-vowels.cpp @@ -0,0 +1,86 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + + // } Driver Code Ends +//User function Template for C++ + +class Solution +{ + public: + const int mod = 1e9+7; + + using ll = long long; + int max_K; + int kvowelwords(int N, int K) { + int cnt = 0; + max_K = K; + vector> dp(N+1,vector (K+1,-1)); + + for(int i=0; i<=N; i++){ + for(int j=0; j<=K; j++){ + if(i == 0){ + dp[i][j] = 1; + continue; + } + if(j>0){ + dp[i][j] = (5*dp[i-1][j-1]%mod+21*dp[i-1][K]%mod)%mod; + } + else{ + dp[i][j] = 21*dp[i-1][K]%mod; + } + } + } + return dp[N][K]; + + // ll ans = solve(N,K,dp); + // return (int)ans; + } + + long long solve(int n,int k,vector> &dp){ + + if(n == 0){ + return 1; + } + if(dp[n][k] != -1){ + return dp[n][k]; + } + if(k>0){ + //take oval + ll ans1 = 5*solve(n-1,k-1,dp)%mod; + + //no take oval + + ll ans2 = 21*solve(n-1,max_K,dp)%mod; + + return dp[n][k] = (ans1+ans2)%mod; + } + else{ + //not possible to take oval, broken sequence so can take ovals again + return dp[n][k] = 21*solve(n-1,max_K,dp)%mod; + } + } +}; + + +// { Driver Code Starts. + + +int main() +{ + int t; + cin >> t; + while (t--) + { + int N;int K; + cin >>N>>K; + + Solution ob; + int ans = ob.kvowelwords(N,K); + cout << ans << endl; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Optimal binary search tree - GFG/README.md b/Optimal binary search tree - GFG/README.md new file mode 100644 index 0000000..18f8792 --- /dev/null +++ b/Optimal binary search tree - GFG/README.md @@ -0,0 +1,56 @@ +# Optimal binary search tree +## Medium +
+

Given a sorted array keys[0.. n-1] of search keys and an array freq[0.. n-1] of frequency counts, where freq[i] is the number of searches to keys[i]. Construct a binary search tree of all keys such that the total cost of all the searches is as small as possible.
+Let us first define the cost of a BST. The cost of a BST node is level of that node multiplied by its frequency. Level of root is 1.

+ +


+Example 1:

+ +
Input:
+n = 2
+keys = {10, 12}
+freq = {34, 50}
+Output: 118
+Explaination:
+There can be following two possible BSTs 
+        10                       12
+          \                     / 
+           12                 10
+                              
+The cost of tree I is 34*1 + 50*2 = 134
+The cost of tree II is 50*1 + 34*2 = 118 
+ +


+Example 2:

+ +

+Input:
+N = 3
+keys = {10, 12, 20}
+freq = {34, 8, 50}
+Output: 142
+Explaination: There can be many possible BSTs
+     20
+    /
+   10  
+    \
+     12  
+     
+Among all possible BSTs, 
+cost of this BST is minimum.  
+Cost of this BST is 1*50 + 2*34 + 3*8 = 142
+ +


+Your Task:
+You don't need to read input or print anything. Your task is to complete the function optimalSearchTree() which takes the array keys[], freq[] and their size as input parameters and returns the total cost of all the searches is as small as possible.

+ +


+Expected Time Complexity: O(n3)
+Expected Auxiliary Space: O(n2)

+ +


+Constraints:
+1 ≤ N ≤ 100

+

+
\ No newline at end of file diff --git a/Optimal binary search tree - GFG/optimal-binary-search-tree.cpp b/Optimal binary search tree - GFG/optimal-binary-search-tree.cpp new file mode 100644 index 0000000..14f44cb --- /dev/null +++ b/Optimal binary search tree - GFG/optimal-binary-search-tree.cpp @@ -0,0 +1,58 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function Template for C++ +class Solution { +public: +int dp[101][101]; +int sumfreq(int i, int j, int freq[]) { +int sum = 0; +for (int k = i; k <= j; k++) { +sum += freq[k]; +} +return sum; +} +int optimalBST(int keys[], int freq[], int i, int j) { +if (i > j) +return dp[i][j] = 0; +if (i == j) +return dp[i][j] = freq[i]; +if (dp[i][j] != -1) +return dp[i][j]; +int fsum = sumfreq(i, j, freq); +int min_cost = INT_MAX; +for (int k = i; k <= j; k++) { +int cost = optimalBST(keys, freq, i, k - 1) + optimalBST(keys, freq, k + 1, j); +min_cost = min(min_cost, cost); +} +return dp[i][j] = min_cost + fsum; +} +int optimalSearchTree(int keys[], int freq[], int n) +{ +memset(dp, -1, sizeof(dp)); +return optimalBST(keys, freq, 0, n - 1); +} +}; + +// { Driver Code Starts. +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin >> n; + int keys[n]; + for(int i=0;i>keys[i]; + int freq[n]; + for(int i=0;i>freq[i]; + Solution ob; + cout< +

Given an array arr[] of size N, check if it can be partitioned into two parts such that the sum of elements in both parts is the same.

+ +

Example 1:

+ +
Input: N = 4
+arr = {1, 5, 11, 5}
+Output: YES
+Explaination: 
+The two parts are {1, 5, 5} and {11}.
+
+ +

Example 2:

+ +
Input: N = 3
+arr = {1, 3, 5}
+Output: NO
+Explaination: This array can never be 
+partitioned into two such parts.
+ +


+Your Task:
+You do not need to read input or print anything. Your task is to complete the function equalPartition() which takes the value N and the array as input parameters and returns 1 if the partition is possible. Otherwise, returns 0.

+ +


+Expected Time Complexity: O(N*sum of elements)
+Expected Auxiliary Space: O(N*sum of elements)

+ +


+Constraints:
+1 ≤ N ≤ 100
+1 ≤ arr[i] ≤ 1000

+

+ \ No newline at end of file diff --git a/Partition Equal Subset Sum - GFG/partition-equal-subset-sum.cpp b/Partition Equal Subset Sum - GFG/partition-equal-subset-sum.cpp new file mode 100644 index 0000000..4c01c3a --- /dev/null +++ b/Partition Equal Subset Sum - GFG/partition-equal-subset-sum.cpp @@ -0,0 +1,57 @@ +// { Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + + // } Driver Code Ends +// User function Template for C++ + + +class Solution{ +public: + int dp[101][10001]; +int subset_sum(int n, int arr[], int tgt) { +if (n == 0) +return 0; +if (tgt == 0) +return 1; +if (dp[n][tgt] != -1) +return dp[n][tgt]; +if (arr[n - 1] <= tgt) +return dp[n][tgt] = subset_sum(n - 1, arr, tgt - arr[n - 1]) || subset_sum(n - 1, arr, tgt); +return dp[n][tgt] = subset_sum(n - 1, arr, tgt); +} +int equalPartition(int N, int arr[]) +{ +int sum = 0; +for (int i = 0; i < N; i++ ) +sum += arr[i]; +memset(dp, -1, sizeof(dp)); +if (sum % 2 != 0) +return 0; +else +return subset_sum(N, arr, sum / 2);} +}; + + +// { Driver Code Starts. + +int main(){ + int t; + cin>>t; + while(t--){ + int N; + cin>>N; + int arr[N]; + for(int i = 0;i < N;i++) + cin>>arr[i]; + + Solution ob; + if(ob.equalPartition(N, arr)) + cout<<"YES\n"; + else + cout<<"NO\n"; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Positive Negative Pair - GFG/README.md b/Positive Negative Pair - GFG/README.md new file mode 100644 index 0000000..567a619 --- /dev/null +++ b/Positive Negative Pair - GFG/README.md @@ -0,0 +1,40 @@ +# Positive Negative Pair +## Easy +
+

Given an array of distinct integers, find all the pairs having both negative and positive values of a number in the array.

+ +


+Example 1:

+ +
Input:
+n = 8
+arr[] = {1,3,6,-2,-1,-3,2,7}
+Output: -1 1 -3 3 -2 2
+Explanation: 1, 3 and 2 are present 
+pairwise postive and negative. 6 and 
+7 have no pair.
+
+ +

Example 2:

+ +
Input:
+n = 3
+arr[] = {3,2,1}
+Output: 0
+Explanation: No such pair exists so the 
+output is 0.
+ +


+Your Task:
+You do not need to read input or print anything. Complete the function findPairs() which takes the array A[] and the size of the array, n, as input parameters and returns a list of integers denoting the pairs. The pair that appears first in A[] should appear first in the returning list and within the pair the negative integer should appear before positive integer. Return an empty integer list if no such pair exists.

+ +


+Expected Time Complexity: O(n)
+Expected Auxiliary Space: O(n)

+ +


+Constraints:
+1 <= n <= 106
+-106 <= arr[i] <= 106

+

+
\ No newline at end of file diff --git a/Positive Negative Pair - GFG/positive-negative-pair.cpp b/Positive Negative Pair - GFG/positive-negative-pair.cpp new file mode 100644 index 0000000..5ee111c --- /dev/null +++ b/Positive Negative Pair - GFG/positive-negative-pair.cpp @@ -0,0 +1,69 @@ +// { Driver Code Starts +// Initial function template for C++ + +#include +#include +#include +using namespace std; + + + // } Driver Code Ends +// User function template for C++ + +class Solution{ + public: + //Function to return list containing all the pairs having both + //negative and positive values of a number in the array. + vector findPairs(int arr[], int n) + { + vector ans; + unordered_map m; + for(int i=0;i> t; + while (t--) { + int n; + cin >> n; + int arr[n]; + for (int i = 0; i < n; i++) cin >> arr[i]; + Solution obj; + vector res = obj.findPairs(arr, n); + if(res.size()!=0) + { + for (int i : res) + cout << i << " "; + cout << endl; + } + else + cout<<0< +

There is BST given with root node with key part as integer only. You need to find the inorder successor and predecessor of a given key. In case, if the either of predecessor or successor is not found print -1.

+ +

Input:
+The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains n denoting the number of edges of the BST. The next line contains the edges of the BST. The last line contains the key.

+ +

Output:
+Print the predecessor followed by successor for the given key. If the predecessor or successor is not found print -1.

+ +

Constraints:
+1<=T<=100
+1<=n<=100
+1<=data of node<=100
+1<=key<=100

+ +

Example:
+Input:

+2
+6
+50 30 L 30 20 L 30 40 R 50 70 R 70 60 L 70 80 R
+65
+6
+50 30 L 30 20 L 30 40 R 50 70 R 70 60 L 70 80 R
+100

+ +

Output:
+60 70
+80 -1

+

+ \ No newline at end of file diff --git a/Predecessor and Successor - GFG/predecessor-and-successor.cpp b/Predecessor and Successor - GFG/predecessor-and-successor.cpp new file mode 100644 index 0000000..1c7c749 --- /dev/null +++ b/Predecessor and Successor - GFG/predecessor-and-successor.cpp @@ -0,0 +1,134 @@ +// { Driver Code Starts +// C++ program to find predecessor and successor in a BST +#include +using namespace std; + +// BST Node +struct Node +{ + int key; + struct Node *left; + struct Node *right; + + Node(int x){ + key = x; + left = NULL; + right = NULL; + } +}; + +int key=0; +// This function finds predecessor and successor of key in BST. +// It sets pre and suc as predecessor and successor respectively +void findPreSuc(Node* root, Node*& pre, Node*& suc, int key); + + void insert(struct Node *root,int n1,int n2,char lr) + { + if(root==NULL) + return; + if(root->key==n1) + { + switch(lr) + { + case 'L': root->left=new Node(n2); + break; + case 'R': root->right=new Node(n2); + break; + } + } + else + { + insert(root->left,n1,n2,lr); + insert(root->right,n1,n2,lr); + } + } +// Driver program to test above functions +int main() +{ + /* Let us construct the tree shown in above diagram */ + int t,k; + cin>>t; + while(t--) + { + int n; + cin>>n; + struct Node *root=NULL; + Node *pre=NULL; + Node *suc=NULL; + while(n--) + { + char lr; + int n1,n2; + cin>>n1>>n2; + cin>>lr; + if(root==NULL) + { + root=new Node(n1); + switch(lr){ + case 'L': root->left=new Node(n2); + break; + case 'R': root->right=new Node(n2); + break; + } + } + else + { + insert(root,n1,n2,lr); + } + } + // Inorder(root); + //Node * target =ptr; + //printkdistanceNode(root, target, k); + //cout<>key; + findPreSuc(root, pre, suc, key); + if (pre != NULL) + cout << pre->key; + else + cout << "-1"; + + if (suc != NULL) + cout <<" "<key<key == key) +{ + findPreSuc(root->left,pre,suc,key); + findPreSuc(root->right,pre,suc,key); +} +else if(root->key > key) +{ + suc = root; + findPreSuc(root->left,pre,suc,key); +} +else +{ + pre = root; + findPreSuc(root->right,pre,suc,key); +} + +} \ No newline at end of file diff --git a/Queries on Strings - GFG/README.md b/Queries on Strings - GFG/README.md new file mode 100644 index 0000000..1492765 --- /dev/null +++ b/Queries on Strings - GFG/README.md @@ -0,0 +1,35 @@ +# Queries on Strings +## Medium +
+

Given a string str you have to answer several queries on that string. In each query you will be provided two values L and R and you have to find the number of distinct characters in the sub string from index L to index R (inclusive) of the original string.

+ +

Example 1:

+ +
Input: str = "abcbaed",
+Query = {{1,4},{2,4},{1,7}}
+Output: {3,2,5}
+Explanation: For the first query distinct 
+characters from [1, 4] are a, b and c.
+For the second query distinct characters from
+[2, 4] are b and c.
+For the third query distinct characters from
+[1, 7] are a, b, c, d and e.
+
+ +

 

+ +

Your Task:
+You don't need to read or print anyhting. Your task is to complete the function SolveQueries() which takes str and Query as input parameter and returns a list containing answer for each query.

+ +

Expected Time Complexity: O(max(26*length of str, 26 * No of queries))
+Expected Space Complexity: O(26 * length of str)

+ +

Constraints:
+1 <= |str| <= 105
+1 <= No of Queries <= 104
+1 <= Li <= Ri <= |str|

+

+
\ No newline at end of file diff --git a/Queries on Strings - GFG/queries-on-strings.cpp b/Queries on Strings - GFG/queries-on-strings.cpp new file mode 100644 index 0000000..d3f431a --- /dev/null +++ b/Queries on Strings - GFG/queries-on-strings.cpp @@ -0,0 +1,48 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution { +public: + vectorSolveQueris(string str, vector>Query){ + vector dp[26]; + for(int i = 0;ires; + for(auto a : Query){ + int ct = 0; + for(int i =0;i<26;i++){ + if(dp[i].size() == 0) continue; + auto t = lower_bound(dp[i].begin(), dp[i].end(), a[0]); + if(*t >= a[0] && *t <= a[1]) ct++; + } + res.push_back(ct); + } + return res; + // Code here + } +}; + +// { Driver Code Starts. +int main(){ + int tc; + cin >> tc; + while(tc--){ + string str; + cin >> str; + int q; + cin >> q; + vector>Query; + for(int i = 0; i < q; i++){ + int l, r; + cin >> l >> r; + Query.push_back({l, r}); + } + Solution obj; + vector ans = obj.SolveQueris(str, Query); + for(auto i: ans)cout << i << " "; + cout << "\n"; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Queue using two Stacks - GFG/README.md b/Queue using two Stacks - GFG/README.md new file mode 100644 index 0000000..dd8eeef --- /dev/null +++ b/Queue using two Stacks - GFG/README.md @@ -0,0 +1,57 @@ +# Queue using two Stacks +## Easy +
+

Implement a Queue using 2 stacks s1 and s2 .
+A Query Q is of 2 Types
+(i) 1 x (a query of this type means  pushing 'x' into the queue)
+(ii) 2   (a query of this type means to pop element from queue and print the poped element)

+ +

Example 1:

+ +
Input:
+5
+1 2 1 3 2 1 4 2
+
+Output: 
+2 3
+
+Explanation: 
+In the first testcase
+1 2 the queue will be {2}
+1 3 the queue will be {2 3}
+2   poped element will be 2 the queue 
+    will be {3}
+1 4 the queue will be {3 4}
+2   poped element will be 3.
+
+ +

Example 2:

+ +
Input:
+4
+1 2 2 2 1 4
+
+Output: 
+2 -1
+
+Explanation: 
+In the second testcase 
+1 2 the queue will be {2}
+2   poped element will be 2 and 
+    then the queue will be empty
+2   the queue is empty and hence -1
+1 4 the queue will be {4}.
+ +

Your Task:
+You are required to complete the two methods push which take one argument an integer 'x' to be pushed into the queue and pop which returns a integer poped out from other queue(-1 if the queue is empty). The printing is done automatically by the driver code.

+ +

Expected Time Complexity : O(1) for push() and O(N) for pop() or O(N) for push() and O(1) for pop()  
+Expected Auxilliary Space : O(1).

+ +

Constraints:
+1 <= Q <= 100
+1 <= x <= 100

+ +

Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.

+

+
\ No newline at end of file diff --git a/Queue using two Stacks - GFG/queue-using-two-stacks.cpp b/Queue using two Stacks - GFG/queue-using-two-stacks.cpp new file mode 100644 index 0000000..adad3f5 --- /dev/null +++ b/Queue using two Stacks - GFG/queue-using-two-stacks.cpp @@ -0,0 +1,82 @@ +// { Driver Code Starts +#include + +using namespace std; + +class StackQueue{ +private: + stack s1; + stack s2; +public: + void push(int B); + int pop(); + +}; +int main() +{ + + int T; + cin>>T; + while(T--) + { + StackQueue *sq = new StackQueue(); + + int Q; + cin>>Q; + while(Q--){ + int QueryType=0; + cin>>QueryType; + if(QueryType==1) + { + int a; + cin>>a; + sq->push(a); + }else if(QueryType==2){ + cout<pop()<<" "; + + } + } + cout< s1; + stack s2; +public: + void push(int); + int pop(); +}; */ + +//Function to push an element in queue by using 2 stacks. +void StackQueue :: push(int x) +{ + s1.push(x); + return; +} + +//Function to pop an element from queue by using 2 stacks. +int StackQueue :: pop() +{ + if(s1.empty()){ + return -1; + } + while(s1.empty() == false){ + s2.push(s1.top()); + s1.pop(); + } + int val = s2.top(); + s2.pop(); + while(s2.empty() == false){ + s1.push(s2.top()); + s2.pop(); + } + return val; +} \ No newline at end of file diff --git a/Rank The Permutations - GFG/README.md b/Rank The Permutations - GFG/README.md new file mode 100644 index 0000000..a55029a --- /dev/null +++ b/Rank The Permutations - GFG/README.md @@ -0,0 +1,44 @@ +# Rank The Permutations +## Medium +
+

Given a string, find the rank of the string amongst its permutations sorted lexicographically. 
+
+Example 1:

+ +
Input:
+S = "abc"
+Output:
+1
+Explanation:
+The order permutations with letters 
+'a', 'c', and 'b' : 
+abc
+acb
+bac
+bca
+cab
+cba
+ +

Example 2:

+ +
Input:
+S = "acb"
+Output:
+2
+
+ +


+Your Task:
+You don't need to read input or print anything. Your task is to complete the function findRank() which takes the string S as input parameter and returns the rank of the string amongst its permutations.

+It is guaranteed no characters are repeated in the string.

+ +


+Expected Time Complexity: O(|S|*26)
+Expected Auxiliary Space: O(|S|)

+Note: |S| represents the length of string S.

+ +


+Constraints:
+1 ≤ |S| ≤ 18

+

+
\ No newline at end of file diff --git a/Rank The Permutations - GFG/rank-the-permutations.cpp b/Rank The Permutations - GFG/rank-the-permutations.cpp new file mode 100644 index 0000000..d740a81 --- /dev/null +++ b/Rank The Permutations - GFG/rank-the-permutations.cpp @@ -0,0 +1,49 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +//User function template for C++ + +class Solution{ + public: + long long findRank(string str) + { + long long fact[19]; + fact[0]=1; + fact[1]=1; + long long n=str.size(),ans=0; + + for(int i=2;i<=18;i++) + { + fact[i]=i*fact[i-1]; + } + + for(int i=0;istr[j]) + count++; + } + + ans+=count*fact[n-1-i]; + } + + return ans+1; + } +}; + +// { Driver Code Starts. +int main(){ + int T; + cin>>T; + while(T--){ + string s; + cin>>s; + Solution obj; + long long ans = obj.findRank(s); + cout< +

Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
+Note: In a path, no cell can be visited more than one time.

+ +

Example 1:

+ +
Input:
+N = 4
+m[][] = {{1, 0, 0, 0},
+         {1, 1, 0, 1}, 
+         {1, 1, 0, 0},
+         {0, 1, 1, 1}}
+Output:
+DDRDRR DRDDRR
+Explanation:
+The rat can reach the destination at 
+(3, 3) from (0, 0) by two paths - DRDDRR 
+and DDRDRR, when printed in sorted order 
+we get DDRDRR DRDDRR.
+ +
Example 2:
+ +
Input:
+N = 2
+m[][] = {{1, 0},
+         {1, 0}}
+Output:
+-1
+Explanation:
+No path exists and destination cell is 
+blocked.
+
+ +

Your Task:  
+You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
 
+Note: In case of no path, return an empty list. The driver will output "-1" automatically.

+ +

Expected Time Complexity: O((3N^2)).
+Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.

+ +

Constraints:
+2 ≤ N ≤ 5
+0 ≤ m[i][j] ≤ 1

+

+ \ No newline at end of file diff --git a/Rat in a Maze Problem - I - GFG/rat-in-a-maze-problem-i.cpp b/Rat in a Maze Problem - I - GFG/rat-in-a-maze-problem-i.cpp new file mode 100644 index 0000000..ce31e96 --- /dev/null +++ b/Rat in a Maze Problem - I - GFG/rat-in-a-maze-problem-i.cpp @@ -0,0 +1,97 @@ +// { Driver Code Starts +// Initial template for C++ + +#include +using namespace std; + + + // } Driver Code Ends +// User function template for C++ + +class Solution{ + public: + + void solve(vector& ans,int row,int col,vector> &m, int n,string a) + { + if(row == n-1 && col == n-1 && m[row][col] == 1) + { + ans.push_back(a); + return; + } + + if(row>=0 && row=0 && col0 && m[row][col-1] == 1) + { + a += "L"; + solve(ans,row,col-1,m,n,a); + a.pop_back(); + } + + if(col < n-1 && m[row][col+1] == 1) + { + a += "R"; + solve(ans,row,col+1,m,n,a); + a.pop_back(); + } + if(row>0 &&m[row-1][col] == 1) + { + a += "U"; + solve(ans,row-1,col,m,n,a); + a.pop_back(); + } + + + + m[row][col] = 1; + } + + } + + + + vector findPath(vector> &m, int n) { + // Your code goes here + vector ans; + string a = ""; + solve(ans,0,0,m,n,a); + // sort(ans.begin(),ans.end()); + return ans; + } +}; + + + + +// { Driver Code Starts. + +int main() { + int t; + cin >> t; + while (t--) { + int n; + cin >> n; + vector> m(n, vector (n,0)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + cin >> m[i][j]; + } + } + Solution obj; + vector result = obj.findPath(m, n); + if (result.size() == 0) + cout << -1; + else + for (int i = 0; i < result.size(); i++) cout << result[i] << " "; + cout << endl; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Rearrange Geek and his Classmates - GFG/README.md b/Rearrange Geek and his Classmates - GFG/README.md new file mode 100644 index 0000000..be1d414 --- /dev/null +++ b/Rearrange Geek and his Classmates - GFG/README.md @@ -0,0 +1,46 @@ +# Rearrange Geek and his Classmates +## Easy +
+

Geek and his classmates are playing a prank on their Computer Science teacher. They change places every time the teacher turns to look at the blackboard. 

+ +

Each of the N students in the class can be identified by a unique roll number X and each desk has a number i associated with it. Only one student can sit on one desk. 
+Each time the teacher turns her back, a student with roll number X sitting on desk number i gets up and takes the place of the student with roll number i.

+ +

If the current position of N students in the class is given to you in an array, such that i is the desk number and a[i] is the roll number of the student sitting on the desk, can you modify a[ ] to represent the next position of all the students ? 

+ +


+Example 1:

+ +
Input:
+N = 6
+a[] = {0, 5, 1, 2, 4, 3}
+Output: 0 3 5 1 4 2
+Explanation: After reshuffling, the modified 
+position of all the students would be 
+{0, 3, 5, 1, 4, 2}.
+ +


+Example 2:

+ +
Input:
+N = 5
+a[] = {4, 3, 2, 1, 0}
+Output: 0 1 2 3 4 
+Explanation: After reshuffling, the modified 
+position of all the students would be 
+{0, 1, 2, 3, 4}.
+ +


+Your Task:  
+You dont need to read input or print anything. Complete the function prank() which takes the array a[ ] and its size N as input parameters and modifies the array in-place to reflect the new arrangement.

+ +


+Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(1)

+ +

Constraints:
+1 ≤ N ≤ 105
+0 ≤ a[i] ≤ N-1

+

+
\ No newline at end of file diff --git a/Rearrange Geek and his Classmates - GFG/rearrange-geek-and-his-classmates.cpp b/Rearrange Geek and his Classmates - GFG/rearrange-geek-and-his-classmates.cpp new file mode 100644 index 0000000..985ed45 --- /dev/null +++ b/Rearrange Geek and his Classmates - GFG/rearrange-geek-and-his-classmates.cpp @@ -0,0 +1,49 @@ +// { Driver Code Starts +//Initial template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function template for C++ + + +class Solution { + public: + void prank(long long a[], int n){ + + int ar2[n]; + for(int i=0;i>t; + while(t--){ + int n; + cin>>n; + long long a[n]; + for(int i = 0 ;i>a[i]; + } + Solution ob; + ob.prank(a,n); + + for(int i = 0;i +

Given an IP address, remove leading zeros from the IP address. Note that our IP address here can be a little different. It can have numbers greater than 255. Also, it does not necessarily have 4 numbers. The count can be lesser/more.

+ +

Example 1:

+ +
Input:
+S = "100.020.003.400"
+Output: 100.20.3.400
+Explanation: The leading zeros are removed
+from 20 and 3.
+
+ +

Example 2:

+ +
Input: 
+S = "100.000.010.0999"
+Output: 100.0.10.999
+Explanation: The leading zeros are removed
+from 0, 10 and 999.
+
+ +


+Your Task:
+You don't need to read input or print anything. Your task is to complete the function newIPAdd() which takes the string S representing the IP address as input and returns a string representing the resultant IP address. 

+ +


+Expected Time Complexity: O(|S|).
+Expected Auxiliary Space: O(|S|).

+ +


+Constraints:
+1<=|S|<=1000

+ +

 

+

+ \ No newline at end of file diff --git a/Remove leading zeros from an IP address - GFG/remove-leading-zeros-from-an-ip-address.cpp b/Remove leading zeros from an IP address - GFG/remove-leading-zeros-from-an-ip-address.cpp new file mode 100644 index 0000000..f7045ce --- /dev/null +++ b/Remove leading zeros from an IP address - GFG/remove-leading-zeros-from-an-ip-address.cpp @@ -0,0 +1,58 @@ +// { Driver Code Starts +#include +using namespace std; + + + // } Driver Code Ends + +class Solution +{ + public: + void solve(string &temp) + { + while(temp.size()!=1) + { + if(temp[0]=='0') + temp.erase(temp.begin()); + else + break; + } + } + string newIPAdd (string s) + { + int left=0; + int right=0; + string ans=""; + while(right> t; + while (t--) + { + string s; cin >> s; + Solution ob; + cout < +

Given an even number N (greater than 2), return two prime numbers whose sum will be equal to given number. There are several combinations possible. Print only the pair whose minimum value is the smallest among all the minimum values of pairs and print the minimum element first.

+ +

NOTE: A solution will always exist, read Goldbachs conjecture. 

+ +

Example 1:

+ +
Input: N = 74
+Output: 3 71
+Explaination: There are several possibilities 
+like 37 37. But the minimum value of this pair 
+is 3 which is smallest among all possible 
+minimum values of all the pairs.
+ +

Example 2:

+ +
Input: 4
+Output: 2 2
+Explaination: This is the only possible 
+prtitioning of 4.
+ +

Your Task:
+You do not need to read input or print anything. Your task is to complete the function primeDivision() which takes N as input parameter and returns the partition satisfying the condition.

+ +

Expected Time Complexity: O(N*log(logN))
+Expected Auxiliary Space: O(N)

+ +

Constraints:
+1 ≤ N ≤ 104  

+

+ \ No newline at end of file diff --git a/Return two prime numbers - GFG/return-two-prime-numbers.cpp b/Return two prime numbers - GFG/return-two-prime-numbers.cpp new file mode 100644 index 0000000..2b6ebf1 --- /dev/null +++ b/Return two prime numbers - GFG/return-two-prime-numbers.cpp @@ -0,0 +1,46 @@ +// { Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + + // } Driver Code Ends +// User function Template for C++ +class Solution{ +public: + bool prime(int a) + { + int k=sqrt(a); + for(int i=2;i<=k;i++) + { + if(a%i==0) + return false; + } + return true; + } + vector primeDivision(int N){ + for(int i=2;i<=N-2;i++) + { + if(prime(i) && prime(N-i)) + { + return {i,N-i}; + } + } + return {}; + } +}; +// { Driver Code Starts. + +int main(){ + int t; + cin>>t; + while(t--){ + int N; + cin>>N; + + Solution ob; + vector ans = ob.primeDivision(N); + cout< +

Given an integer K and a queue of integers, we need to reverse the order of the first K elements of the queue, leaving the other elements in the same relative order.

+ +

Only following standard operations are allowed on queue.

+ +
    +
  • enqueue(x) : Add an item x to rear of queue
  • +
  • dequeue() : Remove an item from front of queue
  • +
  • size() : Returns number of elements in queue.
  • +
  • front() : Finds front item.
  • +
+ +

Example 1:

+ +
Input:
+5 3
+1 2 3 4 5
+
+Output: 
+3 2 1 4 5
+
+Explanation: 
+After reversing the given
+input from the 3rd position the resultant
+output will be 3 2 1 4 5.
+
+
+ +

Example 2:

+ +
Input:
+4 4
+4 3 2 1
+
+Output: 
+1 2 3 4
+
+Explanation: 
+After reversing the given
+input from the 4th position the resultant
+output will be 1 2 3 4.
+ +

Your Task:
+Complete the provided function modifyQueue that takes queue and k as parameters and returns a modified queue. The printing is done automatically by the driver code.

+ +

Expected TIme Complexity : O(n)
+Expected Auxilliary Space : O(n)

+ +

Constraints:
+1 <= N <= 1000
+1 <= K <= N

+ +

Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.

+

+ \ No newline at end of file diff --git a/Reverse First K elements of Queue - GFG/reverse-first-k-elements-of-queue.cpp b/Reverse First K elements of Queue - GFG/reverse-first-k-elements-of-queue.cpp new file mode 100644 index 0000000..f9e3514 --- /dev/null +++ b/Reverse First K elements of Queue - GFG/reverse-first-k-elements-of-queue.cpp @@ -0,0 +1,55 @@ +// { Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; +queue modifyQueue(queue q, int k); +int main() { + int t; + cin >> t; + while (t-- > 0) { + int n, k; + cin >> n >> k; + queue q; + while (n-- > 0) { + int a; + cin >> a; + q.push(a); + } + queue ans = modifyQueue(q, k); + while (!ans.empty()) { + int a = ans.front(); + ans.pop(); + cout << a << " "; + } + cout << endl; + } +}// } Driver Code Ends + + +// User function Template for C++ + +// Function to reverse first k elements of a queue. +queue modifyQueue(queue q, int k) { + // add code here. + if(k > q.size()) return q; + stack s; + queue q1; + for(int i = 0 ; i < k ; i++){ + s.push(q.front()); + q.pop(); + } + while(!q.empty()){ + q1.push(q.front()); + q.pop(); + } + while(!s.empty()){ + q.push(s.top()); + s.pop(); + } + while(!q1.empty()){ + q.push(q1.front()); + q1.pop(); + } + return q; +} \ No newline at end of file diff --git a/Reverse words in a given string - GFG/README.md b/Reverse words in a given string - GFG/README.md new file mode 100644 index 0000000..a0dc126 --- /dev/null +++ b/Reverse words in a given string - GFG/README.md @@ -0,0 +1,41 @@ +# Reverse words in a given string +## Easy +
+

Given a String S, reverse the string without reversing its individual words. Words are separated by dots.

+ +

Example 1:

+ +
Input:
+S = i.like.this.program.very.much
+Output: much.very.program.this.like.i
+Explanation: After reversing the whole
+string(not individual words), the input
+string becomes
+much.very.program.this.like.i
+
+ +

Example 2:

+ +
Input:
+S = pqr.mno
+Output: mno.pqr
+Explanation: After reversing the whole
+string , the input string becomes
+mno.pqr
+
+ +


+Your Task:
+You dont need to read input or print anything. Complete the function reverseWords() which takes string S as input parameter and returns a string containing the words in reversed order. Each word in the returning string should also be separated by '.' 

+ +


+Expected Time Complexity: O(|S|)
+Expected Auxiliary Space: O(|S|)

+ +


+Constraints:
+1 <= |S| <= 2000

+ +

 

+

+
\ No newline at end of file diff --git a/Reverse words in a given string - GFG/reverse-words-in-a-given-string.cpp b/Reverse words in a given string - GFG/reverse-words-in-a-given-string.cpp new file mode 100644 index 0000000..48717b0 --- /dev/null +++ b/Reverse words in a given string - GFG/reverse-words-in-a-given-string.cpp @@ -0,0 +1,48 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends + +class Solution +{ + public: + string reverseWords(string S) + { + vector p; + string temp=""; + for(int i=0;i> t; + while (t--) + { + string s; + cin >> s; + Solution obj; + cout< +

Given a square matrix[][] of size N x N. The task is to rotate it by 90 degrees in an anti-clockwise direction without using any extra space.

+ +

Example 1:

+ +
Input:
+N = 3
+matrix[][] = [[1 2 3],
+              [4 5 6],
+              [7 8 9]]
+Output:
+3 6 9 
+2 5 8 
+1 4 7
+
+ +

Your Task:
+You only need to implement the given function rotate(). Do not read input, instead use the arguments given in the function. 

+ +

Expected Time Complexity: O(N*N)
+Expected Auxiliary Space: O(1)

+ +

Constraints:
+1 ≤ N ≤ 50
+1 <= matrix[][] <= 100

+ +

 

+

+ \ No newline at end of file diff --git a/Rotate by 90 degree - GFG/rotate-by-90-degree.cpp b/Rotate by 90 degree - GFG/rotate-by-90-degree.cpp new file mode 100644 index 0000000..a520284 --- /dev/null +++ b/Rotate by 90 degree - GFG/rotate-by-90-degree.cpp @@ -0,0 +1,67 @@ +// { Driver Code Starts +//Initial template for C++ + +#include +using namespace std; +void rotate (vector >& matrix); + + + // } Driver Code Ends +//User function template for C++ + +/* matrix : given input matrix, you are require + to change it in place without using extra space */ +void rotate (vector >& matrix); + + + // } Driver Code Ends +//User function template for C++ + +/* matrix : given input matrix, you are require + to change it in place without using extra space */ +void rotate(vector >& matrix) +{ +int n = (int) matrix.size(); +int m = (int) matrix[0].size(); +for(int i = 0; i < n; i++){ + +reverse(matrix[i].begin(), matrix[i].end()); +} +for(int i = 0; i < n; i++){ +for(int j = i; j < m; j++){ +swap(matrix[i][j], matrix[j][i]); +} + +} +} + + +// { Driver Code Starts. + +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + vector > matrix(n); + for(int i=0; i>matrix[i][j]; + } + rotate(matrix); + for (int i = 0; i < n; ++i) + { + for(int j=0; j +

Given two strings, one is a text string and other is a pattern string. The task is to print the indexes of all the occurences of pattern string in the text string. For printing, Starting Index of a string should be taken as 1.

+ +

Example 1:

+ +
Input:
+S = "batmanandrobinarebat", pat = "bat"
+Output: 1 18
+Explanation: The string "bat" occurs twice
+in S, one starts are index 1 and the other
+at index 18. 
+
+ +

​Example 2:

+ +
Input: 
+S = "abesdu", pat = "edu"
+Output: -1
+Explanation: There's not substring "edu"
+present in S.
+
+ +


+Your Task:
+You don't need to read input or print anything. Your task is to complete the function search() which takes the string S and the string pat as inputs and returns an array denoting the start indices (1-based) of substring pat in the string S. 
+Note: You don't need to return -1 yourself when there are no possible answers, just return an empty list.

+ +


+Expected Time Complexity: O(|S|).
+Expected Auxiliary Space: O(|S|).

+ +


+Constraints:
+1 ≤ |S| ≤ 105
+1 ≤ |pat| ≤ |S|

+

+ \ No newline at end of file diff --git a/Search Pattern (Z-algorithm) - GFG/search-pattern-zalgorithm.cpp b/Search Pattern (Z-algorithm) - GFG/search-pattern-zalgorithm.cpp new file mode 100644 index 0000000..cc60796 --- /dev/null +++ b/Search Pattern (Z-algorithm) - GFG/search-pattern-zalgorithm.cpp @@ -0,0 +1,56 @@ +// { Driver Code Starts +#include +using namespace std; + + + // } Driver Code Ends +class Solution +{ + public: + vector search(string pat, string txt){ + string s = pat + "#" + txt; + int n = s.length(); + vector lps(n); + for(int i=1;i0 and s[j]!=s[i]){ + j = lps[j-1]; + } + if(s[i]==s[j]){ + j++; + } + lps[i] = j; + } + vector ans; + for(int i=pat.length()+1;i> t; + while (t--) + { + string S, pat; + cin >> S >> pat; + Solution ob; + vector res = ob.search(pat, S); + if(res.size()==0) + cout<<"-1 "; + else + for (int i : res) + cout << i << " "; + cout << endl; + } + return 0; +} + + // } Driver Code Ends \ No newline at end of file diff --git a/Search a node in BST - GFG/README.md b/Search a node in BST - GFG/README.md new file mode 100644 index 0000000..9414a35 --- /dev/null +++ b/Search a node in BST - GFG/README.md @@ -0,0 +1,49 @@ +# Search a node in BST +## Easy +
+

Given a Binary Search Tree and a node value X, find if the node with value X is present in the BST or not.

+ +


+Example 1:

+ +
Input:         2
+                \
+                 81 
+               /    \ 
+             42      87 
+              \       \ 
+               66      90 
+              / 
+            45
+X = 87
+Output: 1
+Explanation: As 87 is present in the
+given nodes , so the output will be
+1.
+ +

Example 2:

+ +
Input:      6
+             \ 
+              8 
+             / \ 
+            7   9
+X = 11
+Output: 0
+Explanation: As 11 is not present in 
+the given nodes , so the output will
+be 0.
+ +


+Your Task:
+You don't need to read input or print anything. Complete the function search()which returns true if the node with value x is present in the BSTelse returns false.

+ +


+Expected Time Complexity: O(Height of the BST)
+Expected Auxiliary Space: O(1).

+ +


+Constraints:
+1 <= Number of nodes <= 105

+

+
\ No newline at end of file diff --git a/Search a node in BST - GFG/search-a-node-in-bst.cpp b/Search a node in BST - GFG/search-a-node-in-bst.cpp new file mode 100644 index 0000000..cba34d4 --- /dev/null +++ b/Search a node in BST - GFG/search-a-node-in-bst.cpp @@ -0,0 +1,68 @@ +// { Driver Code Starts +#include + +using namespace std; + +struct Node { + int data; + Node *right; + Node *left; + + Node(int x) { + data = x; + right = NULL; + left = NULL; + } +}; + +bool search(Node *root, int x); + +Node *insert(Node *tree, int val) { + Node *temp = NULL; + if (tree == NULL) return new Node(val); + + if (val < tree->data) { + tree->left = insert(tree->left, val); + } else if (val > tree->data) { + tree->right = insert(tree->right, val); + } + + return tree; +} + +int main() { + int T; + cin >> T; + while (T--) { + Node *root = NULL; + + int N; + cin >> N; + for (int i = 0; i < N; i++) { + int k; + cin >> k; + root = insert(root, k); + } + + int s; + cin >> s; + + cout << search(root, s); + cout << endl; + } +} +// } Driver Code Ends + + +// Function to search a node in BST. +bool search(Node* root, int x) { + // Your code here + if(!root)return false; + if(root->data == x)return true; + if(x > root->data) + { + return search(root->right,x); + } + else + return search(root->left,x); +} diff --git a/Shortest Path between Cities - GFG/README.md b/Shortest Path between Cities - GFG/README.md new file mode 100644 index 0000000..1191240 --- /dev/null +++ b/Shortest Path between Cities - GFG/README.md @@ -0,0 +1,51 @@ +# Shortest Path between Cities +## Medium +
+

Geek lives in a special city where houses are arranged in a hierarchial manner. Starting from house number 1, each house leads to two more houses.  
+1 leads to 2 and 3. 
+2 leads to 4 and 5. 
+3 leads to 6 and 7. and so on. 
+Given the house numbers on two houses x and y, find the length of the shortest path between them. 

+ +


+Example 1:

+ +
Input:
+x = 2, y = 6
+Output: 3
+Explanation:
+              1
+          /      \
+        /          \
+       2             3
+     /   \         /   \
+    4     5       6     7         
+   / \   / \     / \   / \
+  8  9  10 11   12 13 14 15
+
+The length of the shortest path between 2 
+and 6 is 3. ie 2-> 1-> 3-> 6.
+ +


+Example 2:

+ +
Input:
+x = 8, y = 10
+Output: 4
+Explanation: 8-> 4-> 2-> 5-> 10
+The length of the shortest path between 8 
+and 10 is 4. 
+ +


+Your Task:
+You don't need to read input or print anything. Complete the function shortestPath() which takes integers x and y as input parameters and returns the length of the shortest path from x to y.

+ +


+Expected Time Complexity: O(log(max(x,y)))
+Expected Auxiliary Space: O(1)

+ +


+Constraints: 
+1 <= x,y <= 109

+

+
\ No newline at end of file diff --git a/Shortest Path between Cities - GFG/shortest-path-between-cities.cpp b/Shortest Path between Cities - GFG/shortest-path-between-cities.cpp new file mode 100644 index 0000000..2a93b12 --- /dev/null +++ b/Shortest Path between Cities - GFG/shortest-path-between-cities.cpp @@ -0,0 +1,35 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function Template for C++ + +class Solution{ +public: + int shortestPath( int x, int y){ + int ans=0; + while(x!=y){ + ans++; + x>y?x/=2:y/=2; + } + return ans; + } +}; + +// { Driver Code Starts. +int main() +{ + int t; + cin>>t; + while(t--) + { + int x,y; + cin>>x>>y; + Solution ob; + cout<< ob.shortestPath(x,y) << endl; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Shortest Unique prefix for every word - GFG/README.md b/Shortest Unique prefix for every word - GFG/README.md new file mode 100644 index 0000000..8b22e46 --- /dev/null +++ b/Shortest Unique prefix for every word - GFG/README.md @@ -0,0 +1,47 @@ +# Shortest Unique prefix for every word +## Hard +
+

Given an array of words, find all shortest unique prefixes to represent each word in the given array. Assume that no word is prefix of another.

+ +

Example 1:

+ +
Input: 
+N = 4
+arr[] = {"zebra", "dog", "duck", "dove"}
+Output: z dog du dov
+Explanation: 
+z => zebra 
+dog => dog 
+duck => du 
+dove => dov 
+
+ +

Example 2:

+ +
Input: 
+N = 3
+arr[] =  {"geeksgeeks", "geeksquiz",
+                       "geeksforgeeks"};
+Output: geeksg geeksq geeksf
+Explanation: 
+geeksgeeks => geeksg 
+geeksquiz => geeksq 
+geeksforgeeks => geeksf
+ +
Your task:
+ +
You don't have to read input or print anything. Your task is to complete the function findPrefixes() which takes the array of strings and it's size N as input and returns a list of shortest unique prefix for each word
+ +
 
+ +
Expected Time Complexity: O(N*length of each word)
+ +
Expected Auxiliary Space: O(N*length of each word)
+ +
 
+ +
Constraints:
+ +
1 ≤ N, Length of each word ≤ 1000
+

+
\ No newline at end of file diff --git a/Shortest Unique prefix for every word - GFG/shortest-unique-prefix-for-every-word.cpp b/Shortest Unique prefix for every word - GFG/shortest-unique-prefix-for-every-word.cpp new file mode 100644 index 0000000..dc7dc91 --- /dev/null +++ b/Shortest Unique prefix for every word - GFG/shortest-unique-prefix-for-every-word.cpp @@ -0,0 +1,106 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function Template for C++ + +struct Node{ + Node* links[26]; + bool flag=false; + int cnt=0; + + bool containskey(char ch){ + return links[ch-'a']!=NULL; + } + void put(char ch,Node* node){ + links[ch-'a']=node; + } + Node* get(char ch){ + return links[ch-'a']; + } + void setEnd(){ + flag=true; + } + bool isEnd(){ + return flag; + } +}; +class Trie{ + private: + Node* root; + public: + Trie(){ + root=new Node(); + } + void insert(string word){ + Node* node=root; + for(int i=0;icontainskey(word[i])){ + node->put(word[i],new Node()); + } + node=node->get(word[i]); + node->cnt++; + } + node->setEnd(); + } + string un_prefix(string word){ + Node* node=root; + string pre=""; + for(int i=0;icnt==1)break; + pre+=word[i]; + node=node->get(word[i]); + } + return pre; + } +}; +class Solution +{ + public: + vector findPrefixes(string arr[], int n) + { + //code here + Trie* trie=new Trie(); + vectorans(n); + for(int i=0;iinsert(arr[i]); + } + for(int i=0;iun_prefix(arr[i]); + } + return ans; + } +}; + +// { Driver Code Starts. + +int main() +{ + int t; + cin >> t; + while (t--) + { + int n; + cin >> n; + + string arr[n]; + for (int i = 0; i < n; i++) + cin >> arr[i]; + + Solution ob; + vector ans = ob.findPrefixes(arr, n); + + for (int i = 0; i < ans.size(); i++) + cout << ans[i] <<" "; + + + cout << "\n"; + + } + + return 0; +} + // } Driver Code Ends \ No newline at end of file diff --git a/Smallest Absolute Difference - GFG/README.md b/Smallest Absolute Difference - GFG/README.md new file mode 100644 index 0000000..5f6d27d --- /dev/null +++ b/Smallest Absolute Difference - GFG/README.md @@ -0,0 +1,47 @@ +# Smallest Absolute Difference +## Medium +
+

Given an array of size N containing positive integers n and a number k,The absolute difference between values at indices i and j is |a[i] – a[j]|. There are n*(n-1)/2 such pairs and you have to print the kth smallest absolute difference among all these pairs.

+ +

Example 1:

+ +
Input : 
+N = 4
+A[] = {1, 2, 3, 4}
+k = 3
+Output : 
+1 
+Explanation :
+The possible absolute differences are :
+{1, 2, 3, 1, 2, 1}.
+The 3rd smallest value among these is 1.
+ +
 
+ +
Example 2:
+ +
Input : 
+N = 2
+A[] = {10, 10}
+k = 1
+Output :
+0
+ +


+Your Task:  
+You don't need to read input or print anything. Your task is to complete the function kthDiff() which takes the array A[], its size N and an integer k as inputs and returns the kth smallest absolute difference among all these pairs.

+ +

 

+ +

Expected Time Complexity: O( N. (Log(N))2 )
+Expected Auxiliary Space: O(Log(N))

+ +

 

+ +

Constraints:
+1<=N<=105
+1<=a[i]<=105
+1 <= k <= n*(n-1)/2

+

+
\ No newline at end of file diff --git a/Smallest Absolute Difference - GFG/smallest-absolute-difference.cpp b/Smallest Absolute Difference - GFG/smallest-absolute-difference.cpp new file mode 100644 index 0000000..e8e3ae6 --- /dev/null +++ b/Smallest Absolute Difference - GFG/smallest-absolute-difference.cpp @@ -0,0 +1,52 @@ +// { Driver Code Starts +#include +using namespace std; + +int kthDiff(int a[], int n, int k); + +// Driver code +int main() { + int t, i; + int k; + cin >> t; + while (t--) { + int n; + cin >> n; + int a[n]; + for (i = 0; i < n; i++) { + cin >> a[i]; + } + cin >> k; + + cout << kthDiff(a, n, k) << endl; + } + return 0; +} +// } Driver Code Ends + +int count(int a[], int n, int mid) +{ + int number=0; + for(int i=0;i +

Given an array A of N length. We need to calculate the next greater element for each element in a given array. If the next greater element is not available in a given array then we need to fill -10000000 at that index place.

+ +

Example 1:

+ +
Input : arr[] = {13, 6, 7, 12}
+Output : _ 7 12 13 
+Explanation:
+Here, at index 0, 13 is the greatest value 
+in given array and no other array element 
+is greater from 13. So at index 0 we fill 
+'-10000000'.
+
+ +


+Example 2:

+ +
Input : arr[] = {6, 3, 9, 8, 10, 2, 1, 15, 7} 
+Output :  7 6 10 9 15 3 2 _ 8
+Explanation: Here, at index 7, 15 is the greatest
+value in given array and no other array element is
+greater from 15. So at index 7 we fill '-10000000'.
+
+ +

 

+ +

Your Task:
+This is a function problem. The input is already taken care of by the driver code. You only need to complete the function greaterElement() that takes an array (arr), sizeOfArray (n), and return an array that displays the next greater element to element at that index. The driver code takes care of the printing.

+ +

Expected Time Complexity: O(N*LOG(N)).
+Expected Auxiliary Space: O(N).

+ +

 

+ +

Constraints:
+1 ≤ N ≤ 105
+-106 ≤ Ai ≤ 106

+ +

 

+

+ \ No newline at end of file diff --git a/Smallest greater elements in whole array - GFG/smallest-greater-elements-in-whole-array.cpp b/Smallest greater elements in whole array - GFG/smallest-greater-elements-in-whole-array.cpp new file mode 100644 index 0000000..a2555b0 --- /dev/null +++ b/Smallest greater elements in whole array - GFG/smallest-greater-elements-in-whole-array.cpp @@ -0,0 +1,52 @@ +// { Driver Code Starts +#include +using namespace std; + +int* greaterElement(int arr[], int n); + +int main() +{ + int t,n; + cin>>t; + while(t--) + { + cin>>n; + int arr[n]; + for(int i=0;i>arr[i]; + } + int *b; + b = greaterElement(arr, n); + for(int i=0;is; + for(int i=0;i +

Given a string S consisting of the characters 0, 1 and 2. Your task is to find the length of the smallest substring of string S that contains all the three characters 0, 1 and 2. If no such substring exists, then return -1.

+ +

Example 1:

+ +
Input:
+S = "01212"
+Output:
+3
+Explanation:
+The substring 012 is the smallest substring
+that contains the characters 0, 1 and 2.
+
+ +

Example 2:

+ +
Input: 
+S = "12121"
+Output:
+-1
+Explanation: 
+As the character 0 is not present in the
+string S, therefor no substring containing
+all the three characters 0, 1 and 2
+exists. Hence, the answer is -1 in this case.
+ +

Your Task:
+Complete the function smallestSubstring() which takes the string S as input, and returns the length of the smallest substring of string S that contains all the three characters 0, 1 and 2.

+ +

Expected Time Complexity: O(|S|)
+Expected Auxiliary Space: O(1)

+ +

Constraints:
+1 ≤ |S| ≤ 105
+All the characters of String S lies in the set {'0', '1', '2'}

+

+ \ No newline at end of file diff --git a/Smallest window containing 0, 1 and 2 - GFG/smallest-window-containing-0-1-and-2.cpp b/Smallest window containing 0, 1 and 2 - GFG/smallest-window-containing-0-1-and-2.cpp new file mode 100644 index 0000000..db5c8ce --- /dev/null +++ b/Smallest window containing 0, 1 and 2 - GFG/smallest-window-containing-0-1-and-2.cpp @@ -0,0 +1,52 @@ +// { Driver Code Starts +#include +using namespace std; + + + // } Driver Code Ends +// User function Template for C++ + +class Solution { + public: + int smallestSubstring(string S) { + if(S.size() < 3){ + return -1; + } + int arr[3] = {0, 0, 0}; + int i = 0; + int j = 1; + arr[S[i] - '0']++; + int ans = INT_MAX; + int n = S.size(); + while(j < n){ + arr[S[j] - '0']++; + while(arr[S[i] - '0'] > 1 && i < j){ + arr[S[i] - '0']--; + i++; + } + if(arr[0] > 0 && arr[1] > 0 && arr[2] > 0){ + ans = min(ans, (arr[0] + arr[1] + arr[2])); + } + j++; + } + if(ans == INT_MAX){ + return -1; + } + return ans; + } +}; + + +// { Driver Code Starts. + +int main() { + int t; + cin >> t; + while (t--) { + string S; + cin >> S; + Solution ob; + cout << ob.smallestSubstring(S); + cout << endl; + } +} // } Driver Code Ends \ No newline at end of file diff --git a/Sort a stack - GFG/README.md b/Sort a stack - GFG/README.md new file mode 100644 index 0000000..c545817 --- /dev/null +++ b/Sort a stack - GFG/README.md @@ -0,0 +1,30 @@ +# Sort a stack +## Easy +
+

Given a stack, the task is to sort it such that the top of the stack has the greatest element.

+ +

Example 1:

+ +
Input:
+Stack: 3 2 1
+Output: 3 2 1
+
+ +

Example 2:

+ +
Input:
+Stack: 11 2 32 3 41
+Output: 41 32 11 3 2
+ +

Your Task: 
+You don't have to read input or print anything. Your task is to complete the function sort() which sorts the elements present in the given stack. (The sorted stack is printed by the driver's code by popping the elements of the stack.)

+ +

Expected Time Complexity: O(N*N)
+Expected Auxilliary Space: O(N) recursive.

+ +

Constraints:
+1<=N<=100
+
+Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.

+

+
\ No newline at end of file diff --git a/Sort a stack - GFG/sort-a-stack.cpp b/Sort a stack - GFG/sort-a-stack.cpp new file mode 100644 index 0000000..89ed936 --- /dev/null +++ b/Sort a stack - GFG/sort-a-stack.cpp @@ -0,0 +1,74 @@ +// { Driver Code Starts +#include +using namespace std; + +class SortedStack{ +public: + stack s; + void sort(); +}; + +void printStack(stack s) +{ + while (!s.empty()) + { + printf("%d ", s.top()); + s.pop(); + } + printf("\n"); +} + +int main() +{ +int t; +cin>>t; +while(t--) +{ + SortedStack *ss = new SortedStack(); + int n; + cin>>n; + for(int i=0;i>k; + ss->s.push(k); + } + ss->sort(); + printStack(ss->s); +} +}// } Driver Code Ends + + +/*The structure of the class is +class SortedStack{ +public: + stack s; + void sort(); +}; +*/ + +/* The below method sorts the stack s +you are required to complete the below method */ +void SortedStack :: sort() +{ + //Your code here + priority_queue pq; + stack s1; + while(!s.empty()) + { + pq.push(s.top()); + s.pop(); + } + while(!pq.empty()) + { + s1.push(pq.top()); + pq.pop(); + + } + while(!s1.empty()) + { + s.push(s1.top()); + s1.pop(); + } +} + diff --git a/Sort an array of 0s, 1s and 2s - GFG/README.md b/Sort an array of 0s, 1s and 2s - GFG/README.md new file mode 100644 index 0000000..721ba5b --- /dev/null +++ b/Sort an array of 0s, 1s and 2s - GFG/README.md @@ -0,0 +1,42 @@ +# Sort an array of 0s, 1s and 2s +## Easy +
+

Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order.

+ +


+Example 1:

+ +
Input: 
+N = 5
+arr[]= {0 2 1 2 0}
+Output:
+0 0 1 2 2
+Explanation:
+0s 1s and 2s are segregated 
+into ascending order.
+ +

Example 2:

+ +
Input: 
+N = 3
+arr[] = {0 1 0}
+Output:
+0 0 1
+Explanation:
+0s 1s and 2s are segregated 
+into ascending order.
+ +


+Your Task:
+You don't need to read input or print anything. Your task is to complete the function sort012() that takes an array arr and N as input parameters and sorts the array in-place.

+ +


+Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(1)

+ +


+Constraints:
+1 <= N <= 10^6
+0 <= A[i] <= 2

+

+
\ No newline at end of file diff --git a/Sort an array of 0s, 1s and 2s - GFG/sort-an-array-of-0s-1s-and-2s.cpp b/Sort an array of 0s, 1s and 2s - GFG/sort-an-array-of-0s-1s-and-2s.cpp new file mode 100644 index 0000000..b16a3df --- /dev/null +++ b/Sort an array of 0s, 1s and 2s - GFG/sort-an-array-of-0s-1s-and-2s.cpp @@ -0,0 +1,48 @@ +// { Driver Code Starts +#include +using namespace std; + + + + // } Driver Code Ends +class Solution +{ + public: + void sort012(int a[], int n) + { + // coode here + sort(a,a+n); + return ; + } + +}; + +// { Driver Code Starts. +int main() { + + int t; + cin >> t; + + while(t--){ + int n; + cin >>n; + int a[n]; + for(int i=0;i> a[i]; + } + + Solution ob; + ob.sort012(a, n); + + for(int i=0;i +

Given an array of integers, sort the array (in descending order) according to count of set bits in binary representation of array elements. 

+ +

Note: For integers having same number of set bits in their binary representation, sort according to their position in the original array i.e., a stable sort.

+ +
 
+ +
Example 1:
+ +
Input: 
+arr[] = {5, 2, 3, 9, 4, 6, 7, 15, 32};
+Output:
+15 7 5 3 9 6 2 4 32
+Explanation:
+The integers in their binary
+representation are:
+15 - 1111
+7  - 0111
+5  - 0101
+3  - 0011
+9  - 1001
+6  - 0110
+2  - 0010
+4  - 0100
+32 - 10000
+hence the non-increasing sorted order is:
+{15}, {7}, {5, 3, 9, 6}, {2, 4, 32}
+ +
 
+ +
Example 2:
+ +
Input: 
+arr[] = {1, 2, 3, 4, 5, 6};
+Output: 
+3 5 6 1 2 4
+Explanation:
+3  - 0011
+5  - 0101
+6  - 0110
+1  - 0001
+2  - 0010
+4  - 0100
+hence the non-increasing sorted order is
+{3, 5, 6}, {1, 2, 4}
+ +


+
+Your Task:
+You don't need to print anything, printing is done by the driver code itself. You just need to complete the function sortBySetBitCount() which takes the array arr[] and its size N as inputs and sort the array arr[] inplace. Use of extra space is prohibited.

+ +

Expected Time Complexity: O(N.log(N))
+Expected Auxiliary Space: O(1)

+ +


+Constraints:
+1 ≤ N ≤ 105
+1 ≤ A[i] ≤ 106

+

+ \ No newline at end of file diff --git a/Sort by Set Bit Count - GFG/sort-by-set-bit-count.cpp b/Sort by Set Bit Count - GFG/sort-by-set-bit-count.cpp new file mode 100644 index 0000000..2aec93d --- /dev/null +++ b/Sort by Set Bit Count - GFG/sort-by-set-bit-count.cpp @@ -0,0 +1,54 @@ +// { Driver Code Starts +#include +using namespace std; + + + // } Driver Code Ends +class Solution{ + public: + static bool compare(const int &a, const int &b) + { + int ca=0; + int cb=0; + int A=a,B=b; + while(A) + { + A=A&(A-1); + ca++; + } + while(B) + { + B=B&(B-1); + cb++; + } + return ca>cb; + + } + void sortBySetBitCount(int arr[], int n) + { + stable_sort(arr,arr+n,compare); + } +}; + +// { Driver Code Starts. + +int main() +{ + int t; + cin>>t; + while(t--){ + int n; + cin>>n; + int arr[n]; + for(int i=0;i>arr[i]; + } + Solution ob; + ob.sortBySetBitCount(arr, n); + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + cout << endl; + } + return 0; +} + // } Driver Code Ends \ No newline at end of file diff --git a/Special Matrix - GFG/README.md b/Special Matrix - GFG/README.md new file mode 100644 index 0000000..40682dd --- /dev/null +++ b/Special Matrix - GFG/README.md @@ -0,0 +1,40 @@ +# Special Matrix +## Medium +
+

You are given a matrix having n rows and m columns. The special property of this matrix is that some of the cells of this matrix are blocked i.e. they cannot be reached. Now you have to start from the cell (1,1) and reach the end (n,m) provided during the journey you can move horizontally right from the current cell or vertically down from the current cell. Can you answer the number of ways you can traverse the matrix obeying the above constraints starting from (1,1) and ending at (n,m).

+ +

Example 1:

+ +
Input: n = 3, m = 3, k = 2,
+blocked_cells = {{1,2},{3,2}}.
+Output: 1
+Explanation: There is only one path from
+(1,1) to(3,3) which is (1,1)->(2,1)->(2,2)->
+(2,3)->(3,3).
+
+ +

Example 2:

+ +
Input: n = 5, m = 5, k = 1,
+blocked_cells = {{5,5}}
+Output: 0
+Explanation: There is no path to reach at 
+(5,5) beacuse (5,5) is blocked.
+
+ +

 

+ +

Your Task:
+You don't need to read or print anything, Your task is to complete the function FindWays() which takes n, m and blocked_cells as input parameter and returns total number of ways to reach at (n, m) modulo 109 + 7.

+ +

Expected Time Complexity: O(n*m)
+Expected Space Complexity: O(n*m)

+ +

Constraints:
+1 <= n, m <= 500
+1 <= k <= n*m 

+

+
\ No newline at end of file diff --git a/Special Matrix - GFG/special-matrix.cpp b/Special Matrix - GFG/special-matrix.cpp new file mode 100644 index 0000000..1cb621c --- /dev/null +++ b/Special Matrix - GFG/special-matrix.cpp @@ -0,0 +1,53 @@ +// { Driver Code Starts + +#include +using namespace std; + + // } Driver Code Ends + +class Solution { +private: + int mod = 1000000007; + int dp[1000][1000]; +public: + int FindWaysHelper(int n, int m, vector> grid, int i, int j) + { + if(i < 0 || i >= n || j < 0 || j >= m || grid[i][j] == 1) return 0; + if(i == n-1 && j == m-1) return 1; + grid[i][j] = 1; + if(dp[i][j] != -1) return dp[i][j]; + return dp[i][j] = (FindWaysHelper(n, m, grid, i, j+1) + FindWaysHelper(n, m, grid, i+1, j))%mod; + } + + + int FindWays(int n, int m, vector>blocked_cells){ + vector> grid(n, vector (m, 0)); + memset(dp, -1, sizeof(dp)); + for(int i = 0; i < blocked_cells.size(); i++) + { + grid[blocked_cells[i][0] - 1][blocked_cells[i][1] - 1] = 1; + } + int result = FindWaysHelper(n, m, grid, 0, 0); + return result; + } +}; + +// { Driver Code Starts. +int main(){ + int tc; + cin >> tc; + while(tc--){ + int n, m, k; + cin >> n >> m >> k; + vector>blocked_cells; + for(int i = 0; i < k; i++){ + int x, y; + cin >> x >> y; + blocked_cells.push_back({x, y}); + } + Solution obj; + int ans = obj.FindWays(n, m, blocked_cells); + cout << ans <<'\n'; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Spidey Sense - GFG/README.md b/Spidey Sense - GFG/README.md new file mode 100644 index 0000000..fbfc8c9 --- /dev/null +++ b/Spidey Sense - GFG/README.md @@ -0,0 +1,52 @@ +# Spidey Sense +## Medium +
+

Spiderman is stuck in a difficult situation. His arch-enemy the Green Goblin has planted several of his infamous Pumpkin Bombs in various locations in a building. Help Spiderman activate his Spidey Sense and identify the impact zones. 
+He has a blueprint of the building which is a M x N matrix that is filled with the characters O, B, and W where: 
+O represents an open space.
+B represents a bomb.
+W represents a wall.
+You have to replace all of the Os (open spaces) in the matrix with their shortest distance from a bomb without being able to go through any walls. Also, replace the bombs with 0 and walls with -1 in the resultant matrix. If no path exists between a bomb and an open space replace the corresponding 'O' with -1.

+ +

Example 1:

+ +
Input: N = 3, M = 3
+A[] = {{O, O, O}, 
+       {W, B, B}, 
+       {W, O, O}}
+Output: {{2, 1, 1}, 
+         {-1, 0, 0},  
+         {-1, 1, 1}}
+Explanation: The walls at (1,0) and (2,0) 
+are replaced by -1. The bombs at (1,1) and 
+(1,2) are replaced by 0. The impact zone 
+for the bomb at (1,1) includes open spaces 
+at index (0,0), (0,1) and (2,1) with distance 
+from bomb calculated as 2,1,1 respectively.
+The impact zone for the bomb at (1,2) 
+includes open spaces at index (0,3) and (2,2) 
+with distance from bomb calculated as 1,1 
+respectively.
+
+ +


+Example 2:

+ +
IInput: N = 2, M = 2
+A[] = {{O, O},
+       {O, O}} 
+Output: {{-1, -1}
+         {-1, -1}
+
+ +

Your Task:  
+You don't need to read input or print anything. Complete the function findDistance() which takes the matrix A[], M, and N as input parameters and the resultant matrix

+ +

Expected Time Complexity: O(M*N)
+Expected Auxiliary Space: O(M*N)

+ +


+Constraints:
+1 ≤ N*M ≤ 106

+

+
\ No newline at end of file diff --git a/Spidey Sense - GFG/spidey-sense.cpp b/Spidey Sense - GFG/spidey-sense.cpp new file mode 100644 index 0000000..e731c61 --- /dev/null +++ b/Spidey Sense - GFG/spidey-sense.cpp @@ -0,0 +1,78 @@ +// { Driver Code Starts + +#include +using namespace std; + + // } Driver Code Ends +class Solution{ + + public: + vector > findDistance(vector >& matrix, int M, int N) + { + // Your code goes here + int di[] = {0,0,-1,1}; + int dj[] = {-1,1,0,0}; + queue> q; + vector> ans(M,vector (N,-1));//filling with -1 reduces steps at last + for(int i=0; i 0){ + int i = q.front().first, j = q.front().second; q.pop(); + for(int idx=0; idx<4; idx++){ + int next_i = i+di[idx],next_j = j+dj[idx]; + if(next_i>=0 && next_j >=0 && next_i> t; + while(t--) + { + int M,N; + cin>>M; + cin>>N; + + vector > matrix(M); + for(int i=0; i>matrix[i][j]; + } + + vector >result; + Solution obj; + result = obj.findDistance(matrix, M,N); + for(int i=0; i +

Implement a Stack using two queues q1 and q2.

+ +

Example 1:

+ +
Input:
+push(2)
+push(3)
+pop()
+push(4)
+pop()
+Output: 3 4
+Explanation:
+push(2) the stack will be {2}
+push(3) the stack will be {2 3}
+pop()   poped element will be 3 the 
+        stack will be {2}
+push(4) the stack will be {2 4}
+pop()   poped element will be 4  
+
+ +

Example 2:

+ +
Input:
+push(2)
+pop()
+pop()
+push(3)
+Output: 2 -1
+ +

Your Task:

+ +

Since this is a function problem, you don't need to take inputs. You are required to complete the two methods push() which takes an integer 'x' as input denoting the element to be pushed into the stack and pop() which returns the integer poped out from the stack(-1 if the stack is empty).

+ +

Expected Time Complexity: O(1) for push() and O(N) for pop() (or vice-versa).
+Expected Auxiliary Space: O(1) for both push() and pop().

+ +

Constraints:
+1 <= Number of queries <= 100
+1 <= values of the stack <= 100

+

+ \ No newline at end of file diff --git a/Stack using two queues - GFG/stack-using-two-queues.cpp b/Stack using two queues - GFG/stack-using-two-queues.cpp new file mode 100644 index 0000000..f80c893 --- /dev/null +++ b/Stack using two queues - GFG/stack-using-two-queues.cpp @@ -0,0 +1,79 @@ +// { Driver Code Starts +#include +using namespace std; + +class QueueStack{ +private: + queue q1; + queue q2; +public: + void push(int); + int pop(); +}; + + +int main() +{ + int T; + cin>>T; + while(T--) + { + QueueStack *qs = new QueueStack(); + + int Q; + cin>>Q; + while(Q--){ + int QueryType=0; + cin>>QueryType; + if(QueryType==1) + { + int a; + cin>>a; + qs->push(a); + }else if(QueryType==2){ + cout<pop()<<" "; + + } + } + cout< q1; + queue q2; +public: + void push(int); + int pop(); +}; + */ + +//Function to push an element into stack using two queues. +void QueueStack :: push(int x) +{ + // Your Code + q1.push(x); + int rem = q1.size()-1; + while(rem--) + { + q1.push(q1.front()); + q1.pop(); + } +} + +//Function to pop an element from stack using two queues. +int QueueStack :: pop() +{ + // Your Code + if(!q1.empty()) + { + int ans = q1.front(); + q1.pop(); + return ans; + } + return -1; +} diff --git a/Subset Sums - GFG/README.md b/Subset Sums - GFG/README.md new file mode 100644 index 0000000..1741c2c --- /dev/null +++ b/Subset Sums - GFG/README.md @@ -0,0 +1,43 @@ +# Subset Sums +## Basic +
+

+

Given a list arr of N integers, print sums of all subsets in it.

+ +

Note: Return all the element is increasing order.

+ +

Example 1:

+ +
Input:
+N = 2
+arr[] = {2, 3}
+Output:
+0 2 3 5
+Explanation:
+When no elements is taken then Sum = 0.
+When only 2 is taken then Sum = 2.
+When only 3 is taken then Sum = 3.
+When element 2 and 3 are taken then 
+Sum = 2+3 = 5.
+ +

Example 2:

+ +
Input:
+N = 3
+arr = {5, 2, 1}
+Output:
+0 1 2 3 5 6 7 8
+
+ +

Your Task:  
+You don't need to read input or print anything. Your task is to complete the function subsetSums() which takes a list/vector and an integer N as an input parameter and return the list/vector of all the subset sums.

+ +

Expected Time Complexity: O(2N)
+Expected Auxiliary Space: O(2N)

+ +

Constraints:
+1 <= N <= 15
+0 <= arr[i] <= 104

+
+

+
\ No newline at end of file diff --git a/Subset Sums - GFG/subset-sums.cpp b/Subset Sums - GFG/subset-sums.cpp new file mode 100644 index 0000000..48f4180 --- /dev/null +++ b/Subset Sums - GFG/subset-sums.cpp @@ -0,0 +1,52 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution +{ +public: + void helper(vector arr,vector& ans,int N,int i,int sum) + { + if(i>=N) + { + ans.push_back(sum); + return; + } + + helper(arr,ans,N,i+1,sum+arr[i]); + helper(arr,ans,N,i+1,sum); + } + + vector subsetSums(vector arr, int N) + { + vector ans; + helper(arr,ans,N,0,0); + sort(ans.begin(),ans.end()); + return ans; + } +}; + +// { Driver Code Starts. +int main() +{ + int t; + cin >> t; + while (t--) + { + int N; + cin>>N; + vector arr(N); + for(int i = 0 ; i < N ; i++){ + cin >> arr[i]; + } + Solution ob; + vector ans = ob.subsetSums(arr,N); + sort(ans.begin(),ans.end()); + for(auto sum : ans){ + cout<< sum<<" "; + } + cout< +

Given a set of positive integers, find all its subsets.

+ +

Example 1 :

+ +
Input : 
+array = {1, 2, 3}
+Output :
+// this space denotes null element. 
+1
+1 2
+1 2 3
+1 3
+2
+2 3
+3
+Explanation: 
+The following are the subsets 
+of the array {1, 2, 3}.
+ +

Example 2 :

+ +
Input :
+array = {1, 2}
+Output :
+
+1 
+1 2
+2
+Explanation :
+The following are the 
+subsets of {1, 2}.
+ +
Your task :
+ +
You don't have to read input or print anything. Your task is to complete the function subsets() which takes the array of integers as input and returns the list of list containing the subsets of the given set of numbers in lexicographical order.
+ +
 
+ +
Expected Time Complexity : O(2^n)))
+ +
Expected Auxiliary Space : O(2^n*length of each subset)
+ +
 
+ +
Constraints :
+ +
1 <= n <= 20
+ +
1 <= arr[i] <=10
+

+ \ No newline at end of file diff --git a/Subsets - GFG/subsets.cpp b/Subsets - GFG/subsets.cpp new file mode 100644 index 0000000..31def1e --- /dev/null +++ b/Subsets - GFG/subsets.cpp @@ -0,0 +1,76 @@ +// { Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + + // } Driver Code Ends +//User function Template for C++ + +class Solution +{ + vector> subsetsRes; //global vector declaration + + + + //recursive helper function + void generate(vector& A, int i, vector& nums){ + + if(i==A.size()){ + subsetsRes.push_back(nums); + return; + } // base case + + generate(A, i+1, nums); // Case in which element considered is not added + + nums.push_back(A[i]); + generate(A, i+1, nums); // Case in which element considered is added + nums.pop_back(); //backtrack + } + public: + vector> subsets(vector& A) + { + //code here + vector nums; + generate(A, 0, nums); + sort(subsetsRes.begin(), subsetsRes.end()); + return subsetsRes; + } +}; + +// { Driver Code Starts. + +int main() +{ + int t; + cin >> t; + + while (t--) + { + int n, x; + cin >> n; + + vector array; + for (int i = 0; i < n; i++) + { + cin >> x; + array.push_back(x); + } + + + Solution ob; + vector > res = ob.subsets(array); + + // Print result + for (int i = 0; i < res.size(); i++) { + for (int j = 0; j < res[i].size(); j++) + cout << res[i][j] << " "; + cout << endl; + } + + + } + + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Swap Kth nodes from ends - GFG/README.md b/Swap Kth nodes from ends - GFG/README.md new file mode 100644 index 0000000..4f37f83 --- /dev/null +++ b/Swap Kth nodes from ends - GFG/README.md @@ -0,0 +1,50 @@ +# Swap Kth nodes from ends +## Medium +
+

Given a singly linked list of size N, and an integer K. You need to swap the Kth node from the beginning and Kth node from the end of the linked list. Swap the nodes through the links. Do not change the content of the nodes.

+ +

 

+ +

Example 1:

+ +
Input:
+N = 4,  K = 1
+value[] = {1,2,3,4}
+Output: 1
+Explanation: Here K = 1, hence after
+swapping the 1st node from the beginning
+and end thenew list will be 4 2 3 1.
+
+ +

 

+ +

Example 2:

+ +
Input:
+N = 5,  K = 7
+value[] = {1,2,3,4,5}
+Output: 1
+Explanation: K > N. Swapping is invalid. 
+Return the head node as it is.
+
+ +

 

+ +

Your Task: 
+You do not need to read input or print anything. The task is to complete the function swapkthnode(), which has takes head of link list, N and K as input parameters and returns the new head.
+The generated output will be 1 if you are able to complete your task. 

+ +

 

+ +

Expected Time Complexity: O(n)
+Expected Auxillary space Complexity: O(1)

+ +

 

+ +

Constraints:
+1 <= N <= 103
+1 <= K <= 103

+ +

 

+

+
\ No newline at end of file diff --git a/Swap Kth nodes from ends - GFG/swap-kth-nodes-from-ends.cpp b/Swap Kth nodes from ends - GFG/swap-kth-nodes-from-ends.cpp new file mode 100644 index 0000000..b5ad4d0 --- /dev/null +++ b/Swap Kth nodes from ends - GFG/swap-kth-nodes-from-ends.cpp @@ -0,0 +1,138 @@ +// { Driver Code Starts +#include + +using namespace std; + +struct Node { + int data; + struct Node *next; + Node(int x) { + data = x; + next = NULL; + } +}; + + + +Node *swapkthnode(Node* head, int num, int K); + +void addressstore(Node **arr, Node* head) +{ + Node* temp = head; + int i = 0; + while(temp){ + arr[i] = temp; + i++; + temp = temp->next; + } +} + +bool check(Node ** before, Node **after, int num, int K) +{ + if(K > num) + return 1; + return (before[K-1] == after[num - K]) && (before[num-K] == after[K-1]); +} + +int main() +{ + int T; + cin>>T; + while(T--){ + int num, K , firstdata; + cin>>num>>K; + int temp; + cin>>firstdata; + Node* head = new Node(firstdata); + Node* tail = head; + for(int i = 0; i>temp; + tail->next = new Node(temp); + tail = tail->next; + } + + Node *before[num]; + addressstore(before, head); + + head = swapkthnode(head, num, K); + + Node *after[num]; + addressstore(after, head); + + if(check(before, after, num, K)) + cout<<1< num) + return head; + + if(K > L) + swap(K, L); + + Node *first, *second, *prev1, *prev2; + + prev1 = prev2 = head; + + for(int i=0; inext; + + for(int i=0; inext; + + first = prev1->next; + second = prev2->next; + + if(K == 1) + { + first = head; + head = second; + second->next = first->next; + prev2->next = first; + first->next = nullptr; + + return head; + } + + if(K+1 == L) + { + prev1->next = second; + first->next = second->next; + second->next = first; + + return head; + } + + Node *temp = second->next; + + prev1->next = second; + second->next = first->next; + + prev2->next = first; + first->next = temp; + + return head; +} diff --git a/The Painter's Partition Problem-II - GFG/README.md b/The Painter's Partition Problem-II - GFG/README.md new file mode 100644 index 0000000..a49ec49 --- /dev/null +++ b/The Painter's Partition Problem-II - GFG/README.md @@ -0,0 +1,49 @@ +# The Painter's Partition Problem-II +## Hard +
+

Dilpreet wants to paint his dog's home that has n boards with different lengths. The length of ith board is given by arr[i] where arr[] is an array of n integers. He hired k painters for this work and each painter takes 1 unit time to paint 1 unit of the board. 

+ +

The problem is to find the minimum time to get this job done if all painters start together with the constraint that any painter will only paint continuous boards, say boards numbered {2,3,4} or only board {1} or nothing but not boards {2,4,5}.

+ +


+Example 1:

+ +
Input:
+n = 5
+k = 3
+arr[] = {5,10,30,20,15}
+Output: 35
+Explanation: The most optimal way will be:
+Painter 1 allocation : {5,10}
+Painter 2 allocation : {30}
+Painter 3 allocation : {20,15}
+Job will be done when all painters finish
+i.e. at time = max(5+10, 30, 20+15) = 35
+ +

Example 2:

+ +
Input:
+n = 4
+k = 2
+arr[] = {10,20,30,40}
+Output: 60
+Explanation: The most optimal way to paint:
+Painter 1 allocation : {10,20,30}
+Painter 2 allocation : {40}
+Job will be complete at time = 60
+ +


+Your task:
+Your task is to complete the function minTime() which takes the integers n and k and the array arr[] as input and returns the minimum time required to paint all partitions.

+ +


+Expected Time Complexity: O(n log m) , m = sum of all boards' length
+Expected Auxiliary Space: O(1)

+ +


+Constraints:
+1 ≤ n ≤ 105
+1 ≤ k ≤ 105
+1 ≤ arr[i] ≤ 105

+

+
\ No newline at end of file diff --git a/The Painter's Partition Problem-II - GFG/the-painters-partition-problem-ii.cpp b/The Painter's Partition Problem-II - GFG/the-painters-partition-problem-ii.cpp new file mode 100644 index 0000000..e23a112 --- /dev/null +++ b/The Painter's Partition Problem-II - GFG/the-painters-partition-problem-ii.cpp @@ -0,0 +1,83 @@ +// { Driver Code Starts +// driver code + +#include +using namespace std; + + + // } Driver Code Ends +//User function template for C++ + +class Solution +{ + public: + + bool isPossible(long long int mid,int arr[],int n,int k) + { + int count = 1; + int sum = 0; + for(int i=0;i mid) + { + sum = arr[i]; + count++; + if(count>k) + return false; + } + else + sum += arr[i]; + } + return true; + } + + long long minTime(int arr[], int n, int k) + { + // code here + // return minimum time + int low = INT_MIN; + long long int high = 0; + + for(int i=0;i>t; + while(t--) + { + int k,n; + cin>>k>>n; + + int arr[n]; + for(int i=0;i>arr[i]; + Solution obj; + cout << obj.minTime(arr, n, k) << endl; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Transfiguration - GFG/README.md b/Transfiguration - GFG/README.md new file mode 100644 index 0000000..0fbc848 --- /dev/null +++ b/Transfiguration - GFG/README.md @@ -0,0 +1,46 @@ +# Transfiguration +## Medium +
+

Professor McGonagall teaches transfiguration at Hogwarts. She has given Harry the task of changing himself into a cat. She explains that the trick is to analyze your own DNA and change it into the DNA of a cat. The transfigure spell can be used to pick any one character from the DNA string, remove it and insert it in the beginning. 
+Help Harry calculates minimum number of times he needs to use the spell to change himself into a cat.

+ +

Example 1:

+ +
Input: 
+A = "GEEKSFORGEEKS" 
+B = "FORGEEKSGEEKS"
+Output: 3
+Explanation:The conversion can take place 
+in 3 operations:
+1. Pick 'R' and place it at the front, 
+   A="RGEEKSFOGEEKS"
+2. Pick 'O' and place it at the front, 
+   A="ORGEEKSFGEEKS"
+3. Pick 'F' and place it at the front, 
+   A="FORGEEKSGEEKS"
+ +

Example 2:

+ +
Input: 
+A = "ABC" 
+B = "BCA"
+Output: 2
+Explanation: The conversion can take place 
+in 2 operations:
+1. Pick 'C' and place it at the front, 
+   A = "CAB"
+2. Pick 'B' and place it at the front, 
+   A = "BCA"
+
+ +

Your Task:  
+You don't need to read input or print anything. Complete the function transfigure() which takes strings A and B as input parameters and returns the minimum number of spells needed. If it is not possible to convert A to B then return -1.

+ +

Expected Time Complexity: O(max(|A|, |B|))
+Expected Auxiliary Space: O(1)

+ +

Constraints:
+1 ≤ |A|, |B| ≤ 105
+A and B consists of lowercase and uppercase letters of english alphabet only.

+

+
\ No newline at end of file diff --git a/Triangle and Square - GFG/README.md b/Triangle and Square - GFG/README.md new file mode 100644 index 0000000..df7f00b --- /dev/null +++ b/Triangle and Square - GFG/README.md @@ -0,0 +1,45 @@ +# Triangle and Square +## Easy +
+

Note: This POTD is a part of Geek Summer Carnival. Solve all POTD consecutively from 5th to 10th April and get a chance to win exclusive discount vouchers on our GfG courses.

+ +
+

Geek has a ticket to the Geek Summer Carnival. The ticket has a positive integer B written on it. B denotes the base of a right-angled isosceles triangle. 
+Geek can avail discounts on X courses in the carnival.

+ +

X is the maximum number of squares of size 2x2 units that can fit in the given right-angled isosceles triangle. 
+Find X

+ +


+Example 1:

+ +
Input:
+B = 8
+Output:
+6 
+Explanation: 
+
+
+ +


+Example 2:

+ +
Input:
+B = 2
+Output:
+0
+ +


+Your Task:
+You don't need to read input or print anything. Complete the function countSquare() that takes integer b as input parameter and returns the number of possible squares that can fit into the isosceles triangle. 

+ +


+Expected Time Complexity: O(1)
+Expected Auxiliary Space: O(1)

+ +

 

+ +

Constraints:
+1 <= B <= 1000

+

+
\ No newline at end of file diff --git a/Triangle and Square - GFG/triangle-and-square.cpp b/Triangle and Square - GFG/triangle-and-square.cpp new file mode 100644 index 0000000..edcae52 --- /dev/null +++ b/Triangle and Square - GFG/triangle-and-square.cpp @@ -0,0 +1,29 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution{ + public: + int countSquare(int B) + { + return (((B/2)*(B/2))/2)-(B/4); + } +}; + + + +// { Driver Code Starts. +int main() +{ + int t; + cin>>t; + while(t--) + { + int B,count; + cin>>B; + Solution ob; + count = ob.countSquare(B); + cout< +

Given two arrays a[] and b[] of size n and m respectively. The task is to find union between these two arrays.

+ +

Union of the two arrays can be defined as the set containing distinct elements from both the arrays. If there are repetitions, then only one occurrence of element should be printed in the union.

+ +

Example 1:

+ +
Input:
+5 3
+1 2 3 4 5
+1 2 3
+Output: 
+5
+Explanation: 
+1, 2, 3, 4 and 5 are the
+elements which comes in the union set
+of both arrays. So count is 5.
+
+ +

Example 2:

+ +
Input:
+6 2 
+85 25 1 32 54 6
+85 2 
+Output: 
+7
+Explanation: 
+85, 25, 1, 32, 54, 6, and
+2 are the elements which comes in the
+union set of both arrays. So count is 7.
+ +

Your Task:
+Complete doUnion funciton that takes a, n, b, m as parameters and returns the count of union elements of the two arrays. The printing is done by the driver code.

+ +

Constraints:
+1 ≤ n, m ≤ 105
+0 ≤ a[i], b[i] < 105

+ +

Expected Time Complexity : O((n+m)log(n+m))
+Expected Auxilliary Space : O(n+m)

+

+ \ No newline at end of file diff --git a/Union of two arrays - GFG/union-of-two-arrays.cpp b/Union of two arrays - GFG/union-of-two-arrays.cpp new file mode 100644 index 0000000..cd2f534 --- /dev/null +++ b/Union of two arrays - GFG/union-of-two-arrays.cpp @@ -0,0 +1,50 @@ +// { Driver Code Starts +//Initial template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function template in C++ + +class Solution{ + public: + //Function to return the count of number of elements in union of two arrays. + int doUnion(int a[], int n, int b[], int m) { + //code here + set s; + for(int i=0;i> t; + + while(t--){ + + int n, m; + cin >> n >> m; + int a[n], b[m]; + + for(int i = 0;i> a[i]; + + for(int i = 0;i> b[i]; + Solution ob; + cout << ob.doUnion(a, n, b, m) << endl; + + } + + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/Word Break - Part 2 - GFG/README.md b/Word Break - Part 2 - GFG/README.md new file mode 100644 index 0000000..3374280 --- /dev/null +++ b/Word Break - Part 2 - GFG/README.md @@ -0,0 +1,36 @@ +# Word Break - Part 2 +## Hard +
+

Given a string s and a dictionary of words dict of length n, add spaces in s to construct a sentence where each word is a valid dictionary word. Each dictionary word can be used more than once. Return all such possible sentences.

+ +

Follow examples for better understanding.

+ +

Example 1:

+ +
Input: s = "catsanddog", n = 5 
+dict = {"cats", "cat", "and", "sand", "dog"}
+Output: (cats and dog)(cat sand dog)
+Explanation: All the words in the given 
+sentences are present in the dictionary.
+ +

Example 2:

+ +
Input: s = "catsandog", n = 5
+dict = {"cats", "cat", "and", "sand", "dog"}
+Output: Empty
+Explanation: There is no possible breaking 
+of the string s where all the words are present 
+in dict.
+ +

Your Task:
+You do not need to read input or print anything. Your task is to complete the function wordBreak() which takes n, dict and s as input parameters and returns a list of possible sentences. If no sentence is possible it returns an empty list.

+ +

Expected Time Complexity: O(N2*n) where N = |s|
+Expected Auxiliary Space: O(N2)

+ +

Constraints:
+1 ≤ n ≤ 20
+1 ≤ dict[i] ≤ 15
+1 ≤ |s| ≤ 500 

+

+
\ No newline at end of file diff --git a/Word Break - Part 2 - GFG/word-break-part-2.cpp b/Word Break - Part 2 - GFG/word-break-part-2.cpp new file mode 100644 index 0000000..acaa99b --- /dev/null +++ b/Word Break - Part 2 - GFG/word-break-part-2.cpp @@ -0,0 +1,83 @@ +// { Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + + // } Driver Code Ends +// User function Template for C++ + +class Solution{ +public: + + bool isThere(vector& dict,string & left,int n) + { + for(int i=0;i& ans,string & res,int n, vector& dict, string s) + { + for(int i=1;i<=s.size();i++) + { + string left = s.substr(0,i); + string right = s.substr(i,s.size()-i); + if(isThere(dict,left,n)) + { + if(i==s.size()) + { + res += left; + //string aa = "( " + res + " )"; + ans.push_back(res); + return; + } + string answer = res+left+" "; + helper(ans,answer,n,dict,right); + } + } + } + + vector wordBreak(int n, vector& dict, string s) + { + // code here + vector ans; + string res; + helper(ans,res,n,dict,s); + return ans; + + } +}; + +// { Driver Code Starts. + +int main(){ + int t; + cin>>t; + while(t--){ + int n; + vector dict; + string s; + cin>>n; + for(int i = 0;i < n;i++){ + cin>>s; + dict.push_back(s); + } + cin>>s; + + Solution ob; + vector ans = ob.wordBreak(n, dict, s); + if(ans.size() == 0) + cout<<"Empty\n"; + else{ + sort(ans.begin(), ans.end()); + for(int i = 0;i < ans.size();i++) + cout<<"("< +

Given a positive number k, we need to find a minimum value of positive integer n, such that XOR of n and n+1 is equal to k. If no such n exist then print -1.

+ +


+Example 1:

+ +
Input: k = 3
+Output: 1
+Explaination: 1 xor 2 = 3.
+ +


+Example 2:

+ +
Input: k = 6
+Output: -1
+Explaination: There is no such n, so that, 
+n xor n+1 = k.
+ +


+Your Task:
+You do not need to read input or print anything. Your task is to complete the function xorCal() which takes k as input parameter and returns the value of n. If there is no such , then it returns -1.

+ +


+Expected Time Complexity: O(1)
+Expected Auxiliary Space: O(1)

+ +


+Constraints:
+1 ≤ k ≤ 100

+

+ \ No newline at end of file diff --git a/XOR Game - GFG/xor-game.cpp b/XOR Game - GFG/xor-game.cpp new file mode 100644 index 0000000..e7f822c --- /dev/null +++ b/XOR Game - GFG/xor-game.cpp @@ -0,0 +1,36 @@ +// { Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + + // } Driver Code Ends +// User function Template for C++ + +class Solution{ +public: + int xorCal(int k){ + + + if(k == 1) return 2; + int val = k/2; + if((val ^ (val +1)) == k) return val; + else{ + return -1; + } + } +}; +// { Driver Code Starts. + +int main(){ + int t; + cin>>t; + while(t--){ + int k; + cin>>k; + + Solution ob; + cout<721. Accounts Merge

Medium


Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.

+ +

Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.

+ +

After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.

+ +

 

+

Example 1:

+ +
Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
+Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
+Explanation:
+The first and second John's are the same person as they have the common email "johnsmith@mail.com".
+The third John and Mary are different people as none of their email addresses are used by other accounts.
+We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], 
+['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
+
+ +

Example 2:

+ +
Input: accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]]
+Output: [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= accounts.length <= 1000
  • +
  • 2 <= accounts[i].length <= 10
  • +
  • 1 <= accounts[i][j] <= 30
  • +
  • accounts[i][0] consists of English letters.
  • +
  • accounts[i][j] (for j > 0) is a valid email.
  • +
+
\ No newline at end of file diff --git a/accounts-merge/accounts-merge.cpp b/accounts-merge/accounts-merge.cpp new file mode 100644 index 0000000..dbfe94d --- /dev/null +++ b/accounts-merge/accounts-merge.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + void dfs(string& email) { + seen.insert(email); + ans.back().push_back(email); + for(auto& adjEmail : G[email]) + if(!seen.count(adjEmail)) + dfs(adjEmail); + } + vector> accountsMerge(vector>& A) { + for(auto& acc : A) + for(int i = 2; i < size(acc); i++) // create graph with email as nodes and, + G[acc[i]].push_back(acc[i-1]), // add edges between adjacent nodes of same account + G[acc[i-1]].push_back(acc[i]); + + for(auto& acc : A) + if(!seen.count(acc[1])) { // If an email from a account is not previously seen, + ans.push_back({acc[0]}); // create new account & insert person's name + dfs(acc[1]); // perform dfs to find all his emails & add it to the list + sort(begin(ans.back())+1, end(ans.back())); // sort the emails + } + // ans.push_back({}); + return ans; + } +private: + unordered_map> G; // adjacency list graph with email as nodes and edges between adjacent email of same account + unordered_set seen; // to mark an email as visited in DFS + vector> ans; // final answer after merging accounts +}; \ No newline at end of file diff --git a/add-digits/README.md b/add-digits/README.md new file mode 100644 index 0000000..46da928 --- /dev/null +++ b/add-digits/README.md @@ -0,0 +1,29 @@ +

258. Add Digits

Easy


Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

+ +

 

+

Example 1:

+ +
Input: num = 38
+Output: 2
+Explanation: The process is
+38 --> 3 + 8 --> 11
+11 --> 1 + 1 --> 2 
+Since 2 has only one digit, return it.
+
+ +

Example 2:

+ +
Input: num = 0
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= num <= 231 - 1
  • +
+ +

 

+

Follow up: Could you do it without any loop/recursion in O(1) runtime?

+
\ No newline at end of file diff --git a/add-digits/add-digits.cpp b/add-digits/add-digits.cpp new file mode 100644 index 0000000..7839f13 --- /dev/null +++ b/add-digits/add-digits.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int addDigits(int num) { + if(num / 10 == 0) + return num; + + int temp = num; + int sum = 0; + while(temp) + { + sum += temp%10; + temp /= 10; + } + return addDigits(sum); + } +}; \ No newline at end of file diff --git a/add-strings/README.md b/add-strings/README.md new file mode 100644 index 0000000..ea34177 --- /dev/null +++ b/add-strings/README.md @@ -0,0 +1,32 @@ +

415. Add Strings

Easy


Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

+ +

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

+ +

 

+

Example 1:

+ +
Input: num1 = "11", num2 = "123"
+Output: "134"
+
+ +

Example 2:

+ +
Input: num1 = "456", num2 = "77"
+Output: "533"
+
+ +

Example 3:

+ +
Input: num1 = "0", num2 = "0"
+Output: "0"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= num1.length, num2.length <= 104
  • +
  • num1 and num2 consist of only digits.
  • +
  • num1 and num2 don't have any leading zeros except for the zero itself.
  • +
+
\ No newline at end of file diff --git a/add-strings/add-strings.cpp b/add-strings/add-strings.cpp new file mode 100644 index 0000000..c018f65 --- /dev/null +++ b/add-strings/add-strings.cpp @@ -0,0 +1,20 @@ +class Solution { +public: +string addStrings(string num1, string num2) { + int i = num1.size() - 1; + int j = num2.size() - 1; + int carry = 0; + string res = ""; + while(i>=0 || j>=0 || carry){ + long sum = 0; + if(i >= 0){sum += (num1[i] - '0');i--;} + if(j >= 0){sum += (num2[j] - '0');j--;} + sum += carry; + carry = sum / 10; + sum = sum % 10; + res = res + to_string(sum); + } + reverse(res.begin(), res.end()); + return res; +} +}; \ No newline at end of file diff --git a/add-two-numbers/README.md b/add-two-numbers/README.md new file mode 100644 index 0000000..f257754 --- /dev/null +++ b/add-two-numbers/README.md @@ -0,0 +1,33 @@ +

2. Add Two Numbers

Medium


You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

+ +

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

+ +

 

+

Example 1:

+ +
Input: l1 = [2,4,3], l2 = [5,6,4]
+Output: [7,0,8]
+Explanation: 342 + 465 = 807.
+
+ +

Example 2:

+ +
Input: l1 = [0], l2 = [0]
+Output: [0]
+
+ +

Example 3:

+ +
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
+Output: [8,9,9,9,0,0,0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in each linked list is in the range [1, 100].
  • +
  • 0 <= Node.val <= 9
  • +
  • It is guaranteed that the list represents a number that does not have leading zeros.
  • +
+
\ No newline at end of file diff --git a/add-two-numbers/add-two-numbers.cpp b/add-two-numbers/add-two-numbers.cpp new file mode 100644 index 0000000..85a5c8e --- /dev/null +++ b/add-two-numbers/add-two-numbers.cpp @@ -0,0 +1,58 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: +// ListNode * reverse(ListNode * l1) +// { +// if(!l1 || l1->next == NULL) +// return l1; + +// ListNode * nextnode=l1->next; +// ListNode * reversed = reverse(l1->next); +// l1->next = NULL; +// nextnode->next = l1; +// return reversed; +// } + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + // l1 = reverse(l1); + // l2 = reverse(l2); + int carry = 0; + ListNode * dummy = new ListNode(0); + ListNode * temp = dummy; + while(l1 != NULL || l2 !=NULL) + { + int sum = carry; + if(l1) + sum+=l1->val; + if(l2) + sum+=l2->val; + + int value = sum%10; + carry = sum/10; + ListNode * newNode = new ListNode(value); + temp->next = newNode; + temp = temp->next; + if(l1) + l1 = l1->next; + if(l2) + l2 = l2->next; + } + + if(carry) + { + ListNode * newNode = new ListNode(carry); + temp->next = newNode; + temp = temp->next; + } + return dummy->next; + + } +}; \ No newline at end of file diff --git a/all-elements-in-two-binary-search-trees/README.md b/all-elements-in-two-binary-search-trees/README.md new file mode 100644 index 0000000..bb7f4a4 --- /dev/null +++ b/all-elements-in-two-binary-search-trees/README.md @@ -0,0 +1,43 @@ +

1305. All Elements in Two Binary Search Trees

Medium


Given two binary search trees root1 and root2.

+ +

Return a list containing all the integers from both trees sorted in ascending order.

+ +

 

+

Example 1:

+ +
Input: root1 = [2,1,4], root2 = [1,0,3]
+Output: [0,1,1,2,3,4]
+
+ +

Example 2:

+ +
Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
+Output: [-10,0,0,1,2,5,7,10]
+
+ +

Example 3:

+ +
Input: root1 = [], root2 = [5,1,7,0,2]
+Output: [0,1,2,5,7]
+
+ +

Example 4:

+ +
Input: root1 = [0,-10,10], root2 = []
+Output: [-10,0,10]
+
+ +

Example 5:

+ +
Input: root1 = [1,null,8], root2 = [8,1]
+Output: [1,1,8,8]
+
+ +

 

+

Constraints:

+ +
    +
  • Each tree has at most 5000 nodes.
  • +
  • Each node's value is between [-10^5, 10^5].
  • +
+
\ No newline at end of file diff --git a/all-elements-in-two-binary-search-trees/all-elements-in-two-binary-search-trees.cpp b/all-elements-in-two-binary-search-trees/all-elements-in-two-binary-search-trees.cpp new file mode 100644 index 0000000..2d2ead2 --- /dev/null +++ b/all-elements-in-two-binary-search-trees/all-elements-in-two-binary-search-trees.cpp @@ -0,0 +1,60 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + void inOrderTraverse(TreeNode *root, vector& vec) + { + if(root) + { + inOrderTraverse(root->left, vec); + vec.push_back(root->val); + inOrderTraverse(root->right, vec); + + } + } + void mergeVectors(vector vec1, vector vec2, vector& mergedVectors) + { + int i = 0, j = 0, k = 0; + + // Traverse both array + while (i < vec1.size() && j < vec2.size()) + { + + if (vec1[i] < vec2[j]) + mergedVectors[k++] = vec1[i++]; + else + mergedVectors[k++] = vec2[j++]; + } + + + while (i < vec1.size()) + mergedVectors[k++] = vec1[i++]; + + + while (j < vec2.size()) + mergedVectors[k++] = vec2[j++]; + + + } + + vector getAllElements(TreeNode* root1, TreeNode* root2) { + vector v1; + vector v2; + inOrderTraverse(root1, v1); + inOrderTraverse(root2, v2); + + vector mergedVectors(v1.size() + v2.size()); + + mergeVectors(v1, v2, mergedVectors); + return mergedVectors; + } +}; \ No newline at end of file diff --git a/all-paths-from-source-to-target/README.md b/all-paths-from-source-to-target/README.md new file mode 100644 index 0000000..afe7dee --- /dev/null +++ b/all-paths-from-source-to-target/README.md @@ -0,0 +1,48 @@ +

797. All Paths From Source to Target

Medium


Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.

+ +

The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).

+ +

 

+

Example 1:

+ +
Input: graph = [[1,2],[3],[3],[]]
+Output: [[0,1,3],[0,2,3]]
+Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
+
+ +

Example 2:

+ +
Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
+Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
+
+ +

Example 3:

+ +
Input: graph = [[1],[]]
+Output: [[0,1]]
+
+ +

Example 4:

+ +
Input: graph = [[1,2,3],[2],[3],[]]
+Output: [[0,1,2,3],[0,2,3],[0,3]]
+
+ +

Example 5:

+ +
Input: graph = [[1,3],[2],[3],[]]
+Output: [[0,1,2,3],[0,3]]
+
+ +

 

+

Constraints:

+ +
    +
  • n == graph.length
  • +
  • 2 <= n <= 15
  • +
  • 0 <= graph[i][j] < n
  • +
  • graph[i][j] != i (i.e., there will be no self-loops).
  • +
  • All the elements of graph[i] are unique.
  • +
  • The input graph is guaranteed to be a DAG.
  • +
+
\ No newline at end of file diff --git a/all-paths-from-source-to-target/all-paths-from-source-to-target.cpp b/all-paths-from-source-to-target/all-paths-from-source-to-target.cpp new file mode 100644 index 0000000..fa24701 --- /dev/null +++ b/all-paths-from-source-to-target/all-paths-from-source-to-target.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + void dfs(vector>& g, vector>& res, vector& path, int cur) { + path.push_back(cur); + if (cur == g.size() - 1) + res.push_back(path); + else for (auto it: g[cur]) + dfs(g, res, path, it); + path.pop_back(); + + } + + vector> allPathsSourceTarget(vector>& g) { + vector> paths; + vector path; + dfs(g, paths, path, 0); + return paths; + } +}; \ No newline at end of file diff --git a/all-possible-full-binary-trees/README.md b/all-possible-full-binary-trees/README.md new file mode 100644 index 0000000..a6334d5 --- /dev/null +++ b/all-possible-full-binary-trees/README.md @@ -0,0 +1,26 @@ +

894. All Possible Full Binary Trees

Medium


Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0.

+ +

Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order.

+ +

A full binary tree is a binary tree where each node has exactly 0 or 2 children.

+ +

 

+

Example 1:

+ +
Input: n = 7
+Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]
+
+ +

Example 2:

+ +
Input: n = 3
+Output: [[0,0,0]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 20
  • +
+
\ No newline at end of file diff --git a/all-possible-full-binary-trees/all-possible-full-binary-trees.cpp b/all-possible-full-binary-trees/all-possible-full-binary-trees.cpp new file mode 100644 index 0000000..b9e2657 --- /dev/null +++ b/all-possible-full-binary-trees/all-possible-full-binary-trees.cpp @@ -0,0 +1,36 @@ +class Solution { + vector generateFBTs(int n) { + if(n == 1) return {new TreeNode(0)}; //choice 1 + //choice two + vector trees; + n--; //count this node + + vector leftChoices, rightChoices; + //fixing the sizes of the subtrees + for(int i = 1; ileft = j; + root->right = k; + trees.push_back(root); + } + } + } + return trees; + } +public: + vector allPossibleFBT(int n) { + //checking for base cases + if(n == 1) return {new TreeNode(0)}; + else if(n%2 == 11) return {}; + else if(n==31) return {new TreeNode(0, new TreeNode(0), new TreeNode(0))}; + + //otherwise, do the normal thing + return generateFBTs(n); + } +}; \ No newline at end of file diff --git a/arranging-coins/README.md b/arranging-coins/README.md new file mode 100644 index 0000000..20e3cd8 --- /dev/null +++ b/arranging-coins/README.md @@ -0,0 +1,26 @@ +

441. Arranging Coins

Easy


You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.

+ +

Given the integer n, return the number of complete rows of the staircase you will build.

+ +

 

+

Example 1:

+ +
Input: n = 5
+Output: 2
+Explanation: Because the 3rd row is incomplete, we return 2.
+
+ +

Example 2:

+ +
Input: n = 8
+Output: 3
+Explanation: Because the 4th row is incomplete, we return 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/arranging-coins/arranging-coins.cpp b/arranging-coins/arranging-coins.cpp new file mode 100644 index 0000000..181f32a --- /dev/null +++ b/arranging-coins/arranging-coins.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int arrangeCoins(int n) { + long end = n; + long low = 0; + long high = n; + + while(low <= high) + { + long mid = low + (high-low)/2; + if(mid*(mid+1) <= 2*end) + { + low = mid+1; + } + else + high = mid-1; + } + return (int)(low-1); + } +}; \ No newline at end of file diff --git a/array-of-doubled-pairs/README.md b/array-of-doubled-pairs/README.md new file mode 100644 index 0000000..4e2adfb --- /dev/null +++ b/array-of-doubled-pairs/README.md @@ -0,0 +1,37 @@ +

954. Array of Doubled Pairs

Medium


Given an array of integers arr of even length, return true if and only if it is possible to reorder it such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2.

+ +

 

+

Example 1:

+ +
Input: arr = [3,1,3,6]
+Output: false
+
+ +

Example 2:

+ +
Input: arr = [2,1,2,6]
+Output: false
+
+ +

Example 3:

+ +
Input: arr = [4,-2,2,-4]
+Output: true
+Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].
+
+ +

Example 4:

+ +
Input: arr = [1,2,4,16,8,4]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= arr.length <= 3 * 104
  • +
  • arr.length is even.
  • +
  • -105 <= arr[i] <= 105
  • +
+
\ No newline at end of file diff --git a/balance-a-binary-search-tree/README.md b/balance-a-binary-search-tree/README.md new file mode 100644 index 0000000..59996a0 --- /dev/null +++ b/balance-a-binary-search-tree/README.md @@ -0,0 +1,26 @@ +

1382. Balance a Binary Search Tree

Medium


Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.

+ +

A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.

+ +

 

+

Example 1:

+ +
Input: root = [1,null,2,null,3,null,4,null,null]
+Output: [2,1,3,null,null,null,4]
+Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct.
+
+ +

Example 2:

+ +
Input: root = [2,1,3]
+Output: [2,1,3]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • 1 <= Node.val <= 105
  • +
+
\ No newline at end of file diff --git a/balanced-binary-tree/README.md b/balanced-binary-tree/README.md new file mode 100644 index 0000000..803d204 --- /dev/null +++ b/balanced-binary-tree/README.md @@ -0,0 +1,35 @@ +

110. Balanced Binary Tree

Easy


Given a binary tree, determine if it is height-balanced.

+ +

For this problem, a height-balanced binary tree is defined as:

+ +
+

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

+
+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: true
+
+ +

Example 2:

+ +
Input: root = [1,2,2,3,3,null,null,4,4]
+Output: false
+
+ +

Example 3:

+ +
Input: root = []
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 5000].
  • +
  • -104 <= Node.val <= 104
  • +
+
\ No newline at end of file diff --git a/balanced-binary-tree/balanced-binary-tree.cpp b/balanced-binary-tree/balanced-binary-tree.cpp new file mode 100644 index 0000000..97df1b8 --- /dev/null +++ b/balanced-binary-tree/balanced-binary-tree.cpp @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int helper(TreeNode * root) + { + if(root == NULL) + return 0; + + int l = helper(root->left); + int r = helper(root->right); + + if(l != -1 && r != -1 && abs(l-r) <= 1 ) + return 1 + max(l,r); + return -1; + + } + + bool isBalanced(TreeNode* root) { + if(root == NULL) + return true; + + int ans = helper(root); + if(ans != -1) + return true; + return false; + } +}; \ No newline at end of file diff --git a/best-sightseeing-pair/README.md b/best-sightseeing-pair/README.md new file mode 100644 index 0000000..bf4fdfb --- /dev/null +++ b/best-sightseeing-pair/README.md @@ -0,0 +1,28 @@ +

1014. Best Sightseeing Pair

Medium


You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.

+ +

The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them.

+ +

Return the maximum score of a pair of sightseeing spots.

+ +

 

+

Example 1:

+ +
Input: values = [8,1,5,2,6]
+Output: 11
+Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11
+
+ +

Example 2:

+ +
Input: values = [1,2]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= values.length <= 5 * 104
  • +
  • 1 <= values[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/best-sightseeing-pair/best-sightseeing-pair.cpp b/best-sightseeing-pair/best-sightseeing-pair.cpp new file mode 100644 index 0000000..1390423 --- /dev/null +++ b/best-sightseeing-pair/best-sightseeing-pair.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int maxScoreSightseeingPair(vector& values) { + int ans = INT_MIN; + int prev = values[0] + 0; + for(int i=1;i122. Best Time to Buy and Sell Stock II

Easy


You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

+ +

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

+ +

 

+

Example 1:

+ +
Input: prices = [7,1,5,3,6,4]
+Output: 7
+Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
+Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
+
+ +

Example 2:

+ +
Input: prices = [1,2,3,4,5]
+Output: 4
+Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
+Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
+
+ +

Example 3:

+ +
Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: In this case, no transaction is done, i.e., max profit = 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 3 * 104
  • +
  • 0 <= prices[i] <= 104
  • +
+
\ No newline at end of file diff --git a/best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.cpp b/best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.cpp new file mode 100644 index 0000000..557a683 --- /dev/null +++ b/best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int maxProfit(vector &prices) { + int ret = 0; + for (size_t p = 1; p < prices.size(); ++p) + ret += max(prices[p] - prices[p - 1], 0); + return ret; +} +}; \ No newline at end of file diff --git a/best-time-to-buy-and-sell-stock-iii/README.md b/best-time-to-buy-and-sell-stock-iii/README.md new file mode 100644 index 0000000..89b23aa --- /dev/null +++ b/best-time-to-buy-and-sell-stock-iii/README.md @@ -0,0 +1,37 @@ +

123. Best Time to Buy and Sell Stock III

Hard


You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

Find the maximum profit you can achieve. You may complete at most two transactions.

+ +

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

+ +

 

+

Example 1:

+ +
Input: prices = [3,3,5,0,0,3,1,4]
+Output: 6
+Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
+Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
+ +

Example 2:

+ +
Input: prices = [1,2,3,4,5]
+Output: 4
+Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
+Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
+
+ +

Example 3:

+ +
Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: In this case, no transaction is done, i.e. max profit = 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 105
  • +
  • 0 <= prices[i] <= 105
  • +
+
\ No newline at end of file diff --git a/best-time-to-buy-and-sell-stock-iv/README.md b/best-time-to-buy-and-sell-stock-iv/README.md new file mode 100644 index 0000000..0954381 --- /dev/null +++ b/best-time-to-buy-and-sell-stock-iv/README.md @@ -0,0 +1,30 @@ +

188. Best Time to Buy and Sell Stock IV

Hard


You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.

+ +

Find the maximum profit you can achieve. You may complete at most k transactions.

+ +

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

+ +

 

+

Example 1:

+ +
Input: k = 2, prices = [2,4,1]
+Output: 2
+Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
+
+ +

Example 2:

+ +
Input: k = 2, prices = [3,2,6,5,0,3]
+Output: 7
+Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= k <= 100
  • +
  • 0 <= prices.length <= 1000
  • +
  • 0 <= prices[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/best-time-to-buy-and-sell-stock-iv/best-time-to-buy-and-sell-stock-iv.cpp b/best-time-to-buy-and-sell-stock-iv/best-time-to-buy-and-sell-stock-iv.cpp new file mode 100644 index 0000000..cbd0447 --- /dev/null +++ b/best-time-to-buy-and-sell-stock-iv/best-time-to-buy-and-sell-stock-iv.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + int maxProfit(int k, vector& prices) { + if(prices.size()==0 || k==0)return 0; + vector> dp(k+1,vector (prices.size())); + + for(int i=1;i<=k;i++) + { + int maxi ; + for(int j=1;j309. Best Time to Buy and Sell Stock with Cooldown

Medium


You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

+ +
    +
  • After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
  • +
+ +

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

+ +

 

+

Example 1:

+ +
Input: prices = [1,2,3,0,2]
+Output: 3
+Explanation: transactions = [buy, sell, cooldown, buy, sell]
+
+ +

Example 2:

+ +
Input: prices = [1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 5000
  • +
  • 0 <= prices[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/best-time-to-buy-and-sell-stock-with-cooldown/best-time-to-buy-and-sell-stock-with-cooldown.cpp b/best-time-to-buy-and-sell-stock-with-cooldown/best-time-to-buy-and-sell-stock-with-cooldown.cpp new file mode 100644 index 0000000..abcce8a --- /dev/null +++ b/best-time-to-buy-and-sell-stock-with-cooldown/best-time-to-buy-and-sell-stock-with-cooldown.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int maxProfit(vector& arr) { + vector> dp(2,vector (arr.size()+1)); + + dp[0][1] = -1*arr[0]; + dp[1][1] = 0; + + for(int i=2;i<=arr.size();i++) + { + dp[0][i] = max(dp[0][i-1], dp[1][i-2]-arr[i-1]); + dp[1][i] = max(dp[0][i-1]+arr[i-1],dp[1][i-1]); + } + + + return dp[1][arr.size()]; + } +}; \ No newline at end of file diff --git a/best-time-to-buy-and-sell-stock/README.md b/best-time-to-buy-and-sell-stock/README.md new file mode 100644 index 0000000..f6dbc57 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/README.md @@ -0,0 +1,30 @@ +

121. Best Time to Buy and Sell Stock

Easy


You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

+ +

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

+ +

 

+

Example 1:

+ +
Input: prices = [7,1,5,3,6,4]
+Output: 5
+Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
+Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
+
+ +

Example 2:

+ +
Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: In this case, no transactions are done and the max profit = 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 105
  • +
  • 0 <= prices[i] <= 104
  • +
+
\ No newline at end of file diff --git a/best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.cpp b/best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.cpp new file mode 100644 index 0000000..59b1fd8 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int maxProfit(vector &prices) { + int maxPro = 0; + int minPrice = INT_MAX; + for(int i = 0; i < prices.size(); i++){ + minPrice = min(minPrice, prices[i]); + maxPro = max(maxPro, prices[i] - minPrice); + } + return maxPro; +} +}; \ No newline at end of file diff --git a/binary-search-tree-to-greater-sum-tree/README.md b/binary-search-tree-to-greater-sum-tree/README.md new file mode 100644 index 0000000..73b6022 --- /dev/null +++ b/binary-search-tree-to-greater-sum-tree/README.md @@ -0,0 +1,46 @@ +

1038. Binary Search Tree to Greater Sum Tree

Medium


Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

+ +

As a reminder, a binary search tree is a tree that satisfies these constraints:

+ +
    +
  • The left subtree of a node contains only nodes with keys less than the node's key.
  • +
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • +
  • Both the left and right subtrees must also be binary search trees.
  • +
+ +

Note: This question is the same as 538: https://leetcode.com/problems/convert-bst-to-greater-tree/

+ +

 

+

Example 1:

+ +
Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
+Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
+
+ +

Example 2:

+ +
Input: root = [0,null,1]
+Output: [1,null,1]
+
+ +

Example 3:

+ +
Input: root = [1,0,2]
+Output: [3,3,2]
+
+ +

Example 4:

+ +
Input: root = [3,2,4,1]
+Output: [7,9,4,10]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 100].
  • +
  • 0 <= Node.val <= 100
  • +
  • All the values in the tree are unique.
  • +
  • root is guaranteed to be a valid binary search tree.
  • +
\ No newline at end of file diff --git a/binary-search-tree-to-greater-sum-tree/binary-search-tree-to-greater-sum-tree.cpp b/binary-search-tree-to-greater-sum-tree/binary-search-tree-to-greater-sum-tree.cpp new file mode 100644 index 0000000..e015e32 --- /dev/null +++ b/binary-search-tree-to-greater-sum-tree/binary-search-tree-to-greater-sum-tree.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + TreeNode* bstToGst(TreeNode* root) { + int acc_sum = 0; + sum_node(root,acc_sum); + return root; + } + + void sum_node(TreeNode* node, int& acc_sum){ + if (node == NULL) return; + sum_node(node->right,acc_sum); + node->val += acc_sum; + acc_sum = node->val; + sum_node(node->left, acc_sum); + } +}; \ No newline at end of file diff --git a/binary-search/README.md b/binary-search/README.md new file mode 100644 index 0000000..cb494d2 --- /dev/null +++ b/binary-search/README.md @@ -0,0 +1,29 @@ +

704. Binary Search

Easy


Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

+ +

You must write an algorithm with O(log n) runtime complexity.

+ +

 

+

Example 1:

+ +
Input: nums = [-1,0,3,5,9,12], target = 9
+Output: 4
+Explanation: 9 exists in nums and its index is 4
+
+ +

Example 2:

+ +
Input: nums = [-1,0,3,5,9,12], target = 2
+Output: -1
+Explanation: 2 does not exist in nums so return -1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -104 < nums[i], target < 104
  • +
  • All the integers in nums are unique.
  • +
  • nums is sorted in ascending order.
  • +
+
\ No newline at end of file diff --git a/binary-search/binary-search.cpp b/binary-search/binary-search.cpp new file mode 100644 index 0000000..49dcdde --- /dev/null +++ b/binary-search/binary-search.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + + int bs(vector& nums, int target,int low,int high) + { + if(high>=low) + { + int mid = low+(high-low)/2; + if(nums[mid]==target)return mid; + else if(nums[mid]>target)return bs(nums,target,low,mid-1); + else return bs(nums,target,mid+1,high); + } + return -1; + } + + int search(vector& nums, int target) { + return bs(nums,target,0,nums.size()-1); + } +}; \ No newline at end of file diff --git a/binary-tree-inorder-traversal/README.md b/binary-tree-inorder-traversal/README.md new file mode 100644 index 0000000..728adca --- /dev/null +++ b/binary-tree-inorder-traversal/README.md @@ -0,0 +1,43 @@ +

94. Binary Tree Inorder Traversal

Easy


Given the root of a binary tree, return the inorder traversal of its nodes' values.

+ +

 

+

Example 1:

+ +
Input: root = [1,null,2,3]
+Output: [1,3,2]
+
+ +

Example 2:

+ +
Input: root = []
+Output: []
+
+ +

Example 3:

+ +
Input: root = [1]
+Output: [1]
+
+ +

Example 4:

+ +
Input: root = [1,2]
+Output: [2,1]
+
+ +

Example 5:

+ +
Input: root = [1,null,2]
+Output: [1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+Follow up: Recursive solution is trivial, could you do it iteratively?
\ No newline at end of file diff --git a/binary-tree-inorder-traversal/binary-tree-inorder-traversal.cpp b/binary-tree-inorder-traversal/binary-tree-inorder-traversal.cpp new file mode 100644 index 0000000..d02d1b8 --- /dev/null +++ b/binary-tree-inorder-traversal/binary-tree-inorder-traversal.cpp @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector ans; + vector inorderTraversal(TreeNode* root) { + + if(root == NULL) + return ans; + + inorderTraversal(root->left); + ans.push_back(root->val); + inorderTraversal(root->right); + + return ans; + + } +}; \ No newline at end of file diff --git a/binary-tree-level-order-traversal/README.md b/binary-tree-level-order-traversal/README.md new file mode 100644 index 0000000..26c0297 --- /dev/null +++ b/binary-tree-level-order-traversal/README.md @@ -0,0 +1,29 @@ +

102. Binary Tree Level Order Traversal

Medium


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

+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: [[3],[9,20],[15,7]]
+
+ +

Example 2:

+ +
Input: root = [1]
+Output: [[1]]
+
+ +

Example 3:

+ +
Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 2000].
  • +
  • -1000 <= Node.val <= 1000
  • +
+
\ No newline at end of file diff --git a/binary-tree-level-order-traversal/binary-tree-level-order-traversal.cpp b/binary-tree-level-order-traversal/binary-tree-level-order-traversal.cpp new file mode 100644 index 0000000..5b91c11 --- /dev/null +++ b/binary-tree-level-order-traversal/binary-tree-level-order-traversal.cpp @@ -0,0 +1,81 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> levelOrder(TreeNode* root) { + vector> ans; + + if(root == NULL) + return ans; + + queue pendingNodes; + pendingNodes.push(root); + int siz = 1; + vector level; + while(pendingNodes.size()) + { + + if(siz == 0) + { + siz = pendingNodes.size(); + ans.push_back(level); + level.clear(); + } + TreeNode* front = pendingNodes.front(); + pendingNodes.pop(); + level.push_back(front->val); + // cout<left) + { + pendingNodes.push(front->left); + } + if(front->right) + { + pendingNodes.push(front->right); + } + + + } + if(siz == 0) + { + siz = pendingNodes.size(); + ans.push_back(level); + level.clear(); + } + + return ans; + } +}; + + + + + + + + + + // TreeNode* start = pendingNodes.front(); + +// vector level; +// int siz = pendingNodes.size(); +// while(siz--) +// { +// level.push_back(start->data); + +// } +// TreeNode* front = pendingNodes.front(); +// pendingNodes.pop(); + + // \ No newline at end of file diff --git a/binary-tree-maximum-path-sum/README.md b/binary-tree-maximum-path-sum/README.md new file mode 100644 index 0000000..d17f97a --- /dev/null +++ b/binary-tree-maximum-path-sum/README.md @@ -0,0 +1,29 @@ +

124. Binary Tree Maximum Path Sum

Hard


A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

+ +

The path sum of a path is the sum of the node's values in the path.

+ +

Given the root of a binary tree, return the maximum path sum of any non-empty path.

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3]
+Output: 6
+Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
+
+ +

Example 2:

+ +
Input: root = [-10,9,20,null,null,15,7]
+Output: 42
+Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 3 * 104].
  • +
  • -1000 <= Node.val <= 1000
  • +
+
\ No newline at end of file diff --git a/binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.cpp b/binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.cpp new file mode 100644 index 0000000..26fe647 --- /dev/null +++ b/binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.cpp @@ -0,0 +1,17 @@ +class Solution { + int maxToRoot(TreeNode *root, int &re) { + if (!root) return 0; + int l = maxToRoot(root->left, re); + int r = maxToRoot(root->right, re); + if (l < 0) l = 0; + if (r < 0) r = 0; + if (l + r + root->val > re) re = l + r + root->val; + return root->val += max(l, r); + } +public: + int maxPathSum(TreeNode *root) { + int max = -2147483648; + maxToRoot(root, max); + return max; + } +}; \ No newline at end of file diff --git a/binary-tree-paths/README.md b/binary-tree-paths/README.md new file mode 100644 index 0000000..66ed67e --- /dev/null +++ b/binary-tree-paths/README.md @@ -0,0 +1,25 @@ +

257. Binary Tree Paths

Easy


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

+ +

A leaf is a node with no children.

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3,null,5]
+Output: ["1->2->5","1->3"]
+
+ +

Example 2:

+ +
Input: root = [1]
+Output: ["1"]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/binary-tree-paths/binary-tree-paths.cpp b/binary-tree-paths/binary-tree-paths.cpp new file mode 100644 index 0000000..a918b7d --- /dev/null +++ b/binary-tree-paths/binary-tree-paths.cpp @@ -0,0 +1,41 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + void helper(TreeNode * root, vector & v,string s) + { + if(root == NULL) + { + return ; + } + if(root->left ==NULL && root->right == NULL) + { + s += to_string(root->val); + v.push_back(s); + return ; + } + s += to_string(root->val); + s += "->"; + helper(root->left,v,s); + helper(root->right,v,s); + return ; + + } + vector binaryTreePaths(TreeNode* root) { + if(root == NULL) + return {}; + vector v; + string s = ""; + helper(root,v,s); + return v; + } +}; \ No newline at end of file diff --git a/binary-tree-postorder-traversal/README.md b/binary-tree-postorder-traversal/README.md new file mode 100644 index 0000000..24f1990 --- /dev/null +++ b/binary-tree-postorder-traversal/README.md @@ -0,0 +1,43 @@ +

145. Binary Tree Postorder Traversal

Easy


Given the root of a binary tree, return the postorder traversal of its nodes' values.

+ +

 

+

Example 1:

+ +
Input: root = [1,null,2,3]
+Output: [3,2,1]
+
+ +

Example 2:

+ +
Input: root = []
+Output: []
+
+ +

Example 3:

+ +
Input: root = [1]
+Output: [1]
+
+ +

Example 4:

+ +
Input: root = [1,2]
+Output: [2,1]
+
+ +

Example 5:

+ +
Input: root = [1,null,2]
+Output: [2,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+Follow up: Recursive solution is trivial, could you do it iteratively?
\ No newline at end of file diff --git a/binary-tree-preorder-traversal/README.md b/binary-tree-preorder-traversal/README.md new file mode 100644 index 0000000..7794c1f --- /dev/null +++ b/binary-tree-preorder-traversal/README.md @@ -0,0 +1,44 @@ +

144. Binary Tree Preorder Traversal

Easy


Given the root of a binary tree, return the preorder traversal of its nodes' values.

+ +

 

+

Example 1:

+ +
Input: root = [1,null,2,3]
+Output: [1,2,3]
+
+ +

Example 2:

+ +
Input: root = []
+Output: []
+
+ +

Example 3:

+ +
Input: root = [1]
+Output: [1]
+
+ +

Example 4:

+ +
Input: root = [1,2]
+Output: [1,2]
+
+ +

Example 5:

+ +
Input: root = [1,null,2]
+Output: [1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+

Follow up: Recursive solution is trivial, could you do it iteratively?

+
\ No newline at end of file diff --git a/binary-tree-preorder-traversal/binary-tree-preorder-traversal.cpp b/binary-tree-preorder-traversal/binary-tree-preorder-traversal.cpp new file mode 100644 index 0000000..ee23dff --- /dev/null +++ b/binary-tree-preorder-traversal/binary-tree-preorder-traversal.cpp @@ -0,0 +1,28 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector preorderTraversal(TreeNode* root) { + vector nodes; + preorder(root, nodes); + return nodes; + } +private: + void preorder(TreeNode* root, vector& nodes) { + if (!root) { + return; + } + nodes.push_back(root -> val); + preorder(root -> left, nodes); + preorder(root -> right, nodes); + } +}; \ No newline at end of file diff --git a/binary-tree-pruning/README.md b/binary-tree-pruning/README.md new file mode 100644 index 0000000..cf8305a --- /dev/null +++ b/binary-tree-pruning/README.md @@ -0,0 +1,34 @@ +

814. Binary Tree Pruning

Medium


Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.

+ +

A subtree of a node node is node plus every node that is a descendant of node.

+ +

 

+

Example 1:

+ +
Input: root = [1,null,0,0,1]
+Output: [1,null,0,null,1]
+Explanation: 
+Only the red nodes satisfy the property "every subtree not containing a 1".
+The diagram on the right represents the answer.
+
+ +

Example 2:

+ +
Input: root = [1,0,1,0,0,0,1]
+Output: [1,null,1,null,1]
+
+ +

Example 3:

+ +
Input: root = [1,1,0,1,1,0,1,0]
+Output: [1,1,0,1,1,null,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 200].
  • +
  • Node.val is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/binary-tree-right-side-view/README.md b/binary-tree-right-side-view/README.md new file mode 100644 index 0000000..8117c78 --- /dev/null +++ b/binary-tree-right-side-view/README.md @@ -0,0 +1,29 @@ +

199. Binary Tree Right Side View

Medium


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

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3,null,5,null,4]
+Output: [1,3,4]
+
+ +

Example 2:

+ +
Input: root = [1,null,3]
+Output: [1,3]
+
+ +

Example 3:

+ +
Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/binary-tree-right-side-view/binary-tree-right-side-view.cpp b/binary-tree-right-side-view/binary-tree-right-side-view.cpp new file mode 100644 index 0000000..334791b --- /dev/null +++ b/binary-tree-right-side-view/binary-tree-right-side-view.cpp @@ -0,0 +1,41 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector rightSideView(TreeNode* root) { + if(root == NULL) + return {}; + vector ans; + queue p; + p.push(root); + while(p.size()) + { + + int n = p.size(); + for(int i=0;ival); + + if(front->left) + p.push(front->left); + if(front->right) + p.push(front->right); + } + + } + return ans; + } +}; \ No newline at end of file diff --git a/binary-tree-zigzag-level-order-traversal/README.md b/binary-tree-zigzag-level-order-traversal/README.md new file mode 100644 index 0000000..600d22f --- /dev/null +++ b/binary-tree-zigzag-level-order-traversal/README.md @@ -0,0 +1,29 @@ +

103. Binary Tree Zigzag Level Order Traversal

Medium


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

+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: [[3],[20,9],[15,7]]
+
+ +

Example 2:

+ +
Input: root = [1]
+Output: [[1]]
+
+ +

Example 3:

+ +
Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 2000].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/binary-tree-zigzag-level-order-traversal/binary-tree-zigzag-level-order-traversal.cpp b/binary-tree-zigzag-level-order-traversal/binary-tree-zigzag-level-order-traversal.cpp new file mode 100644 index 0000000..c3a304b --- /dev/null +++ b/binary-tree-zigzag-level-order-traversal/binary-tree-zigzag-level-order-traversal.cpp @@ -0,0 +1,53 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> zigzagLevelOrder(TreeNode* root) { + if(root == NULL) + return {}; + vector> ans; + queue p; + p.push(root); + int l = 0; + while(p.size()) + { + vector level; + int n = p.size(); + + for(int i=0;ival); + + if(front->left) + p.push(front->left); + if(front->right) + p.push(front->right); + } + + if(l != 0) + { + reverse(level.begin(),level.end()); + l = 0; + } + else + { + l = 1; + } + ans.push_back(level); + + } + return ans; + } +}; \ No newline at end of file diff --git a/binary-watch/README.md b/binary-watch/README.md new file mode 100644 index 0000000..a947f89 --- /dev/null +++ b/binary-watch/README.md @@ -0,0 +1,37 @@ +

401. Binary Watch

Easy


A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.

+ +
    +
  • For example, the below binary watch reads "4:51".
  • +
+ +

+ +

Given an integer turnedOn which represents the number of LEDs that are currently on, return all possible times the watch could represent. You may return the answer in any order.

+ +

The hour must not contain a leading zero.

+ +
    +
  • For example, "01:00" is not valid. It should be "1:00".
  • +
+ +

The minute must be consist of two digits and may contain a leading zero.

+ +
    +
  • For example, "10:2" is not valid. It should be "10:02".
  • +
+ +

 

+

Example 1:

+
Input: turnedOn = 1
+Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]
+

Example 2:

+
Input: turnedOn = 9
+Output: []
+
+

 

+

Constraints:

+ +
    +
  • 0 <= turnedOn <= 10
  • +
+
\ No newline at end of file diff --git a/binary-watch/binary-watch.cpp b/binary-watch/binary-watch.cpp new file mode 100644 index 0000000..2f15693 --- /dev/null +++ b/binary-watch/binary-watch.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + + void helper(vector& res,vector& chart,int&num,int curr,int idx,int hour,int min){ + if(hour>11||min>59) return; + if(curr==num){ + string tmp=to_string(hour)+":"+((min<10)?"0":"")+to_string(min); + res.push_back(tmp); + return; + } + for(int i=idx;i readBinaryWatch(int num) { + vector chart({1,2,4,8,1,2,4,8,16,32}); + vector res; + helper(res,chart,num,0,0,0,0); + return res; + } +}; \ No newline at end of file diff --git a/build-array-from-permutation/README.md b/build-array-from-permutation/README.md new file mode 100644 index 0000000..a2f3be6 --- /dev/null +++ b/build-array-from-permutation/README.md @@ -0,0 +1,35 @@ +

1920. Build Array from Permutation

Easy


Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.

+ +

A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).

+ +

 

+

Example 1:

+ +
Input: nums = [0,2,1,5,3,4]
+Output: [0,1,2,4,5,3]
+Explanation: The array ans is built as follows: 
+ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
+    = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]
+    = [0,1,2,4,5,3]
+ +

Example 2:

+ +
Input: nums = [5,0,1,2,3,4]
+Output: [4,5,0,1,2,3]
+Explanation: The array ans is built as follows:
+ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
+    = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]
+    = [4,5,0,1,2,3]
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 0 <= nums[i] < nums.length
  • +
  • The elements in nums are distinct.
  • +
+ +

 

+

Follow-up: Can you solve it without using an extra space (i.e., O(1) memory)?

+
\ No newline at end of file diff --git a/build-array-from-permutation/build-array-from-permutation.cpp b/build-array-from-permutation/build-array-from-permutation.cpp new file mode 100644 index 0000000..2fb3780 --- /dev/null +++ b/build-array-from-permutation/build-array-from-permutation.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + vector buildArray(vector& nums) { + int maxNum = nums.size(); + for(int i=0; i312. Burst Balloons

Hard


You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.

+ +

If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.

+ +

Return the maximum coins you can collect by bursting the balloons wisely.

+ +

 

+

Example 1:

+ +
Input: nums = [3,1,5,8]
+Output: 167
+Explanation:
+nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
+coins =  3*1*5    +   3*5*8   +  1*3*8  + 1*8*1 = 167
+ +

Example 2:

+ +
Input: nums = [1,5]
+Output: 10
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 500
  • +
  • 0 <= nums[i] <= 100
  • +
+
\ No newline at end of file diff --git a/burst-balloons/burst-balloons.cpp b/burst-balloons/burst-balloons.cpp new file mode 100644 index 0000000..c64becd --- /dev/null +++ b/burst-balloons/burst-balloons.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int maxCoins(vector& nums) { + int n = nums.size(); + if(n == 0)return 0; + vector> dp(n,vector (n)); + + for(int gap = 0; gap < n;gap++ ) + { + for(int i=0,j = gap; j70. Climbing Stairs

Easy


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: n = 2
+Output: 2
+Explanation: There are two ways to climb to the top.
+1. 1 step + 1 step
+2. 2 steps
+
+ +

Example 2:

+ +
Input: n = 3
+Output: 3
+Explanation: There are three ways to climb to the top.
+1. 1 step + 1 step + 1 step
+2. 1 step + 2 steps
+3. 2 steps + 1 step
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 45
  • +
+
\ No newline at end of file diff --git a/climbing-stairs/climbing-stairs.cpp b/climbing-stairs/climbing-stairs.cpp new file mode 100644 index 0000000..fef2fc3 --- /dev/null +++ b/climbing-stairs/climbing-stairs.cpp @@ -0,0 +1,13 @@ +class Solution { +public: +int climbStairs(int n) { + int t[n+1]; + for(int i=0;i<=n;i++) t[i]=0; + t[1]=1; + if(n>=2) t[2]=2; + for(int i=3;i<=n;i++){ + t[i] = t[i-1]+t[i-2]; + } + return t[n]; + } +}; \ No newline at end of file diff --git a/clone-graph/README.md b/clone-graph/README.md new file mode 100644 index 0000000..4fe35c9 --- /dev/null +++ b/clone-graph/README.md @@ -0,0 +1,65 @@ +

133. Clone Graph

Medium


Given a reference of a node in a connected undirected graph.

+ +

Return a deep copy (clone) of the graph.

+ +

Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.

+ +
class Node {
+    public int val;
+    public List<Node> neighbors;
+}
+
+ +

 

+ +

Test case format:

+ +

For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.

+ +

An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.

+ +

The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.

+ +

 

+

Example 1:

+ +
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
+Output: [[2,4],[1,3],[2,4],[1,3]]
+Explanation: There are 4 nodes in the graph.
+1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
+2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
+3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
+4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
+
+ +

Example 2:

+ +
Input: adjList = [[]]
+Output: [[]]
+Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
+
+ +

Example 3:

+ +
Input: adjList = []
+Output: []
+Explanation: This an empty graph, it does not have any nodes.
+
+ +

Example 4:

+ +
Input: adjList = [[2],[1]]
+Output: [[2],[1]]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the graph is in the range [0, 100].
  • +
  • 1 <= Node.val <= 100
  • +
  • Node.val is unique for each node.
  • +
  • There are no repeated edges and no self-loops in the graph.
  • +
  • The Graph is connected and all nodes can be visited starting from the given node.
  • +
+
\ No newline at end of file diff --git a/coin-change-2/README.md b/coin-change-2/README.md new file mode 100644 index 0000000..96c3439 --- /dev/null +++ b/coin-change-2/README.md @@ -0,0 +1,43 @@ +

518. Coin Change 2

Medium


You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

+ +

Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.

+ +

You may assume that you have an infinite number of each kind of coin.

+ +

The answer is guaranteed to fit into a signed 32-bit integer.

+ +

 

+

Example 1:

+ +
Input: amount = 5, coins = [1,2,5]
+Output: 4
+Explanation: there are four ways to make up the amount:
+5=5
+5=2+2+1
+5=2+1+1+1
+5=1+1+1+1+1
+
+ +

Example 2:

+ +
Input: amount = 3, coins = [2]
+Output: 0
+Explanation: the amount of 3 cannot be made up just with coins of 2.
+
+ +

Example 3:

+ +
Input: amount = 10, coins = [10]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= coins.length <= 300
  • +
  • 1 <= coins[i] <= 5000
  • +
  • All the values of coins are unique.
  • +
  • 0 <= amount <= 5000
  • +
+
\ No newline at end of file diff --git a/coin-change-2/coin-change-2.cpp b/coin-change-2/coin-change-2.cpp new file mode 100644 index 0000000..17d564e --- /dev/null +++ b/coin-change-2/coin-change-2.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + + int change(int amount, vector& coins) { + int n = coins.size(); + if(amount == 0) { + return 1; + } + if(n==0) + return 0; + vector> dp; + dp.resize(n+2,vector(amount+2,-1)); + + for(int i=0;i j) { + dp[i][j] = dp[i-1][j]; + } else { + dp[i][j] = dp[i-1][j]+dp[i][j-coins[i-1]]; + } + } + } + return dp[n][amount]; + + } +}; \ No newline at end of file diff --git a/coin-change/README.md b/coin-change/README.md new file mode 100644 index 0000000..f3deb93 --- /dev/null +++ b/coin-change/README.md @@ -0,0 +1,35 @@ +

322. Coin Change

Medium


You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

+ +

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

+ +

You may assume that you have an infinite number of each kind of coin.

+ +

 

+

Example 1:

+ +
Input: coins = [1,2,5], amount = 11
+Output: 3
+Explanation: 11 = 5 + 5 + 1
+
+ +

Example 2:

+ +
Input: coins = [2], amount = 3
+Output: -1
+
+ +

Example 3:

+ +
Input: coins = [1], amount = 0
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= coins.length <= 12
  • +
  • 1 <= coins[i] <= 231 - 1
  • +
  • 0 <= amount <= 104
  • +
+
\ No newline at end of file diff --git a/coin-change/coin-change.cpp b/coin-change/coin-change.cpp new file mode 100644 index 0000000..503e101 --- /dev/null +++ b/coin-change/coin-change.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int coinChange(vector& coins, int amount) { + int Max = amount + 1; + vector dp(amount + 1, Max); + dp[0] = 0; + for (int i = 1; i <= amount; i++) { + for (int j = 0; j < coins.size(); j++) { + if (coins[j] <= i) { + dp[i] = min(dp[i], dp[i - coins[j]] + 1); + } + } + } + return dp[amount] > amount ? -1 : dp[amount]; + + } +}; \ No newline at end of file diff --git a/combination-sum-iv/README.md b/combination-sum-iv/README.md new file mode 100644 index 0000000..8504e57 --- /dev/null +++ b/combination-sum-iv/README.md @@ -0,0 +1,40 @@ +

377. Combination Sum IV

Medium


Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.

+ +

The test cases are generated so that the answer can fit in a 32-bit integer.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3], target = 4
+Output: 7
+Explanation:
+The possible combination ways are:
+(1, 1, 1, 1)
+(1, 1, 2)
+(1, 2, 1)
+(1, 3)
+(2, 1, 1)
+(2, 2)
+(3, 1)
+Note that different sequences are counted as different combinations.
+
+ +

Example 2:

+ +
Input: nums = [9], target = 3
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 200
  • +
  • 1 <= nums[i] <= 1000
  • +
  • All the elements of nums are unique.
  • +
  • 1 <= target <= 1000
  • +
+ +

 

+

Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?

+
\ No newline at end of file diff --git a/combination-sum-iv/combination-sum-iv.cpp b/combination-sum-iv/combination-sum-iv.cpp new file mode 100644 index 0000000..350d888 --- /dev/null +++ b/combination-sum-iv/combination-sum-iv.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int combinationSum4(vector& nums, int target) { + sort(begin(nums), end(nums)); + vector dp(target + 1); dp[0] = 1; + for (int curTarget = 1; curTarget <= target; curTarget++) + for (auto& num : nums) + if (num <= curTarget) dp[curTarget] += dp[curTarget - num]; + else break; + return dp[target]; +} +}; \ No newline at end of file diff --git a/combination-sum/README.md b/combination-sum/README.md new file mode 100644 index 0000000..fd7ca62 --- /dev/null +++ b/combination-sum/README.md @@ -0,0 +1,51 @@ +

39. Combination Sum

Medium


Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

+ +

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

+ +

It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

+ +

 

+

Example 1:

+ +
Input: candidates = [2,3,6,7], target = 7
+Output: [[2,2,3],[7]]
+Explanation:
+2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
+7 is a candidate, and 7 = 7.
+These are the only two combinations.
+
+ +

Example 2:

+ +
Input: candidates = [2,3,5], target = 8
+Output: [[2,2,2,2],[2,3,3],[3,5]]
+
+ +

Example 3:

+ +
Input: candidates = [2], target = 1
+Output: []
+
+ +

Example 4:

+ +
Input: candidates = [1], target = 1
+Output: [[1]]
+
+ +

Example 5:

+ +
Input: candidates = [1], target = 2
+Output: [[1,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= candidates.length <= 30
  • +
  • 1 <= candidates[i] <= 200
  • +
  • All elements of candidates are distinct.
  • +
  • 1 <= target <= 500
  • +
+
\ No newline at end of file diff --git a/combination-sum/combination-sum.cpp b/combination-sum/combination-sum.cpp new file mode 100644 index 0000000..7aebb52 --- /dev/null +++ b/combination-sum/combination-sum.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + +vector>result; +vectorcurrent; + +void function(vector& candidates,int target,int index) +{ + if(target==0){ + result.push_back(current); + return; + } + + if(index==candidates.size() || target<0)return; + + current.push_back(candidates[index]); + function(candidates,target-candidates[index],index); + current.pop_back(); + function(candidates,target,index+1); +} + +vector> combinationSum(vector& candidates, int target) { + function(candidates,target,0); + return result; +} +}; \ No newline at end of file diff --git a/combine-two-tables/README.md b/combine-two-tables/README.md new file mode 100644 index 0000000..01eeded --- /dev/null +++ b/combine-two-tables/README.md @@ -0,0 +1,32 @@ +

175. Combine Two Tables

Easy


Table: Person

+ +
+-------------+---------+
+| Column Name | Type    |
++-------------+---------+
+| PersonId    | int     |
+| FirstName   | varchar |
+| LastName    | varchar |
++-------------+---------+
+PersonId is the primary key column for this table.
+
+ +

Table: Address

+ +
+-------------+---------+
+| Column Name | Type    |
++-------------+---------+
+| AddressId   | int     |
+| PersonId    | int     |
+| City        | varchar |
+| State       | varchar |
++-------------+---------+
+AddressId is the primary key column for this table.
+
+ +

 

+ +

Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:

+ +
FirstName, LastName, City, State
+
+
\ No newline at end of file diff --git a/combine-two-tables/combine-two-tables.sql b/combine-two-tables/combine-two-tables.sql new file mode 100644 index 0000000..6658ef3 --- /dev/null +++ b/combine-two-tables/combine-two-tables.sql @@ -0,0 +1,4 @@ +# Write your MySQL query statement below +SELECT Person.FirstName, Person.LastName, Address.City, Address.State +FROM Person LEFT JOIN Address +on Person.PersonId = Address.PersonId \ No newline at end of file diff --git a/consecutive-characters/README.md b/consecutive-characters/README.md new file mode 100644 index 0000000..561fd51 --- /dev/null +++ b/consecutive-characters/README.md @@ -0,0 +1,45 @@ +

1446. Consecutive Characters

Easy


The power of the string is the maximum length of a non-empty substring that contains only one unique character.

+ +

Given a string s, return the power of s.

+ +

 

+

Example 1:

+ +
Input: s = "leetcode"
+Output: 2
+Explanation: The substring "ee" is of length 2 with the character 'e' only.
+
+ +

Example 2:

+ +
Input: s = "abbcccddddeeeeedcba"
+Output: 5
+Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
+
+ +

Example 3:

+ +
Input: s = "triplepillooooow"
+Output: 5
+
+ +

Example 4:

+ +
Input: s = "hooraaaaaaaaaaay"
+Output: 11
+
+ +

Example 5:

+ +
Input: s = "tourist"
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 500
  • +
  • s consists of only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/consecutive-characters/consecutive-characters.cpp b/consecutive-characters/consecutive-characters.cpp new file mode 100644 index 0000000..6ebd418 --- /dev/null +++ b/consecutive-characters/consecutive-characters.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int maxPower(string s) { + + if(s.length() <= 1) + return 1; + + int temp = 1; + int count = 0; + for(int i=1;i106. Construct Binary Tree from Inorder and Postorder Traversal

Medium


Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.

+ +

 

+

Example 1:

+ +
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
+Output: [3,9,20,null,null,15,7]
+
+ +

Example 2:

+ +
Input: inorder = [-1], postorder = [-1]
+Output: [-1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= inorder.length <= 3000
  • +
  • postorder.length == inorder.length
  • +
  • -3000 <= inorder[i], postorder[i] <= 3000
  • +
  • inorder and postorder consist of unique values.
  • +
  • Each value of postorder also appears in inorder.
  • +
  • inorder is guaranteed to be the inorder traversal of the tree.
  • +
  • postorder is guaranteed to be the postorder traversal of the tree.
  • +
+
\ No newline at end of file diff --git a/construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.cpp b/construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.cpp new file mode 100644 index 0000000..c874b50 --- /dev/null +++ b/construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.cpp @@ -0,0 +1,51 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode * helper(vector& postorder, vector& inorder,int poss,int pose,int ins,int ine) + { + if(poss > pose)return NULL; + + + int rootdata = postorder[pose]; + int rootIndex = -1; + for(int i=ins;i<=ine;i++) + { + if(inorder[i] == rootdata) + { + rootIndex = i; + break; + } + } + + int lins = ins; + int line = rootIndex-1; + int rins = rootIndex + 1; + int rine = ine; + int lposs = poss; + int lpose = lposs + (line-lins); + int rposs = lpose + 1; + int rpose = pose-1; + + TreeNode * root = new TreeNode(rootdata); + root->left = helper(postorder,inorder,lposs,lpose,lins,line); + root->right = helper(postorder,inorder,rposs,rpose,rins,rine); + + return root; + + } + + + TreeNode* buildTree(vector& inorder, vector& postorder) { + return helper(postorder,inorder,0,postorder.size()-1,0,inorder.size()-1); + } +}; \ No newline at end of file diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal/README.md b/construct-binary-tree-from-preorder-and-inorder-traversal/README.md new file mode 100644 index 0000000..63363b6 --- /dev/null +++ b/construct-binary-tree-from-preorder-and-inorder-traversal/README.md @@ -0,0 +1,28 @@ +

105. Construct Binary Tree from Preorder and Inorder Traversal

Medium


Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

+ +

 

+

Example 1:

+ +
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
+Output: [3,9,20,null,null,15,7]
+
+ +

Example 2:

+ +
Input: preorder = [-1], inorder = [-1]
+Output: [-1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= preorder.length <= 3000
  • +
  • inorder.length == preorder.length
  • +
  • -3000 <= preorder[i], inorder[i] <= 3000
  • +
  • preorder and inorder consist of unique values.
  • +
  • Each value of inorder also appears in preorder.
  • +
  • preorder is guaranteed to be the preorder traversal of the tree.
  • +
  • inorder is guaranteed to be the inorder traversal of the tree.
  • +
+
\ No newline at end of file diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal.cpp b/construct-binary-tree-from-preorder-and-inorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal.cpp new file mode 100644 index 0000000..4cf8e46 --- /dev/null +++ b/construct-binary-tree-from-preorder-and-inorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal.cpp @@ -0,0 +1,51 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode * helper(vector& preorder, vector& inorder,int pres,int pree,int ins,int ine) + { + if(pres > pree)return NULL; + + + int rootdata = preorder[pres]; + int rootIndex = -1; + for(int i=ins;i<=ine;i++) + { + if(inorder[i] == rootdata) + { + rootIndex = i; + break; + } + } + + int lins = ins; + int line = rootIndex-1; + int rins = rootIndex + 1; + int rine = ine; + int lpres = pres + 1; + int lpree = lpres + (line-lins); + int rpres = lpree + 1; + int rpree = pree; + + TreeNode * root = new TreeNode(rootdata); + root->left = helper(preorder,inorder,lpres,lpree,lins,line); + root->right = helper(preorder,inorder,rpres,rpree,rins,rine); + + return root; + + } + + TreeNode* buildTree(vector& preorder, vector& inorder) { + + return helper(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1); + } +}; \ No newline at end of file diff --git a/contains-duplicate-ii/README.md b/contains-duplicate-ii/README.md new file mode 100644 index 0000000..1e79687 --- /dev/null +++ b/contains-duplicate-ii/README.md @@ -0,0 +1,30 @@ +

219. Contains Duplicate II

Easy


Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,1], k = 3
+Output: true
+
+ +

Example 2:

+ +
Input: nums = [1,0,1,1], k = 1
+Output: true
+
+ +

Example 3:

+ +
Input: nums = [1,2,3,1,2,3], k = 2
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
  • 0 <= k <= 105
  • +
+
\ No newline at end of file diff --git a/contains-duplicate-ii/contains-duplicate-ii.cpp b/contains-duplicate-ii/contains-duplicate-ii.cpp new file mode 100644 index 0000000..43f158a --- /dev/null +++ b/contains-duplicate-ii/contains-duplicate-ii.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + bool containsNearbyDuplicate(vector& nums, int k) { + unordered_map mp; + for(int i = 0; i < nums.size(); i++) { + if(mp.count(nums[i])){ + int diff = abs(mp[nums[i]] - i); + if (diff <= k)return true; + } + mp[nums[i]] = i; + } + return false; + } +}; \ No newline at end of file diff --git a/contains-duplicate/README.md b/contains-duplicate/README.md new file mode 100644 index 0000000..3c222d4 --- /dev/null +++ b/contains-duplicate/README.md @@ -0,0 +1,21 @@ +

217. Contains Duplicate

Easy


Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

+ +

 

+

Example 1:

+
Input: nums = [1,2,3,1]
+Output: true
+

Example 2:

+
Input: nums = [1,2,3,4]
+Output: false
+

Example 3:

+
Input: nums = [1,1,1,3,3,4,3,2,4,2]
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/contains-duplicate/contains-duplicate.cpp b/contains-duplicate/contains-duplicate.cpp new file mode 100644 index 0000000..8363cd1 --- /dev/null +++ b/contains-duplicate/contains-duplicate.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + bool containsDuplicate(vector& nums) { + + map m; + int i=0; + for(i=0;i1290. Convert Binary Number in a Linked List to Integer

Easy


Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.

+ +

Return the decimal value of the number in the linked list.

+ +

 

+

Example 1:

+ +
Input: head = [1,0,1]
+Output: 5
+Explanation: (101) in base 2 = (5) in base 10
+
+ +

Example 2:

+ +
Input: head = [0]
+Output: 0
+
+ +

Example 3:

+ +
Input: head = [1]
+Output: 1
+
+ +

Example 4:

+ +
Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
+Output: 18880
+
+ +

Example 5:

+ +
Input: head = [0,0]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • The Linked List is not empty.
  • +
  • Number of nodes will not exceed 30.
  • +
  • Each node's value is either 0 or 1.
  • +
\ No newline at end of file diff --git a/convert-binary-number-in-a-linked-list-to-integer/convert-binary-number-in-a-linked-list-to-integer.cpp b/convert-binary-number-in-a-linked-list-to-integer/convert-binary-number-in-a-linked-list-to-integer.cpp new file mode 100644 index 0000000..4d37430 --- /dev/null +++ b/convert-binary-number-in-a-linked-list-to-integer/convert-binary-number-in-a-linked-list-to-integer.cpp @@ -0,0 +1,22 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + int getDecimalValue(ListNode* head) { + int ans = 0; + while(head != NULL) + { + ans = (ans<<1) + head->val; + head = head->next; + } + return ans; + } +}; \ No newline at end of file diff --git a/convert-sorted-array-to-binary-search-tree/README.md b/convert-sorted-array-to-binary-search-tree/README.md new file mode 100644 index 0000000..f590b05 --- /dev/null +++ b/convert-sorted-array-to-binary-search-tree/README.md @@ -0,0 +1,29 @@ +

108. Convert Sorted Array to Binary Search Tree

Easy


Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

+ +

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

+ +

 

+

Example 1:

+ +
Input: nums = [-10,-3,0,5,9]
+Output: [0,-3,9,-10,null,5]
+Explanation: [0,-10,5,null,-3,null,9] is also accepted:
+
+
+ +

Example 2:

+ +
Input: nums = [1,3]
+Output: [3,1]
+Explanation: [1,3] and [3,1] are both a height-balanced BSTs.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums is sorted in a strictly increasing order.
  • +
+
\ No newline at end of file diff --git a/convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.cpp b/convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.cpp new file mode 100644 index 0000000..e4bb3bb --- /dev/null +++ b/convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.cpp @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + TreeNode* helper(vector& nums,int start,int end) + { + if(start<= end) + { + int mid = (start+end)/2; + TreeNode * root = new TreeNode(nums[mid]); + TreeNode * left = helper(nums,start,mid-1); + TreeNode * right = helper(nums,mid+1,end); + root->left = left; + root->right = right; + return root; + } + return NULL; + } + + TreeNode* sortedArrayToBST(vector& nums) { + + if(nums.size()==0) + return NULL; + + return helper(nums,0,nums.size()-1); + + } +}; \ No newline at end of file diff --git a/copy-list-with-random-pointer/README.md b/copy-list-with-random-pointer/README.md new file mode 100644 index 0000000..fec390f --- /dev/null +++ b/copy-list-with-random-pointer/README.md @@ -0,0 +1,54 @@ +

138. Copy List with Random Pointer

Medium


A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.

+ +

Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.

+ +

For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.

+ +

Return the head of the copied linked list.

+ +

The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:

+ +
    +
  • val: an integer representing Node.val
  • +
  • random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.
  • +
+ +

Your code will only be given the head of the original linked list.

+ +

 

+

Example 1:

+ +
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
+Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
+
+ +

Example 2:

+ +
Input: head = [[1,1],[2,1]]
+Output: [[1,1],[2,1]]
+
+ +

Example 3:

+ +

+ +
Input: head = [[3,null],[3,0],[3,null]]
+Output: [[3,null],[3,0],[3,null]]
+
+ +

Example 4:

+ +
Input: head = []
+Output: []
+Explanation: The given linked list is empty (null pointer), so return null.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 1000
  • +
  • -10000 <= Node.val <= 10000
  • +
  • Node.random is null or is pointing to some node in the linked list.
  • +
+
\ No newline at end of file diff --git a/copy-list-with-random-pointer/copy-list-with-random-pointer.cpp b/copy-list-with-random-pointer/copy-list-with-random-pointer.cpp new file mode 100644 index 0000000..a2c1b70 --- /dev/null +++ b/copy-list-with-random-pointer/copy-list-with-random-pointer.cpp @@ -0,0 +1,61 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; + + Node(int _val) { + val = _val; + next = NULL; + random = NULL; + } +}; +*/ + +class Solution { +public: + Node* copyRandomList(Node* head) { + + if(head == NULL)return NULL; + + Node * it = head; + Node * front = head; + + while(it != NULL) + { + front = it->next; + Node * newNode = new Node(it->val); + it->next = newNode; + newNode->next = front; + it = front; + } + + it = head; + front = NULL; + while(it != NULL) + { + if(it->random) + { + it->next->random = it->random->next; + } + it = it->next->next; + } + + Node * dummy = new Node(0); + Node * temp = dummy; + + it = head; + while(it != NULL) + { + front = it->next->next; + temp->next = it->next; + it->next = front; + it = front; + temp = temp->next; + } + + return dummy->next; + } +}; \ No newline at end of file diff --git a/count-number-of-teams/README.md b/count-number-of-teams/README.md new file mode 100644 index 0000000..de2821c --- /dev/null +++ b/count-number-of-teams/README.md @@ -0,0 +1,42 @@ +

1395. Count Number of Teams

Medium


There are n soldiers standing in a line. Each soldier is assigned a unique rating value.

+ +

You have to form a team of 3 soldiers amongst them under the following rules:

+ +
    +
  • Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).
  • +
  • A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).
  • +
+ +

Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).

+ +

 

+

Example 1:

+ +
Input: rating = [2,5,3,4,1]
+Output: 3
+Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). 
+
+ +

Example 2:

+ +
Input: rating = [2,1,3]
+Output: 0
+Explanation: We can't form any team given the conditions.
+
+ +

Example 3:

+ +
Input: rating = [1,2,3,4]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • n == rating.length
  • +
  • 3 <= n <= 1000
  • +
  • 1 <= rating[i] <= 105
  • +
  • All the integers in rating are unique.
  • +
+
\ No newline at end of file diff --git a/count-sorted-vowel-strings/README.md b/count-sorted-vowel-strings/README.md new file mode 100644 index 0000000..a19f772 --- /dev/null +++ b/count-sorted-vowel-strings/README.md @@ -0,0 +1,34 @@ +

1641. Count Sorted Vowel Strings

Medium


Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.

+ +

A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet.

+ +

 

+

Example 1:

+ +
Input: n = 1
+Output: 5
+Explanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"].
+
+ +

Example 2:

+ +
Input: n = 2
+Output: 15
+Explanation: The 15 sorted strings that consist of vowels only are
+["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"].
+Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet.
+
+ +

Example 3:

+ +
Input: n = 33
+Output: 66045
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 50 
  • +
+
\ No newline at end of file diff --git a/count-substrings-that-differ-by-one-character/README.md b/count-substrings-that-differ-by-one-character/README.md new file mode 100644 index 0000000..9068aa5 --- /dev/null +++ b/count-substrings-that-differ-by-one-character/README.md @@ -0,0 +1,52 @@ +

1638. Count Substrings That Differ by One Character

Medium


Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character.

+ +

For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way.

+ +

Return the number of substrings that satisfy the condition above.

+ +

A substring is a contiguous sequence of characters within a string.

+ +

 

+

Example 1:

+ +
Input: s = "aba", t = "baba"
+Output: 6
+Explanation: The following are the pairs of substrings from s and t that differ by exactly 1 character:
+("aba", "baba")
+("aba", "baba")
+("aba", "baba")
+("aba", "baba")
+("aba", "baba")
+("aba", "baba")
+The underlined portions are the substrings that are chosen from s and t.
+
+​​Example 2: + +
Input: s = "ab", t = "bb"
+Output: 3
+Explanation: The following are the pairs of substrings from s and t that differ by 1 character:
+("ab", "bb")
+("ab", "bb")
+("ab", "bb")
+​​​​The underlined portions are the substrings that are chosen from s and t.
+
+Example 3: + +
Input: s = "a", t = "a"
+Output: 0
+
+ +

Example 4:

+ +
Input: s = "abe", t = "bbc"
+Output: 10
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length, t.length <= 100
  • +
  • s and t consist of lowercase English letters only.
  • +
+
\ No newline at end of file diff --git a/count-substrings-that-differ-by-one-character/count-substrings-that-differ-by-one-character.cpp b/count-substrings-that-differ-by-one-character/count-substrings-that-differ-by-one-character.cpp new file mode 100644 index 0000000..8aa82dc --- /dev/null +++ b/count-substrings-that-differ-by-one-character/count-substrings-that-differ-by-one-character.cpp @@ -0,0 +1,54 @@ +class Solution { +public: + int countSubstrings(string s, string t) { + // dp[i][j] := longest substring ends at s[i] and t[j] such that they are equal + // dp2[i][j] := longest substring starts at s[i] and t[j] such that they are equal + int m = s.length(), n = t.length(); + vector> dp(m + 2, vector(n + 2)); + vector> dp2(m + 2, vector(n + 2)); + + { + dp[1][1] = s[0] == t[0]; + + for (int i = 1; i <= m; i++) + dp[i][1] = s[i - 1] == t[0]; + + for (int j = 1; j <= n; j++) + dp[1][j] = s[0] == t[j - 1]; + + for (int i = 2; i <= m; i++) + for (int j = 2; j <= n; j++) { + if (s[i - 1] == t[j - 1]) + dp[i][j] = 1 + dp[i - 1][j - 1]; + } + } + + { + dp2[m][n] = s[m - 1] == t[n - 1]; + + for (int i = 1; i <= m; i++) + dp2[i][n] = s[i - 1] == t[n - 1]; + + for (int j = 1; j <= n; j++) + dp2[m][j] = s[m - 1] == t[j - 1]; + + for (int i = m - 1; i >= 1; i--) + for (int j = n - 1; j >= 1; j--) { + if (s[i - 1] == t[j - 1]) + dp2[i][j] = 1 + dp2[i + 1][j + 1]; + } + } + + int res = 0; + + for (int i = 0; i < m; i++) + for (int j = 0; j < n; j++) { + if (s[i] != t[j]) { + res += (dp[i][j] + 1) * (dp2[i + 2][j + 2] + 1); + } + } + + return res; + + } +}; \ No newline at end of file diff --git a/count-triplets-that-can-form-two-arrays-of-equal-xor/README.md b/count-triplets-that-can-form-two-arrays-of-equal-xor/README.md new file mode 100644 index 0000000..b01876f --- /dev/null +++ b/count-triplets-that-can-form-two-arrays-of-equal-xor/README.md @@ -0,0 +1,54 @@ +

1442. Count Triplets That Can Form Two Arrays of Equal XOR

Medium


Given an array of integers arr.

+ +

We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).

+ +

Let's define a and b as follows:

+ +
    +
  • a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
  • +
  • b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
  • +
+ +

Note that ^ denotes the bitwise-xor operation.

+ +

Return the number of triplets (i, j and k) Where a == b.

+ +

 

+

Example 1:

+ +
Input: arr = [2,3,1,6,7]
+Output: 4
+Explanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)
+
+ +

Example 2:

+ +
Input: arr = [1,1,1,1,1]
+Output: 10
+
+ +

Example 3:

+ +
Input: arr = [2,3]
+Output: 0
+
+ +

Example 4:

+ +
Input: arr = [1,3,5,7,9]
+Output: 3
+
+ +

Example 5:

+ +
Input: arr = [7,11,12,9,5,2,7,17,22]
+Output: 8
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 300
  • +
  • 1 <= arr[i] <= 10^8
  • +
\ No newline at end of file diff --git a/course-schedule-ii/README.md b/course-schedule-ii/README.md new file mode 100644 index 0000000..363108b --- /dev/null +++ b/course-schedule-ii/README.md @@ -0,0 +1,42 @@ +

210. Course Schedule II

Medium


There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

+ +
    +
  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
  • +
+ +

Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

+ +

 

+

Example 1:

+ +
Input: numCourses = 2, prerequisites = [[1,0]]
+Output: [0,1]
+Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].
+
+ +

Example 2:

+ +
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
+Output: [0,2,1,3]
+Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
+So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
+
+ +

Example 3:

+ +
Input: numCourses = 1, prerequisites = []
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= numCourses <= 2000
  • +
  • 0 <= prerequisites.length <= numCourses * (numCourses - 1)
  • +
  • prerequisites[i].length == 2
  • +
  • 0 <= ai, bi < numCourses
  • +
  • ai != bi
  • +
  • All the pairs [ai, bi] are distinct.
  • +
+
\ No newline at end of file diff --git a/course-schedule-ii/course-schedule-ii.cpp b/course-schedule-ii/course-schedule-ii.cpp new file mode 100644 index 0000000..058a519 --- /dev/null +++ b/course-schedule-ii/course-schedule-ii.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector findOrder(int numCourses, vector>& prerequisites) { + + vectoradj[numCourses]; + queueq; + vectorindegree(numCourses,0); + //store + for(int i =0; i< prerequisites.size(); i++ ){ + adj[prerequisites[i][1]].push_back(prerequisites[i][0]); + } + //indegree u -> v + for(int i =0; i < prerequisites.size(); i++){ + indegree[prerequisites[i][0]]++; + + } + //push into q,indegree having 0 + for(int i =0; i< indegree.size(); i++){ + if(indegree[i] == 0)q.push(i); + } + vectorresult; + //Simple BFS and keep storing indegree values equal to 0 into result vector + while(!q.empty()){ + int v = q.front(); + q.pop(); + for(auto it : adj[v]){ + indegree[it]--; + if(indegree[it] == 0)q.push(it); + } + result.emplace_back(v); + } + //check case + if (result.size() != numCourses) + result.clear(); + return result; + } +}; \ No newline at end of file diff --git a/course-schedule/README.md b/course-schedule/README.md new file mode 100644 index 0000000..9ce82ab --- /dev/null +++ b/course-schedule/README.md @@ -0,0 +1,36 @@ +

207. Course Schedule

Medium


There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

+ +
    +
  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
  • +
+ +

Return true if you can finish all courses. Otherwise, return false.

+ +

 

+

Example 1:

+ +
Input: numCourses = 2, prerequisites = [[1,0]]
+Output: true
+Explanation: There are a total of 2 courses to take. 
+To take course 1 you should have finished course 0. So it is possible.
+
+ +

Example 2:

+ +
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
+Output: false
+Explanation: There are a total of 2 courses to take. 
+To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= numCourses <= 105
  • +
  • 0 <= prerequisites.length <= 5000
  • +
  • prerequisites[i].length == 2
  • +
  • 0 <= ai, bi < numCourses
  • +
  • All the pairs prerequisites[i] are unique.
  • +
+
\ No newline at end of file diff --git a/custom-sort-string/README.md b/custom-sort-string/README.md new file mode 100644 index 0000000..f693659 --- /dev/null +++ b/custom-sort-string/README.md @@ -0,0 +1,26 @@ +

791. Custom Sort String

Medium


order and str are strings composed of lowercase letters. In order, no letter occurs more than once.

+ +

order was sorted in some custom order previously. We want to permute the characters of str so that they match the order that order was sorted. More specifically, if x occurs before y in order, then x should occur before y in the returned string.

+ +

Return any permutation of str (as a string) that satisfies this property.

+ +
Example:
+Input: 
+order = "cba"
+str = "abcd"
+Output: "cbad"
+Explanation: 
+"a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a". 
+Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.
+
+ +

 

+ +

Note:

+ +
    +
  • order has length at most 26, and no character is repeated in order.
  • +
  • str has length at most 200.
  • +
  • order and str consist of lowercase letters only.
  • +
+
\ No newline at end of file diff --git a/custom-sort-string/custom-sort-string.cpp b/custom-sort-string/custom-sort-string.cpp new file mode 100644 index 0000000..117e60a --- /dev/null +++ b/custom-sort-string/custom-sort-string.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + string customSortString(string order, string str) + { + unordered_map mp; + for(auto i:str) + mp[i]++; + string res; + for(auto i:order) + { + res+=string(mp[i],i); + mp[i]=0; + } + for (auto i : mp) { + res += string(i.second, i.first); + } + return res; + } +}; \ No newline at end of file diff --git a/daily-temperatures/README.md b/daily-temperatures/README.md new file mode 100644 index 0000000..b9fb76b --- /dev/null +++ b/daily-temperatures/README.md @@ -0,0 +1,21 @@ +

739. Daily Temperatures

Medium


Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

+ +

 

+

Example 1:

+
Input: temperatures = [73,74,75,71,69,72,76,73]
+Output: [1,1,4,2,1,1,0,0]
+

Example 2:

+
Input: temperatures = [30,40,50,60]
+Output: [1,1,1,0]
+

Example 3:

+
Input: temperatures = [30,60,90]
+Output: [1,1,0]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= temperatures.length <= 105
  • +
  • 30 <= temperatures[i] <= 100
  • +
+
\ No newline at end of file diff --git a/daily-temperatures/daily-temperatures.cpp b/daily-temperatures/daily-temperatures.cpp new file mode 100644 index 0000000..b7c161e --- /dev/null +++ b/daily-temperatures/daily-temperatures.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector dailyTemperatures(vector& temperatures) { + vector res(temperatures.size()); + for (int i = temperatures.size() - 1; i >= 0; --i) { + int j = i+1; + while (j < temperatures.size() && temperatures[j] <= temperatures[i]) { + if (res[j] > 0) j = res[j] + j; + else j = temperatures.size(); + } + // either j == size || temperatures[j] > temperatures[i] + if (j < temperatures.size()) res[i] = j - i; + } + return res; +} +}; \ No newline at end of file diff --git a/decode-ways-ii/README.md b/decode-ways-ii/README.md new file mode 100644 index 0000000..ce34689 --- /dev/null +++ b/decode-ways-ii/README.md @@ -0,0 +1,59 @@ +

639. Decode Ways II

Hard


A message containing letters from A-Z can be encoded into numbers using the following mapping:

+ +
'A' -> "1"
+'B' -> "2"
+...
+'Z' -> "26"
+
+ +

To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:

+ +
    +
  • "AAJF" with the grouping (1 1 10 6)
  • +
  • "KJF" with the grouping (11 10 6)
  • +
+ +

Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".

+ +

In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent.

+ +

Given a string s containing digits and the '*' character, return the number of ways to decode it.

+ +

Since the answer may be very large, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: s = "*"
+Output: 9
+Explanation: The encoded message can represent any of the encoded messages "1", "2", "3", "4", "5", "6", "7", "8", or "9".
+Each of these can be decoded to the strings "A", "B", "C", "D", "E", "F", "G", "H", and "I" respectively.
+Hence, there are a total of 9 ways to decode "*".
+
+ +

Example 2:

+ +
Input: s = "1*"
+Output: 18
+Explanation: The encoded message can represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19".
+Each of these encoded messages have 2 ways to be decoded (e.g. "11" can be decoded to "AA" or "K").
+Hence, there are a total of 9 * 2 = 18 ways to decode "1*".
+
+ +

Example 3:

+ +
Input: s = "2*"
+Output: 15
+Explanation: The encoded message can represent any of the encoded messages "21", "22", "23", "24", "25", "26", "27", "28", or "29".
+"21", "22", "23", "24", "25", and "26" have 2 ways of being decoded, but "27", "28", and "29" only have 1 way.
+Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode "2*".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s[i] is a digit or '*'.
  • +
+
\ No newline at end of file diff --git a/decode-ways/README.md b/decode-ways/README.md new file mode 100644 index 0000000..07eac2a --- /dev/null +++ b/decode-ways/README.md @@ -0,0 +1,60 @@ +

91. Decode Ways

Medium


A message containing letters from A-Z can be encoded into numbers using the following mapping:

+ +
'A' -> "1"
+'B' -> "2"
+...
+'Z' -> "26"
+
+ +

To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:

+ +
    +
  • "AAJF" with the grouping (1 1 10 6)
  • +
  • "KJF" with the grouping (11 10 6)
  • +
+ +

Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".

+ +

Given a string s containing only digits, return the number of ways to decode it.

+ +

The answer is guaranteed to fit in a 32-bit integer.

+ +

 

+

Example 1:

+ +
Input: s = "12"
+Output: 2
+Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
+
+ +

Example 2:

+ +
Input: s = "226"
+Output: 3
+Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
+
+ +

Example 3:

+ +
Input: s = "0"
+Output: 0
+Explanation: There is no character that is mapped to a number starting with 0.
+The only valid mappings with 0 are 'J' -> "10" and 'T' -> "20", neither of which start with 0.
+Hence, there are no valid ways to decode this since all digits need to be mapped.
+
+ +

Example 4:

+ +
Input: s = "06"
+Output: 0
+Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 100
  • +
  • s contains only digits and may contain leading zero(s).
  • +
+
\ No newline at end of file diff --git a/decode-ways/decode-ways.cpp b/decode-ways/decode-ways.cpp new file mode 100644 index 0000000..b7a1213 --- /dev/null +++ b/decode-ways/decode-ways.cpp @@ -0,0 +1,26 @@ +class Solution { +public: +int numDecodings(string s) { + if (!s.size() || s.front() == '0') return 0; + // r2: decode ways of s[i-2] , r1: decode ways of s[i-1] + int r1 = 1, r2 = 1; + + for (int i = 1; i < s.size(); i++) { + // zero voids ways of the last because zero cannot be used separately + if (s[i] == '0') r1 = 0; + + // possible two-digit letter, so new r1 is sum of both while new r2 is the old r1 + if (s[i - 1] == '1' || s[i - 1] == '2' && s[i] <= '6') { + r1 = r2 + r1; + r2 = r1 - r2; + } + + // one-digit letter, no new way added + else { + r2 = r1; + } + } + + return r1; +} +}; \ No newline at end of file diff --git a/deepest-leaves-sum/README.md b/deepest-leaves-sum/README.md new file mode 100644 index 0000000..9652701 --- /dev/null +++ b/deepest-leaves-sum/README.md @@ -0,0 +1,22 @@ +

1302. Deepest Leaves Sum

Medium


Given the root of a binary tree, return the sum of values of its deepest leaves. +

 

+

Example 1:

+ +
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
+Output: 15
+
+ +

Example 2:

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

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • 1 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/deepest-leaves-sum/deepest-leaves-sum.cpp b/deepest-leaves-sum/deepest-leaves-sum.cpp new file mode 100644 index 0000000..61e09f1 --- /dev/null +++ b/deepest-leaves-sum/deepest-leaves-sum.cpp @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int max_depth; + int deepestLeavesSum(TreeNode* root) { + max_depth = depthHelper(root); + return sumHelper(root, 0); + } + + int sumHelper (TreeNode* root, int depth) { + if(!root) return 0; + if(depth==max_depth-1) return root->val; + return sumHelper(root->left, depth+1) + + sumHelper(root->right, depth+1); + + } + int depthHelper(TreeNode* root) { + if(!root) return 0; + return max(1+ depthHelper(root->left), 1+ depthHelper(root->right)); + } +}; \ No newline at end of file diff --git a/delete-and-earn/README.md b/delete-and-earn/README.md new file mode 100644 index 0000000..83932cd --- /dev/null +++ b/delete-and-earn/README.md @@ -0,0 +1,37 @@ +

740. Delete and Earn

Medium


You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:

+ +
    +
  • Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.
  • +
+ +

Return the maximum number of points you can earn by applying the above operation some number of times.

+ +

 

+

Example 1:

+ +
Input: nums = [3,4,2]
+Output: 6
+Explanation: You can perform the following operations:
+- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].
+- Delete 2 to earn 2 points. nums = [].
+You earn a total of 6 points.
+
+ +

Example 2:

+ +
Input: nums = [2,2,3,3,3,4]
+Output: 9
+Explanation: You can perform the following operations:
+- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].
+- Delete a 3 again to earn 3 points. nums = [3].
+- Delete a 3 once more to earn 3 points. nums = [].
+You earn a total of 9 points.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2 * 104
  • +
  • 1 <= nums[i] <= 104
  • +
+
\ No newline at end of file diff --git a/delete-leaves-with-a-given-value/README.md b/delete-leaves-with-a-given-value/README.md new file mode 100644 index 0000000..50dc740 --- /dev/null +++ b/delete-leaves-with-a-given-value/README.md @@ -0,0 +1,53 @@ +

1325. Delete Leaves With a Given Value

Medium


Given a binary tree root and an integer target, delete all the leaf nodes with value target.

+ +

Note that once you delete a leaf node with value targetif it's parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you can't).

+ +

 

+

Example 1:

+ +

+ +
Input: root = [1,2,3,2,null,2,4], target = 2
+Output: [1,null,3,null,4]
+Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). 
+After removing, new nodes become leaf nodes with value (target = 2) (Picture in center).
+
+ +

Example 2:

+ +

+ +
Input: root = [1,3,3,3,2], target = 3
+Output: [1,3,null,null,2]
+
+ +

Example 3:

+ +

+ +
Input: root = [1,2,null,2,null,2], target = 2
+Output: [1]
+Explanation: Leaf nodes in green with value (target = 2) are removed at each step.
+
+ +

Example 4:

+ +
Input: root = [1,1,1], target = 1
+Output: []
+
+ +

Example 5:

+ +
Input: root = [1,2,3], target = 1
+Output: [1,2,3]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= target <= 1000
  • +
  • The given binary tree will have between 1 and 3000 nodes.
  • +
  • Each node's value is between [1, 1000].
  • +
+
\ No newline at end of file diff --git a/delete-node-in-a-bst/README.md b/delete-node-in-a-bst/README.md new file mode 100644 index 0000000..90e77ba --- /dev/null +++ b/delete-node-in-a-bst/README.md @@ -0,0 +1,47 @@ +

450. Delete Node in a BST

Medium


Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

+ +

Basically, the deletion can be divided into two stages:

+ +
    +
  1. Search for a node to remove.
  2. +
  3. If the node is found, delete the node.
  4. +
+ +

 

+

Example 1:

+ +
Input: root = [5,3,6,2,4,null,7], key = 3
+Output: [5,4,6,2,null,null,7]
+Explanation: Given key to delete is 3. So we find the node with value 3 and delete it.
+One valid answer is [5,4,6,2,null,null,7], shown in the above BST.
+Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.
+
+
+ +

Example 2:

+ +
Input: root = [5,3,6,2,4,null,7], key = 0
+Output: [5,3,6,2,4,null,7]
+Explanation: The tree does not contain a node with value = 0.
+
+ +

Example 3:

+ +
Input: root = [], key = 0
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • -105 <= Node.val <= 105
  • +
  • Each node has a unique value.
  • +
  • root is a valid binary search tree.
  • +
  • -105 <= key <= 105
  • +
+ +

 

+

Follow up: Could you solve it with time complexity O(height of tree)?

+
\ No newline at end of file diff --git a/delete-node-in-a-bst/delete-node-in-a-bst.cpp b/delete-node-in-a-bst/delete-node-in-a-bst.cpp new file mode 100644 index 0000000..b9ca729 --- /dev/null +++ b/delete-node-in-a-bst/delete-node-in-a-bst.cpp @@ -0,0 +1,65 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode * findMini (TreeNode * root) + { + if(root == NULL) + return NULL; + TreeNode * temp = root; + while(temp->left != NULL) + { + temp = temp->left; + } + return temp; + + } + + TreeNode* deleteNode(TreeNode* root, int key) { + + if(root == NULL) + return root; + if(root->val > key) + root->left = deleteNode(root->left,key); + if(root->val < key) + root->right = deleteNode(root->right,key); + if(root->val == key) + { + if(root->left == NULL && root->right == NULL) + { + delete root; + return NULL; + } + if(root->left == NULL) + { + TreeNode * temp = root->right; + root->right = NULL; + delete root; + return temp; + } + if(root->right == NULL) + { + TreeNode * temp = root->left; + root->left = NULL; + delete root; + return temp; + } + + TreeNode * temp = findMini(root->right); + root->val = temp->val; + root->right = deleteNode(root->right,temp->val); + //delete temp; + return root; + } + return root; + } +}; \ No newline at end of file diff --git a/delete-node-in-a-linked-list/README.md b/delete-node-in-a-linked-list/README.md new file mode 100644 index 0000000..87760a2 --- /dev/null +++ b/delete-node-in-a-linked-list/README.md @@ -0,0 +1,47 @@ +

237. Delete Node in a Linked List

Easy


Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.

+ +

It is guaranteed that the node to be deleted is not a tail node in the list.

+ +

 

+

Example 1:

+ +
Input: head = [4,5,1,9], node = 5
+Output: [4,1,9]
+Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
+
+ +

Example 2:

+ +
Input: head = [4,5,1,9], node = 1
+Output: [4,5,9]
+Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
+
+ +

Example 3:

+ +
Input: head = [1,2,3,4], node = 3
+Output: [1,2,4]
+
+ +

Example 4:

+ +
Input: head = [0,1], node = 0
+Output: [1]
+
+ +

Example 5:

+ +
Input: head = [-3,5,-99], node = -3
+Output: [5,-99]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the given list is in the range [2, 1000].
  • +
  • -1000 <= Node.val <= 1000
  • +
  • The value of each node in the list is unique.
  • +
  • The node to be deleted is in the list and is not a tail node
  • +
+
\ No newline at end of file diff --git a/delete-node-in-a-linked-list/delete-node-in-a-linked-list.cpp b/delete-node-in-a-linked-list/delete-node-in-a-linked-list.cpp new file mode 100644 index 0000000..6aab0b7 --- /dev/null +++ b/delete-node-in-a-linked-list/delete-node-in-a-linked-list.cpp @@ -0,0 +1,17 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + void deleteNode(ListNode* node) { + + node->val = node->next->val; + node->next = node->next->next; + + } +}; \ No newline at end of file diff --git a/destination-city/README.md b/destination-city/README.md new file mode 100644 index 0000000..41a0181 --- /dev/null +++ b/destination-city/README.md @@ -0,0 +1,41 @@ +

1436. Destination City

Easy


You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.

+ +

It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.

+ +

 

+

Example 1:

+ +
Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
+Output: "Sao Paulo" 
+Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo".
+
+ +

Example 2:

+ +
Input: paths = [["B","C"],["D","B"],["C","A"]]
+Output: "A"
+Explanation: All possible trips are: 
+"D" -> "B" -> "C" -> "A". 
+"B" -> "C" -> "A". 
+"C" -> "A". 
+"A". 
+Clearly the destination city is "A".
+
+ +

Example 3:

+ +
Input: paths = [["A","Z"]]
+Output: "Z"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= paths.length <= 100
  • +
  • paths[i].length == 2
  • +
  • 1 <= cityAi.length, cityBi.length <= 10
  • +
  • cityAi != cityBi
  • +
  • All strings consist of lowercase and uppercase English letters and the space character.
  • +
+
\ No newline at end of file diff --git a/detonate-the-maximum-bombs/README.md b/detonate-the-maximum-bombs/README.md new file mode 100644 index 0000000..fc99ad9 --- /dev/null +++ b/detonate-the-maximum-bombs/README.md @@ -0,0 +1,49 @@ +

2101. Detonate the Maximum Bombs

Medium


You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb.

+ +

The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri denotes the radius of its range.

+ +

You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges.

+ +

Given the list of bombs, return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb.

+ +

 

+

Example 1:

+ +
Input: bombs = [[2,1,3],[6,1,4]]
+Output: 2
+Explanation:
+The above figure shows the positions and ranges of the 2 bombs.
+If we detonate the left bomb, the right bomb will not be affected.
+But if we detonate the right bomb, both bombs will be detonated.
+So the maximum bombs that can be detonated is max(1, 2) = 2.
+
+ +

Example 2:

+ +
Input: bombs = [[1,1,5],[10,10,5]]
+Output: 1
+Explanation:
+Detonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.
+
+ +

Example 3:

+ +
Input: bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]
+Output: 5
+Explanation:
+The best bomb to detonate is bomb 0 because:
+- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.
+- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.
+- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.
+Thus all 5 bombs are detonated.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= bombs.length <= 100
  • +
  • bombs[i].length == 3
  • +
  • 1 <= xi, yi, ri <= 105
  • +
+
\ No newline at end of file diff --git a/detonate-the-maximum-bombs/detonate-the-maximum-bombs.cpp b/detonate-the-maximum-bombs/detonate-the-maximum-bombs.cpp new file mode 100644 index 0000000..4003731 --- /dev/null +++ b/detonate-the-maximum-bombs/detonate-the-maximum-bombs.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + // from gfg https://www.geeksforgeeks.org/find-if-a-point-lies-inside-or-on-circle/ + bool isInside(int circle_x, int circle_y, + int rad, int x, int y) + { + + if ((x - circle_x) * (x - circle_x) + + (y - circle_y) * (y - circle_y) <= rad * rad) + return true; + else + return false; +} + int maximumDetonation(vector>& bs) { + int res = 0, sz = bs.size(); + vector> al(bs.size()); + for (int i = 0; i < sz; ++i) { + long long x = bs[i][0], y = bs[i][1], r2 = (long long)bs[i][2] * bs[i][2]; + for (int j = 0; j < bs.size(); ++j) + if ((x - bs[j][0]) * (x - bs[j][0]) + (y - bs[j][1]) * (y - bs[j][1]) <= r2) + al[i].push_back(j); + } + for (int i = 0; i < sz && res < sz; ++i) { + vector q{i}; + unordered_set detonated{i}; + while (!q.empty()) { + vector q1; + for (int j : q) + for (int k : al[j]) + if (detonated.insert(k).second) + q1.push_back(k); + swap(q, q1); + } + res = max((int)detonated.size(), res); + } + return res; + } +}; \ No newline at end of file diff --git a/di-string-match/README.md b/di-string-match/README.md new file mode 100644 index 0000000..a2cb4a9 --- /dev/null +++ b/di-string-match/README.md @@ -0,0 +1,28 @@ +

942. DI String Match

Easy


A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:

+ +
    +
  • s[i] == 'I' if perm[i] < perm[i + 1], and
  • +
  • s[i] == 'D' if perm[i] > perm[i + 1].
  • +
+ +

Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.

+ +

 

+

Example 1:

+
Input: s = "IDID"
+Output: [0,4,1,3,2]
+

Example 2:

+
Input: s = "III"
+Output: [0,1,2,3]
+

Example 3:

+
Input: s = "DDI"
+Output: [3,2,0,1]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s[i] is either 'I' or 'D'.
  • +
+
\ No newline at end of file diff --git a/di-string-match/di-string-match.cpp b/di-string-match/di-string-match.cpp new file mode 100644 index 0000000..48d917f --- /dev/null +++ b/di-string-match/di-string-match.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + vector diStringMatch(string S) { + vector res; + for (int l = 0, h = S.size(), i = 0; i <= S.size(); ++i) + res.push_back(i == S.size() || S[i] == 'I' ? l++ : h--); + return res; +} +}; \ No newline at end of file diff --git a/diameter-of-binary-tree/README.md b/diameter-of-binary-tree/README.md new file mode 100644 index 0000000..cde9546 --- /dev/null +++ b/diameter-of-binary-tree/README.md @@ -0,0 +1,28 @@ +

543. Diameter of Binary Tree

Easy


Given the root of a binary tree, return the length of the diameter of the tree.

+ +

The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

+ +

The length of a path between two nodes is represented by the number of edges between them.

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3,4,5]
+Output: 3
+Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
+
+ +

Example 2:

+ +
Input: root = [1,2]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/diameter-of-binary-tree/diameter-of-binary-tree.cpp b/diameter-of-binary-tree/diameter-of-binary-tree.cpp new file mode 100644 index 0000000..25fa113 --- /dev/null +++ b/diameter-of-binary-tree/diameter-of-binary-tree.cpp @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + pair hd(TreeNode * root) + { + if(root == NULL) + { + pair p; + p.first = 0; + p.second = 0; + return p; + } + pair left = hd(root->left); + pair right = hd(root->right); + + pair ans; + ans.first = 1 + max(left.first , right.first); + ans.second = max( left.first + right.first,max(left.second,right.second)); + return ans; + + + } + + int diameterOfBinaryTree(TreeNode* root) { + pair p; + p = hd(root); + return p.second; + } +}; \ No newline at end of file diff --git a/different-ways-to-add-parentheses/README.md b/different-ways-to-add-parentheses/README.md new file mode 100644 index 0000000..33c65ab --- /dev/null +++ b/different-ways-to-add-parentheses/README.md @@ -0,0 +1,33 @@ +

241. Different Ways to Add Parentheses

Medium


Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: expression = "2-1-1"
+Output: [0,2]
+Explanation:
+((2-1)-1) = 0 
+(2-(1-1)) = 2
+
+ +

Example 2:

+ +
Input: expression = "2*3-4*5"
+Output: [-34,-14,-10,-10,10]
+Explanation:
+(2*(3-(4*5))) = -34 
+((2*3)-(4*5)) = -14 
+((2*(3-4))*5) = -10 
+(2*((3-4)*5)) = -10 
+(((2*3)-4)*5) = 10
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= expression.length <= 20
  • +
  • expression consists of digits and the operator '+', '-', and '*'.
  • +
  • All the integer values in the input expression are in the range [0, 99].
  • +
+
\ No newline at end of file diff --git a/divide-two-integers/README.md b/divide-two-integers/README.md new file mode 100644 index 0000000..935ef13 --- /dev/null +++ b/divide-two-integers/README.md @@ -0,0 +1,43 @@ +

29. Divide Two Integers

Medium


Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.

+ +

Return the quotient after dividing dividend by divisor.

+ +

The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.

+ +

Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, assume that your function returns 231 − 1 when the division result overflows.

+ +

 

+

Example 1:

+ +
Input: dividend = 10, divisor = 3
+Output: 3
+Explanation: 10/3 = truncate(3.33333..) = 3.
+
+ +

Example 2:

+ +
Input: dividend = 7, divisor = -3
+Output: -2
+Explanation: 7/-3 = truncate(-2.33333..) = -2.
+
+ +

Example 3:

+ +
Input: dividend = 0, divisor = 1
+Output: 0
+
+ +

Example 4:

+ +
Input: dividend = 1, divisor = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= dividend, divisor <= 231 - 1
  • +
  • divisor != 0
  • +
+
\ No newline at end of file diff --git a/edit-distance/README.md b/edit-distance/README.md new file mode 100644 index 0000000..fd57dbc --- /dev/null +++ b/edit-distance/README.md @@ -0,0 +1,41 @@ +

72. Edit Distance

Hard


Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.

+ +

You have the following three operations permitted on a word:

+ +
    +
  • Insert a character
  • +
  • Delete a character
  • +
  • Replace a character
  • +
+ +

 

+

Example 1:

+ +
Input: word1 = "horse", word2 = "ros"
+Output: 3
+Explanation: 
+horse -> rorse (replace 'h' with 'r')
+rorse -> rose (remove 'r')
+rose -> ros (remove 'e')
+
+ +

Example 2:

+ +
Input: word1 = "intention", word2 = "execution"
+Output: 5
+Explanation: 
+intention -> inention (remove 't')
+inention -> enention (replace 'i' with 'e')
+enention -> exention (replace 'n' with 'x')
+exention -> exection (replace 'n' with 'c')
+exection -> execution (insert 'u')
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= word1.length, word2.length <= 500
  • +
  • word1 and word2 consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/encode-and-decode-tinyurl/README.md b/encode-and-decode-tinyurl/README.md new file mode 100644 index 0000000..34013ef --- /dev/null +++ b/encode-and-decode-tinyurl/README.md @@ -0,0 +1,34 @@ +

535. Encode and Decode TinyURL

Medium


Note: This is a companion problem to the System Design problem: Design TinyURL.
+ +

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL.

+ +

There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

+ +

Implement the Solution class:

+ +
    +
  • Solution() Initializes the object of the system.
  • +
  • String encode(String longUrl) Returns a tiny URL for the given longUrl.
  • +
  • String decode(String shortUrl) Returns the original long URL for the given shortUrl. It is guaranteed that the given shortUrl was encoded by the same object.
  • +
+ +

 

+

Example 1:

+ +
Input: url = "https://leetcode.com/problems/design-tinyurl"
+Output: "https://leetcode.com/problems/design-tinyurl"
+
+Explanation:
+Solution obj = new Solution();
+string tiny = obj.encode(url); // returns the encoded tiny url.
+string ans = obj.decode(tiny); // returns the original url after deconding it.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= url.length <= 104
  • +
  • url is guranteed to be a valid URL.
  • +
+
\ No newline at end of file diff --git a/encode-and-decode-tinyurl/encode-and-decode-tinyurl.cpp b/encode-and-decode-tinyurl/encode-and-decode-tinyurl.cpp new file mode 100644 index 0000000..f726b81 --- /dev/null +++ b/encode-and-decode-tinyurl/encode-and-decode-tinyurl.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + + // Encodes a URL to a shortened URL. + string encode(string longUrl) { + return longUrl; + } + + // Decodes a shortened URL to its original URL. + string decode(string shortUrl) { + return shortUrl; + } +}; \ No newline at end of file diff --git a/excel-sheet-column-title/README.md b/excel-sheet-column-title/README.md new file mode 100644 index 0000000..8a6c269 --- /dev/null +++ b/excel-sheet-column-title/README.md @@ -0,0 +1,45 @@ +

168. Excel Sheet Column Title

Easy


Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

+ +

For example:

+ +
A -> 1
+B -> 2
+C -> 3
+...
+Z -> 26
+AA -> 27
+AB -> 28 
+...
+
+ +

 

+

Example 1:

+ +
Input: columnNumber = 1
+Output: "A"
+
+ +

Example 2:

+ +
Input: columnNumber = 28
+Output: "AB"
+
+ +

Example 3:

+ +
Input: columnNumber = 701
+Output: "ZY"
+
+ +

Example 4:

+ +
Input: columnNumber = 2147483647
+Output: "FXSHRXW"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= columnNumber <= 231 - 1
  • +
\ No newline at end of file diff --git a/excel-sheet-column-title/excel-sheet-column-title.cpp b/excel-sheet-column-title/excel-sheet-column-title.cpp new file mode 100644 index 0000000..9f98b5b --- /dev/null +++ b/excel-sheet-column-title/excel-sheet-column-title.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + string convertToTitle(int n) { + + string res; + + char tmp; + + while(n){ + + n -= 1; + + tmp = 'A' + n % 26; + + res = tmp + res; + + n /= 26; + + } + + return res; + +} +}; diff --git a/fibonacci-number/README.md b/fibonacci-number/README.md new file mode 100644 index 0000000..3dfc343 --- /dev/null +++ b/fibonacci-number/README.md @@ -0,0 +1,37 @@ +

509. Fibonacci Number

Easy


The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

+ +
F(0) = 0, F(1) = 1
+F(n) = F(n - 1) + F(n - 2), for n > 1.
+
+ +

Given n, calculate F(n).

+ +

 

+

Example 1:

+ +
Input: n = 2
+Output: 1
+Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
+
+ +

Example 2:

+ +
Input: n = 3
+Output: 2
+Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
+
+ +

Example 3:

+ +
Input: n = 4
+Output: 3
+Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 30
  • +
+
\ No newline at end of file diff --git a/fibonacci-number/fibonacci-number.cpp b/fibonacci-number/fibonacci-number.cpp new file mode 100644 index 0000000..e6f38d8 --- /dev/null +++ b/fibonacci-number/fibonacci-number.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + int fib(int N) { + double phi = (sqrt(5) + 1) / 2; + return round(pow(phi, N) / sqrt(5)); + } +}; \ No newline at end of file diff --git a/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/README.md b/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/README.md new file mode 100644 index 0000000..8e5c3cb --- /dev/null +++ b/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/README.md @@ -0,0 +1,52 @@ +

1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree

Medium


Given two binary trees original and cloned and given a reference to a node target in the original tree.

+ +

The cloned tree is a copy of the original tree.

+ +

Return a reference to the same node in the cloned tree.

+ +

Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.

+ +

 

+

Example 1:

+ +
Input: tree = [7,4,3,null,null,6,19], target = 3
+Output: 3
+Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.
+
+ +

Example 2:

+ +
Input: tree = [7], target =  7
+Output: 7
+
+ +

Example 3:

+ +
Input: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4
+Output: 4
+
+ +

Example 4:

+ +
Input: tree = [1,2,3,4,5,6,7,8,9,10], target = 5
+Output: 5
+
+ +

Example 5:

+ +
Input: tree = [1,2,null,3], target = 2
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • The values of the nodes of the tree are unique.
  • +
  • target node is a node from the original tree and is not null.
  • +
+ +

 

+

Follow up: Could you solve the problem if repeated values on the tree are allowed?

+
\ No newline at end of file diff --git a/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.cpp b/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.cpp new file mode 100644 index 0000000..5c34ded --- /dev/null +++ b/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.cpp @@ -0,0 +1,18 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + +class Solution { +public: + TreeNode* getTargetCopy(TreeNode* original, TreeNode* clone, TreeNode* targ) { + return original == nullptr ? nullptr : + original == targ ? clone : + getTargetCopy(original->left, clone->left, targ) ?: getTargetCopy(original->right, clone->right, targ); + } +}; \ No newline at end of file diff --git a/find-all-numbers-disappeared-in-an-array/README.md b/find-all-numbers-disappeared-in-an-array/README.md new file mode 100644 index 0000000..66b6fce --- /dev/null +++ b/find-all-numbers-disappeared-in-an-array/README.md @@ -0,0 +1,22 @@ +

448. Find All Numbers Disappeared in an Array

Easy


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

+ +

 

+

Example 1:

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

Example 2:

+
Input: nums = [1,1]
+Output: [2]
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 105
  • +
  • 1 <= nums[i] <= n
  • +
+ +

 

+

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

+
\ No newline at end of file diff --git a/find-all-numbers-disappeared-in-an-array/find-all-numbers-disappeared-in-an-array.cpp b/find-all-numbers-disappeared-in-an-array/find-all-numbers-disappeared-in-an-array.cpp new file mode 100644 index 0000000..fcff191 --- /dev/null +++ b/find-all-numbers-disappeared-in-an-array/find-all-numbers-disappeared-in-an-array.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector findDisappearedNumbers(vector& nums) { + vector freq(nums.size()+1,0); + vector ans; + for(int i=0;i1791. Find Center of Star Graph

Easy


There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node.

+ +

You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.

+ +

 

+

Example 1:

+ +
Input: edges = [[1,2],[2,3],[4,2]]
+Output: 2
+Explanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
+
+ +

Example 2:

+ +
Input: edges = [[1,2],[5,1],[1,3],[1,4]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= n <= 105
  • +
  • edges.length == n - 1
  • +
  • edges[i].length == 2
  • +
  • 1 <= ui, vi <= n
  • +
  • ui != vi
  • +
  • The given edges represent a valid star graph.
  • +
+
\ No newline at end of file diff --git a/find-center-of-star-graph/find-center-of-star-graph.cpp b/find-center-of-star-graph/find-center-of-star-graph.cpp new file mode 100644 index 0000000..003f890 --- /dev/null +++ b/find-center-of-star-graph/find-center-of-star-graph.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int findCenter(vector>& edges) { + + int n = edges.size()+1; + + vector v(n+1,0); + + for(int i=0;i1) + return i; + + return -1; + } + +}; \ No newline at end of file diff --git a/find-first-and-last-position-of-element-in-sorted-array/README.md b/find-first-and-last-position-of-element-in-sorted-array/README.md new file mode 100644 index 0000000..5d30040 --- /dev/null +++ b/find-first-and-last-position-of-element-in-sorted-array/README.md @@ -0,0 +1,27 @@ +

34. Find First and Last Position of Element in Sorted Array

Medium


Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

+ +

If target is not found in the array, return [-1, -1].

+ +

You must write an algorithm with O(log n) runtime complexity.

+ +

 

+

Example 1:

+
Input: nums = [5,7,7,8,8,10], target = 8
+Output: [3,4]
+

Example 2:

+
Input: nums = [5,7,7,8,8,10], target = 6
+Output: [-1,-1]
+

Example 3:

+
Input: nums = [], target = 0
+Output: [-1,-1]
+
+

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
  • nums is a non-decreasing array.
  • +
  • -109 <= target <= 109
  • +
+
\ No newline at end of file diff --git a/find-first-and-last-position-of-element-in-sorted-array/find-first-and-last-position-of-element-in-sorted-array.cpp b/find-first-and-last-position-of-element-in-sorted-array/find-first-and-last-position-of-element-in-sorted-array.cpp new file mode 100644 index 0000000..850c4f4 --- /dev/null +++ b/find-first-and-last-position-of-element-in-sorted-array/find-first-and-last-position-of-element-in-sorted-array.cpp @@ -0,0 +1,23 @@ +class Solution { +public: +vector searchRange(vector& nums, int target) { + int idx1 = lower_bound(nums, target); + int idx2 = lower_bound(nums, target+1)-1; + if (idx1 < nums.size() && nums[idx1] == target) + return {idx1, idx2}; + else + return {-1, -1}; +} + +int lower_bound(vector& nums, int target) { + int l = 0, r = nums.size()-1; + while (l <= r) { + int mid = (r-l)/2+l; + if (nums[mid] < target) + l = mid+1; + else + r = mid-1; + } + return l; +} +}; \ No newline at end of file diff --git a/find-median-from-data-stream/README.md b/find-median-from-data-stream/README.md new file mode 100644 index 0000000..0c4c67c --- /dev/null +++ b/find-median-from-data-stream/README.md @@ -0,0 +1,50 @@ +

295. Find Median from Data Stream

Hard


The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.

+ +
    +
  • For example, for arr = [2,3,4], the median is 3.
  • +
  • For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.
  • +
+ +

Implement the MedianFinder class:

+ +
    +
  • MedianFinder() initializes the MedianFinder object.
  • +
  • void addNum(int num) adds the integer num from the data stream to the data structure.
  • +
  • double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.
  • +
+ +

 

+

Example 1:

+ +
Input
+["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
+[[], [1], [2], [], [3], []]
+Output
+[null, null, null, 1.5, null, 2.0]
+
+Explanation
+MedianFinder medianFinder = new MedianFinder();
+medianFinder.addNum(1);    // arr = [1]
+medianFinder.addNum(2);    // arr = [1, 2]
+medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
+medianFinder.addNum(3);    // arr[1, 2, 3]
+medianFinder.findMedian(); // return 2.0
+
+ +

 

+

Constraints:

+ +
    +
  • -105 <= num <= 105
  • +
  • There will be at least one element in the data structure before calling findMedian.
  • +
  • At most 5 * 104 calls will be made to addNum and findMedian.
  • +
+ +

 

+

Follow up:

+ +
    +
  • If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
  • +
  • If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
  • +
+
\ No newline at end of file diff --git a/find-median-from-data-stream/find-median-from-data-stream.cpp b/find-median-from-data-stream/find-median-from-data-stream.cpp new file mode 100644 index 0000000..61d25b4 --- /dev/null +++ b/find-median-from-data-stream/find-median-from-data-stream.cpp @@ -0,0 +1,26 @@ +class MedianFinder { + priority_queue small, large; +public: + + void addNum(int num) { + small.push(num); + large.push(-small.top()); + small.pop(); + if (small.size() < large.size()) { + small.push(-large.top()); + large.pop(); + } + } + + double findMedian() { + return small.size() > large.size() + ? small.top() + : (small.top() - large.top()) / 2.0; + } +}; +/** + * Your MedianFinder object will be instantiated and called as such: + * MedianFinder* obj = new MedianFinder(); + * obj->addNum(num); + * double param_2 = obj->findMedian(); + */ \ No newline at end of file diff --git a/find-minimum-in-rotated-sorted-array-ii/README.md b/find-minimum-in-rotated-sorted-array-ii/README.md new file mode 100644 index 0000000..f8a17ad --- /dev/null +++ b/find-minimum-in-rotated-sorted-array-ii/README.md @@ -0,0 +1,36 @@ +

154. Find Minimum in Rotated Sorted Array II

Hard


Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:

+ +
    +
  • [4,5,6,7,0,1,4] if it was rotated 4 times.
  • +
  • [0,1,4,4,5,6,7] if it was rotated 7 times.
  • +
+ +

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

+ +

Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array.

+ +

You must decrease the overall operation steps as much as possible.

+ +

 

+

Example 1:

+
Input: nums = [1,3,5]
+Output: 1
+

Example 2:

+
Input: nums = [2,2,2,0,1]
+Output: 0
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 5000
  • +
  • -5000 <= nums[i] <= 5000
  • +
  • nums is sorted and rotated between 1 and n times.
  • +
+ +

 

+

Follow up: This problem is similar to Find Minimum in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why?

+ +

 

+
\ No newline at end of file diff --git a/find-minimum-in-rotated-sorted-array-ii/find-minimum-in-rotated-sorted-array-ii.cpp b/find-minimum-in-rotated-sorted-array-ii/find-minimum-in-rotated-sorted-array-ii.cpp new file mode 100644 index 0000000..9a6562d --- /dev/null +++ b/find-minimum-in-rotated-sorted-array-ii/find-minimum-in-rotated-sorted-array-ii.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int findMin(vector& nums) { + + int low = 0; + int high = nums.size()-1; + + while(low < high) + { + int mid = low + (high-low)/2; + + if(nums[mid] > nums[high]) + { + low = mid+1; + } + else if(nums[mid] < nums[high]) + { + high = mid; + } + else + { + high--; + } + + } + return nums[high]; + + } +}; \ No newline at end of file diff --git a/find-minimum-in-rotated-sorted-array/README.md b/find-minimum-in-rotated-sorted-array/README.md new file mode 100644 index 0000000..54c6b9f --- /dev/null +++ b/find-minimum-in-rotated-sorted-array/README.md @@ -0,0 +1,46 @@ +

153. Find Minimum in Rotated Sorted Array

Medium


Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:

+ +
    +
  • [4,5,6,7,0,1,2] if it was rotated 4 times.
  • +
  • [0,1,2,4,5,6,7] if it was rotated 7 times.
  • +
+ +

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

+ +

Given the sorted rotated array nums of unique elements, return the minimum element of this array.

+ +

You must write an algorithm that runs in O(log n) time.

+ +

 

+

Example 1:

+ +
Input: nums = [3,4,5,1,2]
+Output: 1
+Explanation: The original array was [1,2,3,4,5] rotated 3 times.
+
+ +

Example 2:

+ +
Input: nums = [4,5,6,7,0,1,2]
+Output: 0
+Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.
+
+ +

Example 3:

+ +
Input: nums = [11,13,15,17]
+Output: 11
+Explanation: The original array was [11,13,15,17] and it was rotated 4 times. 
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 5000
  • +
  • -5000 <= nums[i] <= 5000
  • +
  • All the integers of nums are unique.
  • +
  • nums is sorted and rotated between 1 and n times.
  • +
+
\ No newline at end of file diff --git a/find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.cpp b/find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.cpp new file mode 100644 index 0000000..d0d1222 --- /dev/null +++ b/find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int findMin(vector &num) { + int start=0,end=num.size()-1; + + while (start=num[start]) { + start = mid+1; + } else { + end = mid; + } + } + + return num[start]; + } +}; \ No newline at end of file diff --git a/find-peak-element/README.md b/find-peak-element/README.md new file mode 100644 index 0000000..6be57e0 --- /dev/null +++ b/find-peak-element/README.md @@ -0,0 +1,30 @@ +

162. Find Peak Element

Medium


A peak element is an element that is strictly greater than its neighbors.

+ +

Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

+ +

You may imagine that nums[-1] = nums[n] = -∞.

+ +

You must write an algorithm that runs in O(log n) time.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,1]
+Output: 2
+Explanation: 3 is a peak element and your function should return the index number 2.
+ +

Example 2:

+ +
Input: nums = [1,2,1,3,5,6,4]
+Output: 5
+Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • nums[i] != nums[i + 1] for all valid i.
  • +
+
\ No newline at end of file diff --git a/find-peak-element/find-peak-element.cpp b/find-peak-element/find-peak-element.cpp new file mode 100644 index 0000000..c88604d --- /dev/null +++ b/find-peak-element/find-peak-element.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int findPeakElement(vector& nums) { + // edge case - only one item + if (nums.size() == 1) return 0; + // peak is first item + if (nums[0] > nums[1]) return 0; + // peak is last item + if (nums.back() > nums[nums.size()-2]) return nums.size()-1; + // iterate to find peak + for (int i=0; i nums[max(0,i-1)]) && (nums[i] > nums[i+1])) return i; + return -1; + } +}; \ No newline at end of file diff --git a/find-positive-integer-solution-for-a-given-equation/README.md b/find-positive-integer-solution-for-a-given-equation/README.md new file mode 100644 index 0000000..e5f901d --- /dev/null +++ b/find-positive-integer-solution-for-a-given-equation/README.md @@ -0,0 +1,60 @@ +

1237. Find Positive Integer Solution for a Given Equation

Medium


Given a callable function f(x, y) with a hidden formula and a value z, reverse engineer the formula and return all positive integer pairs x and y where f(x,y) == z. You may return the pairs in any order.

+ +

While the exact formula is hidden, the function is monotonically increasing, i.e.:

+ +
    +
  • f(x, y) < f(x + 1, y)
  • +
  • f(x, y) < f(x, y + 1)
  • +
+ +

The function interface is defined like this:

+ +
interface CustomFunction {
+public:
+  // Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
+  int f(int x, int y);
+};
+
+ +

We will judge your solution as follows:

+ +
    +
  • The judge has a list of 9 hidden implementations of CustomFunction, along with a way to generate an answer key of all valid pairs for a specific z.
  • +
  • The judge will receive two inputs: a function_id (to determine which implementation to test your code with), and the target z.
  • +
  • The judge will call your findSolution and compare your results with the answer key.
  • +
  • If your results match the answer key, your solution will be Accepted.
  • +
+ +

 

+

Example 1:

+ +
Input: function_id = 1, z = 5
+Output: [[1,4],[2,3],[3,2],[4,1]]
+Explanation: The hidden formula for function_id = 1 is f(x, y) = x + y.
+The following positive integer values of x and y make f(x, y) equal to 5:
+x=1, y=4 -> f(1, 4) = 1 + 4 = 5.
+x=2, y=3 -> f(2, 3) = 2 + 3 = 5.
+x=3, y=2 -> f(3, 2) = 3 + 2 = 5.
+x=4, y=1 -> f(4, 1) = 4 + 1 = 5.
+
+ +

Example 2:

+ +
Input: function_id = 2, z = 5
+Output: [[1,5],[5,1]]
+Explanation: The hidden formula for function_id = 2 is f(x, y) = x * y.
+The following positive integer values of x and y make f(x, y) equal to 5:
+x=1, y=5 -> f(1, 5) = 1 * 5 = 5.
+x=5, y=1 -> f(5, 1) = 5 * 1 = 5.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= function_id <= 9
  • +
  • 1 <= z <= 100
  • +
  • It is guaranteed that the solutions of f(x, y) == z will be in the range 1 <= x, y <= 1000.
  • +
  • It is also guaranteed that f(x, y) will fit in 32 bit signed integer if 1 <= x, y <= 1000.
  • +
+
\ No newline at end of file diff --git a/find-the-duplicate-number/README.md b/find-the-duplicate-number/README.md new file mode 100644 index 0000000..4b0c25c --- /dev/null +++ b/find-the-duplicate-number/README.md @@ -0,0 +1,38 @@ +

287. Find the Duplicate Number

Medium


Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

+ +

There is only one repeated number in nums, return this repeated number.

+ +

You must solve the problem without modifying the array nums and uses only constant extra space.

+ +

 

+

Example 1:

+
Input: nums = [1,3,4,2,2]
+Output: 2
+

Example 2:

+
Input: nums = [3,1,3,4,2]
+Output: 3
+

Example 3:

+
Input: nums = [1,1]
+Output: 1
+

Example 4:

+
Input: nums = [1,1,2]
+Output: 1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • nums.length == n + 1
  • +
  • 1 <= nums[i] <= n
  • +
  • All the integers in nums appear only once except for precisely one integer which appears two or more times.
  • +
+ +

 

+

Follow up:

+ +
    +
  • How can we prove that at least one duplicate number must exist in nums?
  • +
  • Can you solve the problem in linear runtime complexity?
  • +
+
\ No newline at end of file diff --git a/find-the-duplicate-number/find-the-duplicate-number.cpp b/find-the-duplicate-number/find-the-duplicate-number.cpp new file mode 100644 index 0000000..af87c52 --- /dev/null +++ b/find-the-duplicate-number/find-the-duplicate-number.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int findDuplicate(vector& nums) { + int slow = nums[0]; + int fast = nums[0]; + + do{ + slow = nums[slow]; + fast = nums[nums[fast]]; + }while(slow != fast); + + fast = nums[0]; + while(slow != fast) + { + slow = nums[slow]; + fast = nums[fast]; + } + + return fast; + } +}; \ No newline at end of file diff --git a/find-the-town-judge/README.md b/find-the-town-judge/README.md new file mode 100644 index 0000000..80b2545 --- /dev/null +++ b/find-the-town-judge/README.md @@ -0,0 +1,57 @@ +

997. Find the Town Judge

Easy


In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.

+ +

If the town judge exists, then:

+ +
    +
  1. The town judge trusts nobody.
  2. +
  3. Everybody (except for the town judge) trusts the town judge.
  4. +
  5. There is exactly one person that satisfies properties 1 and 2.
  6. +
+ +

You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi.

+ +

Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.

+ +

 

+

Example 1:

+ +
Input: n = 2, trust = [[1,2]]
+Output: 2
+
+ +

Example 2:

+ +
Input: n = 3, trust = [[1,3],[2,3]]
+Output: 3
+
+ +

Example 3:

+ +
Input: n = 3, trust = [[1,3],[2,3],[3,1]]
+Output: -1
+
+ +

Example 4:

+ +
Input: n = 3, trust = [[1,2],[2,3]]
+Output: -1
+
+ +

Example 5:

+ +
Input: n = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 1000
  • +
  • 0 <= trust.length <= 104
  • +
  • trust[i].length == 2
  • +
  • All the pairs of trust are unique.
  • +
  • ai != bi
  • +
  • 1 <= ai, bi <= n
  • +
+
\ No newline at end of file diff --git a/find-the-town-judge/find-the-town-judge.cpp b/find-the-town-judge/find-the-town-judge.cpp new file mode 100644 index 0000000..8645d1b --- /dev/null +++ b/find-the-town-judge/find-the-town-judge.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int findJudge(int n, vector>& trust) { + //this condition is to check if given input is empty but n==1 + + if(trust.empty() && n==1) + return 1; + + //counts outdegree of a person or node + //outdegree means number of nodes that are trusted by given specific node + + vector out(n+1,0); + + //counts indegree of a person or node + //indegree means number of nodes that trusts a given specific node + + vector in(n+1,0); + + //loop counts indegree and outdegree + + for(auto edge : trust){ + out[edge[0]]++; + in[edge[1]]++; + } + + //if a node has outdegree==0 that means that node doesnot trust anyone and + //indegree ==n-1 that means all other nodes trusts this node except himself + + for(int i=0;i<=n;i++){ + if(out[i]==0 && in[i]==n-1) + return i; + } + //if there is no such node return -1 + return -1; + } + +}; \ No newline at end of file diff --git a/find-the-winner-of-the-circular-game/README.md b/find-the-winner-of-the-circular-game/README.md new file mode 100644 index 0000000..ab584f1 --- /dev/null +++ b/find-the-winner-of-the-circular-game/README.md @@ -0,0 +1,43 @@ +

1823. Find the Winner of the Circular Game

Medium


There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.

+ +

The rules of the game are as follows:

+ +
    +
  1. Start at the 1st friend.
  2. +
  3. Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once.
  4. +
  5. The last friend you counted leaves the circle and loses the game.
  6. +
  7. If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat.
  8. +
  9. Else, the last friend in the circle wins the game.
  10. +
+ +

Given the number of friends, n, and an integer k, return the winner of the game.

+ +

 

+

Example 1:

+ +
Input: n = 5, k = 2
+Output: 3
+Explanation: Here are the steps of the game:
+1) Start at friend 1.
+2) Count 2 friends clockwise, which are friends 1 and 2.
+3) Friend 2 leaves the circle. Next start is friend 3.
+4) Count 2 friends clockwise, which are friends 3 and 4.
+5) Friend 4 leaves the circle. Next start is friend 5.
+6) Count 2 friends clockwise, which are friends 5 and 1.
+7) Friend 1 leaves the circle. Next start is friend 3.
+8) Count 2 friends clockwise, which are friends 3 and 5.
+9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.
+ +

Example 2:

+ +
Input: n = 6, k = 5
+Output: 1
+Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= n <= 500
  • +
\ No newline at end of file diff --git a/finding-the-users-active-minutes/README.md b/finding-the-users-active-minutes/README.md new file mode 100644 index 0000000..17872f6 --- /dev/null +++ b/finding-the-users-active-minutes/README.md @@ -0,0 +1,42 @@ +

1817. Finding the Users Active Minutes

Medium


You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei.

+ +

Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute.

+ +

The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it.

+ +

You are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] is the number of users whose UAM equals j.

+ +

Return the array answer as described above.

+ +

 

+

Example 1:

+ +
Input: logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5
+Output: [0,2,0,0,0]
+Explanation:
+The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).
+The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.
+Since both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.
+
+ +

Example 2:

+ +
Input: logs = [[1,1],[2,2],[2,3]], k = 4
+Output: [1,1,0,0]
+Explanation:
+The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.
+The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.
+There is one user with a UAM of 1 and one with a UAM of 2.
+Hence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= logs.length <= 104
  • +
  • 0 <= IDi <= 109
  • +
  • 1 <= timei <= 105
  • +
  • k is in the range [The maximum UAM for a user, 105].
  • +
+
\ No newline at end of file diff --git a/first-bad-version/README.md b/first-bad-version/README.md new file mode 100644 index 0000000..d0bd6b1 --- /dev/null +++ b/first-bad-version/README.md @@ -0,0 +1,31 @@ +

278. First Bad Version

Easy


You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

+ +

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

+ +

You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

+ +

 

+

Example 1:

+ +
Input: n = 5, bad = 4
+Output: 4
+Explanation:
+call isBadVersion(3) -> false
+call isBadVersion(5) -> true
+call isBadVersion(4) -> true
+Then 4 is the first bad version.
+
+ +

Example 2:

+ +
Input: n = 1, bad = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= bad <= n <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/first-bad-version/first-bad-version.cpp b/first-bad-version/first-bad-version.cpp new file mode 100644 index 0000000..66c86fe --- /dev/null +++ b/first-bad-version/first-bad-version.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int firstBadVersion(int n) { + int lower = 1, upper = n, mid; + while(lower < upper) { + mid = lower + (upper - lower) / 2; + if(!isBadVersion(mid)) lower = mid + 1; /* Only one call to API */ + else upper = mid; + } + return lower; /* Because there will alway be a bad version, return lower here */ + } +}; \ No newline at end of file diff --git a/flatten-a-multilevel-doubly-linked-list/README.md b/flatten-a-multilevel-doubly-linked-list/README.md new file mode 100644 index 0000000..a887c42 --- /dev/null +++ b/flatten-a-multilevel-doubly-linked-list/README.md @@ -0,0 +1,77 @@ +

430. Flatten a Multilevel Doubly Linked List

Medium


You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.

+ +

Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
+Output: [1,2,3,7,8,11,12,9,10,4,5,6]
+Explanation:
+
+The multilevel linked list in the input is as follows:
+
+
+
+After flattening the multilevel linked list it becomes:
+
+
+
+ +

Example 2:

+ +
Input: head = [1,2,null,3]
+Output: [1,3,2]
+Explanation:
+
+The input multilevel linked list is as follows:
+
+  1---2---NULL
+  |
+  3---NULL
+
+ +

Example 3:

+ +
Input: head = []
+Output: []
+
+ +

 

+ +

How multilevel linked list is represented in test case:

+ +

We use the multilevel linked list from Example 1 above:

+ +
 1---2---3---4---5---6--NULL
+         |
+         7---8---9---10--NULL
+             |
+             11--12--NULL
+ +

The serialization of each level is as follows:

+ +
[1,2,3,4,5,6,null]
+[7,8,9,10,null]
+[11,12,null]
+
+ +

To serialize all levels together we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:

+ +
[1,2,3,4,5,6,null]
+[null,null,7,8,9,10,null]
+[null,11,12,null]
+
+ +

Merging the serialization of each level and removing trailing nulls we obtain:

+ +
[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
+ +

 

+

Constraints:

+ +
    +
  • The number of Nodes will not exceed 1000.
  • +
  • 1 <= Node.val <= 105
  • +
+
\ No newline at end of file diff --git a/flatten-a-multilevel-doubly-linked-list/flatten-a-multilevel-doubly-linked-list.cpp b/flatten-a-multilevel-doubly-linked-list/flatten-a-multilevel-doubly-linked-list.cpp new file mode 100644 index 0000000..7949a69 --- /dev/null +++ b/flatten-a-multilevel-doubly-linked-list/flatten-a-multilevel-doubly-linked-list.cpp @@ -0,0 +1,25 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + Node* prev; + Node* next; + Node* child; +}; +*/ + +class Solution { +public: + +Node* ff(Node* head, Node* rest = nullptr) { + if (!head) return rest; + head->next = ff(head->child, ff(head->next, rest)); + if (head->next) head->next->prev = head; + head->child = nullptr; + return head; +} + Node* flatten(Node* head) { + return ff(head); + } +}; diff --git a/flatten-binary-tree-to-linked-list/README.md b/flatten-binary-tree-to-linked-list/README.md new file mode 100644 index 0000000..299afc3 --- /dev/null +++ b/flatten-binary-tree-to-linked-list/README.md @@ -0,0 +1,36 @@ +

114. Flatten Binary Tree to Linked List

Medium


Given the root of a binary tree, flatten the tree into a "linked list":

+ +
    +
  • The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
  • +
  • The "linked list" should be in the same order as a pre-order traversal of the binary tree.
  • +
+ +

 

+

Example 1:

+ +
Input: root = [1,2,5,3,4,null,6]
+Output: [1,null,2,null,3,null,4,null,5,null,6]
+
+ +

Example 2:

+ +
Input: root = []
+Output: []
+
+ +

Example 3:

+ +
Input: root = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 2000].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+Follow up: Can you flatten the tree in-place (with O(1) extra space)?
\ No newline at end of file diff --git a/flatten-binary-tree-to-linked-list/flatten-binary-tree-to-linked-list.cpp b/flatten-binary-tree-to-linked-list/flatten-binary-tree-to-linked-list.cpp new file mode 100644 index 0000000..4784c06 --- /dev/null +++ b/flatten-binary-tree-to-linked-list/flatten-binary-tree-to-linked-list.cpp @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + void flatten(TreeNode* root) { + + TreeNode * curr = root; + while(curr != NULL) + { + if(curr->left) + { + TreeNode * prev = curr->left; + while(prev->right) + { + prev = prev->right; + } + prev->right = curr->right; + curr->right = curr->left; + curr->left = NULL; + + } + curr = curr->right; + + } + + return ; + } +}; \ No newline at end of file diff --git a/flip-columns-for-maximum-number-of-equal-rows/README.md b/flip-columns-for-maximum-number-of-equal-rows/README.md new file mode 100644 index 0000000..248f4de --- /dev/null +++ b/flip-columns-for-maximum-number-of-equal-rows/README.md @@ -0,0 +1,38 @@ +

1072. Flip Columns For Maximum Number of Equal Rows

Medium


You are given an m x n binary matrix matrix.

+ +

You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa).

+ +

Return the maximum number of rows that have all values equal after some number of flips.

+ +

 

+

Example 1:

+ +
Input: matrix = [[0,1],[1,1]]
+Output: 1
+Explanation: After flipping no values, 1 row has all values equal.
+
+ +

Example 2:

+ +
Input: matrix = [[0,1],[1,0]]
+Output: 2
+Explanation: After flipping values in the first column, both rows have equal values.
+
+ +

Example 3:

+ +
Input: matrix = [[0,0,0],[0,0,1],[1,1,0]]
+Output: 2
+Explanation: After flipping values in the first two columns, the last two rows have equal values.
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 300
  • +
  • matrix[i][j] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/flip-string-to-monotone-increasing/README.md b/flip-string-to-monotone-increasing/README.md new file mode 100644 index 0000000..d7a95fb --- /dev/null +++ b/flip-string-to-monotone-increasing/README.md @@ -0,0 +1,36 @@ +

926. Flip String to Monotone Increasing

Medium


A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none).

+ +

You are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0.

+ +

Return the minimum number of flips to make s monotone increasing.

+ +

 

+

Example 1:

+ +
Input: s = "00110"
+Output: 1
+Explanation: We flip the last digit to get 00111.
+
+ +

Example 2:

+ +
Input: s = "010110"
+Output: 2
+Explanation: We flip to get 011111, or alternatively 000111.
+
+ +

Example 3:

+ +
Input: s = "00011000"
+Output: 2
+Explanation: We flip to get 00000000.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s[i] is either '0' or '1'.
  • +
+
\ No newline at end of file diff --git a/flip-string-to-monotone-increasing/flip-string-to-monotone-increasing.cpp b/flip-string-to-monotone-increasing/flip-string-to-monotone-increasing.cpp new file mode 100644 index 0000000..2b2d54f --- /dev/null +++ b/flip-string-to-monotone-increasing/flip-string-to-monotone-increasing.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int minFlipsMonoIncr(const std::string& S, int counter_one = 0, int counter_flip = 0) { + for (auto ch : S) { + if (ch == '1') { + ++counter_one; + } else { + ++counter_flip; + } + counter_flip = std::min(counter_one, counter_flip); + } + return counter_flip; + } +}; \ No newline at end of file diff --git a/flood-fill/README.md b/flood-fill/README.md new file mode 100644 index 0000000..f5d9633 --- /dev/null +++ b/flood-fill/README.md @@ -0,0 +1,35 @@ +

733. Flood Fill

Easy


An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.

+ +

You are also given three integers sr, sc, and newColor. You should perform a flood fill on the image starting from the pixel image[sr][sc].

+ +

To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with newColor.

+ +

Return the modified image after performing the flood fill.

+ +

 

+

Example 1:

+ +
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2
+Output: [[2,2,2],[2,2,0],[2,0,1]]
+Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
+Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
+
+ +

Example 2:

+ +
Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2
+Output: [[2,2,2],[2,2,2]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == image.length
  • +
  • n == image[i].length
  • +
  • 1 <= m, n <= 50
  • +
  • 0 <= image[i][j], newColor < 216
  • +
  • 0 <= sr < m
  • +
  • 0 <= sc < n
  • +
+
\ No newline at end of file diff --git a/flood-fill/flood-fill.cpp b/flood-fill/flood-fill.cpp new file mode 100644 index 0000000..72d71d1 --- /dev/null +++ b/flood-fill/flood-fill.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + + void floodFill(vector>& image, int sr, int sc, int newColor,int color) + { + if(image[sr][sc] == color) + { + image[sr][sc] = newColor; + if(sr >= 1 ) + { + floodFill(image,sr-1,sc,newColor,color); + } + if(sc >= 1) + { + floodFill(image,sr,sc-1,newColor,color); + } + if(sr < image.size() - 1) + { + floodFill(image,sr+1,sc,newColor,color); + } + if(sc < image[0].size() - 1) + { + floodFill(image,sr,sc+1,newColor,color); + } + + } + } + + vector> floodFill(vector>& image, int sr, int sc, int newColor) { + if(image[sr][sc] == newColor) + return image; + int color = image[sr][sc]; + floodFill(image,sr,sc,newColor,color); + return image; + } +}; \ No newline at end of file diff --git a/fruit-into-baskets/README.md b/fruit-into-baskets/README.md new file mode 100644 index 0000000..50af033 --- /dev/null +++ b/fruit-into-baskets/README.md @@ -0,0 +1,51 @@ +

904. Fruit Into Baskets

Medium


You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.

+ +

You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:

+ +
    +
  • You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.
  • +
  • Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
  • +
  • Once you reach a tree with fruit that cannot fit in your baskets, you must stop.
  • +
+ +

Given the integer array fruits, return the maximum number of fruits you can pick.

+ +

 

+

Example 1:

+ +
Input: fruits = [1,2,1]
+Output: 3
+Explanation: We can pick from all 3 trees.
+
+ +

Example 2:

+ +
Input: fruits = [0,1,2,2]
+Output: 3
+Explanation: We can pick from trees [1,2,2].
+If we had started at the first tree, we would only pick from trees [0,1].
+
+ +

Example 3:

+ +
Input: fruits = [1,2,3,2,2]
+Output: 4
+Explanation: We can pick from trees [2,3,2,2].
+If we had started at the first tree, we would only pick from trees [1,2].
+
+ +

Example 4:

+ +
Input: fruits = [3,3,3,1,2,1,1,2,3,3,4]
+Output: 5
+Explanation: We can pick from trees [1,2,1,1,2].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= fruits.length <= 105
  • +
  • 0 <= fruits[i] < fruits.length
  • +
+
\ No newline at end of file diff --git a/generate-parentheses/README.md b/generate-parentheses/README.md new file mode 100644 index 0000000..2053704 --- /dev/null +++ b/generate-parentheses/README.md @@ -0,0 +1,17 @@ +

22. Generate Parentheses

Medium


Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

+ +

 

+

Example 1:

+
Input: n = 3
+Output: ["((()))","(()())","(())()","()(())","()()()"]
+

Example 2:

+
Input: n = 1
+Output: ["()"]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 8
  • +
+
\ No newline at end of file diff --git a/generate-parentheses/generate-parentheses.cpp b/generate-parentheses/generate-parentheses.cpp new file mode 100644 index 0000000..4a49c74 --- /dev/null +++ b/generate-parentheses/generate-parentheses.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vectorresult; + + void helper(int open,int close,int n,string current) + { + if(current.length()==n*2) + { + result.push_back(current); + return; + } + if(open generateParenthesis(int n) { + helper(0,0,n,""); + return result; + } +}; \ No newline at end of file diff --git a/group-anagrams/README.md b/group-anagrams/README.md new file mode 100644 index 0000000..e97202a --- /dev/null +++ b/group-anagrams/README.md @@ -0,0 +1,24 @@ +

49. Group Anagrams

Medium


Given an array of strings strs, group the anagrams together. You can return the answer in any order.

+ +

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

+ +

 

+

Example 1:

+
Input: strs = ["eat","tea","tan","ate","nat","bat"]
+Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
+

Example 2:

+
Input: strs = [""]
+Output: [[""]]
+

Example 3:

+
Input: strs = ["a"]
+Output: [["a"]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= strs.length <= 104
  • +
  • 0 <= strs[i].length <= 100
  • +
  • strs[i] consists of lower-case English letters.
  • +
+
\ No newline at end of file diff --git a/group-anagrams/group-anagrams.cpp b/group-anagrams/group-anagrams.cpp new file mode 100644 index 0000000..c1eb42d --- /dev/null +++ b/group-anagrams/group-anagrams.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> mp; + for (string s : strs) { + mp[strSort(s)].push_back(s); + } + vector> anagrams; + for (auto p : mp) { + anagrams.push_back(p.second); + } + return anagrams; + } +private: + string strSort(string s) { + int counter[26] = {0}; + for (char c : s) { + counter[c - 'a']++; + } + string t; + for (int c = 0; c < 26; c++) { + t += string(counter[c], c + 'a'); + } + return t; + } +}; \ No newline at end of file diff --git a/group-the-people-given-the-group-size-they-belong-to/README.md b/group-the-people-given-the-group-size-they-belong-to/README.md new file mode 100644 index 0000000..3db9e5a --- /dev/null +++ b/group-the-people-given-the-group-size-they-belong-to/README.md @@ -0,0 +1,35 @@ +

1282. Group the People Given the Group Size They Belong To

Medium


There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.

+ +

You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.

+ +

Return a list of groups such that each person i is in a group of size groupSizes[i].

+ +

Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.

+ +

 

+

Example 1:

+ +
Input: groupSizes = [3,3,3,3,3,1,3]
+Output: [[5],[0,1,2],[3,4,6]]
+Explanation: 
+The first group is [5]. The size is 1, and groupSizes[5] = 1.
+The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.
+The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.
+Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].
+
+ +

Example 2:

+ +
Input: groupSizes = [2,1,3,3,3,2]
+Output: [[1],[0,5],[2,3,4]]
+
+ +

 

+

Constraints:

+ +
    +
  • groupSizes.length == n
  • +
  • 1 <= n <= 500
  • +
  • 1 <= groupSizes[i] <= n
  • +
+
\ No newline at end of file diff --git a/group-the-people-given-the-group-size-they-belong-to/group-the-people-given-the-group-size-they-belong-to.cpp b/group-the-people-given-the-group-size-they-belong-to/group-the-people-given-the-group-size-they-belong-to.cpp new file mode 100644 index 0000000..b3c7464 --- /dev/null +++ b/group-the-people-given-the-group-size-they-belong-to/group-the-people-given-the-group-size-they-belong-to.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + vector> groupThePeople(vector& gz) { + vector> res, groups(gz.size() + 3); + for (auto i = 0; i < gz.size(); ++i) { + groups[gz[i]].push_back(i); + if (groups[gz[i]].size() == gz[i]) { + res.push_back({}); + swap(res.back(), groups[gz[i]]); + } + } + return res; +} +}; \ No newline at end of file diff --git a/hamming-distance/README.md b/hamming-distance/README.md new file mode 100644 index 0000000..3f86179 --- /dev/null +++ b/hamming-distance/README.md @@ -0,0 +1,29 @@ +

461. Hamming Distance

Easy


The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

+ +

Given two integers x and y, return the Hamming distance between them.

+ +

 

+

Example 1:

+ +
Input: x = 1, y = 4
+Output: 2
+Explanation:
+1   (0 0 0 1)
+4   (0 1 0 0)
+       ↑   ↑
+The above arrows point to positions where the corresponding bits are different.
+
+ +

Example 2:

+ +
Input: x = 3, y = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= x, y <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/hamming-distance/hamming-distance.cpp b/hamming-distance/hamming-distance.cpp new file mode 100644 index 0000000..0989ce1 --- /dev/null +++ b/hamming-distance/hamming-distance.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int hammingDistance(int x, int y) { + + int sum = 0; + + while(x != 0 || y != 0) + { + if(x % 2 == 0) + { + if(y % 2 != 0) + { + sum++; + } + } + else + { + if(y % 2 == 0) + { + sum++; + } + } + x = x/2; + y = y/2; + } + + return sum; + } +}; \ No newline at end of file diff --git a/house-robber-ii/README.md b/house-robber-ii/README.md new file mode 100644 index 0000000..07c2349 --- /dev/null +++ b/house-robber-ii/README.md @@ -0,0 +1,34 @@ +

213. House Robber II

Medium


You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.

+ +

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

+ +

 

+

Example 1:

+ +
Input: nums = [2,3,2]
+Output: 3
+Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,1]
+Output: 4
+Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
+Total amount you can rob = 1 + 3 = 4.
+
+ +

Example 3:

+ +
Input: nums = [1,2,3]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 0 <= nums[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/house-robber-iii/README.md b/house-robber-iii/README.md new file mode 100644 index 0000000..b192749 --- /dev/null +++ b/house-robber-iii/README.md @@ -0,0 +1,29 @@ +

337. House Robber III

Medium


The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.

+ +

Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.

+ +

Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.

+ +

 

+

Example 1:

+ +
Input: root = [3,2,3,null,3,null,1]
+Output: 7
+Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
+
+ +

Example 2:

+ +
Input: root = [3,4,5,1,3,null,1]
+Output: 9
+Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • 0 <= Node.val <= 104
  • +
+
\ No newline at end of file diff --git a/house-robber-iii/house-robber-iii.cpp b/house-robber-iii/house-robber-iii.cpp new file mode 100644 index 0000000..d06ac79 --- /dev/null +++ b/house-robber-iii/house-robber-iii.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int tryRob(TreeNode* root, int& l, int& r) { + if (!root) + return 0; + + int ll = 0, lr = 0, rl = 0, rr = 0; + l = tryRob(root->left, ll, lr); + r = tryRob(root->right, rl, rr); + + return max(root->val + ll + lr + rl + rr, l + r); + } + + int rob(TreeNode* root) { + int l, r; + return tryRob(root, l, r); + } +}; \ No newline at end of file diff --git a/house-robber/README.md b/house-robber/README.md new file mode 100644 index 0000000..3b9409e --- /dev/null +++ b/house-robber/README.md @@ -0,0 +1,29 @@ +

198. House Robber

Medium


You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

+ +

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,1]
+Output: 4
+Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
+Total amount you can rob = 1 + 3 = 4.
+
+ +

Example 2:

+ +
Input: nums = [2,7,9,3,1]
+Output: 12
+Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
+Total amount you can rob = 2 + 9 + 1 = 12.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 0 <= nums[i] <= 400
  • +
+
\ No newline at end of file diff --git a/house-robber/house-robber.cpp b/house-robber/house-robber.cpp new file mode 100644 index 0000000..7df70b5 --- /dev/null +++ b/house-robber/house-robber.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + vector dp(n+1); + + dp[0] = 0; + dp[1] = nums[0]; + + if(nums.size()<=1)return nums[0]; + for(int i=2;i<=n;i++) + { + if(dp[i-1]>=dp[i-2]+nums[i-1]) + dp[i] = dp[i-1]; + else + dp[i] = dp[i-2]+nums[i-1]; + } + + return dp[n]; + } +}; \ No newline at end of file diff --git a/increasing-order-search-tree/README.md b/increasing-order-search-tree/README.md new file mode 100644 index 0000000..bb4f076 --- /dev/null +++ b/increasing-order-search-tree/README.md @@ -0,0 +1,22 @@ +

897. Increasing Order Search Tree

Easy


Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.

+ +

 

+

Example 1:

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

Example 2:

+ +
Input: root = [5,1,7]
+Output: [1,null,5,null,7]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the given tree will be in the range [1, 100].
  • +
  • 0 <= Node.val <= 1000
  • +
\ No newline at end of file diff --git a/insert-into-a-binary-search-tree/README.md b/insert-into-a-binary-search-tree/README.md new file mode 100644 index 0000000..8488968 --- /dev/null +++ b/insert-into-a-binary-search-tree/README.md @@ -0,0 +1,36 @@ +

701. Insert into a Binary Search Tree

Medium


You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

+ +

Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

+ +

 

+

Example 1:

+ +
Input: root = [4,2,7,1,3], val = 5
+Output: [4,2,7,1,3,5]
+Explanation: Another accepted tree is:
+
+
+ +

Example 2:

+ +
Input: root = [40,20,60,10,30,50,70], val = 25
+Output: [40,20,60,10,30,50,70,null,null,25]
+
+ +

Example 3:

+ +
Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
+Output: [4,2,7,1,3,5]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree will be in the range [0, 104].
  • +
  • -108 <= Node.val <= 108
  • +
  • All the values Node.val are unique.
  • +
  • -108 <= val <= 108
  • +
  • It's guaranteed that val does not exist in the original BST.
  • +
+
\ No newline at end of file diff --git a/insert-into-a-binary-search-tree/insert-into-a-binary-search-tree.cpp b/insert-into-a-binary-search-tree/insert-into-a-binary-search-tree.cpp new file mode 100644 index 0000000..49e8df4 --- /dev/null +++ b/insert-into-a-binary-search-tree/insert-into-a-binary-search-tree.cpp @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* insertIntoBST(TreeNode* root, int val) { + if(root == NULL) + { + TreeNode* newNode = new TreeNode(val); + return newNode; + + } + if(root->val > val) + { + root->left = insertIntoBST(root->left,val); + return root; + } + if(root->val < val) + { + root->right = insertIntoBST(root->right,val); + return root; + } + return root; + } +}; \ No newline at end of file diff --git a/insertion-sort-list/README.md b/insertion-sort-list/README.md new file mode 100644 index 0000000..521112e --- /dev/null +++ b/insertion-sort-list/README.md @@ -0,0 +1,33 @@ +

147. Insertion Sort List

Medium


Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.

+ +

The steps of the insertion sort algorithm:

+ +
    +
  1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
  2. +
  3. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
  4. +
  5. It repeats until no input elements remain.
  6. +
+ +

The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.

+ +

 

+

Example 1:

+ +
Input: head = [4,2,1,3]
+Output: [1,2,3,4]
+
+ +

Example 2:

+ +
Input: head = [-1,5,3,4,0]
+Output: [-1,0,3,4,5]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 5000].
  • +
  • -5000 <= Node.val <= 5000
  • +
+
\ No newline at end of file diff --git a/insertion-sort-list/insertion-sort-list.cpp b/insertion-sort-list/insertion-sort-list.cpp new file mode 100644 index 0000000..4858a5b --- /dev/null +++ b/insertion-sort-list/insertion-sort-list.cpp @@ -0,0 +1,20 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* insertionSortList(ListNode* head) { + for(auto cur = head; cur; cur = cur -> next) + for(auto j = head; j != cur; j = j -> next) + if(j -> val > cur -> val) + swap(j -> val, cur -> val); + return head; + } +}; \ No newline at end of file diff --git a/integer-break/README.md b/integer-break/README.md new file mode 100644 index 0000000..d697f83 --- /dev/null +++ b/integer-break/README.md @@ -0,0 +1,26 @@ +

343. Integer Break

Medium


Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.

+ +

Return the maximum product you can get.

+ +

 

+

Example 1:

+ +
Input: n = 2
+Output: 1
+Explanation: 2 = 1 + 1, 1 × 1 = 1.
+
+ +

Example 2:

+ +
Input: n = 10
+Output: 36
+Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 58
  • +
+
\ No newline at end of file diff --git a/integer-break/integer-break.cpp b/integer-break/integer-break.cpp new file mode 100644 index 0000000..291f299 --- /dev/null +++ b/integer-break/integer-break.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int recursion(int n, int cur) + { + // base + if (n == 0 || cur == 0) { + return 1; + } + // recurisve + if (cur > n) { + return recursion(n - 0, cur - 1); + } + else { + return max(recursion(n - 0, cur - 1), cur * recursion(n - cur, cur)); + } + } + + int integerBreak(int n) + { + return recursion(n, n - 1); + } +}; \ No newline at end of file diff --git a/intersection-of-two-arrays/README.md b/intersection-of-two-arrays/README.md new file mode 100644 index 0000000..b873037 --- /dev/null +++ b/intersection-of-two-arrays/README.md @@ -0,0 +1,24 @@ +

349. Intersection of Two Arrays

Easy


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

+ +

 

+

Example 1:

+ +
Input: nums1 = [1,2,2,1], nums2 = [2,2]
+Output: [2]
+
+ +

Example 2:

+ +
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
+Output: [9,4]
+Explanation: [4,9] is also accepted.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length, nums2.length <= 1000
  • +
  • 0 <= nums1[i], nums2[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/intersection-of-two-arrays/intersection-of-two-arrays.cpp b/intersection-of-two-arrays/intersection-of-two-arrays.cpp new file mode 100644 index 0000000..fd7d89b --- /dev/null +++ b/intersection-of-two-arrays/intersection-of-two-arrays.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + vector intersection(vector& nums1, vector& nums2) { + + vector c; + sort(nums1.begin(),nums1.end()); + sort(nums2.begin(),nums2.end()); + + int a = nums1.size(); + int b = nums2.size(); + int i = 0,j = 0; + while((i < a) && (j < b)) + { + if(nums1[i] == nums2[j]) + { + c.push_back(nums1[i]); + + while((i < a) && nums1[i] == c[c.size()-1] ) + { + i++; + } + while((j < b) && nums2[j] == c[c.size()-1] ) + { + j++; + } + + } + else + { + if(nums1[i] > nums2[j]) + j++; + else + i++; + } + } + return c; + + } +}; \ No newline at end of file diff --git a/intersection-of-two-linked-lists/README.md b/intersection-of-two-linked-lists/README.md new file mode 100644 index 0000000..682bf96 --- /dev/null +++ b/intersection-of-two-linked-lists/README.md @@ -0,0 +1,63 @@ +

160. Intersection of Two Linked Lists

Easy


Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

+ +

For example, the following two linked lists begin to intersect at node c1:

+ +

The test cases are generated such that there are no cycles anywhere in the entire linked structure.

+ +

Note that the linked lists must retain their original structure after the function returns.

+ +

Custom Judge:

+ +

The inputs to the judge are given as follows (your program is not given these inputs):

+ +
    +
  • intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.
  • +
  • listA - The first linked list.
  • +
  • listB - The second linked list.
  • +
  • skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.
  • +
  • skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node.
  • +
+ +

The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted.

+ +

 

+

Example 1:

+ +
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
+Output: Intersected at '8'
+Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
+From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
+
+ +

Example 2:

+ +
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
+Output: Intersected at '2'
+Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
+From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
+
+ +

Example 3:

+ +
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
+Output: No intersection
+Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
+Explanation: The two lists do not intersect, so return null.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes of listA is in the m.
  • +
  • The number of nodes of listB is in the n.
  • +
  • 0 <= m, n <= 3 * 104
  • +
  • 1 <= Node.val <= 105
  • +
  • 0 <= skipA <= m
  • +
  • 0 <= skipB <= n
  • +
  • intersectVal is 0 if listA and listB do not intersect.
  • +
  • intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.
  • +
+ +

 

+Follow up: Could you write a solution that runs in O(n) time and use only O(1) memory?
\ No newline at end of file diff --git a/intersection-of-two-linked-lists/intersection-of-two-linked-lists.cpp b/intersection-of-two-linked-lists/intersection-of-two-linked-lists.cpp new file mode 100644 index 0000000..3df00bd --- /dev/null +++ b/intersection-of-two-linked-lists/intersection-of-two-linked-lists.cpp @@ -0,0 +1,39 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + ListNode * slow = headA; + ListNode * fast = headB; + + while(slow != fast) + { + if(slow == NULL) + { + slow = headB; + } + else + { + slow =slow->next; + } + if(fast == NULL) + { + fast = headA; + } + else + { + fast = fast->next; + } + + // slow = slow->next; + // fast = fast->next; + } + return slow; + } +}; \ No newline at end of file diff --git a/interval-list-intersections/README.md b/interval-list-intersections/README.md new file mode 100644 index 0000000..11f71af --- /dev/null +++ b/interval-list-intersections/README.md @@ -0,0 +1,45 @@ +

986. Interval List Intersections

Medium


You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.

+ +

Return the intersection of these two interval lists.

+ +

A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b.

+ +

The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].

+ +

 

+

Example 1:

+ +
Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]
+Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
+
+ +

Example 2:

+ +
Input: firstList = [[1,3],[5,9]], secondList = []
+Output: []
+
+ +

Example 3:

+ +
Input: firstList = [], secondList = [[4,8],[10,12]]
+Output: []
+
+ +

Example 4:

+ +
Input: firstList = [[1,7]], secondList = [[3,10]]
+Output: [[3,7]]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= firstList.length, secondList.length <= 1000
  • +
  • firstList.length + secondList.length >= 1
  • +
  • 0 <= starti < endi <= 109
  • +
  • endi < starti+1
  • +
  • 0 <= startj < endj <= 109
  • +
  • endj < startj+1
  • +
+
\ No newline at end of file diff --git a/interval-list-intersections/interval-list-intersections.cpp b/interval-list-intersections/interval-list-intersections.cpp new file mode 100644 index 0000000..ee99724 --- /dev/null +++ b/interval-list-intersections/interval-list-intersections.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector> intervalIntersection(vector>& A, vector>& B) { + vector> v; + int i=0,j=0; + while(i2121. Intervals Between Identical Elements

Medium


You are given a 0-indexed array of n integers arr.

+ +

The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|.

+ +

Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i].

+ +

Note: |x| is the absolute value of x.

+ +

 

+

Example 1:

+ +
Input: arr = [2,1,3,1,2,3,3]
+Output: [4,2,7,2,4,4,5]
+Explanation:
+- Index 0: Another 2 is found at index 4. |0 - 4| = 4
+- Index 1: Another 1 is found at index 3. |1 - 3| = 2
+- Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7
+- Index 3: Another 1 is found at index 1. |3 - 1| = 2
+- Index 4: Another 2 is found at index 0. |4 - 0| = 4
+- Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4
+- Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5
+
+ +

Example 2:

+ +
Input: arr = [10,5,10,10]
+Output: [5,0,3,4]
+Explanation:
+- Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5
+- Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0.
+- Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3
+- Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4
+
+ +

 

+

Constraints:

+ +
    +
  • n == arr.length
  • +
  • 1 <= n <= 105
  • +
  • 1 <= arr[i] <= 105
  • +
+
\ No newline at end of file diff --git a/invert-binary-tree/README.md b/invert-binary-tree/README.md new file mode 100644 index 0000000..124a904 --- /dev/null +++ b/invert-binary-tree/README.md @@ -0,0 +1,29 @@ +

226. Invert Binary Tree

Easy


Given the root of a binary tree, invert the tree, and return its root.

+ +

 

+

Example 1:

+ +
Input: root = [4,2,7,1,3,6,9]
+Output: [4,7,2,9,6,3,1]
+
+ +

Example 2:

+ +
Input: root = [2,1,3]
+Output: [2,3,1]
+
+ +

Example 3:

+ +
Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/invert-binary-tree/invert-binary-tree.cpp b/invert-binary-tree/invert-binary-tree.cpp new file mode 100644 index 0000000..7d0ed0d --- /dev/null +++ b/invert-binary-tree/invert-binary-tree.cpp @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if(root == NULL) + return NULL; + + TreeNode * temp = root->left; + root->left = root->right; + root->right = temp; + + root->left = invertTree(root->left); + root->right = invertTree(root->right); + + return root; + } +}; \ No newline at end of file diff --git a/is-graph-bipartite/README.md b/is-graph-bipartite/README.md new file mode 100644 index 0000000..9965b88 --- /dev/null +++ b/is-graph-bipartite/README.md @@ -0,0 +1,39 @@ +

785. Is Graph Bipartite?

Medium


There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:

+ +
    +
  • There are no self-edges (graph[u] does not contain u).
  • +
  • There are no parallel edges (graph[u] does not contain duplicate values).
  • +
  • If v is in graph[u], then u is in graph[v] (the graph is undirected).
  • +
  • The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.
  • +
+ +

A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.

+ +

Return true if and only if it is bipartite.

+ +

 

+

Example 1:

+ +
Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
+Output: false
+Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
+ +

Example 2:

+ +
Input: graph = [[1,3],[0,2],[1,3],[0,2]]
+Output: true
+Explanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.
+ +

 

+

Constraints:

+ +
    +
  • graph.length == n
  • +
  • 1 <= n <= 100
  • +
  • 0 <= graph[u].length < n
  • +
  • 0 <= graph[u][i] <= n - 1
  • +
  • graph[u] does not contain u.
  • +
  • All the values of graph[u] are unique.
  • +
  • If graph[u] contains v, then graph[v] contains u.
  • +
+
\ No newline at end of file diff --git a/is-graph-bipartite/is-graph-bipartite.cpp b/is-graph-bipartite/is-graph-bipartite.cpp new file mode 100644 index 0000000..4fe43c3 --- /dev/null +++ b/is-graph-bipartite/is-graph-bipartite.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + + bool isBipartiteBFS(vector>& graph,bool * visited,int * color,int source) + { + color[source] = 0; + visited[source] = true; + + + queue q; + q.push(source); + + while(!q.empty()) + { + int front = q.front(); + q.pop(); + + for(auto nbrs:graph[front]) + { + if(visited[nbrs] == false) + { + visited[nbrs] = true; + color[nbrs] = !color[front]; + q.push(nbrs); + } + else + { + if(color[nbrs] == color[front]) + return false; + } + + } + } + return true; + } + + bool isBipartite(vector>& graph) { + bool * visited = new bool [graph.size()] {false}; + int * color = new int [graph.size()] {-1}; + + + for(int i=0;i392. Is Subsequence

Easy


Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

+ +

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

+ +

 

+

Example 1:

+
Input: s = "abc", t = "ahbgdc"
+Output: true
+

Example 2:

+
Input: s = "axc", t = "ahbgdc"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 100
  • +
  • 0 <= t.length <= 104
  • +
  • s and t consist only of lowercase English letters.
  • +
+ +

 

+Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?
\ No newline at end of file diff --git a/is-subsequence/is-subsequence.cpp b/is-subsequence/is-subsequence.cpp new file mode 100644 index 0000000..14d5391 --- /dev/null +++ b/is-subsequence/is-subsequence.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + bool isSubsequence(string s, string t) { + if(s.size()>t.size()) + return false; + + int i = 0; + int j = 0; + while(i< s.size() && j205. Isomorphic Strings

Easy


Given two strings s and t, determine if they are isomorphic.

+ +

Two strings s and t are isomorphic if the characters in s can be replaced to get t.

+ +

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

+ +

 

+

Example 1:

+
Input: s = "egg", t = "add"
+Output: true
+

Example 2:

+
Input: s = "foo", t = "bar"
+Output: false
+

Example 3:

+
Input: s = "paper", t = "title"
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 104
  • +
  • t.length == s.length
  • +
  • s and t consist of any valid ascii character.
  • +
+
\ No newline at end of file diff --git a/isomorphic-strings/isomorphic-strings.cpp b/isomorphic-strings/isomorphic-strings.cpp new file mode 100644 index 0000000..f70031d --- /dev/null +++ b/isomorphic-strings/isomorphic-strings.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + bool isIsomorphic(string s, string t) { + int m1[256] = {0}, m2[256] = {0}, n = s.size(); + for (int i = 0; i < n; ++i) { + if (m1[s[i]] != m2[t[i]]) return false; + m1[s[i]] = i + 1; + m2[t[i]] = i + 1; + } + return true; + } +}; \ No newline at end of file diff --git a/iterator-for-combination/README.md b/iterator-for-combination/README.md new file mode 100644 index 0000000..155bc99 --- /dev/null +++ b/iterator-for-combination/README.md @@ -0,0 +1,37 @@ +

1286. Iterator for Combination

Medium


Design the CombinationIterator class:

+ +
    +
  • CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.
  • +
  • next() Returns the next combination of length combinationLength in lexicographical order.
  • +
  • hasNext() Returns true if and only if there exists a next combination.
  • +
+ +

 

+

Example 1:

+ +
Input
+["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
+[["abc", 2], [], [], [], [], [], []]
+Output
+[null, "ab", true, "ac", true, "bc", false]
+
+Explanation
+CombinationIterator itr = new CombinationIterator("abc", 2);
+itr.next();    // return "ab"
+itr.hasNext(); // return True
+itr.next();    // return "ac"
+itr.hasNext(); // return True
+itr.next();    // return "bc"
+itr.hasNext(); // return False
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= combinationLength <= characters.length <= 15
  • +
  • All the characters of characters are unique.
  • +
  • At most 104 calls will be made to next and hasNext.
  • +
  • It's guaranteed that all calls of the function next are valid.
  • +
+
\ No newline at end of file diff --git a/iterator-for-combination/iterator-for-combination.cpp b/iterator-for-combination/iterator-for-combination.cpp new file mode 100644 index 0000000..35f25fb --- /dev/null +++ b/iterator-for-combination/iterator-for-combination.cpp @@ -0,0 +1,24 @@ +class CombinationIterator { + string s; + int n, L, mask = 0; + bool has_next = true; +public: + CombinationIterator(string s, int n) : s(s), L(size(s)), n(n) { + for(int i = 0; i < n; i++) mask |= 1 << (L-1-i); + } + string next() { + string combination = ""; + for(int j = L; j >= 0; j--) // iterate over mask from MSB to LSB + if(mask & (1 << j)) // if a bit is set, + combination += s[L-1-j]; // then add character corresponding to that bit + updateMask(); // move to next mask + return combination; + } + // using Gospel's hack + void updateMask() { + int t = mask + 1, u = t ^ mask, v = t & mask; + mask = v - (v & -v) / (u + 1); + has_next = mask; + } + bool hasNext() { return has_next; } +}; \ No newline at end of file diff --git a/jewels-and-stones/README.md b/jewels-and-stones/README.md new file mode 100644 index 0000000..1e29354 --- /dev/null +++ b/jewels-and-stones/README.md @@ -0,0 +1,21 @@ +

771. Jewels and Stones

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: jewels = "aA", stones = "aAAbbbb"
+Output: 3
+

Example 2:

+
Input: jewels = "z", stones = "ZZ"
+Output: 0
+
+

 

+

Constraints:

+ +
    +
  • 1 <= jewels.length, stones.length <= 50
  • +
  • jewels and stones consist of only English letters.
  • +
  • All the characters of jewels are unique.
  • +
+
\ No newline at end of file diff --git a/jewels-and-stones/jewels-and-stones.cpp b/jewels-and-stones/jewels-and-stones.cpp new file mode 100644 index 0000000..6211b4a --- /dev/null +++ b/jewels-and-stones/jewels-and-stones.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int numJewelsInStones(string jewels, string stones) { + + unordered_map m; + + for(int i=0;i45. Jump Game II

Medium


Given an array of non-negative integers nums, you are initially positioned at the first index of the array.

+ +

Each element in the array represents your maximum jump length at that position.

+ +

Your goal is to reach the last index in the minimum number of jumps.

+ +

You can assume that you can always reach the last index.

+ +

 

+

Example 1:

+ +
Input: nums = [2,3,1,1,4]
+Output: 2
+Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
+
+ +

Example 2:

+ +
Input: nums = [2,3,0,1,4]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • 0 <= nums[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/jump-game-ii/jump-game-ii.cpp b/jump-game-ii/jump-game-ii.cpp new file mode 100644 index 0000000..2cc6688 --- /dev/null +++ b/jump-game-ii/jump-game-ii.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int jump(vector& nums) { + int n = size(nums), i = 0, maxReachable = 0, lastJumpedPos = 0, jumps = 0; + while(lastJumpedPos < n - 1) { // loop till last jump hasn't taken us till the end + maxReachable = max(maxReachable, i + nums[i]); // furthest index reachable on the next level from current level + if(i == lastJumpedPos) { // current level has been iterated & maxReachable position on next level has been finalised + lastJumpedPos = maxReachable; // so just move to that maxReachable position + jumps++; // and increment the level + // NOTE: jump^ only gets updated after we iterate all possible jumps from previous level + // This ensures jumps will only store minimum jump required to reach lastJumpedPos + } + i++; + } + return jumps; + } +}; \ No newline at end of file diff --git a/jump-game/README.md b/jump-game/README.md new file mode 100644 index 0000000..c9f4e2b --- /dev/null +++ b/jump-game/README.md @@ -0,0 +1,27 @@ +

55. Jump Game

Medium


You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

+ +

Return true if you can reach the last index, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: nums = [2,3,1,1,4]
+Output: true
+Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
+
+ +

Example 2:

+ +
Input: nums = [3,2,1,0,4]
+Output: false
+Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • 0 <= nums[i] <= 105
  • +
+
\ No newline at end of file diff --git a/k-closest-points-to-origin/README.md b/k-closest-points-to-origin/README.md new file mode 100644 index 0000000..69b6c43 --- /dev/null +++ b/k-closest-points-to-origin/README.md @@ -0,0 +1,33 @@ +

973. K Closest Points to Origin

Medium


Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).

+ +

The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).

+ +

You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).

+ +

 

+

Example 1:

+ +
Input: points = [[1,3],[-2,2]], k = 1
+Output: [[-2,2]]
+Explanation:
+The distance between (1, 3) and the origin is sqrt(10).
+The distance between (-2, 2) and the origin is sqrt(8).
+Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
+We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].
+
+ +

Example 2:

+ +
Input: points = [[3,3],[5,-1],[-2,4]], k = 2
+Output: [[3,3],[-2,4]]
+Explanation: The answer [[-2,4],[3,3]] would also be accepted.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= points.length <= 104
  • +
  • -104 < xi, yi < 104
  • +
+
\ No newline at end of file diff --git a/k-closest-points-to-origin/k-closest-points-to-origin.cpp b/k-closest-points-to-origin/k-closest-points-to-origin.cpp new file mode 100644 index 0000000..66d168c --- /dev/null +++ b/k-closest-points-to-origin/k-closest-points-to-origin.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + vector> kClosest(vector>& points, int K) { + // points.push_back({0,0}); + partial_sort(points.begin(), points.begin() + K, points.end(), [](vector& p, vector& q) { + return p[0] * p[0] + p[1] * p[1] < q[0] * q[0] + q[1] * q[1]; + }); + + + return vector>(points.begin(), points.begin() + K); + } +}; \ No newline at end of file diff --git a/koko-eating-bananas/README.md b/koko-eating-bananas/README.md new file mode 100644 index 0000000..311ecd1 --- /dev/null +++ b/koko-eating-bananas/README.md @@ -0,0 +1,36 @@ +

875. Koko Eating Bananas

Medium


Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.

+ +

Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.

+ +

Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.

+ +

Return the minimum integer k such that she can eat all the bananas within h hours.

+ +

 

+

Example 1:

+ +
Input: piles = [3,6,7,11], h = 8
+Output: 4
+
+ +

Example 2:

+ +
Input: piles = [30,11,23,4,20], h = 5
+Output: 30
+
+ +

Example 3:

+ +
Input: piles = [30,11,23,4,20], h = 6
+Output: 23
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= piles.length <= 104
  • +
  • piles.length <= h <= 109
  • +
  • 1 <= piles[i] <= 109
  • +
+
\ No newline at end of file diff --git a/kth-largest-element-in-an-array/README.md b/kth-largest-element-in-an-array/README.md new file mode 100644 index 0000000..88e18f4 --- /dev/null +++ b/kth-largest-element-in-an-array/README.md @@ -0,0 +1,20 @@ +

 Kth Largest Element in an Array


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

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [3,2,1,5,6,4], k = 2
+Output: 5
+

Example 2:

+
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
+Output: 4
+
+

 

+

Constraints:

+ +
    +
  • 1 <= k <= nums.length <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
+
\ No newline at end of file diff --git a/kth-smallest-element-in-a-bst/README.md b/kth-smallest-element-in-a-bst/README.md new file mode 100644 index 0000000..4d6e137 --- /dev/null +++ b/kth-smallest-element-in-a-bst/README.md @@ -0,0 +1,27 @@ +

230. Kth Smallest Element in a BST

Medium


Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

+ +

 

+

Example 1:

+ +
Input: root = [3,1,4,null,2], k = 1
+Output: 1
+
+ +

Example 2:

+ +
Input: root = [5,3,6,2,4,null,null,1], k = 3
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is n.
  • +
  • 1 <= k <= n <= 104
  • +
  • 0 <= Node.val <= 104
  • +
+ +

 

+

Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?

+
\ No newline at end of file diff --git a/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst.cpp b/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst.cpp new file mode 100644 index 0000000..54c6eac --- /dev/null +++ b/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst.cpp @@ -0,0 +1,60 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int kthSmallest(TreeNode* root, int k) { + if(root == NULL) + return -1; + int count = 0; + int kmin = INT_MAX; + TreeNode * curr = root; + TreeNode * pre; + while(curr) + { + if(curr->left==NULL) + { + count++; + if(k==count) + { + kmin= curr->val; + } + curr = curr->right; + } + else + { + pre = curr->left; + while(pre->right != NULL && pre->right != curr) + { + pre = pre->right; + } + + if(pre->right == NULL) + { + pre->right = curr; + curr = curr->left; + } + else + { + pre->right = NULL; + count++; + if(k == count) + { + kmin= curr->val; + } + curr = curr->right; + } + } + } + + return kmin; + } +}; \ No newline at end of file diff --git a/kth-smallest-element-in-a-sorted-matrix/README.md b/kth-smallest-element-in-a-sorted-matrix/README.md new file mode 100644 index 0000000..45ee2d5 --- /dev/null +++ b/kth-smallest-element-in-a-sorted-matrix/README.md @@ -0,0 +1,30 @@ +

378. Kth Smallest Element in a Sorted Matrix

Medium


Given an n x n matrix where each of the rows and columns are sorted in ascending order, return the kth smallest element in the matrix.

+ +

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

+ +

 

+

Example 1:

+ +
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
+Output: 13
+Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
+
+ +

Example 2:

+ +
Input: matrix = [[-5]], k = 1
+Output: -5
+
+ +

 

+

Constraints:

+ +
    +
  • n == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= n <= 300
  • +
  • -109 <= matrix[i][j] <= 109
  • +
  • All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
  • +
  • 1 <= k <= n2
  • +
+
\ No newline at end of file diff --git a/kth-smallest-element-in-a-sorted-matrix/kth-smallest-element-in-a-sorted-matrix.cpp b/kth-smallest-element-in-a-sorted-matrix/kth-smallest-element-in-a-sorted-matrix.cpp new file mode 100644 index 0000000..b7bdafd --- /dev/null +++ b/kth-smallest-element-in-a-sorted-matrix/kth-smallest-element-in-a-sorted-matrix.cpp @@ -0,0 +1,29 @@ +class Solution +{ +public: + int kthSmallest(vector>& matrix, int k) + { + int n = matrix.size(); + int le = matrix[0][0], ri = matrix[n - 1][n - 1]; + int mid = 0; + while (le < ri) + { + mid = le + (ri-le)/2; + int num = 0; + for (int i = 0; i < n; i++) + { + int pos = upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin(); + num += pos; + } + if (num < k) + { + le = mid + 1; + } + else + { + ri = mid; + } + } + return le; + } +}; \ No newline at end of file diff --git a/largest-component-size-by-common-factor/README.md b/largest-component-size-by-common-factor/README.md new file mode 100644 index 0000000..ed887de --- /dev/null +++ b/largest-component-size-by-common-factor/README.md @@ -0,0 +1,37 @@ +

952. Largest Component Size by Common Factor

Hard


You are given an integer array of unique positive integers nums. Consider the following graph:

+ +
    +
  • There are nums.length nodes, labeled nums[0] to nums[nums.length - 1],
  • +
  • There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.
  • +
+ +

Return the size of the largest connected component in the graph.

+ +

 

+

Example 1:

+ +
Input: nums = [4,6,15,35]
+Output: 4
+
+ +

Example 2:

+ +
Input: nums = [20,50,9,63]
+Output: 2
+
+ +

Example 3:

+ +
Input: nums = [2,3,6,7,4,12,21,39]
+Output: 8
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2 * 104
  • +
  • 1 <= nums[i] <= 105
  • +
  • All the values of nums are unique.
  • +
+
\ No newline at end of file diff --git a/largest-component-size-by-common-factor/largest-component-size-by-common-factor.cpp b/largest-component-size-by-common-factor/largest-component-size-by-common-factor.cpp new file mode 100644 index 0000000..5164025 --- /dev/null +++ b/largest-component-size-by-common-factor/largest-component-size-by-common-factor.cpp @@ -0,0 +1,45 @@ +class UnionFindSet { +public: + UnionFindSet(int n) : _parent(n) { + for (int i=0; i _parent; +}; + +class Solution { +public: + int largestComponentSize(vector& A) { + int n = *max_element(A.begin(), A.end()); + UnionFindSet ufs(n+1); + for (int &a : A) { + for (int k = 2; k <= sqrt(a); k++) { + if (a % k == 0) { + ufs.Union(a, k); + ufs.Union(a, a / k); + } + } + } + + unordered_map mp; + int ans = 1; + for (int &a : A) { + ans = max(ans, ++mp[ufs.Find(a)]); + } + return ans; + } +}; \ No newline at end of file diff --git a/letter-combinations-of-a-phone-number/README.md b/letter-combinations-of-a-phone-number/README.md new file mode 100644 index 0000000..c14d0ad --- /dev/null +++ b/letter-combinations-of-a-phone-number/README.md @@ -0,0 +1,33 @@ +

17. Letter Combinations of a Phone Number

Medium


Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

+ +

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

+ +

+ +

 

+

Example 1:

+ +
Input: digits = "23"
+Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
+
+ +

Example 2:

+ +
Input: digits = ""
+Output: []
+
+ +

Example 3:

+ +
Input: digits = "2"
+Output: ["a","b","c"]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= digits.length <= 4
  • +
  • digits[i] is a digit in the range ['2', '9'].
  • +
+
\ No newline at end of file diff --git a/letter-combinations-of-a-phone-number/letter-combinations-of-a-phone-number.cpp b/letter-combinations-of-a-phone-number/letter-combinations-of-a-phone-number.cpp new file mode 100644 index 0000000..d65c402 --- /dev/null +++ b/letter-combinations-of-a-phone-number/letter-combinations-of-a-phone-number.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + const vector pad = { + "", "", "abc", "def", "ghi", "jkl", + "mno", "pqrs", "tuv", "wxyz" + }; + + vector letterCombinations(string digits) { + if (digits.empty()) return {}; + vector result; + result.push_back(""); + + for(auto digit: digits) { + vector tmp; + for(auto candidate: pad[digit - '0']) { + for(auto s: result) { + tmp.push_back(s + candidate); + } + } + result.swap(tmp); + } + return result; + } +}; \ No newline at end of file diff --git a/linked-list-cycle-ii/README.md b/linked-list-cycle-ii/README.md new file mode 100644 index 0000000..d35ac2d --- /dev/null +++ b/linked-list-cycle-ii/README.md @@ -0,0 +1,40 @@ +

142. Linked List Cycle II

Medium


Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.

+ +

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.

+ +

Do not modify the linked list.

+ +

 

+

Example 1:

+ +
Input: head = [3,2,0,-4], pos = 1
+Output: tail connects to node index 1
+Explanation: There is a cycle in the linked list, where tail connects to the second node.
+
+ +

Example 2:

+ +
Input: head = [1,2], pos = 0
+Output: tail connects to node index 0
+Explanation: There is a cycle in the linked list, where tail connects to the first node.
+
+ +

Example 3:

+ +
Input: head = [1], pos = -1
+Output: no cycle
+Explanation: There is no cycle in the linked list.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the list is in the range [0, 104].
  • +
  • -105 <= Node.val <= 105
  • +
  • pos is -1 or a valid index in the linked-list.
  • +
+ +

 

+

Follow up: Can you solve it using O(1) (i.e. constant) memory?

+
\ No newline at end of file diff --git a/linked-list-cycle/README.md b/linked-list-cycle/README.md new file mode 100644 index 0000000..3d904c7 --- /dev/null +++ b/linked-list-cycle/README.md @@ -0,0 +1,40 @@ +

141. Linked List Cycle

Easy


Given head, the head of a linked list, determine if the linked list has a cycle in it.

+ +

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

+ +

Return true if there is a cycle in the linked list. Otherwise, return false.

+ +

 

+

Example 1:

+ +
Input: head = [3,2,0,-4], pos = 1
+Output: true
+Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
+
+ +

Example 2:

+ +
Input: head = [1,2], pos = 0
+Output: true
+Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
+
+ +

Example 3:

+ +
Input: head = [1], pos = -1
+Output: false
+Explanation: There is no cycle in the linked list.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the list is in the range [0, 104].
  • +
  • -105 <= Node.val <= 105
  • +
  • pos is -1 or a valid index in the linked-list.
  • +
+ +

 

+

Follow up: Can you solve it using O(1) (i.e. constant) memory?

+
\ No newline at end of file diff --git a/linked-list-cycle/linked-list-cycle.cpp b/linked-list-cycle/linked-list-cycle.cpp new file mode 100644 index 0000000..b13da37 --- /dev/null +++ b/linked-list-cycle/linked-list-cycle.cpp @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool hasCycle(ListNode *head) { + if(head == NULL || head -> next == NULL) + return false; + + ListNode *fast = head; + ListNode *slow = head; + + while(fast -> next && fast -> next -> next){ + fast = fast -> next -> next; + slow = slow -> next; + if(fast == slow) + return true; + } + + return false; + } +}; \ No newline at end of file diff --git a/longest-common-subsequence/README.md b/longest-common-subsequence/README.md new file mode 100644 index 0000000..3f0785b --- /dev/null +++ b/longest-common-subsequence/README.md @@ -0,0 +1,40 @@ +

1143. Longest Common Subsequence

Medium


Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

+ +

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

+ +
    +
  • For example, "ace" is a subsequence of "abcde".
  • +
+ +

A common subsequence of two strings is a subsequence that is common to both strings.

+ +

 

+

Example 1:

+ +
Input: text1 = "abcde", text2 = "ace" 
+Output: 3  
+Explanation: The longest common subsequence is "ace" and its length is 3.
+
+ +

Example 2:

+ +
Input: text1 = "abc", text2 = "abc"
+Output: 3
+Explanation: The longest common subsequence is "abc" and its length is 3.
+
+ +

Example 3:

+ +
Input: text1 = "abc", text2 = "def"
+Output: 0
+Explanation: There is no such common subsequence, so the result is 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= text1.length, text2.length <= 1000
  • +
  • text1 and text2 consist of only lowercase English characters.
  • +
+
\ No newline at end of file diff --git a/longest-common-subsequence/longest-common-subsequence.cpp b/longest-common-subsequence/longest-common-subsequence.cpp new file mode 100644 index 0000000..039970f --- /dev/null +++ b/longest-common-subsequence/longest-common-subsequence.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int longestCommonSubsequence(string &a, string &b) { + vector> m(a.size() + 1, vector(b.size() + 1)); + for (auto i = 1; i <= a.size(); ++i) + for (auto j = 1; j <= b.size(); ++j) + if (a[i - 1] == b[j - 1]) m[i][j] = m[i - 1][j - 1] + 1; + else m[i][j] = max(m[i - 1][j], m[i][j - 1]); + return m[a.size()][b.size()]; +} +}; \ No newline at end of file diff --git a/longest-consecutive-sequence/README.md b/longest-consecutive-sequence/README.md new file mode 100644 index 0000000..efe0a44 --- /dev/null +++ b/longest-consecutive-sequence/README.md @@ -0,0 +1,26 @@ +

128. Longest Consecutive Sequence

Medium


Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

+ +

You must write an algorithm that runs in O(n) time.

+ +

 

+

Example 1:

+ +
Input: nums = [100,4,200,1,3,2]
+Output: 4
+Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
+
+ +

Example 2:

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

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/longest-consecutive-sequence/longest-consecutive-sequence.cpp b/longest-consecutive-sequence/longest-consecutive-sequence.cpp new file mode 100644 index 0000000..54a4347 --- /dev/null +++ b/longest-consecutive-sequence/longest-consecutive-sequence.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int longestConsecutive(vector& nums) { + + if(nums.size() == 0) + return 0; + + int max = INT_MIN; + int count = 1; + map m; + for(auto num:nums) + { + m[num]++; + } + auto it = m.begin(); + int prev = it->first; + it++; + + for(;it != m.end();it++) + { + //cout<first - prev != 1) + { + if(count > max) + max = count; + count = 1; + + } + else + count++; + prev = it->first; + } + + if(count > max) + max = count; + + return max; + } +}; \ No newline at end of file diff --git a/longest-increasing-subsequence/README.md b/longest-increasing-subsequence/README.md new file mode 100644 index 0000000..60446c7 --- /dev/null +++ b/longest-increasing-subsequence/README.md @@ -0,0 +1,35 @@ +

300. Longest Increasing Subsequence

Medium


Given an integer array nums, return the length of the longest strictly increasing subsequence.

+ +

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

+ +

 

+

Example 1:

+ +
Input: nums = [10,9,2,5,3,7,101,18]
+Output: 4
+Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
+
+ +

Example 2:

+ +
Input: nums = [0,1,0,3,2,3]
+Output: 4
+
+ +

Example 3:

+ +
Input: nums = [7,7,7,7,7,7,7]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2500
  • +
  • -104 <= nums[i] <= 104
  • +
+ +

 

+

Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?

+
\ No newline at end of file diff --git a/longest-increasing-subsequence/longest-increasing-subsequence.cpp b/longest-increasing-subsequence/longest-increasing-subsequence.cpp new file mode 100644 index 0000000..70b49dc --- /dev/null +++ b/longest-increasing-subsequence/longest-increasing-subsequence.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int lengthOfLIS(vector& nums) { + vector res; + for(int i=0; i516. Longest Palindromic Subsequence

Medium


Given a string s, find the longest palindromic subsequence's length in s.

+ +

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

+ +

 

+

Example 1:

+ +
Input: s = "bbbab"
+Output: 4
+Explanation: One possible longest palindromic subsequence is "bbbb".
+
+ +

Example 2:

+ +
Input: s = "cbbd"
+Output: 2
+Explanation: One possible longest palindromic subsequence is "bb".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s consists only of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/longest-palindromic-substring/README.md b/longest-palindromic-substring/README.md new file mode 100644 index 0000000..2a30d2a --- /dev/null +++ b/longest-palindromic-substring/README.md @@ -0,0 +1,24 @@ +

5. Longest Palindromic Substring

Medium


Given a string s, return the longest palindromic substring in s.

+ +

 

+

Example 1:

+ +
Input: s = "babad"
+Output: "bab"
+Explanation: "aba" is also a valid answer.
+
+ +

Example 2:

+ +
Input: s = "cbbd"
+Output: "bb"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s consist of only digits and English letters.
  • +
+
\ No newline at end of file diff --git a/longest-palindromic-substring/longest-palindromic-substring.cpp b/longest-palindromic-substring/longest-palindromic-substring.cpp new file mode 100644 index 0000000..c3fd732 --- /dev/null +++ b/longest-palindromic-substring/longest-palindromic-substring.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + string longestPalindrome(string s) { + if (s.empty()) return ""; + if (s.size() == 1) return s; + int min_start = 0, max_len = 1; + for (int i = 0; i < s.size();) { + if (s.size() - i <= max_len / 2) break; + int j = i, k = i; + while (k < s.size()-1 && s[k+1] == s[k]) ++k; // Skip duplicate characters. + i = k+1; + while (k < s.size()-1 && j > 0 && s[k + 1] == s[j - 1]) { ++k; --j; } // Expand. + int new_len = k - j + 1; + if (new_len > max_len) { min_start = j; max_len = new_len; } + } + return s.substr(min_start, max_len); +} +}; \ No newline at end of file diff --git a/longest-repeating-character-replacement/README.md b/longest-repeating-character-replacement/README.md new file mode 100644 index 0000000..33e8277 --- /dev/null +++ b/longest-repeating-character-replacement/README.md @@ -0,0 +1,29 @@ +

424. Longest Repeating Character Replacement

Medium


You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

+ +

Return the length of the longest substring containing the same letter you can get after performing the above operations.

+ +

 

+

Example 1:

+ +
Input: s = "ABAB", k = 2
+Output: 4
+Explanation: Replace the two 'A's with two 'B's or vice versa.
+
+ +

Example 2:

+ +
Input: s = "AABABBA", k = 1
+Output: 4
+Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA".
+The substring "BBBB" has the longest repeating letters, which is 4.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists of only uppercase English letters.
  • +
  • 0 <= k <= s.length
  • +
+
\ No newline at end of file diff --git a/longest-substring-without-repeating-characters/README.md b/longest-substring-without-repeating-characters/README.md new file mode 100644 index 0000000..2c228b4 --- /dev/null +++ b/longest-substring-without-repeating-characters/README.md @@ -0,0 +1,39 @@ +

3. Longest Substring Without Repeating Characters

Medium


Given a string s, find the length of the longest substring without repeating characters.

+ +

 

+

Example 1:

+ +
Input: s = "abcabcbb"
+Output: 3
+Explanation: The answer is "abc", with the length of 3.
+
+ +

Example 2:

+ +
Input: s = "bbbbb"
+Output: 1
+Explanation: The answer is "b", with the length of 1.
+
+ +

Example 3:

+ +
Input: s = "pwwkew"
+Output: 3
+Explanation: The answer is "wke", with the length of 3.
+Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
+
+ +

Example 4:

+ +
Input: s = ""
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 5 * 104
  • +
  • s consists of English letters, digits, symbols and spaces.
  • +
+
\ No newline at end of file diff --git a/longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.cpp b/longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.cpp new file mode 100644 index 0000000..9a289c4 --- /dev/null +++ b/longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int lengthOfLongestSubstring(string s) { + + if(s.size() <=1) + return s.size(); + + int ans = 0; + int low = 0; + int right = 0; + vector v(256,-1); + + while(right < s.size()) + { + if(v[s[right]] != -1) + { + low = max(low,v[s[right]]+1); + } + + v[s[right]] = right; + ans = max(ans,right-low+1); + + right++; + } + + + return ans; + } +}; + + + + + + + diff --git a/longest-uncommon-subsequence-ii/README.md b/longest-uncommon-subsequence-ii/README.md new file mode 100644 index 0000000..210f1e2 --- /dev/null +++ b/longest-uncommon-subsequence-ii/README.md @@ -0,0 +1,27 @@ +

522. Longest Uncommon Subsequence II

Medium


Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1.

+ +

An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others.

+ +

A subsequence of a string s is a string that can be obtained after deleting any number of characters from s.

+ +
    +
  • For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).
  • +
+ +

 

+

Example 1:

+
Input: strs = ["aba","cdc","eae"]
+Output: 3
+

Example 2:

+
Input: strs = ["aaa","aaa","aa"]
+Output: -1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= strs.length <= 50
  • +
  • 1 <= strs[i].length <= 10
  • +
  • strs[i] consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/lowest-common-ancestor-of-a-binary-search-tree/README.md b/lowest-common-ancestor-of-a-binary-search-tree/README.md new file mode 100644 index 0000000..d52dc14 --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-search-tree/README.md @@ -0,0 +1,36 @@ +

235. Lowest Common Ancestor of a Binary Search Tree

Easy


Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

+ +

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

+ +

 

+

Example 1:

+ +
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
+Output: 6
+Explanation: The LCA of nodes 2 and 8 is 6.
+
+ +

Example 2:

+ +
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
+Output: 2
+Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
+
+ +

Example 3:

+ +
Input: root = [2,1], p = 2, q = 1
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 105].
  • +
  • -109 <= Node.val <= 109
  • +
  • All Node.val are unique.
  • +
  • p != q
  • +
  • p and q will exist in the BST.
  • +
+
\ No newline at end of file diff --git a/lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.cpp b/lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.cpp new file mode 100644 index 0000000..057a850 --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.cpp @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + + if(root==NULL) + return root; + + if(root == p || root ==q) + return root; + + if(root->val > p->val && root->val > q->val) + return lowestCommonAncestor(root->left,p,q); + if(root->val < p->val && root->val < q->val) + return lowestCommonAncestor(root->right,p,q); + + return root; + + } +}; \ No newline at end of file diff --git a/lowest-common-ancestor-of-a-binary-tree/README.md b/lowest-common-ancestor-of-a-binary-tree/README.md new file mode 100644 index 0000000..4c0eb0a --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-tree/README.md @@ -0,0 +1,36 @@ +

236. Lowest Common Ancestor of a Binary Tree

Medium


Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

+ +

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

+ +

 

+

Example 1:

+ +
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
+Output: 3
+Explanation: The LCA of nodes 5 and 1 is 3.
+
+ +

Example 2:

+ +
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
+Output: 5
+Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
+
+ +

Example 3:

+ +
Input: root = [1,2], p = 1, q = 2
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 105].
  • +
  • -109 <= Node.val <= 109
  • +
  • All Node.val are unique.
  • +
  • p != q
  • +
  • p and q will exist in the tree.
  • +
+
\ No newline at end of file diff --git a/lowest-common-ancestor-of-a-binary-tree/lowest-common-ancestor-of-a-binary-tree.cpp b/lowest-common-ancestor-of-a-binary-tree/lowest-common-ancestor-of-a-binary-tree.cpp new file mode 100644 index 0000000..0a4f605 --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-tree/lowest-common-ancestor-of-a-binary-tree.cpp @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + + if(root == NULL) + return NULL; + + if(root == p || root == q) + return root; + + TreeNode * l = lowestCommonAncestor(root->left,p,q); + TreeNode * r = lowestCommonAncestor(root->right,p,q); + + if(l != NULL && r != NULL) + return root; + + if(l == NULL) + return r; + return l; + } +}; \ No newline at end of file diff --git a/majority-element-ii/README.md b/majority-element-ii/README.md new file mode 100644 index 0000000..bdceb3a --- /dev/null +++ b/majority-element-ii/README.md @@ -0,0 +1,32 @@ +

229. Majority Element II

Medium


Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

+ +

 

+

Example 1:

+ +
Input: nums = [3,2,3]
+Output: [3]
+
+ +

Example 2:

+ +
Input: nums = [1]
+Output: [1]
+
+ +

Example 3:

+ +
Input: nums = [1,2]
+Output: [1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • -109 <= nums[i] <= 109
  • +
+ +

 

+

Follow up: Could you solve the problem in linear time and in O(1) space?

+
\ No newline at end of file diff --git a/majority-element-ii/majority-element-ii.cpp b/majority-element-ii/majority-element-ii.cpp new file mode 100644 index 0000000..0eaa24c --- /dev/null +++ b/majority-element-ii/majority-element-ii.cpp @@ -0,0 +1,59 @@ +class Solution { +public: + vector majorityElement(vector& nums) { + + int c1 = 0; + int c2 = 0; + int ele1 = INT_MIN; + int ele2 = INT_MIN; + + for(auto num:nums) + { + if(num == ele1) + c1++; + else if(num == ele2) + c2++; + else if(c1==0) + { + ele1 = num; + c1 = 1; + } + else if(c2==0) + { + ele2 = num; + c2 =1 ; + } + else + { + c1--; + c2--; + } + } + vector ans; + // if(ele1 != -1 ) + // { + // ans.push_back(ele1); + // } + // if(ele2 != -1) + // { + // ans.push_back(ele2); + // } + c1 = 0; + c2 = 0; + for(auto num:nums) + { + if(num == ele1) + c1++; + if(num == ele2) + c2++; + + } + + if(c1>floor(nums.size()/3)) + ans.push_back(ele1); + if(c2>floor(nums.size()/3)) + ans.push_back(ele2); + + return ans; + } +}; \ No newline at end of file diff --git a/majority-element/README.md b/majority-element/README.md new file mode 100644 index 0000000..6c4d3ff --- /dev/null +++ b/majority-element/README.md @@ -0,0 +1,23 @@ +

169. Majority Element

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [3,2,3]
+Output: 3
+

Example 2:

+
Input: nums = [2,2,1,1,1,2,2]
+Output: 2
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 5 * 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+ +

 

+Follow-up: Could you solve the problem in linear time and in O(1) space?
\ No newline at end of file diff --git a/majority-element/majority-element.cpp b/majority-element/majority-element.cpp new file mode 100644 index 0000000..9a16910 --- /dev/null +++ b/majority-element/majority-element.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int majorityElement(vector& nums) { + + int counter = 0; + int candidate = 0; + + + for(auto num:nums) + { + if(counter == 0 ) + candidate = num; + + candidate == num ? counter++: counter--; + } + + return candidate; + } +}; \ No newline at end of file diff --git a/make-the-string-great/README.md b/make-the-string-great/README.md new file mode 100644 index 0000000..4751fd3 --- /dev/null +++ b/make-the-string-great/README.md @@ -0,0 +1,45 @@ +

1544. Make The String Great

Easy


Given a string s of lower and upper case English letters.

+ +

A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:

+ +
    +
  • 0 <= i <= s.length - 2
  • +
  • s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
  • +
+ +

To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.

+ +

Return the string after making it good. The answer is guaranteed to be unique under the given constraints.

+ +

Notice that an empty string is also good.

+ +

 

+

Example 1:

+ +
Input: s = "leEeetcode"
+Output: "leetcode"
+Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".
+
+ +

Example 2:

+ +
Input: s = "abBAcC"
+Output: ""
+Explanation: We have many possible scenarios, and all lead to the same answer. For example:
+"abBAcC" --> "aAcC" --> "cC" --> ""
+"abBAcC" --> "abBA" --> "aA" --> ""
+
+ +

Example 3:

+ +
Input: s = "s"
+Output: "s"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 100
  • +
  • s contains only lower and upper case English letters.
  • +
\ No newline at end of file diff --git a/make-the-string-great/make-the-string-great.cpp b/make-the-string-great/make-the-string-great.cpp new file mode 100644 index 0000000..f7a6101 --- /dev/null +++ b/make-the-string-great/make-the-string-great.cpp @@ -0,0 +1,12 @@ +class Solution { +public: +string makeGood(string s, int p = 0) { + for (int i = 0; i < s.size(); ++i) { + if (p > 0 && abs(s[i] - s[p - 1]) == 32) + --p; + else + s[p++] = s[i]; + } + return s.substr(0, p); +} +}; \ No newline at end of file diff --git a/matrix-block-sum/README.md b/matrix-block-sum/README.md new file mode 100644 index 0000000..766a606 --- /dev/null +++ b/matrix-block-sum/README.md @@ -0,0 +1,31 @@ +

1314. Matrix Block Sum

Medium


Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:

+ +
    +
  • i - k <= r <= i + k,
  • +
  • j - k <= c <= j + k, and
  • +
  • (r, c) is a valid position in the matrix.
  • +
+ +

 

+

Example 1:

+ +
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
+Output: [[12,21,16],[27,45,33],[24,39,28]]
+
+ +

Example 2:

+ +
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
+Output: [[45,45,45],[45,45,45],[45,45,45]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == mat.length
  • +
  • n == mat[i].length
  • +
  • 1 <= m, n, k <= 100
  • +
  • 1 <= mat[i][j] <= 100
  • +
+
\ No newline at end of file diff --git a/matrix-block-sum/matrix-block-sum.cpp b/matrix-block-sum/matrix-block-sum.cpp new file mode 100644 index 0000000..dfbc85e --- /dev/null +++ b/matrix-block-sum/matrix-block-sum.cpp @@ -0,0 +1,81 @@ +class Solution { +public: + vector> matrixBlockSum(vector>& mat, int k) { + int n=mat.size(); + int m=mat[0].size(); + vector s(m,0); + vector> l(n,s); + for(int i=0;i s1(m,0); + vector> ans(n,s1); + for(int i=0;i=0){ + if(j+k=0){ + if(i+k=0 && j-k-1>=0){ + fourth=l[i-k-1][j-k-1]; + } + else{ + fourth=0; + } + ans[i][j]=first-second-third+fourth; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/max-area-of-island/README.md b/max-area-of-island/README.md new file mode 100644 index 0000000..9cc5e6f --- /dev/null +++ b/max-area-of-island/README.md @@ -0,0 +1,30 @@ +

695. Max Area of Island

Medium


You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

+ +

The area of an island is the number of cells with a value 1 in the island.

+ +

Return the maximum area of an island in grid. If there is no island, return 0.

+ +

 

+

Example 1:

+ +
Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
+Output: 6
+Explanation: The answer is not 11, because the island must be connected 4-directionally.
+
+ +

Example 2:

+ +
Input: grid = [[0,0,0,0,0,0,0,0]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 50
  • +
  • grid[i][j] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/max-area-of-island/max-area-of-island.cpp b/max-area-of-island/max-area-of-island.cpp new file mode 100644 index 0000000..3388d84 --- /dev/null +++ b/max-area-of-island/max-area-of-island.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int AreaOfIsland(vector>& grid, int i, int j){ + if( i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] == 1){ + grid[i][j] = 0; + return 1 + AreaOfIsland(grid, i+1, j) + AreaOfIsland(grid, i-1, j) + AreaOfIsland(grid, i, j-1) + AreaOfIsland(grid, i, j+1); + } + return 0; + } + int maxAreaOfIsland(vector>& grid) { + int max_area = 0; + for(int i = 0; i < grid.size(); i++) + for(int j = 0; j < grid[0].size(); j++) + if(grid[i][j] == 1)max_area = max(max_area, AreaOfIsland(grid, i, j)); + return max_area; + } + + +}; \ No newline at end of file diff --git a/max-consecutive-ones-iii/README.md b/max-consecutive-ones-iii/README.md new file mode 100644 index 0000000..49181d8 --- /dev/null +++ b/max-consecutive-ones-iii/README.md @@ -0,0 +1,27 @@ +

1004. Max Consecutive Ones III

Medium


Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.

+ +

 

+

Example 1:

+ +
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
+Output: 6
+Explanation: [1,1,1,0,0,1,1,1,1,1,1]
+Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
+ +

Example 2:

+ +
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
+Output: 10
+Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
+Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • nums[i] is either 0 or 1.
  • +
  • 0 <= k <= nums.length
  • +
+
\ No newline at end of file diff --git a/max-consecutive-ones-iii/max-consecutive-ones-iii.cpp b/max-consecutive-ones-iii/max-consecutive-ones-iii.cpp new file mode 100644 index 0000000..054b631 --- /dev/null +++ b/max-consecutive-ones-iii/max-consecutive-ones-iii.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int longestOnes(vector& nums, int k) { + + int l = 0,r = 0; + int counter = 0; + int n = nums.size(); + int ans = INT_MIN; + + while(r k) + { + if(nums[l]==0) + counter--; + + l++; + } + ans = max(ans,r-l); + + } + return ans; + } +}; \ No newline at end of file diff --git a/max-consecutive-ones/README.md b/max-consecutive-ones/README.md new file mode 100644 index 0000000..3054700 --- /dev/null +++ b/max-consecutive-ones/README.md @@ -0,0 +1,24 @@ +

485. Max Consecutive Ones

Easy


Given a binary array nums, return the maximum number of consecutive 1's in the array.

+ +

 

+

Example 1:

+ +
Input: nums = [1,1,0,1,1,1]
+Output: 3
+Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
+
+ +

Example 2:

+ +
Input: nums = [1,0,1,1,0,1]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • nums[i] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/max-consecutive-ones/max-consecutive-ones.cpp b/max-consecutive-ones/max-consecutive-ones.cpp new file mode 100644 index 0000000..e86b37b --- /dev/null +++ b/max-consecutive-ones/max-consecutive-ones.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + + int ans = 0; + int start = 0; + int currones = 0; + while(startans) + ans = currones; + currones = 0; + } + start++; + } + + if(currones>ans) + ans = currones; + + return ans; + + } +}; \ No newline at end of file diff --git a/maximal-rectangle/README.md b/maximal-rectangle/README.md new file mode 100644 index 0000000..e3a02b7 --- /dev/null +++ b/maximal-rectangle/README.md @@ -0,0 +1,44 @@ +

85. Maximal Rectangle

Hard


Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

+ +

 

+

Example 1:

+ +
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
+Output: 6
+Explanation: The maximal rectangle is shown in the above picture.
+
+ +

Example 2:

+ +
Input: matrix = []
+Output: 0
+
+ +

Example 3:

+ +
Input: matrix = [["0"]]
+Output: 0
+
+ +

Example 4:

+ +
Input: matrix = [["1"]]
+Output: 1
+
+ +

Example 5:

+ +
Input: matrix = [["0","0"]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • rows == matrix.length
  • +
  • cols == matrix[i].length
  • +
  • 0 <= row, cols <= 200
  • +
  • matrix[i][j] is '0' or '1'.
  • +
+
\ No newline at end of file diff --git a/maximal-rectangle/maximal-rectangle.cpp b/maximal-rectangle/maximal-rectangle.cpp new file mode 100644 index 0000000..23f560a --- /dev/null +++ b/maximal-rectangle/maximal-rectangle.cpp @@ -0,0 +1,30 @@ +class Solution {public: +int maximalRectangle(vector > &matrix) { + if(matrix.empty()) return 0; + const int m = matrix.size(); + const int n = matrix[0].size(); + int left[n], right[n], height[n]; + fill_n(left,n,0); fill_n(right,n,n); fill_n(height,n,0); + int maxA = 0; + for(int i=0; i=0; j--) { + if(matrix[i][j]=='1') right[j]=min(right[j],cur_right); + else {right[j]=n; cur_right=j;} + } + // compute the area of rectangle (can do this from either side) + for(int j=0; j221. Maximal Square

Medium


Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

+ +

 

+

Example 1:

+ +
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
+Output: 4
+
+ +

Example 2:

+ +
Input: matrix = [["0","1"],["1","0"]]
+Output: 1
+
+ +

Example 3:

+ +
Input: matrix = [["0"]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 300
  • +
  • matrix[i][j] is '0' or '1'.
  • +
+
\ No newline at end of file diff --git a/maximal-square/maximal-square.cpp b/maximal-square/maximal-square.cpp new file mode 100644 index 0000000..b893edd --- /dev/null +++ b/maximal-square/maximal-square.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maximalSquare(vector>& matrix) { + if (matrix.empty()) { + return 0; + } + int m = matrix.size(), n = matrix[0].size(), sz = 0, pre; + vector cur(n, 0); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int temp = cur[j]; + if (!i || !j || matrix[i][j] == '0') { + cur[j] = matrix[i][j] - '0'; + } else { + cur[j] = min(pre, min(cur[j], cur[j - 1])) + 1; + } + sz = max(cur[j], sz); + pre = temp; + } + } + return sz*sz; + } +}; \ No newline at end of file diff --git a/maximum-69-number/README.md b/maximum-69-number/README.md new file mode 100644 index 0000000..1c5f00a --- /dev/null +++ b/maximum-69-number/README.md @@ -0,0 +1,36 @@ +

1323. Maximum 69 Number

Easy


Given a positive integer num consisting only of digits 6 and 9.

+ +

Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).

+ +

 

+

Example 1:

+ +
Input: num = 9669
+Output: 9969
+Explanation: 
+Changing the first digit results in 6669.
+Changing the second digit results in 9969.
+Changing the third digit results in 9699.
+Changing the fourth digit results in 9666. 
+The maximum number is 9969.
+
+ +

Example 2:

+ +
Input: num = 9996
+Output: 9999
+Explanation: Changing the last digit 6 to 9 results in the maximum number.
+ +

Example 3:

+ +
Input: num = 9999
+Output: 9999
+Explanation: It is better not to apply any change.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= num <= 10^4
  • +
  • num's digits are 6 or 9.
  • +
\ No newline at end of file diff --git a/maximum-average-subarray-i/README.md b/maximum-average-subarray-i/README.md new file mode 100644 index 0000000..51db272 --- /dev/null +++ b/maximum-average-subarray-i/README.md @@ -0,0 +1,27 @@ +

643. Maximum Average Subarray I

Easy


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

+ +

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

+ +

 

+

Example 1:

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

Example 2:

+ +
Input: nums = [5], k = 1
+Output: 5.00000
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= k <= n <= 105
  • +
  • -104 <= nums[i] <= 104
  • +
+
\ No newline at end of file diff --git a/maximum-average-subarray-i/maximum-average-subarray-i.cpp b/maximum-average-subarray-i/maximum-average-subarray-i.cpp new file mode 100644 index 0000000..9e69369 --- /dev/null +++ b/maximum-average-subarray-i/maximum-average-subarray-i.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + double findMaxAverage(vector& nums, int k) { + double ans = 0; + + for(int i=0;i654. Maximum Binary Tree

Medium


You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:

+ +
    +
  1. Create a root node whose value is the maximum value in nums.
  2. +
  3. Recursively build the left subtree on the subarray prefix to the left of the maximum value.
  4. +
  5. Recursively build the right subtree on the subarray suffix to the right of the maximum value.
  6. +
+ +

Return the maximum binary tree built from nums.

+ +

 

+

Example 1:

+ +
Input: nums = [3,2,1,6,0,5]
+Output: [6,3,5,null,2,0,null,null,1]
+Explanation: The recursive calls are as follow:
+- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].
+    - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].
+        - Empty array, so no child.
+        - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].
+            - Empty array, so no child.
+            - Only one element, so child is a node with value 1.
+    - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].
+        - Only one element, so child is a node with value 0.
+        - Empty array, so no child.
+
+ +

Example 2:

+ +
Input: nums = [3,2,1]
+Output: [3,null,2,null,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 0 <= nums[i] <= 1000
  • +
  • All integers in nums are unique.
  • +
+
\ No newline at end of file diff --git a/maximum-depth-of-binary-tree/README.md b/maximum-depth-of-binary-tree/README.md new file mode 100644 index 0000000..3a9697e --- /dev/null +++ b/maximum-depth-of-binary-tree/README.md @@ -0,0 +1,37 @@ +

104. Maximum Depth of Binary Tree

Easy


Given the root of a binary tree, return its maximum depth.

+ +

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: 3
+
+ +

Example 2:

+ +
Input: root = [1,null,2]
+Output: 2
+
+ +

Example 3:

+ +
Input: root = []
+Output: 0
+
+ +

Example 4:

+ +
Input: root = [0]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.cpp b/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.cpp new file mode 100644 index 0000000..f09af49 --- /dev/null +++ b/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.cpp @@ -0,0 +1,22 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxDepth(TreeNode* root) { + + if(root == NULL) + return 0; + + return 1+ max(maxDepth(root->left) , maxDepth(root->right)); + + } +}; \ No newline at end of file diff --git a/maximum-difference-between-node-and-ancestor/README.md b/maximum-difference-between-node-and-ancestor/README.md new file mode 100644 index 0000000..1c8b3e4 --- /dev/null +++ b/maximum-difference-between-node-and-ancestor/README.md @@ -0,0 +1,30 @@ +

1026. Maximum Difference Between Node and Ancestor

Medium


Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.

+ +

A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.

+ +

 

+

Example 1:

+ +
Input: root = [8,3,10,1,6,null,14,null,null,4,7,13]
+Output: 7
+Explanation: We have various ancestor-node differences, some of which are given below :
+|8 - 3| = 5
+|3 - 7| = 4
+|8 - 1| = 7
+|10 - 13| = 3
+Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
+ +

Example 2:

+ +
Input: root = [1,null,2,null,0,3]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 5000].
  • +
  • 0 <= Node.val <= 105
  • +
+
\ No newline at end of file diff --git a/maximum-difference-between-node-and-ancestor/maximum-difference-between-node-and-ancestor.cpp b/maximum-difference-between-node-and-ancestor/maximum-difference-between-node-and-ancestor.cpp new file mode 100644 index 0000000..0c91af2 --- /dev/null +++ b/maximum-difference-between-node-and-ancestor/maximum-difference-between-node-and-ancestor.cpp @@ -0,0 +1,19 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + int maxAncestorDiff(TreeNode* r, int mn = 100000, int mx = 0) { + return r ? max(maxAncestorDiff(r->left, min(mn, r->val), max(mx, r->val)), + maxAncestorDiff(r->right, min(mn, r->val), max(mx, r->val))) : mx - mn; + } +}; \ No newline at end of file diff --git a/maximum-employees-to-be-invited-to-a-meeting/README.md b/maximum-employees-to-be-invited-to-a-meeting/README.md new file mode 100644 index 0000000..873cadf --- /dev/null +++ b/maximum-employees-to-be-invited-to-a-meeting/README.md @@ -0,0 +1,52 @@ +

2127. Maximum Employees to Be Invited to a Meeting

Hard


A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees.

+ +

The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself.

+ +

Given a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting.

+ +

 

+

Example 1:

+ +
Input: favorite = [2,2,1,2]
+Output: 3
+Explanation:
+The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.
+All employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.
+Note that the company can also invite employees 1, 2, and 3, and give them their desired seats.
+The maximum number of employees that can be invited to the meeting is 3. 
+
+ +

Example 2:

+ +
Input: favorite = [1,2,0]
+Output: 3
+Explanation: 
+Each employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee.
+The seating arrangement will be the same as that in the figure given in example 1:
+- Employee 0 will sit between employees 2 and 1.
+- Employee 1 will sit between employees 0 and 2.
+- Employee 2 will sit between employees 1 and 0.
+The maximum number of employees that can be invited to the meeting is 3.
+
+ +

Example 3:

+ +
Input: favorite = [3,0,1,4,1]
+Output: 4
+Explanation:
+The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.
+Employee 2 cannot be invited because the two spots next to their favorite employee 0 are taken.
+So the company leaves them out of the meeting.
+The maximum number of employees that can be invited to the meeting is 4.
+
+ +

 

+

Constraints:

+ +
    +
  • n == favorite.length
  • +
  • 2 <= n <= 105
  • +
  • 0 <= favorite[i] <= n - 1
  • +
  • favorite[i] != i
  • +
+
\ No newline at end of file diff --git a/maximum-length-of-repeated-subarray/README.md b/maximum-length-of-repeated-subarray/README.md new file mode 100644 index 0000000..fa53a1f --- /dev/null +++ b/maximum-length-of-repeated-subarray/README.md @@ -0,0 +1,24 @@ +

718. Maximum Length of Repeated Subarray

Medium


Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.

+ +

 

+

Example 1:

+ +
Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
+Output: 3
+Explanation: The repeated subarray with maximum length is [3,2,1].
+
+ +

Example 2:

+ +
Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
+Output: 5
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length, nums2.length <= 1000
  • +
  • 0 <= nums1[i], nums2[i] <= 100
  • +
+
\ No newline at end of file diff --git a/maximum-length-of-subarray-with-positive-product/README.md b/maximum-length-of-subarray-with-positive-product/README.md new file mode 100644 index 0000000..578197e --- /dev/null +++ b/maximum-length-of-subarray-with-positive-product/README.md @@ -0,0 +1,48 @@ +

1567. Maximum Length of Subarray With Positive Product

Medium


Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.

+ +

A subarray of an array is a consecutive sequence of zero or more values taken out of that array.

+ +

Return the maximum length of a subarray with positive product.

+ +

 

+

Example 1:

+ +
Input: nums = [1,-2,-3,4]
+Output: 4
+Explanation: The array nums already has a positive product of 24.
+
+ +

Example 2:

+ +
Input: nums = [0,1,-2,-3,-4]
+Output: 3
+Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
+Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
+ +

Example 3:

+ +
Input: nums = [-1,-2,-3,0,1]
+Output: 2
+Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
+
+ +

Example 4:

+ +
Input: nums = [-1,2]
+Output: 1
+
+ +

Example 5:

+ +
Input: nums = [1,2,3,5,-6,4,0,10]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 10^5
  • +
  • -10^9 <= nums[i] <= 10^9
  • +
+
\ No newline at end of file diff --git a/maximum-product-subarray/README.md b/maximum-product-subarray/README.md new file mode 100644 index 0000000..608ace2 --- /dev/null +++ b/maximum-product-subarray/README.md @@ -0,0 +1,30 @@ +

152. Maximum Product Subarray

Medium


Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.

+ +

It is guaranteed that the answer will fit in a 32-bit integer.

+ +

A subarray is a contiguous subsequence of the array.

+ +

 

+

Example 1:

+ +
Input: nums = [2,3,-2,4]
+Output: 6
+Explanation: [2,3] has the largest product 6.
+
+ +

Example 2:

+ +
Input: nums = [-2,0,-1]
+Output: 0
+Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2 * 104
  • +
  • -10 <= nums[i] <= 10
  • +
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
  • +
+
\ No newline at end of file diff --git a/maximum-product-subarray/maximum-product-subarray.cpp b/maximum-product-subarray/maximum-product-subarray.cpp new file mode 100644 index 0000000..d5974a1 --- /dev/null +++ b/maximum-product-subarray/maximum-product-subarray.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + + + int maxProduct(vector& nums) { + int r = nums[0]; + int maxi = r,mini = r; + + for(int i=1;i1235. Maximum Profit in Job Scheduling

Hard


We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].

+ +

You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.

+ +

If you choose a job that ends at time X you will be able to start another job that starts at time X.

+ +

 

+

Example 1:

+ +

+ +
Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
+Output: 120
+Explanation: The subset chosen is the first and fourth job. 
+Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.
+
+ +

Example 2:

+ +

+ +
Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
+Output: 150
+Explanation: The subset chosen is the first, fourth and fifth job. 
+Profit obtained 150 = 20 + 70 + 60.
+
+ +

Example 3:

+ +

+ +
Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]
+Output: 6
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= startTime.length == endTime.length == profit.length <= 5 * 104
  • +
  • 1 <= startTime[i] < endTime[i] <= 109
  • +
  • 1 <= profit[i] <= 104
  • +
+
\ No newline at end of file diff --git a/maximum-profit-in-job-scheduling/maximum-profit-in-job-scheduling.cpp b/maximum-profit-in-job-scheduling/maximum-profit-in-job-scheduling.cpp new file mode 100644 index 0000000..e0f06f8 --- /dev/null +++ b/maximum-profit-in-job-scheduling/maximum-profit-in-job-scheduling.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int jobScheduling(vector& startTime, vector& endTime, vector& profit) { + vector idx(startTime.size()); + iota(begin(idx), end(idx), 0); + sort(begin(idx), end(idx), [&](int i, int j) { return startTime[i] > startTime[j]; }); + map memo; + int max_profit = 0; + for (auto i = 0; i < idx.size(); ++i) { + auto it = memo.lower_bound(endTime[idx[i]]); + max_profit = max(max_profit, (it == end(memo) ? 0 : it->second) + profit[idx[i]]); + memo[startTime[idx[i]]] = max_profit; + } + return max_profit; +} +}; \ No newline at end of file diff --git a/maximum-score-from-removing-stones/README.md b/maximum-score-from-removing-stones/README.md new file mode 100644 index 0000000..bf2d22f --- /dev/null +++ b/maximum-score-from-removing-stones/README.md @@ -0,0 +1,49 @@ +

1753. Maximum Score From Removing Stones

Medium


You are playing a solitaire game with three piles of stones of sizes a​​​​​​, b,​​​​​​ and c​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves).

+ +

Given three integers a​​​​​, b,​​​​​ and c​​​​​, return the maximum score you can get.

+ +

 

+

Example 1:

+ +
Input: a = 2, b = 4, c = 6
+Output: 6
+Explanation: The starting state is (2, 4, 6). One optimal set of moves is:
+- Take from 1st and 3rd piles, state is now (1, 4, 5)
+- Take from 1st and 3rd piles, state is now (0, 4, 4)
+- Take from 2nd and 3rd piles, state is now (0, 3, 3)
+- Take from 2nd and 3rd piles, state is now (0, 2, 2)
+- Take from 2nd and 3rd piles, state is now (0, 1, 1)
+- Take from 2nd and 3rd piles, state is now (0, 0, 0)
+There are fewer than two non-empty piles, so the game ends. Total: 6 points.
+
+ +

Example 2:

+ +
Input: a = 4, b = 4, c = 6
+Output: 7
+Explanation: The starting state is (4, 4, 6). One optimal set of moves is:
+- Take from 1st and 2nd piles, state is now (3, 3, 6)
+- Take from 1st and 3rd piles, state is now (2, 3, 5)
+- Take from 1st and 3rd piles, state is now (1, 3, 4)
+- Take from 1st and 3rd piles, state is now (0, 3, 3)
+- Take from 2nd and 3rd piles, state is now (0, 2, 2)
+- Take from 2nd and 3rd piles, state is now (0, 1, 1)
+- Take from 2nd and 3rd piles, state is now (0, 0, 0)
+There are fewer than two non-empty piles, so the game ends. Total: 7 points.
+
+ +

Example 3:

+ +
Input: a = 1, b = 8, c = 8
+Output: 8
+Explanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.
+After that, there are fewer than two non-empty piles, so the game ends.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= a, b, c <= 105
  • +
+
\ No newline at end of file diff --git a/maximum-subarray/README.md b/maximum-subarray/README.md new file mode 100644 index 0000000..d2ab332 --- /dev/null +++ b/maximum-subarray/README.md @@ -0,0 +1,32 @@ +

53. Maximum Subarray

Easy


Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

+ +

 

+

Example 1:

+ +
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
+Output: 6
+Explanation: [4,-1,2,1] has the largest sum = 6.
+
+ +

Example 2:

+ +
Input: nums = [1]
+Output: 1
+
+ +

Example 3:

+ +
Input: nums = [5,4,-1,7,8]
+Output: 23
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -105 <= nums[i] <= 105
  • +
+ +

 

+Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
\ No newline at end of file diff --git a/maximum-subarray/maximum-subarray.cpp b/maximum-subarray/maximum-subarray.cpp new file mode 100644 index 0000000..c7aaf81 --- /dev/null +++ b/maximum-subarray/maximum-subarray.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int maxSubArray(vector& nums) { + int max_sum=nums[0], sum=nums[0]; + for(int i=1; imax_sum) { + max_sum=sum; + } + } + + return max_sum; + } +}; \ No newline at end of file diff --git a/maximum-sum-circular-subarray/README.md b/maximum-sum-circular-subarray/README.md new file mode 100644 index 0000000..231217f --- /dev/null +++ b/maximum-sum-circular-subarray/README.md @@ -0,0 +1,51 @@ +

918. Maximum Sum Circular Subarray

Medium


Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.

+ +

A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n].

+ +

A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i <= k1, k2 <= j with k1 % n == k2 % n.

+ +

 

+

Example 1:

+ +
Input: nums = [1,-2,3,-2]
+Output: 3
+Explanation: Subarray [3] has maximum sum 3
+
+ +

Example 2:

+ +
Input: nums = [5,-3,5]
+Output: 10
+Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10
+
+ +

Example 3:

+ +
Input: nums = [3,-1,2,-1]
+Output: 4
+Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4
+
+ +

Example 4:

+ +
Input: nums = [3,-2,2,-3]
+Output: 3
+Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3
+
+ +

Example 5:

+ +
Input: nums = [-2,-3,-1]
+Output: -1
+Explanation: Subarray [-1] has maximum sum -1
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 3 * 104
  • +
  • -3 * 104 <= nums[i] <= 3 * 104
  • +
+
\ No newline at end of file diff --git a/maximum-sum-circular-subarray/maximum-sum-circular-subarray.cpp b/maximum-sum-circular-subarray/maximum-sum-circular-subarray.cpp new file mode 100644 index 0000000..9d11e06 --- /dev/null +++ b/maximum-sum-circular-subarray/maximum-sum-circular-subarray.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int maxSubarraySumCircular(vector& A) { + if(A.size() == 0) return 0; + int sum = A[0]; + int maxSoFar = A[0]; + int maxTotal = A[0]; + int minSoFar = A[0]; + int minTotal = A[0]; + for(int i = 1; i< A.size();i++){ + maxSoFar = max(A[i], maxSoFar + A[i]); + maxTotal = max(maxTotal, maxSoFar); + + minSoFar = min(A[i], minSoFar + A[i]); + minTotal = min(minTotal, minSoFar); + sum += A[i]; + + } + if(sum == minTotal) return maxTotal; + return max(sum - minTotal, maxTotal); + } +}; \ No newline at end of file diff --git a/maximum-units-on-a-truck/README.md b/maximum-units-on-a-truck/README.md new file mode 100644 index 0000000..506b020 --- /dev/null +++ b/maximum-units-on-a-truck/README.md @@ -0,0 +1,39 @@ +

1710. Maximum Units on a Truck

Easy


You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]:

+ +
    +
  • numberOfBoxesi is the number of boxes of type i.
  • +
  • numberOfUnitsPerBoxi is the number of units in each box of the type i.
  • +
+ +

You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.

+ +

Return the maximum total number of units that can be put on the truck.

+ +

 

+

Example 1:

+ +
Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
+Output: 8
+Explanation: There are:
+- 1 box of the first type that contains 3 units.
+- 2 boxes of the second type that contain 2 units each.
+- 3 boxes of the third type that contain 1 unit each.
+You can take all the boxes of the first and second types, and one box of the third type.
+The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.
+
+ +

Example 2:

+ +
Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
+Output: 91
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= boxTypes.length <= 1000
  • +
  • 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000
  • +
  • 1 <= truckSize <= 106
  • +
+
\ No newline at end of file diff --git a/maximum-units-on-a-truck/maximum-units-on-a-truck.cpp b/maximum-units-on-a-truck/maximum-units-on-a-truck.cpp new file mode 100644 index 0000000..8776409 --- /dev/null +++ b/maximum-units-on-a-truck/maximum-units-on-a-truck.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + static bool myfunction(vector& a, vector& b){ + return a[1] > b[1]; + } + int maximumUnits(vector>& boxTypes, int truckSize) { + //custom sort (in increasing order of numberOfUnitsPerBox as we have to return maximum total number of units ) + sort(boxTypes.begin(),boxTypes.end(),myfunction); + //greedily pick boxes till capacity is full + int ans=0; + for(auto box: boxTypes){ + int x=min(box[0],truckSize); //choose minimum boxes from available boxes and capacity left + ans+=(x*box[1]); //adding units in ans + truckSize-=x; //reduce the capacity + if(!truckSize) break; //capacity full + } + return ans; + } +}; \ No newline at end of file diff --git a/median-of-two-sorted-arrays/README.md b/median-of-two-sorted-arrays/README.md new file mode 100644 index 0000000..9bed02b --- /dev/null +++ b/median-of-two-sorted-arrays/README.md @@ -0,0 +1,49 @@ +

4. Median of Two Sorted Arrays

Hard


Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

+ +

The overall run time complexity should be O(log (m+n)).

+ +

 

+

Example 1:

+ +
Input: nums1 = [1,3], nums2 = [2]
+Output: 2.00000
+Explanation: merged array = [1,2,3] and median is 2.
+
+ +

Example 2:

+ +
Input: nums1 = [1,2], nums2 = [3,4]
+Output: 2.50000
+Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
+
+ +

Example 3:

+ +
Input: nums1 = [0,0], nums2 = [0,0]
+Output: 0.00000
+
+ +

Example 4:

+ +
Input: nums1 = [], nums2 = [1]
+Output: 1.00000
+
+ +

Example 5:

+ +
Input: nums1 = [2], nums2 = []
+Output: 2.00000
+
+ +

 

+

Constraints:

+ +
    +
  • nums1.length == m
  • +
  • nums2.length == n
  • +
  • 0 <= m <= 1000
  • +
  • 0 <= n <= 1000
  • +
  • 1 <= m + n <= 2000
  • +
  • -106 <= nums1[i], nums2[i] <= 106
  • +
+
\ No newline at end of file diff --git a/median-of-two-sorted-arrays/median-of-two-sorted-arrays.cpp b/median-of-two-sorted-arrays/median-of-two-sorted-arrays.cpp new file mode 100644 index 0000000..83fd5f4 --- /dev/null +++ b/median-of-two-sorted-arrays/median-of-two-sorted-arrays.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + double findMedianSortedArrays(std::vector& nums1, std::vector& nums2) { + int temp, median_pos; + double median; + std::vector nums3 = nums1; + + nums3.insert( nums3.end(), nums2.begin(), nums2.end() ); + for (int i = 0; i < nums3.size() -1; i++) { + for (int j = i + 1; j < nums3.size(); j++) { + if (nums3[i] > nums3[j]) { + temp = nums3[i]; + nums3[i] = nums3[j]; + nums3[j] = temp; + } + } + } + + if (nums3.size() % 2 != 0) + median = nums3[ ((nums3.size() + 1) >> 1) - 1 ]; + else { + int lhs = nums3[(nums3.size() >> 1) - 1]; + int rhs = nums3[(nums3.size() >> 1)]; + median = (lhs + rhs) / 2.0; + } + + return median+1-1; + } +}; \ No newline at end of file diff --git a/merge-intervals/README.md b/merge-intervals/README.md new file mode 100644 index 0000000..408c422 --- /dev/null +++ b/merge-intervals/README.md @@ -0,0 +1,26 @@ +

56. Merge Intervals

Medium


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

+ +

 

+

Example 1:

+ +
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
+Output: [[1,6],[8,10],[15,18]]
+Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
+
+ +

Example 2:

+ +
Input: intervals = [[1,4],[4,5]]
+Output: [[1,5]]
+Explanation: Intervals [1,4] and [4,5] are considered overlapping.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= intervals.length <= 104
  • +
  • intervals[i].length == 2
  • +
  • 0 <= starti <= endi <= 104
  • +
+
\ No newline at end of file diff --git a/merge-intervals/merge-intervals.cpp b/merge-intervals/merge-intervals.cpp new file mode 100644 index 0000000..981fe67 --- /dev/null +++ b/merge-intervals/merge-intervals.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector> merge(vector>& intervals) { + vector> merged ; + sort(intervals.begin(),intervals.end()); + + for(auto interval:intervals) + { + if(merged.size() == 0 || merged.back()[1] < interval[0]) + { + merged.push_back(interval); + } + else + { + merged.back()[1] = max(merged.back()[1],interval[1]); + } + + } + return merged; + + } +}; \ No newline at end of file diff --git a/merge-k-sorted-lists/README.md b/merge-k-sorted-lists/README.md new file mode 100644 index 0000000..a436b33 --- /dev/null +++ b/merge-k-sorted-lists/README.md @@ -0,0 +1,43 @@ +

23. Merge k Sorted Lists

Hard


You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

+ +

Merge all the linked-lists into one sorted linked-list and return it.

+ +

 

+

Example 1:

+ +
Input: lists = [[1,4,5],[1,3,4],[2,6]]
+Output: [1,1,2,3,4,4,5,6]
+Explanation: The linked-lists are:
+[
+  1->4->5,
+  1->3->4,
+  2->6
+]
+merging them into one sorted list:
+1->1->2->3->4->4->5->6
+
+ +

Example 2:

+ +
Input: lists = []
+Output: []
+
+ +

Example 3:

+ +
Input: lists = [[]]
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • k == lists.length
  • +
  • 0 <= k <= 10^4
  • +
  • 0 <= lists[i].length <= 500
  • +
  • -10^4 <= lists[i][j] <= 10^4
  • +
  • lists[i] is sorted in ascending order.
  • +
  • The sum of lists[i].length won't exceed 10^4.
  • +
+
\ No newline at end of file diff --git a/merge-k-sorted-lists/merge-k-sorted-lists.cpp b/merge-k-sorted-lists/merge-k-sorted-lists.cpp new file mode 100644 index 0000000..271d541 --- /dev/null +++ b/merge-k-sorted-lists/merge-k-sorted-lists.cpp @@ -0,0 +1,59 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + + if(l1 == NULL) + return l2; + if(l2 == NULL) + return l1; + + if(l1->val >= l2->val) + { + ListNode * temp = l1; + l1 = l2; + l2 = temp; + } + + ListNode* res = l1; + + while(l2 != NULL && l1 != NULL) + { + ListNode * temp = NULL; + while(l1 != NULL && l2->val >= l1->val) + { + temp = l1; + l1 = l1->next; + } + temp -> next = l2; + + ListNode * tem = l1; + l1 = l2; + l2 = tem; + + } + return res; + + } + ListNode* mergeKLists(vector& lists) { + + if (lists.size() == 0) return NULL; + + ListNode* head = lists[0]; + + for (int i = 1; i < lists.size(); i++) + head = mergeTwoLists(head, lists[i]); + + return head; + } +}; \ No newline at end of file diff --git a/merge-sorted-array/README.md b/merge-sorted-array/README.md new file mode 100644 index 0000000..35a9ff3 --- /dev/null +++ b/merge-sorted-array/README.md @@ -0,0 +1,46 @@ +

88. Merge Sorted Array

Easy


You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

+ +

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

+ +

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

+ +

 

+

Example 1:

+ +
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
+Output: [1,2,2,3,5,6]
+Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
+The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
+
+ +

Example 2:

+ +
Input: nums1 = [1], m = 1, nums2 = [], n = 0
+Output: [1]
+Explanation: The arrays we are merging are [1] and [].
+The result of the merge is [1].
+
+ +

Example 3:

+ +
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
+Output: [1]
+Explanation: The arrays we are merging are [] and [1].
+The result of the merge is [1].
+Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
+
+ +

 

+

Constraints:

+ +
    +
  • nums1.length == m + n
  • +
  • nums2.length == n
  • +
  • 0 <= m, n <= 200
  • +
  • 1 <= m + n <= 200
  • +
  • -109 <= nums1[i], nums2[j] <= 109
  • +
+ +

 

+

Follow up: Can you come up with an algorithm that runs in O(m + n) time?

+
\ No newline at end of file diff --git a/merge-sorted-array/merge-sorted-array.cpp b/merge-sorted-array/merge-sorted-array.cpp new file mode 100644 index 0000000..caa9bd3 --- /dev/null +++ b/merge-sorted-array/merge-sorted-array.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + vector ans(n+m); + + int i=0; + int j =0; + int k=0; + while(i != m && j != n) + { + if(nums1[i]>= nums2[j]) + ans[k++] = nums2[j++]; + else + ans[k++] = nums1[i++]; + } + + if(i == m) + { + while(j != n) + ans[k++] = nums2[j++]; + } + if(j == n) + { + while(i != m) + ans[k++] = nums1[i++]; + } + + for(int l=0;l<(n+m);l++) + nums1[l] = ans[l]; + + } +}; \ No newline at end of file diff --git a/merge-two-binary-trees/README.md b/merge-two-binary-trees/README.md new file mode 100644 index 0000000..eb2a305 --- /dev/null +++ b/merge-two-binary-trees/README.md @@ -0,0 +1,29 @@ +

617. Merge Two Binary Trees

Easy


You are given two binary trees root1 and root2.

+ +

Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.

+ +

Return the merged tree.

+ +

Note: The merging process must start from the root nodes of both trees.

+ +

 

+

Example 1:

+ +
Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
+Output: [3,4,5,5,4,null,7]
+
+ +

Example 2:

+ +
Input: root1 = [1], root2 = [1,2]
+Output: [2,2]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in both trees is in the range [0, 2000].
  • +
  • -104 <= Node.val <= 104
  • +
+
\ No newline at end of file diff --git a/merge-two-binary-trees/merge-two-binary-trees.cpp b/merge-two-binary-trees/merge-two-binary-trees.cpp new file mode 100644 index 0000000..06590af --- /dev/null +++ b/merge-two-binary-trees/merge-two-binary-trees.cpp @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { + if(root1 == NULL && root2 == NULL ) + return NULL; + if(root1 == NULL) + return root2; + if(root2 == NULL) + return root1; + + root1->val = root1->val + root2->val; + + root1->left = mergeTrees(root1->left,root2->left); + root1->right = mergeTrees(root1->right,root2->right); + + return root1; + } +}; \ No newline at end of file diff --git a/merge-two-sorted-lists/README.md b/merge-two-sorted-lists/README.md new file mode 100644 index 0000000..0a79189 --- /dev/null +++ b/merge-two-sorted-lists/README.md @@ -0,0 +1,30 @@ +

21. Merge Two Sorted Lists

Easy


Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

+ +

 

+

Example 1:

+ +
Input: l1 = [1,2,4], l2 = [1,3,4]
+Output: [1,1,2,3,4,4]
+
+ +

Example 2:

+ +
Input: l1 = [], l2 = []
+Output: []
+
+ +

Example 3:

+ +
Input: l1 = [], l2 = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in both lists is in the range [0, 50].
  • +
  • -100 <= Node.val <= 100
  • +
  • Both l1 and l2 are sorted in non-decreasing order.
  • +
+
\ No newline at end of file diff --git a/merge-two-sorted-lists/merge-two-sorted-lists.cpp b/merge-two-sorted-lists/merge-two-sorted-lists.cpp new file mode 100644 index 0000000..dbf58a0 --- /dev/null +++ b/merge-two-sorted-lists/merge-two-sorted-lists.cpp @@ -0,0 +1,54 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + if(l1==NULL) + return l2; + if(l2 == NULL) + return l1; + + if(l1->val >= l2->val) + { + ListNode * temp = l1; + l1 = l2; + l2 = temp; + } + ListNode * dummy = new ListNode(0); + ListNode * temp = dummy; + dummy->next = l1; + + while(l1 !=NULL && l2 != NULL) + { + while(l1 != NULL && l1->val <= l2->val) + { + l1 = l1->next; + temp = temp->next; + } + if(l1 != NULL && l1->val > l2->val) + { + temp->next = l2; + // temp = temp->next; + ListNode * re = l2; + l2 = l1; + l1 = re; + } + + } + + if(l1 == NULL) + temp->next = l2; + if(l2 == NULL) + temp->next = l1; + + return dummy->next; + } +}; \ No newline at end of file diff --git a/middle-of-the-linked-list/README.md b/middle-of-the-linked-list/README.md new file mode 100644 index 0000000..5ac8a92 --- /dev/null +++ b/middle-of-the-linked-list/README.md @@ -0,0 +1,27 @@ +

876. Middle of the Linked List

Easy


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5]
+Output: [3,4,5]
+Explanation: The middle node of the list is node 3.
+
+ +

Example 2:

+ +
Input: head = [1,2,3,4,5,6]
+Output: [4,5,6]
+Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 100].
  • +
  • 1 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/middle-of-the-linked-list/middle-of-the-linked-list.cpp b/middle-of-the-linked-list/middle-of-the-linked-list.cpp new file mode 100644 index 0000000..a0dac35 --- /dev/null +++ b/middle-of-the-linked-list/middle-of-the-linked-list.cpp @@ -0,0 +1,26 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* middleNode(ListNode* head) { + if(head == NULL || head->next == NULL)return head; + ListNode * slow = head; + ListNode * fast = head; + + while(fast != NULL && fast->next != NULL) + { + slow = slow->next; + fast = fast->next->next; + } + + return slow; + } +}; \ No newline at end of file diff --git a/min-cost-climbing-stairs/README.md b/min-cost-climbing-stairs/README.md new file mode 100644 index 0000000..12f03b4 --- /dev/null +++ b/min-cost-climbing-stairs/README.md @@ -0,0 +1,38 @@ +

746. Min Cost Climbing Stairs

Easy


You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.

+ +

You can either start from the step with index 0, or the step with index 1.

+ +

Return the minimum cost to reach the top of the floor.

+ +

 

+

Example 1:

+ +
Input: cost = [10,15,20]
+Output: 15
+Explanation: You will start at index 1.
+- Pay 15 and climb two steps to reach the top.
+The total cost is 15.
+
+ +

Example 2:

+ +
Input: cost = [1,100,1,1,1,100,1,1,100,1]
+Output: 6
+Explanation: You will start at index 0.
+- Pay 1 and climb two steps to reach index 2.
+- Pay 1 and climb two steps to reach index 4.
+- Pay 1 and climb two steps to reach index 6.
+- Pay 1 and climb one step to reach index 7.
+- Pay 1 and climb two steps to reach index 9.
+- Pay 1 and climb one step to reach the top.
+The total cost is 6.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= cost.length <= 1000
  • +
  • 0 <= cost[i] <= 999
  • +
+
\ No newline at end of file diff --git a/min-cost-climbing-stairs/min-cost-climbing-stairs.cpp b/min-cost-climbing-stairs/min-cost-climbing-stairs.cpp new file mode 100644 index 0000000..6f08ff4 --- /dev/null +++ b/min-cost-climbing-stairs/min-cost-climbing-stairs.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + int n = cost.size(); + vector dp(n); + dp[n-1] = cost[n-1]; + dp[n-2] = cost[n-2]; + if(n<=2)return min(dp[n-1],dp[n-2]); + for(int i=n-3;i>=0;i--) + { + dp[i] = min(dp[i+1],dp[i+2])+cost[i]; + } + // for(int i=0;i530. Minimum Absolute Difference in BST

Easy


Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

+ +

 

+

Example 1:

+ +
Input: root = [4,2,6,1,3]
+Output: 1
+
+ +

Example 2:

+ +
Input: root = [1,0,48,null,null,12,49]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 104].
  • +
  • 0 <= Node.val <= 105
  • +
+ +

 

+

Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/

+
\ No newline at end of file diff --git a/minimum-absolute-difference-in-bst/minimum-absolute-difference-in-bst.cpp b/minimum-absolute-difference-in-bst/minimum-absolute-difference-in-bst.cpp new file mode 100644 index 0000000..2b0d301 --- /dev/null +++ b/minimum-absolute-difference-in-bst/minimum-absolute-difference-in-bst.cpp @@ -0,0 +1,41 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int getMinimumDifference(TreeNode* root) { + if(root == NULL) + return -1; + int mini = INT_MAX; + int prev = INT_MIN; + stack s; + TreeNode * temp = root; + + while(temp || !s.empty()) + { + if(temp) + { + s.push(temp); + temp = temp->left; + } + else + { + temp = s.top(); + s.pop(); + if(prev != INT_MIN) + mini = min(mini,abs(prev-temp->val)); + prev = temp->val; + temp = temp->right; + } + } + return mini; + } +}; \ No newline at end of file diff --git a/minimum-cost-to-move-chips-to-the-same-position/README.md b/minimum-cost-to-move-chips-to-the-same-position/README.md new file mode 100644 index 0000000..03393dc --- /dev/null +++ b/minimum-cost-to-move-chips-to-the-same-position/README.md @@ -0,0 +1,42 @@ +

1217. Minimum Cost to Move Chips to The Same Position

Easy


We have n chips, where the position of the ith chip is position[i].

+ +

We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to:

+ +
    +
  • position[i] + 2 or position[i] - 2 with cost = 0.
  • +
  • position[i] + 1 or position[i] - 1 with cost = 1.
  • +
+ +

Return the minimum cost needed to move all the chips to the same position.

+ +

 

+

Example 1:

+ +
Input: position = [1,2,3]
+Output: 1
+Explanation: First step: Move the chip at position 3 to position 1 with cost = 0.
+Second step: Move the chip at position 2 to position 1 with cost = 1.
+Total cost is 1.
+
+ +

Example 2:

+ +
Input: position = [2,2,2,3,3]
+Output: 2
+Explanation: We can move the two chips at position  3 to position 2. Each move has cost = 1. The total cost = 2.
+
+ +

Example 3:

+ +
Input: position = [1,1000000000]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= position.length <= 100
  • +
  • 1 <= position[i] <= 10^9
  • +
+
\ No newline at end of file diff --git a/minimum-cost-to-move-chips-to-the-same-position/minimum-cost-to-move-chips-to-the-same-position.cpp b/minimum-cost-to-move-chips-to-the-same-position/minimum-cost-to-move-chips-to-the-same-position.cpp new file mode 100644 index 0000000..e258aec --- /dev/null +++ b/minimum-cost-to-move-chips-to-the-same-position/minimum-cost-to-move-chips-to-the-same-position.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int minCostToMoveChips(vector& P) { + int oddPos = 0, evenPos = 0; + for(int p : P) + p & 1 ? oddPos++ : evenPos++; + return min(oddPos, evenPos); + } +}; \ No newline at end of file diff --git a/minimum-depth-of-binary-tree/README.md b/minimum-depth-of-binary-tree/README.md new file mode 100644 index 0000000..449f6c6 --- /dev/null +++ b/minimum-depth-of-binary-tree/README.md @@ -0,0 +1,27 @@ +

111. Minimum Depth of Binary Tree

Easy


Given a binary tree, find its minimum depth.

+ +

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

+ +

Note: A leaf is a node with no children.

+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: 2
+
+ +

Example 2:

+ +
Input: root = [2,null,3,null,4,null,5,null,6]
+Output: 5
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 105].
  • +
  • -1000 <= Node.val <= 1000
  • +
+
\ No newline at end of file diff --git a/minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.cpp b/minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.cpp new file mode 100644 index 0000000..e7759b3 --- /dev/null +++ b/minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.cpp @@ -0,0 +1,44 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int minDepth(TreeNode* root) { + + if(root == NULL) + return 0; + queue q; + int ans = 0; + q.push(root); + while(q.size()) + { + int n = q.size(); + ans++; + + for(int i=0;ileft == NULL && front->right == NULL) + return ans; + + if(front->left) + q.push(front->left); + if(front->right) + q.push(front->right); + + } + + } + return ans; + } +}; \ No newline at end of file diff --git a/minimum-distance-between-bst-nodes/README.md b/minimum-distance-between-bst-nodes/README.md new file mode 100644 index 0000000..c32258d --- /dev/null +++ b/minimum-distance-between-bst-nodes/README.md @@ -0,0 +1,26 @@ +

783. Minimum Distance Between BST Nodes

Easy


Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.

+ +

 

+

Example 1:

+ +
Input: root = [4,2,6,1,3]
+Output: 1
+
+ +

Example 2:

+ +
Input: root = [1,0,48,null,null,12,49]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 100].
  • +
  • 0 <= Node.val <= 105
  • +
+ +

 

+

Note: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/

+
\ No newline at end of file diff --git a/minimum-distance-between-bst-nodes/minimum-distance-between-bst-nodes.cpp b/minimum-distance-between-bst-nodes/minimum-distance-between-bst-nodes.cpp new file mode 100644 index 0000000..66661f0 --- /dev/null +++ b/minimum-distance-between-bst-nodes/minimum-distance-between-bst-nodes.cpp @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int minDiffInBST(TreeNode* root) { + if(root == NULL) + return INT_MAX; + + int mini = INT_MAX; + stack s; + TreeNode * temp = NULL; + + while(root != NULL || !s.empty() ) + { + while(root != NULL) + { + s.push(root); + root = root->left; + } + root = s.top(); + s.pop(); + if(temp != NULL && abs(temp->val - root->val) < mini ) + mini = abs(temp->val - root->val) ; + temp = root; + root = root->right; + } + return mini; + } +}; \ No newline at end of file diff --git a/minimum-falling-path-sum/README.md b/minimum-falling-path-sum/README.md new file mode 100644 index 0000000..ab22a5d --- /dev/null +++ b/minimum-falling-path-sum/README.md @@ -0,0 +1,28 @@ +

931. Minimum Falling Path Sum

Medium


Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.

+ +

A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).

+ +

 

+

Example 1:

+ +
Input: matrix = [[2,1,3],[6,5,4],[7,8,9]]
+Output: 13
+Explanation: There are two falling paths with a minimum sum as shown.
+
+ +

Example 2:

+ +
Input: matrix = [[-19,57],[-40,-5]]
+Output: -59
+Explanation: The falling path with a minimum sum is shown.
+
+ +

 

+

Constraints:

+ +
    +
  • n == matrix.length == matrix[i].length
  • +
  • 1 <= n <= 100
  • +
  • -100 <= matrix[i][j] <= 100
  • +
+
\ No newline at end of file diff --git a/minimum-falling-path-sum/minimum-falling-path-sum.cpp b/minimum-falling-path-sum/minimum-falling-path-sum.cpp new file mode 100644 index 0000000..f9b6aab --- /dev/null +++ b/minimum-falling-path-sum/minimum-falling-path-sum.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int minFallingPathSum(vector>& A) { + vector> dp(A.size(),vector(A.size(),INT_MAX)); + for(int i=0;i0 and j310. Minimum Height Trees

Medium


A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.

+ +

Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))  are called minimum height trees (MHTs).

+ +

Return a list of all MHTs' root labels. You can return the answer in any order.

+ +

The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

+ +

 

+

Example 1:

+ +
Input: n = 4, edges = [[1,0],[1,2],[1,3]]
+Output: [1]
+Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
+
+ +

Example 2:

+ +
Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
+Output: [3,4]
+
+ +

Example 3:

+ +
Input: n = 1, edges = []
+Output: [0]
+
+ +

Example 4:

+ +
Input: n = 2, edges = [[0,1]]
+Output: [0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 2 * 104
  • +
  • edges.length == n - 1
  • +
  • 0 <= ai, bi < n
  • +
  • ai != bi
  • +
  • All the pairs (ai, bi) are distinct.
  • +
  • The given input is guaranteed to be a tree and there will be no repeated edges.
  • +
+
\ No newline at end of file diff --git a/minimum-number-of-buckets-required-to-collect-rainwater-from-houses/README.md b/minimum-number-of-buckets-required-to-collect-rainwater-from-houses/README.md new file mode 100644 index 0000000..8edddbd --- /dev/null +++ b/minimum-number-of-buckets-required-to-collect-rainwater-from-houses/README.md @@ -0,0 +1,64 @@ +

2086. Minimum Number of Buckets Required to Collect Rainwater from Houses

Medium


You are given a 0-indexed string street. Each character in street is either 'H' representing a house or '.' representing an empty space.

+ +

You can place buckets on the empty spaces to collect rainwater that falls from the adjacent houses. The rainwater from a house at index i is collected if a bucket is placed at index i - 1 and/or index i + 1. A single bucket, if placed adjacent to two houses, can collect the rainwater from both houses.

+ +

Return the minimum number of buckets needed so that for every house, there is at least one bucket collecting rainwater from it, or -1 if it is impossible.

+ +

 

+

Example 1:

+ +
Input: street = "H..H"
+Output: 2
+Explanation:
+We can put buckets at index 1 and index 2.
+"H..H" -> "HBBH" ('B' denotes where a bucket is placed).
+The house at index 0 has a bucket to its right, and the house at index 3 has a bucket to its left.
+Thus, for every house, there is at least one bucket collecting rainwater from it.
+
+ +

Example 2:

+ +
Input: street = ".H.H."
+Output: 1
+Explanation:
+We can put a bucket at index 2.
+".H.H." -> ".HBH." ('B' denotes where a bucket is placed).
+The house at index 1 has a bucket to its right, and the house at index 3 has a bucket to its left.
+Thus, for every house, there is at least one bucket collecting rainwater from it.
+
+ +

Example 3:

+ +
Input: street = ".HHH."
+Output: -1
+Explanation:
+There is no empty space to place a bucket to collect the rainwater from the house at index 2.
+Thus, it is impossible to collect the rainwater from all the houses.
+
+ +

Example 4:

+ +
Input: street = "H"
+Output: -1
+Explanation:
+There is no empty space to place a bucket.
+Thus, it is impossible to collect the rainwater from the house.
+
+ +

Example 5:

+ +
Input: street = "."
+Output: 0
+Explanation:
+There is no house to collect water from.
+Thus, 0 buckets are needed.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= street.length <= 105
  • +
  • street[i] is either'H' or '.'.
  • +
+
\ No newline at end of file diff --git a/minimum-number-of-steps-to-make-two-strings-anagram/README.md b/minimum-number-of-steps-to-make-two-strings-anagram/README.md new file mode 100644 index 0000000..91c6477 --- /dev/null +++ b/minimum-number-of-steps-to-make-two-strings-anagram/README.md @@ -0,0 +1,49 @@ +

1347. Minimum Number of Steps to Make Two Strings Anagram

Medium


Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character.

+ +

Return the minimum number of steps to make t an anagram of s.

+ +

An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.

+ +

 

+

Example 1:

+ +
Input: s = "bab", t = "aba"
+Output: 1
+Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.
+
+ +

Example 2:

+ +
Input: s = "leetcode", t = "practice"
+Output: 5
+Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.
+
+ +

Example 3:

+ +
Input: s = "anagram", t = "mangaar"
+Output: 0
+Explanation: "anagram" and "mangaar" are anagrams. 
+
+ +

Example 4:

+ +
Input: s = "xxyyzz", t = "xxyyzz"
+Output: 0
+
+ +

Example 5:

+ +
Input: s = "friend", t = "family"
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 50000
  • +
  • s.length == t.length
  • +
  • s and t contain lower-case English letters only.
  • +
+
\ No newline at end of file diff --git a/minimum-number-of-steps-to-make-two-strings-anagram/minimum-number-of-steps-to-make-two-strings-anagram.cpp b/minimum-number-of-steps-to-make-two-strings-anagram/minimum-number-of-steps-to-make-two-strings-anagram.cpp new file mode 100644 index 0000000..f8f65f2 --- /dev/null +++ b/minimum-number-of-steps-to-make-two-strings-anagram/minimum-number-of-steps-to-make-two-strings-anagram.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int minSteps(string s, string t) { + vector mp(26, 0); + for(int i = 0; i < s.size(); i++) { + mp[s[i] - 'a']++; + mp[t[i] - 'a']--; + } + int pos = 0, neg = 0; + for(auto it : mp) { + if(it > 0) pos += it; + if(it < 0) neg -= it; + } + return max(pos, neg); + } +}; \ No newline at end of file diff --git a/minimum-operations-to-make-array-equal/README.md b/minimum-operations-to-make-array-equal/README.md new file mode 100644 index 0000000..ba9efd6 --- /dev/null +++ b/minimum-operations-to-make-array-equal/README.md @@ -0,0 +1,28 @@ +

1551. Minimum Operations to Make Array Equal

Medium


You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e. 0 <= i < n).

+ +

In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e. perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.

+ +

Given an integer n, the length of the array. Return the minimum number of operations needed to make all the elements of arr equal.

+ +

 

+

Example 1:

+ +
Input: n = 3
+Output: 2
+Explanation: arr = [1, 3, 5]
+First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]
+In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].
+
+ +

Example 2:

+ +
Input: n = 6
+Output: 9
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 10^4
  • +
\ No newline at end of file diff --git a/minimum-operations-to-make-the-array-k-increasing/README.md b/minimum-operations-to-make-the-array-k-increasing/README.md new file mode 100644 index 0000000..45d9f1c --- /dev/null +++ b/minimum-operations-to-make-the-array-k-increasing/README.md @@ -0,0 +1,61 @@ +

2111. Minimum Operations to Make the Array K-Increasing

Hard


You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k.

+ +

The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1.

+ +
    +
  • For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: + +
      +
    • arr[0] <= arr[2] (4 <= 5)
    • +
    • arr[1] <= arr[3] (1 <= 2)
    • +
    • arr[2] <= arr[4] (5 <= 6)
    • +
    • arr[3] <= arr[5] (2 <= 2)
    • +
    +
  • +
  • However, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1]) or k = 3 (because arr[0] > arr[3]).
  • +
+ +

In one operation, you can choose an index i and change arr[i] into any positive integer.

+ +

Return the minimum number of operations required to make the array K-increasing for the given k.

+ +

 

+

Example 1:

+ +
Input: arr = [5,4,3,2,1], k = 1
+Output: 4
+Explanation:
+For k = 1, the resultant array has to be non-decreasing.
+Some of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations.
+It is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations.
+It can be shown that we cannot make the array K-increasing in less than 4 operations.
+
+ +

Example 2:

+ +
Input: arr = [4,1,5,2,6,2], k = 2
+Output: 0
+Explanation:
+This is the same example as the one in the problem description.
+Here, for every index i where 2 <= i <= 5, arr[i-2] <= arr[i].
+Since the given array is already K-increasing, we do not need to perform any operations.
+ +

Example 3:

+ +
Input: arr = [4,1,5,2,6,2], k = 3
+Output: 2
+Explanation:
+Indices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5.
+One of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5.
+The array will now be [4,1,5,4,6,5].
+Note that there can be other ways to make the array K-increasing, but none of them require less than 2 operations.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 105
  • +
  • 1 <= arr[i], k <= arr.length
  • +
+
\ No newline at end of file diff --git a/minimum-operations-to-make-the-array-k-increasing/minimum-operations-to-make-the-array-k-increasing.cpp b/minimum-operations-to-make-the-array-k-increasing/minimum-operations-to-make-the-array-k-increasing.cpp new file mode 100644 index 0000000..c244537 --- /dev/null +++ b/minimum-operations-to-make-the-array-k-increasing/minimum-operations-to-make-the-array-k-increasing.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int kIncreasing(vector& arr, int k) { + int ans = 0; + + for(int i=0;i lis; + for(int j=i;j64. Minimum Path Sum

Medium


Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.

+ +

Note: You can only move either down or right at any point in time.

+ +

 

+

Example 1:

+ +
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
+Output: 7
+Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
+
+ +

Example 2:

+ +
Input: grid = [[1,2,3],[4,5,6]]
+Output: 12
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • 0 <= grid[i][j] <= 100
  • +
+
\ No newline at end of file diff --git a/minimum-path-sum/minimum-path-sum.cpp b/minimum-path-sum/minimum-path-sum.cpp new file mode 100644 index 0000000..b553be7 --- /dev/null +++ b/minimum-path-sum/minimum-path-sum.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int minPathSum(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + vector> dp(m, vector (n)); + dp[0][0] = grid[0][0]; + for(int i=0;i0) + { + dp[i][j] = dp[i-1][j]+grid[i][j]; + } + else if(j>0 && i==0) + { + dp[i][j] = dp[i][j-1] + grid[i][j]; + } + else if(i!=0 && j!=0) + { + dp[i][j] = min(dp[i-1][j],dp[i][j-1])+grid[i][j]; + } + } + } + return dp[m-1][n-1]; + + } +}; \ No newline at end of file diff --git a/minimum-size-subarray-sum/README.md b/minimum-size-subarray-sum/README.md new file mode 100644 index 0000000..ea315ea --- /dev/null +++ b/minimum-size-subarray-sum/README.md @@ -0,0 +1,33 @@ +

209. Minimum Size Subarray Sum

Medium


Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.

+ +

 

+

Example 1:

+ +
Input: target = 7, nums = [2,3,1,2,4,3]
+Output: 2
+Explanation: The subarray [4,3] has the minimal length under the problem constraint.
+
+ +

Example 2:

+ +
Input: target = 4, nums = [1,4,4]
+Output: 1
+
+ +

Example 3:

+ +
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= target <= 109
  • +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 105
  • +
+ +

 

+Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)).
\ No newline at end of file diff --git a/minimum-size-subarray-sum/minimum-size-subarray-sum.cpp b/minimum-size-subarray-sum/minimum-size-subarray-sum.cpp new file mode 100644 index 0000000..28da110 --- /dev/null +++ b/minimum-size-subarray-sum/minimum-size-subarray-sum.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int minSubArrayLen(int target, vector& nums) { + + int left= 0; + int right = 0; + int minlen = INT_MAX; + int sum = 0; + + while(right=target) + { + minlen=min(minlen,right - left); + sum-=nums[left++]; + } + + } + return minlen == INT_MAX ? 0 : minlen; + + } +}; \ No newline at end of file diff --git a/minimum-value-to-get-positive-step-by-step-sum/README.md b/minimum-value-to-get-positive-step-by-step-sum/README.md new file mode 100644 index 0000000..faa7d8f --- /dev/null +++ b/minimum-value-to-get-positive-step-by-step-sum/README.md @@ -0,0 +1,41 @@ +

1413. Minimum Value to Get Positive Step by Step Sum

Easy


Given an array of integers nums, you start with an initial positive value startValue.

+ +

In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).

+ +

Return the minimum positive value of startValue such that the step by step sum is never less than 1.

+ +

 

+

Example 1:

+ +
Input: nums = [-3,2,-3,4,2]
+Output: 5
+Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
+                step by step sum
+                startValue = 4 | startValue = 5 | nums
+                  (4 -3 ) = 1  | (5 -3 ) = 2    |  -3
+                  (1 +2 ) = 3  | (2 +2 ) = 4    |   2
+                  (3 -3 ) = 0  | (4 -3 ) = 1    |  -3
+                  (0 +4 ) = 4  | (1 +4 ) = 5    |   4
+                  (4 +2 ) = 6  | (5 +2 ) = 7    |   2
+
+ +

Example 2:

+ +
Input: nums = [1,2]
+Output: 1
+Explanation: Minimum start value should be positive. 
+
+ +

Example 3:

+ +
Input: nums = [1,-2,-3]
+Output: 5
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • -100 <= nums[i] <= 100
  • +
\ No newline at end of file diff --git a/minimum-value-to-get-positive-step-by-step-sum/minimum-value-to-get-positive-step-by-step-sum.cpp b/minimum-value-to-get-positive-step-by-step-sum/minimum-value-to-get-positive-step-by-step-sum.cpp new file mode 100644 index 0000000..7d84a85 --- /dev/null +++ b/minimum-value-to-get-positive-step-by-step-sum/minimum-value-to-get-positive-step-by-step-sum.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int minStartValue(vector& nums) { + int ans = 0 , minAns=0; + for(int x : nums){ + ans+= x; + if(ans < minAns) + minAns = ans; + } + return -minAns+1; + } +}; \ No newline at end of file diff --git a/minimum-window-substring/README.md b/minimum-window-substring/README.md new file mode 100644 index 0000000..4bbfe2b --- /dev/null +++ b/minimum-window-substring/README.md @@ -0,0 +1,41 @@ +

76. Minimum Window Substring

Hard


Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".

+ +

The testcases will be generated such that the answer is unique.

+ +

A substring is a contiguous sequence of characters within the string.

+ +

 

+

Example 1:

+ +
Input: s = "ADOBECODEBANC", t = "ABC"
+Output: "BANC"
+Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
+
+ +

Example 2:

+ +
Input: s = "a", t = "a"
+Output: "a"
+Explanation: The entire string s is the minimum window.
+
+ +

Example 3:

+ +
Input: s = "a", t = "aa"
+Output: ""
+Explanation: Both 'a's from t must be included in the window.
+Since the largest window of s only has one 'a', return empty string.
+
+ +

 

+

Constraints:

+ +
    +
  • m == s.length
  • +
  • n == t.length
  • +
  • 1 <= m, n <= 105
  • +
  • s and t consist of uppercase and lowercase English letters.
  • +
+ +

 

+Follow up: Could you find an algorithm that runs in O(m + n) time?
\ No newline at end of file diff --git a/minimum-window-substring/minimum-window-substring.cpp b/minimum-window-substring/minimum-window-substring.cpp new file mode 100644 index 0000000..fd08628 --- /dev/null +++ b/minimum-window-substring/minimum-window-substring.cpp @@ -0,0 +1,52 @@ +// Including climits, which allows for usage of INT_MIN constant in C++ +#include +class Solution { + public: + string minWindow(string searchString, string t) { + + // Our hashtable of characters filled with occurences in our string + vector table(128, 0); + + // Store the frequency of characters in string t + for(auto character : t) { + table[character]++; + } + + int start = 0; + int end = 0; + int counter = t.size(); + int startMin = 0; + int minimum = INT_MAX; + + // Here we use the 2 pointer approach + while(end < searchString.size()) { + if(table[searchString[end]] > 0) { + counter--; + } + + table[searchString[end]]--; + end++; + + while(counter == 0) { + if(end - start < minimum) { + startMin = start; + minimum = end - start; + } + + table[searchString[start]]++; + + if(table[searchString[start]] > 0) { + counter++; + } + start++; + } + } + + // Case when no substring satisfies + if(minimum == INT_MAX) { + return ""; + } + + return searchString.substr(startMin, minimum); + } +}; diff --git a/move-zeroes/README.md b/move-zeroes/README.md new file mode 100644 index 0000000..a9f88f3 --- /dev/null +++ b/move-zeroes/README.md @@ -0,0 +1,22 @@ +

283. Move Zeroes

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [0,1,0,3,12]
+Output: [1,3,12,0,0]
+

Example 2:

+
Input: nums = [0]
+Output: [0]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+ +

 

+Follow up: Could you minimize the total number of operations done?
\ No newline at end of file diff --git a/move-zeroes/move-zeroes.cpp b/move-zeroes/move-zeroes.cpp new file mode 100644 index 0000000..5090aa3 --- /dev/null +++ b/move-zeroes/move-zeroes.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + void moveZeroes(vector& nums) { + int counter = 0; + int j = 0; + for(int i=0;i43. Multiply Strings

Medium


Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

+ +

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

+ +

 

+

Example 1:

+
Input: num1 = "2", num2 = "3"
+Output: "6"
+

Example 2:

+
Input: num1 = "123", num2 = "456"
+Output: "56088"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= num1.length, num2.length <= 200
  • +
  • num1 and num2 consist of digits only.
  • +
  • Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  • +
+
\ No newline at end of file diff --git a/multiply-strings/multiply-strings.cpp b/multiply-strings/multiply-strings.cpp new file mode 100644 index 0000000..5dadeee --- /dev/null +++ b/multiply-strings/multiply-strings.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + string multiply(string num1, string num2) { + if (num1 == "0" || num2 == "0") return "0"; + + vector res(num1.size()+num2.size(), 0); + + for (int i = num1.size()-1; i >= 0; i--) { + for (int j = num2.size()-1; j >= 0; j--) { + res[i + j + 1] += (num1[i]-'0') * (num2[j]-'0'); + res[i + j] += res[i + j + 1] / 10; + res[i + j + 1] %= 10; + } + } + + int i = 0; + string ans = ""; + while (res[i] == 0) i++; + while (i < res.size()) ans += to_string(res[i++]); + + return ans; + } +}; \ No newline at end of file diff --git a/n-ary-tree-level-order-traversal/README.md b/n-ary-tree-level-order-traversal/README.md new file mode 100644 index 0000000..ed3de5a --- /dev/null +++ b/n-ary-tree-level-order-traversal/README.md @@ -0,0 +1,29 @@ +

429. N-ary Tree Level Order Traversal

Medium


Given an n-ary tree, return the level order traversal of its nodes' values.

+ +

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

+ +

 

+

Example 1:

+ +

+ +
Input: root = [1,null,3,2,4,null,5,6]
+Output: [[1],[3,2,4],[5,6]]
+
+ +

Example 2:

+ +

+ +
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
+Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
+
+ +

 

+

Constraints:

+ +
    +
  • The height of the n-ary tree is less than or equal to 1000
  • +
  • The total number of nodes is between [0, 104]
  • +
+
\ No newline at end of file diff --git a/n-ary-tree-level-order-traversal/n-ary-tree-level-order-traversal.cpp b/n-ary-tree-level-order-traversal/n-ary-tree-level-order-traversal.cpp new file mode 100644 index 0000000..74488a2 --- /dev/null +++ b/n-ary-tree-level-order-traversal/n-ary-tree-level-order-traversal.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + void rec(Node* root, int level) { + if (!root) return; + if (level == res.size()) res.push_back({}); + res[level].push_back(root->val); + for (auto child : root->children) + rec(child, level+1); + } + + vector> levelOrder(Node* root) { + rec(root, 0); + return res; + } + +private: + vector> res; +}; \ No newline at end of file diff --git a/n-ary-tree-preorder-traversal/README.md b/n-ary-tree-preorder-traversal/README.md new file mode 100644 index 0000000..d20897a --- /dev/null +++ b/n-ary-tree-preorder-traversal/README.md @@ -0,0 +1,33 @@ +

589. N-ary Tree Preorder Traversal

Easy


Given the root of an n-ary tree, return the preorder traversal of its nodes' values.

+ +

Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)

+ +

 

+

Example 1:

+ +

+ +
Input: root = [1,null,3,2,4,null,5,6]
+Output: [1,3,5,6,2,4]
+
+ +

Example 2:

+ +

+ +
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
+Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • 0 <= Node.val <= 104
  • +
  • The height of the n-ary tree is less than or equal to 1000.
  • +
+ +

 

+

Follow up: Recursive solution is trivial, could you do it iteratively?

+
\ No newline at end of file diff --git a/n-ary-tree-preorder-traversal/n-ary-tree-preorder-traversal.cpp b/n-ary-tree-preorder-traversal/n-ary-tree-preorder-traversal.cpp new file mode 100644 index 0000000..cd006a0 --- /dev/null +++ b/n-ary-tree-preorder-traversal/n-ary-tree-preorder-traversal.cpp @@ -0,0 +1,41 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ +#include +using namespace std; + +class Solution { +public: + vector preorder(Node* root) { + if(root == NULL) + return {}; + + vector ans; + for(int i=0;ichildren.size();i++) + { + vector an = preorder(root->children[i]); + ans.insert(ans.end(),an.begin() , an.end()); + } + + ans.insert(ans.begin(),root->val); + + return ans; + + } +}; \ No newline at end of file diff --git a/n-th-tribonacci-number/README.md b/n-th-tribonacci-number/README.md new file mode 100644 index 0000000..514ab2e --- /dev/null +++ b/n-th-tribonacci-number/README.md @@ -0,0 +1,29 @@ +

1137. N-th Tribonacci Number

Easy


The Tribonacci sequence Tn is defined as follows: 

+ +

T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.

+ +

Given n, return the value of Tn.

+ +

 

+

Example 1:

+ +
Input: n = 4
+Output: 4
+Explanation:
+T_3 = 0 + 1 + 1 = 2
+T_4 = 1 + 1 + 2 = 4
+
+ +

Example 2:

+ +
Input: n = 25
+Output: 1389537
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 37
  • +
  • The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.
  • +
\ No newline at end of file diff --git a/n-th-tribonacci-number/n-th-tribonacci-number.cpp b/n-th-tribonacci-number/n-th-tribonacci-number.cpp new file mode 100644 index 0000000..25aa56a --- /dev/null +++ b/n-th-tribonacci-number/n-th-tribonacci-number.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int tribonacci(int n) { + vector a; + a.push_back(0); + a.push_back(1); + a.push_back(1); + for(int i=3;i<=n;i++) + { + a.push_back(a[i-1]+a[i-2]+a[i-3]); + } + return a[n]; + } +}; \ No newline at end of file diff --git a/nCr mod M _ Part 1 - GFG/README.md b/nCr mod M _ Part 1 - GFG/README.md new file mode 100644 index 0000000..5b6a635 --- /dev/null +++ b/nCr mod M _ Part 1 - GFG/README.md @@ -0,0 +1,34 @@ +# nCr mod M | Part 1 +## Hard +
+

Given 2 integers n and r. You task is to calculate nCr%1000003.

+ +

Example 1:

+ +
Input: n = 5, r = 2
+Output: 10
+Explanation: 5C2 = 5! / (2! * 3!) = 10
+
+ +

Example 2:

+ +
Input: n = 3, r = 2
+Output: 3
+Explanation: 3C2 = 3! / (2! * 1!) = 3
+
+ +

 

+ +

Your Task:
+You don't need to read or print anything. Your task is to complete the function nCr() which takes n and r as input parameter and returns nCr modulo 1000003.

+ +

Expected Time Complexity: O(m * logmn) where m = 1000003
+Expected Space Complexity: O(m)

+ +

Constraints:
+1 <= n <= r <= 1016

+

+
\ No newline at end of file diff --git a/nCr mod M _ Part 1 - GFG/n-cr-mod-m-part-1.cpp b/nCr mod M _ Part 1 - GFG/n-cr-mod-m-part-1.cpp new file mode 100644 index 0000000..3ebc2ea --- /dev/null +++ b/nCr mod M _ Part 1 - GFG/n-cr-mod-m-part-1.cpp @@ -0,0 +1,69 @@ +// { Driver Code Starts + + +#include +using namespace std; + + // } Driver Code Ends + +class Solution { +private: + int mod = 1000003; + vector fac; + vector fac_inv; + int power(int n, int m) { + int res = 1; + n %= mod; + while(m > 0) { + if(m & 1) { + res = (1LL * res * n)%mod; + m--; + } else { + n = (1LL * n * n)%mod; + m /= 2; + } + } + return res%mod; + } + int fermat(int n, int r) { + n %= mod, r %= mod; + if(n < r) return 0; + if(r == 0 || n == r) return 1; + return (1LL * fac[n] * fac_inv[r] * fac_inv[n-r])%mod; + } + long long lucas(long long n,long long r){ + if(r == 0) return 1; + int ni = n % mod, ri = r % mod; + return (lucas(n/mod,r/mod) * fermat(ni,ri)) % mod; + } +public: + Solution() { + fac.resize(mod); + fac_inv.resize(mod); + + fac[0] = 1; + for(int i=1; i0; i--) + fac_inv[i] = (1LL * fac_inv[i+1] * (i+1))%mod; + } + int nCr(long long n, long long r) { + return lucas(n, r); + } +}; + +// { Driver Code Starts. +int main(){ + int tc; + cin >> tc; + while(tc--){ + long long n, r; + cin >> n >> r; + Solution obj; + int ans = obj.nCr(n, r); + cout << ans << "\n"; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/next-greater-element-i/README.md b/next-greater-element-i/README.md new file mode 100644 index 0000000..00d3d7f --- /dev/null +++ b/next-greater-element-i/README.md @@ -0,0 +1,40 @@ +

496. Next Greater Element I

Easy


The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.

+ +

You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.

+ +

For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.

+ +

Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.

+ +

 

+

Example 1:

+ +
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
+Output: [-1,3,-1]
+Explanation: The next greater element for each value of nums1 is as follows:
+- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
+- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.
+- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
+
+ +

Example 2:

+ +
Input: nums1 = [2,4], nums2 = [1,2,3,4]
+Output: [3,-1]
+Explanation: The next greater element for each value of nums1 is as follows:
+- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.
+- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length <= nums2.length <= 1000
  • +
  • 0 <= nums1[i], nums2[i] <= 104
  • +
  • All integers in nums1 and nums2 are unique.
  • +
  • All the integers of nums1 also appear in nums2.
  • +
+ +

 

+Follow up: Could you find an O(nums1.length + nums2.length) solution?
\ No newline at end of file diff --git a/next-greater-element-i/next-greater-element-i.cpp b/next-greater-element-i/next-greater-element-i.cpp new file mode 100644 index 0000000..370e12b --- /dev/null +++ b/next-greater-element-i/next-greater-element-i.cpp @@ -0,0 +1,51 @@ +class Solution { +public: + vector nextGreaterElement(vector& nums1, vector& nums2) { + + stack s; + map m; + vector res(nums1.size(),-1); + + for(int i=0;i s.top()) + { + m[s.top()] = ele; + s.pop(); + } + s.push(ele); + + } + + for(int i=0;i503. Next Greater Element II

Medium


Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.

+ +

The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,1]
+Output: [2,-1,2]
+Explanation: The first 1's next greater number is 2; 
+The number 2 can't find next greater number. 
+The second 1's next greater number needs to search circularly, which is also 2.
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,4,3]
+Output: [2,3,4,-1,4]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -109 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/next-greater-element-ii/next-greater-element-ii.cpp b/next-greater-element-ii/next-greater-element-ii.cpp new file mode 100644 index 0000000..c771e41 --- /dev/null +++ b/next-greater-element-ii/next-greater-element-ii.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector nextGreaterElements(vector& nums) { + + vector temp(nums); + + vector res(nums.size(),-1); + + for(int i=0;i nums[i]) + { + res[i] = temp[j]; + break; + } + } + } + + return res; + + } +}; \ No newline at end of file diff --git a/next-permutation/README.md b/next-permutation/README.md new file mode 100644 index 0000000..6219648 --- /dev/null +++ b/next-permutation/README.md @@ -0,0 +1,28 @@ +

31. Next Permutation

Medium


Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

+ +

If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).

+ +

The replacement must be in place and use only constant extra memory.

+ +

 

+

Example 1:

+
Input: nums = [1,2,3]
+Output: [1,3,2]
+

Example 2:

+
Input: nums = [3,2,1]
+Output: [1,2,3]
+

Example 3:

+
Input: nums = [1,1,5]
+Output: [1,5,1]
+

Example 4:

+
Input: nums = [1]
+Output: [1]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 0 <= nums[i] <= 100
  • +
+
\ No newline at end of file diff --git a/next-permutation/next-permutation.cpp b/next-permutation/next-permutation.cpp new file mode 100644 index 0000000..fec61a2 --- /dev/null +++ b/next-permutation/next-permutation.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + void nextPermutation(vector& nums) { + int index = 0; + + for(int i=nums.size()-1;i>=1;i--) + { + if(nums[i] > nums[i-1]) + { + index = i; + break; + } + } + + if(index) + { + int index2 = index; + for(int i=nums.size()-1;i>=index;i--) + { + if(nums[i]>nums[index-1] && nums[i]<=nums[index]) + { + index2 = i; + break; + } + } + swap(nums[index-1],nums[index2]); + sort(nums.begin()+index,nums.end()); + + } + else + { + sort(nums.begin(),nums.end()); + + } + } +}; \ No newline at end of file diff --git a/number-of-1-bits/README.md b/number-of-1-bits/README.md new file mode 100644 index 0000000..5082363 --- /dev/null +++ b/number-of-1-bits/README.md @@ -0,0 +1,40 @@ +

191. Number of 1 Bits

Easy


Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

+ +

Note:

+ +
    +
  • Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
  • +
  • In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.
  • +
+ +

 

+

Example 1:

+ +
Input: n = 00000000000000000000000000001011
+Output: 3
+Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
+
+ +

Example 2:

+ +
Input: n = 00000000000000000000000010000000
+Output: 1
+Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
+
+ +

Example 3:

+ +
Input: n = 11111111111111111111111111111101
+Output: 31
+Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
+
+ +

 

+

Constraints:

+ +
    +
  • The input must be a binary string of length 32.
  • +
+ +

 

+Follow up: If this function is called many times, how would you optimize it?
\ No newline at end of file diff --git a/number-of-islands/README.md b/number-of-islands/README.md new file mode 100644 index 0000000..bb3597e --- /dev/null +++ b/number-of-islands/README.md @@ -0,0 +1,37 @@ +

200. Number of Islands

Medium


Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

+ +

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

+ +

 

+

Example 1:

+ +
Input: grid = [
+  ["1","1","1","1","0"],
+  ["1","1","0","1","0"],
+  ["1","1","0","0","0"],
+  ["0","0","0","0","0"]
+]
+Output: 1
+
+ +

Example 2:

+ +
Input: grid = [
+  ["1","1","0","0","0"],
+  ["1","1","0","0","0"],
+  ["0","0","1","0","0"],
+  ["0","0","0","1","1"]
+]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 300
  • +
  • grid[i][j] is '0' or '1'.
  • +
+
\ No newline at end of file diff --git a/number-of-islands/number-of-islands.cpp b/number-of-islands/number-of-islands.cpp new file mode 100644 index 0000000..2a345d2 --- /dev/null +++ b/number-of-islands/number-of-islands.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + + void dfs(vector>& grid,int r,int c) + { + if(r>=0 && c>=0 && r>& grid) { + int count = 0; + + for(int i=0;i547. Number of Provinces

Medium


There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.

+ +

A province is a group of directly or indirectly connected cities and no other cities outside of the group.

+ +

You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.

+ +

Return the total number of provinces.

+ +

 

+

Example 1:

+ +
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
+Output: 2
+
+ +

Example 2:

+ +
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 200
  • +
  • n == isConnected.length
  • +
  • n == isConnected[i].length
  • +
  • isConnected[i][j] is 1 or 0.
  • +
  • isConnected[i][i] == 1
  • +
  • isConnected[i][j] == isConnected[j][i]
  • +
+
\ No newline at end of file diff --git a/number-of-provinces/number-of-provinces.cpp b/number-of-provinces/number-of-provinces.cpp new file mode 100644 index 0000000..1e85ef4 --- /dev/null +++ b/number-of-provinces/number-of-provinces.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + + + void dfs(int source,vector>& isConnected,int n,bool * visited) + { + visited[source] = true; + for(int i = 0;i>& isConnected) { + int n = isConnected.size(); + bool * visited = new bool[n+1]; + int count = 0; + for(int i=0;i<=n;i++) + visited[i] = false; + + for(int i=1;i<=n ;i++) + { + if(!visited[i]) + { + dfs(i,isConnected,n,visited); + count++; + } + } + return count; + } +}; \ No newline at end of file diff --git a/number-of-valid-words-for-each-puzzle/README.md b/number-of-valid-words-for-each-puzzle/README.md new file mode 100644 index 0000000..e0339e6 --- /dev/null +++ b/number-of-valid-words-for-each-puzzle/README.md @@ -0,0 +1,43 @@ +

1178. Number of Valid Words for Each Puzzle

Hard


With respect to a given puzzle string, a word is valid if both the following conditions are satisfied: +
    +
  • word contains the first letter of puzzle.
  • +
  • For each letter in word, that letter is in puzzle. +
      +
    • For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", and "baggage", while
    • +
    • invalid words are "beefed" (does not include 'a') and "based" (includes 's' which is not in the puzzle).
    • +
    +
  • +
+Return an array answer, where answer[i] is the number of words in the given word list words that is valid with respect to the puzzle puzzles[i]. +

 

+

Example 1:

+ +
Input: words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
+Output: [1,1,3,2,4,0]
+Explanation: 
+1 valid word for "aboveyz" : "aaaa" 
+1 valid word for "abrodyz" : "aaaa"
+3 valid words for "abslute" : "aaaa", "asas", "able"
+2 valid words for "absoryz" : "aaaa", "asas"
+4 valid words for "actresz" : "aaaa", "asas", "actt", "access"
+There are no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'.
+
+ +

Example 2:

+ +
Input: words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"]
+Output: [0,1,3,2,0]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 105
  • +
  • 4 <= words[i].length <= 50
  • +
  • 1 <= puzzles.length <= 104
  • +
  • puzzles[i].length == 7
  • +
  • words[i] and puzzles[i] consist of lowercase English letters.
  • +
  • Each puzzles[i] does not contain repeated characters.
  • +
+
\ No newline at end of file diff --git a/odd-even-linked-list/README.md b/odd-even-linked-list/README.md new file mode 100644 index 0000000..734ab69 --- /dev/null +++ b/odd-even-linked-list/README.md @@ -0,0 +1,30 @@ +

328. Odd Even Linked List

Medium


Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

+ +

The first node is considered odd, and the second node is even, and so on.

+ +

Note that the relative order inside both the even and odd groups should remain as it was in the input.

+ +

You must solve the problem in O(1) extra space complexity and O(n) time complexity.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5]
+Output: [1,3,5,2,4]
+
+ +

Example 2:

+ +
Input: head = [2,1,3,5,6,4,7]
+Output: [2,3,6,7,1,5,4]
+
+ +

 

+

Constraints:

+ +
    +
  • n == number of nodes in the linked list
  • +
  • 0 <= n <= 104
  • +
  • -106 <= Node.val <= 106
  • +
+
\ No newline at end of file diff --git a/odd-even-linked-list/odd-even-linked-list.cpp b/odd-even-linked-list/odd-even-linked-list.cpp new file mode 100644 index 0000000..2c1dbaa --- /dev/null +++ b/odd-even-linked-list/odd-even-linked-list.cpp @@ -0,0 +1,41 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* oddEvenList(ListNode* head) { + + if(head == NULL || head->next == NULL)return head; + ListNode* f = head; + ListNode * g= f; + ListNode* s = head->next; + ListNode * d = s; + + while(f &&f->next && s && s->next) + { + if(f->next && f->next->next) + { + f->next = f->next->next; + f = f->next; + // cout<<"a"<next) + { + s->next = s->next->next; + s = s->next; + // cout<<"v"<next = d; + return g; + + } +}; \ No newline at end of file diff --git a/pairs-of-songs-with-total-durations-divisible-by-60/README.md b/pairs-of-songs-with-total-durations-divisible-by-60/README.md new file mode 100644 index 0000000..05ff88a --- /dev/null +++ b/pairs-of-songs-with-total-durations-divisible-by-60/README.md @@ -0,0 +1,30 @@ +

1010. Pairs of Songs With Total Durations Divisible by 60

Medium


You are given a list of songs where the ith song has a duration of time[i] seconds.

+ +

Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.

+ +

 

+

Example 1:

+ +
Input: time = [30,20,150,100,40]
+Output: 3
+Explanation: Three pairs have a total duration divisible by 60:
+(time[0] = 30, time[2] = 150): total duration 180
+(time[1] = 20, time[3] = 100): total duration 120
+(time[1] = 20, time[4] = 40): total duration 60
+
+ +

Example 2:

+ +
Input: time = [60,60,60]
+Output: 3
+Explanation: All three pairs have a total duration of 120, which is divisible by 60.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= time.length <= 6 * 104
  • +
  • 1 <= time[i] <= 500
  • +
+
\ No newline at end of file diff --git a/pairs-of-songs-with-total-durations-divisible-by-60/pairs-of-songs-with-total-durations-divisible-by-60.cpp b/pairs-of-songs-with-total-durations-divisible-by-60/pairs-of-songs-with-total-durations-divisible-by-60.cpp new file mode 100644 index 0000000..8648ced --- /dev/null +++ b/pairs-of-songs-with-total-durations-divisible-by-60/pairs-of-songs-with-total-durations-divisible-by-60.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int numPairsDivisibleBy60(vector& t) { + vector v(60); + int ans =0; + for(int i=0;i234. Palindrome Linked List

Easy


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

+ +

 

+

Example 1:

+ +
Input: head = [1,2,2,1]
+Output: true
+
+ +

Example 2:

+ +
Input: head = [1,2]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 105].
  • +
  • 0 <= Node.val <= 9
  • +
+ +

 

+Follow up: Could you do it in O(n) time and O(1) space?
\ No newline at end of file diff --git a/palindrome-linked-list/palindrome-linked-list.cpp b/palindrome-linked-list/palindrome-linked-list.cpp new file mode 100644 index 0000000..ef84d80 --- /dev/null +++ b/palindrome-linked-list/palindrome-linked-list.cpp @@ -0,0 +1,60 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode * reverse(ListNode * head) + { + if(head == NULL || head->next == NULL) + return head; + ListNode * curr = head; + ListNode * pre = NULL; + ListNode * nex = NULL; + + while(curr != NULL) + { + nex = curr->next; + curr->next = pre; + pre = curr; + curr = nex; + } + + return pre; + } + bool isPalindrome(ListNode* head) { + + if(head == NULL || head->next == NULL) + return true; + ListNode * slow = head; + ListNode * fast = head; + // cout<val<next != NULL && fast->next->next != NULL) + { + slow = slow->next; + fast = fast->next->next; + } + // cout<val<next = reverse(slow->next); + slow = slow->next; + //cout<val<val<<" a "<val<<" d "<val != start->val) + return false; + + slow = slow->next; + start = start->next; + } + return true; + } +}; \ No newline at end of file diff --git a/palindrome-partitioning-ii/README.md b/palindrome-partitioning-ii/README.md new file mode 100644 index 0000000..71e01de --- /dev/null +++ b/palindrome-partitioning-ii/README.md @@ -0,0 +1,32 @@ +

132. Palindrome Partitioning II

Hard


Given a string s, partition s such that every substring of the partition is a palindrome.

+ +

Return the minimum cuts needed for a palindrome partitioning of s.

+ +

 

+

Example 1:

+ +
Input: s = "aab"
+Output: 1
+Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
+
+ +

Example 2:

+ +
Input: s = "a"
+Output: 0
+
+ +

Example 3:

+ +
Input: s = "ab"
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 2000
  • +
  • s consists of lower-case English letters only.
  • +
+
\ No newline at end of file diff --git a/partition-array-for-maximum-sum/README.md b/partition-array-for-maximum-sum/README.md new file mode 100644 index 0000000..f00e8d1 --- /dev/null +++ b/partition-array-for-maximum-sum/README.md @@ -0,0 +1,33 @@ +

1043. Partition Array for Maximum Sum

Medium


Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.

+ +

Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.

+ +

 

+

Example 1:

+ +
Input: arr = [1,15,7,9,2,5,10], k = 3
+Output: 84
+Explanation: arr becomes [15,15,15,9,10,10,10]
+
+ +

Example 2:

+ +
Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
+Output: 83
+
+ +

Example 3:

+ +
Input: arr = [1], k = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 500
  • +
  • 0 <= arr[i] <= 109
  • +
  • 1 <= k <= arr.length
  • +
+
\ No newline at end of file diff --git a/partition-array-for-maximum-sum/partition-array-for-maximum-sum.cpp b/partition-array-for-maximum-sum/partition-array-for-maximum-sum.cpp new file mode 100644 index 0000000..710bbf3 --- /dev/null +++ b/partition-array-for-maximum-sum/partition-array-for-maximum-sum.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int dp[501] = {}; +int maxSumAfterPartitioning(vector& A, int K, int pos = 0, int res = 0) { + if (pos < A.size() && dp[pos] != 0) return dp[pos]; + for (int i = 1, mv = 0; i <= K && pos + i <= A.size(); ++i) { + mv = max(mv, A[pos + i - 1]); + res = max(res, mv * i + maxSumAfterPartitioning(A, K, pos + i)); + } + return dp[pos] = res; +} +}; \ No newline at end of file diff --git a/partition-array-into-disjoint-intervals/README.md b/partition-array-into-disjoint-intervals/README.md new file mode 100644 index 0000000..56de9af --- /dev/null +++ b/partition-array-into-disjoint-intervals/README.md @@ -0,0 +1,42 @@ +

915. Partition Array into Disjoint Intervals

Medium


Given an array nums, partition it into two (contiguous) subarrays left and right so that:

+ +
    +
  • Every element in left is less than or equal to every element in right.
  • +
  • left and right are non-empty.
  • +
  • left has the smallest possible size.
  • +
+ +

Return the length of left after such a partitioning.  It is guaranteed that such a partitioning exists.

+ +

 

+ +

Example 1:

+ +
Input: nums = [5,0,3,8,6]
+Output: 3
+Explanation: left = [5,0,3], right = [8,6]
+
+ +
+

Example 2:

+ +
Input: nums = [1,1,1,0,6,12]
+Output: 4
+Explanation: left = [1,1,1,0], right = [6,12]
+
+ +

 

+
+ +

Note:

+ +
    +
  1. 2 <= nums.length <= 30000
  2. +
  3. 0 <= nums[i] <= 106
  4. +
  5. It is guaranteed there is at least one way to partition nums as described.
  6. +
+ +
+
 
+
+
\ No newline at end of file diff --git a/partition-array-into-disjoint-intervals/partition-array-into-disjoint-intervals.cpp b/partition-array-into-disjoint-intervals/partition-array-into-disjoint-intervals.cpp new file mode 100644 index 0000000..d2f058e --- /dev/null +++ b/partition-array-into-disjoint-intervals/partition-array-into-disjoint-intervals.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int partitionDisjoint(vector& A) { + vector mx(A.size()), mi(A.size()); + mx[0]=A[0]; mi[A.size()-1]=A.back(); + for(int i=1; i=0; i--) + mi[i]=min(A[i], mi[i+1]); + int i; + for(i=0; i119. Pascal's Triangle II

Easy


Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.

+ +

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

+ +

 

+

Example 1:

+
Input: rowIndex = 3
+Output: [1,3,3,1]
+

Example 2:

+
Input: rowIndex = 0
+Output: [1]
+

Example 3:

+
Input: rowIndex = 1
+Output: [1,1]
+
+

 

+

Constraints:

+ +
    +
  • 0 <= rowIndex <= 33
  • +
+ +

 

+

Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?

+
\ No newline at end of file diff --git a/pascals-triangle/README.md b/pascals-triangle/README.md new file mode 100644 index 0000000..a1948e8 --- /dev/null +++ b/pascals-triangle/README.md @@ -0,0 +1,19 @@ +

118. Pascal's Triangle

Easy


Given an integer numRows, return the first numRows of Pascal's triangle.

+ +

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

+ +

 

+

Example 1:

+
Input: numRows = 5
+Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
+

Example 2:

+
Input: numRows = 1
+Output: [[1]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= numRows <= 30
  • +
+
\ No newline at end of file diff --git a/pascals-triangle/pascals-triangle.cpp b/pascals-triangle/pascals-triangle.cpp new file mode 100644 index 0000000..3c82199 --- /dev/null +++ b/pascals-triangle/pascals-triangle.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + vector> generate(int numRows) { + vector> r(numRows); + + for(int i=0;i a; +// a.resize(numRows); +// a[0] = 1; +// a[numRows-1] =1; + +// for(int i=1;i330. Patching Array

Hard


Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.

+ +

Return the minimum number of patches required.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3], n = 6
+Output: 1
+Explanation:
+Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
+Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
+Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
+So we only need 1 patch.
+
+ +

Example 2:

+ +
Input: nums = [1,5,10], n = 20
+Output: 2
+Explanation: The two patches can be [2, 4].
+
+ +

Example 3:

+ +
Input: nums = [1,2,2], n = 5
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 1 <= nums[i] <= 104
  • +
  • nums is sorted in ascending order.
  • +
  • 1 <= n <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/patching-array/patching-array.cpp b/patching-array/patching-array.cpp new file mode 100644 index 0000000..1a4ed6e --- /dev/null +++ b/patching-array/patching-array.cpp @@ -0,0 +1,15 @@ +class Solution { +public: +int minPatches(vector& nums, int n) { + int cnt=0,i=0; + long long maxNum=0; + while (maxNum113. Path Sum II

Medium


Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.

+ +

A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

+ +

 

+

Example 1:

+ +
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
+Output: [[5,4,11,2],[5,8,4,5]]
+Explanation: There are two paths whose sum equals targetSum:
+5 + 4 + 11 + 2 = 22
+5 + 8 + 4 + 5 = 22
+
+ +

Example 2:

+ +
Input: root = [1,2,3], targetSum = 5
+Output: []
+
+ +

Example 3:

+ +
Input: root = [1,2], targetSum = 0
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 5000].
  • +
  • -1000 <= Node.val <= 1000
  • +
  • -1000 <= targetSum <= 1000
  • +
+
\ No newline at end of file diff --git a/path-sum-ii/path-sum-ii.cpp b/path-sum-ii/path-sum-ii.cpp new file mode 100644 index 0000000..0559ec3 --- /dev/null +++ b/path-sum-ii/path-sum-ii.cpp @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> pathSum(TreeNode* root, int sum) { + vector > paths; + vector path; + findPaths(root, sum, path, paths); + return paths; + } +private: + void findPaths(TreeNode* node, int sum, vector& path, vector >& paths) { + if (!node) return; + path.push_back(node -> val); + if (!(node -> left) && !(node -> right) && sum == node -> val) + paths.push_back(path); + findPaths(node -> left, sum - node -> val, path, paths); + findPaths(node -> right, sum - node -> val, path, paths); + path.pop_back(); + } +}; \ No newline at end of file diff --git a/path-sum/README.md b/path-sum/README.md new file mode 100644 index 0000000..484fdce --- /dev/null +++ b/path-sum/README.md @@ -0,0 +1,32 @@ +

112. Path Sum

Easy


Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

+ +

A leaf is a node with no children.

+ +

 

+

Example 1:

+ +
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
+Output: true
+
+ +

Example 2:

+ +
Input: root = [1,2,3], targetSum = 5
+Output: false
+
+ +

Example 3:

+ +
Input: root = [1,2], targetSum = 0
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 5000].
  • +
  • -1000 <= Node.val <= 1000
  • +
  • -1000 <= targetSum <= 1000
  • +
+
\ No newline at end of file diff --git a/path-sum/path-sum.cpp b/path-sum/path-sum.cpp new file mode 100644 index 0000000..83bea79 --- /dev/null +++ b/path-sum/path-sum.cpp @@ -0,0 +1,23 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool hasPathSum(TreeNode* root, int targetSum) { + if(root == NULL) + return false; + + if(root->right == NULL && root->left == NULL && root->val == targetSum) + return true; + + return hasPathSum(root->left,targetSum - root->val) || hasPathSum(root->right,targetSum - root->val); + } +}; \ No newline at end of file diff --git a/perfect-squares/README.md b/perfect-squares/README.md new file mode 100644 index 0000000..1ae0ade --- /dev/null +++ b/perfect-squares/README.md @@ -0,0 +1,26 @@ +

279. Perfect Squares

Medium


Given an integer n, return the least number of perfect square numbers that sum to n.

+ +

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

+ +

 

+

Example 1:

+ +
Input: n = 12
+Output: 3
+Explanation: 12 = 4 + 4 + 4.
+
+ +

Example 2:

+ +
Input: n = 13
+Output: 2
+Explanation: 13 = 4 + 9.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 104
  • +
+
\ No newline at end of file diff --git a/perfect-squares/perfect-squares.cpp b/perfect-squares/perfect-squares.cpp new file mode 100644 index 0000000..9d76bdd --- /dev/null +++ b/perfect-squares/perfect-squares.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int numSquares(int n) { + + if(n<=3) + return n; + vector v(n + 1); + v[0] = 0; + v[1] = 1; + v[2] = 2; + v[3] = 3; + + for (int i = 4; i <= n; i++) + { + v[i] = i; + for (int j = 1; j <= ceil(sqrt(i)); j++) + { + int temp = j * j; + if (temp > i) + break; + + v[i] = min(v[i], 1 + v[i - temp]); + } + } + return v[n]; + } +}; \ No newline at end of file diff --git a/permutations-ii/README.md b/permutations-ii/README.md new file mode 100644 index 0000000..0a772d3 --- /dev/null +++ b/permutations-ii/README.md @@ -0,0 +1,26 @@ +

47. Permutations II

Medium


Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

+ +

 

+

Example 1:

+ +
Input: nums = [1,1,2]
+Output:
+[[1,1,2],
+ [1,2,1],
+ [2,1,1]]
+
+ +

Example 2:

+ +
Input: nums = [1,2,3]
+Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 8
  • +
  • -10 <= nums[i] <= 10
  • +
+
\ No newline at end of file diff --git a/permutations-ii/permutations-ii.cpp b/permutations-ii/permutations-ii.cpp new file mode 100644 index 0000000..3d3f9ae --- /dev/null +++ b/permutations-ii/permutations-ii.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + + void permuteUniqueHelper(int i, vector& nums, vector >& result) { + if (i == nums.size()) { result.emplace_back(nums); return; } + unordered_set st; + for (int j = i; j < nums.size(); ++j) { + if (st.count(nums[j]) == 1) { continue; } + st.insert(nums[j]); + std::swap(nums[i], nums[j]); + permuteUniqueHelper(i + 1, nums, result); + std::swap(nums[i], nums[j]); + } + } + + vector> permuteUnique(vector& nums) { + vector > result; + permuteUniqueHelper(0, nums, result); + return result; + } +}; \ No newline at end of file diff --git a/populating-next-right-pointers-in-each-node/README.md b/populating-next-right-pointers-in-each-node/README.md new file mode 100644 index 0000000..2143e6d --- /dev/null +++ b/populating-next-right-pointers-in-each-node/README.md @@ -0,0 +1,44 @@ +

116. Populating Next Right Pointers in Each Node

Medium


You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

+ +
struct Node {
+  int val;
+  Node *left;
+  Node *right;
+  Node *next;
+}
+
+ +

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

+ +

Initially, all next pointers are set to NULL.

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3,4,5,6,7]
+Output: [1,#,2,3,#,4,5,6,7,#]
+Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
+
+ +

Example 2:

+ +
Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 212 - 1].
  • +
  • -1000 <= Node.val <= 1000
  • +
+ +

 

+

Follow-up:

+ +
    +
  • You may only use constant extra space.
  • +
  • The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
  • +
+
\ No newline at end of file diff --git a/populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.cpp b/populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.cpp new file mode 100644 index 0000000..e9dcbe4 --- /dev/null +++ b/populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.cpp @@ -0,0 +1,34 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; +*/ + +class Solution { +public: + Node* connect(Node* root) { + if (root) { + if (root->left) { + root->left->next = root->right; + if (root->next) + root->right->next = root->next->left; + connect(root->left); + connect(root->right); + + } + } + return root; + } +}; \ No newline at end of file diff --git a/populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.java b/populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.java new file mode 100644 index 0000000..735f8fe --- /dev/null +++ b/populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.java @@ -0,0 +1,18 @@ +class Solution { + public Node connect(Node root) { + + if (root == null || root.left == null) { + return root; + } + + root.left.next = root.right; + if (root.next != null) { + root.right.next = root.next.left; + } + + connect (root.left); + connect (root.right); + + return root; + } +} \ No newline at end of file diff --git a/power-of-four/README.md b/power-of-four/README.md new file mode 100644 index 0000000..f537239 --- /dev/null +++ b/power-of-four/README.md @@ -0,0 +1,24 @@ +

342. Power of Four

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: n = 16
+Output: true
+

Example 2:

+
Input: n = 5
+Output: false
+

Example 3:

+
Input: n = 1
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without loops/recursion?
\ No newline at end of file diff --git a/power-of-four/power-of-four.cpp b/power-of-four/power-of-four.cpp new file mode 100644 index 0000000..ca362fe --- /dev/null +++ b/power-of-four/power-of-four.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + bool isPowerOfFour(int n) { + if(n == 0) + return false; + if(n ==1) + return true; + if(n%4 == 0) + return isPowerOfFour(n/4); + return false; + } +}; \ No newline at end of file diff --git a/power-of-three/README.md b/power-of-three/README.md new file mode 100644 index 0000000..1efabf6 --- /dev/null +++ b/power-of-three/README.md @@ -0,0 +1,27 @@ +

326. Power of Three

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: n = 27
+Output: true
+

Example 2:

+
Input: n = 0
+Output: false
+

Example 3:

+
Input: n = 9
+Output: true
+

Example 4:

+
Input: n = 45
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without loops/recursion?
\ No newline at end of file diff --git a/power-of-three/power-of-three.cpp b/power-of-three/power-of-three.cpp new file mode 100644 index 0000000..bc89321 --- /dev/null +++ b/power-of-three/power-of-three.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + bool isPowerOfThree(int n) { + + if(n==0) + return false; + if(n==1) + { + return true; + } + + int x = n/3; + + if(isPowerOfThree(x) && (x*3 == n)) + return true; + return false; + + } +}; \ No newline at end of file diff --git a/power-of-two/README.md b/power-of-two/README.md new file mode 100644 index 0000000..58d82a9 --- /dev/null +++ b/power-of-two/README.md @@ -0,0 +1,46 @@ +

231. Power of Two

Easy


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: n = 1
+Output: true
+Explanation: 20 = 1
+
+ +

Example 2:

+ +
Input: n = 16
+Output: true
+Explanation: 24 = 16
+
+ +

Example 3:

+ +
Input: n = 3
+Output: false
+
+ +

Example 4:

+ +
Input: n = 4
+Output: true
+
+ +

Example 5:

+ +
Input: n = 5
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without loops/recursion?
\ No newline at end of file diff --git a/power-of-two/power-of-two.cpp b/power-of-two/power-of-two.cpp new file mode 100644 index 0000000..33edf20 --- /dev/null +++ b/power-of-two/power-of-two.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + bool isPowerOfTwo(int n) { + // n = abs(n); + + if(n <= 0) + return false; + + if(n%2 == 0) + return isPowerOfTwo(n/2); + + if(n == 1) + return true; + + return false; + + } +}; \ No newline at end of file diff --git a/powx-n/README.md b/powx-n/README.md new file mode 100644 index 0000000..6a9e8aa --- /dev/null +++ b/powx-n/README.md @@ -0,0 +1,31 @@ +

50. Pow(x, n)

Medium


Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

+ +

 

+

Example 1:

+ +
Input: x = 2.00000, n = 10
+Output: 1024.00000
+
+ +

Example 2:

+ +
Input: x = 2.10000, n = 3
+Output: 9.26100
+
+ +

Example 3:

+ +
Input: x = 2.00000, n = -2
+Output: 0.25000
+Explanation: 2-2 = 1/22 = 1/4 = 0.25
+
+ +

 

+

Constraints:

+ +
    +
  • -100.0 < x < 100.0
  • +
  • -231 <= n <= 231-1
  • +
  • -104 <= xn <= 104
  • +
+
\ No newline at end of file diff --git a/powx-n/powx-n.cpp b/powx-n/powx-n.cpp new file mode 100644 index 0000000..f83fe07 --- /dev/null +++ b/powx-n/powx-n.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + double myPow(double x, int n) { + if (n == std::numeric_limits::lowest()) { + return myPow(1 / x, -(n + 1)) / x; + } + if (n < 0) { + return myPow(1 / x, -n); + } + double ans = 1; + while (n) { + if (n & 1 == 1) ans *= x; + x *= x; + n >>= 1; + } + return ans; + } +}; \ No newline at end of file diff --git a/product-of-array-except-self/README.md b/product-of-array-except-self/README.md new file mode 100644 index 0000000..9888518 --- /dev/null +++ b/product-of-array-except-self/README.md @@ -0,0 +1,26 @@ +

238. Product of Array Except Self

Medium


Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

+ +

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

+ +

You must write an algorithm that runs in O(n) time and without using the division operation.

+ +

 

+

Example 1:

+
Input: nums = [1,2,3,4]
+Output: [24,12,8,6]
+

Example 2:

+
Input: nums = [-1,1,0,-3,3]
+Output: [0,0,9,0,0]
+
+

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 105
  • +
  • -30 <= nums[i] <= 30
  • +
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
  • +
+ +

 

+

Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

+
\ No newline at end of file diff --git a/product-of-array-except-self/product-of-array-except-self.cpp b/product-of-array-except-self/product-of-array-except-self.cpp new file mode 100644 index 0000000..9d31ff7 --- /dev/null +++ b/product-of-array-except-self/product-of-array-except-self.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + vector productExceptSelf(vector& nums) { + vector pre(nums.size()); + vector post(nums.size()); + + pre[0] = 1; + for(int i=1;i=0;i--) + { + post[i] = post[i+1]*nums[i+1]; + } + + for(int i=0;i1352. Product of the Last K Numbers

Medium


Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream.

+ +

Implement the ProductOfNumbers class:

+ +
    +
  • ProductOfNumbers() Initializes the object with an empty stream.
  • +
  • void add(int num) Appends the integer num to the stream.
  • +
  • int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers.
  • +
+ +

The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.

+ +

 

+

Example:

+ +
Input
+["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
+[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]
+
+Output
+[null,null,null,null,null,null,20,40,0,null,32]
+
+Explanation
+ProductOfNumbers productOfNumbers = new ProductOfNumbers();
+productOfNumbers.add(3);        // [3]
+productOfNumbers.add(0);        // [3,0]
+productOfNumbers.add(2);        // [3,0,2]
+productOfNumbers.add(5);        // [3,0,2,5]
+productOfNumbers.add(4);        // [3,0,2,5,4]
+productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20
+productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40
+productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0
+productOfNumbers.add(8);        // [3,0,2,5,4,8]
+productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32 
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= num <= 100
  • +
  • 1 <= k <= 4 * 104
  • +
  • At most 4 * 104 calls will be made to add and getProduct.
  • +
  • The product of the stream at any point in time will fit in a 32-bit integer.
  • +
+
\ No newline at end of file diff --git a/push-dominoes/README.md b/push-dominoes/README.md new file mode 100644 index 0000000..f083055 --- /dev/null +++ b/push-dominoes/README.md @@ -0,0 +1,41 @@ +

838. Push Dominoes

Medium


There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.

+ +

After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.

+ +

When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.

+ +

For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.

+ +

You are given a string dominoes representing the initial state where:

+ +
    +
  • dominoes[i] = 'L', if the ith domino has been pushed to the left,
  • +
  • dominoes[i] = 'R', if the ith domino has been pushed to the right, and
  • +
  • dominoes[i] = '.', if the ith domino has not been pushed.
  • +
+ +

Return a string representing the final state.

+ +

 

+

Example 1:

+ +
Input: dominoes = "RR.L"
+Output: "RR.L"
+Explanation: The first domino expends no additional force on the second domino.
+
+ +

Example 2:

+ +
Input: dominoes = ".L.R...LR..L.."
+Output: "LL.RR.LLRRLL.."
+
+ +

 

+

Constraints:

+ +
    +
  • n == dominoes.length
  • +
  • 1 <= n <= 105
  • +
  • dominoes[i] is either 'L', 'R', or '.'.
  • +
+
\ No newline at end of file diff --git a/push-dominoes/push-dominoes.cpp b/push-dominoes/push-dominoes.cpp new file mode 100644 index 0000000..1659bfe --- /dev/null +++ b/push-dominoes/push-dominoes.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + string pushDominoes(string dominoes) { + int n = dominoes.size(); + vector left_r_dis(n + 1, 0); + vector right_l_dis(n + 1, 0); + int r_pos = n + 1; + for (int i = 0; i < n; ++i) { + if (dominoes[i] == 'R') { + r_pos = i; + } + else if (dominoes[i] == 'L') { + r_pos = n + 1; + } + left_r_dis[i] = r_pos == n + 1 ? n + 1 : i - r_pos; + } + int l_pos = -1; + for (int i = n - 1; i >= 0; --i) { + if (dominoes[i] == 'L') { + l_pos = i; + } + else if (dominoes[i] == 'R') { + l_pos = -1; + } + right_l_dis[i] = l_pos == -1 ? n + 1 : l_pos - i; + } + + string result = dominoes; + for (int i = 0; i < n; ++i) { + if (left_r_dis[i] < right_l_dis[i]) result[i] = 'R'; + else if (left_r_dis[i] > right_l_dis[i]) result[i] = 'L'; + //else + } + + return result; + } +}; \ No newline at end of file diff --git a/range-addition-ii/README.md b/range-addition-ii/README.md new file mode 100644 index 0000000..399a67f --- /dev/null +++ b/range-addition-ii/README.md @@ -0,0 +1,35 @@ +

598. Range Addition II

Easy


You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi.

+ +

Count and return the number of maximum integers in the matrix after performing all the operations.

+ +

 

+

Example 1:

+ +
Input: m = 3, n = 3, ops = [[2,2],[3,3]]
+Output: 4
+Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4.
+
+ +

Example 2:

+ +
Input: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]
+Output: 4
+
+ +

Example 3:

+ +
Input: m = 3, n = 3, ops = []
+Output: 9
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= m, n <= 4 * 104
  • +
  • 1 <= ops.length <= 104
  • +
  • ops[i].length == 2
  • +
  • 1 <= ai <= m
  • +
  • 1 <= bi <= n
  • +
+
\ No newline at end of file diff --git a/range-addition-ii/range-addition-ii.cpp b/range-addition-ii/range-addition-ii.cpp new file mode 100644 index 0000000..fc9b53d --- /dev/null +++ b/range-addition-ii/range-addition-ii.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int maxCount(int m, int n, vector>& ops) { + for (int i = 0; i < ops.size(); ++i) { + m = min(m, ops[i][0]); + n = min(n, ops[i][1]); + } + return m*n; + } +}; \ No newline at end of file diff --git a/range-sum-of-bst/README.md b/range-sum-of-bst/README.md new file mode 100644 index 0000000..2436e88 --- /dev/null +++ b/range-sum-of-bst/README.md @@ -0,0 +1,27 @@ +

938. Range Sum of BST

Easy


Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].

+ +

 

+

Example 1:

+ +
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
+Output: 32
+Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.
+
+ +

Example 2:

+ +
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
+Output: 23
+Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 2 * 104].
  • +
  • 1 <= Node.val <= 105
  • +
  • 1 <= low <= high <= 105
  • +
  • All Node.val are unique.
  • +
+
\ No newline at end of file diff --git a/range-sum-of-bst/range-sum-of-bst.cpp b/range-sum-of-bst/range-sum-of-bst.cpp new file mode 100644 index 0000000..43d7b48 --- /dev/null +++ b/range-sum-of-bst/range-sum-of-bst.cpp @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int rangeSumBST(TreeNode* root, int low, int high) { + int sum = 0; + if(root == NULL) + return sum; + + if(root->val < low) + { + return rangeSumBST(root->right,low,high); + } + + if(root->val > high) + { + return rangeSumBST(root->left,low,high); + } + sum += root->val; + return sum +rangeSumBST(root->left,low,high)+ rangeSumBST(root->right,low,high); + + } +}; \ No newline at end of file diff --git a/range-sum-query-2d-immutable/README.md b/range-sum-query-2d-immutable/README.md new file mode 100644 index 0000000..730e5cf --- /dev/null +++ b/range-sum-query-2d-immutable/README.md @@ -0,0 +1,42 @@ +

304. Range Sum Query 2D - Immutable

Medium


Given a 2D matrix matrix, handle multiple queries of the following type:

+ +
    +
  • Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
  • +
+ +

Implement the NumMatrix class:

+ +
    +
  • NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix.
  • +
  • int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
  • +
+ +

 

+

Example 1:

+ +
Input
+["NumMatrix", "sumRegion", "sumRegion", "sumRegion"]
+[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]
+Output
+[null, 8, 11, 12]
+
+Explanation
+NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);
+numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
+numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
+numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • -105 <= matrix[i][j] <= 105
  • +
  • 0 <= row1 <= row2 < m
  • +
  • 0 <= col1 <= col2 < n
  • +
  • At most 104 calls will be made to sumRegion.
  • +
+
\ No newline at end of file diff --git a/range-sum-query-2d-immutable/range-sum-query-2d-immutable.cpp b/range-sum-query-2d-immutable/range-sum-query-2d-immutable.cpp new file mode 100644 index 0000000..dced07f --- /dev/null +++ b/range-sum-query-2d-immutable/range-sum-query-2d-immutable.cpp @@ -0,0 +1,26 @@ +class NumMatrix {private: + int row, col; + vector> sums; +public: + NumMatrix(vector> &matrix) { + row = matrix.size(); + col = row>0 ? matrix[0].size() : 0; + sums = vector>(row+1, vector(col+1, 0)); + for(int i=1; i<=row; i++) { + for(int j=1; j<=col; j++) { + sums[i][j] = matrix[i-1][j-1] + + sums[i-1][j] + sums[i][j-1] - sums[i-1][j-1] ; + } + } + } + + int sumRegion(int row1, int col1, int row2, int col2) { + return sums[row2+1][col2+1] - sums[row2+1][col1] - sums[row1][col2+1] + sums[row1][col1]; + } +}; + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix* obj = new NumMatrix(matrix); + * int param_1 = obj->sumRegion(row1,col1,row2,col2); + */ \ No newline at end of file diff --git a/range-sum-query-immutable/README.md b/range-sum-query-immutable/README.md new file mode 100644 index 0000000..c3d6a3a --- /dev/null +++ b/range-sum-query-immutable/README.md @@ -0,0 +1,39 @@ +

303. Range Sum Query - Immutable

Easy


Given an integer array nums, handle multiple queries of the following type:

+ +
    +
  1. Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
  2. +
+ +

Implement the NumArray class:

+ +
    +
  • NumArray(int[] nums) Initializes the object with the integer array nums.
  • +
  • int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).
  • +
+ +

 

+

Example 1:

+ +
Input
+["NumArray", "sumRange", "sumRange", "sumRange"]
+[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
+Output
+[null, 1, -1, -3]
+
+Explanation
+NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
+numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
+numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
+numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -105 <= nums[i] <= 105
  • +
  • 0 <= left <= right < nums.length
  • +
  • At most 104 calls will be made to sumRange.
  • +
+
\ No newline at end of file diff --git a/rank-transform-of-a-matrix/README.md b/rank-transform-of-a-matrix/README.md new file mode 100644 index 0000000..516f9e9 --- /dev/null +++ b/rank-transform-of-a-matrix/README.md @@ -0,0 +1,58 @@ +

1632. Rank Transform of a Matrix

Hard


Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col].

+ +

The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules:

+ +
    +
  • The rank is an integer starting from 1.
  • +
  • If two elements p and q are in the same row or column, then: +
      +
    • If p < q then rank(p) < rank(q)
    • +
    • If p == q then rank(p) == rank(q)
    • +
    • If p > q then rank(p) > rank(q)
    • +
    +
  • +
  • The rank should be as small as possible.
  • +
+ +

It is guaranteed that answer is unique under the given rules.

+ +

 

+

Example 1:

+ +
Input: matrix = [[1,2],[3,4]]
+Output: [[1,2],[2,3]]
+Explanation:
+The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.
+The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.
+The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.
+The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.
+
+ +

Example 2:

+ +
Input: matrix = [[7,7],[7,7]]
+Output: [[1,1],[1,1]]
+
+ +

Example 3:

+ +
Input: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]
+Output: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]
+
+ +

Example 4:

+ +
Input: matrix = [[7,3,6],[1,4,5],[9,8,2]]
+Output: [[5,1,4],[1,2,3],[6,3,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 500
  • +
  • -109 <= matrix[row][col] <= 109
  • +
+
\ No newline at end of file diff --git a/rank-transform-of-a-matrix/rank-transform-of-a-matrix.cpp b/rank-transform-of-a-matrix/rank-transform-of-a-matrix.cpp new file mode 100644 index 0000000..c46d4d5 --- /dev/null +++ b/rank-transform-of-a-matrix/rank-transform-of-a-matrix.cpp @@ -0,0 +1,124 @@ +class Solution { +public: + +#define lop(i,s,e) for(int i=s;i<(int)e;i++) +#define pii pair +#define ff first +#define ss second + + pii par[501][501]; // par[i][j] -> parent of cell {i, j} + int sz[501][501]; // sz[i][j] -> size of set whose leader/parent is {i, j} + + // DSU IMPLEMENTATION below + // void build(int n, int m); // Initialising DSU + // pii find(pii a) ; // Finding leader/parent of cell {i, j} + // void make_union(pii a, pii b); // Uniting 2 cells + + vector> matrixRankTransform(vector>& mat) { + int n = mat.size(), m = mat[0].size(); + vector < vector > ans(n, vector (m, -1) ); + + // Initialising DSU + build(n, m); + + // Uniting All cells with rank value in same row + lop(i, 0, n){ + map mp; + lop(j, 0, m){ + int val = mat[i][j]; + if( mp.count( val ) ) make_union( {i,j} , mp[val]); + mp[val] = {i, j}; + } + } + + // Uniting all cells with rank value in same column + lop(j, 0, m){ + map mp; + lop(i, 0, n){ + int val = mat[i][j]; + if( mp.count( val ) ) make_union( {i,j} , mp[val]); + mp[val] = {i, j}; + } + } + + + // Keeping cells with same rank in a vector of their parent/leader + vector all[n][m]; + lop(i, 0, n)lop(j, 0, m){ + pii x = {i, j}; + pii p = find(x); + all[p.ff][p.ss].push_back( x ); + } + + // Storing vectors in a map with their parent value as key + map > > mp; + lop(i, 0, n){ + lop(j,0,m){ + if( (int)all[i][j].size() == 0 ) continue; + int val = mat[i][j]; + mp[ val ].push_back( all[i][j] ); + } + } + vector row(n, 0), col(m, 0); + + // row[i] = largest rank till now in ith row + // col[i] = largest rank till now in ith column + + + for(auto &i: mp){ // first assigning ranks to smaller elements then larger elements + + for(auto &j: i.ss){ + + // x -> answer for current vector of cells ( all these cells will get the same rank ) + int x = 0; + + for(auto &k: j){ + int r = k.ff, c = k.ss; // {r,c} -> current cell + + // ans should be >= max(row[r], row[c]) + 1 , + // because largest rank of smaller elements in this row/column is == max(row[r], row[c]) + + x = max(x, max(row[r], col[c]) + 1 ); + } + + for(auto &k: j){ + int r = k.ff, c = k.ss; + ans[r][c] = x; + + // Updating largest rank in row and column for the current row and column + row[r] = max(row[r], x); + col[c] = max(col[c], x); + } + } + } + + return ans; + } + + /// DSU IMPLEMENTATION + void build(int n, int m) { + for(int i = 0; i < n; i++){ + for(int j = 0; j < m; j++){ + par[i][j] = {i, j}; + sz[i][j] = 1; + } + } + } + + pii find(pii a) { // finding leader/parent of cell {i, j} + if( par[a.ff][a.ss] == a) return a; + return par[a.ff][a.ss] = find( par[a.ff][a.ss] ); + } + + void make_union(pii a, pii b) { // Uniting 2 cells + pii pa = find(a), pb = find(b); + + if( pa != pb ) { + if( sz[pa.ff][pa.ss] < sz[pb.ff][pb.ss] ) swap(pa,pb); + par[pb.ff][pb.ss] = pa; + sz[pa.ff][pb.ss] += sz[pb.ff][pb.ss]; + } + } + + +}; diff --git a/remove-boxes/README.md b/remove-boxes/README.md new file mode 100644 index 0000000..a67bcb5 --- /dev/null +++ b/remove-boxes/README.md @@ -0,0 +1,39 @@ +

546. Remove Boxes

Hard


You are given several boxes with different colors represented by different positive numbers.

+ +

You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1), remove them and get k * k points.

+ +

Return the maximum points you can get.

+ +

 

+

Example 1:

+ +
Input: boxes = [1,3,2,2,2,3,4,3,1]
+Output: 23
+Explanation:
+[1, 3, 2, 2, 2, 3, 4, 3, 1] 
+----> [1, 3, 3, 4, 3, 1] (3*3=9 points) 
+----> [1, 3, 3, 3, 1] (1*1=1 points) 
+----> [1, 1] (3*3=9 points) 
+----> [] (2*2=4 points)
+
+ +

Example 2:

+ +
Input: boxes = [1,1,1]
+Output: 9
+
+ +

Example 3:

+ +
Input: boxes = [1]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= boxes.length <= 100
  • +
  • 1 <= boxes[i] <= 100
  • +
+
\ No newline at end of file diff --git a/remove-duplicates-from-sorted-array/README.md b/remove-duplicates-from-sorted-array/README.md new file mode 100644 index 0000000..d170b12 --- /dev/null +++ b/remove-duplicates-from-sorted-array/README.md @@ -0,0 +1,51 @@ +

26. Remove Duplicates from Sorted Array

Easy


Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

+ +

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

+ +

Return k after placing the final result in the first k slots of nums.

+ +

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

+ +

Custom Judge:

+ +

The judge will test your solution with the following code:

+ +
int[] nums = [...]; // Input array
+int[] expectedNums = [...]; // The expected answer with correct length
+
+int k = removeDuplicates(nums); // Calls your implementation
+
+assert k == expectedNums.length;
+for (int i = 0; i < k; i++) {
+    assert nums[i] == expectedNums[i];
+}
+
+ +

If all assertions pass, then your solution will be accepted.

+ +

 

+

Example 1:

+ +
Input: nums = [1,1,2]
+Output: 2, nums = [1,2,_]
+Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
+It does not matter what you leave beyond the returned k (hence they are underscores).
+
+ +

Example 2:

+ +
Input: nums = [0,0,1,1,1,2,2,3,3,4]
+Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
+Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
+It does not matter what you leave beyond the returned k (hence they are underscores).
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 3 * 104
  • +
  • -100 <= nums[i] <= 100
  • +
  • nums is sorted in non-decreasing order.
  • +
+
\ No newline at end of file diff --git a/remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.cpp b/remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.cpp new file mode 100644 index 0000000..0ea5bda --- /dev/null +++ b/remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int removeDuplicates(vector& nums) { + + if(nums.size()<=1) + return nums.size(); + int low = 0; + int high = 0; + + while(high203. Remove Linked List Elements

Easy


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

+ +

 

+

Example 1:

+ +
Input: head = [1,2,6,3,4,5,6], val = 6
+Output: [1,2,3,4,5]
+
+ +

Example 2:

+ +
Input: head = [], val = 1
+Output: []
+
+ +

Example 3:

+ +
Input: head = [7,7,7,7], val = 7
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 104].
  • +
  • 1 <= Node.val <= 50
  • +
  • 0 <= val <= 50
  • +
+
\ No newline at end of file diff --git a/remove-linked-list-elements/remove-linked-list-elements.cpp b/remove-linked-list-elements/remove-linked-list-elements.cpp new file mode 100644 index 0000000..35c7339 --- /dev/null +++ b/remove-linked-list-elements/remove-linked-list-elements.cpp @@ -0,0 +1,38 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeElements(ListNode* head, int val) { + if(head == NULL)return NULL; + + ListNode * temp = new ListNode(-1); + temp->next = head; + + ListNode * ans = temp; + + while(temp->next != NULL) + { + if(temp->next->val == val) + { + ListNode * del = temp->next; + temp->next = temp->next->next; + del->next = NULL; + delete del; + } + else + { + temp = temp->next; + } + } + + return ans->next; + } +}; \ No newline at end of file diff --git a/remove-nth-node-from-end-of-list/README.md b/remove-nth-node-from-end-of-list/README.md new file mode 100644 index 0000000..8f0abb0 --- /dev/null +++ b/remove-nth-node-from-end-of-list/README.md @@ -0,0 +1,34 @@ +

19. Remove Nth Node From End of List

Medium


Given the head of a linked list, remove the nth node from the end of the list and return its head.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5], n = 2
+Output: [1,2,3,5]
+
+ +

Example 2:

+ +
Input: head = [1], n = 1
+Output: []
+
+ +

Example 3:

+ +
Input: head = [1,2], n = 1
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is sz.
  • +
  • 1 <= sz <= 30
  • +
  • 0 <= Node.val <= 100
  • +
  • 1 <= n <= sz
  • +
+ +

 

+

Follow up: Could you do this in one pass?

+
\ No newline at end of file diff --git a/remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.cpp b/remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.cpp new file mode 100644 index 0000000..01f797f --- /dev/null +++ b/remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.cpp @@ -0,0 +1,39 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + + ListNode *dummy = new ListNode(); + dummy->next = head; + + ListNode * slow = dummy; + ListNode * fast = dummy; + + while(n--) + { + fast = fast->next; + } + + while(fast ->next != NULL) + { + fast = fast->next; + slow = slow->next; + } + + ListNode * node = slow->next; + slow->next = slow->next->next; + delete node; + + return dummy->next; + + } +}; \ No newline at end of file diff --git a/reorder-list/README.md b/reorder-list/README.md new file mode 100644 index 0000000..3ee80eb --- /dev/null +++ b/reorder-list/README.md @@ -0,0 +1,33 @@ +

143. Reorder List

Medium


You are given the head of a singly linked-list. The list can be represented as:

+ +
L0 → L1 → … → Ln - 1 → Ln
+
+ +

Reorder the list to be on the following form:

+ +
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
+
+ +

You may not modify the values in the list's nodes. Only nodes themselves may be changed.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4]
+Output: [1,4,2,3]
+
+ +

Example 2:

+ +
Input: head = [1,2,3,4,5]
+Output: [1,5,2,4,3]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 5 * 104].
  • +
  • 1 <= Node.val <= 1000
  • +
+
\ No newline at end of file diff --git a/reverse-linked-list/README.md b/reverse-linked-list/README.md new file mode 100644 index 0000000..243642c --- /dev/null +++ b/reverse-linked-list/README.md @@ -0,0 +1,32 @@ +

206. Reverse Linked List

Easy


Given the head of a singly linked list, reverse the list, and return the reversed list.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5]
+Output: [5,4,3,2,1]
+
+ +

Example 2:

+ +
Input: head = [1,2]
+Output: [2,1]
+
+ +

Example 3:

+ +
Input: head = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is the range [0, 5000].
  • +
  • -5000 <= Node.val <= 5000
  • +
+ +

 

+

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

+
\ No newline at end of file diff --git a/reverse-linked-list/reverse-linked-list.cpp b/reverse-linked-list/reverse-linked-list.cpp new file mode 100644 index 0000000..1ce85ef --- /dev/null +++ b/reverse-linked-list/reverse-linked-list.cpp @@ -0,0 +1,22 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + if(head == NULL || head->next == NULL) + return head; + ListNode * nextp = head->next; + ListNode * reversed = reverseList(head->next); + nextp->next = head; + head->next = NULL; + return reversed; + } +}; \ No newline at end of file diff --git a/reverse-nodes-in-k-group/README.md b/reverse-nodes-in-k-group/README.md new file mode 100644 index 0000000..bb3fa90 --- /dev/null +++ b/reverse-nodes-in-k-group/README.md @@ -0,0 +1,43 @@ +

25. Reverse Nodes in k-Group

Hard


Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

+ +

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

+ +

You may not alter the values in the list's nodes, only nodes themselves may be changed.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5], k = 2
+Output: [2,1,4,3,5]
+
+ +

Example 2:

+ +
Input: head = [1,2,3,4,5], k = 3
+Output: [3,2,1,4,5]
+
+ +

Example 3:

+ +
Input: head = [1,2,3,4,5], k = 1
+Output: [1,2,3,4,5]
+
+ +

Example 4:

+ +
Input: head = [1], k = 1
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range sz.
  • +
  • 1 <= sz <= 5000
  • +
  • 0 <= Node.val <= 1000
  • +
  • 1 <= k <= sz
  • +
+ +

 

+Follow-up: Can you solve the problem in O(1) extra memory space?
\ No newline at end of file diff --git a/reverse-nodes-in-k-group/reverse-nodes-in-k-group.cpp b/reverse-nodes-in-k-group/reverse-nodes-in-k-group.cpp new file mode 100644 index 0000000..823a177 --- /dev/null +++ b/reverse-nodes-in-k-group/reverse-nodes-in-k-group.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + ListNode *reverseKGroup(ListNode *head, int k) { + if(head==NULL||k==1) return head; + int num=0; + ListNode *preheader = new ListNode(-1); + preheader->next = head; + ListNode *cur = preheader, *nex, *pre = preheader; + while(cur = cur->next) + num++; + while(num>=k) { + cur = pre->next; + nex = cur->next; + for(int i=1;inext=nex->next; + nex->next=pre->next; + pre->next=nex; + nex=cur->next; + } + pre = cur; + num-=k; + } + return preheader->next; + } +}; \ No newline at end of file diff --git a/reverse-pairs/README.md b/reverse-pairs/README.md new file mode 100644 index 0000000..27f6743 --- /dev/null +++ b/reverse-pairs/README.md @@ -0,0 +1,20 @@ +

493. Reverse Pairs

Hard


Given an integer array nums, return the number of reverse pairs in the array.

+ +

A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].

+ +

 

+

Example 1:

+
Input: nums = [1,3,2,3,1]
+Output: 2
+

Example 2:

+
Input: nums = [2,4,3,5,1]
+Output: 3
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/reverse-pairs/reverse-pairs.cpp b/reverse-pairs/reverse-pairs.cpp new file mode 100644 index 0000000..36e5f2b --- /dev/null +++ b/reverse-pairs/reverse-pairs.cpp @@ -0,0 +1,130 @@ +class Solution { +public: + int merge(vector& nums,int start,int mid,int end) + { + int j = mid+1; + int count = 0; + for(int i = start;i<=mid;i++ ) + { + while(j<=end && nums[i] > 2LL * nums[j] ) + { + j++; + } + count += (j-(mid+1)); + } + + vector temp; + int i = start; + j = mid+1; + int k = 0; + while(i<= mid && j<= end) + { + if(nums[i]>=nums[j]) + temp.push_back(nums[j++]); + else + temp.push_back(nums[i++]); + } + + while(i<=mid) + temp.push_back(nums[i++]); + while(j<=end) + temp.push_back(nums[j++]); + + for(int y =start;y<=end;y++) + nums[y] = temp[y-start]; + + return count; + + } + + int merge_sort(vector& nums,int start,int end) + { + if(start>=end) + return 0; + int pairs = 0; + int mid = (start + end)/2; + pairs+=merge_sort(nums,start,mid); + pairs+=merge_sort(nums,mid+1,end); + + pairs+=merge(nums,start,mid,end); + return pairs; + } + + int reversePairs(vector& nums) { + return merge_sort(nums,0,nums.size()-1); + } +}; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +// class Solution { +// public: +// int merge(vector &nums, int l, int m, int h) { +// int count=0; +// int j=m+1; +// for(int i=l;i<=m;++i) { +// while(j<=h && nums[i] > 2LL*nums[j]) ++j; +// count += (j - (m+1)); +// } +// // merge of two sorted array +// vector temp; +// int left=l,right=m+1; +// // loop till on of them execuested +// while(left<=m && right<=h) { +// if(nums[left]<=nums[right]) temp.push_back(nums[left++]); +// else temp.push_back(nums[right++]); +// } +// // remaining elements of left side +// while(left<=m) temp.push_back(nums[left++]); +// // remaining elements of right side +// while(right<=h) temp.push_back(nums[right++]); +// // assingn in main vector after merging +// for(int i=l;i<=h;++i) { +// nums[i]=temp[i-l]; +// } +// return count; +// } +// int mergeSort(vector &nums, int l, int h) { +// if(l>=h) return 0; // A single element does not contain any pair +// int m=(l+h)/2; +// int count=0; +// count += mergeSort(nums,l,m); // count from left side of vector +// count += mergeSort(nums,m+1,h); // count from right side of vector +// count += merge(nums,l,m,h); // count merge +// return count; +// } +// int reversePairs(vector& nums) { +// return mergeSort(nums, 0, nums.size()-1); +// } +// }; \ No newline at end of file diff --git a/reverse-words-in-a-string-iii/README.md b/reverse-words-in-a-string-iii/README.md new file mode 100644 index 0000000..d60372a --- /dev/null +++ b/reverse-words-in-a-string-iii/README.md @@ -0,0 +1,21 @@ +

557. Reverse Words in a String III

Easy


Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

+ +

 

+

Example 1:

+
Input: s = "Let's take LeetCode contest"
+Output: "s'teL ekat edoCteeL tsetnoc"
+

Example 2:

+
Input: s = "God Ding"
+Output: "doG gniD"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 104
  • +
  • s contains printable ASCII characters.
  • +
  • s does not contain any leading or trailing spaces.
  • +
  • There is at least one word in s.
  • +
  • All the words in s are separated by a single space.
  • +
+
\ No newline at end of file diff --git a/robot-return-to-origin/README.md b/robot-return-to-origin/README.md new file mode 100644 index 0000000..177e74d --- /dev/null +++ b/robot-return-to-origin/README.md @@ -0,0 +1,41 @@ +

657. Robot Return to Origin

Easy


There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

+ +

The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

+ +

Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

+ +

 

+

Example 1:

+ +
Input: moves = "UD"
+Output: true
+Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
+
+ +

Example 2:

+ +
Input: moves = "LL"
+Output: false
+Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
+
+ +

Example 3:

+ +
Input: moves = "RRDD"
+Output: false
+
+ +

Example 4:

+ +
Input: moves = "LDRRLRUULR"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= moves.length <= 2 * 104
  • +
  • moves only contains the characters 'U', 'D', 'L' and 'R'.
  • +
+
\ No newline at end of file diff --git a/robot-return-to-origin/robot-return-to-origin.cpp b/robot-return-to-origin/robot-return-to-origin.cpp new file mode 100644 index 0000000..7530b1a --- /dev/null +++ b/robot-return-to-origin/robot-return-to-origin.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + bool judgeCircle(string moves) { + int v = 0; + int h = 0; + for (char ch : moves) { + switch (ch) { + case 'U' : v++; break; + case 'D' : v--; break; + case 'R' : h++; break; + case 'L' : h--; break; + } + } + return v == 0 && h == 0; + } +}; \ No newline at end of file diff --git a/roman-to-integer/README.md b/roman-to-integer/README.md new file mode 100644 index 0000000..1c6e097 --- /dev/null +++ b/roman-to-integer/README.md @@ -0,0 +1,65 @@ +

13. Roman to Integer

Easy


Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

+ +
Symbol       Value
+I             1
+V             5
+X             10
+L             50
+C             100
+D             500
+M             1000
+ +

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

+ +

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

+ +
    +
  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • +
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • +
  • C can be placed before D (500) and M (1000) to make 400 and 900.
  • +
+ +

Given a roman numeral, convert it to an integer.

+ +

 

+

Example 1:

+ +
Input: s = "III"
+Output: 3
+
+ +

Example 2:

+ +
Input: s = "IV"
+Output: 4
+
+ +

Example 3:

+ +
Input: s = "IX"
+Output: 9
+
+ +

Example 4:

+ +
Input: s = "LVIII"
+Output: 58
+Explanation: L = 50, V= 5, III = 3.
+
+ +

Example 5:

+ +
Input: s = "MCMXCIV"
+Output: 1994
+Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 15
  • +
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • +
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].
  • +
+
\ No newline at end of file diff --git a/roman-to-integer/roman-to-integer.cpp b/roman-to-integer/roman-to-integer.cpp new file mode 100644 index 0000000..e982b04 --- /dev/null +++ b/roman-to-integer/roman-to-integer.cpp @@ -0,0 +1,28 @@ +class Solution { +public: +int romanToInt(string s) +{ + unordered_map T = { { 'I' , 1 }, + { 'V' , 5 }, + { 'X' , 10 }, + { 'L' , 50 }, + { 'C' , 100 }, + { 'D' , 500 }, + { 'M' , 1000 } }; + + int sum = T[s.back()]; + for (int i = s.length() - 2; i >= 0; --i) + { + if (T[s[i]] < T[s[i + 1]]) + { + sum -= T[s[i]]; + } + else + { + sum += T[s[i]]; + } + } + + return sum; +} +}; \ No newline at end of file diff --git a/rotate-array/README.md b/rotate-array/README.md new file mode 100644 index 0000000..49cca61 --- /dev/null +++ b/rotate-array/README.md @@ -0,0 +1,39 @@ +

189. Rotate Array

Medium


Given an array, rotate the array to the right by k steps, where k is non-negative.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,4,5,6,7], k = 3
+Output: [5,6,7,1,2,3,4]
+Explanation:
+rotate 1 steps to the right: [7,1,2,3,4,5,6]
+rotate 2 steps to the right: [6,7,1,2,3,4,5]
+rotate 3 steps to the right: [5,6,7,1,2,3,4]
+
+ +

Example 2:

+ +
Input: nums = [-1,-100,3,99], k = 2
+Output: [3,99,-1,-100]
+Explanation: 
+rotate 1 steps to the right: [99,-1,-100,3]
+rotate 2 steps to the right: [3,99,-1,-100]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • 0 <= k <= 105
  • +
+ +

 

+

Follow up:

+ +
    +
  • Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
  • +
  • Could you do it in-place with O(1) extra space?
  • +
+
\ No newline at end of file diff --git a/rotate-array/rotate-array.cpp b/rotate-array/rotate-array.cpp new file mode 100644 index 0000000..9230e79 --- /dev/null +++ b/rotate-array/rotate-array.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + void rotate(vector& nums, int k) { + + if(k>nums.size()) + k = k % nums.size(); + + reverse(nums.begin(),nums.begin()+(nums.size()-k)); + reverse(nums.begin()+(nums.size()-k),nums.end()); + reverse(nums.begin(),nums.end()); + + } +}; \ No newline at end of file diff --git a/rotate-image/README.md b/rotate-image/README.md new file mode 100644 index 0000000..74239c2 --- /dev/null +++ b/rotate-image/README.md @@ -0,0 +1,39 @@ +

48. Rotate Image

Medium


You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

+ +

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

+ +

 

+

Example 1:

+ +
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
+Output: [[7,4,1],[8,5,2],[9,6,3]]
+
+ +

Example 2:

+ +
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
+Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
+
+ +

Example 3:

+ +
Input: matrix = [[1]]
+Output: [[1]]
+
+ +

Example 4:

+ +
Input: matrix = [[1,2],[3,4]]
+Output: [[3,1],[4,2]]
+
+ +

 

+

Constraints:

+ +
    +
  • matrix.length == n
  • +
  • matrix[i].length == n
  • +
  • 1 <= n <= 20
  • +
  • -1000 <= matrix[i][j] <= 1000
  • +
+
\ No newline at end of file diff --git a/rotate-image/rotate-image.cpp b/rotate-image/rotate-image.cpp new file mode 100644 index 0000000..8351400 --- /dev/null +++ b/rotate-image/rotate-image.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + void rotate(vector>& matrix) { + + int m = matrix.size(); + int n = matrix[0].size(); + + // Doing Transpose of the matrix + + for(int i=0;i61. Rotate List

Medium


Given the head of a linked list, rotate the list to the right by k places.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5], k = 2
+Output: [4,5,1,2,3]
+
+ +

Example 2:

+ +
Input: head = [0,1,2], k = 4
+Output: [2,0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 500].
  • +
  • -100 <= Node.val <= 100
  • +
  • 0 <= k <= 2 * 109
  • +
+
\ No newline at end of file diff --git a/rotate-list/rotate-list.cpp b/rotate-list/rotate-list.cpp new file mode 100644 index 0000000..4ef4d77 --- /dev/null +++ b/rotate-list/rotate-list.cpp @@ -0,0 +1,53 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* rotateRight(ListNode* head, int k) { + + if(k == 0 || head == NULL || head->next == NULL) + return head; + + int count = 0; + ListNode * temp = head; + while(temp != NULL) + { + temp = temp->next; + count++; + } + + + k = k % count; + if(k==0)return head; + + // cout<next; + k--; + } + // cout<val<val<next != NULL) + { + slow = slow->next; + fast = fast->next; + } + ListNode * res = slow->next; + slow->next = NULL; + fast->next = head; + return res; + + + } +}; \ No newline at end of file diff --git a/rotated-digits/README.md b/rotated-digits/README.md new file mode 100644 index 0000000..e4579da --- /dev/null +++ b/rotated-digits/README.md @@ -0,0 +1,20 @@ +

788. Rotated Digits

Easy


x is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone.

+ +

A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other (on this case they are rotated in a different direction, in other words 2 or 5 gets mirrored); 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.

+ +

Now given a positive number n, how many numbers x from 1 to n are good?

+ +
Example:
+Input: 10
+Output: 4
+Explanation: 
+There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
+Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.
+
+ +

Note:

+ +
    +
  • n will be in range [1, 10000].
  • +
+
\ No newline at end of file diff --git a/rotated-digits/rotated-digits.cpp b/rotated-digits/rotated-digits.cpp new file mode 100644 index 0000000..c346e5b --- /dev/null +++ b/rotated-digits/rotated-digits.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int rotatedDigits(int N) { + //3,4,7 invalid ->0 + //0,1,8 valid ->1 + //2,5,6,9 good ->2 + vector dp(N+1,0); + int cnt=0; + for(int i=0;i<=N;++i){ + if(i<10){ + if(i==0 || i==1 || i==8) dp[i]=1; + else if(i==2 || i==5 || i==6 || i==9) dp[i]=2,++cnt; + }else{ + if(dp[i/10]==1 && dp[i%10]==1) dp[i]=1; + else if(dp[i/10]>=1 && dp[i%10]>=1) dp[i]=2,++cnt; + } + } + return cnt; +} +}; \ No newline at end of file diff --git a/rotting-oranges/README.md b/rotting-oranges/README.md new file mode 100644 index 0000000..b4c408e --- /dev/null +++ b/rotting-oranges/README.md @@ -0,0 +1,43 @@ +

994. Rotting Oranges

Medium


You are given an m x n grid where each cell can have one of three values:

+ +
    +
  • 0 representing an empty cell,
  • +
  • 1 representing a fresh orange, or
  • +
  • 2 representing a rotten orange.
  • +
+ +

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

+ +

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

+ +

 

+

Example 1:

+ +
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
+Output: 4
+
+ +

Example 2:

+ +
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
+Output: -1
+Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
+
+ +

Example 3:

+ +
Input: grid = [[0,2]]
+Output: 0
+Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 10
  • +
  • grid[i][j] is 0, 1, or 2.
  • +
+
\ No newline at end of file diff --git a/rotting-oranges/rotting-oranges.cpp b/rotting-oranges/rotting-oranges.cpp new file mode 100644 index 0000000..02a2524 --- /dev/null +++ b/rotting-oranges/rotting-oranges.cpp @@ -0,0 +1,49 @@ +class Solution { +public: + int orangesRotting(vector>& grid) + { + + vector dir={-1,0,1,0,-1}; //used for finding all 4 adjacent coordinates + + int m=grid.size(); + int n=grid[0].size(); + + queue> q; + int fresh=0; //To keep track of all fresh oranges left + for(int i=0;i p=q.front(); + q.pop(); + for(int i=0;i<4;i++) + { + int r=p.first+dir[i]; + int c=p.second+dir[i+1]; + if(r>=0 && r=0 && c0) return -1; //if fresh>0 that means there are fresh oranges left + if(ans==-1) return 0; //we initialised with -1, so if there were no oranges it'd take 0 mins. + return ans; + + } +}; \ No newline at end of file diff --git a/same-tree/README.md b/same-tree/README.md new file mode 100644 index 0000000..9572f3d --- /dev/null +++ b/same-tree/README.md @@ -0,0 +1,31 @@ +

100. Same Tree

Easy


Given the roots of two binary trees p and q, write a function to check if they are the same or not.

+ +

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

+ +

 

+

Example 1:

+ +
Input: p = [1,2,3], q = [1,2,3]
+Output: true
+
+ +

Example 2:

+ +
Input: p = [1,2], q = [1,null,2]
+Output: false
+
+ +

Example 3:

+ +
Input: p = [1,2,1], q = [1,1,2]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in both trees is in the range [0, 100].
  • +
  • -104 <= Node.val <= 104
  • +
+
\ No newline at end of file diff --git a/same-tree/same-tree.cpp b/same-tree/same-tree.cpp new file mode 100644 index 0000000..614439b --- /dev/null +++ b/same-tree/same-tree.cpp @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if(p == NULL && q == NULL) + return true; + else if(p == NULL || q == NULL) + return false; + + if(p->val == q->val) + { + return isSameTree(p->left,q->left) && isSameTree(p->right,q->right); + } + else + return false; + } +}; \ No newline at end of file diff --git a/search-a-2d-matrix-ii/README.md b/search-a-2d-matrix-ii/README.md new file mode 100644 index 0000000..8f206be --- /dev/null +++ b/search-a-2d-matrix-ii/README.md @@ -0,0 +1,33 @@ +

240. Search a 2D Matrix II

Medium


Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties:

+ +
    +
  • Integers in each row are sorted in ascending from left to right.
  • +
  • Integers in each column are sorted in ascending from top to bottom.
  • +
+ +

 

+

Example 1:

+ +
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
+Output: true
+
+ +

Example 2:

+ +
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= n, m <= 300
  • +
  • -109 <= matrix[i][j] <= 109
  • +
  • All the integers in each row are sorted in ascending order.
  • +
  • All the integers in each column are sorted in ascending order.
  • +
  • -109 <= target <= 109
  • +
+
\ No newline at end of file diff --git a/search-a-2d-matrix-ii/search-a-2d-matrix-ii.cpp b/search-a-2d-matrix-ii/search-a-2d-matrix-ii.cpp new file mode 100644 index 0000000..9527e27 --- /dev/null +++ b/search-a-2d-matrix-ii/search-a-2d-matrix-ii.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + + int rows = matrix.size(); + int col = matrix[0].size(); + + int i = 0; + int j = col -1; + + while(i=0) + { + if(matrix[i][j] == target) + return true; + else if(matrix[i][j] > target) + { + j--; + } + else + i++; + + } + return false; + + } +}; \ No newline at end of file diff --git a/search-a-2d-matrix/README.md b/search-a-2d-matrix/README.md new file mode 100644 index 0000000..511073a --- /dev/null +++ b/search-a-2d-matrix/README.md @@ -0,0 +1,30 @@ +

74. Search a 2D Matrix

Medium


Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

+ +
    +
  • Integers in each row are sorted from left to right.
  • +
  • The first integer of each row is greater than the last integer of the previous row.
  • +
+ +

 

+

Example 1:

+ +
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
+Output: true
+
+ +

Example 2:

+ +
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • -104 <= matrix[i][j], target <= 104
  • +
+
\ No newline at end of file diff --git a/search-a-2d-matrix/search-a-2d-matrix.cpp b/search-a-2d-matrix/search-a-2d-matrix.cpp new file mode 100644 index 0000000..863097d --- /dev/null +++ b/search-a-2d-matrix/search-a-2d-matrix.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + + bool binarysearch(vector v,int s,int e,int target) + { + if(s<=e) + { + int m = (s+e)/2; + if(v[m] == target) + return true; + else if(v[m]>& matrix, int target) { + + int m = matrix.size(); + int n = matrix[0].size(); + + int i=0; + while(i matrix[i][n-1]) + { + i++; + } + if(i == m) + return false; + return binarysearch(matrix[i],0,n-1,target); + + + } +}; \ No newline at end of file diff --git a/search-in-rotated-sorted-array/README.md b/search-in-rotated-sorted-array/README.md new file mode 100644 index 0000000..850441c --- /dev/null +++ b/search-in-rotated-sorted-array/README.md @@ -0,0 +1,30 @@ +

33. Search in Rotated Sorted Array

Medium


There is an integer array nums sorted in ascending order (with distinct values).

+ +

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

+ +

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

+ +

You must write an algorithm with O(log n) runtime complexity.

+ +

 

+

Example 1:

+
Input: nums = [4,5,6,7,0,1,2], target = 0
+Output: 4
+

Example 2:

+
Input: nums = [4,5,6,7,0,1,2], target = 3
+Output: -1
+

Example 3:

+
Input: nums = [1], target = 0
+Output: -1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5000
  • +
  • -104 <= nums[i] <= 104
  • +
  • All values of nums are unique.
  • +
  • nums is an ascending array that is possibly rotated.
  • +
  • -104 <= target <= 104
  • +
+
\ No newline at end of file diff --git a/search-in-rotated-sorted-array/search-in-rotated-sorted-array.cpp b/search-in-rotated-sorted-array/search-in-rotated-sorted-array.cpp new file mode 100644 index 0000000..175d78e --- /dev/null +++ b/search-in-rotated-sorted-array/search-in-rotated-sorted-array.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int search(vector& nums, int target) { + + int low = 0; + int high = nums.size()-1; + + while(low <= high) + { + int mid = (high+low)/2; + if(nums[mid] == target) + { + return mid; + } + else if(nums[mid] >= nums[low] ) + { + if( target >= nums[low] && target <= nums[mid]) + high = mid-1; + else + low = mid+1; + } + else if(nums[mid] <= nums[high] ) + { + if(target >= nums[mid] && target <= nums[high]) + low = mid + 1; + else + high = mid-1; + } + + } + return -1; + } +}; \ No newline at end of file diff --git a/search-insert-position/README.md b/search-insert-position/README.md new file mode 100644 index 0000000..7e57581 --- /dev/null +++ b/search-insert-position/README.md @@ -0,0 +1,31 @@ +

35. Search Insert Position

Easy


Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

+ +

You must write an algorithm with O(log n) runtime complexity.

+ +

 

+

Example 1:

+
Input: nums = [1,3,5,6], target = 5
+Output: 2
+

Example 2:

+
Input: nums = [1,3,5,6], target = 2
+Output: 1
+

Example 3:

+
Input: nums = [1,3,5,6], target = 7
+Output: 4
+

Example 4:

+
Input: nums = [1,3,5,6], target = 0
+Output: 0
+

Example 5:

+
Input: nums = [1], target = 0
+Output: 0
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums contains distinct values sorted in ascending order.
  • +
  • -104 <= target <= 104
  • +
+
\ No newline at end of file diff --git a/search-insert-position/search-insert-position.cpp b/search-insert-position/search-insert-position.cpp new file mode 100644 index 0000000..985a28b --- /dev/null +++ b/search-insert-position/search-insert-position.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + int searchInsert(vector& nums, int target) { + return lower_bound(nums.begin(),nums.end(),target)-nums.begin(); + } +}; \ No newline at end of file diff --git a/second-highest-salary/README.md b/second-highest-salary/README.md new file mode 100644 index 0000000..f034e2c --- /dev/null +++ b/second-highest-salary/README.md @@ -0,0 +1,20 @@ +

176. Second Highest Salary

Easy


Write a SQL query to get the second highest salary from the Employee table.

+ +
+----+--------+
+| Id | Salary |
++----+--------+
+| 1  | 100    |
+| 2  | 200    |
+| 3  | 300    |
++----+--------+
+
+ +

For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

+ +
+---------------------+
+| SecondHighestSalary |
++---------------------+
+| 200                 |
++---------------------+
+
+
\ No newline at end of file diff --git a/second-highest-salary/second-highest-salary.sql b/second-highest-salary/second-highest-salary.sql new file mode 100644 index 0000000..6b60396 --- /dev/null +++ b/second-highest-salary/second-highest-salary.sql @@ -0,0 +1,3 @@ +# Write your MySQL query statement below + +SELECT MAX(Salary) as SecondHighestSalary FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee); diff --git a/set-matrix-zeroes/README.md b/set-matrix-zeroes/README.md new file mode 100644 index 0000000..b2ffdac --- /dev/null +++ b/set-matrix-zeroes/README.md @@ -0,0 +1,36 @@ +

73. Set Matrix Zeroes

Medium


Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix.

+ +

You must do it in place.

+ +

 

+

Example 1:

+ +
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
+Output: [[1,0,1],[0,0,0],[1,0,1]]
+
+ +

Example 2:

+ +
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
+Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[0].length
  • +
  • 1 <= m, n <= 200
  • +
  • -231 <= matrix[i][j] <= 231 - 1
  • +
+ +

 

+

Follow up:

+ +
    +
  • A straightforward solution using O(mn) space is probably a bad idea.
  • +
  • A simple improvement uses O(m + n) space, but still not the best solution.
  • +
  • Could you devise a constant space solution?
  • +
+
\ No newline at end of file diff --git a/set-matrix-zeroes/set-matrix-zeroes.cpp b/set-matrix-zeroes/set-matrix-zeroes.cpp new file mode 100644 index 0000000..5d03c66 --- /dev/null +++ b/set-matrix-zeroes/set-matrix-zeroes.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + void setZeroes(vector>& matrix) { + + int col = 1; + int m = matrix.size(); + int n = matrix[0].size(); + + for(int i=0;i=0;i--) + { + for(int j=n-1;j>=1;j--) + { + if(matrix[i][0] == 0 || matrix[0][j] == 0) + matrix[i][j] = 0; + } + if(col == 0) + matrix[i][0] = 0; + } + + } +}; \ No newline at end of file diff --git a/shuffle-an-array/README.md b/shuffle-an-array/README.md new file mode 100644 index 0000000..51662c5 --- /dev/null +++ b/shuffle-an-array/README.md @@ -0,0 +1,39 @@ +

384. Shuffle an Array

Medium


Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.

+ +

Implement the Solution class:

+ +
    +
  • Solution(int[] nums) Initializes the object with the integer array nums.
  • +
  • int[] reset() Resets the array to its original configuration and returns it.
  • +
  • int[] shuffle() Returns a random shuffling of the array.
  • +
+ +

 

+

Example 1:

+ +
Input
+["Solution", "shuffle", "reset", "shuffle"]
+[[[1, 2, 3]], [], [], []]
+Output
+[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
+
+Explanation
+Solution solution = new Solution([1, 2, 3]);
+solution.shuffle();    // Shuffle the array [1,2,3] and return its result.
+                       // Any permutation of [1,2,3] must be equally likely to be returned.
+                       // Example: return [3, 1, 2]
+solution.reset();      // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]
+solution.shuffle();    // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]
+
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 200
  • +
  • -106 <= nums[i] <= 106
  • +
  • All the elements of nums are unique.
  • +
  • At most 5 * 104 calls in total will be made to reset and shuffle.
  • +
+
\ No newline at end of file diff --git a/shuffle-an-array/shuffle-an-array.cpp b/shuffle-an-array/shuffle-an-array.cpp new file mode 100644 index 0000000..4228638 --- /dev/null +++ b/shuffle-an-array/shuffle-an-array.cpp @@ -0,0 +1,22 @@ +class Solution { + vector nums; +public: + Solution(vector nums) { + this->nums = nums; + } + + /** Resets the array to its original configuration and return it. */ + vector reset() { + return nums; + } + + /** Returns a random shuffling of the array. */ + vector shuffle() { + vector result(nums); + for (int i = 0;i < result.size();i++) { + int pos = rand()%(result.size()-i); + swap(result[i+pos], result[i]); + } + return result; + } +}; \ No newline at end of file diff --git a/single-element-in-a-sorted-array/README.md b/single-element-in-a-sorted-array/README.md new file mode 100644 index 0000000..b014b19 --- /dev/null +++ b/single-element-in-a-sorted-array/README.md @@ -0,0 +1,22 @@ +

540. Single Element in a Sorted Array

Medium


You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.

+ +

Return the single element that appears only once.

+ +

Your solution must run in O(log n) time and O(1) space.

+ +

 

+

Example 1:

+
Input: nums = [1,1,2,3,3,4,4,8,8]
+Output: 2
+

Example 2:

+
Input: nums = [3,3,7,7,10,11,11]
+Output: 10
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 0 <= nums[i] <= 105
  • +
+
\ No newline at end of file diff --git a/single-element-in-a-sorted-array/single-element-in-a-sorted-array.cpp b/single-element-in-a-sorted-array/single-element-in-a-sorted-array.cpp new file mode 100644 index 0000000..e051a62 --- /dev/null +++ b/single-element-in-a-sorted-array/single-element-in-a-sorted-array.cpp @@ -0,0 +1,58 @@ +class Solution { +public: + + int helper(vector& nums,int l ,int h) + { + while(l=0 && nums[mid] == nums[mid-1]) + { + int a = helper(nums,l,mid-2); + if(a != -1) + return a; + + int b = helper(nums,mid+1,h); + if(b != -1) + return b; + + return -1; + } + else if((mid+1 < nums.size() && nums[mid] == nums[mid+1] )) + { + int a = helper(nums,l,mid-1); + if(a != -1) + return a; + + int b = helper(nums,mid+2,h); + if(b != -1) + return b; + + return -1; + } + else + { + return nums[mid]; + } + + } + + if(l == h) + return nums[l]; + return -1; + + } + int singleNonDuplicate(vector& nums) { + + if(nums.size()==1) + return nums[0]; + if(nums.size() == 2) + return -1; + + int low = 0; + int high = nums.size()-1; + + return helper(nums,low,high); + } +}; \ No newline at end of file diff --git a/single-number-iii/README.md b/single-number-iii/README.md new file mode 100644 index 0000000..d8afd72 --- /dev/null +++ b/single-number-iii/README.md @@ -0,0 +1,33 @@ +

260. Single Number III

Medium


Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.

+ +

You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,1,3,2,5]
+Output: [3,5]
+Explanation:  [5, 3] is also a valid answer.
+
+ +

Example 2:

+ +
Input: nums = [-1,0]
+Output: [-1,0]
+
+ +

Example 3:

+ +
Input: nums = [0,1]
+Output: [1,0]
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 3 * 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • Each integer in nums will appear twice, only two integers will appear once.
  • +
+
\ No newline at end of file diff --git a/single-number-iii/single-number-iii.cpp b/single-number-iii/single-number-iii.cpp new file mode 100644 index 0000000..e32301e --- /dev/null +++ b/single-number-iii/single-number-iii.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + + vector singleNumber(vector& nums) { + int n = nums.size(); + vectorres{}; + int bucket1{}, bucket2{}; + long long int xr{}; + + //Calculate xor of every number so that xr will have (x^y) + for(int i{}; i1629. Slowest Key

Easy


A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.

+ +

You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released.

+ +

The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0].

+ +

Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration.

+ +

Return the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses.

+ +

 

+

Example 1:

+ +
Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd"
+Output: "c"
+Explanation: The keypresses were as follows:
+Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
+Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
+Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
+Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
+The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
+'c' is lexicographically larger than 'b', so the answer is 'c'.
+
+ +

Example 2:

+ +
Input: releaseTimes = [12,23,36,46,62], keysPressed = "spuda"
+Output: "a"
+Explanation: The keypresses were as follows:
+Keypress for 's' had a duration of 12.
+Keypress for 'p' had a duration of 23 - 12 = 11.
+Keypress for 'u' had a duration of 36 - 23 = 13.
+Keypress for 'd' had a duration of 46 - 36 = 10.
+Keypress for 'a' had a duration of 62 - 46 = 16.
+The longest of these was the keypress for 'a' with duration 16.
+ +

 

+

Constraints:

+ +
    +
  • releaseTimes.length == n
  • +
  • keysPressed.length == n
  • +
  • 2 <= n <= 1000
  • +
  • 1 <= releaseTimes[i] <= 109
  • +
  • releaseTimes[i] < releaseTimes[i+1]
  • +
  • keysPressed contains only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/slowest-key/slowest-key.cpp b/slowest-key/slowest-key.cpp new file mode 100644 index 0000000..be2fef0 --- /dev/null +++ b/slowest-key/slowest-key.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + char slowestKey(vector& times, string keys) { + int max_p = times[0], res = keys[0]; + for (auto i = 1; i < times.size(); ++i) + if (max_p <= times[i] - times[i - 1]) { + if (max_p == times[i] - times[i - 1]) + res = max((char)res, keys[i]); + else + res = keys[i]; + max_p = times[i] - times[i - 1]; + } + return res; +} +}; \ No newline at end of file diff --git a/smallest-integer-divisible-by-k/README.md b/smallest-integer-divisible-by-k/README.md new file mode 100644 index 0000000..b5ec720 --- /dev/null +++ b/smallest-integer-divisible-by-k/README.md @@ -0,0 +1,35 @@ +

1015. Smallest Integer Divisible by K

Medium


Given a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1.

+ +

Return the length of n. If there is no such n, return -1.

+ +

Note: n may not fit in a 64-bit signed integer.

+ +

 

+

Example 1:

+ +
Input: k = 1
+Output: 1
+Explanation: The smallest answer is n = 1, which has length 1.
+
+ +

Example 2:

+ +
Input: k = 2
+Output: -1
+Explanation: There is no such positive integer n divisible by 2.
+
+ +

Example 3:

+ +
Input: k = 3
+Output: 3
+Explanation: The smallest answer is n = 111, which has length 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= 105
  • +
+
\ No newline at end of file diff --git a/smallest-integer-divisible-by-k/smallest-integer-divisible-by-k.cpp b/smallest-integer-divisible-by-k/smallest-integer-divisible-by-k.cpp new file mode 100644 index 0000000..a33b530 --- /dev/null +++ b/smallest-integer-divisible-by-k/smallest-integer-divisible-by-k.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int smallestRepunitDivByK(int K) { + for (int r = 0, N = 1; N <= K; ++N) + if ((r = (r * 10 + 1) % K) == 0) + return N; + return -1; + } +}; \ No newline at end of file diff --git a/sort-an-array/README.md b/sort-an-array/README.md new file mode 100644 index 0000000..95ef07f --- /dev/null +++ b/sort-an-array/README.md @@ -0,0 +1,18 @@ +

912. Sort an Array

Medium


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

+ +

 

+

Example 1:

+
Input: nums = [5,2,3,1]
+Output: [1,2,3,5]
+

Example 2:

+
Input: nums = [5,1,1,2,0,0]
+Output: [0,0,1,1,2,5]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • -5 * 104 <= nums[i] <= 5 * 104
  • +
+
\ No newline at end of file diff --git a/sort-an-array/sort-an-array.cpp b/sort-an-array/sort-an-array.cpp new file mode 100644 index 0000000..29a1be1 --- /dev/null +++ b/sort-an-array/sort-an-array.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + vector sortArray(vector& nums) { + + stable_sort(nums.begin(), nums.end()); + return nums; + } +}; \ No newline at end of file diff --git a/sort-characters-by-frequency/README.md b/sort-characters-by-frequency/README.md new file mode 100644 index 0000000..6dfa169 --- /dev/null +++ b/sort-characters-by-frequency/README.md @@ -0,0 +1,37 @@ +

451. Sort Characters By Frequency

Medium


Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

+ +

Return the sorted string. If there are multiple answers, return any of them.

+ +

 

+

Example 1:

+ +
Input: s = "tree"
+Output: "eert"
+Explanation: 'e' appears twice while 'r' and 't' both appear once.
+So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
+
+ +

Example 2:

+ +
Input: s = "cccaaa"
+Output: "aaaccc"
+Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
+Note that "cacaca" is incorrect, as the same characters must be together.
+
+ +

Example 3:

+ +
Input: s = "Aabb"
+Output: "bbAa"
+Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
+Note that 'A' and 'a' are treated as two different characters.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 105
  • +
  • s consists of uppercase and lowercase English letters and digits.
  • +
+
\ No newline at end of file diff --git a/sort-characters-by-frequency/sort-characters-by-frequency.cpp b/sort-characters-by-frequency/sort-characters-by-frequency.cpp new file mode 100644 index 0000000..2f6e63b --- /dev/null +++ b/sort-characters-by-frequency/sort-characters-by-frequency.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + string frequencySort(string s) { + int counts[256] = {0}; + for (char ch : s) + ++counts[ch]; + sort(s.begin(), s.end(), [&](char a, char b) { + return counts[a] > counts[b] || (counts[a] == counts[b] && a < b); + }); + return s; + } +}; \ No newline at end of file diff --git a/sort-colors/README.md b/sort-colors/README.md new file mode 100644 index 0000000..e79cb45 --- /dev/null +++ b/sort-colors/README.md @@ -0,0 +1,32 @@ +

75. Sort Colors

Medium


Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

+ +

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

+ +

You must solve this problem without using the library's sort function.

+ +

 

+

Example 1:

+
Input: nums = [2,0,2,1,1,0]
+Output: [0,0,1,1,2,2]
+

Example 2:

+
Input: nums = [2,0,1]
+Output: [0,1,2]
+

Example 3:

+
Input: nums = [0]
+Output: [0]
+

Example 4:

+
Input: nums = [1]
+Output: [1]
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 300
  • +
  • nums[i] is 0, 1, or 2.
  • +
+ +

 

+

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

+
\ No newline at end of file diff --git a/sort-colors/sort-colors.cpp b/sort-colors/sort-colors.cpp new file mode 100644 index 0000000..6874464 --- /dev/null +++ b/sort-colors/sort-colors.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + void sortColors(vector& nums) { + + int left = 0; + int mid = 0; + int right = nums.size()-1; + + while(mid<=right) + { + if(nums[mid] == 0) + { + swap(nums[mid],nums[left]); + mid++; + left++; + } + else if(nums[mid] == 1) + { + mid++; + } + else + { + swap(nums[mid],nums[right]); + right--; + + } + + } + + + } +}; \ No newline at end of file diff --git a/sort-integers-by-the-number-of-1-bits/README.md b/sort-integers-by-the-number-of-1-bits/README.md new file mode 100644 index 0000000..978e591 --- /dev/null +++ b/sort-integers-by-the-number-of-1-bits/README.md @@ -0,0 +1,49 @@ +

1356. Sort Integers by The Number of 1 Bits

Easy


Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.

+ +

Return the sorted array.

+ +

 

+

Example 1:

+ +
Input: arr = [0,1,2,3,4,5,6,7,8]
+Output: [0,1,2,4,8,3,5,6,7]
+Explantion: [0] is the only integer with 0 bits.
+[1,2,4,8] all have 1 bit.
+[3,5,6] have 2 bits.
+[7] has 3 bits.
+The sorted array by bits is [0,1,2,4,8,3,5,6,7]
+
+ +

Example 2:

+ +
Input: arr = [1024,512,256,128,64,32,16,8,4,2,1]
+Output: [1,2,4,8,16,32,64,128,256,512,1024]
+Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.
+
+ +

Example 3:

+ +
Input: arr = [10000,10000]
+Output: [10000,10000]
+
+ +

Example 4:

+ +
Input: arr = [2,3,5,7,11,13,17,19]
+Output: [2,3,5,17,7,11,13,19]
+
+ +

Example 5:

+ +
Input: arr = [10,100,1000,10000]
+Output: [10,100,10000,1000]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 500
  • +
  • 0 <= arr[i] <= 10^4
  • +
+
\ No newline at end of file diff --git a/spiral-matrix/README.md b/spiral-matrix/README.md new file mode 100644 index 0000000..02d4fd6 --- /dev/null +++ b/spiral-matrix/README.md @@ -0,0 +1,25 @@ +

54. Spiral Matrix

Medium


Given an m x n matrix, return all elements of the matrix in spiral order.

+ +

 

+

Example 1:

+ +
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
+Output: [1,2,3,6,9,8,7,4,5]
+
+ +

Example 2:

+ +
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
+Output: [1,2,3,4,8,12,11,10,9,5,6,7]
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 10
  • +
  • -100 <= matrix[i][j] <= 100
  • +
+
\ No newline at end of file diff --git a/spiral-matrix/spiral-matrix.cpp b/spiral-matrix/spiral-matrix.cpp new file mode 100644 index 0000000..cadb576 --- /dev/null +++ b/spiral-matrix/spiral-matrix.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + vector spiralOrder(vector>& matrix) { + int m = matrix.size(), n = m ? matrix[0].size() : 0, u = 0, d = m - 1, l = 0, r = n - 1, p = 0; + vector order(m * n); + while (u <= d && l <= r) { + for (int col = l; col <= r; col++) { + order[p++] = matrix[u][col]; + } + if (++u > d) { + break; + } + for (int row = u; row <= d; row++) { + order[p++] = matrix[row][r]; + } + if (--r < l) { + break; + } + for (int col = r; col >= l; col--) { + order[p++] = matrix[d][col]; + } + if (--d < u) { + break; + } + for (int row = d; row >= u; row--) { + order[p++] = matrix[row][l]; + } + if (l++ > r) { + break; + } + } + //order.push_back(1); + return order; + } +}; \ No newline at end of file diff --git a/sqrtx/README.md b/sqrtx/README.md new file mode 100644 index 0000000..c25fd96 --- /dev/null +++ b/sqrtx/README.md @@ -0,0 +1,26 @@ +

69. Sqrt(x)

Easy


Given a non-negative integer x, compute and return the square root of x.

+ +

Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

+ +

Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.

+ +

 

+

Example 1:

+ +
Input: x = 4
+Output: 2
+
+ +

Example 2:

+ +
Input: x = 8
+Output: 2
+Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
+ +

 

+

Constraints:

+ +
    +
  • 0 <= x <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/sqrtx/sqrtx.cpp b/sqrtx/sqrtx.cpp new file mode 100644 index 0000000..070137d --- /dev/null +++ b/sqrtx/sqrtx.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + int mySqrt(int x) { + return sqrt(x); + } +}; \ No newline at end of file diff --git a/squares-of-a-sorted-array/README.md b/squares-of-a-sorted-array/README.md new file mode 100644 index 0000000..19d5498 --- /dev/null +++ b/squares-of-a-sorted-array/README.md @@ -0,0 +1,28 @@ +

977. Squares of a Sorted Array

Easy


Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

+ +

 

+

Example 1:

+ +
Input: nums = [-4,-1,0,3,10]
+Output: [0,1,9,16,100]
+Explanation: After squaring, the array becomes [16,1,0,9,100].
+After sorting, it becomes [0,1,9,16,100].
+
+ +

Example 2:

+ +
Input: nums = [-7,-3,2,3,11]
+Output: [4,9,9,49,121]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums is sorted in non-decreasing order.
  • +
+ +

 

+Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?
\ No newline at end of file diff --git a/squares-of-a-sorted-array/squares-of-a-sorted-array.cpp b/squares-of-a-sorted-array/squares-of-a-sorted-array.cpp new file mode 100644 index 0000000..58d9bf5 --- /dev/null +++ b/squares-of-a-sorted-array/squares-of-a-sorted-array.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + vector sortedSquares(vector& nums) { + + for(int i=0;i877. Stone Game

Medium


Alex and Lee play a game with piles of stones.  There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].

+ +

The objective of the game is to end with the most stones.  The total number of stones is odd, so there are no ties.

+ +

Alex and Lee take turns, with Alex starting first.  Each turn, a player takes the entire pile of stones from either the beginning or the end of the row.  This continues until there are no more piles left, at which point the person with the most stones wins.

+ +

Assuming Alex and Lee play optimally, return True if and only if Alex wins the game.

+ +

 

+

Example 1:

+ +
Input: piles = [5,3,4,5]
+Output: true
+Explanation: 
+Alex starts first, and can only take the first 5 or the last 5.
+Say he takes the first 5, so that the row becomes [3, 4, 5].
+If Lee takes 3, then the board is [4, 5], and Alex takes 5 to win with 10 points.
+If Lee takes the last 5, then the board is [3, 4], and Alex takes 4 to win with 9 points.
+This demonstrated that taking the first 5 was a winning move for Alex, so we return true.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= piles.length <= 500
  • +
  • piles.length is even.
  • +
  • 1 <= piles[i] <= 500
  • +
  • sum(piles) is odd.
  • +
+
\ No newline at end of file diff --git a/stone-game/stone-game.cpp b/stone-game/stone-game.cpp new file mode 100644 index 0000000..fa3582d --- /dev/null +++ b/stone-game/stone-game.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + bool stoneGame(vector& p) { + vector dp = p; + for (int d = 1; d < p.size(); d++) + for (int i = 0; i < p.size() - d; i++) + dp[i] = max(p[i] - dp[i + 1], p[i + d] - dp[i]); + return dp[0] > 0; + } +}; \ No newline at end of file diff --git a/subsets/README.md b/subsets/README.md new file mode 100644 index 0000000..a2af7b4 --- /dev/null +++ b/subsets/README.md @@ -0,0 +1,26 @@ +

78. Subsets

Medium


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3]
+Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
+
+ +

Example 2:

+ +
Input: nums = [0]
+Output: [[],[0]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 10
  • +
  • -10 <= nums[i] <= 10
  • +
  • All the numbers of nums are unique.
  • +
+
\ No newline at end of file diff --git a/subsets/subsets.cpp b/subsets/subsets.cpp new file mode 100644 index 0000000..1bc88f0 --- /dev/null +++ b/subsets/subsets.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + vector> ans; + + void subsets_helper(int index,vector & nums,vector &subset) + { + + if(index == nums.size()) + { + ans.push_back(subset); + return; + } + subset.push_back(nums[index]); + subsets_helper(index+1,nums,subset); + subset.pop_back(); + subsets_helper(index+1,nums,subset); + + return; + +// ans.push_back(subset); + +// for(int i= index;i> subsets(vector& nums) { + vector subset; + subsets_helper(0,nums,subset); + return ans; + } +}; \ No newline at end of file diff --git a/sum-of-left-leaves/README.md b/sum-of-left-leaves/README.md new file mode 100644 index 0000000..b9e7ba5 --- /dev/null +++ b/sum-of-left-leaves/README.md @@ -0,0 +1,24 @@ +

404. Sum of Left Leaves

Easy


Given the root of a binary tree, return the sum of all left leaves.

+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: 24
+Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.
+
+ +

Example 2:

+ +
Input: root = [1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • -1000 <= Node.val <= 1000
  • +
+
\ No newline at end of file diff --git a/sum-of-left-leaves/sum-of-left-leaves.cpp b/sum-of-left-leaves/sum-of-left-leaves.cpp new file mode 100644 index 0000000..063286b --- /dev/null +++ b/sum-of-left-leaves/sum-of-left-leaves.cpp @@ -0,0 +1,28 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + //20 + int sum = 0; + int sumOfLeftLeaves(TreeNode* root) { + dfs(root); + return sum; + } + void dfs(TreeNode* root){ + if(root == nullptr)return; + dfs(root->left); + dfs(root->right); + if(root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr) { + sum += root->left->val; + } + } +}; \ No newline at end of file diff --git a/sum-of-nodes-with-even-valued-grandparent/README.md b/sum-of-nodes-with-even-valued-grandparent/README.md new file mode 100644 index 0000000..de1a759 --- /dev/null +++ b/sum-of-nodes-with-even-valued-grandparent/README.md @@ -0,0 +1,21 @@ +

1315. Sum of Nodes with Even-Valued Grandparent

Medium


Given a binary tree, return the sum of values of nodes with even-valued grandparent.  (A grandparent of a node is the parent of its parent, if it exists.)

+ +

If there are no nodes with an even-valued grandparent, return 0.

+ +

 

+

Example 1:

+ +

+ +
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
+Output: 18
+Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is between 1 and 10^4.
  • +
  • The value of nodes is between 1 and 100.
  • +
\ No newline at end of file diff --git a/sum-of-nodes-with-even-valued-grandparent/sum-of-nodes-with-even-valued-grandparent.cpp b/sum-of-nodes-with-even-valued-grandparent/sum-of-nodes-with-even-valued-grandparent.cpp new file mode 100644 index 0000000..31cee64 --- /dev/null +++ b/sum-of-nodes-with-even-valued-grandparent/sum-of-nodes-with-even-valued-grandparent.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int s=0; + int sumEvenGrandparent(TreeNode* root) { + fun(root,NULL,NULL); //passing the root node with it's parent & grandparent as NULL + return s; + } + void fun(TreeNode* root,TreeNode* parent,TreeNode* grandparent) + { + if(!root) return; //if root is null then return + if(grandparent && grandparent->val%2==0) //checking even valued grandparent existance + s+=root->val; + fun(root->left,root,parent); //calling function for left subtree where root will be the parent & previous parent will act as the grandparent for left subtree of the root. + fun(root->right,root,parent); //same for right subtree + } +}; \ No newline at end of file diff --git a/sum-of-square-numbers/README.md b/sum-of-square-numbers/README.md new file mode 100644 index 0000000..0575c71 --- /dev/null +++ b/sum-of-square-numbers/README.md @@ -0,0 +1,41 @@ +

633. Sum of Square Numbers

Medium


Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.

+ +

 

+

Example 1:

+ +
Input: c = 5
+Output: true
+Explanation: 1 * 1 + 2 * 2 = 5
+
+ +

Example 2:

+ +
Input: c = 3
+Output: false
+
+ +

Example 3:

+ +
Input: c = 4
+Output: true
+
+ +

Example 4:

+ +
Input: c = 2
+Output: true
+
+ +

Example 5:

+ +
Input: c = 1
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= c <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/sum-of-square-numbers/sum-of-square-numbers.cpp b/sum-of-square-numbers/sum-of-square-numbers.cpp new file mode 100644 index 0000000..6ccf56a --- /dev/null +++ b/sum-of-square-numbers/sum-of-square-numbers.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + bool judgeSquareSum(int c) + { + if(c<0) + return false; + long int left=0,right=sqrt(c); + while(left<=right) + { + long int cur=left*left+right*right; + if(curc) + right--; + else + return true; + } + return false; + } +}; \ No newline at end of file diff --git a/sum-root-to-leaf-numbers/README.md b/sum-root-to-leaf-numbers/README.md new file mode 100644 index 0000000..029935e --- /dev/null +++ b/sum-root-to-leaf-numbers/README.md @@ -0,0 +1,43 @@ +

129. Sum Root to Leaf Numbers

Medium


You are given the root of a binary tree containing digits from 0 to 9 only.

+ +

Each root-to-leaf path in the tree represents a number.

+ +
    +
  • For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
  • +
+ +

Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.

+ +

A leaf node is a node with no children.

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3]
+Output: 25
+Explanation:
+The root-to-leaf path 1->2 represents the number 12.
+The root-to-leaf path 1->3 represents the number 13.
+Therefore, sum = 12 + 13 = 25.
+
+ +

Example 2:

+ +
Input: root = [4,9,0,5,1]
+Output: 1026
+Explanation:
+The root-to-leaf path 4->9->5 represents the number 495.
+The root-to-leaf path 4->9->1 represents the number 491.
+The root-to-leaf path 4->0 represents the number 40.
+Therefore, sum = 495 + 491 + 40 = 1026.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • 0 <= Node.val <= 9
  • +
  • The depth of the tree will not exceed 10.
  • +
+
\ No newline at end of file diff --git a/surrounded-regions/README.md b/surrounded-regions/README.md new file mode 100644 index 0000000..56830b7 --- /dev/null +++ b/surrounded-regions/README.md @@ -0,0 +1,28 @@ +

130. Surrounded Regions

Medium


Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.

+ +

A region is captured by flipping all 'O's into 'X's in that surrounded region.

+ +

 

+

Example 1:

+ +
Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
+Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
+Explanation: Surrounded regions should not be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.
+
+ +

Example 2:

+ +
Input: board = [["X"]]
+Output: [["X"]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == board.length
  • +
  • n == board[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • board[i][j] is 'X' or 'O'.
  • +
+
\ No newline at end of file diff --git a/surrounded-regions/surrounded-regions.cpp b/surrounded-regions/surrounded-regions.cpp new file mode 100644 index 0000000..ebecf89 --- /dev/null +++ b/surrounded-regions/surrounded-regions.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + void solve(vector>& board) { + int i,j; + int row=board.size(); + if(!row) + return; + int col=board[0].size(); + + for(i=0;i1) + check(board,i,col-1,row,col); + } + for(j=1;j+11) + check(board,row-1,j,row,col); + } + for(i=0;i >&vec,int i,int j,int row,int col){ + if(vec[i][j]=='O'){ + vec[i][j]='1'; + if(i>1) + check(vec,i-1,j,row,col); + if(j>1) + check(vec,i,j-1,row,col); + if(i+1101. Symmetric Tree

Easy


Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

+ +

 

+

Example 1:

+ +
Input: root = [1,2,2,3,4,4,3]
+Output: true
+
+ +

Example 2:

+ +
Input: root = [1,2,2,null,3,null,3]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+Follow up: Could you solve it both recursively and iteratively?
\ No newline at end of file diff --git a/three-equal-parts/README.md b/three-equal-parts/README.md new file mode 100644 index 0000000..b62e24d --- /dev/null +++ b/three-equal-parts/README.md @@ -0,0 +1,34 @@ +

927. Three Equal Parts

Hard


You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value.

+ +

If it is possible, return any [i, j] with i + 1 < j, such that:

+ +
    +
  • arr[0], arr[1], ..., arr[i] is the first part,
  • +
  • arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and
  • +
  • arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.
  • +
  • All three parts have equal binary values.
  • +
+ +

If it is not possible, return [-1, -1].

+ +

Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.

+ +

 

+

Example 1:

+
Input: arr = [1,0,1,0,1]
+Output: [0,3]
+

Example 2:

+
Input: arr = [1,1,0,1,1]
+Output: [-1,-1]
+

Example 3:

+
Input: arr = [1,1,0,0,1]
+Output: [0,2]
+
+

 

+

Constraints:

+ +
    +
  • 3 <= arr.length <= 3 * 104
  • +
  • arr[i] is 0 or 1
  • +
+
\ No newline at end of file diff --git a/three-equal-parts/three-equal-parts.cpp b/three-equal-parts/three-equal-parts.cpp new file mode 100644 index 0000000..39463a2 --- /dev/null +++ b/three-equal-parts/three-equal-parts.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vector threeEqualParts(vector& A) { + vector dp; + for(int i = 0 ; i < A.size(); i++) // this loop is used to store the index of all 1s + if(A[i]) dp.push_back(i); + if(dp.size() % 3) return {-1, -1}; // if the number of 1s cannot be devided perfectly by 3, the input is invalid + if(dp.empty()) return {0,2}; // if the number of 1 is zero, then it is natually valid, return {0, 2} + int l1 = 0, l2 = dp.size() / 3, l3 = l2 * 2; //if we want to devide into 3 parts, the distribution pattern of 1s in three parts should be the same + for(int i = 1; i < l2; i++ ) { + int diff = dp[i] - dp[i-1]; + if(dp[l2+i] - dp[l2+i-1] != diff || dp[l3+i] - dp[l3+i-1] != diff) //unmatched pattern + return {-1, -1}; + } + int tail0 = A.size() - dp.back(); // calculate how many 0s tail + if(dp[l3] - dp[l3-1] < tail0 || dp[l2] - dp[l2-1] < tail0) return {-1,-1};// all three parts should tail with the same number of 0s with that in the last part + return {dp[l2-1] + tail0 - 1, dp[l3-1] + tail0}; + } +}; \ No newline at end of file diff --git a/total-hamming-distance/README.md b/total-hamming-distance/README.md new file mode 100644 index 0000000..bf3c00a --- /dev/null +++ b/total-hamming-distance/README.md @@ -0,0 +1,30 @@ +

477. Total Hamming Distance

Medium


The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

+ +

Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.

+ +

 

+

Example 1:

+ +
Input: nums = [4,14,2]
+Output: 6
+Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
+showing the four bits relevant in this case).
+The answer will be:
+HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
+
+ +

Example 2:

+ +
Input: nums = [4,14,4]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • 0 <= nums[i] <= 109
  • +
  • The answer for the given input will fit in a 32-bit integer.
  • +
+
\ No newline at end of file diff --git a/trapping-rain-water/README.md b/trapping-rain-water/README.md new file mode 100644 index 0000000..b57dde7 --- /dev/null +++ b/trapping-rain-water/README.md @@ -0,0 +1,25 @@ +

42. Trapping Rain Water

Hard


Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

+ +

 

+

Example 1:

+ +
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
+Output: 6
+Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
+
+ +

Example 2:

+ +
Input: height = [4,2,0,3,2,5]
+Output: 9
+
+ +

 

+

Constraints:

+ +
    +
  • n == height.length
  • +
  • 1 <= n <= 2 * 104
  • +
  • 0 <= height[i] <= 105
  • +
+
\ No newline at end of file diff --git a/trapping-rain-water/trapping-rain-water.cpp b/trapping-rain-water/trapping-rain-water.cpp new file mode 100644 index 0000000..4739bc5 --- /dev/null +++ b/trapping-rain-water/trapping-rain-water.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int trap(vector& height) { + + if(height.size()<=2) + return 0; + int n = height.size(); + int l = 0; + int r = n-1; + int ans = 0; + int lmax = 0; + int rmax = 0; + + while(r>=l) + { + if(lmax>=rmax) + { + ans += max(0,rmax-height[r]); + rmax = max(rmax,height[r]); + r--; + } + else + { + ans += max(0,lmax-height[l]); + lmax = max(lmax,height[l]); + l++; + } + + } + return ans; + } +}; \ No newline at end of file diff --git a/triangle/README.md b/triangle/README.md new file mode 100644 index 0000000..24ab426 --- /dev/null +++ b/triangle/README.md @@ -0,0 +1,35 @@ +

120. Triangle

Medium


Given a triangle array, return the minimum path sum from top to bottom.

+ +

For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.

+ +

 

+

Example 1:

+ +
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
+Output: 11
+Explanation: The triangle looks like:
+   2
+  3 4
+ 6 5 7
+4 1 8 3
+The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
+
+ +

Example 2:

+ +
Input: triangle = [[-10]]
+Output: -10
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= triangle.length <= 200
  • +
  • triangle[0].length == 1
  • +
  • triangle[i].length == triangle[i - 1].length + 1
  • +
  • -104 <= triangle[i][j] <= 104
  • +
+ +

 

+Follow up: Could you do this using only O(n) extra space, where n is the total number of rows in the triangle?
\ No newline at end of file diff --git a/trim-a-binary-search-tree/README.md b/trim-a-binary-search-tree/README.md new file mode 100644 index 0000000..d29817c --- /dev/null +++ b/trim-a-binary-search-tree/README.md @@ -0,0 +1,46 @@ +

669. Trim a Binary Search Tree

Medium


Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.

+ +

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

+ +

 

+

Example 1:

+ +
Input: root = [1,0,2], low = 1, high = 2
+Output: [1,null,2]
+
+ +

Example 2:

+ +
Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
+Output: [3,2,null,1]
+
+ +

Example 3:

+ +
Input: root = [1], low = 1, high = 2
+Output: [1]
+
+ +

Example 4:

+ +
Input: root = [1,null,2], low = 1, high = 3
+Output: [1,null,2]
+
+ +

Example 5:

+ +
Input: root = [1,null,2], low = 2, high = 4
+Output: [2]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree in the range [1, 104].
  • +
  • 0 <= Node.val <= 104
  • +
  • The value of each node in the tree is unique.
  • +
  • root is guaranteed to be a valid binary search tree.
  • +
  • 0 <= low <= high <= 104
  • +
+
\ No newline at end of file diff --git a/trim-a-binary-search-tree/trim-a-binary-search-tree.cpp b/trim-a-binary-search-tree/trim-a-binary-search-tree.cpp new file mode 100644 index 0000000..b99f498 --- /dev/null +++ b/trim-a-binary-search-tree/trim-a-binary-search-tree.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + TreeNode* trimBST(TreeNode* root, int L, int R) { + if (root == NULL) return NULL; + if (root->val < L) return trimBST(root->right, L, R); + if (root->val > R) return trimBST(root->left, L, R); + root->left = trimBST(root->left, L, R); + root->right = trimBST(root->right, L, R); + return root; + } +}; \ No newline at end of file diff --git a/two-sum-ii-input-array-is-sorted/README.md b/two-sum-ii-input-array-is-sorted/README.md new file mode 100644 index 0000000..76542e8 --- /dev/null +++ b/two-sum-ii-input-array-is-sorted/README.md @@ -0,0 +1,39 @@ +

167. Two Sum II - Input array is sorted

Easy


Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= first < second <= numbers.length.

+ +

Return the indices of the two numbers, index1 and index2, as an integer array [index1, index2] of length 2.

+ +

The tests are generated such that there is exactly one solution. You may not use the same element twice.

+ +

 

+

Example 1:

+ +
Input: numbers = [2,7,11,15], target = 9
+Output: [1,2]
+Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
+
+ +

Example 2:

+ +
Input: numbers = [2,3,4], target = 6
+Output: [1,3]
+Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3.
+
+ +

Example 3:

+ +
Input: numbers = [-1,0], target = -1
+Output: [1,2]
+Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= numbers.length <= 3 * 104
  • +
  • -1000 <= numbers[i] <= 1000
  • +
  • numbers is sorted in non-decreasing order.
  • +
  • -1000 <= target <= 1000
  • +
  • The tests are generated such that there is exactly one solution.
  • +
+
\ No newline at end of file diff --git a/two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.cpp b/two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.cpp new file mode 100644 index 0000000..bf4dad0 --- /dev/null +++ b/two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + vector twoSum(vector& nums, int target) { + int i=0; + int j = nums.size()-1; + + while(itarget) + j--; + else if(nums[i]+nums[j]653. Two Sum IV - Input is a BST

Easy


Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.

+ +

 

+

Example 1:

+ +
Input: root = [5,3,6,2,4,null,7], k = 9
+Output: true
+
+ +

Example 2:

+ +
Input: root = [5,3,6,2,4,null,7], k = 28
+Output: false
+
+ +

Example 3:

+ +
Input: root = [2,1,3], k = 4
+Output: true
+
+ +

Example 4:

+ +
Input: root = [2,1,3], k = 1
+Output: false
+
+ +

Example 5:

+ +
Input: root = [2,1,3], k = 3
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -104 <= Node.val <= 104
  • +
  • root is guaranteed to be a valid binary search tree.
  • +
  • -105 <= k <= 105
  • +
+
\ No newline at end of file diff --git a/two-sum-iv-input-is-a-bst/two-sum-iv-input-is-a-bst.cpp b/two-sum-iv-input-is-a-bst/two-sum-iv-input-is-a-bst.cpp new file mode 100644 index 0000000..bef41a5 --- /dev/null +++ b/two-sum-iv-input-is-a-bst/two-sum-iv-input-is-a-bst.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + unordered_set s; + bool findTarget(TreeNode* root, int k) { + if(!root) + return false; + if(s.count(k-root->val)) + return true; + s.insert(root->val); + return findTarget(root->left,k)||findTarget(root->right,k); + } +}; \ No newline at end of file diff --git a/two-sum/README.md b/two-sum/README.md new file mode 100644 index 0000000..5dd9f3f --- /dev/null +++ b/two-sum/README.md @@ -0,0 +1,38 @@ +

1. Two Sum

Easy


Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

+ +

You may assume that each input would have exactly one solution, and you may not use the same element twice.

+ +

You can return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: nums = [2,7,11,15], target = 9
+Output: [0,1]
+Output: Because nums[0] + nums[1] == 9, we return [0, 1].
+
+ +

Example 2:

+ +
Input: nums = [3,2,4], target = 6
+Output: [1,2]
+
+ +

Example 3:

+ +
Input: nums = [3,3], target = 6
+Output: [0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 104
  • +
  • -109 <= nums[i] <= 109
  • +
  • -109 <= target <= 109
  • +
  • Only one valid answer exists.
  • +
+ +

 

+Follow-up: Can you come up with an algorithm that is less than O(n2time complexity?
\ No newline at end of file diff --git a/two-sum/two-sum.cpp b/two-sum/two-sum.cpp new file mode 100644 index 0000000..86560ea --- /dev/null +++ b/two-sum/two-sum.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector twoSum(vector& nums, int target) { + map m; + vector v; + + for(int i=0;i264. Ugly Number II

Medium


An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

+ +

Given an integer n, return the nth ugly number.

+ +

 

+

Example 1:

+ +
Input: n = 10
+Output: 12
+Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.
+
+ +

Example 2:

+ +
Input: n = 1
+Output: 1
+Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 1690
  • +
+
\ No newline at end of file diff --git a/ugly-number-ii/ugly-number-ii.cpp b/ugly-number-ii/ugly-number-ii.cpp new file mode 100644 index 0000000..9724a11 --- /dev/null +++ b/ugly-number-ii/ugly-number-ii.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int nthUglyNumber(int n) { + vector results (1,1); + int i = 0, j = 0, k = 0; + while (results.size() < n) + { + results.push_back(min(results[i] * 2, min(results[j] * 3, results[k] * 5))); + if (results.back() == results[i] * 2) ++i; + if (results.back() == results[j] * 3) ++j; + if (results.back() == results[k] * 5) ++k; + } + return results.back(); + } +}; \ No newline at end of file diff --git a/unique-binary-search-trees-ii/README.md b/unique-binary-search-trees-ii/README.md new file mode 100644 index 0000000..09b3af2 --- /dev/null +++ b/unique-binary-search-trees-ii/README.md @@ -0,0 +1,22 @@ +

95. Unique Binary Search Trees II

Medium


Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: n = 3
+Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
+
+ +

Example 2:

+ +
Input: n = 1
+Output: [[1]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 8
  • +
+
\ No newline at end of file diff --git a/unique-binary-search-trees/README.md b/unique-binary-search-trees/README.md new file mode 100644 index 0000000..99e5681 --- /dev/null +++ b/unique-binary-search-trees/README.md @@ -0,0 +1,22 @@ +

96. Unique Binary Search Trees

Medium


Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.

+ +

 

+

Example 1:

+ +
Input: n = 3
+Output: 5
+
+ +

Example 2:

+ +
Input: n = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 19
  • +
+
\ No newline at end of file diff --git a/unique-binary-search-trees/unique-binary-search-trees.cpp b/unique-binary-search-trees/unique-binary-search-trees.cpp new file mode 100644 index 0000000..9700c7a --- /dev/null +++ b/unique-binary-search-trees/unique-binary-search-trees.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int numTrees(int n) { + if(n<=2) + return n; + vector v(n+1); + v[0] = 1; + v[1] = 1; + v[2] = 2; + + for(int i=3;i<=n;i++) + { + for(int j=0;j63. Unique Paths II

Medium


A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

+ +

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

+ +

Now consider if some obstacles are added to the grids. How many unique paths would there be?

+ +

An obstacle and space is marked as 1 and 0 respectively in the grid.

+ +

 

+

Example 1:

+ +
Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
+Output: 2
+Explanation: There is one obstacle in the middle of the 3x3 grid above.
+There are two ways to reach the bottom-right corner:
+1. Right -> Right -> Down -> Down
+2. Down -> Down -> Right -> Right
+
+ +

Example 2:

+ +
Input: obstacleGrid = [[0,1],[0,0]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • m == obstacleGrid.length
  • +
  • n == obstacleGrid[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • obstacleGrid[i][j] is 0 or 1.
  • +
+
\ No newline at end of file diff --git a/unique-paths-iii/README.md b/unique-paths-iii/README.md new file mode 100644 index 0000000..aadf15e --- /dev/null +++ b/unique-paths-iii/README.md @@ -0,0 +1,52 @@ +

980. Unique Paths III

Hard


You are given an m x n integer array grid where grid[i][j] could be:

+ +
    +
  • 1 representing the starting square. There is exactly one starting square.
  • +
  • 2 representing the ending square. There is exactly one ending square.
  • +
  • 0 representing empty squares we can walk over.
  • +
  • -1 representing obstacles that we cannot walk over.
  • +
+ +

Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.

+ +

 

+

Example 1:

+ +
Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
+Output: 2
+Explanation: We have the following two paths: 
+1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
+2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)
+
+ +

Example 2:

+ +
Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
+Output: 4
+Explanation: We have the following four paths: 
+1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
+2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
+3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
+4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)
+
+ +

Example 3:

+ +
Input: grid = [[0,1],[2,0]]
+Output: 0
+Explanation: There is no path that walks over every empty square exactly once.
+Note that the starting and ending square can be anywhere in the grid.
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 20
  • +
  • 1 <= m * n <= 20
  • +
  • -1 <= grid[i][j] <= 2
  • +
  • There is exactly one starting cell and one ending cell.
  • +
+
\ No newline at end of file diff --git a/unique-paths-iii/unique-paths-iii.cpp b/unique-paths-iii/unique-paths-iii.cpp new file mode 100644 index 0000000..1591993 --- /dev/null +++ b/unique-paths-iii/unique-paths-iii.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int res = 0, empty = 1; + void dfs(vector>& grid, int x, int y, int count) { + if (x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size() || grid[x][y] == -1) return; + + if (grid[x][y] == 2) { + if(empty == count) res++; + return; + } + + grid[x][y] = -1; + + dfs(grid, x+1, y, count+1); + dfs(grid, x-1, y, count+1); + dfs(grid, x, y+1, count+1); + dfs(grid, x, y-1, count+1); + + grid[x][y] = 0; + + } + + int uniquePathsIII(vector>& grid) { + int start_x, start_y; + for (int i = 0; i < grid.size(); i++) { + for (int j = 0; j < grid[0].size(); j++) { + if (grid[i][j] == 1) start_x = i, start_y = j; + else if (grid[i][j] == 0) empty++; + } + } + + dfs(grid, start_x, start_y, 0); + return res; + } +}; \ No newline at end of file diff --git a/unique-paths/README.md b/unique-paths/README.md new file mode 100644 index 0000000..2bdfde0 --- /dev/null +++ b/unique-paths/README.md @@ -0,0 +1,44 @@ +

62. Unique Paths

Medium


A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

+ +

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

+ +

How many possible unique paths are there?

+ +

 

+

Example 1:

+ +
Input: m = 3, n = 7
+Output: 28
+
+ +

Example 2:

+ +
Input: m = 3, n = 2
+Output: 3
+Explanation:
+From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
+1. Right -> Down -> Down
+2. Down -> Down -> Right
+3. Down -> Right -> Down
+
+ +

Example 3:

+ +
Input: m = 7, n = 3
+Output: 28
+
+ +

Example 4:

+ +
Input: m = 3, n = 3
+Output: 6
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= m, n <= 100
  • +
  • It's guaranteed that the answer will be less than or equal to 2 * 109.
  • +
+
\ No newline at end of file diff --git a/unique-paths/unique-paths.cpp b/unique-paths/unique-paths.cpp new file mode 100644 index 0000000..bdb7735 --- /dev/null +++ b/unique-paths/unique-paths.cpp @@ -0,0 +1,12 @@ +class Solution { +public: +int uniquePaths(int m, int n) { + int N = m+n-2; + int r = min(m-1,n-1); + long double res = 1.0; + for(int i=1; i<=r; i++){ + res = res*(N-r+i)/i; + } + return (int)res; +} +}; \ No newline at end of file diff --git a/valid-palindrome/README.md b/valid-palindrome/README.md new file mode 100644 index 0000000..f27fc0c --- /dev/null +++ b/valid-palindrome/README.md @@ -0,0 +1,25 @@ +

125. Valid Palindrome

Easy


Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

+ +

 

+

Example 1:

+ +
Input: s = "A man, a plan, a canal: Panama"
+Output: true
+Explanation: "amanaplanacanalpanama" is a palindrome.
+
+ +

Example 2:

+ +
Input: s = "race a car"
+Output: false
+Explanation: "raceacar" is not a palindrome.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 2 * 105
  • +
  • s consists only of printable ASCII characters.
  • +
+
\ No newline at end of file diff --git a/valid-palindrome/valid-palindrome.cpp b/valid-palindrome/valid-palindrome.cpp new file mode 100644 index 0000000..4fe64a9 --- /dev/null +++ b/valid-palindrome/valid-palindrome.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool isPalindrome(string s) { + string a ; + for(int i=0;i= 'a' && s[i] <= 'z' ) || (s[i] >= 'A' && s[i] <= 'Z') || s[i] >= '0' && s[i] <= '9') + a.push_back(tolower(s[i])); + } + for(int i=0;i20. Valid Parentheses

Easy


Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

+ +

An input string is valid if:

+ +
    +
  1. Open brackets must be closed by the same type of brackets.
  2. +
  3. Open brackets must be closed in the correct order.
  4. +
+ +

 

+

Example 1:

+ +
Input: s = "()"
+Output: true
+
+ +

Example 2:

+ +
Input: s = "()[]{}"
+Output: true
+
+ +

Example 3:

+ +
Input: s = "(]"
+Output: false
+
+ +

Example 4:

+ +
Input: s = "([)]"
+Output: false
+
+ +

Example 5:

+ +
Input: s = "{[]}"
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of parentheses only '()[]{}'.
  • +
+
\ No newline at end of file diff --git a/valid-parentheses/valid-parentheses.cpp b/valid-parentheses/valid-parentheses.cpp new file mode 100644 index 0000000..d8d9095 --- /dev/null +++ b/valid-parentheses/valid-parentheses.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + bool isValid(string s) { + stack sc; + + for(int i=0;i36. Valid Sudoku

Medium


Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

+ +
    +
  1. Each row must contain the digits 1-9 without repetition.
  2. +
  3. Each column must contain the digits 1-9 without repetition.
  4. +
  5. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
  6. +
+ +

Note:

+ +
    +
  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • +
  • Only the filled cells need to be validated according to the mentioned rules.
  • +
+ +

 

+

Example 1:

+ +
Input: board = 
+[["5","3",".",".","7",".",".",".","."]
+,["6",".",".","1","9","5",".",".","."]
+,[".","9","8",".",".",".",".","6","."]
+,["8",".",".",".","6",".",".",".","3"]
+,["4",".",".","8",".","3",".",".","1"]
+,["7",".",".",".","2",".",".",".","6"]
+,[".","6",".",".",".",".","2","8","."]
+,[".",".",".","4","1","9",".",".","5"]
+,[".",".",".",".","8",".",".","7","9"]]
+Output: true
+
+ +

Example 2:

+ +
Input: board = 
+[["8","3",".",".","7",".",".",".","."]
+,["6",".",".","1","9","5",".",".","."]
+,[".","9","8",".",".",".",".","6","."]
+,["8",".",".",".","6",".",".",".","3"]
+,["4",".",".","8",".","3",".",".","1"]
+,["7",".",".",".","2",".",".",".","6"]
+,[".","6",".",".",".",".","2","8","."]
+,[".",".",".","4","1","9",".",".","5"]
+,[".",".",".",".","8",".",".","7","9"]]
+Output: false
+Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
+
+ +

 

+

Constraints:

+ +
    +
  • board.length == 9
  • +
  • board[i].length == 9
  • +
  • board[i][j] is a digit or '.'.
  • +
+
\ No newline at end of file diff --git a/valid-sudoku/valid-sudoku.cpp b/valid-sudoku/valid-sudoku.cpp new file mode 100644 index 0000000..76969b6 --- /dev/null +++ b/valid-sudoku/valid-sudoku.cpp @@ -0,0 +1,20 @@ +class Solution +{ +public: + bool isValidSudoku(vector > &board) + { + int used1[9][9] = {0}, used2[9][9] = {0}, used3[9][9] = {0}; + + for(int i = 0; i < board.size(); ++ i) + for(int j = 0; j < board[i].size(); ++ j) + if(board[i][j] != '.') + { + int num = board[i][j] - '0' - 1, k = i / 3 * 3 + j / 3; + if(used1[i][num] || used2[j][num] || used3[k][num]) + return false; + used1[i][num] = used2[j][num] = used3[k][num] = 1; + } + + return true; + } +}; \ No newline at end of file diff --git a/valid-triangle-number/README.md b/valid-triangle-number/README.md new file mode 100644 index 0000000..d662112 --- /dev/null +++ b/valid-triangle-number/README.md @@ -0,0 +1,27 @@ +

611. Valid Triangle Number

Medium


Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.

+ +

 

+

Example 1:

+ +
Input: nums = [2,2,3,4]
+Output: 3
+Explanation: Valid combinations are: 
+2,3,4 (using the first 2)
+2,3,4 (using the second 2)
+2,2,3
+
+ +

Example 2:

+ +
Input: nums = [4,2,3,4]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 0 <= nums[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/valid-triangle-number/valid-triangle-number.cpp b/valid-triangle-number/valid-triangle-number.cpp new file mode 100644 index 0000000..ba2e732 --- /dev/null +++ b/valid-triangle-number/valid-triangle-number.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int triangleNumber(vector& nums) { + vector snums(nums); + sort(snums.begin(), snums.end()); + int count = 0; + for ( int n = nums.size(), k = n - 1; k > 1; --k ) { + int i = 0, j = k - 1; + while ( i < j ) { + // any value x between i...j will satisfy snums[x] + snums[j] > snums[k] + // and because snums[k] > snums[j] > snums[x] >= 0, they will always satisfy + // snums[k] + snums[x] > snums[j] and snums[k] + snums[j] > snums[x] + if ( snums[i] + snums[j] > snums[k] ) + count += --j - i + 1; + else + ++i; + } + } + return count; + } +}; \ No newline at end of file diff --git a/validate-binary-search-tree/README.md b/validate-binary-search-tree/README.md new file mode 100644 index 0000000..3e6f61c --- /dev/null +++ b/validate-binary-search-tree/README.md @@ -0,0 +1,32 @@ +

98. Validate Binary Search Tree

Medium


Given the root of a binary tree, determine if it is a valid binary search tree (BST).

+ +

A valid BST is defined as follows:

+ +
    +
  • The left subtree of a node contains only nodes with keys less than the node's key.
  • +
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • +
  • Both the left and right subtrees must also be binary search trees.
  • +
+ +

 

+

Example 1:

+ +
Input: root = [2,1,3]
+Output: true
+
+ +

Example 2:

+ +
Input: root = [5,1,4,null,null,3,6]
+Output: false
+Explanation: The root node's value is 5 but its right child's value is 4.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -231 <= Node.val <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/validate-binary-search-tree/validate-binary-search-tree.cpp b/validate-binary-search-tree/validate-binary-search-tree.cpp new file mode 100644 index 0000000..e96e563 --- /dev/null +++ b/validate-binary-search-tree/validate-binary-search-tree.cpp @@ -0,0 +1,43 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isValidBST(TreeNode* root) { + + if(root == NULL) + return true; + + stack s; + TreeNode * temp = NULL; + while(root != NULL || !s.empty()) + { + + if(root != NULL) + { + s.push(root); + root = root->left; + } + else + { + root = s.top(); + s.pop(); + if(temp != NULL && temp->val >= root->val) + return false; + temp = root; + root = root->right; + } + + } + + return true; + } +}; \ No newline at end of file diff --git a/verify-preorder-serialization-of-a-binary-tree/README.md b/verify-preorder-serialization-of-a-binary-tree/README.md new file mode 100644 index 0000000..fe3a558 --- /dev/null +++ b/verify-preorder-serialization-of-a-binary-tree/README.md @@ -0,0 +1,35 @@ +

331. Verify Preorder Serialization of a Binary Tree

Medium


One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'.

+ +

For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents a null node.

+ +

Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree.

+ +

It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer.

+ +

You may assume that the input format is always valid.

+ +
    +
  • For example, it could never contain two consecutive commas, such as "1,,3".
  • +
+ +

Note: You are not allowed to reconstruct the tree.

+ +

 

+

Example 1:

+
Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
+Output: true
+

Example 2:

+
Input: preorder = "1,#"
+Output: false
+

Example 3:

+
Input: preorder = "9,#,#,1"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= preorder.length <= 104
  • +
  • preoder consist of integers in the range [0, 100] and '#' separated by commas ','.
  • +
+
\ No newline at end of file diff --git a/verify-preorder-serialization-of-a-binary-tree/verify-preorder-serialization-of-a-binary-tree.cpp b/verify-preorder-serialization-of-a-binary-tree/verify-preorder-serialization-of-a-binary-tree.cpp new file mode 100644 index 0000000..a9cdf7e --- /dev/null +++ b/verify-preorder-serialization-of-a-binary-tree/verify-preorder-serialization-of-a-binary-tree.cpp @@ -0,0 +1,16 @@ +class Solution { +public: +bool isValidSerialization(string preorder) { + if (preorder.empty()) return false; + preorder+=','; + int sz=preorder.size(),idx=0; + int capacity=1; + for (idx=0;idx2069. Walking Robot Simulation II

Medium


A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions ("North", "East", "South", and "West"). A robot is initially at cell (0, 0) facing direction "East".

+ +

The robot can be instructed to move for a specific number of steps. For each step, it does the following.

+ +
    +
  1. Attempts to move forward one cell in the direction it is facing.
  2. +
  3. If the cell the robot is moving to is out of bounds, the robot instead turns 90 degrees counterclockwise and retries the step.
  4. +
+ +

After the robot finishes moving the number of steps required, it stops and awaits the next instruction.

+ +

Implement the Robot class:

+ +
    +
  • Robot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing "East".
  • +
  • void move(int num) Instructs the robot to move forward num steps.
  • +
  • int[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y].
  • +
  • String getDir() Returns the current direction of the robot, "North", "East", "South", or "West".
  • +
+ +

 

+

Example 1:

+example-1 +
Input
+["Robot", "move", "move", "getPos", "getDir", "move", "move", "move", "getPos", "getDir"]
+[[6, 3], [2], [2], [], [], [2], [1], [4], [], []]
+Output
+[null, null, null, [4, 0], "East", null, null, null, [1, 2], "West"]
+
+Explanation
+Robot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.
+robot.move(2);  // It moves two steps East to (2, 0), and faces East.
+robot.move(2);  // It moves two steps East to (4, 0), and faces East.
+robot.getPos(); // return [4, 0]
+robot.getDir(); // return "East"
+robot.move(2);  // It moves one step East to (5, 0), and faces East.
+                // Moving the next step East would be out of bounds, so it turns and faces North.
+                // Then, it moves one step North to (5, 1), and faces North.
+robot.move(1);  // It moves one step North to (5, 2), and faces North (not West).
+robot.move(4);  // Moving the next step North would be out of bounds, so it turns and faces West.
+                // Then, it moves four steps West to (1, 2), and faces West.
+robot.getPos(); // return [1, 2]
+robot.getDir(); // return "West"
+
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= width, height <= 100
  • +
  • 1 <= num <= 105
  • +
  • At most 104 calls in total will be made to move, getPos, and getDir.
  • +
+
\ No newline at end of file diff --git a/walking-robot-simulation-ii/walking-robot-simulation-ii.cpp b/walking-robot-simulation-ii/walking-robot-simulation-ii.cpp new file mode 100644 index 0000000..7217a4b --- /dev/null +++ b/walking-robot-simulation-ii/walking-robot-simulation-ii.cpp @@ -0,0 +1,28 @@ +class Robot { + int dir = 0, dirs[4][2] = {{1,0},{0,1},{-1,0},{0,-1}}, w, h, perimeter, x = 0, y = 0; + string text[4] = {"East","North","West","South"}; +public: + Robot(int width, int height) : w(width), h(height), perimeter(2*(w + h - 2)) {} + void move(int k) { + if (k >= perimeter) { + k %= perimeter; + if (x == 0 && y == 0 && dir == 0) dir = 3; // Special case: if we are at the beginning (x = 0, y = 0 and facing east), after the round trip, the direction becomes south. + } + while (k > 0) { + auto &[dx, dy] = dirs[dir]; + int nx = x + dx, ny = y + dy; + if (nx < 0 || ny < 0 || nx >= w || ny >= h) { + dir = (dir + 1) % 4; + } else { + x = nx, y = ny; + --k; + } + } + } + vector getPos() { + return {x,y}; + } + string getDir() { + return text[dir]; + } +}; \ No newline at end of file diff --git a/wiggle-subsequence/README.md b/wiggle-subsequence/README.md new file mode 100644 index 0000000..e4366ed --- /dev/null +++ b/wiggle-subsequence/README.md @@ -0,0 +1,44 @@ +

376. Wiggle Subsequence

Medium


A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.

+ +
    +
  • For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.
  • +
  • In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
  • +
+ +

A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.

+ +

Given an integer array nums, return the length of the longest wiggle subsequence of nums.

+ +

 

+

Example 1:

+ +
Input: nums = [1,7,4,9,2,5]
+Output: 6
+Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).
+
+ +

Example 2:

+ +
Input: nums = [1,17,5,10,13,15,10,5,16,8]
+Output: 7
+Explanation: There are several subsequences that achieve this length.
+One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).
+
+ +

Example 3:

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

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 0 <= nums[i] <= 1000
  • +
+ +

 

+

Follow up: Could you solve this in O(n) time?

+
\ No newline at end of file diff --git a/wiggle-subsequence/wiggle-subsequence.cpp b/wiggle-subsequence/wiggle-subsequence.cpp new file mode 100644 index 0000000..3431152 --- /dev/null +++ b/wiggle-subsequence/wiggle-subsequence.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int wiggleMaxLength(vector& nums) { + if (nums.size() < 2) + return nums.size(); + int down = 1, up = 1; + for (int i = 1; i < nums.size(); i++) { + if (nums[i] > nums[i - 1]) + up = down + 1; + else if (nums[i] < nums[i - 1]) + down = up + 1; + } + return max(down, up); + } +}; \ No newline at end of file diff --git a/wildcard-matching/README.md b/wildcard-matching/README.md new file mode 100644 index 0000000..38edee9 --- /dev/null +++ b/wildcard-matching/README.md @@ -0,0 +1,40 @@ +

44. Wildcard Matching

Hard


Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:

+ +
    +
  • '?' Matches any single character.
  • +
  • '*' Matches any sequence of characters (including the empty sequence).
  • +
+ +

The matching should cover the entire input string (not partial).

+ +

 

+

Example 1:

+ +
Input: s = "aa", p = "a"
+Output: false
+Explanation: "a" does not match the entire string "aa".
+
+ +

Example 2:

+ +
Input: s = "aa", p = "*"
+Output: true
+Explanation: '*' matches any sequence.
+
+ +

Example 3:

+ +
Input: s = "cb", p = "?a"
+Output: false
+Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length, p.length <= 2000
  • +
  • s contains only lowercase English letters.
  • +
  • p contains only lowercase English letters, '?' or '*'.
  • +
+
\ No newline at end of file diff --git a/word-break/README.md b/word-break/README.md new file mode 100644 index 0000000..49efd2b --- /dev/null +++ b/word-break/README.md @@ -0,0 +1,37 @@ +

139. Word Break

Medium


Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

+ +

Note that the same word in the dictionary may be reused multiple times in the segmentation.

+ +

 

+

Example 1:

+ +
Input: s = "leetcode", wordDict = ["leet","code"]
+Output: true
+Explanation: Return true because "leetcode" can be segmented as "leet code".
+
+ +

Example 2:

+ +
Input: s = "applepenapple", wordDict = ["apple","pen"]
+Output: true
+Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
+Note that you are allowed to reuse a dictionary word.
+
+ +

Example 3:

+ +
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 300
  • +
  • 1 <= wordDict.length <= 1000
  • +
  • 1 <= wordDict[i].length <= 20
  • +
  • s and wordDict[i] consist of only lowercase English letters.
  • +
  • All the strings of wordDict are unique.
  • +
+
\ No newline at end of file diff --git a/word-break/word-break.cpp b/word-break/word-break.cpp new file mode 100644 index 0000000..8162a13 --- /dev/null +++ b/word-break/word-break.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + vector dp(s.size()+1, false); + dp[0] = true; + + // we mark as true every index that we managed to segment so far + for (int i = 1; i <= s.size(); i++) + for (int j = 0; j < i; j++) + if ((dp[j]) && (find(wordDict.begin(), wordDict.end(), s.substr(j, i-j)) != wordDict.end())) { + dp[i] = true; + break; + } + return dp.back(); + } +}; \ No newline at end of file diff --git a/word-ladder/README.md b/word-ladder/README.md new file mode 100644 index 0000000..30efa8f --- /dev/null +++ b/word-ladder/README.md @@ -0,0 +1,38 @@ +

127. Word Ladder

Hard


A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:

+ +
    +
  • Every adjacent pair of words differs by a single letter.
  • +
  • Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
  • +
  • sk == endWord
  • +
+ +

Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.

+ +

 

+

Example 1:

+ +
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
+Output: 5
+Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.
+
+ +

Example 2:

+ +
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
+Output: 0
+Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= beginWord.length <= 10
  • +
  • endWord.length == beginWord.length
  • +
  • 1 <= wordList.length <= 5000
  • +
  • wordList[i].length == beginWord.length
  • +
  • beginWord, endWord, and wordList[i] consist of lowercase English letters.
  • +
  • beginWord != endWord
  • +
  • All the words in wordList are unique.
  • +
+
\ No newline at end of file diff --git a/word-search/README.md b/word-search/README.md new file mode 100644 index 0000000..9898373 --- /dev/null +++ b/word-search/README.md @@ -0,0 +1,37 @@ +

79. Word Search

Medium


Given an m x n grid of characters board and a string word, return true if word exists in the grid.

+ +

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

+ +

 

+

Example 1:

+ +
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
+Output: true
+
+ +

Example 2:

+ +
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
+Output: true
+
+ +

Example 3:

+ +
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • m == board.length
  • +
  • n = board[i].length
  • +
  • 1 <= m, n <= 6
  • +
  • 1 <= word.length <= 15
  • +
  • board and word consists of only lowercase and uppercase English letters.
  • +
+ +

 

+

Follow up: Could you use search pruning to make your solution faster with a larger board?

+
\ No newline at end of file diff --git a/xor-queries-of-a-subarray/README.md b/xor-queries-of-a-subarray/README.md new file mode 100644 index 0000000..d94ff17 --- /dev/null +++ b/xor-queries-of-a-subarray/README.md @@ -0,0 +1,35 @@ +

1310. XOR Queries of a Subarray

Medium


Given the array arr of positive integers and the array queries where queries[i] = [Li, Ri], for each query i compute the XOR of elements from Li to Ri (that is, arr[Li] xor arr[Li+1] xor ... xor arr[Ri] ). Return an array containing the result for the given queries. +

 

+

Example 1:

+ +
Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
+Output: [2,7,14,8] 
+Explanation: 
+The binary representation of the elements in the array are:
+1 = 0001 
+3 = 0011 
+4 = 0100 
+8 = 1000 
+The XOR values for queries are:
+[0,1] = 1 xor 3 = 2 
+[1,2] = 3 xor 4 = 7 
+[0,3] = 1 xor 3 xor 4 xor 8 = 14 
+[3,3] = 8
+
+ +

Example 2:

+ +
Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
+Output: [8,0,4,4]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 3 * 10^4
  • +
  • 1 <= arr[i] <= 10^9
  • +
  • 1 <= queries.length <= 3 * 10^4
  • +
  • queries[i].length == 2
  • +
  • 0 <= queries[i][0] <= queries[i][1] < arr.length
  • +
\ No newline at end of file