Repository: Sagar0-0/DSA Branch: main Commit: fb3dccef4374 Files: 2230 Total size: 2.2 MB Directory structure: gitextract_b94qtoqo/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ └── custom.md │ └── pull_request_template.md ├── 0012-integer-to-roman/ │ ├── 0012-integer-to-roman.java │ ├── 0012-integer-to-roman.py │ ├── NOTES.md │ └── README.md ├── 0026-remove-duplicates-from-sorted-array/ │ ├── 0026-remove-duplicates-from-sorted-array.java │ ├── 0026-remove-duplicates-from-sorted-array.py │ ├── NOTES.md │ └── README.md ├── 0036-valid-sudoku/ │ ├── 0036-valid-sudoku.java │ ├── 0036-valid-sudoku.py │ ├── NOTES.md │ └── README.md ├── 0037-sudoku-solver/ │ ├── 0037-sudoku-solver.java │ ├── NOTES.md │ └── README.md ├── 0038-count-and-say/ │ ├── 0038-count-and-say.java │ ├── 0038-count-and-say.py │ └── README.md ├── 0049-group-anagrams/ │ ├── 0049-group-anagrams.java │ ├── 0049-group-anagrams.py │ └── README.md ├── 0055-jump-game/ │ ├── 0055-jump-game.java │ ├── 0055-jump-game.py │ ├── NOTES.md │ └── README.md ├── 0057-insert-interval/ │ ├── 0057-insert-interval.java │ ├── 0057-insert-interval.py │ ├── NOTES.md │ └── README.md ├── 0070-climbing-stairs/ │ ├── 0070-climbing-stairs.java │ ├── NOTES.md │ └── README.md ├── 0076-minimum-window-substring/ │ ├── 0076-minimum-window-substring.java │ ├── NOTES.md │ └── README.md ├── 0079-word-search/ │ ├── 0079-word-search.java │ ├── NOTES.md │ └── README.md ├── 0093-restore-ip-addresses/ │ ├── 0093-restore-ip-addresses.java │ └── README.md ├── 0100-same-tree/ │ ├── 0100-same-tree.java │ ├── NOTES.md │ └── README.md ├── 0124-binary-tree-maximum-path-sum/ │ ├── 0124-binary-tree-maximum-path-sum.java │ ├── NOTES.md │ └── README.md ├── 0125-valid-palindrome/ │ ├── 0125-valid-palindrome.java │ ├── NOTES.md │ └── README.md ├── 0131-palindrome-partitioning/ │ ├── 0131-palindrome-partitioning.java │ ├── NOTES.md │ └── README.md ├── 0134-gas-station/ │ ├── 0134-gas-station.java │ ├── NOTES.md │ └── README.md ├── 0144-binary-tree-preorder-traversal/ │ ├── 0144-binary-tree-preorder-traversal.java │ ├── NOTES.md │ └── README.md ├── 0149-max-points-on-a-line/ │ ├── 0149-max-points-on-a-line.java │ ├── NOTES.md │ └── README.md ├── 0150-evaluate-reverse-polish-notation/ │ ├── 0150-evaluate-reverse-polish-notation.java │ ├── NOTES.md │ └── README.md ├── 0151-reverse-words-in-a-string/ │ ├── 0151-reverse-words-in-a-string.java │ ├── NOTES.md │ └── README.md ├── 0198-house-robber/ │ ├── 0198-house-robber.java │ └── README.md ├── 0212-word-search-ii/ │ ├── 0212-word-search-ii.java │ ├── NOTES.md │ └── README.md ├── 0219-contains-duplicate-ii/ │ ├── 0219-contains-duplicate-ii.java │ ├── NOTES.md │ └── README.md ├── 0222-count-complete-tree-nodes/ │ ├── 0222-count-complete-tree-nodes.java │ ├── NOTES.md │ └── README.md ├── 0223-rectangle-area/ │ ├── 0223-rectangle-area.java │ ├── NOTES.md │ └── README.md ├── 0224-basic-calculator/ │ ├── 0224-basic-calculator.java │ ├── NOTES.md │ └── README.md ├── 0232-implement-queue-using-stacks/ │ ├── 0232-implement-queue-using-stacks.java │ ├── NOTES.md │ └── README.md ├── 0236-lowest-common-ancestor-of-a-binary-tree/ │ ├── 0236-lowest-common-ancestor-of-a-binary-tree.java │ ├── NOTES.md │ └── README.md ├── 0237-delete-node-in-a-linked-list/ │ ├── 0237-delete-node-in-a-linked-list.java │ ├── NOTES.md │ └── README.md ├── 0242-valid-anagram/ │ ├── 0242-valid-anagram.cpp │ ├── 0242-valid-anagram.java │ ├── NOTES.md │ └── README.md ├── 0263-ugly-number/ │ ├── 0263-ugly-number.java │ ├── NOTES.md │ └── README.md ├── 0279-perfect-squares/ │ ├── 0279-perfect-squares.java │ ├── NOTES.md │ └── README.md ├── 0290-word-pattern/ │ ├── 0290-word-pattern.java │ └── README.md ├── 0295-find-median-from-data-stream/ │ ├── 0295-find-median-from-data-stream.java │ ├── NOTES.md │ └── README.md ├── 0309-best-time-to-buy-and-sell-stock-with-cooldown/ │ ├── 0309-best-time-to-buy-and-sell-stock-with-cooldown.java │ ├── NOTES.md │ └── README.md ├── 0328-odd-even-linked-list/ │ ├── 0328-odd-even-linked-list.java │ ├── NOTES.md │ └── README.md ├── 0334-increasing-triplet-subsequence/ │ ├── 0334-increasing-triplet-subsequence.java │ ├── NOTES.md │ └── README.md ├── 0345-reverse-vowels-of-a-string/ │ ├── 0345-reverse-vowels-of-a-string.java │ ├── NOTES.md │ └── README.md ├── 0374-guess-number-higher-or-lower/ │ ├── 0374-guess-number-higher-or-lower.java │ ├── NOTES.md │ └── README.md ├── 0380-insert-delete-getrandom-o1/ │ ├── 0380-insert-delete-getrandom-o1.java │ ├── NOTES.md │ └── README.md ├── 0409-longest-palindrome/ │ ├── 0409-longest-palindrome.java │ ├── NOTES.md │ └── README.md ├── 0446-arithmetic-slices-ii-subsequence/ │ ├── 0446-arithmetic-slices-ii-subsequence.java │ ├── NOTES.md │ └── README.md ├── 0451-sort-characters-by-frequency/ │ ├── 0451-sort-characters-by-frequency.java │ ├── NOTES.md │ └── README.md ├── 0452-minimum-number-of-arrows-to-burst-balloons/ │ ├── 0452-minimum-number-of-arrows-to-burst-balloons.java │ ├── NOTES.md │ └── README.md ├── 0491-non-decreasing-subsequences/ │ ├── 0491-non-decreasing-subsequences.java │ ├── NOTES.md │ └── README.md ├── 0520-detect-capital/ │ ├── 0520-detect-capital.java │ └── NOTES.md ├── 0523-continuous-subarray-sum/ │ ├── 0523-continuous-subarray-sum.java │ ├── NOTES.md │ └── README.md ├── 0587-erect-the-fence/ │ ├── 0587-erect-the-fence.java │ └── README.md ├── 0645-set-mismatch/ │ ├── 0645-set-mismatch.java │ ├── NOTES.md │ └── README.md ├── 0692-top-k-frequent-words/ │ ├── 0692-top-k-frequent-words.java │ ├── NOTES.md │ └── README.md ├── 0739-daily-temperatures/ │ ├── 0739-daily-temperatures.java │ └── README.md ├── 0766-toeplitz-matrix/ │ ├── 0766-toeplitz-matrix.java │ └── README.md ├── 0787-cheapest-flights-within-k-stops/ │ ├── 0787-cheapest-flights-within-k-stops.java │ ├── NOTES.md │ └── README.md ├── 0790-domino-and-tromino-tiling/ │ ├── 0790-domino-and-tromino-tiling.java │ ├── NOTES.md │ └── README.md ├── 0797-all-paths-from-source-to-target/ │ ├── 0797-all-paths-from-source-to-target.java │ ├── NOTES.md │ └── README.md ├── 0834-sum-of-distances-in-tree/ │ ├── 0834-sum-of-distances-in-tree.java │ ├── NOTES.md │ └── README.md ├── 0835-image-overlap/ │ ├── 0835-image-overlap.java │ ├── NOTES.md │ └── README.md ├── 0841-keys-and-rooms/ │ ├── 0841-keys-and-rooms.java │ ├── NOTES.md │ └── README.md ├── 0872-leaf-similar-trees/ │ ├── 0872-leaf-similar-trees.java │ ├── NOTES.md │ └── README.md ├── 0876-middle-of-the-linked-list/ │ ├── 0876-middle-of-the-linked-list.java │ ├── NOTES.md │ └── README.md ├── 0886-possible-bipartition/ │ ├── 0886-possible-bipartition.java │ ├── NOTES.md │ └── README.md ├── 0899-orderly-queue/ │ ├── 0899-orderly-queue.java │ ├── NOTES.md │ └── README.md ├── 0901-online-stock-span/ │ ├── 0901-online-stock-span.java │ ├── NOTES.md │ └── README.md ├── 0907-sum-of-subarray-minimums/ │ ├── 0907-sum-of-subarray-minimums.java │ ├── NOTES.md │ └── README.md ├── 0909-snakes-and-ladders/ │ ├── 0909-snakes-and-ladders.java │ ├── NOTES.md │ └── README.md ├── 0918-maximum-sum-circular-subarray/ │ ├── 0918-maximum-sum-circular-subarray.java │ └── README.md ├── 0926-flip-string-to-monotone-increasing/ │ ├── 0926-flip-string-to-monotone-increasing.java │ └── NOTES.md ├── 0938-range-sum-of-bst/ │ ├── 0938-range-sum-of-bst.java │ ├── NOTES.md │ └── README.md ├── 0944-delete-columns-to-make-sorted/ │ ├── 0944-delete-columns-to-make-sorted.java │ ├── NOTES.md │ └── README.md ├── 0947-most-stones-removed-with-same-row-or-column/ │ ├── 0947-most-stones-removed-with-same-row-or-column.java │ ├── NOTES.md │ └── README.md ├── 0974-subarray-sums-divisible-by-k/ │ ├── 0974-subarray-sums-divisible-by-k.java │ ├── NOTES.md │ └── README.md ├── 0976-largest-perimeter-triangle/ │ ├── 0976-largest-perimeter-triangle.java │ ├── NOTES.md │ └── README.md ├── 0980-unique-paths-iii/ │ ├── 0980-unique-paths-iii.java │ ├── NOTES.md │ └── README.md ├── 0997-find-the-town-judge/ │ ├── 0997-find-the-town-judge.java │ ├── NOTES.md │ └── README.md ├── 1007-minimum-domino-rotations-for-equal-row/ │ ├── 1007-minimum-domino-rotations-for-equal-row.java │ ├── NOTES.md │ └── README.md ├── 102-binary-tree-level-order-traversal/ │ ├── 102-binary-tree-level-order-traversal.java │ ├── 102-binary-tree-level-order-traversal.py │ ├── NOTES.md │ └── README.md ├── 1020-number-of-enclaves/ │ └── 1020-number-of-enclaves.cpp ├── 1020. Number of Enclaves.java ├── 1026-maximum-difference-between-node-and-ancestor/ │ ├── 1026-maximum-difference-between-node-and-ancestor.java │ ├── NOTES.md │ └── README.md ├── 1029-two-city-scheduling/ │ ├── 1029-two-city-scheduling.java │ ├── NOTES.md │ └── README.md ├── 1046-last-stone-weight/ │ ├── 1046-last-stone-weight.java │ ├── NOTES.md │ └── README.md ├── 1047-remove-all-adjacent-duplicates-in-string/ │ ├── 1047-remove-all-adjacent-duplicates-in-string.java │ ├── NOTES.md │ └── README.md ├── 1048-longest-string-chain/ │ ├── 1048-longest-string-chain.java │ ├── NOTES.md │ └── README.md ├── 105-construct-binary-tree-from-preorder-and-inorder-traversal/ │ ├── 105-construct-binary-tree-from-preorder-and-inorder-traversal.java │ ├── NOTES.md │ └── README.md ├── 1061-lexicographically-smallest-equivalent-string/ │ ├── 1061-lexicographically-smallest-equivalent-string.java │ ├── NOTES.md │ └── README.md ├── 1074-number-of-submatrices-that-sum-to-target/ │ ├── 1074-number-of-submatrices-that-sum-to-target.java │ └── NOTES.md ├── 108-convert-sorted-array-to-binary-search-tree/ │ ├── 108-convert-sorted-array-to-binary-search-tree.java │ ├── NOTES.md │ └── README.md ├── 1081-smallest-subsequence-of-distinct-characters/ │ ├── 1081-smallest-subsequence-of-distinct-characters.java │ ├── NOTES.md │ └── README.md ├── 1091-shortest-path-in-binary-matrix/ │ ├── 1091-shortest-path-in-binary-matrix.java │ ├── NOTES.md │ └── README.md ├── 11-container-with-most-water/ │ ├── 11-container-with-most-water.java │ ├── Container_With_Most_Water.cpp │ ├── NOTES.md │ └── README.md ├── 112-path-sum/ │ ├── 112-path-sum.java │ ├── NOTES.md │ └── README.md ├── 113 Path Sum II med s24.cpp ├── 113-Path-Sum-II.cpp ├── 113-path-sum-ii/ │ ├── 113-path-sum-ii.java │ ├── 113. Path Sum II.cpp │ ├── NOTES.md │ └── README.md ├── 114-flatten-binary-tree-to-linked-list/ │ ├── 114-flatten-binary-tree-to-linked-list.java │ ├── NOTES.md │ ├── README.md │ └── SolutionCode.cpp ├── 1143-longest-common-subsequence/ │ ├── 1143-longest-common-subsequence.java │ └── README.md ├── 1155-number-of-dice-rolls-with-target-sum/ │ ├── 1155-number-of-dice-rolls-with-target-sum.java │ ├── NOTES.md │ └── README.md ├── 117-populating-next-right-pointers-in-each-node-ii/ │ ├── 117-populating-next-right-pointers-in-each-node-ii.java │ ├── NOTES.md │ └── README.md ├── 118-pascals-triangle/ │ ├── 118-pascals-triangle.java │ ├── NOTES.md │ └── README.md ├── 1192-critical-connections-in-a-network/ │ ├── 1192-critical-connections-in-a-network.java │ └── README.md ├── 12-integer-to-roman/ │ ├── 12-Leetcode-Integer-to-roman.cpp │ ├── 12-integer-to-roman.java │ ├── NOTES.md │ └── README.md ├── 120-triangle/ │ ├── 120-triangle.java │ ├── NOTES.md │ └── README.md ├── 1207-unique-number-of-occurrences/ │ ├── 1207-unique-number-of-occurrences.java │ ├── NOTES.md │ └── README.md ├── 1209-remove-all-adjacent-duplicates-in-string-ii/ │ ├── 1209-remove-all-adjacent-duplicates-in-string-ii.java │ ├── NOTES.md │ └── README.md ├── 1220-count-vowels-permutation/ │ ├── 1220-count-vowels-permutation.java │ ├── NOTES.md │ └── README.md ├── 1235-maximum-profit-in-job-scheduling/ │ ├── 1235-maximum-profit-in-job-scheduling.java │ ├── NOTES.md │ └── README.md ├── 1239-maximum-length-of-a-concatenated-string-with-unique-characters/ │ ├── 1239-maximum-length-of-a-concatenated-string-with-unique-characters.java │ ├── NOTES.md │ └── README.md ├── 126-word-ladder-ii/ │ ├── 126-word-ladder-ii.java │ ├── NOTES.md │ └── README.md ├── 1260-shift-2d-grid/ │ ├── 1260-shift-2d-grid.java │ ├── NOTES.md │ └── README.md ├── 1268-search-suggestions-system/ │ ├── 1268-search-suggestions-system.java │ ├── NOTES.md │ └── README.md ├── 128-longest-consecutive-sequence/ │ ├── 128-longest-consecutive-sequence.java │ ├── NOTES.md │ └── README.md ├── 1293-shortest-path-in-a-grid-with-obstacles-elimination/ │ ├── 1293-shortest-path-in-a-grid-with-obstacles-elimination.java │ ├── NOTES.md │ └── README.md ├── 13-roman-to-integer/ │ ├── 13-roman-to-integer.cpp │ ├── 13-roman-to-integer.java │ ├── NOTES.md │ └── README.md ├── 1302-deepest-leaves-sum/ │ ├── 1302-deepest-leaves-sum.java │ ├── NOTES.md │ └── README.md ├── 1323-maximum-69-number/ │ ├── 1323-maximum-69-number.java │ ├── NOTES.md │ └── README.md ├── 1328-break-a-palindrome/ │ ├── 1328-break-a-palindrome.java │ ├── NOTES.md │ └── README.md ├── 1329-sort-the-matrix-diagonally/ │ ├── 1329-sort-the-matrix-diagonally.cpp │ ├── 1329-sort-the-matrix-diagonally.java │ ├── NOTES.md │ ├── README.md │ └── SolutionCode.cpp ├── 1332-remove-palindromic-subsequences/ │ ├── 1332-remove-palindromic-subsequences.java │ └── README.md ├── 1335-minimum-difficulty-of-a-job-schedule/ │ ├── 1335-minimum-difficulty-of-a-job-schedule.java │ ├── NOTES.md │ └── README.md ├── 1337-the-k-weakest-rows-in-a-matrix/ │ ├── 1337-the-k-weakest-rows-in-a-matrix.java │ ├── NOTES.md │ └── README.md ├── 1338-reduce-array-size-to-the-half/ │ ├── 1338-reduce-array-size-to-the-half.cpp │ ├── 1338-reduce-array-size-to-the-half.java │ └── README.md ├── 1339-maximum-product-of-splitted-binary-tree/ │ ├── 1339-maximum-product-of-splitted-binary-tree.java │ ├── NOTES.md │ └── README.md ├── 1342-number-of-steps-to-reduce-a-number-to-zero/ │ ├── 1342-number-of-steps-to-reduce-a-number-to-zero.java │ ├── NOTES.md │ └── README.md ├── 135-candy/ │ ├── 135-candy.java │ ├── NOTES.md │ └── README.md ├── 1354-construct-target-array-with-multiple-sums/ │ ├── 1354-construct-target-array-with-multiple-sums.java │ ├── NOTES.md │ └── README.md ├── 1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/ │ ├── 1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.java │ └── README.md ├── 1381. Design a Stack With Increment Operation/ │ └── 1381-Design-a-Stack-With-Increment-Operation.cpp ├── 1383 Maximum Performance of a Team lc hard.cpp ├── 1383-maximum-performance-of-a-team/ │ ├── 1383-maximum-performance-of-a-team.java │ └── README.md ├── 1396-design-underground-system/ │ ├── 1396-design-underground-system.java │ ├── NOTES.md │ └── README.md ├── 14. Longest Common Prefix.py ├── 1423-maximum-points-you-can-obtain-from-cards/ │ ├── 1423-maximum-points-you-can-obtain-from-cards.java │ ├── NOTES.md │ └── README.md ├── 143-Reorder List.java ├── 1443-minimum-time-to-collect-all-apples-in-a-tree/ │ ├── 1443-minimum-time-to-collect-all-apples-in-a-tree.java │ └── README.md ├── 1448-count-good-nodes-in-binary-tree/ │ ├── 1448-count-good-nodes-in-binary-tree.java │ ├── NOTES.md │ └── README.md ├── 1457 Pseudo-Palindromic Paths in a Binary Tree lc.cpp ├── 1457-pseudo-palindromic-paths-in-a-binary-tree/ │ ├── 1457-pseudo-palindromic-paths-in-a-binary-tree.java │ └── README.md ├── 1461-check-if-a-string-contains-all-binary-codes-of-size-k/ │ ├── 1461-check-if-a-string-contains-all-binary-codes-of-size-k.java │ ├── NOTES.md │ └── README.md ├── 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.java │ ├── NOTES.md │ └── README.md ├── 1473-paint-house-iii/ │ ├── 1473-paint-house-iii.java │ ├── NOTES.md │ └── README.md ├── 1480-running-sum-of-1d-array/ │ ├── 1480-running-sum-of-1d-array.java │ ├── NOTES.md │ └── README.md ├── 15. 3Sum/ │ └── SolutionCode.cpp ├── 151. Reverse Words in a String.java ├── 1519-number-of-nodes-in-the-sub-tree-with-the-same-label/ │ ├── 1519-number-of-nodes-in-the-sub-tree-with-the-same-label.java │ ├── NOTES.md │ └── README.md ├── 1531-string-compression-ii/ │ ├── 1531-string-compression-ii.java │ ├── NOTES.md │ └── README.md ├── 1544-make-the-string-great/ │ ├── 1544-make-the-string-great.java │ ├── NOTES.md │ └── README.md ├── 1578-minimum-time-to-make-rope-colorful/ │ ├── 1578-minimum-time-to-make-rope-colorful.java │ ├── NOTES.md │ └── README.md ├── 1584-min-cost-to-connect-all-points/ │ ├── 1584-min-cost-to-connect-all-points.java │ ├── NOTES.md │ └── README.md ├── 16-3sum-closest/ │ ├── 16-3sum-closest.java │ ├── NOTES.md │ └── README.md ├── 16. 3Sum Closest - leetcode/ │ └── SolutionCode.cpp ├── 160-intersection-of-two-linked-lists/ │ ├── 160-intersection-of-two-linked-lists.java │ ├── NOTES.md │ └── README.md ├── 1631-path-with-minimum-effort/ │ ├── 1631-path-with-minimum-effort.java │ ├── NOTES.md │ └── README.md ├── 1641-count-sorted-vowel-strings/ │ ├── 1641-count-sorted-vowel-strings.java │ ├── NOTES.md │ └── README.md ├── 1642-furthest-building-you-can-reach/ │ ├── 1642-furthest-building-you-can-reach.java │ ├── NOTES.md │ └── README.md ├── 1647-minimum-deletions-to-make-character-frequencies-unique/ │ ├── 1647-minimum-deletions-to-make-character-frequencies-unique.java │ ├── NOTES.md │ └── README.md ├── 1657-determine-if-two-strings-are-close/ │ ├── 1657-determine-if-two-strings-are-close.java │ ├── NOTES.md │ └── README.md ├── 1658-minimum-operations-to-reduce-x-to-zero/ │ ├── 1658-minimum-operations-to-reduce-x-to-zero.java │ ├── NOTES.md │ └── README.md ├── 1662-check-if-two-string-arrays-are-equivalent/ │ ├── 1662-check-if-two-string-arrays-are-equivalent.java │ ├── NOTES.md │ └── README.md ├── 1663-smallest-string-with-a-given-numeric-value/ │ ├── 1663-smallest-string-with-a-given-numeric-value.java │ ├── NOTES.md │ └── README.md ├── 167-two-sum-ii-input-array-is-sorted/ │ ├── 167-two-sum-ii-input-array-is-sorted.java │ ├── NOTES.md │ └── README.md ├── 1679-max-number-of-k-sum-pairs/ │ ├── 1679-max-number-of-k-sum-pairs.java │ └── NOTES.md ├── 1680 Concatenation of Consecutive Binary Numbers med s23.cpp ├── 1680-concatenation-of-consecutive-binary-numbers/ │ ├── 1680-concatenation-of-consecutive-binary-numbers.java │ └── README.md ├── 1689-partitioning-into-minimum-number-of-deci-binary-numbers/ │ ├── 1689-partitioning-into-minimum-number-of-deci-binary-numbers.java │ ├── NOTES.md │ └── README.md ├── 1695-maximum-erasure-value/ │ ├── 1695-maximum-erasure-value.java │ ├── NOTES.md │ └── README.md ├── 1696-jump-game-vi/ │ ├── 1696-jump-game-vi.java │ ├── NOTES.md │ └── README.md ├── 17-letter-combinations-of-a-phone-number/ │ ├── 17-letter-combinations-of-a-phone-number.java │ ├── NOTES.md │ └── README.md ├── 1704-determine-if-string-halves-are-alike/ │ ├── 1704-determine-if-string-halves-are-alike.java │ ├── NOTES.md │ └── README.md ├── 1706-where-will-the-ball-fall/ │ ├── 1706-where-will-the-ball-fall.java │ ├── NOTES.md │ └── README.md ├── 1710-maximum-units-on-a-truck/ │ ├── 1710-maximum-units-on-a-truck.java │ ├── NOTES.md │ └── README.md ├── 1721-swapping-nodes-in-a-linked-list/ │ ├── 1721-swapping-nodes-in-a-linked-list.java │ └── README.md ├── 173-binary-search-tree-iterator/ │ ├── 173-binary-search-tree-iterator.java │ ├── NOTES.md │ └── binary-search-tree-iterator.cpp ├── 1742. Maximum Number of Balls in a Box(leetcode) ├── 1770 Maximum Score from Performing Multiplication Operations lc.cpp ├── 1770-maximum-score-from-performing-multiplication-operations/ │ ├── 1770-maximum-score-from-performing-multiplication-operations.java │ ├── NOTES.md │ └── README.md ├── 179-Largest Number.java ├── 1791. Find Center of Star Graph.java ├── 1832-check-if-the-sentence-is-pangram/ │ ├── 1832-check-if-the-sentence-is-pangram.java │ ├── NOTES.md │ └── README.md ├── 1833-maximum-ice-cream-bars/ │ ├── 1833-maximum-ice-cream-bars.java │ ├── NOTES.md │ └── README.md ├── 1834-single-threaded-cpu/ │ ├── 1834-single-threaded-cpu.java │ ├── NOTES.md │ └── README.md ├── 188-best-time-to-buy-and-sell-stock-iv/ │ ├── 188-best-time-to-buy-and-sell-stock-iv.java │ ├── NOTES.md │ └── README.md ├── 188. Best Time to Buy and Sell Stock IV.cpp ├── 19-remove-nth-node-from-end-of-list/ │ ├── 19-remove-nth-node-from-end-of-list.java │ ├── NOTES.md │ └── README.md ├── 191-number-of-1-bits/ │ ├── 191-number-of-1-bits.java │ ├── NOTES.md │ └── README.md ├── 1926-nearest-exit-from-entrance-in-maze/ │ ├── 1926-nearest-exit-from-entrance-in-maze.java │ ├── NOTES.md │ └── README.md ├── 1962-remove-stones-to-minimize-the-total/ │ ├── 1962-remove-stones-to-minimize-the-total.java │ ├── NOTES.md │ └── README.md ├── 1971-find-if-path-exists-in-graph/ │ ├── 1971-find-if-path-exists-in-graph.java │ └── README.md ├── 199-binary-tree-right-side-view/ │ ├── 199-binary-tree-right-side-view.java │ ├── NOTES.md │ └── README.md ├── 1991-find-the-middle-index-in-array/ │ ├── 1991-find-the-middle-index-in-array.java │ ├── NOTES.md │ └── README.md ├── 1996-the-number-of-weak-characters-in-the-game/ │ ├── 1996-the-number-of-weak-characters-in-the-game.cpp │ ├── 1996-the-number-of-weak-characters-in-the-game.java │ ├── NOTES.md │ └── README.md ├── 200-number-of-islands/ │ ├── 200-number-of-islands.java │ ├── NOTES.md │ └── README.md ├── 2007 Find Original Array From Doubled Array lc.cpp ├── 2007-find-original-array-from-doubled-array/ │ ├── 2007-find-original-array-from-doubled-array.java │ ├── NOTES.md │ └── README.md ├── 2095-delete-the-middle-node-of-a-linked-list/ │ ├── 2095-delete-the-middle-node-of-a-linked-list.java │ └── NOTES.md ├── 2131-longest-palindrome-by-concatenating-two-letter-words/ │ ├── 2131-longest-palindrome-by-concatenating-two-letter-words.java │ └── README.md ├── 2136-earliest-possible-day-of-full-bloom/ │ ├── 2136-earliest-possible-day-of-full-bloom.java │ └── NOTES.md ├── 215-kth-largest-element-in-an-array/ │ ├── 215-kth-largest-element-in-an-array.java │ └── NOTES.md ├── 216-combination-sum-iii/ │ ├── 216-combination-sum-iii.java │ ├── NOTES.md │ └── README.md ├── 218-the-skyline-problem/ │ ├── 218-the-skyline-problem.java │ ├── NOTES.md │ └── README.md ├── 2225-find-players-with-zero-or-one-losses/ │ ├── 2225-find-players-with-zero-or-one-losses.java │ ├── NOTES.md │ └── README.md ├── 2244-minimum-rounds-to-complete-all-tasks/ │ ├── 2244-minimum-rounds-to-complete-all-tasks.java │ ├── NOTES.md │ └── README.md ├── 2246-longest-path-with-different-adjacent-characters/ │ ├── 2246-longest-path-with-different-adjacent-characters.java │ ├── NOTES.md │ └── README.md ├── 225-implement-stack-using-queues/ │ ├── 225-implement-stack-using-queues.java │ └── NOTES.md ├── 2256-minimum-average-difference/ │ ├── 2256-minimum-average-difference.java │ ├── NOTES.md │ └── README.md ├── 2279-maximum-bags-with-full-capacity-of-rocks/ │ ├── 2279-maximum-bags-with-full-capacity-of-rocks.java │ ├── NOTES.md │ └── README.md ├── 23-Merge-k-Sorted-Lists/ │ ├── 23-Merge-k-Sorted-Lists.cpp │ ├── NOTES.md │ └── README.md ├── 230-kth-smallest-element-in-a-bst/ │ ├── 230-kth-smallest-element-in-a-bst.java │ └── NOTES.md ├── 234-palindrome-linked-list/ │ ├── 234-palindrome-linked-list.java │ ├── 234-palindrome-linked-list.py │ ├── NOTES.md │ ├── README.md │ └── palindrome-linked-list.cpp ├── 234. Palindrome Linked List/ │ └── SolutionCode.cpp ├── 235-lowest-common-ancestor-of-a-binary-search-tree/ │ ├── 235-lowest-common-ancestor-of-a-binary-search-tree.java │ ├── 235-lowest-common-ancestor-of-a-binary-search-tree.py │ ├── NOTES.md │ └── README.md ├── 2359-find-closest-node-to-given-two-nodes/ │ ├── NOTES.md │ └── README.md ├── 236-lowest-common-ancestor-of-a-binary-tree/ │ ├── 236-lowest-common-ancestor-of-a-binary-tree.java │ └── NOTES.md ├── 237-delete-node-in-a-linked-list/ │ ├── 237-delete-node-in-a-linked-list.java │ └── NOTES.md ├── 2389-longest-subsequence-with-limited-sum/ │ ├── 2389-longest-subsequence-with-limited-sum.java │ ├── NOTES.md │ └── README.md ├── 2389_longest_subsequence_with_limited_sum.cpp ├── 2390_removing_stars_from_a_string.cpp ├── 2395_Find_Subarrays_With_Equal_Sum.cpp ├── 240-search-a-2d-matrix-ii/ │ ├── 240-search-a-2d-matrix-ii.java │ ├── NOTES.md │ └── README.md ├── 242-valid-anagram/ │ ├── 242-valid-anagram.java │ ├── NOTES.md │ └── README.md ├── 2421-number-of-good-paths/ │ ├── 2421-number-of-good-paths.java │ └── NOTES.md ├── 2429-minimize-xor/ │ ├── 2429-minimize-xor.cpp │ ├── Notes.md │ └── Readme.md ├── 2453-destroy-sequential-targets/ │ ├── 2453-destroy-sequential-targets.java │ └── NOTES.md ├── 268-missing-number/ │ ├── 268-missing-number.java │ ├── NOTES.md │ └── README.md ├── 284-peeking-iterator/ │ ├── 284-peeking-iterator.java │ └── README.md ├── 287-find-the-duplicate-number/ │ ├── 287-find-the-duplicate-number.java │ ├── NOTES.md │ └── README.md ├── 289-game-of-life/ │ ├── 289-game-of-life.java │ ├── NOTES.md │ └── README.md ├── 29-divide-two-integers/ │ ├── 29-divide-two-integers.java │ └── NOTES.md ├── 3-longest-substring-without-repeating-characters/ │ ├── 3-longest-substring-without-repeating-characters.java │ ├── NOTES.md │ └── README.md ├── 30-substring-with-concatenation-of-all-words/ │ ├── 30-substring-with-concatenation-of-all-words.java │ ├── 30-substring-with-concatenation-of-all-words.py │ ├── NOTES.md │ └── README.md ├── 300-longest-increasing-subsequence/ │ ├── 300-longest-increasing-subsequence.java │ ├── NOTES.md │ └── README.md ├── 304-range-sum-query-2d-immutable/ │ ├── 304-range-sum-query-2d-immutable.java │ ├── NOTES.md │ └── README.md ├── 307-range-sum-query-mutable/ │ ├── 307-range-sum-query-mutable.java │ ├── NOTES.md │ └── README.md ├── 31-next-permutation/ │ ├── 31-next-permutation.java │ ├── NOTES.md │ ├── README.md │ └── nextPurmutation.cpp ├── 315-count-of-smaller-numbers-after-self/ │ ├── 315-count-of-smaller-numbers-after-self.java │ ├── NOTES.md │ └── README.md ├── 316-remove-duplicate-letters/ │ ├── 316-remove-duplicate-letters.java │ ├── NOTES.md │ └── README.md ├── 318-maximum-product-of-word-lengths/ │ ├── 318-maximum-product-of-word-lengths.java │ ├── NOTES.md │ └── README.md ├── 32-longest-valid-parentheses/ │ ├── 32-longest-valid-parentheses.java │ ├── NOTES.md │ └── README.md ├── 322-coin-change/ │ ├── 322-coin-change.java │ ├── NOTES.md │ └── README.md ├── 326-power-of-three/ │ ├── 326-power-of-three.java │ ├── 326_Power_of_three.cpp │ ├── NOTES.md │ └── README.md ├── 329-longest-increasing-path-in-a-matrix/ │ ├── 329-longest-increasing-path-in-a-matrix.java │ └── README.md ├── 33-search-in-rotated-sorted-array/ │ ├── 33-search-in-rotated-sorted-array.java │ └── README.md ├── 336-palindrome-pairs/ │ ├── 336-palindrome-pairs.java │ ├── NOTES.md │ └── README.md ├── 34-find-first-and-last-position-of-element-in-sorted-array/ │ ├── 34-find-first-and-last-position-of-element-in-sorted-array.java │ └── README.md ├── 341-flatten-nested-list-iterator/ │ ├── 341-flatten-nested-list-iterator.java │ ├── NOTES.md │ └── README.md ├── 342-power-of-four/ │ ├── 342-power-of-four.java │ ├── NOTES.md │ ├── README.md │ └── power of four.cpp ├── 344-reverse-string/ │ ├── 344-reverse-string.java │ ├── NOTES.md │ └── README.md ├── 347-top-k-frequent-elements/ │ ├── 347-top-k-frequent-elements.cpp │ ├── 347-top-k-frequent-elements.java │ ├── NOTES.md │ └── README.md ├── 354-russian-doll-envelopes/ │ ├── 354-russian-doll-envelopes.java │ ├── NOTES.md │ └── README.md ├── 363-max-sum-of-rectangle-no-larger-than-k/ │ ├── 363-max-sum-of-rectangle-no-larger-than-k.cpp │ ├── 363-max-sum-of-rectangle-no-larger-than-k.java │ ├── NOTES.md │ └── README.md ├── 37-Sudoku-solver/ │ ├── 37-Sudoku-solver.js │ └── README.md ├── 371-sum-of-two-integers/ │ ├── 371-sum-of-two-integers.java │ ├── NOTES.md │ └── README.md ├── 376-wiggle-subsequence/ │ ├── 376-wiggle-subsequence.java │ ├── NOTES.md │ └── README.md ├── 377-combination-sum-iv/ │ ├── 377-combination-sum-iv.java │ ├── NOTES.md │ └── README.md ├── 378-kth-smallest-element-in-a-sorted-matrix/ │ ├── 378-kth-smallest-element-in-a-sorted-matrix.java │ └── NOTES.md ├── 383-ransom-note/ │ ├── 383-ransom-note.java │ ├── NOTES.md │ ├── README.md │ ├── ransom-note.cpp │ └── ransome-note-two-approaches.cpp ├── 387-first-unique-character-in-a-string/ │ ├── 387-first-unique-character-in-a-string.java │ ├── NOTES.md │ ├── README.md │ └── first-unique-character-in-a-string.CPP ├── 393-utf-8-validation/ │ ├── 393-utf-8-validation.java │ ├── NOTES.md │ └── README.md ├── 399-evaluate-division/ │ ├── 399-evaluate-division.java │ ├── NOTES.md │ └── README.md ├── 4-median-of-two-sorted-arrays/ │ ├── 4-median-of-two-sorted-arrays.java │ └── NOTES.md ├── 406-queue-reconstruction-by-height/ │ ├── 406-queue-reconstruction-by-height.java │ ├── NOTES.md │ └── README.md ├── 410-split-array-largest-sum/ │ ├── 410-split-array-largest-sum.java │ ├── NOTES.md │ └── README.md ├── 417-pacific-atlantic-water-flow/ │ ├── 417-pacific-atlantic-water-flow.java │ ├── NOTES.md │ └── README.md ├── 417_Pacific Atlantic Water Flow.cpp ├── 42 Trapping Rain Water hd s18.cpp ├── 42-trapping-rain-water/ │ ├── 42-trapping-rain-water.java │ ├── NOTES.md │ └── README.md ├── 429-n-ary-tree-level-order-traversal/ │ ├── 429-n-ary-tree-level-order-traversal.cpp │ ├── 429-n-ary-tree-level-order-traversal.java │ ├── NOTES.md │ └── README.md ├── 456-132-pattern/ │ ├── 456-132-pattern.java │ ├── NOTES.md │ └── README.md ├── 458-poor-pigs/ │ ├── 458-poor-pigs.java │ ├── NOTES.md │ └── README.md ├── 462-minimum-moves-to-equal-array-elements-ii/ │ ├── 462-minimum-moves-to-equal-array-elements-ii.java │ ├── NOTES.md │ └── README.md ├── 47-permutations-ii/ │ ├── 47-permutations-ii.java │ ├── NOTES.md │ └── README.md ├── 473-matchsticks-to-square/ │ ├── 473-matchsticks-to-square.java │ ├── NOTES.md │ └── README.md ├── 474-ones-and-zeroes/ │ ├── 474-ones-and-zeroes.java │ ├── NOTES.md │ └── README.md ├── 48-rotate-image/ │ ├── 48-Rotate-Image.cpp │ ├── 48-rotate-image.java │ ├── NOTES.md │ └── README.md ├── 5-longest-palindromic-substring/ │ ├── 5-longest-palindromic-substring.java │ ├── NOTES.md │ └── README.md ├── 50-powx-n/ │ ├── 50-powx-n.java │ ├── NOTES.md │ └── README.md ├── 509-fibonacci-number/ │ ├── 509-fibonacci-number.java │ ├── NOTES.md │ └── README.md ├── 51-n-queens/ │ ├── 51-n-queens.java │ ├── NOTES.md │ └── README.md ├── 52-n-queens-ii/ │ ├── 52-n-queens-ii.java │ ├── NOTES.md │ └── README.md ├── 53-maximum-subarray/ │ ├── 53-maximum-subarray.java │ ├── Maximum Subarray.py │ ├── NOTES.md │ └── README.md ├── 535-encode-and-decode-tinyurl/ │ ├── 535-encode-and-decode-tinyurl.java │ ├── NOTES.md │ └── README.md ├── 538-convert-bst-to-greater-tree/ │ ├── 538-convert-bst-to-greater-tree.java │ ├── NOTES.md │ └── README.md ├── 541-reverse-string-ii/ │ ├── 541-reverse-string-ii.java │ ├── NOTES.md │ └── README.md ├── 557 Reverse Words in a String III easy lc s22.cpp ├── 557-reverse-words-in-a-string-iii/ │ ├── 557-reverse-words-in-a-string-iii.java │ └── NOTES.md ├── 560. Subarray Sum Equals K/ │ └── 560. Subarray Sum Equals K.cpp ├── 576-out-of-boundary-paths/ │ ├── 576-out-of-boundary-paths.java │ ├── NOTES.md │ └── README.md ├── 581-shortest-unsorted-continuous-subarray/ │ ├── 581-shortest-unsorted-continuous-subarray.java │ ├── NOTES.md │ └── README.md ├── 583-delete-operation-for-two-strings/ │ ├── 583-delete-operation-for-two-strings.java │ ├── NOTES.md │ └── README.md ├── 59-spiral-matrix-ii/ │ ├── 59-spiral-matrix-ii.java │ ├── NOTES.md │ └── README.md ├── 6-zigzag-conversion/ │ ├── 6-zigzag-conversion.java │ ├── NOTES.md │ └── README.md ├── 606-construct-string-from-binary-tree/ │ ├── 606-construct-string-from-binary-tree.java │ ├── NOTES.md │ └── README.md ├── 609 Find Duplicate File in System lc med s19.cpp ├── 609-find-duplicate-file-in-system/ │ ├── 609-find-duplicate-file-in-system.java │ ├── NOTES.md │ └── README.md ├── 62-unique-paths/ │ ├── 62-unique-paths.java │ ├── NOTES.md │ └── README.md ├── 622-design-circular-queue/ │ ├── 622-design-circular-queue.java │ ├── NOTES.md │ └── README.md ├── 623-add-one-row-to-tree/ │ ├── 623-add-one-row-to-tree.java │ ├── NOTES.md │ └── README.md ├── 629-k-inverse-pairs-array/ │ ├── 629-k-inverse-pairs-array.java │ ├── NOTES.md │ └── README.md ├── 63-unique-paths-ii/ │ ├── 63-unique-paths-ii.java │ ├── NOTES.md │ └── README.md ├── 630-course-schedule-iii/ │ ├── 630-course-schedule-iii.java │ └── README.md ├── 637-average-of-levels-in-binary-tree/ │ ├── 637-average-of-levels-in-binary-tree.cpp │ ├── 637-average-of-levels-in-binary-tree.java │ └── README.md ├── 637-average-of-levels-in-binary-tree.py ├── 647-palindromic-substrings/ │ ├── 647-palindromic-substrings.java │ └── NOTES.md ├── 653-two-sum-iv-input-is-a-bst/ │ ├── 653-two-sum-iv-input-is-a-bst.java │ ├── NOTES.md │ └── README.md ├── 658-find-k-closest-elements/ │ ├── 658-find-k-closest-elements.java │ └── README.md ├── 659-split-array-into-consecutive-subsequences/ │ ├── 659-split-array-into-consecutive-subsequences.cpp │ ├── 659-split-array-into-consecutive-subsequences.java │ ├── NOTES.md │ └── README.md ├── 665-non-decreasing-array/ │ ├── 665-non-decreasing-array.java │ ├── NOTES.md │ └── README.md ├── 669-trim-a-binary-search-tree/ │ ├── 669-trim-a-binary-search-tree.java │ ├── NOTES.md │ └── README.md ├── 680-valid-palindrome-ii/ │ ├── 680-valid-palindrome-ii.java │ ├── NOTES.md │ └── README.md ├── 682-baseball-game/ │ ├── 682-baseball-game.java │ ├── NOTES.md │ └── README.md ├── 695-max-area-of-island/ │ ├── 695-max-area-of-island.java │ ├── NOTES.md │ ├── README.md │ └── SolutionCode.cpp ├── 698-partition-to-k-equal-sum-subsets/ │ ├── 698-partition-to-k-equal-sum-subsets.java │ └── README.md ├── 7 Segment Display.java ├── 70-climbing-stairs/ │ ├── 70-climbing-stairs.java │ ├── NOTES.md │ └── README.md ├── 700-search-in-a-binary-search-tree/ │ ├── 700-search-in-a-binary-search-tree.java │ ├── NOTES.md │ └── README.md ├── 703-kth-largest-element-in-a-stream/ │ ├── 703-kth-largest-element-in-a-stream.py │ └── NOTES.md ├── 704-binary-search/ │ ├── 704-binary-search.java │ ├── NOTES.md │ └── README.md ├── 705-design-hashset/ │ ├── 705-design-hashset.java │ ├── NOTES.md │ └── README.md ├── 706-design-hashmap/ │ ├── 706-design-hashmap.java │ ├── NOTES.md │ └── README.md ├── 713_Subarray_Product_Less_Than_K.cpp ├── 718-Maximum-Length-of-Repeated-Subarray.cpp ├── 718-maximum-length-of-repeated-subarray/ │ ├── 718-maximum-length-of-repeated-subarray.java │ ├── NOTES.md │ ├── README.md │ └── Solved Using DP.java ├── 718. Maximum Length of Repeated Subarray/ │ └── 718. Maximum Length of Repeated Subarray.cpp ├── 718. Maximum Length of Repeated Subarray lc med s20.cpp ├── 724-find-pivot-index/ │ ├── 724-find-pivot-index.java │ ├── NOTES.md │ └── README.md ├── 729-my-calendar-i/ │ ├── 729-my-calendar-i.java │ ├── NOTES.md │ └── README.md ├── 732-my-calendar-iii/ │ ├── 732-my-calendar-iii.java │ ├── NOTES.md │ └── README.md ├── 74-search-a-2d-matrix/ │ ├── 74-search-a-2d-matrix.java │ ├── NOTES.md │ └── README.md ├── 743-network-delay-time/ │ ├── 743-network-delay-time.java │ ├── NOTES.md │ └── README.md ├── 745-prefix-and-suffix-search/ │ ├── 745-prefix-and-suffix-search.java │ ├── NOTES.md │ └── README.md ├── 746-min-cost-climbing-stairs/ │ ├── 746-min-cost-climbing-stairs.java │ ├── NOTES.md │ └── README.md ├── 76-minimum-window-substring/ │ ├── 76-minimum-window-substring.java │ ├── NOTES.md │ └── README.md ├── 763-partition-labels/ │ ├── 763-partition-labels.java │ ├── NOTES.md │ └── README.md ├── 785-is-graph-bipartite/ │ ├── 785-is-graph-bipartite.java │ ├── NOTES.md │ └── README.md ├── 791-Custom-Sort-String-Leetcode.cpp ├── 792-number-of-matching-subsequences/ │ ├── 792-number-of-matching-subsequences.java │ ├── NOTES.md │ └── README.md ├── 802. Find Eventual Safe States.java ├── 804-unique-morse-code-words/ │ ├── 804-unique-morse-code-words.java │ ├── NOTES.md │ ├── README.md │ └── unique-morse-code.cpp ├── 81-search-in-rotated-sorted-array-ii/ │ ├── 81-search-in-rotated-sorted-array-ii.java │ ├── NOTES.md │ └── README.md ├── 814-binary-tree-pruning/ │ ├── 814-binary-tree-pruning.java │ └── README.md ├── 82-remove-duplicates-from-sorted-list-ii/ │ ├── 82-remove-duplicates-from-sorted-list-ii.java │ ├── NOTES.md │ └── README.md ├── 820-short-encoding-of-words/ │ ├── 820-short-encoding-of-words.java │ ├── NOTES.md │ └── README.md ├── 823-binary-trees-with-factors/ │ ├── 823-binary-trees-with-factors.java │ ├── NOTES.md │ └── README.md ├── 838-push-dominoes/ │ ├── 838-push-dominoes.java │ ├── NOTES.md │ └── README.md ├── 844-backspace-string-compare/ │ ├── 844-backspace-string-compare.java │ ├── NOTES.md │ └── README.md ├── 845_Longest_Mountain_in_Array.cpp ├── 856-score-of-parentheses/ │ ├── 856-score-of-parentheses.java │ ├── NOTES.md │ └── README.md ├── 86-partition-list/ │ ├── 86-partition-list.java │ ├── NOTES.md │ └── README.md ├── 867-transpose-matrix/ │ ├── 867-transpose-matrix.java │ └── README.md ├── 869-Reordered-Power-of-2/ │ └── 869-Reordered-Power-of-2.cpp ├── 871-minimum-number-of-refueling-stops/ │ ├── 871-minimum-number-of-refueling-stops.java │ ├── Minimum-Number-of-Refueling-Stops.cpp │ ├── NOTES.md │ └── README.md ├── 871. Minimum Number of Refueling Stops.cpp ├── 876-middle-of-the-linked-list/ │ ├── 876-middle-of-the-linked-list.java │ ├── NOTES.md │ └── README.md ├── 88-merge-sorted-array/ │ ├── 88-merge-sorted-array.java │ ├── NOTES.md │ └── README.md ├── 881-boats-to-save-people/ │ ├── 881-boats-to-save-people.java │ ├── NOTES.md │ └── README.md ├── 890-find-and-replace-pattern/ │ ├── 890-find-and-replace-pattern.java │ ├── NOTES.md │ └── README.md ├── 895-maximum-frequency-stack/ │ ├── 895-maximum-frequency-stack.java │ ├── NOTES.md │ └── README.md ├── 897-increasing-order-search-tree/ │ ├── 897-increasing-order-search-tree.java │ ├── NOTES.md │ └── README.md ├── 905-sort-array-by-parity/ │ ├── 905-sort-array-by-parity.java │ ├── NOTES.md │ └── README.md ├── 91-decode-ways/ │ ├── 91-decode-ways.java │ ├── NOTES.md │ └── README.md ├── 916-word-subsets/ │ ├── 916-word-subsets.java │ ├── NOTES.md │ └── README.md ├── 92-reverse-linked-list-ii/ │ ├── 92-reverse-linked-list-ii.java │ ├── NOTES.md │ └── README.md ├── 923-3sum-with-multiplicity/ │ ├── 923-3sum-with-multiplicity.java │ ├── NOTES.md │ └── README.md ├── 936-stamping-the-sequence/ │ ├── 936-stamping-the-sequence.java │ ├── NOTES.md │ ├── README.md │ ├── Stamping The Sequence.cpp │ └── stamping-the-sequence.cpp ├── 94-binary-tree-inorder-traversal/ │ ├── 94-binary-tree-inorder-traversal.java │ ├── Binary Tree InOrder Traversal lc.cpp │ ├── NOTES.md │ └── README.md ├── 94. Binary Tree Inorder Traversal.cpp ├── 948 Bag of Tokens lc med.cpp ├── 948-bag-of-tokens/ │ ├── 948-bag-of-tokens.java │ ├── NOTES.md │ └── README.md ├── 96-Unique Binary Search Trees.java ├── 967-numbers-with-same-consecutive-differences/ │ ├── 967-numbers-with-same-consecutive-differences.java │ ├── NOTES.md │ └── README.md ├── 968-binary-tree-cameras/ │ ├── 968-binary-tree-cameras.java │ ├── NOTES.md │ └── README.md ├── 97-interleaving-string/ │ ├── 97-interleaving-string.java │ ├── NOTES.md │ └── README.md ├── 98-validate-binary-search-tree/ │ ├── 98-validate-binary-search-tree.java │ ├── NOTES.md │ └── README.md ├── 981-time-based-key-value-store/ │ ├── 981-time-based-key-value-store.java │ ├── NOTES.md │ └── README.md ├── 985 Sum of Even Numbers After Queries lc med.cpp ├── 985-sum-of-even-numbers-after-queries/ │ ├── 985-sum-of-even-numbers-after-queries.java │ ├── NOTES.md │ └── README.md ├── 987-vertical-order-traversal-of-a-binary-tree/ │ ├── 987-vertical-order-traversal-of-a-binary-tree.java │ ├── NOTES.md │ └── README.md ├── 99-recover-binary-search-tree/ │ ├── 99-recover-binary-search-tree.java │ └── README.md ├── 990-satisfiability-of-equality-equations/ │ ├── 990-satisfiability-of-equality-equations.java │ ├── NOTES.md │ └── README.md ├── 991-broken-calculator/ │ ├── 991-broken-calculator.java │ ├── NOTES.md │ └── README.md ├── Add 1 to linked list.java ├── Add Binary Strings.java ├── Add Digits.java ├── Add One To Array.java ├── Add Two Numbers.java ├── Add all greater values to every node in a BST.java ├── Add binary.java ├── Adding Array Elements.java ├── Adventure in a Maze - GFG/ │ ├── README.md │ └── adventure-in-a-maze.java ├── Alien Dictionary - GFG/ │ └── Alien Dictionary.cpp ├── All Elements in Two Binary Search Trees.java ├── All Factors.py ├── All Possible Combinations.java ├── All Unique Permutations.java ├── Allocate minimum number of pages.cpp ├── Alternate positive and negative numbers.cpp ├── Alternate positive and negative numbers.java ├── Anagram of String.java ├── Anagrams.java ├── Anti Diagonals.py ├── Arithmetic Slices.java ├── Array 3 Pointers.java ├── Array Partition - GFG/ │ ├── README.md │ └── array-partition.java ├── Array Sum.java ├── Array to BST - GFG/ │ ├── README.md │ └── array-to-bst.java ├── Assign Mice to Holes.java ├── Assignment Problem - GFG/ │ ├── README.md │ ├── assignment-problem.cpp │ ├── assignment-problem.java │ ├── assignment-problem.py │ └── hungarian_java(not_accepted).java ├── Average of level in Binary tree.cpp ├── Average of levels in binary tree.java ├── BST To Max Heap.cpp ├── BST to greater sum tree - GFG/ │ ├── README.md │ └── bst-to-greater-sum-tree.java ├── BST to max heap GFG/ │ └── BstToMaxHeap.cpp ├── BST to max heap gfg med.cpp ├── BST-to-max-Heap/ │ ├── BSTtoMaxHeap.java │ ├── Solution.cpp │ └── question.md ├── Bag Of Tokens.java ├── Balance Array.java ├── Balanced Binary Tree.java ├── Balanced Parantheses!.java ├── Ball Coloring.cpp ├── Ball coloring.cpp ├── Ball coloring.java ├── Ball coloring.py ├── Ball-Coloring/ │ ├── ball_coloring.java │ └── question.md ├── Best Time to Buy and Sell Stock IV.java ├── Best Time to Buy and Sell Stock.java ├── Biconnected Graph.java ├── Bike Racing - GFG/ │ ├── README.md │ └── bike-racing.java ├── Binary Matrix with at most K 1s.java ├── Binary Tree Pruning lc.cpp ├── Binary Tree Pruning.java ├── Bipartite Graph - GFG/ │ ├── README.md │ └── bipartite-graph.java ├── Bit Difference - GFG/ │ └── Bit Difference.cpp ├── Bitwise AND of the Array.java ├── Black Shapes.java ├── Book_Allcoation_Problem.cpp ├── Brackets in Matrix Chain Multiplication - GFG/ │ ├── README.md │ ├── brackets-in-matrix-chain-multiplication.cpp │ └── brackets-in-matrix-chain-multiplication.java ├── Brain Game - GFG/ │ ├── README.md │ ├── brain-game.cpp │ └── brain-game.java ├── Breadth first search.cpp ├── Broken blocks - GFG/ │ ├── README.md │ └── broken-blocks.java ├── Burning Tree.cpp ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Can Make Triangle.java ├── Can Place Flowers.java ├── Capacity To Ship Packages Within D Days.java ├── Capitalize the Title ├── Case-specific Sorting of Strings.java ├── Case-specific Sorting of Strings.py ├── Case-specific Sorting string.cpp ├── Ceil in BST.java ├── Champagne Tower.java ├── Change Bits - GFG/ │ ├── README.md │ └── change-bits.java ├── Check Mirror in N-ary tree.java ├── Check Palindrome!.java ├── Check if Every Row and Column Contains All Numbers ├── Check if subtree ├── Cherry Pickup II (LC) ├── Chips Factory.java ├── Chocolate_Distribution_Problem_gfg.cpp ├── Choose and Swap - GFG/ │ ├── README.md │ └── choose-and-swap.java ├── Climbing Stairs.java ├── Clone Graph.java ├── Clone a stack without using extra space ├── Closest Palindrome - GFG/ │ ├── README.md │ └── closest-palindrome.java ├── Coin Piles - GFG/ │ ├── README.md │ └── coin-piles.java ├── Coins of Geekland.java ├── Combination Sum II.java ├── Combination Sum.java ├── Combinations.java ├── Compare Version Numbers.java ├── Complete Binary Tree.java ├── Composite And Prime.java ├── Composite and Prime gfg med s18.cpp ├── Composite and Prime.cpp ├── Composite and Prime.java ├── Composite and Prime.py ├── Composite-and-prime.cpp ├── Compute Before Matrix.java ├── Concatenate two numbers.java ├── Connect Ropes.java ├── Consecutive Parent - Child.java ├── Construct BST from Preorder.java ├── Construct Binary Tree From Inorder And Preorder.java ├── Construct String With Repeat Limit.java ├── Construct String from Binary Tree lc easy.cpp ├── Construct String from Binary Tree.java ├── Container With Most Water.java ├── Contiguous Binary Array.java ├── Convert Sorted List to Binary Search Tree.java ├── Convert the amount in number to words.java ├── Convert to Palindrome.java ├── Copy List with Random Pointer.java ├── Corona Vaccine.java ├── Count All Valid Pickup and Delivery Options.java ├── Count And Say.java ├── Count BST nodes that lie in a given range - GFG/ │ ├── README.md │ └── count-bst-nodes-that-lie-in-a-given-range.java ├── Count Common Words With One Occurrence ├── Count Integers With Even Digit Sum.py ├── Count Operations to Obtain Zero.java ├── Count Palindromic Subsequence.cpp ├── Count Palindromic Subsequences.java ├── Count Smaller elements.java ├── Count Words Obtained After Adding a Letter ├── Count digit groupings of a number - GFG/ │ ├── README.md │ └── count-digit-groupings-of-a-number.java ├── Count occurrences of a given word in a 2-d array(dynamic programming).cpp ├── Count occurrences of a given word in a 2-d array.cpp ├── Count occurrences of a given word in a 2-d array.java ├── Count occurrences of a given word in a 2-d array.py ├── Count pairs in array divisible by K - GFG/ │ ├── README.md │ └── count-pairs-in-array-divisible-by-k.java ├── Count possible ways to construct buildings - GFG/ │ ├── README.md │ └── count-possible-ways-to-construct-buildings.java ├── Count subsequences of type a^i, b^j, c^k - GFG/ │ ├── README.md │ └── count-subsequences-of-type-ai-bj-ck.java ├── Count the paths - GFG/ │ ├── README.md │ └── count-the-paths.java ├── Count-occurrences-of-a-given-string-in-2d-array.cpp ├── Count_occurences_of_a_given_word_in_a_2-d_array/ │ ├── Solution.java │ └── question.md ├── Counting Bits.java ├── Counts Zeros Xor Pairs - GFG/ │ ├── README.md │ └── counts-zeros-xor-pairs.java ├── Course Schedule - GFG/ │ ├── README.md │ └── course-schedule.java ├── Cousins of a given node.java ├── Covered-Uncovered Nodes.java ├── Create number of weak characters in game.java ├── Delete and Earn.java ├── Delete nodes greater than k.java ├── Deserialize.java ├── Design Add and Search Words Data Structure.java ├── Design Bitset.java ├── Design Browser History/ │ └── Design-Browser-History.cpp ├── Diagonal Traversal of Binary Tree - GFG/ │ ├── README.md │ └── diagonal-traversal-of-binary-tree.java ├── Different Bits Sum Pairwise.java ├── Diffk II.java ├── Diffk.java ├── Digital Root.java ├── Dijkstra’s_Algorithm_Shortest_distance.cpp ├── Distance from the Source (Bellman-Ford Algorithm).java ├── Distinct Numbers in Window.java ├── Distinct Subsequences.java ├── Distinct palindromic substrings.java ├── Distribute in Circle!.java ├── Divisible by 60.java ├── Dungeon Princess.java ├── Earthquake and the Paint Shop - GFG/ │ ├── README.md │ └── earthquake-and-the-paint-shop.java ├── Egg Dropping Puzzle.java ├── Elements in the Range.java ├── Equivalent Sub-Arrays - GFG/ │ ├── README.md │ └── equivalent-sub-arrays.java ├── Escape the Forbidden Forest.java ├── Eulerian Path in an Undirected Graph - GFG/ │ ├── README.md │ └── eulerian-path-in-an-undirected-graph.java ├── Evaluate Expression To True.java ├── Evaluate Expression(Postfix).java ├── Even and Odd - GFG/ │ ├── README.md │ └── even-and-odd.java ├── Exactly one swap.java ├── Excel Column Title.java ├── Excel Sheet Column Number.java ├── Exceptionally odd.java ├── Fact Digit Sum/ │ └── Fact-Digit-Sum.cpp ├── Fact Digit Sum.cpp ├── Fact Digit Sum.java ├── Farthest number - GFG/ │ ├── README.md │ └── farthest-number.java ├── File Search.java ├── Fill the Tank - GFG/ │ ├── README.md │ └── fill-the-tank.java ├── Filling Bucket - GFG/ │ ├── README.md │ └── filling-bucket.java ├── Find All Anagrams in a String.java ├── Find Last Digit.java ├── Find Missing And Repeating.java ├── Find Original Array From Doubled Array.java ├── Find Prime numbers in a range.java ├── Find Second Smallest and Second Largest Element in an array without sorting/ │ └── Find-Second-Smallest-and-Second-Largest-Element-in-an-array-with-out-sorting.cpp ├── Find Three Consecutive Integers That Sum to a Given Number.py ├── Find Transition Point - GFG/ │ ├── README.md │ └── find-transition-point.java ├── Find a peak element.java ├── Find all distinct subset (or subsequence) sums - GFG/ │ └── Find all distinct subset (or subsequence) sums.cpp ├── Find all distinct subset (or subsequence) sums.java ├── Find all possible paths from top to bottom - GFG/ │ ├── README.md │ └── find-all-possible-paths-from-top-to-bottom.java ├── Find an Replace in String - GFG/ │ ├── README.md │ └── find-an-replace-in-string.java ├── Find length of Loop - GFG/ │ ├── README.md │ └── find-length-of-loop.java ├── Find pairs with given sum in doubly linked list.cpp ├── Find pairs with given sum in doubly linked list.java ├── Find rectangle with corners as 1.java ├── Find the Difference.java ├── Find the Maximum Flow - GFG/ │ ├── README.md │ └── find-the-maximum-flow.java ├── Find the nearest smaller number in left.cpp ├── Find the number of islands.java ├── Find whether path exist - GFG/ │ ├── README.md │ └── find-whether-path-exist.java ├── Find-Pattern/ │ ├── find_patter.java │ └── question.md ├── Finding Profession - GFG/ │ ├── README.md │ └── finding-profession.java ├── Firing employees.java ├── First Missing Integer.java ├── First Repeating element.java ├── Flip.java ├── Foldable Binary Tree.cpp ├── Foldable Binary Tree.java ├── Form a palindrome - GFG/ │ ├── README.md │ └── form-a-palindrome.java ├── Form coils in a matrix - GFG/ │ ├── README.md │ └── form-coils-in-a-matrix.java ├── Fraction Trouble - GFG/ │ ├── README.md │ └── fraction-trouble.java ├── Fraction.java ├── Friends Pairing Problem DP.java ├── Friends Pairing Problem.cpp ├── Friends Pairing Problem.java ├── GFG/ │ ├── 0 -1 Knapsack Problem/ │ │ └── 0 - 1 Knapsack Problem.java │ ├── 2D Hopscotch/ │ │ └── 2D Hopscotch.java │ ├── 3 Divisors/ │ │ └── 3 Divisors.java │ ├── A Game of LCM/ │ │ └── A Game of LCM.java │ ├── A difference of values and indexes/ │ │ └── A difference of values and indexes.java │ ├── Absolute List Sorting/ │ │ └── Absolute List Sorting.java │ ├── Absolute difference divisible by K/ │ │ └── Absolute difference divisible by K.java │ ├── Add Binary Strings/ │ │ └── Add Binary Strings.java │ ├── Aggressive Cows/ │ │ └── Aggressive Cows.java │ ├── Akku and Binary Numbers/ │ │ └── Akku and Binary Numbers.java │ ├── Alex Travelling/ │ │ ├── Alex Travelling.cpp │ │ └── Alex Travelling.java │ ├── Alternate Vowel and Consonant String/ │ │ ├── Alternate Vowel and Consonant String.java │ │ └── ReadMe.md │ ├── Array Pair Sum Divisibility Problem/ │ │ └── Array Pair Sum Divisibility Problem.java │ ├── Array Removals/ │ │ ├── Array Removals.cpp │ │ └── Array Removals.java │ ├── Articulation Point - I/ │ │ └── Articulation Point - I.java │ ├── Asteroid Collision/ │ │ ├── Asteroid Collision.cpp │ │ └── Asteroid Collision.java │ ├── Balanced string/ │ │ └── Balanced string.java │ ├── Base Equivalance/ │ │ └── Base Equivalence.java │ ├── Base Equivalence/ │ │ └── Base Equivalence.java │ ├── Binary Tree to DLL/ │ │ ├── Binary Tree to DLL.cpp │ │ └── Binary Tree to DLL.java │ ├── Black and White/ │ │ └── Black and White.java │ ├── Break a number/ │ │ └── Break a number.java │ ├── Build the smallest/ │ │ └── Build the smallest.java │ ├── Burst Balloons/ │ │ └── Burst Balloons.java │ ├── Check for BST/ │ │ └── Check for BST.java │ ├── Check if all levels of two trees are anagrams or not/ │ │ └── Check if all levels of two trees are anagrams or not.java │ ├── Check if it is possible to convert one string into another with given constraints/ │ │ └── Check if it is possible to convert one string into another with given constraints.java │ ├── Chicks in a Zoo/ │ │ ├── Chicks in a Zoo.cpp │ │ └── Chicks in a Zoo.java │ ├── Complement/ │ │ └── Complement.java │ ├── Construct Binary Tree from String with bracket representation/ │ │ ├── Construct Binary Tree from String with bracket representation.cpp │ │ └── Construct Binary Tree from String with bracket representation.java │ ├── Container With Most Water/ │ │ ├── Container With Most Water.cpp │ │ └── Container With Most Water.java │ ├── Count Lucky Permutations/ │ │ └── Count Lucky Permutations.java │ ├── Count all possible paths from top left to bottom right/ │ │ ├── Count all possible paths from top left to bottom right oc4.cpp │ │ ├── Count all possible paths from top left to bottom right.cpp │ │ └── README.md │ ├── Count even length/ │ │ └── Count even length.java │ ├── Count of Subarrays/ │ │ ├── Count of Subarrays.cpp │ │ ├── Count of Subarrays.java │ │ └── README.md │ ├── Count the Substring/ │ │ ├── Count the Substring.cpp │ │ └── Count the Substring.java │ ├── Counting Elements in Two Arrays/ │ │ ├── Counting Elements in Two Arrays.cpp │ │ ├── Counting Elements in Two Arrays.java │ │ └── Counting Elements in Two Arrays.py │ ├── Cycle in Directed Graph/ │ │ └── Cycle in Directed Graph.java │ ├── Cycle in Undirected Graph/ │ │ └── Cycle in Undirected Graph.java │ ├── Decode the string/ │ │ ├── Decode the string.cpp │ │ ├── Decode the string.java │ │ └── README.md │ ├── Distance of nearest cell having 1/ │ │ └── Distance of nearest cell having 1.java │ ├── Earthquake and the Paint Shop/ │ │ ├── Earthquake and the Paint Shop.cpp │ │ └── README.md │ ├── Enemy/ │ │ ├── Enemy.cpp │ │ └── Enemy.java │ ├── Fill up buckets/ │ │ ├── Fill up buckets.cpp │ │ └── Fill up buckets.java │ ├── Filling Bucket/ │ │ ├── Filling Bucket.cpp │ │ ├── Filling Bucket.java │ │ └── README.md │ ├── Find The Safe Position/ │ │ ├── Find The Safe Position s30.cpp │ │ └── Find the Safe Position.java │ ├── Find minimum number of Laptops required/ │ │ ├── Find minimum number of Laptops required.cpp │ │ └── Find minimum number of Laptops required.java │ ├── Find patterns/ │ │ ├── Find patterns.cpp │ │ ├── Find patterns.java │ │ └── README.md │ ├── Find the N-th character/ │ │ └── Find the N-th character.cpp │ ├── Find the first node of loop in linked list/ │ │ └── Find the first node of loop in linked list.java │ ├── Find the longest string/ │ │ └── Find the longest string.java │ ├── Find the maximum GCD of the siblings of a Binary Tree/ │ │ └── Find the maximum GCD of the siblings of a Binary Tree.java │ ├── Fitting The Array/ │ │ ├── Fitting The Array s28.cpp │ │ ├── Fitting The Array.cpp │ │ └── Fitting The Array.java │ ├── Flatten binary tree to linked list/ │ │ ├── Flatten binary tree to linked list.java │ │ └── Readme.md │ ├── Flattening a Linked List/ │ │ └── Flattening a Linked List.java │ ├── Floyd Warshall/ │ │ ├── Floyd Warshall.java │ │ ├── FloydWarshall.cpp │ │ └── README.md │ ├── Form a palindrome/ │ │ └── Form a palindrome.py │ ├── GCD Array/ │ │ └── GCD Array.java │ ├── Geek and Number String/ │ │ └── Geek and Number Str.cpp │ ├── Geek and Strings/ │ │ ├── Geek and Strings.java │ │ └── ReadMe.md │ ├── Geek in a Maze/ │ │ ├── Geek in a maze.java │ │ └── README.md │ ├── Grouping Of Numbers/ │ │ └── Grouping Of Numbers.java │ ├── Hamiltonian Path/ │ │ ├── Hamiltonian Path.cpp │ │ ├── Hamiltonian Path.java │ │ └── README.md │ ├── Help Ishaan/ │ │ ├── Help Ishaan.cpp │ │ ├── Help Ishaan.java │ │ └── README.md │ ├── Help a Thief/ │ │ ├── Help a thief.cpp │ │ └── README.md │ ├── Help the Old Man/ │ │ ├── Help the old man.java │ │ └── README.md │ ├── Hungry Pizza Lovers/ │ │ ├── Hungry pizza lovers.java │ │ └── README.md │ ├── IPL/ │ │ └── IPL.cpp │ ├── IPL 2021 - Match Day 2/ │ │ └── IPL 2021 - Match Day 2 gfg med s22.cpp │ ├── Ishaan Loves Chocolates/ │ │ ├── Ishaan loves chocolates.py │ │ └── README.md │ ├── Josephus problem/ │ │ └── Josephus problem.java │ ├── Jump Game/ │ │ ├── Jump game.java │ │ └── README.md │ ├── Jumping Numbers/ │ │ ├── Jumping Numbers.cpp │ │ └── README.md │ ├── K-Ary Tree/ │ │ └── README.md │ ├── Knight Walk/ │ │ ├── Knight Walk.cpp │ │ └── Knight Walk.java │ ├── Kth smallest element/ │ │ └── Kth smallest element.py │ ├── LCM Triplet/ │ │ └── LCM Triplet.java │ ├── Largest subtree sum in a tree/ │ │ ├── Largest subtree sum in a tree.cpp │ │ └── Largest subtree sum in a tree.java │ ├── Last modified ball/ │ │ └── Last modified ball.java │ ├── Longest Bitonic subsequence/ │ │ └── Longest Bitonic subsequence.java │ ├── Longest Perfect Piece/ │ │ └── Longest Perfect Piece.java │ ├── Magic Triplets/ │ │ └── Magic Triplets.java │ ├── Majority Element/ │ │ ├── Majority Element.java │ │ ├── Majority Element.py │ │ └── README.md │ ├── Make array elements unique/ │ │ └── Make array elements unique.java │ ├── Max Min/ │ │ ├── Max Min.cpp │ │ ├── Max Min.java │ │ ├── Max Min.py │ │ └── README.md │ ├── Maximize the sum of selected numbers from an array to make it empty/ │ │ ├── Maximize the sum of selected numbers from a sorted array to make it empty.cpp │ │ ├── Maximize the sum of selected numbers from an array to make it empty.java │ │ └── README.md │ ├── Maximum Number of Toys/ │ │ └── Maximum Number of Toys.java │ ├── Maximum Profit By Choosing A Subset Of Intervals/ │ │ └── Maximum Profit By Choosing A Subset Of Intervals.java │ ├── Maximum Sub Array/ │ │ └── Maximum Sub Array.java │ ├── Maximum Sub-String after at most K changes/ │ │ ├── Maximum Sub-String after at most K changes.cpp │ │ ├── Maximum Sub-String after at most K changes.java │ │ └── README.md │ ├── Maximum Sum LCM/ │ │ └── Maximum Sum LCM.java │ ├── Maximum Value/ │ │ └── Maximum Value.java │ ├── Maximum of all subarrays of size k/ │ │ └── Maximum of all subarrays of size k.java │ ├── Median in a row-wise sorted Matrix/ │ │ └── Median in a row-wise sorted Matrix.java │ ├── Merge Sort/ │ │ └── Merge Sort.java │ ├── Merge two BST 's/ │ │ └── Merge two BST.cpp │ ├── Min operations/ │ │ └── Min operations.java │ ├── Minimize number of Students to be removed/ │ │ └── Minimize number of Students to be removed.java │ ├── Minimize the sum/ │ │ └── Minimize the sum.java │ ├── Minimum Cost of ropes/ │ │ └── Minimum Cost of ropes.java │ ├── Minimum Costs of Ropes/ │ │ └── Minimum Costs of Ropes.cpp │ ├── Minimum characters to be added at front to make string palindrome/ │ │ ├── Minimum characters to be added at front to make string palindrome oc2.cpp │ │ ├── Minimum characters to be added at front to make string palindrome.cpp │ │ ├── Minimum characters to be added at front to make string palindrome.java │ │ ├── Minimum characters to be added at front to make string palindrome.py │ │ └── README.md │ ├── Minimum number of Coins/ │ │ ├── Minimum number of Coins.cpp │ │ └── Minimum number of Coins.java │ ├── Minimum sum partition/ │ │ ├── Minimum sum partition.cpp │ │ ├── Minimum sum partition.java │ │ └── README.md │ ├── Missing number in matrix.java/ │ │ └── Missing number in matrix.java │ ├── Modified Numbers and Queries/ │ │ ├── Modified Numbers And Queries.java │ │ ├── Modified Numbers and Queries oc3.cpp │ │ ├── Modified Numbers and Queries.py │ │ └── README.md │ ├── Move Last Element to Front of a Linked List/ │ │ ├── Move Last Element to Front of a Linked List 2 different approaches.java │ │ ├── Move Last Element to Front of a Linked List.cpp │ │ ├── Move Last Element to Front of a Linked List.java │ │ └── README.md │ ├── Next Greater Element/ │ │ └── Next Greater Element.java │ ├── Next Happy Number/ │ │ └── Next Happy Number.java │ ├── Nine Divisors/ │ │ ├── Nine Divisors.cpp │ │ └── Nine Divisors.java │ ├── Number Formation/ │ │ ├── Number Formation.cpp │ │ ├── Number Formation.java │ │ └── README.md │ ├── Number Of Islands/ │ │ ├── Number Of Islands.cpp │ │ ├── Number Of Islands.java │ │ └── README.md │ ├── Number Of Open Doors/ │ │ └── Number Of Open Doors.java │ ├── Number of Distinct Islands/ │ │ ├── Number of Distinct Islands oct1.cpp │ │ └── Number of Distinct Islands.py │ ├── Number of turns in binary tree/ │ │ ├── Number of turns in binary tree.cpp │ │ └── Number of turns in binary tree.java │ ├── Phone directory/ │ │ ├── Phone directory.cpp │ │ └── Phone directory.java │ ├── Primes sum/ │ │ ├── Primes sum.cpp │ │ ├── Primes sum.java │ │ └── README.md │ ├── Print Diagonally/ │ │ ├── Print Diagonally.cpp │ │ ├── Print Diagonally.java │ │ └── README.md │ ├── Print leaf nodes from preorder traversal of BST/ │ │ ├── Print leaf nodes from preorder traversal of BST.cpp │ │ ├── Print leaf nodes from preorder traversal of BST.java │ │ └── README.md │ ├── Queries on a matrix/ │ │ └── Queries on a matrix hard s25 gfg.cpp │ ├── Rearrange Array Alternately/ │ │ └── Rearrange Array Alternately.java │ ├── Reorder List/ │ │ └── Reorder List.java │ ├── Replace O's with X's/ │ │ └── Replace O's with X's.cpp │ ├── Replace every element with the least greater element on its right/ │ │ ├── README.md │ │ ├── Replace every element with the least greater element on its right.cpp │ │ └── Replace every element with the least greater element on its right.java │ ├── Reverse Spiral Form of Matrix/ │ │ ├── Reverse Spiral Form of Matrix.cpp │ │ └── Reverse Spiral Form of Matrix.java │ ├── Satisfy the equation/ │ │ └── Satisfy the equation.java │ ├── Save Your Life/ │ │ ├── README.md │ │ ├── Save Your Life.cpp │ │ └── Save Your Life.java │ ├── Search Pattern (KMP-Algorithm)/ │ │ └── Search Pattern (KMP-Algorithm).java │ ├── Search Pattern (Rabin-Karp Algorithm)/ │ │ └── Search Pattern (Rabin-Karp Algorithm).java │ ├── Sequence Fun/ │ │ └── Sequence Fun.java │ ├── Shortest Distance in a Binary Maze/ │ │ ├── README.md │ │ ├── Shortest Distance in a Binary Maze.cpp │ │ └── Shortest Distance in a Binary Maze.java │ ├── Shortest Path by Removing K walls/ │ │ └── Shortest Path by Removing K walls.java │ ├── Shortest Prime Path/ │ │ └── Shortest Prime Path.java │ ├── Shreyansh and his bits/ │ │ └── Shreyansh and his bits.java │ ├── Single valued subtree/ │ │ └── Single valued subtree.java │ ├── Sort an array of 0s, 1s and 2s/ │ │ ├── Sort an array of 0s, 1s and 2s.java │ │ └── Sort an array of 0s,1s and 2s s29.cpp │ ├── Spiral Matrix/ │ │ └── Spiral Matrix.cpp │ ├── Split Array Largest Sum/ │ │ └── Split Array Largest Sum.java │ ├── Stepping Numbers/ │ │ ├── README.md │ │ ├── Stepping Numbers.cpp │ │ └── Stepping Numbers.java │ ├── Substrings of length k with k-1 distinct elements/ │ │ ├── README.md │ │ ├── Substrings of length k with k-1 distinct elements.cpp │ │ └── Substrings of length k with k-1 distinct elements.java │ ├── Sum of Beauty of All Substrings/ │ │ └── Sum of Beauty of All Substrings.java │ ├── The Smurfs/ │ │ ├── The Smurfs.cpp │ │ └── The Smurfs.java │ ├── Tom and jerry/ │ │ ├── Tom and Jerry easy s26.cpp │ │ ├── Tom and Jerry.java │ │ └── Tom and Jerry.py │ ├── Transform to Sum Tree/ │ │ └── Transform to Sum Tree.java │ ├── Two numbers with odd occurrences/ │ │ ├── README.md │ │ ├── Two numbers with odd occurrences.cpp │ │ └── Two numbers with odd occurrences.java │ ├── Unique partitions/ │ │ └── Unique partitions.java │ ├── Wine Buying and Selling/ │ │ └── Wine Buying and Selling.java │ ├── Zero Sum Subarrays/ │ │ └── Zero Sum Subarrays.java │ └── k-th smallest element in BST/ │ └── k-th smallest element in BST.java ├── GFG_Find_all_distinct_subset_(or subsequence ├── Game with nos ├── Game with nos.java ├── Gas Station.java ├── Geek and Number String s23 med.cpp ├── Geek and Number String.cpp ├── Geek and Number String.java ├── Geek and knots.java ├── Generate IP Addresses.cpp ├── Generate IP Addresses.java ├── Generate IP Addresses.py ├── Generate all Parentheses II.java ├── Get min at pop.java ├── Greater of Lesser.java ├── Greater than All.java ├── Hamiltonian Path - GFG/ │ ├── README.md │ └── hamiltonian-path.java ├── Height Using Parent Array.java ├── Highest Product.java ├── Highest Score.java ├── Hit most Balloons.java ├── INVERSIONS.java ├── IPL 2021 - Match Day 2 by AMAN SAINI ├── IPL 2021 - Match Day 2.cpp ├── IPL 2021 - Match Day 2.java ├── IPL 2021 - Match Day 2.py ├── Identical Binary Trees.java ├── Immediate Smaller Element.java ├── Immediate Smaller Element.js ├── Immediate Smaller Element.py ├── Implement Power Function(IB) ├── Implement StrStr.java ├── Implementing Dijkstra Algorithm.java ├── Inorder Traversal of Cartesian Tree.java ├── Inorder linear Traversal.java ├── Insert into a Binary Search Tree ├── Insertion Sort List.java ├── Insertion Sort for Singly Linked List.java ├── Integer To Roman.java ├── Integers in Strings.java ├── Intersection Of Sorted Arrays.java ├── Intersection of Linked Lists.java ├── Interviewbit/ │ ├── Colorful Number/ │ │ ├── Colorful Number.java │ │ └── Colorful Number.py │ ├── Copy List/ │ │ └── Copy List.java │ └── Valid Sudoku/ │ ├── Valid Sudoku.cpp │ └── Valid Sudoku.java ├── Invert the Binary Tree.java ├── Is Subsequence.java ├── IsRectangle.java ├── Jump Game Array.java ├── Jump Game IV ├── K Largest Elements.java ├── K-diff Pairs in an Array.java ├── Kill Captain America - GFG/ │ ├── README.md │ └── kill-captain-america.java ├── Killing Spree - GFG/ │ ├── README.md │ └── killing-spree.java ├── Koko Eating Bananas.java ├── Kth Permutation Sequence.java ├── Kth Row of Pascal's Triangle.java ├── Kth Smallest Absolute Difference.java ├── Kth Smallest Element In Tree.java ├── Kth smallest element.cpp ├── LC 1000. Minimum Cost to Merge Stones.cpp ├── LCP - GFG/ │ ├── README.md │ └── lcp.java ├── LICENSE ├── Largest BST - GFG/ │ ├── README.md │ └── largest-bst.java ├── Largest Number.java ├── Largest Permutation.java ├── Largest Rectangle in Histogram.java ├── Largest number with given sum - GFG/ │ ├── README.md │ └── largest-number-with-given-sum.java ├── Largest prime factor.cpp ├── Largest value in each level.java ├── Last Node in a Complete Binary Tree.java ├── Last digit K count.java ├── Leaders in an array.java ├── Leaves to DLL.java ├── Leetcode/ │ ├── 104 maximum depth of binary tree/ │ │ ├── 104 maximum depth of binary tree.cpp │ │ ├── 104. Maximum Depth of Binary Tree.java │ │ └── README.md │ ├── 112 Path Sum/ │ │ ├── 112 Path Sum oc4.cpp │ │ └── Path Sum.java │ ├── 1155. Number of Dice Rolls With Target Sum/ │ │ ├── 1155 Number of Dice Rolls With Target Sum.cpp │ │ ├── 1155. Number of Dice Rolls With Target Sum.java │ │ └── 1155. Number of Dice Rolls With Target Sum.py │ ├── 1217. Minimum Cost to Move Chips to The Same Position/ │ │ ├── 1217. Minimum Cost to Move Chips to The Same Position.java │ │ ├── Notes.md │ │ └── README.md │ ├── 1252. Cells with Odd Values in a Matrix/ │ │ ├── 1252. Cells with Odd Values in a Matrix.java │ │ ├── Notes.md │ │ └── README.md │ ├── 1304.Find N Unique Integers Sum up to Zero/ │ │ ├── 1304.Find N Unique Integers Sum up to Zero.java │ │ ├── Notes.md │ │ └── README.md │ ├── 15. 3Sum/ │ │ ├── 3sum.java │ │ └── README.md │ ├── 151.Reverse Words in a String/ │ │ └── Reverse Words in a String.java │ ├── 1531. String Compression II/ │ │ └── 1531. String Compression II.cpp │ ├── 1578 Minimum Time to Make Rope Colorful/ │ │ └── 1578 Minimum Time to Make Rope Colorful.cpp │ ├── 1578. Minimum Time to Make Rope Colorful/ │ │ └── 1578. Minimum Time to Make Rope Colorful.py │ ├── 1662. Check If Two String Arrays are Equivalent/ │ │ └── Check If Two String Arrays are Equivalent.java │ ├── 19 Remove Nth Node From End of List/ │ │ ├── 19 Remove Nth Node From End of List.cpp │ │ └── Remove Nth Node from End Of List.java │ ├── 1996. The Number of Weak Characters in the Game/ │ │ └── The Number of Weak Characters in the Game.cpp │ ├── 2095. Delete the Middle Node of a Linked List/ │ │ ├── 2095 Delete the Middle Node of a Linked List.java │ │ └── README.md │ ├── 2124. Check if All A's Appears Before All B's/ │ │ └── 2124. Check if All A's Appears Before All B's.java │ ├── 218 The Skyline Problem/ │ │ └── 218 The Skyline Problem s30.cpp │ ├── 221. Maximal Square/ │ │ └── 221. Maximal Square.java │ ├── 222. Count Complete Tree Nodes/ │ │ └── Count Complete Tree Nodes.java │ ├── 2368. Reachable Nodes With Restrictions/ │ │ └── Reachable Nodes With Restrictions.cpp │ ├── 237. Delete Node in a Linked List/ │ │ ├── Delete Node in a Linked List.cpp │ │ └── Delete Node in a Linked List.java │ ├── 2424. Longest Uploaded Prefix/ │ │ └── 2424. Longest Uploaded Prefix.java │ ├── 2427. Number of Common Factors/ │ │ └── 2427. Number of Common Factors.cpp │ ├── 2428. Maximum Sum of an Hour Glass/ │ │ └── 2428. Maximum Sum of an Hour Glass.cpp │ ├── 263. Ugly Number/ │ │ └── 263. Ugly Number.cpp │ ├── 279. Perfect Squares/ │ │ └── 279. Perfect Squares.cpp │ ├── 336. Palindrome Pairs/ │ │ ├── 336. Palindrome Pairs.java │ │ └── 336. Palindrome pairs.cpp │ ├── 4. Median of Two Sorted Arrays/ │ │ ├── 4. Median of Two Sorted Arrays.java │ │ └── Median of Two Sorted Arrays.cpp │ ├── 401 binary watch/ │ │ ├── 401-binary-watch.java │ │ ├── NOTES.md │ │ └── README.md │ ├── 437 Path Sum III/ │ │ └── pathSum.cpp │ ├── 450 Delete Node in a BST/ │ │ └── deleteNode.java │ ├── 4Sum II/ │ │ └── 4Sum II.java │ ├── 622 Design Circular Queue/ │ │ └── 622 Design Circular Queue med s25.cpp │ ├── 623 Add One Row To Tree/ │ │ ├── Add one row to tree.java │ │ └── ReadMe.md │ ├── 623 Add One Row to Tree/ │ │ └── 623 Add One Row to Tree.java │ ├── 658 Find K Closest Elements/ │ │ ├── 658 Find K Closest Elements s29.cpp │ │ └── Find k Closest Elements.java │ ├── 704 binary search/ │ │ ├── 704-Binary-Search.py │ │ ├── NOTES.md │ │ └── README.md │ ├── 72 Edit distance/ │ │ ├── minDistance.cpp │ │ └── minDistance.java │ ├── 75.Sort colors/ │ │ ├── 75.Sort-colors.java │ │ ├── Notes.md │ │ ├── README.md │ │ └── Sort colors.cpp │ ├── 766.Toeplitz Matrix/ │ │ └── Toeplitz Matrix.java │ ├── 79.Word Search/ │ │ ├── 79. Word Search.cpp │ │ ├── NOTES.md │ │ └── README.md │ ├── 838 Push Dominoes/ │ │ └── 838 Push Dominoes lc med s27.cpp │ ├── 91 Decode Ways/ │ │ └── 91 Decode Ways oc1.cpp │ ├── 92 Reverse Linked List II/ │ │ ├── Reverse Linked List II.cpp │ │ └── Reverse Linked List II.java │ ├── 990 Satisfiability of Equality Equations/ │ │ └── 990 Satisfiability of Equality Equations med s26.cpp │ ├── Break A Palindrome/ │ │ └── Break A Palindrome.java │ ├── K diff pairs/ │ │ └── K diff pairs.cpp │ ├── Merge Overlapping Intervals/ │ │ └── Merge Overlapping Intervals.cpp │ ├── Minimum time to Make Rope Colorful/ │ │ └── Minimum Time to Make Rope Colorful.cpp │ ├── Number of Dice rolls with target sum/ │ │ └── Number of dice rolls.cpp │ ├── Remove Letter To Equalize Frequency/ │ │ └── Remove Letter To Equalize Frequency.cpp │ ├── Sort Colors/ │ │ └── Sort Colors.cpp │ ├── Top K Frequent Words/ │ │ └── Top K Frequent Words.cpp │ └── Two Sum IV-Input is BST/ │ └── Two Sum IV-Input is a BST.java ├── Length of Last Word.java ├── Length of longest palindrome in Linked List.java ├── Length of longest palindrome in linked list.java ├── Letter Phone.java ├── Level Order.java ├── Levels Of Game.java ├── Licence Key Formatting.java ├── License Key Formatting GFG/ │ └── Licence.cpp ├── License Key Formatting med s21.cpp ├── License Key Formatting(explanation in comments).cpp ├── License Key Formatting.cpp ├── License Key Formatting.java ├── Linked List Cycle II.java ├── Linked List Cycle.java ├── Longest Bitonic subsequence.cpp ├── Longest Common Prefix.java ├── Longest Common Subsequence.java ├── Longest Palindrome by Concatenating Two Letter Words ├── Longest Palindromic Subsequence.java ├── Longest Palindromic Substring.java ├── Longest Path in a matrix - GFG/ │ ├── README.md │ └── longest-path-in-a-matrix.java ├── Longest Possible Route in a Matrix with Hurdles - GFG/ │ ├── README.md │ └── longest-possible-route-in-a-matrix-with-hurdles.java ├── Longest Sub-Array with Sum K.cpp ├── Longest Sub-Array with Sum K.java ├── Longest subarray with sum divisible by K - GFG/ │ ├── README.md │ └── longest-subarray-with-sum-divisible-by-k.java ├── Longest substring to form a Palindrome - GFG/ │ ├── README.md │ └── longest-substring-to-form-a-palindrome.java ├── Longest valid Parentheses.java ├── M-Coloring Problem.java ├── MInimum time to fulfil all orders.cpp ├── Magician and Chocolates.java ├── Magnet Array Problem - GFG/ │ ├── README.md │ └── magnet-array-problem.java ├── Majority Element.java ├── Make equal elements Array.java ├── Matrix Chain Multiplication.cpp ├── Matrix Exponentiation - GFG/ │ ├── README.md │ └── matrix-exponentiation.java ├── Matrix Operations.java ├── Matrix Search.java ├── Max Depth of Binary Tree.java ├── Max Distance.java ├── Max Non Negative SubArray.java ├── Max Product Subarray.java ├── Max Rectangle in Binary Matrix.java ├── Max Sum Path in Binary Tree.java ├── Max length chain.cpp ├── Max length chain.java ├── Maximize Distance to Closest Person ├── Maximize The Array - GFG/ │ ├── README.md │ └── maximize-the-array.java ├── Maximize the sum of selected numbers from an array to make it empty - GFG/ │ ├── README.md │ └── maximize-the-sum-of-selected-numbers-from-an-array-to-make-it-empty.java ├── Maximum Depth of Binary Tree.java ├── Maximum GCD of siblings of a binary tree - GFG/ │ ├── README.md │ └── maximum-gcd-of-siblings-of-a-binary-tree.java ├── Maximum Number of Words Found in Sentences.java ├── Maximum Path Sum between 2 Leaf Nodes.cpp ├── Maximum Path in Triangle.java ├── Maximum Product of Increasing Subsequence of Size 3 - GFG/ │ ├── README.md │ └── maximum-product-of-increasing-subsequence-of-size-3.java ├── Maximum Split of Positive Even Integers.py ├── Maximum Twin Sum of a Linked List.java ├── Maximum Width of Binary Tree.java ├── Maximum Winning score.java ├── Maximum XOR of Two Numbers in an Array.java ├── Maximum average subarray - GFG/ │ ├── README.md │ └── maximum-average-subarray.java ├── Maximum level sum.java ├── Maximum number of 2X2 squares.cpp ├── Maximum number of 2X2 squares.java ├── Maximum number of events that can be attended.java ├── Maximum selections - GFG/ │ ├── README.md │ └── maximum-selections.java ├── Maximum sum Rectangle - GFG/ │ ├── README.md │ └── maximum-sum-rectangle.java ├── Maximum sum leaf to root path.java ├── Maximum sum of Non-adjacent nodes.java ├── Maximum sum of increasing order elements from n arrays.java ├── Maximum twin sum of a linkedlist.cpp ├── Maximum-number-of-2X2-squares.cpp ├── Merge Intervals ├── Merge K sorted linked lists.java ├── Merge Nodes in Between Zeros.java ├── Merge Overlapping Intervals.java ├── Merge Two Sorted Array.py ├── Merge Two Sorted Lists ├── Merge Two Sorted Lists.java ├── Merge Without Extra Space.cpp ├── Merge k Sorted Lists.java ├── Merge new Interval.java ├── Merge two Binary Tree.java ├── Merge two binary Max heaps ├── Merge two sorted linked lists - GFG/ │ ├── README.md │ └── merge-two-sorted-linked-lists.java ├── Merging Details - GFG/ │ └── Merging Details.cpp ├── Merging Details _GFG.cpp ├── Merging Details.java ├── Min Coin - GFG/ │ ├── README.md │ └── min-coin.java ├── Min Depth of Binary Tree.java ├── Min Jumps Array.java ├── Min Stack.java ├── Min Steps in Infinite Grid.java ├── Min Sum Path in Matrix.java ├── Min Sum Path in Triangle.java ├── Min sum formed by digits - GFG/ │ ├── README.md │ └── min-sum-formed-by-digits.java ├── Minimize Deviation in Array.java ├── Minimum Add to Make Parentheses Valid/ │ └── Minimum-Add-to-Make-Parentheses-Valid.cpp ├── Minimum Cost to Set Cooking Time.java ├── Minimum Cost to cut a board into squares.cpp ├── Minimum Cost to cut a board into squares.java ├── Minimum Cost to cut a board into squares.py ├── Minimum Exchange GFG/ │ └── MinimumExchange.cpp ├── Minimum Exchange gfg easy sep12.cpp ├── Minimum Exchange.java ├── Minimum Lights to Activate.java ├── Minimum Number in a sorted rotated array - GFG/ │ ├── README.md │ ├── minimum-number-in-a-sorted-rotated-array.java │ └── minimum-number-in-a-sorted-rotated-array.py ├── Minimum Number of Arrows to Burst Balloons(Non Overlapping intervals) ├── Minimum Number of Vertices to Reach All Nodes.java ├── Minimum Operations to Make the Array Alternating.java ├── Minimum Parantheses!.java ├── Minimum Platforms.java ├── Minimum Remove to Make Valid Parentheses/ │ └── Minimum-Remove-to-Make-Valid-Parentheses.cpp ├── Minimum Remove to Make Valid Parentheses.java ├── Minimum Sum of Absolute Differences of Pairs gfg easy.cpp ├── Minimum Sum of Absolute Differences of Pairs.java ├── Minimum Sum of Absolute Differences of Pairs.py ├── Minimum Sum of Four Digit Number After Splitting Digits.java ├── Minimum Swaps GFG (easy solution with comments).cpp ├── Minimum Swaps to Group All 1's Together II.cpp ├── Minimum Swaps to Sort.java ├── Minimum Swaps.java ├── Minimum Time To Fulfill All Orders Using BinarySearch And ApSeries Formula.java ├── Minimum Time to Remove All Cars Containing Illegal Goods.java ├── Minimum X (xor) A - GFG/ │ ├── README.md │ └── minimum-x-xor-a.java ├── Minimum increment/ │ └── decrement to make array non-Increasing - GFG/ │ ├── README.md │ └── minimum-incrementdecrement-to-make-array-non-increasing.java ├── Minimum sum of absolute difference of pairs.cpp ├── Minimum time to fulfil all orders ├── Minimum time to fulfil all orders gfg hard.cpp ├── Minimum time to fulfil all orders.java ├── Minimum time to fulfill all orders.java ├── Minimum times A has to be repeated such that B is a substring of it - GFG/ │ ├── README.md │ └── minimum-times-a-has-to-be-repeated-such-that-b-is-a-substring-of-it.py ├── Minimum-Exchange/ │ ├── Solution.java │ └── question.md ├── Minimum-swaps.cpp ├── Minimum_Cost_to_cut_a_board_into_squares_gfg_greedy.cpp ├── Mirror Reflection.java LeetCode ├── Move Last Element to Front of a Linked List - GFG/ │ ├── README.md │ └── move-last-element-to-front-of-a-linked-list.java ├── Move Zeroes.java ├── Move all zeroes to end of the array.java ├── Move all zeros to the front of the linked list - GFG/ │ ├── README.md │ └── move-all-zeros-to-the-front-of-the-linked-list.java ├── Moving on grid - GFG/ │ ├── README.md │ └── moving-on-grid.java ├── Multiple left rotations of the array.java ├── N Digit numbers with digits in increasing order ├── N by 3 Repeating Number ├── N-th_Tribonacci_Number_leetcode1137.cpp ├── Nearest Smaller Element.java ├── Nearly sorted - GFG/ │ ├── README.md │ └── nearly-sorted.java ├── Negative weight cycle - GFG/ │ ├── README.md │ └── negative-weight-cycle.java ├── Next Permutation ├── Next Pointer Binary Tree.java ├── Next Right Node.cpp ├── Next Right Node.java ├── Next element with greater frequency - GFG/ │ ├── README.md │ └── next-element-with-greater-frequency.java ├── Noble Integer.java ├── Node with highest edge score.cpp ├── Nodes at even distance - GFG/ │ ├── README.md │ └── nodes-at-even-distance.java ├── Nth item through sum - GFG/ │ ├── README.md │ └── nth-item-through-sum.py ├── Number Formation - GFG/ │ ├── README.md │ └── number-formation.java ├── Number of 1 Bits.java ├── Number of Provinces.java ├── Number of Sundays.java ├── Number of Ways to Arrive at Destination gfg med sep16.cpp ├── Number of Ways to Arrive at Destination.cpp ├── Number of Ways to Arrive at Destination.java ├── Number of distict Words with k maximum contiguous vowels.java ├── Number of distinct Words with k maximum contiguous vowels - GFG/ │ ├── README.md │ └── number-of-distinct-words-with-k-maximum-contiguous-vowels.java ├── Number of positive integral solutions - GFG/ │ ├── README.md │ └── number-of-positive-integral-solutions.py ├── Number of ways - GFG/ │ ├── README.md │ └── number-of-ways.java ├── Number-of-ways-to-arrive-destination/ │ ├── Solution.cpp │ └── question.md ├── Numbers-With-Same-Consecutive-Differences.cpp ├── Occurence of Each Number.java ├── Odd Even Rule.java ├── POTD_gfg_The_Bit_Game .py ├── Pair With Given Difference.java ├── Pairs With Given Xor.java ├── Pairs of Non Coinciding Points - GFG/ │ ├── README.md │ └── pairs-of-non-coinciding-points.java ├── Palindrome List.java ├── Palindrome Numbers.java ├── Palindrome Partitioning II.java ├── Palindrome Partitioning.java ├── Palindromic Substrings.java ├── Palindromic Time.java ├── Palindromic Words.java ├── Partition Array According to Given Pivot.java ├── Partition Labels .cpp ├── Partition List.java ├── Partition a Linked List around a given value - GFG/ │ ├── README.md │ └── partition-a-linked-list-around-a-given-value.java ├── Partition a number into two divisible parts - GFG/ │ ├── README.md │ └── partition-a-number-into-two-divisible-parts.java ├── Partition array to K subsets - GFG/ │ ├── README.md │ ├── partition-array-to-k-subsets.java │ └── partition-array-to-k-subsets.py ├── Partition array to K subsets.java ├── Party in Town - GFG/ │ ├── README.md │ └── party-in-town.java ├── Pascal's Triangle.java ├── Path in Directed Graph.java ├── Path in Matrix.java ├── Path to Given Node.java ├── Path with good nodes!.java ├── Perfect Peak of Array.java ├── Permutation in String.java ├── Permutation with Spaces - GFG/ │ ├── README.md │ └── permutation-with-spaces.java ├── Permutations.java ├── Polynomial Addition - GFG/ │ ├── README.md │ └── polynomial-addition.java ├── Positive Negative Pair ├── Postorder Traversal (Iterative).java ├── Postorder Traversal.py ├── Pots of Gold Game.java ├── Power Of 2 and Subsequences GFG/ │ └── powerOf2Sub.cpp ├── Power Of 2 and Subsequences.cpp ├── Power Of 2 and Subsequences.java ├── Power Of 2 and Subsequences.py ├── Power of 2 and Subsequences.cpp ├── Power of 2 and Subsequences.java ├── Power-of-2-&-Subsequences/ │ ├── Solution.cpp │ └── question.md ├── Preorder Traversal.java ├── Preorder to BST.java ├── Previous number in one swap - GFG/ │ ├── README.md │ └── previous-number-in-one-swap.py ├── Prim's_Algorithm.cpp ├── Prime Sum.java ├── Print Diagonally - GFG/ │ ├── README.md │ └── print-diagonally.java ├── Print Pattern using String.java ├── Print the pattern gfg sep_4.cpp ├── Print the pattern.java ├── Probability of Knight - GFG/ │ ├── README.md │ └── probability-of-knight.java ├── Product of Digits.java ├── Product of Primes - GFG/ │ ├── README.md │ └── product-of-primes.java ├── Profit Maximisation.java ├── Pythagorean Triplets.java ├── Queries on Strings - GFG/ │ ├── README.md │ └── queries-on-strings.java ├── Queries on a Matrix.java ├── Queue using two Stacks.java ├── QuickSort on Doubly Linked List.java ├── README.md ├── Rank The Permutations - GFG/ │ ├── README.md │ └── rank-the-permutations.java ├── Rat Maze With Multiple Jumps - GFG/ │ ├── README.md │ └── rat-maze-with-multiple-jumps.java ├── Reaching the heights - GFG/ │ ├── README.md │ └── reaching-the-heights.java ├── Rearrange Geek and his Classmates.java ├── Recursively remove all adjacent duplicates - GFG/ │ ├── README.md │ └── recursively-remove-all-adjacent-duplicates.java ├── Redundant Braces.java ├── Region in BinaryMatrix.java ├── Remove Consecutive Characters.java ├── Remove Covered Intervals.java ├── Remove Duplicates from Sorted Array II.java ├── Remove Duplicates from Sorted List II.java ├── Remove Duplicates from Sorted List.java ├── Remove Half Nodes.java ├── Remove K Digits.java ├── Remove Nth Node from List End.java ├── Remove leading zeros from an IP address.java ├── Repeat and Missing Number Array.java ├── Repeated Character.java ├── Replace every element with the least greater element on its right - GFG/ │ ├── README.md │ └── replace-every-element-with-the-least-greater-element-on-its-right.java ├── Return two prime numbers.java ├── Reverse Bits.java ├── Reverse First K elements of Queue ├── Reverse Level Order.java ├── Reverse Spiral Form of Matrix - GFG/ │ ├── README.md │ └── reverse-spiral-form-of-matrix.java ├── Reverse a Stack using Recursion.cpp ├── Reverse a string using Stack.java ├── Reverse a sublist of a linked list - GFG/ │ ├── README.md │ └── reverse-a-sublist-of-a-linked-list.java ├── Reverse array in groups(GFG)) ├── Reverse the String.cpp ├── Reverse the String.java ├── Reverse-Interger.java ├── Richest Customer Wealth.java ├── RightView in a Binary Tree ├── Robot Bounded In Circle ├── Robots.java ├── Roman To Integer.java ├── Root to Leaf Paths With Sum.java ├── Rotate Image.cpp ├── Rotate List.java ├── Rotate Matrix.java ├── Salutes.java ├── Save Your Life - GFG/ │ ├── README.md │ └── save-your-life.java ├── Score of Parentheses.java ├── Search for a Range.java ├── Search in Bitonic Array!.java ├── Search insert position of K in a sorted array - GFG/ │ ├── README.md │ └── search-insert-position-of-k-in-a-sorted-array.java ├── Searching all indices for matching substring.py ├── Segregate 0s and 1s in an array.java ├── Self Permutation.java ├── Sequential Digits.java ├── Serialize.java ├── Shop in Candy Store - GFG/ │ ├── README.md │ └── shop-in-candy-store.java ├── Shortest Distance in a Binary Maze - GFG/ │ ├── README.md │ └── shortest-distance-in-a-binary-maze.java ├── Shortest Path Visiting All Nodes.java ├── Shortest Path between Cities - GFG/ │ ├── README.md │ └── shortest-path-between-cities.java ├── Shortest Uncommon Subsequence - GFG/ │ ├── README.md │ ├── shortest-uncommon-subsequence.cpp │ └── shortest-uncommon-subsequence.java ├── Shortest Unique prefix for every word.java ├── Shortest_distance_in_Directed_acyclic_graph.cpp ├── Simplify Path.java ├── Single Element in Sorted Array.py ├── Single Number II.java ├── Single Number.java ├── Sliding Window Maximum.java ├── Smaller on Left - GFG/ │ ├── README.md │ └── smaller-on-left.java ├── Smallest Subset With Greater Sum.Java ├── Smallest Subset With Greater Sum.java ├── Smallest Subset with Greater Sum GFG/ │ └── SmallestSubsetWithGreterSum.cpp ├── Smallest Subset with Greater Sum gfg s15.cpp ├── Smallest Subset with Greater Sum.Cpp ├── Smallest Subset with Greater Sum.java ├── Smallest Subset with Max Sum.py ├── Smallest Value of the Rearranged Number.java ├── Smallest distinct window - GFG/ │ └── README.md ├── Smallest factorial number - GFG/ │ ├── README.md │ └── smallest-factorial-number.java ├── Smallest greater elements in whole array - GFG/ │ ├── README.md │ └── smallest-greater-elements-in-whole-array.java ├── Smallest number on left gfg med.cpp ├── Smallest number on left.cpp ├── Smallest number on left.java ├── Smallest number with sum of digits as N and divisible by 10^N.cpp ├── Smallest number with sum of digits as N and divisible by 10^N.java ├── Smallest number with sum of digits as N and divisible by 10^N.py ├── Smallest number with sum of digits as N and divisible by 10powerN.cpp ├── Smallest sum contiguous subarray.cpp ├── Smallest sum contiguous subarray.java ├── Smallest sum contiguous subarray.py ├── Smallest window containing 0, 1 and 2.java ├── SmallestNumberWithSumOfDigitsAsNAndDivisbileBy10ToThePowerN.java ├── Solve-the-Sudoku - GFG/ │ └── Solve-the-Sudoku.java ├── Sort Binary Linked List.java ├── Sort Even and Odd Indices Independently.java ├── Sort List.java ├── Sort by Set Bit Count.java ├── Sorted Array To Balanced BST.java ├── Sorted Insert Position.java ├── Sorted Link List to BST - GFG/ │ └── README.md ├── Special Matrix.java ├── Spidey Sense.java ├── Spiral Matrix.java ├── Spiral Order Matrix II.java ├── Split_Array_Into_Consecutive_subsequence.java ├── Square Root of Integer.java ├── Stack Permutation med gfg sep7.cpp ├── Stack Permutations [GFG POTD(07-09-22)].java ├── Stack Permutations.java ├── Stack Permutations.py ├── Step by Step.java ├── Stepping Numbers - GFG/ │ ├── README.md │ └── stepping-numbers.java ├── Steps by Knight ├── Stock buy and sell - GFG/ │ └── Stock buy and sell.cpp ├── Stone Game IV.java ├── String And Its Frequency.java ├── String formation from substring - GFG/ │ ├── README.md │ └── string-formation-from-substring.java ├── String to Integer (atoi).java ├── Subarray Sum Equals K.java ├── Subarray with equal occurences!.java ├── Subarray with given sum - GFG/ │ └── Subarray with given sum.cpp ├── Subset.java ├── Subsets II.java ├── Subsets with XOR value - GFG/ │ ├── README.md │ └── subsets-with-xor-value.java ├── Subsets.java ├── Sum Of k smallest elements in BST.java ├── Sum Root to Leaf Numbers.java ├── Sum of 7's Multiple.java ├── Sum of K smallest elements in BST.cpp ├── Sum of Root To Leaf Binary Numbers.java ├── Sum of elements between k1'th and k2'th smallest elements - GFG/ │ ├── README.md │ └── sum-of-elements-between-k1th-and-k2th-smallest-elements.java ├── Sum of k smallest elements in BST.cpp ├── Sum of k smallest elements in BST.java ├── Sum of nodes within k distance from target - GFG/ │ ├── README.md │ └── sum-of-nodes-within-k-distance-from-target.java ├── Sum of two large numbers.cpp ├── Sum of two large numbers.java ├── Sum of two numbers without using arithmetic operators - GFG/ │ ├── README.md │ └── sum-of-two-numbers-without-using-arithmetic-operators.java ├── Summary Ranges.java ├── Super Primes - GFG/ │ ├── README.md │ └── super-primes.java ├── Swap Bits.java ├── Swap Kth nodes from ends - GFG/ │ ├── README.md │ └── swap-kth-nodes-from-ends.java ├── Swap Nodes in Pairs.java ├── Swap bits - GFG/ │ ├── README.md │ └── swap-bits.java ├── Symmetric Binary Tree.java ├── The Bit Game easy s24.cpp ├── The bit Game.cpp ├── Theft at World Bank - GFG/ │ ├── README.md │ └── theft-at-world-bank.java ├── Topo_sort.cpp ├── Total Moves For Bishop!.java ├── Towers_CSES.cpp ├── Trailing Zeroes.java ├── Transfiguration.java ├── Transform String - GFG/ │ └── README.md ├── Tree Path Sum.java ├── Triangle and Square - GFG/ │ ├── README.md │ └── triangle-and-square.java ├── Tricky Subset Problem - GFG/ │ ├── README.md │ └── tricky-subset-problem.java ├── Two Sum.java ├── Two Sum.py ├── UTF-8-Validation med lc.cpp ├── Union-Find - GFG/ │ ├── README.md │ └── union-find.java ├── Unique Subsets - GFG/ │ ├── README.md │ └── unique-subsets.java ├── Unit Area of largest region of 1's.cpp ├── Unit Area of largest region of 1's.java ├── Valid Binary Search Tree.java ├── Valid Mountain Array.java ├── Valid Parentheses.java ├── Valid Password.java ├── Validate Stack Sequences.java ├── Verify Prime.java ├── Vertical Sum of a Binary Tree.java ├── Villain Con - GFG/ │ ├── README.md │ └── villain-con.java ├── Vowel and Consonant Substrings!.java ├── Wave Array.java ├── Ways to Decode.java ├── Window String.java ├── Word Break - Part 2 - GFG/ │ ├── README.md │ └── word-break-part-2.java ├── Word Break II.cpp ├── Word Break II.java ├── Word Break.java ├── Word Count.py ├── Word Ladder I.cpp ├── Word Ladder II.py ├── Word Ladder.java ├── Word Pattern.java ├── Word Wrap - GFG/ │ ├── README.md │ └── word-wrap.java ├── X Total Shapes.java ├── XOR Game.java ├── XOR-ing the Subarrays!.java ├── ZigZag Level Order Traversal BT.java ├── Zigzag String.java ├── alternate positive and negative.cpp ├── check if array is sorted and rotated/ │ └── check-if-array-is-rotated-and-sorted.cpp ├── depth first search.cpp ├── rotate-array/ │ └── rotate-array.cpp ├── sorting-characters-by-frequency/ │ └── sorting-characters-by-frequency.cpp ├── split array into consecutive subsequences/ │ └── split-array-into-consecutive-subsequences.cpp ├── string-to-integer(atoi)/ │ └── string-to-integer(atoi).cpp ├── sum of k smallest elements in BST.cpp └── valid parenthesis.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/custom.md ================================================ --- name: Custom issue template about: Describe this issue template's purpose here. title: '' labels: '' assignees: '' --- ================================================ FILE: .github/pull_request_template.md ================================================ **Please fill the details before contributing.** # ⚠️Important!! - [ ] Done reading [CONTRIBUTING.md](https://github.com/Sagar0-0/DsA/blob/main/CONTRIBUTING.md)? # Adding Code PRs?🔥 ⚠️Do not add multiple files for the same solution!!! - [ ] Added problem statement(Readme.md) with solution? - [ ] Contributing new file? - [ ] Appending your code in already existing file? ### From Platform: - [ ] Leetcode - [ ] GFG - [ ] Interviewbit - [ ] Others(only acceptable after DISCUSSIONS) # Migration PRs?🤝 - [ ] Done deleteing file from home directory? - [ ] Added file with correct name and correct directory? ================================================ FILE: 0012-integer-to-roman/0012-integer-to-roman.java ================================================ class Solution { public String intToRoman(int num) { int[] val = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; String[] code = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; StringBuilder sb = new StringBuilder(); while (num > 0) { for (int i = 0; i < 13; i++) { if (num >= val[i]) { num -= val[i]; sb.append(code[i]); break; } } } return sb.toString(); } } ================================================ FILE: 0012-integer-to-roman/0012-integer-to-roman.py ================================================ class Solution: def intToRoman(self, num: int) -> str: d = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'} res = '' for k in d: while num >= k: res += d[k] num -= k return res ================================================ FILE: 0012-integer-to-roman/NOTES.md ================================================ ​ ================================================ FILE: 0012-integer-to-roman/README.md ================================================

12. Integer to Roman

Medium


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:

Given an integer, convert it to a roman numeral.

 

Example 1:

Input: num = 3
Output: "III"
Explanation: 3 is represented as 3 ones.

Example 2:

Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.

Example 3:

Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

 

Constraints:

================================================ FILE: 0026-remove-duplicates-from-sorted-array/0026-remove-duplicates-from-sorted-array.java ================================================ class Solution { public int removeDuplicates(int[] nums) { int idx=0; int i=0; while(i26. 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:

================================================ FILE: 0036-valid-sudoku/0036-valid-sudoku.java ================================================ class Solution { public static boolean isCorrect(char[][] board,int x,int y){ for(int i=0;i bool: seen = sum(([(c, i), (j, c), (i//3, j//3, c)] for i in range(9) for j in range(9) for c in [board[i][j]] if c != '.'), []) return len(seen) == len(set(seen)) ================================================ FILE: 0036-valid-sudoku/NOTES.md ================================================ ​ ================================================ FILE: 0036-valid-sudoku/README.md ================================================

36. 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. Each column must contain the digits 1-9 without repetition.
  3. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

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 1-9 or '.'.
================================================ FILE: 0037-sudoku-solver/0037-sudoku-solver.java ================================================ class Solution { public void solveSudoku(char[][] board) { dfs(0,0,board); } boolean dfs(int i,int j,char[][]board){ if(i==9)return true; if(board[i][j]!='.'){ if(j==8){ return dfs(i+1,0,board); }else{ return dfs(i,j+1,board); } } for(int num=1;num<=9;num++){ board[i][j]=(char)(num+'0'); if(safe(board,i,j)){ boolean ans; if(j==8){ ans=dfs(i+1,0,board); }else{ ans=dfs(i,j+1,board); } if(ans)return true; } board[i][j]='.'; } return false; } boolean notInRow(char arr[][], int row) { HashSet st = new HashSet<>(); for (int i = 0; i < 9; i++) { if (st.contains(arr[row][i])) return false; if (arr[row][i] != '.') st.add(arr[row][i]); } return true; } boolean notInCol(char arr[][], int col) { HashSet st = new HashSet<>(); for (int i = 0; i < 9; i++) { if (st.contains(arr[i][col])) return false; if (arr[i][col] != '.') st.add(arr[i][col]); } return true; } boolean notInBox(char arr[][], int startRow, int startCol) { HashSet st = new HashSet<>(); for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { char curr = arr[row + startRow][col + startCol]; if (st.contains(curr)) return false; if (curr != '.') st.add(curr); } } return true; } boolean safe(char arr[][], int row, int col) { return notInRow(arr, row) && notInCol(arr, col) && notInBox(arr, row - row % 3, col - col % 3); } } ================================================ FILE: 0037-sudoku-solver/NOTES.md ================================================ ​ ================================================ FILE: 0037-sudoku-solver/README.md ================================================

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. Each of the digits 1-9 must occur exactly once in each column.
  3. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

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.
================================================ FILE: 0038-count-and-say/0038-count-and-say.java ================================================ class Solution { public String countAndSay(int n) { StringBuilder sb = new StringBuilder("1"); for (int i = 2; i <= n; i++) { sb = getNextState(sb); } return sb.toString(); } private StringBuilder getNextState(StringBuilder curSb) { StringBuilder nextSb = new StringBuilder(); int len = curSb.length(); int i = 0; while (i < len) { char c = curSb.charAt(i++); int count = 1; while (i < len && c == curSb.charAt(i)) { count++; i++; } nextSb.append(count).append(c); } return nextSb; } } ================================================ FILE: 0038-count-and-say/0038-count-and-say.py ================================================ import re class Solution: def countAndSay(self, n: int) -> str: s = '1' for _ in range(n - 1): s = re.sub(r'(.)\1*', lambda m: str(len(m.group(0))) + m.group(1), s) return s ================================================ FILE: 0038-count-and-say/README.md ================================================

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 substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.

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
================================================ FILE: 0049-group-anagrams/0049-group-anagrams.java ================================================ class Solution { public List> groupAnagrams(String[] strs) { Set> set=new HashSet<>(); Map,Integer>map=new HashMap<>(); List> ans=new ArrayList<>(); for(String s:strs){ Map curr=new HashMap<>(); for(char c:s.toCharArray()){ curr.put(c,curr.getOrDefault(c,0)+1); } if(set.contains(curr)){ int idx=map.get(curr); ans.get(idx).add(s); }else{ set.add(curr); ans.add(new ArrayList<>()); ans.get(ans.size()-1).add(s); map.put(curr,ans.size()-1); } } return ans; } } ================================================ FILE: 0049-group-anagrams/0049-group-anagrams.py ================================================ from collections import defaultdict class Solution: def groupAnagrams(self, strs): letters_to_words = defaultdict(list) for word in strs: letters_to_words[tuple(sorted(word))].append(word) return list(letters_to_words.values()) ================================================ FILE: 0049-group-anagrams/README.md ================================================

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.
================================================ FILE: 0055-jump-game/0055-jump-game.java ================================================ class Solution { public boolean canJump(int[] nums) { int maxReachableDistance=nums[0]; int i=1; while(maxReachableDistance>=i && i=nums.length-1; } } ================================================ FILE: 0055-jump-game/0055-jump-game.py ================================================ class Solution: def canJump(self, nums: List[int]) -> bool: if len(nums) <= 1: return True j = len(nums) - 2 i = len(nums) - 1 while j > -1: if j + nums[j] >= i: i = j j -= 1 else: j -= 1 #print('i', i, 'j', j) if i <= 0: return True else: return False ================================================ FILE: 0055-jump-game/NOTES.md ================================================ ​ ================================================ FILE: 0055-jump-game/README.md ================================================

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
================================================ FILE: 0057-insert-interval/0057-insert-interval.java ================================================ class Solution { public int[][] insert(int[][] intervals, int[] newInterval) { List inter = new ArrayList<>(intervals.length); for(int[] curr : intervals){ if(curr[0] > newInterval[1]){ inter.add(newInterval); newInterval = curr; } else if(curr[1] < newInterval[0]){ inter.add(curr); } else{ int st = Math.min(curr[0],newInterval[0]); int end = Math.max(curr[1],newInterval[1]); newInterval[0] = st; newInterval[1] = end; } } inter.add(newInterval); int[][] retu = new int[inter.size()][]; for(int i=0;i57. Insert Interval

Medium


You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.

Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).

Return intervals after the insertion.

 

Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

 

Constraints:

  • 0 <= intervals.length <= 104
  • intervals[i].length == 2
  • 0 <= starti <= endi <= 105
  • intervals is sorted by starti in ascending order.
  • newInterval.length == 2
  • 0 <= start <= end <= 105
================================================ FILE: 0070-climbing-stairs/0070-climbing-stairs.java ================================================ class Solution { public int climbStairs(int n) { if (n < 3) return n; int oneStep = 1, twoStep = 2; for (int i = 3; i <= n; i++) { int count = oneStep + twoStep; oneStep = twoStep; twoStep = count; } return twoStep; } } ================================================ FILE: 0070-climbing-stairs/NOTES.md ================================================ ​ ================================================ FILE: 0070-climbing-stairs/README.md ================================================

70. 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
================================================ FILE: 0076-minimum-window-substring/0076-minimum-window-substring.java ================================================ class Solution { public String minWindow(String s, String t) { int[] cs = new int[256]; for (char ch : t.toCharArray()) { cs[ch]++; } int l = 0, r = 0, cnt = t.length(); int start = -1, end = s.length(); // substring [start, end) while (r < s.length()) { if (cs[s.charAt(r++)]-- > 0) { cnt--; } while (cnt == 0) { if (cs[s.charAt(l++)]++ == 0) { cnt++; } if (r - l + 1 < end - start) { start = l - 1; end = r; } } } return end - start > s.length() ? "" : s.substring(start, end); } } ================================================ FILE: 0076-minimum-window-substring/NOTES.md ================================================ ​ ================================================ FILE: 0076-minimum-window-substring/README.md ================================================

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?

================================================ FILE: 0079-word-search/0079-word-search.java ================================================ class Solution { int[][] dirs = new int[][] {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; public boolean exist(char[][] board, String word) { int[] alphFreqForBoard = new int[26]; int[] alphFreqForWord = new int[26]; for (char cc : word.toCharArray()) { alphFreqForWord[cc - 'A']++; } for (char[] row : board) { for (char c : row) { alphFreqForBoard[c - 'A']++; } } for (char cc : word.toCharArray()) { if (alphFreqForBoard[cc - 'A'] < alphFreqForWord[cc - 'A']) { return false; } } if (alphFreqForBoard[word.charAt(0) - 'A'] > alphFreqForWord[word.charAt(word.length() - 1) - 'A']) { word = new StringBuilder(word).reverse().toString(); } for(int i = 0; i < board.length; i++) { for(int j = 0; j < board[i].length; j++) { if(dfs(board, word, i, j, 0)) { return true; } } } return false; } private boolean dfs(char[][] board, String word, int i, int j, int ci) { if(ci == word.length()) { return true; } if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) { return false; } char c = board[i][j]; if(c != word.charAt(ci) || c == '#') { return false; } board[i][j] = '#'; for(int[] dir : dirs) { if(dfs(board, word, i + dir[0], j + dir[1], ci + 1)) { board[i][j] = c; // Restore the original character return true; } } board[i][j] = c; // Restore the original character return false; } } ================================================ FILE: 0079-word-search/NOTES.md ================================================ ​ ================================================ FILE: 0079-word-search/README.md ================================================

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?

================================================ FILE: 0093-restore-ip-addresses/0093-restore-ip-addresses.java ================================================ class Solution { private boolean valid(String s, int start, int length) { return length == 1 || (s.charAt(start) != '0' && (length < 3 || s.substring(start, start + length).compareTo("255") <= 0)); } private void helper(String s, int startIndex, List dots, List ans) { final int remainingLength = s.length() - startIndex; final int remainingNumberOfIntegers = 4 - dots.size(); if (remainingLength > remainingNumberOfIntegers * 3 || remainingLength < remainingNumberOfIntegers) { return; } if (dots.size() == 3) { if (valid(s, startIndex, remainingLength)) { StringBuilder sb = new StringBuilder(); int last = 0; for (Integer dot : dots) { sb.append(s.substring(last, last + dot)); last += dot; sb.append('.'); } sb.append(s.substring(startIndex)); ans.add(sb.toString()); } return; } for (int curPos = 1; curPos <= 3 && curPos <= remainingLength; ++curPos) { // Append a dot at the current position. dots.add(curPos); // Try making all combinations with the remaining string. if (valid(s, startIndex, curPos)) { helper(s, startIndex + curPos, dots, ans); } // Backtrack, i.e. remove the dot to try placing it at the next position. dots.remove(dots.size() - 1); } } public List restoreIpAddresses(String s) { List ans = new ArrayList<>(); helper(s, 0, new ArrayList<>(), ans); return ans; } } ================================================ FILE: 0093-restore-ip-addresses/README.md ================================================

93. Restore IP Addresses

Medium


A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.

  • For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses.

Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.

 

Example 1:

Input: s = "25525511135"
Output: ["255.255.11.135","255.255.111.35"]

Example 2:

Input: s = "0000"
Output: ["0.0.0.0"]

Example 3:

Input: s = "101023"
Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

 

Constraints:

  • 1 <= s.length <= 20
  • s consists of digits only.
================================================ FILE: 0100-same-tree/0100-same-tree.java ================================================ class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { // return recursive traversal of tree return inOrderTraversal(q,p); } public boolean inOrderTraversal(TreeNode node1, TreeNode node2) { // initialize boolean result as true boolean result = true; // if one of the nodes is null and the other isn't, result is false if( (node1 == null && node2 != null) || (node2 == null && node1 != null) ) { result = false; } // else determine if node1 isn't null (if so, assumes both nodes aren't null) else if( node1 != null ) { // determine if node1 shares don't value with node2 if( node1.val != node2.val ) { // if so, result is false result = false; } // else (assume node1 and node2 share value) else { // recursively call on left nodes result = inOrderTraversal(node1.left, node2.left); // if result is true for recursive call if( result == true ) { // recursively call on right nodes result = inOrderTraversal(node1.right, node2.right); } } } // return result return result; } } ================================================ FILE: 0100-same-tree/NOTES.md ================================================ ​ ================================================ FILE: 0100-same-tree/README.md ================================================

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
================================================ FILE: 0124-binary-tree-maximum-path-sum/0124-binary-tree-maximum-path-sum.java ================================================ class Solution { public int maxPathSum(TreeNode root) { maxSum = Integer.MIN_VALUE; gainFromSubtree(root); return maxSum; } private int maxSum; // post order traversal of subtree rooted at `root` private int gainFromSubtree(TreeNode root) { if (root == null) { return 0; } // add the path sum from left subtree. Note that if the path // sum is negative, we can ignore it, or count it as 0. // This is the reason we use `Math.max` here. int gainFromLeft = Math.max(gainFromSubtree(root.left), 0); // add the path sum from right subtree. 0 if negative int gainFromRight = Math.max(gainFromSubtree(root.right), 0); // if left or right path sum are negative, they are counted // as 0, so this statement takes care of all four scenarios maxSum = Math.max(maxSum, gainFromLeft + gainFromRight + root.val); // return the max sum for a path starting at the root of subtree return Math.max(gainFromLeft + root.val, gainFromRight + root.val); } } ================================================ FILE: 0124-binary-tree-maximum-path-sum/NOTES.md ================================================ ​ ================================================ FILE: 0124-binary-tree-maximum-path-sum/README.md ================================================

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
================================================ FILE: 0125-valid-palindrome/0125-valid-palindrome.java ================================================ class Solution { public boolean isPalindrome(String s) { int i=0; int j= s.length()-1; while(i125. Valid Palindrome

Easy


A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

 

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.

Example 3:

Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.

 

Constraints:

  • 1 <= s.length <= 2 * 105
  • s consists only of printable ASCII characters.
================================================ FILE: 0131-palindrome-partitioning/0131-palindrome-partitioning.java ================================================ class Solution { public List> partition(String s) { List> Al1 = new ArrayList<>(); List Al2 = new ArrayList<>(); String[][] dp = new String[s.length()][s.length()]; palPart(Al1,Al2,s,0,dp); return Al1; } public void palPart(List> Al1, List Al2,String s, int start,String[][] dp){ if (start == s.length()) Al1.add(new ArrayList<>(Al2)); for (int i=start;i131. 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.

 

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.
================================================ FILE: 0134-gas-station/0134-gas-station.java ================================================ class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int sum = 0, n = gas.length; int gasInTank = 0, start = 0; for(int i=0;i= 0 ? start : -1; } } ================================================ FILE: 0134-gas-station/NOTES.md ================================================ ​ ================================================ FILE: 0134-gas-station/README.md ================================================

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:

  • n == gas.length == cost.length
  • 1 <= n <= 105
  • 0 <= gas[i], cost[i] <= 104
================================================ FILE: 0144-binary-tree-preorder-traversal/0144-binary-tree-preorder-traversal.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List preorderTraversal(TreeNode root) { List list = new ArrayList<>(); preOrder(root,list); return list; } void preOrder(TreeNode root, List list){ if(root==null)return; list.add(root.val); preOrder(root.left,list); preOrder(root.right,list); } } ================================================ FILE: 0144-binary-tree-preorder-traversal/NOTES.md ================================================ ​ ================================================ FILE: 0144-binary-tree-preorder-traversal/README.md ================================================

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?

================================================ FILE: 0149-max-points-on-a-line/0149-max-points-on-a-line.java ================================================ class Solution { public int maxPoints(int[][] points) { int n = points.length; if (n == 1) { return 1; } int result = 2; for (int i = 0; i < n; i++) { Map cnt = new HashMap<>(); for (int j = 0; j < n; j++) { if (j != i) { cnt.merge(Math.atan2(points[j][1] - points[i][1], points[j][0] - points[i][0]), 1, Integer::sum); } } result = Math.max(result, Collections.max(cnt.values()) + 1); } return result; } } ================================================ FILE: 0149-max-points-on-a-line/NOTES.md ================================================ ​ ================================================ FILE: 0149-max-points-on-a-line/README.md ================================================

149. Max Points on a Line

Hard


Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.

 

Example 1:

Input: points = [[1,1],[2,2],[3,3]]
Output: 3

Example 2:

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

 

Constraints:

  • 1 <= points.length <= 300
  • points[i].length == 2
  • -104 <= xi, yi <= 104
  • All the points are unique.
================================================ FILE: 0150-evaluate-reverse-polish-notation/0150-evaluate-reverse-polish-notation.java ================================================ class Solution { public int evalRPN(String[] tokens) { int[] nxtPos = new int[1]; return eval(tokens, tokens.length - 1, nxtPos); } private int eval(String[] tokens, int pos, int[] nxtPos) { char ac = tokens[pos].charAt(0); if (tokens[pos].length() == 1 && (ac == '+' || ac == '-' || ac == '*' || ac == '/')) { // get operands int a = eval(tokens, pos - 1, nxtPos); int b = eval(tokens, nxtPos[0], nxtPos); // perform operation if (ac == '+') { return b + a; } else if (ac == '-') { return b - a; } else if (ac == '*') { return b * a; } else { return b / a; } } else { nxtPos[0] = pos - 1; return Integer.parseInt(tokens[pos]); } } } ================================================ FILE: 0150-evaluate-reverse-polish-notation/NOTES.md ================================================ ​ ================================================ FILE: 0150-evaluate-reverse-polish-notation/README.md ================================================

150. Evaluate Reverse Polish Notation

Medium


Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, and /. Each operand may be an integer or another expression.

Note that division between two integers should truncate toward zero.

It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.

 

Example 1:

Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

 

Constraints:

  • 1 <= tokens.length <= 104
  • tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
================================================ FILE: 0151-reverse-words-in-a-string/0151-reverse-words-in-a-string.java ================================================ class Solution { public String reverseWords(String s) { List arr=new ArrayList<>(); StringBuilder sb=new StringBuilder(); boolean word=false; for(int i=0;i0)arr.add(sb); sb=new StringBuilder(); for(int i=arr.size()-1;i>=0;i--){ sb.append(arr.get(i)); if(i!=0){ sb.append(" "); } } return sb.toString(); } } ================================================ FILE: 0151-reverse-words-in-a-string/NOTES.md ================================================ ​ ================================================ FILE: 0151-reverse-words-in-a-string/README.md ================================================

151. Reverse Words in a String

Medium


Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

 

Example 1:

Input: s = "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: s = "  hello world  "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: s = "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

 

Constraints:

  • 1 <= s.length <= 104
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.

 

Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?

================================================ FILE: 0198-house-robber/0198-house-robber.java ================================================ class Solution { public int rob(int[] nums) { int n = nums.length; if(n == 1) return nums[0]; int dp2=nums[0], dp1=Math.max(nums[0],nums[1]),dp=dp1; for(int i = 2; i < n; i++){ dp = Math.max(dp1, dp2 + nums[i]); dp2 = dp1; dp1 = dp; } return dp; } } ================================================ FILE: 0198-house-robber/README.md ================================================

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
================================================ FILE: 0212-word-search-ii/0212-word-search-ii.java ================================================ class Solution { private static final char HASH_TAG = '#'; private Tree root = new Tree(); public List findWords(char[][] board, String[] words) { for (String word : words) { Tree temp = root; // Test case 60/63 for (int i = word.length() - 1; i >= 0; i--) { int idx = word.charAt(i) - 'a'; if (temp.val[idx] == null) { temp.val[idx] = new Tree(); temp.val[idx].parent = temp; temp.val[idx].idx = idx; } temp = temp.val[idx]; } temp.word = word; } return searchWord(board); } private List searchWord(char[][] board) { List res = new ArrayList<>(); for (int i = 0; i < board.length; i++) for (int j = 0; j < board[0].length; j++) { Tree temp = root; checkWord(res, i, j, board, temp); } return res; } private void checkWord(List res, int y, int x, char[][] board, Tree temp) { if (x >= board[0].length || x < 0 || y >= board.length || y < 0) return; char ch = board[y][x]; if (ch== HASH_TAG || temp.val[ch - 'a'] == null) return; temp = temp.val[ch - 'a']; if (temp.word != null) { res.add(temp.word); temp.word = null; // Test case 17/63: When there is more than one answer Tree ptr = temp; while (ptr.parent != null && ptr.isEmpty()) { int idx = ptr.idx; ptr = ptr.parent; ptr.val[idx] = null; } } board[y][x] = HASH_TAG; checkWord(res, y, x + 1, board, temp); checkWord(res, y, x - 1, board, temp); checkWord(res, y + 1, x, board, temp); checkWord(res, y - 1, x, board, temp); board[y][x] = ch; } class Tree { Tree parent; Tree[] val = new Tree[26]; String word; int idx; public boolean isEmpty() { for (int i = 0; i < 26; i++) if (val[i] != null) return false; return true; } } } ================================================ FILE: 0212-word-search-ii/NOTES.md ================================================ ​ ================================================ FILE: 0212-word-search-ii/README.md ================================================

212. Word Search II

Hard


Given an m x n board of characters and a list of strings words, return all words on the board.

Each word must 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 in a word.

 

Example 1:

Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]

Example 2:

Input: board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []

 

Constraints:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 12
  • board[i][j] is a lowercase English letter.
  • 1 <= words.length <= 3 * 104
  • 1 <= words[i].length <= 10
  • words[i] consists of lowercase English letters.
  • All the strings of words are unique.
================================================ FILE: 0219-contains-duplicate-ii/0219-contains-duplicate-ii.java ================================================ class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { Map list = new HashMap(); for(int i=0; i219. 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
================================================ FILE: 0222-count-complete-tree-nodes/0222-count-complete-tree-nodes.java ================================================ class Solution { public int countNodes(TreeNode root) { if(root == null){ return 0; } int leftDep=1; TreeNode leftNode = root.left; while(leftNode != null){ leftDep++; leftNode = leftNode.left; } int rightDep = 1; TreeNode rightNode = root.right; while(rightNode != null){ rightDep++; rightNode = rightNode.right; } if(leftDep == rightDep){ return (int)Math.pow(2,leftDep)-1; } return countNodes(root.left)+countNodes(root.right)+1; } } ================================================ FILE: 0222-count-complete-tree-nodes/NOTES.md ================================================ ​ ================================================ FILE: 0222-count-complete-tree-nodes/README.md ================================================

222. Count Complete Tree Nodes

Medium


Given the root of a complete binary tree, return the number of the nodes in the tree.

According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Design an algorithm that runs in less than O(n) time complexity.

 

Example 1:

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

Example 2:

Input: root = []
Output: 0

Example 3:

Input: root = [1]
Output: 1

 

Constraints:

  • The number of nodes in the tree is in the range [0, 5 * 104].
  • 0 <= Node.val <= 5 * 104
  • The tree is guaranteed to be complete.
================================================ FILE: 0223-rectangle-area/0223-rectangle-area.java ================================================ class Solution { public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { int areaOfA = (ay2 - ay1) * (ax2 - ax1); int areaOfB = (by2 - by1) * (bx2 - bx1); // calculate x overlap int left = Math.max(ax1, bx1); int right = Math.min(ax2, bx2); int xOverlap = right - left; // calculate y overlap int top = Math.min(ay2, by2); int bottom = Math.max(ay1, by1); int yOverlap = top - bottom; int areaOfOverlap = 0; // if the rectangles overlap each other, then calculate // the area of the overlap if (xOverlap > 0 && yOverlap > 0) { areaOfOverlap = xOverlap * yOverlap; } // areaOfOverlap is counted twice when in the summation of // areaOfA and areaOfB, so we need to subtract it from the // total, to get the toal area covered by both the rectangles int totalArea = areaOfA + areaOfB - areaOfOverlap; return totalArea; } } ================================================ FILE: 0223-rectangle-area/NOTES.md ================================================ ​ ================================================ FILE: 0223-rectangle-area/README.md ================================================

223. Rectangle Area

Medium


Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.

The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).

The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).

 

Example 1:

Rectangle Area
Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
Output: 45

Example 2:

Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
Output: 16

 

Constraints:

  • -104 <= ax1 <= ax2 <= 104
  • -104 <= ay1 <= ay2 <= 104
  • -104 <= bx1 <= bx2 <= 104
  • -104 <= by1 <= by2 <= 104
================================================ FILE: 0224-basic-calculator/0224-basic-calculator.java ================================================ class Solution { int idx; // this index traverse the string in one pass, between different level of recursion public int calculate(String s) { idx = 0; // Initialization should be here return calc(s); } private int calc(String s) { int res = 0, num = 0, sign = 1; while (idx < s.length()) { char c = s.charAt(idx++); if (c >= '0' && c <= '9') num = num * 10 + c - '0'; else if (c == '(') num = calc(s); // ( is start of a new sub-problem, Let recursion solve the sub-problem else if (c == ')') return res + sign * num; else if (c == '+' || c == '-') { // only when we meet a new sign, we know a while number has been read res += sign * num; num = 0; sign = c == '-' ? -1 : 1; } } return res + sign * num; // last number is not processed yet } } ================================================ FILE: 0224-basic-calculator/NOTES.md ================================================ ​ ================================================ FILE: 0224-basic-calculator/README.md ================================================

224. Basic Calculator

Hard


Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

 

Example 1:

Input: s = "1 + 1"
Output: 2

Example 2:

Input: s = " 2-1 + 2 "
Output: 3

Example 3:

Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23

 

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consists of digits, '+', '-', '(', ')', and ' '.
  • s represents a valid expression.
  • '+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid).
  • '-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid).
  • There will be no two consecutive operators in the input.
  • Every number and running calculation will fit in a signed 32-bit integer.
================================================ FILE: 0232-implement-queue-using-stacks/0232-implement-queue-using-stacks.java ================================================ class MyQueue { private Stack s1 = new Stack<>(); private Stack s2 = new Stack<>(); /** Initialize your data structure here. */ public MyQueue() { } /** Push element x to the back of queue. */ public void push(int x) { s1.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() { if (s2.isEmpty()) { while (!s1.isEmpty()) s2.push(s1.pop()); } return s2.pop(); } /** Get the front element. */ public int peek() { if (s2.isEmpty()) { while (!s1.isEmpty()) s2.push(s1.pop()); } return s2.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return s1.isEmpty() && s2.isEmpty(); } } /** * 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(); * boolean param_4 = obj.empty(); */ ================================================ FILE: 0232-implement-queue-using-stacks/NOTES.md ================================================ ​ ================================================ FILE: 0232-implement-queue-using-stacks/README.md ================================================

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.

================================================ FILE: 0236-lowest-common-ancestor-of-a-binary-tree/0236-lowest-common-ancestor-of-a-binary-tree.java ================================================ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null) return root; return left != null ? left : right; } } ================================================ FILE: 0236-lowest-common-ancestor-of-a-binary-tree/NOTES.md ================================================ ​ ================================================ FILE: 0236-lowest-common-ancestor-of-a-binary-tree/README.md ================================================

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.
================================================ FILE: 0237-delete-node-in-a-linked-list/0237-delete-node-in-a-linked-list.java ================================================ class Solution { public void deleteNode(ListNode node) { // Since we know input node is not last node, so nextNode will not be null ListNode nextNode = node.next; // Step 2 node.val = nextNode.val; // Step 3 node.next = nextNode.next; nextNode.next = null; } } ================================================ FILE: 0237-delete-node-in-a-linked-list/NOTES.md ================================================ ​ ================================================ FILE: 0237-delete-node-in-a-linked-list/README.md ================================================

237. Delete Node in a Linked List

Medium


There is a singly-linked list head and we want to delete a node node in it.

You are given the node to be deleted node. You will not be given access to the first node of head.

All the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list.

Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:

  • The value of the given node should not exist in the linked list.
  • The number of nodes in the linked list should decrease by one.
  • All the values before node should be in the same order.
  • All the values after node should be in the same order.

Custom testing:

  • For the input, you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list.
  • We will build the linked list and pass the node to your function.
  • The output will be the entire list after calling your function.

 

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.
================================================ FILE: 0242-valid-anagram/0242-valid-anagram.cpp ================================================ class Solution { public: bool isAnagram(string s, string t) { sort(s.begin(),s.end()); sort(t.begin(),t.end()); if(s==t) return true; else return false; } }; ================================================ FILE: 0242-valid-anagram/0242-valid-anagram.java ================================================ class Solution { public boolean isAnagram(String a, String b) { int[] arr=new int[128]; //O(1) if(a.length()!=b.length()){ return false; } // abca // caba for(int i=0;i242. 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?

================================================ FILE: 0263-ugly-number/0263-ugly-number.java ================================================ class Solution { public boolean isUgly(int n) { while(n!=0){ if(n==1 || n==2 || n==3 || n==5){ return true; } if(n%2==0){ n/=2; } else if(n%3==0){ n/=3; } else if(n%5==0){ n/=5; }else{ return false; } } return false; } } ================================================ FILE: 0263-ugly-number/NOTES.md ================================================ ​ ================================================ FILE: 0263-ugly-number/README.md ================================================

263. Ugly Number

Easy


An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

Given an integer n, return true if n is an ugly number.

 

Example 1:

Input: n = 6
Output: true
Explanation: 6 = 2 × 3

Example 2:

Input: n = 1
Output: true
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.

Example 3:

Input: n = 14
Output: false
Explanation: 14 is not ugly since it includes the prime factor 7.

 

Constraints:

  • -231 <= n <= 231 - 1
================================================ FILE: 0279-perfect-squares/0279-perfect-squares.java ================================================ class Solution { public int numSquares(int n) { int sqrt = (int) Math.sqrt(n); if (sqrt * sqrt == n) // Perfect square return 1; while (n % 4 == 0) // 4^a (8b + 7) n = n / 4; if (n % 8 == 7) return 4; for (int i = 1; i * i <= n; i++) { // Sum of two perfect squares int square = i * i; int base = (int) Math.sqrt(n - square); if (base * base == n - square) return 2; } return 3; } } ================================================ FILE: 0279-perfect-squares/NOTES.md ================================================ ​ ================================================ FILE: 0279-perfect-squares/README.md ================================================

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
================================================ FILE: 0290-word-pattern/0290-word-pattern.java ================================================ class Solution { public boolean wordPattern(String pattern, String s) { String[] words = s.split(" "); Map wordMap = new HashMap<>(); Map charMap = new HashMap<>(); if(pattern.length()!=words.length){ return false; } for(int i= 0;i290. Word Pattern

Easy


Given a pattern and a string s, find if s follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.

 

Example 1:

Input: pattern = "abba", s = "dog cat cat dog"
Output: true

Example 2:

Input: pattern = "abba", s = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false

 

Constraints:

  • 1 <= pattern.length <= 300
  • pattern contains only lower-case English letters.
  • 1 <= s.length <= 3000
  • s contains only lowercase English letters and spaces ' '.
  • s does not contain any leading or trailing spaces.
  • All the words in s are separated by a single space.
================================================ FILE: 0295-find-median-from-data-stream/0295-find-median-from-data-stream.java ================================================ class MedianFinder { ArrayList list; public MedianFinder() { list = new ArrayList<>(); } public void addNum(int num) { int i; if(list.size() > 0){ for (i = 0; (i < list.size() && list.get(i) < num); i++); if(i == -1){ i = 0; } list.add(i , num); }else{ list.add(num); } } public double findMedian() { // System.out.println(list); int index = list.size()/2; if(list.size() % 2 == 0){ return (double) (list.get(index) + list.get(index - 1))/2; }else{ return list.get(index); } } } ================================================ FILE: 0295-find-median-from-data-stream/NOTES.md ================================================ ​ ================================================ FILE: 0295-find-median-from-data-stream/README.md ================================================

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?
================================================ FILE: 0309-best-time-to-buy-and-sell-stock-with-cooldown/0309-best-time-to-buy-and-sell-stock-with-cooldown.java ================================================ class Solution { public int maxProfit(int[] prices) { if (prices == null || prices.length <= 1) { return 0; } int len = prices.length; int[] hold = new int[len]; int[] unHold = new int[len]; hold[0] = -prices[0]; hold[1] = Math.max(-prices[0], -prices[1]); unHold[0] = 0; unHold[1] = Math.max(0, prices[1] - prices[0]); for (int i = 2; i < len; i++) { hold[i] = Math.max(hold[i - 1], unHold[i - 2] - prices[i]); unHold[i] = Math.max(unHold[i - 1], hold[i - 1] + prices[i]); } return unHold[len - 1]; } } ================================================ FILE: 0309-best-time-to-buy-and-sell-stock-with-cooldown/NOTES.md ================================================ ​ ================================================ FILE: 0309-best-time-to-buy-and-sell-stock-with-cooldown/README.md ================================================

309. 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
================================================ FILE: 0328-odd-even-linked-list/0328-odd-even-linked-list.java ================================================ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode oddEvenList(ListNode head) { if(head==null || head.next==null)return head; ListNode oddHead=head; ListNode evenHead=head.next; ListNode odd=head; ListNode even=head.next; while(odd!=null && even!=null && even.next!=null){ odd.next=odd.next.next; even.next=even.next.next; odd=odd.next; even=even.next; } if(odd==null)even.next=oddHead; else odd.next=evenHead; return oddHead; } } ================================================ FILE: 0328-odd-even-linked-list/NOTES.md ================================================ ​ ================================================ FILE: 0328-odd-even-linked-list/README.md ================================================

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:

  • The number of nodes in the linked list is in the range [0, 104].
  • -106 <= Node.val <= 106
================================================ FILE: 0334-increasing-triplet-subsequence/0334-increasing-triplet-subsequence.java ================================================ class Solution { public boolean increasingTriplet(int[] nums) { int first_num = Integer.MAX_VALUE; int second_num = Integer.MAX_VALUE; for(int num:nums) { if(num<=first_num) { first_num = num; } else if(num<=second_num) { second_num = num; }else { return true; } } return false; } } ================================================ FILE: 0334-increasing-triplet-subsequence/NOTES.md ================================================ ​ ================================================ FILE: 0334-increasing-triplet-subsequence/README.md ================================================

334. Increasing Triplet Subsequence

Medium


Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.

 

Example 1:

Input: nums = [1,2,3,4,5]
Output: true
Explanation: Any triplet where i < j < k is valid.

Example 2:

Input: nums = [5,4,3,2,1]
Output: false
Explanation: No triplet exists.

Example 3:

Input: nums = [2,1,5,0,4,6]
Output: true
Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.

 

Constraints:

  • 1 <= nums.length <= 5 * 105
  • -231 <= nums[i] <= 231 - 1

 

Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?
================================================ FILE: 0345-reverse-vowels-of-a-string/0345-reverse-vowels-of-a-string.java ================================================ class Solution { public String reverseVowels(String s) { int i=0; int j=s.length()-1; char[]arr=s.toCharArray(); while(ii && !vowel(arr[j]))j--; if(i>j)break; char temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; i++; j--; } return new String(arr); } boolean vowel(char c){ return switch (c) { case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' -> true; default -> false; }; } } ================================================ FILE: 0345-reverse-vowels-of-a-string/NOTES.md ================================================ ​ ================================================ FILE: 0345-reverse-vowels-of-a-string/README.md ================================================

345. 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 lower and upper cases, more than once.

 

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.
================================================ FILE: 0374-guess-number-higher-or-lower/0374-guess-number-higher-or-lower.java ================================================ /* The guess API is defined in the parent class GuessGame. @param num, your guess @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 int guess(int num); */ public class Solution extends GuessGame { public int guessNumber(int n) { int low = 1; int high = n; while (low <= high) { int mid1 = low + (high - low) / 3; int mid2 = high - (high - low) / 3; int res1 = guess(mid1); int res2 = guess(mid2); if (res1 == 0) return mid1; if (res2 == 0) return mid2; else if (res1 < 0) high = mid1 - 1; else if (res2 > 0) low = mid2 + 1; else { low = mid1 + 1; high = mid2 - 1; } } return -1; } } ================================================ FILE: 0374-guess-number-higher-or-lower/NOTES.md ================================================ ​ ================================================ FILE: 0374-guess-number-higher-or-lower/README.md ================================================

374. Guess Number Higher or Lower

Easy


We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.

You call a pre-defined API int guess(int num), which returns three possible results:

  • -1: Your guess is higher than the number I picked (i.e. num > pick).
  • 1: Your guess is lower than the number I picked (i.e. num < pick).
  • 0: your guess is equal to the number I picked (i.e. num == pick).

Return the number that I picked.

 

Example 1:

Input: n = 10, pick = 6
Output: 6

Example 2:

Input: n = 1, pick = 1
Output: 1

Example 3:

Input: n = 2, pick = 1
Output: 1

 

Constraints:

  • 1 <= n <= 231 - 1
  • 1 <= pick <= n
================================================ FILE: 0380-insert-delete-getrandom-o1/0380-insert-delete-getrandom-o1.java ================================================ class RandomizedSet { List list; HashMap map; public RandomizedSet() { list=new ArrayList<>(); map=new HashMap<>(); } public boolean insert(int val) { if(!map.containsKey(val)){ list.add(val); map.put(val,list.size()-1); return true; } return false; } // Swap value to be removed with last value. Remove now the value at last // index & update map with new index and remove the value to be removed. public boolean remove(int val) { if(map.containsKey(val)){ int index=map.get(val); swap(index); list.remove(list.size()-1); map.remove(val); return true; } return false; } // User defined. private void swap(int index) { int lastIndex=list.size()-1; int lastVal=list.get(lastIndex); int temp=list.get(index); list.set(index,lastVal); map.put(lastVal,index); } public int getRandom() { return list.get(new Random().nextInt(list.size())); } } ================================================ FILE: 0380-insert-delete-getrandom-o1/NOTES.md ================================================ ​ ================================================ FILE: 0380-insert-delete-getrandom-o1/README.md ================================================

380. Insert Delete GetRandom O(1)

Medium


Implement the RandomizedSet class:

  • RandomizedSet() Initializes the RandomizedSet object.
  • bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
  • bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
  • int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.

You must implement the functions of the class such that each function works in average O(1) time complexity.

 

Example 1:

Input
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]

Explanation
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.

 

Constraints:

  • -231 <= val <= 231 - 1
  • At most 2 * 105 calls will be made to insert, remove, and getRandom.
  • There will be at least one element in the data structure when getRandom is called.
================================================ FILE: 0409-longest-palindrome/0409-longest-palindrome.java ================================================ class Solution { public int longestPalindrome(String s) { int[]freq=new int[123]; for(char c:s.toCharArray()){ freq[c]++; } int ans=0; boolean hasOdd=false; for(int i:freq){ if((i&1)==1){ hasOdd=true; ans+=i-1; }else{ ans+=i; } } return hasOdd?ans+1:ans; } } ================================================ FILE: 0409-longest-palindrome/NOTES.md ================================================ ​ ================================================ FILE: 0409-longest-palindrome/README.md ================================================

409. Longest Palindrome

Easy


Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.

Letters are case sensitive, for example, "Aa" is not considered a palindrome here.

 

Example 1:

Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.

Example 2:

Input: s = "a"
Output: 1
Explanation: The longest palindrome that can be built is "a", whose length is 1.

 

Constraints:

  • 1 <= s.length <= 2000
  • s consists of lowercase and/or uppercase English letters only.
================================================ FILE: 0446-arithmetic-slices-ii-subsequence/0446-arithmetic-slices-ii-subsequence.java ================================================ class Solution { public int numberOfArithmeticSlices(int[] A) { int n = A.length; long ans = 0; Map[] cnt = new Map[n]; for (int i = 0; i < n; i++) { cnt[i] = new HashMap<>(i); for (int j = 0; j < i; j++) { long delta = (long)A[i] - (long)A[j]; if (delta < Integer.MIN_VALUE || delta > Integer.MAX_VALUE) { continue; } int diff = (int)delta; int sum = cnt[j].getOrDefault(diff, 0); int origin = cnt[i].getOrDefault(diff, 0); cnt[i].put(diff, origin + sum + 1); ans += sum; } } return (int)ans; } } ================================================ FILE: 0446-arithmetic-slices-ii-subsequence/NOTES.md ================================================ ​ ================================================ FILE: 0446-arithmetic-slices-ii-subsequence/README.md ================================================

446. Arithmetic Slices II - Subsequence

Hard


Given an integer array nums, return the number of all the arithmetic subsequences of nums.

A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

  • For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.
  • For example, [1, 1, 2, 5, 7] is not an arithmetic sequence.

A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.

  • For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].

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

 

Example 1:

Input: nums = [2,4,6,8,10]
Output: 7
Explanation: All arithmetic subsequence slices are:
[2,4,6]
[4,6,8]
[6,8,10]
[2,4,6,8]
[4,6,8,10]
[2,4,6,8,10]
[2,6,10]

Example 2:

Input: nums = [7,7,7,7,7]
Output: 16
Explanation: Any subsequence of this array is arithmetic.

 

Constraints:

  • 1  <= nums.length <= 1000
  • -231 <= nums[i] <= 231 - 1
================================================ FILE: 0451-sort-characters-by-frequency/0451-sort-characters-by-frequency.java ================================================ class Solution { public String frequencySort(String s) { int[] a = new int[750]; for(int i=0;ia[max_freq]) max_freq=i; } sb.append(String.valueOf((char)(max_freq+48)).repeat(a[max_freq])); a[max_freq]=0; } return sb.toString(); } } ================================================ FILE: 0451-sort-characters-by-frequency/NOTES.md ================================================ ​ ================================================ FILE: 0451-sort-characters-by-frequency/README.md ================================================

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.
================================================ FILE: 0452-minimum-number-of-arrows-to-burst-balloons/0452-minimum-number-of-arrows-to-burst-balloons.java ================================================ class Solution { public int findMinArrowShots(int[][] points) { // This Problem is similar to Non Overlapping Interval Problem of Greedy Approach // Link for detiled discussion : http://www.leetcode-solution.com/2019/06/01/0452-minimum-number-of-arrows-to-burst-balloons.html // Base case if(points.length == 0) return 0; // Sort the point accroding to their end points i.e., a[1] - b[1] Arrays.sort(points, (a,b) -> a[1] - b[1]); // Position arrow at end (Extreme Right) as it has maximum chance of hittng there int arrPos = points[0][1]; int count = 1; // Minimun 1 arrow is required to shoot any points for(int i = 1; i < points.length; i++ ) // start with 1 as 0th index end will be check for start of 1st { int left = points[i][0]; int right = points[i][1]; //check whether the arrowFired can burst other balloons. //if not fire arrow at the next point end value if (!(arrPos >= left && arrPos <= right)) { count++; // increase the arrowsFired by 1. arrPos = points[i][1]; // next point end value. } /* if(arrPos >= points[i][0]) // Since Current arrow position than start pos of array that means we can { // continue, but as soon as it not true we break as our current arrow pos continue; // cant handle beyond that point . so update its pos and count++ } count++ ; // As we are done with current pos arrPos = points[i][1]; // Update as we already exhausted our option with previous position */ } return count; } } ================================================ FILE: 0452-minimum-number-of-arrows-to-burst-balloons/NOTES.md ================================================ ​ ================================================ FILE: 0452-minimum-number-of-arrows-to-burst-balloons/README.md ================================================

452. Minimum Number of Arrows to Burst Balloons

Medium


There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.

Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.

Given the array points, return the minimum number of arrows that must be shot to burst all balloons.

 

Example 1:

Input: points = [[10,16],[2,8],[1,6],[7,12]]
Output: 2
Explanation: The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].
- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].

Example 2:

Input: points = [[1,2],[3,4],[5,6],[7,8]]
Output: 4
Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.

Example 3:

Input: points = [[1,2],[2,3],[3,4],[4,5]]
Output: 2
Explanation: The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].
- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].

 

Constraints:

  • 1 <= points.length <= 105
  • points[i].length == 2
  • -231 <= xstart < xend <= 231 - 1
================================================ FILE: 0491-non-decreasing-subsequences/0491-non-decreasing-subsequences.java ================================================ class Solution { private void backtrack(int[] nums, int index, List sequence, Set> result) { // if we have checked all elements if (index == nums.length) { if (sequence.size() >= 2) { result.add(new ArrayList<>(sequence)); } return; } // if the sequence remains increasing after appending nums[index] if (sequence.isEmpty() || sequence.get(sequence.size() - 1) <= nums[index]) { // append nums[index] to the sequence sequence.add(nums[index]); // call recursively backtrack(nums, index + 1, sequence, result); // delete nums[index] from the end of the sequence sequence.remove(sequence.size() - 1); } // call recursively not appending an element backtrack(nums, index + 1, sequence, result); } public List> findSubsequences(int[] nums) { Set> result = new HashSet>(); List sequence = new ArrayList(); backtrack(nums, 0, sequence, result); return new ArrayList(result); } } ================================================ FILE: 0491-non-decreasing-subsequences/NOTES.md ================================================ ​ ================================================ FILE: 0491-non-decreasing-subsequences/README.md ================================================

491. Non-decreasing Subsequences

Medium


Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.

 

Example 1:

Input: nums = [4,6,7,7]
Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]

Example 2:

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

 

Constraints:

  • 1 <= nums.length <= 15
  • -100 <= nums[i] <= 100
================================================ FILE: 0520-detect-capital/0520-detect-capital.java ================================================ class Solution { public boolean detectCapitalUse(String word) { int n = word.length(); if (n == 1) { return true; } // case 1: All capital if (Character.isUpperCase(word.charAt(0)) && Character.isUpperCase(word.charAt(1))) { for (int i = 2; i < n; i++) { if (Character.isLowerCase(word.charAt(i))) { return false; } } // case 2 and case 3 } else { for (int i = 1; i < n; i++) { if (Character.isUpperCase(word.charAt(i))) { return false; } } } // if pass one of the cases return true; } } ================================================ FILE: 0520-detect-capital/NOTES.md ================================================ ​ ================================================ FILE: 0523-continuous-subarray-sum/0523-continuous-subarray-sum.java ================================================ class Solution { public boolean checkSubarraySum(int[] nums, int k) { int prefixSum = 0; HashMap map = new HashMap<>(); map.put(0, -1); for (int i = 0; i < nums.length; i++) { prefixSum += nums[i]; // this is the twist if (k != 0) { prefixSum = prefixSum % k; //whose elements sum up to a multiple of k } // this is general if (map.containsKey(prefixSum)) { // if nums has a continuous subarray of size at least two elements if (i - map.get(prefixSum) > 1) { return true; } } else { map.put(prefixSum, i); // adding the index } } return false; } } ================================================ FILE: 0523-continuous-subarray-sum/NOTES.md ================================================ ​ ================================================ FILE: 0523-continuous-subarray-sum/README.md ================================================

523. Continuous Subarray Sum

Medium


Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise.

An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k.

 

Example 1:

Input: nums = [23,2,4,6,7], k = 6
Output: true
Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.

Example 2:

Input: nums = [23,2,6,4,7], k = 6
Output: true
Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.

Example 3:

Input: nums = [23,2,6,4,7], k = 13
Output: false

 

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 109
  • 0 <= sum(nums[i]) <= 231 - 1
  • 1 <= k <= 231 - 1
================================================ FILE: 0587-erect-the-fence/0587-erect-the-fence.java ================================================ public class Solution { public int orientation(int[] p, int[] q, int[] r) { return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]); } public int[][] outerTrees(int[][] points) { Arrays.sort(points, new Comparator () { public int compare(int[] p, int[] q) { return q[0] - p[0] == 0 ? q[1] - p[1] : q[0] - p[0]; } }); Stack hull = new Stack<>(); for (int i = 0; i < points.length; i++) { while (hull.size() >= 2 && orientation(hull.get(hull.size() - 2), hull.get(hull.size() - 1), points[i]) > 0) hull.pop(); hull.push(points[i]); } hull.pop(); for (int i = points.length - 1; i >= 0; i--) { while (hull.size() >= 2 && orientation(hull.get(hull.size() - 2), hull.get(hull.size() - 1), points[i]) > 0) hull.pop(); hull.push(points[i]); } // remove redundant elements from the stack HashSet ret = new HashSet<>(hull); return ret.toArray(new int[ret.size()][]); } } ================================================ FILE: 0587-erect-the-fence/README.md ================================================

587. Erect the Fence

Hard


You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden.

You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed.

Return the coordinates of trees that are exactly located on the fence perimeter.

 

Example 1:

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

Example 2:

Input: points = [[1,2],[2,2],[4,2]]
Output: [[4,2],[2,2],[1,2]]

 

Constraints:

  • 1 <= points.length <= 3000
  • points[i].length == 2
  • 0 <= xi, yi <= 100
  • All the given points are unique.
================================================ FILE: 0645-set-mismatch/0645-set-mismatch.java ================================================ class Solution { public int[] findErrorNums(int[] nums) { /** Assume m is the missing and d is the duplicate element diff= m-d; squareDiff= m^2-d^2; sum=m+d= squareDiff/diff =>sum = (m+d)(m-d)/(m-d); now m=(sum+diff)2; and d= (sum-diff)2; **/ int diff=0; int sqaureDiff=0; for(int i=0;i645. Set Mismatch

Easy


You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.

You are given an integer array nums representing the data status of this set after the error.

Find the number that occurs twice and the number that is missing and return them in the form of an array.

 

Example 1:

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

Example 2:

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

 

Constraints:

  • 2 <= nums.length <= 104
  • 1 <= nums[i] <= 104
================================================ FILE: 0692-top-k-frequent-words/0692-top-k-frequent-words.java ================================================ class Solution { public List topKFrequent(String[] words, int k) { Map map = new HashMap<>(); for(String w : words){ int c = map.getOrDefault(w,0); c++; map.put(w,c); } Queue> pq = new PriorityQueue<>((a,b)->(a.getValue() == b.getValue() ? a.getKey().compareTo(b.getKey()) : (a.getValue()-b.getValue())*-1)); for(Map.Entry e : map.entrySet()){ pq.offer(e); } List result = new ArrayList<>(); while(k > 0){ k--; result.add(pq.poll().getKey()); } return result; } } ================================================ FILE: 0692-top-k-frequent-words/NOTES.md ================================================ ​ ================================================ FILE: 0692-top-k-frequent-words/README.md ================================================

692. Top K Frequent Words

Medium


Given an array of strings words and an integer k, return the k most frequent strings.

Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.

 

Example 1:

Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.

Example 2:

Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.

 

Constraints:

  • 1 <= words.length <= 500
  • 1 <= words[i].length <= 10
  • words[i] consists of lowercase English letters.
  • k is in the range [1, The number of unique words[i]]

 

Follow-up: Could you solve it in O(n log(k)) time and O(n) extra space?

================================================ FILE: 0739-daily-temperatures/0739-daily-temperatures.java ================================================ class Solution { public int[] dailyTemperatures(int[] a) { Deque s=new ArrayDeque<>(); int[]ans=new int[a.length]; for(int i=a.length-1;i>=0;i--){ while(!s.isEmpty() && a[s.peek()]<=a[i]){ s.pop(); } if(s.isEmpty()){ ans[i]=0; }else{ ans[i]=s.peek()-i; } s.push(i); } return ans; } } ================================================ FILE: 0739-daily-temperatures/README.md ================================================

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
================================================ FILE: 0766-toeplitz-matrix/0766-toeplitz-matrix.java ================================================ class Solution { public boolean isToeplitzMatrix(int[][] matrix) { for(int i=0;i766. Toeplitz Matrix

Easy


Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.

 

Example 1:

Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.

Example 2:

Input: matrix = [[1,2],[2,2]]
Output: false
Explanation:
The diagonal "[1, 2]" has different elements.

 

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 20
  • 0 <= matrix[i][j] <= 99

 

Follow up:

  • What if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
  • What if the matrix is so large that you can only load up a partial row into the memory at once?
================================================ FILE: 0787-cheapest-flights-within-k-stops/0787-cheapest-flights-within-k-stops.java ================================================ class Solution { public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { Map> adj = new HashMap<>(); for (int[] i : flights) adj.computeIfAbsent(i[0], value -> new ArrayList<>()).add(new int[] { i[1], i[2] }); int[] dist = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); Queue q = new LinkedList<>(); q.offer(new int[] { src, 0 }); int stops = 0; while (stops <= k && !q.isEmpty()) { int sz = q.size(); // Iterate on current level. while (sz-- > 0) { int[] temp = q.poll(); int node = temp[0]; int distance = temp[1]; if (!adj.containsKey(node)) continue; // Loop over neighbors of popped node. for (int[] e : adj.get(node)) { int neighbour = e[0]; int price = e[1]; if (price + distance >= dist[neighbour]) continue; dist[neighbour] = price + distance; q.offer(new int[] { neighbour, dist[neighbour] }); } } stops++; } return dist[dst] == Integer.MAX_VALUE ? -1 : dist[dst]; } } ================================================ FILE: 0787-cheapest-flights-within-k-stops/NOTES.md ================================================ ​ ================================================ FILE: 0787-cheapest-flights-within-k-stops/README.md ================================================

787. Cheapest Flights Within K Stops

Medium


There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.

You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.

 

Example 1:

Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
Output: 700
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.

Example 2:

Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.

Example 3:

Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.

 

Constraints:

  • 1 <= n <= 100
  • 0 <= flights.length <= (n * (n - 1) / 2)
  • flights[i].length == 3
  • 0 <= fromi, toi < n
  • fromi != toi
  • 1 <= pricei <= 104
  • There will not be any multiple flights between two cities.
  • 0 <= src, dst, k < n
  • src != dst
================================================ FILE: 0790-domino-and-tromino-tiling/0790-domino-and-tromino-tiling.java ================================================ class Solution { public int numTilings(int n) { int dp[] = new int[n+4]; int mod = (int)(Math.pow(10,9)+7); dp[1] = 1; dp[2] = 2; dp[3] = 5; for(int i=4;i<=n;i++){ dp[i] = ((2*dp[i-1])%mod)+dp[i-3]; dp[i] %= mod; } return dp[n]; } } ================================================ FILE: 0790-domino-and-tromino-tiling/NOTES.md ================================================ ​ ================================================ FILE: 0790-domino-and-tromino-tiling/README.md ================================================

790. Domino and Tromino Tiling

Medium


You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.

Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7.

In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.

 

Example 1:

Input: n = 3
Output: 5
Explanation: The five different ways are show above.

Example 2:

Input: n = 1
Output: 1

 

Constraints:

  • 1 <= n <= 1000
================================================ FILE: 0797-all-paths-from-source-to-target/0797-all-paths-from-source-to-target.java ================================================ class Solution { public List> allPathsSourceTarget(int[][] graph) { List> ans = new ArrayList<>(); List temp = new ArrayList<>(); temp.add(0); dfs(graph,ans,temp,0); return ans; } public void dfs(int[][] graph, List> ans, List temp, int start){ if(start == graph.length-1){ ans.add(new ArrayList<>(temp)); return; } for(int i : graph[start]){ temp.add(i); dfs(graph,ans,temp,i); temp.remove(temp.size()-1); } } } ================================================ FILE: 0797-all-paths-from-source-to-target/NOTES.md ================================================ ​ ================================================ FILE: 0797-all-paths-from-source-to-target/README.md ================================================

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]]

 

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.
================================================ FILE: 0834-sum-of-distances-in-tree/0834-sum-of-distances-in-tree.java ================================================ class Solution { public int[] sumOfDistancesInTree(int n, int[][] edges) { final int[] parents = buildParents(n, edges); final int[] counts = new int[n]; final int[] childrenCount = new int[n]; final int[] distanceToChildren = new int[n]; for (int p : parents) { if (p >= 0) counts[p]++; } int start = 0, end = 0; for (int i = 0; i < parents.length; i++) { if (counts[i] == 0) { q[end++] = i; } } while (start < end) { final int node = q[start++]; final int parent = parents[node]; if (parent < 0) break; final int c = childrenCount[node] + 1; childrenCount[parent] += c; distanceToChildren[parent] += distanceToChildren[node] + c; if (--counts[parent] == 0) { q[end++] = parent; } } // System.out.println("Parents: " + Arrays.toString(parents)); // System.out.println("ChildrenCount: " + Arrays.toString(childrenCount)); // System.out.println("distanceToChildren: " + Arrays.toString(distanceToChildren)); final int root = q[end - 1]; final int[] r = new int[n]; r[root] = distanceToChildren[root]; for (int i = end - 2; i >= 0; i--) { final int node = q[i]; final int parent = parents[node]; final int minus = childrenCount[node] + 1; r[node] = r[parent] + n - 2 * minus; } return r; } static final int[] q = new int[30001]; static int[] buildParents(int n, int[][] edges) { final int[][] next = buildNext(n, edges); final int[] parents = new int[n]; Arrays.fill(parents, -1); int start = 0, end = 0; q[end++] = 0; while (start < end) { final int parent = q[start++]; for (int c : next[parent]) { if (parents[c] < 0) { parents[c] = parent; q[end++] = c; } } } parents[0] = -1; return parents; } static int[][] buildNext(final int n, final int[][] edges) { final int[] counts = new int[n]; for (final int[] e : edges) { counts[e[0]]++; counts[e[1]]++; } final int[][] res = new int[n][]; for (int i = 0; i < n; i++) { res[i] = new int[counts[i]]; } for (final int[] e : edges) { final int l = e[0]; final int r = e[1]; res[l][--counts[l]] = r; res[r][--counts[r]] = l; } return res; } } ================================================ FILE: 0834-sum-of-distances-in-tree/NOTES.md ================================================ ​ ================================================ FILE: 0834-sum-of-distances-in-tree/README.md ================================================

834. Sum of Distances in Tree

Hard


There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.

You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.

 

Example 1:

Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.

Example 2:

Input: n = 1, edges = []
Output: [0]

Example 3:

Input: n = 2, edges = [[1,0]]
Output: [1,1]

 

Constraints:

  • 1 <= n <= 3 * 104
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 <= ai, bi < n
  • ai != bi
  • The given input represents a valid tree.
================================================ FILE: 0835-image-overlap/0835-image-overlap.java ================================================ class Solution { protected int convolute(int[][] A, int[][] kernel, int xShift, int yShift) { int result = 0; for (int row = 0; row < A.length; ++row) for (int col = 0; col < A.length; ++col) result += A[row][col] * kernel[row + yShift][col + xShift]; return result; } public int largestOverlap(int[][] A, int[][] B) { int N = A.length; int[][] B_padded = new int[3 * N - 2][3 * N - 2]; for (int row = 0; row < N; ++row) for (int col = 0; col < N; ++col) B_padded[row + N - 1][col + N - 1] = B[row][col]; int maxOverlaps = 0; for (int xShift = 0; xShift < 2 * N - 1; ++xShift) for (int yShift = 0; yShift < 2 * N - 1; ++yShift) { maxOverlaps = Math.max(maxOverlaps, convolute(A, B_padded, xShift, yShift)); } return maxOverlaps; } } ================================================ FILE: 0835-image-overlap/NOTES.md ================================================ ​ ================================================ FILE: 0835-image-overlap/README.md ================================================

835. Image Overlap

Medium


You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values.

We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images.

Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased.

Return the largest possible overlap.

 

Example 1:

Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
Output: 3
Explanation: We translate img1 to right by 1 unit and down by 1 unit.

The number of positions that have a 1 in both images is 3 (shown in red).

Example 2:

Input: img1 = [[1]], img2 = [[1]]
Output: 1

Example 3:

Input: img1 = [[0]], img2 = [[0]]
Output: 0

 

Constraints:

  • n == img1.length == img1[i].length
  • n == img2.length == img2[i].length
  • 1 <= n <= 30
  • img1[i][j] is either 0 or 1.
  • img2[i][j] is either 0 or 1.
================================================ FILE: 0841-keys-and-rooms/0841-keys-and-rooms.java ================================================ class Solution { public boolean canVisitAllRooms(List> rooms) { boolean[] visited = new boolean[rooms.size()]; int count = 0; count = dfs(rooms,0, visited, count); return count == rooms.size(); } public int dfs(List> rooms, int currRoom, boolean[] visited, int count) { if (visited[currRoom] == true) { return count; } visited[currRoom] = true; ++count; for (Integer roomKey: rooms.get(currRoom)) { count = dfs(rooms, roomKey, visited, count); } return count; } } ================================================ FILE: 0841-keys-and-rooms/NOTES.md ================================================ ​ ================================================ FILE: 0841-keys-and-rooms/README.md ================================================

841. Keys and Rooms

Medium


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

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

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

 

Example 1:

Input: rooms = [[1],[2],[3],[]]
Output: true
Explanation: 
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.

Example 2:

Input: rooms = [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.

 

Constraints:

  • n == rooms.length
  • 2 <= n <= 1000
  • 0 <= rooms[i].length <= 1000
  • 1 <= sum(rooms[i].length) <= 3000
  • 0 <= rooms[i][j] < n
  • All the values of rooms[i] are unique.
================================================ FILE: 0872-leaf-similar-trees/0872-leaf-similar-trees.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean leafSimilar(TreeNode root1, TreeNode root2) { // Collect the leaf values from each tree List leafValues1 = getLeafValues(root1, new ArrayList<>()); List leafValues2 = getLeafValues(root2, new ArrayList<>()); // Compare the leaf value lists return leafValues1.equals(leafValues2); } List getLeafValues(TreeNode node, List values) { // If the node is null, return if (node == null) { return values; } // If the node is a leaf node, add its value to the list if (node.left == null && node.right == null) { values.add(node.val); } // Recursively traverse the left and right subtrees getLeafValues(node.left, values); getLeafValues(node.right, values); return values; } } ================================================ FILE: 0872-leaf-similar-trees/NOTES.md ================================================ ​ ================================================ FILE: 0872-leaf-similar-trees/README.md ================================================

872. Leaf-Similar Trees

Easy


Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

 

Example 1:

Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
Output: true

Example 2:

Input: root1 = [1,2,3], root2 = [1,3,2]
Output: false

 

Constraints:

  • The number of nodes in each tree will be in the range [1, 200].
  • Both of the given trees will have values in the range [0, 200].
================================================ FILE: 0876-middle-of-the-linked-list/0876-middle-of-the-linked-list.java ================================================ class Solution { public ListNode middleNode(ListNode head) { ListNode slow = head, fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } } ================================================ FILE: 0876-middle-of-the-linked-list/NOTES.md ================================================ ​ ================================================ FILE: 0876-middle-of-the-linked-list/README.md ================================================

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
================================================ FILE: 0886-possible-bipartition/0886-possible-bipartition.java ================================================ class Solution { public boolean possibleBipartition(int n, int[][] dislikes) { int[] colour = new int[n+1]; ArrayList[] dislikeMap = new ArrayList[n+1]; for(int i = 1; i <= n; i++) dislikeMap[i] = new ArrayList(); for(int[] d: dislikes) { dislikeMap[d[0]].add(d[1]); dislikeMap[d[1]].add(d[0]); } Queue queue = new LinkedList<>(); for(int i = 1; i <= n; i++) { if(colour[i] == 0) { colour[i] = 1; queue = new LinkedList<>(); queue.offer(i); while(!queue.isEmpty()) { int curr = queue.poll(); for(int neighbour: dislikeMap[curr]) { if(colour[neighbour] == 0) { colour[neighbour] = colour[curr] == 1?-1:1; queue.offer(neighbour); } else { if(colour[neighbour] == colour[curr]) return false; } } } } } return true; } } ================================================ FILE: 0886-possible-bipartition/NOTES.md ================================================ ​ ================================================ FILE: 0886-possible-bipartition/README.md ================================================

886. Possible Bipartition

Medium


We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.

Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.

 

Example 1:

Input: n = 4, dislikes = [[1,2],[1,3],[2,4]]
Output: true
Explanation: group1 [1,4] and group2 [2,3].

Example 2:

Input: n = 3, dislikes = [[1,2],[1,3],[2,3]]
Output: false

Example 3:

Input: n = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
Output: false

 

Constraints:

  • 1 <= n <= 2000
  • 0 <= dislikes.length <= 104
  • dislikes[i].length == 2
  • 1 <= dislikes[i][j] <= n
  • ai < bi
  • All the pairs of dislikes are unique.
================================================ FILE: 0899-orderly-queue/0899-orderly-queue.java ================================================ class Solution { public String orderlyQueue(String s, int k) { if (k == 1) { String ans = s; for (int i = 0; i < s.length(); ++i) { String temp = s.substring(i) + s.substring(0, i); if (temp.compareTo(ans) < 0) { ans = temp; } } return ans; } else { char[] chars = s.toCharArray(); Arrays.sort(chars); return new String(chars); } } } ================================================ FILE: 0899-orderly-queue/NOTES.md ================================================ ​ ================================================ FILE: 0899-orderly-queue/README.md ================================================

899. Orderly Queue

Hard


You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string..

Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.

 

Example 1:

Input: s = "cba", k = 1
Output: "acb"
Explanation: 
In the first move, we move the 1st character 'c' to the end, obtaining the string "bac".
In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb".

Example 2:

Input: s = "baaca", k = 3
Output: "aaabc"
Explanation: 
In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab".
In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc".

 

Constraints:

  • 1 <= k <= s.length <= 1000
  • s consist of lowercase English letters.
================================================ FILE: 0901-online-stock-span/0901-online-stock-span.java ================================================ class StockSpanner { Stack stack = new Stack<>(); public int next(int price) { int ans = 1; while (!stack.isEmpty() && stack.peek()[0] <= price) { ans += stack.pop()[1]; } stack.push(new int[] {price, ans}); return ans; } } /** * Your StockSpanner object will be instantiated and called as such: * StockSpanner obj = new StockSpanner(); * int param_1 = obj.next(price); */ ================================================ FILE: 0901-online-stock-span/NOTES.md ================================================ ​ ================================================ FILE: 0901-online-stock-span/README.md ================================================

901. Online Stock Span

Medium


Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day.

The span of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price.

  • For example, if the price of a stock over the next 7 days were [100,80,60,70,60,75,85], then the stock spans would be [1,1,1,2,1,4,6].

Implement the StockSpanner class:

  • StockSpanner() Initializes the object of the class.
  • int next(int price) Returns the span of the stock's price given that today's price is price.

 

Example 1:

Input
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"]
[[], [100], [80], [60], [70], [60], [75], [85]]
Output
[null, 1, 1, 1, 2, 1, 4, 6]

Explanation
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80);  // return 1
stockSpanner.next(60);  // return 1
stockSpanner.next(70);  // return 2
stockSpanner.next(60);  // return 1
stockSpanner.next(75);  // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85);  // return 6

 

Constraints:

  • 1 <= price <= 105
  • At most 104 calls will be made to next.
================================================ FILE: 0907-sum-of-subarray-minimums/0907-sum-of-subarray-minimums.java ================================================ class Solution { public int sumSubarrayMins(int[] arr) { int MOD = 1000000007; Stack stack = new Stack<>(); long sumOfMinimums = 0; // building monotonically increasing stack for (int i = 0; i <= arr.length; i++) { // when i reaches the array length, it is an indication that // all the elements have been processed, and the remaining // elements in the stack should now be popped out. while (!stack.empty() && (i == arr.length || arr[stack.peek()] >= arr[i])) { // Notice the sign ">=", This ensures that no contribution // is counted twice. rightBoundary takes equal or smaller // elements into account while leftBoundary takes only the // strictly smaller elements into account int mid = stack.pop(); int leftBoundary = stack.empty() ? -1 : stack.peek(); int rightBoundary = i; // count of subarrays where mid is the minimum element long count = (mid - leftBoundary) * (rightBoundary - mid) % MOD; sumOfMinimums += (count * arr[mid]) % MOD; sumOfMinimums %= MOD; } stack.push(i); } return (int) (sumOfMinimums); } } ================================================ FILE: 0907-sum-of-subarray-minimums/NOTES.md ================================================ ​ ================================================ FILE: 0907-sum-of-subarray-minimums/README.md ================================================

907. Sum of Subarray Minimums

Medium


Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.

 

Example 1:

Input: arr = [3,1,2,4]
Output: 17
Explanation: 
Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. 
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.

Example 2:

Input: arr = [11,81,94,43,3]
Output: 444

 

Constraints:

  • 1 <= arr.length <= 3 * 104
  • 1 <= arr[i] <= 3 * 104
================================================ FILE: 0909-snakes-and-ladders/0909-snakes-and-ladders.java ================================================ class Solution { public int snakesAndLadders(int[][] board) { int n = board.length; Pair[] cells = new Pair[n * n + 1]; int label = 1; Integer[] columns = new Integer[n]; for (int i = 0; i < n; i++) { columns[i] = i; } for (int row = n - 1; row >= 0; row--) { for (int column : columns) { cells[label++] = new Pair<>(row, column); } Collections.reverse(Arrays.asList(columns)); } int[] dist = new int[n * n + 1]; Arrays.fill(dist, -1); Queue q = new LinkedList(); dist[1] = 0; q.add(1); while (!q.isEmpty()) { int curr = q.remove(); for (int next = curr + 1; next <= Math.min(curr + 6, n * n); next++) { int row = cells[next].getKey(), column = cells[next].getValue(); int destination = board[row][column] != -1 ? board[row][column] : next; if (dist[destination] == -1) { dist[destination] = dist[curr] + 1; q.add(destination); } } } return dist[n * n]; } } ================================================ FILE: 0909-snakes-and-ladders/NOTES.md ================================================ ​ ================================================ FILE: 0909-snakes-and-ladders/README.md ================================================

909. Snakes and Ladders

Medium


You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.

You start on square 1 of the board. In each move, starting from square curr, do the following:

  • Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)].
    • This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board.
  • If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next.
  • The game ends when you reach the square n2.

A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 do not have a snake or ladder.

Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder.

  • For example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4.

Return the least number of moves required to reach the square n2. If it is not possible to reach the square, return -1.

 

Example 1:

Input: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]
Output: 4
Explanation: 
In the beginning, you start at square 1 (at row 5, column 0).
You decide to move to square 2 and must take the ladder to square 15.
You then decide to move to square 17 and must take the snake to square 13.
You then decide to move to square 14 and must take the ladder to square 35.
You then decide to move to square 36, ending the game.
This is the lowest possible number of moves to reach the last square, so return 4.

Example 2:

Input: board = [[-1,-1],[-1,3]]
Output: 1

 

Constraints:

  • n == board.length == board[i].length
  • 2 <= n <= 20
  • grid[i][j] is either -1 or in the range [1, n2].
  • The squares labeled 1 and n2 do not have any ladders or snakes.
================================================ FILE: 0918-maximum-sum-circular-subarray/0918-maximum-sum-circular-subarray.java ================================================ class Solution { public int maxSubarraySumCircular(int[] nums) { int curMax = 0, curMin = 0, sum = 0, maxSum = nums[0], minSum = nums[0]; for (int num : nums) { curMax = Math.max(curMax, 0) + num; maxSum = Math.max(maxSum, curMax); curMin = Math.min(curMin, 0) + num; minSum = Math.min(minSum, curMin); sum += num; } return sum == minSum ? maxSum : Math.max(maxSum, sum - minSum); } } ================================================ FILE: 0918-maximum-sum-circular-subarray/README.md ================================================

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,-2,-3]
Output: -2
Explanation: Subarray [-2] has maximum sum -2.

 

Constraints:

  • n == nums.length
  • 1 <= n <= 3 * 104
  • -3 * 104 <= nums[i] <= 3 * 104
================================================ FILE: 0926-flip-string-to-monotone-increasing/0926-flip-string-to-monotone-increasing.java ================================================ class Solution { public int minFlipsMonoIncr(String s) { int ans = 0, num = 0; for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == '0') { ans = Math.min(num, ans + 1); } else { ++num; } } return ans; } } ================================================ FILE: 0926-flip-string-to-monotone-increasing/NOTES.md ================================================ ​ ================================================ FILE: 0938-range-sum-of-bst/0938-range-sum-of-bst.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int rangeSumBST(TreeNode root, int low, int high) { return root == null ? 0 : (root.val >= low && root.val <= high ? root.val : 0) + (root.val > low ? rangeSumBST(root.left, low, high) : 0) + (root.val < high ? rangeSumBST(root.right, low, high) : 0); } } ================================================ FILE: 0938-range-sum-of-bst/NOTES.md ================================================ ​ ================================================ FILE: 0938-range-sum-of-bst/README.md ================================================

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.
================================================ FILE: 0944-delete-columns-to-make-sorted/0944-delete-columns-to-make-sorted.java ================================================ class Solution { public int minDeletionSize(String[] strs) { int cols=strs[0].length(); int ans=0; for(int col=0;col944. Delete Columns to Make Sorted

Easy


You are given an array of n strings strs, all of the same length.

The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as:

abc
bce
cae

You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted while column 1 ('b', 'c', 'a') is not, so you would delete column 1.

Return the number of columns that you will delete.

 

Example 1:

Input: strs = ["cba","daf","ghi"]
Output: 1
Explanation: The grid looks as follows:
  cba
  daf
  ghi
Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.

Example 2:

Input: strs = ["a","b"]
Output: 0
Explanation: The grid looks as follows:
  a
  b
Column 0 is the only column and is sorted, so you will not delete any columns.

Example 3:

Input: strs = ["zyx","wvu","tsr"]
Output: 3
Explanation: The grid looks as follows:
  zyx
  wvu
  tsr
All 3 columns are not sorted, so you will delete all 3.

 

Constraints:

  • n == strs.length
  • 1 <= n <= 100
  • 1 <= strs[i].length <= 1000
  • strs[i] consists of lowercase English letters.
================================================ FILE: 0947-most-stones-removed-with-same-row-or-column/0947-most-stones-removed-with-same-row-or-column.java ================================================ class Solution { public int removeStones(int[][] stones) { if (stones == null || stones.length <= 1) { return 0; } int n = stones.length; UnionFind uf = new UnionFind(); for (int[] edge : stones) { uf.union(edge[0] + 10001, edge[1]); } return n - uf.count; } class UnionFind { Map parents; int count; public UnionFind() { parents = new HashMap<>(); count = 0; } public int find(int x) { if (!parents.containsKey(x)) { parents.put(x, x); count++; } if (x != parents.get(x)) { parents.put(x, find(parents.get(x))); } return parents.get(x); } public void union(int x, int y) { int rootX = find(x); int rootY = find(y); if (rootX == rootY) { return; } parents.put(rootX, rootY); count--; } } } ================================================ FILE: 0947-most-stones-removed-with-same-row-or-column/NOTES.md ================================================ ​ ================================================ FILE: 0947-most-stones-removed-with-same-row-or-column/README.md ================================================

947. Most Stones Removed with Same Row or Column

Medium


On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.

A stone can be removed if it shares either the same row or the same column as another stone that has not been removed.

Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.

 

Example 1:

Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5
Explanation: One way to remove 5 stones is as follows:
1. Remove stone [2,2] because it shares the same row as [2,1].
2. Remove stone [2,1] because it shares the same column as [0,1].
3. Remove stone [1,2] because it shares the same row as [1,0].
4. Remove stone [1,0] because it shares the same column as [0,0].
5. Remove stone [0,1] because it shares the same row as [0,0].
Stone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.

Example 2:

Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3
Explanation: One way to make 3 moves is as follows:
1. Remove stone [2,2] because it shares the same row as [2,0].
2. Remove stone [2,0] because it shares the same column as [0,0].
3. Remove stone [0,2] because it shares the same row as [0,0].
Stones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.

Example 3:

Input: stones = [[0,0]]
Output: 0
Explanation: [0,0] is the only stone on the plane, so you cannot remove it.

 

Constraints:

  • 1 <= stones.length <= 1000
  • 0 <= xi, yi <= 104
  • No two stones are at the same coordinate point.
================================================ FILE: 0974-subarray-sums-divisible-by-k/0974-subarray-sums-divisible-by-k.java ================================================ class Solution { public int subarraysDivByK(int[] nums, int k) { int n = nums.length; int prefixMod = 0, result = 0; // There are k mod groups 0...k-1. int[] modGroups = new int[k]; modGroups[0] = 1; for (int num: nums) { // Take modulo twice to avoid negative remainders. prefixMod = (prefixMod + num % k + k) % k; // Add the count of subarrays that have the same remainder as the current // one to cancel out the remainders. result += modGroups[prefixMod]; modGroups[prefixMod]++; } return result; } } ================================================ FILE: 0974-subarray-sums-divisible-by-k/NOTES.md ================================================ ​ ================================================ FILE: 0974-subarray-sums-divisible-by-k/README.md ================================================

974. Subarray Sums Divisible by K

Medium


Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.

A subarray is a contiguous part of an array.

 

Example 1:

Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by k = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]

Example 2:

Input: nums = [5], k = 9
Output: 0

 

Constraints:

  • 1 <= nums.length <= 3 * 104
  • -104 <= nums[i] <= 104
  • 2 <= k <= 104
================================================ FILE: 0976-largest-perimeter-triangle/0976-largest-perimeter-triangle.java ================================================ class Solution { public int largestPerimeter(int[] nums) { Arrays.sort(nums); int i=nums.length-1; while(i>1){ int a=nums[i]; int b=nums[i-1]; int c=nums[i-2]; if(c+b>a){ return a+b+c; }else{ i--; } } return 0; } } ================================================ FILE: 0976-largest-perimeter-triangle/NOTES.md ================================================ ​ ================================================ FILE: 0976-largest-perimeter-triangle/README.md ================================================

976. Largest Perimeter Triangle

Easy


Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.

 

Example 1:

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

Example 2:

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

 

Constraints:

  • 3 <= nums.length <= 104
  • 1 <= nums[i] <= 106
================================================ FILE: 0980-unique-paths-iii/0980-unique-paths-iii.java ================================================ class Solution { public int uniquePathsIII(int[][] grid) { int zero = 0; // Count the 0's int sx = 0; // starting x index int sy = 0; // starting y index for(int r = 0; r < grid.length; r++){ // r = row for(int c = 0; c < grid[0].length; c++){ // c = column if(grid[r][c] == 0) zero++; // if current cell is 0, count it. else if(grid[r][c] == 1){ sx = r; // starting x co-ordinate sy = c; // starting y co-ordinate } } } return dfs(grid, sx, sy, zero); } public int dfs(int grid[][], int x, int y, int zero){ // Base Condition if(x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] == -1){ return 0; } if(grid[x][y] == 2){ return zero == -1 ? 1 : 0; // Why zero = -1, because in above example we have 9 zero's. So, when we reach the final cell we are covering one cell extra then the zero count. // If that's the case we find the path and return '1' otherwise return '0'; } grid[x][y] = -1; // mark the visited cells as -1; zero--; // and reduce the zero by 1 int totalPaths = dfs(grid, x + 1, y, zero) + // calculating all the paths available in 4 directions dfs(grid, x - 1, y, zero) + dfs(grid, x, y + 1, zero) + dfs(grid, x, y - 1, zero); // Let's say if we are not able to count all the paths. Now we use Backtracking over here grid[x][y] = 0; zero++; return totalPaths; // if we get all the paths, simply return it. } } ================================================ FILE: 0980-unique-paths-iii/NOTES.md ================================================ ​ ================================================ FILE: 0980-unique-paths-iii/README.md ================================================

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.
================================================ FILE: 0997-find-the-town-judge/0997-find-the-town-judge.java ================================================ class Solution { public int findJudge(int n, int[][] trust) { int count[] = new int[n+1]; for(int t[] : trust){ count[t[0]]--; // outdegree count[t[1]]++; // indegree } for(int i=1;i<=n;i++){ if(count[i]==n-1) return i; } return -1; } } ================================================ FILE: 0997-find-the-town-judge/NOTES.md ================================================ ​ ================================================ FILE: 0997-find-the-town-judge/README.md ================================================

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. Everybody (except for the town judge) trusts the town judge.
  3. There is exactly one person that satisfies properties 1 and 2.

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

 

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
================================================ FILE: 1007-minimum-domino-rotations-for-equal-row/1007-minimum-domino-rotations-for-equal-row.java ================================================ class Solution { public int minDominoRotations(int[] tops, int[] bottoms) { int ans =-1; for(int i=1;i<=6;i++){ int currAns = helper(i,tops,bottoms); if (currAns != -1 && (ans == -1 || ans > currAns)) { ans = currAns; } } return ans; } private int helper(int target,int[] a,int[] b){ int numswapA =0; int numswapB =0; for(int i=0;i1007. Minimum Domino Rotations For Equal Row

Medium


In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)

We may rotate the ith domino, so that tops[i] and bottoms[i] swap values.

Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same.

If it cannot be done, return -1.

 

Example 1:

Input: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]
Output: 2
Explanation: 
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.

Example 2:

Input: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]
Output: -1
Explanation: 
In this case, it is not possible to rotate the dominoes to make one row of values equal.

 

Constraints:

  • 2 <= tops.length <= 2 * 104
  • bottoms.length == tops.length
  • 1 <= tops[i], bottoms[i] <= 6
================================================ FILE: 102-binary-tree-level-order-traversal/102-binary-tree-level-order-traversal.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List> levelOrder(TreeNode root) { List> ans=new ArrayList<>(); if(root==null)return ans; Queue q=new LinkedList<>(); q.add(root); while(!q.isEmpty()){ int sz=q.size(); List list=new ArrayList<>(); while(sz-->0){ TreeNode node=q.remove(); list.add(node.val); if(node.left!=null)q.add(node.left); if(node.right!=null)q.add(node.right); } ans.add(list); } return ans; } } ================================================ FILE: 102-binary-tree-level-order-traversal/102-binary-tree-level-order-traversal.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: res = [] # Breadth-First-Search Algo def traverse(node, i): if node: if i102. 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
================================================ FILE: 1020-number-of-enclaves/1020-number-of-enclaves.cpp ================================================ class Solution { public: pair bfs(vector>& gr, vector>& vis, int x, int y) { queue>qq; // (1,2) (2,1) (1,0) (0,1) vectorxmoves = { 0,1,0,-1 }; vectorymoves = { 1,0,-1,0 }; qq.push(make_pair(x, y)); vis[x][y] = true; pairtemp; int r,c; bool is_at_boundary = false; int count = 0; while (!qq.empty()) { temp = qq.front(); qq.pop(); ++count; for (int i = 0;i < 4;i++) { r = temp.first + xmoves[i]; c = temp.second + ymoves[i]; if (r < 0 || c < 0 || r >= gr.size() || c >= gr[0].size()) is_at_boundary = true; else if (!vis[r][c] && gr[r][c]) { vis[r][c] = true; qq.push(make_pair(r, c)); } } } return { count,is_at_boundary }; } int numEnclaves(vector>& grid) { int n = grid.size(), m = grid[0].size(); int answer = 0; vector>vis(n, vector(m,false)); pairresult; for (int i = 0;i < n;i++) { for (int j = 0;j < m;j++) { if (!vis[i][j] && grid[i][j]) { result = bfs(grid, vis, i, j); //cout <<"result is "<< result.first << endl; if (!result.second)answer += result.first; } } } return answer; } }; ================================================ FILE: 1020. Number of Enclaves.java ================================================ class Solution { public int numEnclaves(int[][] grid) { int n=grid.length; int m=grid[0].length; int[][] vis=new int[n][m]; for(int j=0;j=a.length || j<0 || j>=a[0].length || vis[i][j]==1 || a[i][j]==0){ return ; } vis[i][j]=1; dfs(a,vis,i+1,j); dfs(a,vis,i-1,j); dfs(a,vis,i,j+1); dfs(a,vis,i,j-1); return; } } ================================================ FILE: 1026-maximum-difference-between-node-and-ancestor/1026-maximum-difference-between-node-and-ancestor.java ================================================ class Solution { int maxDifference = 0; public int maxAncestorDiff(TreeNode root) { int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; dfs(root, max, min); return maxDifference; } void dfs(TreeNode root, int max, int min){ if(root == null) return; if(root.val < min) { min = root.val; } if(root.val > max) { max = root.val; }; if(Math.abs(min - max) > maxDifference) { maxDifference = Math.abs(min - max); } dfs(root.left, max, min); dfs(root.right, max, min); } } ================================================ FILE: 1026-maximum-difference-between-node-and-ancestor/NOTES.md ================================================ ​ ================================================ FILE: 1026-maximum-difference-between-node-and-ancestor/README.md ================================================

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
================================================ FILE: 1029-two-city-scheduling/1029-two-city-scheduling.java ================================================ class Solution { public int twoCitySchedCost(int[][] costs) { int n=costs.length; int[][]diff=new int[n][3]; for(int i=0;io1[0]-o2[0]); int ans=0; for(int i=0;i=n/2){ ans+=diff[i][1]; }else{ ans+=diff[i][2]; } } return ans; } } ================================================ FILE: 1029-two-city-scheduling/NOTES.md ================================================ ​ ================================================ FILE: 1029-two-city-scheduling/README.md ================================================

1029. 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
================================================ FILE: 1046-last-stone-weight/1046-last-stone-weight.java ================================================ class Solution { public int lastStoneWeight(int[] stones) { int c = stones.length; while(c > 1){ Arrays.sort(stones); stones[c-2]=stones[c-1] - stones[c-2]; c--; } return stones[0]; } } ================================================ FILE: 1046-last-stone-weight/NOTES.md ================================================ ​ ================================================ FILE: 1046-last-stone-weight/README.md ================================================

1046. Last Stone Weight

Easy


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 the heaviest two stones and smash them together. Suppose the heaviest two 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 combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.

Example 2:

Input: stones = [1]
Output: 1

 

Constraints:

  • 1 <= stones.length <= 30
  • 1 <= stones[i] <= 1000
================================================ FILE: 1047-remove-all-adjacent-duplicates-in-string/1047-remove-all-adjacent-duplicates-in-string.java ================================================ class Solution { public String removeDuplicates(String s) { int i = 0; int len = s.length(); char arr[] = s.toCharArray(); for(int j = 0; j0 && arr[i]==arr[i-1]){ i -= 2; } i++; } return new String(arr, 0, i); } } ================================================ FILE: 1047-remove-all-adjacent-duplicates-in-string/NOTES.md ================================================ ​ ================================================ FILE: 1047-remove-all-adjacent-duplicates-in-string/README.md ================================================

1047. Remove All Adjacent Duplicates In String

Easy


You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.

We repeatedly make duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.

 

Example 1:

Input: s = "abbaca"
Output: "ca"
Explanation: 
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".

Example 2:

Input: s = "azxxzy"
Output: "ay"

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters.
================================================ FILE: 1048-longest-string-chain/1048-longest-string-chain.java ================================================ class Solution { public int longestStrChain(String[] words) { Arrays.sort(words,(a,b)->a.length()-b.length()); Map map=new HashMap<>(); int res=0; for(String word:words){ map.put(word,1); for(int i=0;i1048. Longest String Chain

Medium


You are given an array of words where each word consists of lowercase English letters.

wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.

  • For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".

A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.

Return the length of the longest possible word chain with words chosen from the given list of words.

 

Example 1:

Input: words = ["a","b","ba","bca","bda","bdca"]
Output: 4
Explanation: One of the longest word chains is ["a","ba","bda","bdca"].

Example 2:

Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
Output: 5
Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].

Example 3:

Input: words = ["abcd","dbqca"]
Output: 1
Explanation: The trivial word chain ["abcd"] is one of the longest word chains.
["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed.

 

Constraints:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 16
  • words[i] only consists of lowercase English letters.
================================================ FILE: 105-construct-binary-tree-from-preorder-and-inorder-traversal/105-construct-binary-tree-from-preorder-and-inorder-traversal.java ================================================ class Solution { int preorderIndex; Map inorderIndexMap; public TreeNode buildTree(int[] preorder, int[] inorder) { preorderIndex = 0; // build a hashmap to store value -> its index relations inorderIndexMap = new HashMap<>(); for (int i = 0; i < inorder.length; i++) { inorderIndexMap.put(inorder[i], i); } return arrayToTree(preorder, 0, preorder.length - 1); } private TreeNode arrayToTree(int[] preorder, int left, int right) { // if there are no elements to construct the tree if (left > right) return null; // select the preorder_index element as the root and increment it int rootValue = preorder[preorderIndex++]; TreeNode root = new TreeNode(rootValue); // build left and right subtree // excluding inorderIndexMap[rootValue] element because it's the root root.left = arrayToTree(preorder, left, inorderIndexMap.get(rootValue) - 1); root.right = arrayToTree(preorder, inorderIndexMap.get(rootValue) + 1, right); return root; } } ================================================ FILE: 105-construct-binary-tree-from-preorder-and-inorder-traversal/NOTES.md ================================================ ​ ================================================ FILE: 105-construct-binary-tree-from-preorder-and-inorder-traversal/README.md ================================================

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.
================================================ FILE: 1061-lexicographically-smallest-equivalent-string/1061-lexicographically-smallest-equivalent-string.java ================================================ class Solution { int representative[] = new int[26]; // Returns the root representative of the component. int find(int x) { if (representative[x] == x) { return x; } return representative[x] = find(representative[x]); } // Perform union if x and y aren't in the same component. void performUnion(int x, int y) { x = find(x); y = find(y); if (x == y) { return; } // Make the smaller character representative. if (x < y) { representative[y] = x; } else { representative[x] = y; } } public String smallestEquivalentString(String s1, String s2, String baseStr) { // Make each character representative of itself. for (int i = 0; i < 26; i++) { representative[i] = i; } // Perform union merge for all the edges. for (int i = 0; i < s1.length(); i++) { performUnion(s1.charAt(i) - 'a', s2.charAt(i) - 'a'); } String ans = ""; // Create the answer string with final mappings. for (char c : baseStr.toCharArray()) { ans += (char)(find(c - 'a') + 'a'); } return ans; } } ================================================ FILE: 1061-lexicographically-smallest-equivalent-string/NOTES.md ================================================ ​ ================================================ FILE: 1061-lexicographically-smallest-equivalent-string/README.md ================================================

1061. Lexicographically Smallest Equivalent String

Medium


You are given two strings of the same length s1 and s2 and a string baseStr.

We say s1[i] and s2[i] are equivalent characters.

  • For example, if s1 = "abc" and s2 = "cde", then we have 'a' == 'c', 'b' == 'd', and 'c' == 'e'.

Equivalent characters follow the usual rules of any equivalence relation:

  • Reflexivity: 'a' == 'a'.
  • Symmetry: 'a' == 'b' implies 'b' == 'a'.
  • Transitivity: 'a' == 'b' and 'b' == 'c' implies 'a' == 'c'.

For example, given the equivalency information from s1 = "abc" and s2 = "cde", "acd" and "aab" are equivalent strings of baseStr = "eed", and "aab" is the lexicographically smallest equivalent string of baseStr.

Return the lexicographically smallest equivalent string of baseStr by using the equivalency information from s1 and s2.

 

Example 1:

Input: s1 = "parker", s2 = "morris", baseStr = "parser"
Output: "makkek"
Explanation: Based on the equivalency information in s1 and s2, we can group their characters as [m,p], [a,o], [k,r,s], [e,i].
The characters in each group are equivalent and sorted in lexicographical order.
So the answer is "makkek".

Example 2:

Input: s1 = "hello", s2 = "world", baseStr = "hold"
Output: "hdld"
Explanation: Based on the equivalency information in s1 and s2, we can group their characters as [h,w], [d,e,o], [l,r].
So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld".

Example 3:

Input: s1 = "leetcode", s2 = "programs", baseStr = "sourcecode"
Output: "aauaaaaada"
Explanation: We group the equivalent characters in s1 and s2 as [a,o,e,r,s,c], [l,p], [g,t] and [d,m], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada".

 

Constraints:

  • 1 <= s1.length, s2.length, baseStr <= 1000
  • s1.length == s2.length
  • s1, s2, and baseStr consist of lowercase English letters.
================================================ FILE: 1074-number-of-submatrices-that-sum-to-target/1074-number-of-submatrices-that-sum-to-target.java ================================================ class Solution { public int numSubmatrixSumTarget(int[][] matrix, int target) { int m = matrix.length; int n = matrix[0].length; int res = 0; // traverse upper boundary for (int top = 0; top < m; top++) { // for each upper boundary, we have a prefix sum array int[] sum = new int[n]; // traverse lower boundary for (int bottom = top; bottom < m; bottom++) { // count the prefix sum for each column for (int col = 0; col < n; col++) { sum[col] += matrix[bottom][col]; } // traverse left and right boundary for (int left = 0; left < n; left++) { int cnt = 0; for (int right = left; right < n; right++) { cnt += sum[right]; if (cnt == target) res++; } } } } return res; } } ================================================ FILE: 1074-number-of-submatrices-that-sum-to-target/NOTES.md ================================================ ​ ================================================ FILE: 108-convert-sorted-array-to-binary-search-tree/108-convert-sorted-array-to-binary-search-tree.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode sortedArrayToBST(int[] nums) { return create(nums,0,nums.length-1); } TreeNode create(int[]nums,int i,int j){ if(j108. 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.
================================================ FILE: 1081-smallest-subsequence-of-distinct-characters/1081-smallest-subsequence-of-distinct-characters.java ================================================ class Solution { public String smallestSubsequence(String s) { int[]freq=new int[26]; int[]done=new int[26]; for(char c:s.toCharArray()){ freq[c-97]++; } Deque stack=new ArrayDeque<>(); for(int i=0;i0 && stack.peek()>ch){ if(freq[stack.peek()-97]>0){ char out=stack.pop(); done[out-97]=0; }else{ break; } } done[ch-97]=1; stack.push(ch); } freq[ch-97]--; } StringBuilder sb=new StringBuilder(); while(stack.size()>0){ sb.append(stack.pop()); } return sb.reverse().toString(); } } ================================================ FILE: 1081-smallest-subsequence-of-distinct-characters/NOTES.md ================================================ ​ ================================================ FILE: 1081-smallest-subsequence-of-distinct-characters/README.md ================================================

1081. Smallest Subsequence of Distinct Characters

Medium


Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.

 

Example 1:

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

Example 2:

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

 

Constraints:

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

 

Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/
================================================ FILE: 1091-shortest-path-in-binary-matrix/1091-shortest-path-in-binary-matrix.java ================================================ class Solution { public int shortestPathBinaryMatrix(int[][] grid) { int n=grid.length; if(grid[0][0]==1||grid[n-1][n-1]==1)return -1; if(n==1&&grid[0][0]==0)return 1; grid[0][0]=1; List pos=new ArrayList<>(); pos.add(new int[]{0,0}); check(grid,pos); if(grid[n-1][n-1]==0)return -1; return grid[n-1][n-1]; } public void check(int[][] grid,List pos){ int n=grid.length; List newpos=new ArrayList<>(); for(int[] p:pos){ int i=p[0]; int j=p[1]; int curdis=grid[i][j]+1; if(i>0&&j>0&&grid[i-1][j-1]==0){ grid[i-1][j-1]=curdis; newpos.add(new int[]{i-1,j-1}); } if(i0&&grid[i+1][j-1]==0){ grid[i+1][j-1]=curdis; newpos.add(new int[]{i+1,j-1}); } if(i>0&&j0&&grid[i][j-1]==0){ grid[i][j-1]=curdis; newpos.add(new int[]{i,j-1}); } if(j0&&grid[i-1][j]==0){ grid[i-1][j]=curdis; newpos.add(new int[]{i-1,j}); } } if(!newpos.isEmpty())check(grid,newpos); } } ================================================ FILE: 1091-shortest-path-in-binary-matrix/NOTES.md ================================================ ​ ================================================ FILE: 1091-shortest-path-in-binary-matrix/README.md ================================================

1091. Shortest Path in Binary Matrix

Medium


Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.

A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:

  • All the visited cells of the path are 0.
  • All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).

The length of a clear path is the number of visited cells of this path.

 

Example 1:

Input: grid = [[0,1],[1,0]]
Output: 2

Example 2:

Input: grid = [[0,0,0],[1,1,0],[1,1,0]]
Output: 4

Example 3:

Input: grid = [[1,0,0],[1,1,0],[1,1,0]]
Output: -1

 

Constraints:

  • n == grid.length
  • n == grid[i].length
  • 1 <= n <= 100
  • grid[i][j] is 0 or 1
================================================ FILE: 11-container-with-most-water/11-container-with-most-water.java ================================================ class Solution { public int maxArea(int[] height) { int result = 0; int left = 0; int right = height.length - 1; while (left < right) { int hLeft = height[left]; int hRight = height[right]; result = Math.max(result, Math.min(hLeft, hRight) * (right - left)); if (hLeft < hRight) { while (left < right && height[left] <= hLeft) { left++; } } else { while (left < right && height[right] <= hRight) { right--; } } } return result; } } ================================================ FILE: 11-container-with-most-water/Container_With_Most_Water.cpp ================================================ class Solution { public: int maxArea(vector& h) { int maxi = 0; int i=0,j=h.size()-1; while(i11. 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
================================================ FILE: 112-path-sum/112-path-sum.java ================================================ class Solution{ public boolean hasPathSum(TreeNode root, int targetSum) { if(root==null){ return false; } if(root.left==null && root.right==null && targetSum-root.val==0){ return true; } return hasPathSum(root.left, targetSum-root.val) || hasPathSum(root.right, targetSum-root.val); } } ================================================ FILE: 112-path-sum/NOTES.md ================================================ ​ ================================================ FILE: 112-path-sum/README.md ================================================

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
Explanation: The root-to-leaf path with the target sum is shown.

Example 2:

Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.

Example 3:

Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.

 

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000
================================================ FILE: 113 Path Sum II med s24.cpp ================================================ #include using namespace std; class Solution { public: vector> ans; void dfs(TreeNode* node, vector& path, int remainingSum) { if (!node) return; path.push_back(node-> val); if (!node->left && !node->right && remainingSum == node->val) ans.push_back(path); dfs(node-> left, path, remainingSum - node-> val); dfs(node-> right, path, remainingSum - node-> val); // backtrack path.pop_back(); } vector> pathSum(TreeNode* root, int targetSum) { // used to store current route vector path; // dfs from the root dfs(root, path, targetSum); return ans; } }; ================================================ FILE: 113-Path-Sum-II.cpp ================================================ class Solution { public: vector>ans; void dfs(vector&curr,TreeNode* root,int target) { if(!root) return; curr.push_back(root->val); if(root->val==target && !root->left && !root->right) ans.push_back(curr); dfs(curr,root->left,target-root->val); dfs(curr,root->right,target-root->val); curr.pop_back(); } /////// vector> pathSum(TreeNode* root, int targetSum) { vectorcurr; dfs(curr,root,targetSum); return ans; } }; ================================================ FILE: 113-path-sum-ii/113-path-sum-ii.java ================================================ class Solution { public void check(TreeNode root,int T,List curr,List> list){ if(root == null){ return; } if(T-root.val==0 && root.left == root.right){ curr.add(root.val); list.add(new ArrayList<>(curr)); curr.remove(curr.size()-1); return; } curr.add(root.val); check(root.left,T-root.val,curr,list); check(root.right,T-root.val,curr,list); curr.remove(curr.size()-1); } public List> pathSum(TreeNode root, int targetSum) { List> list = new ArrayList<>(); List curr = new ArrayList<>(); check(root,targetSum,curr,list); return list; } } ================================================ FILE: 113-path-sum-ii/113. Path Sum II.cpp ================================================ class Solution { public: vector> v; void dfs(TreeNode* root, int targetSum, vector &t){ if(!root) return; t.push_back(root->val); targetSum -= root->val; if(!root->left and !root->right and targetSum == 0){ v.push_back(t); }else{ dfs(root->left, targetSum, t); dfs(root->right, targetSum, t); } // backtracking t.pop_back(); return; } vector> pathSum(TreeNode* root, int targetSum) { if(!root) return {}; vector t; dfs(root, targetSum, t); return v; } }; ================================================ FILE: 113-path-sum-ii/NOTES.md ================================================ ​ ================================================ FILE: 113-path-sum-ii/README.md ================================================

113. 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
================================================ FILE: 114-flatten-binary-tree-to-linked-list/114-flatten-binary-tree-to-linked-list.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public void flatten(TreeNode root) { if(root==null)return; flatten(root.left); TreeNode righty=root.right; root.right=root.left; root.left=null; flatten(righty); TreeNode temp=root; while(temp.right!=null){ temp=temp.right; } temp.right=righty; } } ================================================ FILE: 114-flatten-binary-tree-to-linked-list/NOTES.md ================================================ ​ ================================================ FILE: 114-flatten-binary-tree-to-linked-list/README.md ================================================

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)?
================================================ FILE: 114-flatten-binary-tree-to-linked-list/SolutionCode.cpp ================================================ class Solution { public: Node* helper(Node* root){ if(!root) return NULL; if(!root->left && !root->right) return root; Node* l = helper(root->left); Node* r = helper(root->right); root->left = NULL; if(l){ root->right = l; while(l->right){ l = l->right; } l-> right = r; } else if(r) root->right = r; return root; } void flatten(Node *root) { helper(root); } }; ================================================ FILE: 1143-longest-common-subsequence/1143-longest-common-subsequence.java ================================================ class Solution { public int longestCommonSubsequence(String s1, String s2) { int[][]dp=new int[s1.length()+1][s2.length()+1]; for(int i=1;i<=s1.length();i++){ for(int j=1;j<=s2.length();j++){ if(s1.charAt(i-1)==s2.charAt(j-1)){ dp[i][j]=dp[i-1][j-1]+1; }else{ dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]); } } } return dp[s1.length()][s2.length()]; } } ================================================ FILE: 1143-longest-common-subsequence/README.md ================================================

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.
================================================ FILE: 1155-number-of-dice-rolls-with-target-sum/1155-number-of-dice-rolls-with-target-sum.java ================================================ class Solution { static int MOD = (int)1e9 + 7; int helper(int n,int t,int k,int dp[][]){ if(n < 0 || t < 0) return 0; if(n == 0 && t == 0) return 1; if(dp[n][t] != -1) return dp[n][t]; int c_ans = 0; for(int i = 1;i <= k;i++){ c_ans = (c_ans + helper(n - 1,t - i,k,dp)) % MOD; } return dp[n][t] = c_ans; } public int numRollsToTarget(int n, int k, int target) { int dp[][] = new int[n + 1][target + 1]; for(var a:dp) Arrays.fill(a,-1); return helper(n,target,k,dp); } } ================================================ FILE: 1155-number-of-dice-rolls-with-target-sum/NOTES.md ================================================ ​ ================================================ FILE: 1155-number-of-dice-rolls-with-target-sum/README.md ================================================

1155. Number of Dice Rolls With Target Sum

Medium


You have n dice and each die has k faces numbered from 1 to k.

Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7.

 

Example 1:

Input: n = 1, k = 6, target = 3
Output: 1
Explanation: You throw one die with 6 faces.
There is only one way to get a sum of 3.

Example 2:

Input: n = 2, k = 6, target = 7
Output: 6
Explanation: You throw two dice, each with 6 faces.
There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.

Example 3:

Input: n = 30, k = 30, target = 500
Output: 222616187
Explanation: The answer must be returned modulo 109 + 7.

 

Constraints:

  • 1 <= n, k <= 30
  • 1 <= target <= 1000
================================================ FILE: 117-populating-next-right-pointers-in-each-node-ii/117-populating-next-right-pointers-in-each-node-ii.java ================================================ class Solution { public Node connect(Node root) { if (root == null || (root.left == null && root.right == null) ) { return root; } // connect left child to right child if (root.left != null && root.right != null) { root.left.next = root.right; } // connect right child (or left if right is abasent) to child of next nodes. Node lNode = (root.right == null) ? root.left : root.right; Node next = root.next; while (next != null && next.left == null && next.right == null) { next = next.next; } if (next != null) { lNode.next = (next.left != null) ? next.left : next.right; } // process right child first connect(root.right); connect(root.left); return root; } } ================================================ FILE: 117-populating-next-right-pointers-in-each-node-ii/NOTES.md ================================================ ​ ================================================ FILE: 117-populating-next-right-pointers-in-each-node-ii/README.md ================================================

117. Populating Next Right Pointers in Each Node II

Medium


Given a binary tree

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,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above 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, 6000].
  • -100 <= Node.val <= 100

 

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.
================================================ FILE: 118-pascals-triangle/118-pascals-triangle.java ================================================ class Solution { public List> generate(int numRows) { List> triangle = new ArrayList<>(); triangle.add(new ArrayList()); triangle.get(0).add(1); for(int i=1; i row = new ArrayList<>(); List previousRow = triangle.get(i-1); //first element is always 1 row.add(1); for(int j=1; j118. 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
================================================ FILE: 1192-critical-connections-in-a-network/1192-critical-connections-in-a-network.java ================================================ class Solution { int[] disc, low; int time = 1; List> ans = new ArrayList<>(); Map> edgeMap = new HashMap<>(); public List> criticalConnections(int n, List> connections) { disc = new int[n]; low = new int[n]; for (int i = 0; i < n; i++) edgeMap.put(i, new ArrayList()); for (List conn : connections) { edgeMap.get(conn.get(0)).add(conn.get(1)); edgeMap.get(conn.get(1)).add(conn.get(0)); } dfs(0, -1); return ans; } public void dfs(int curr, int prev) { disc[curr] = low[curr] = time++; for (int next : edgeMap.get(curr)) { if (disc[next] == 0) { dfs(next, curr); low[curr] = Math.min(low[curr], low[next]); } else if (next != prev) low[curr] = Math.min(low[curr], disc[next]); if (low[next] > disc[curr]) ans.add(Arrays.asList(curr, next)); } } } ================================================ FILE: 1192-critical-connections-in-a-network/README.md ================================================

1192. Critical Connections in a Network

Hard


There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network.

A critical connection is a connection that, if removed, will make some servers unable to reach some other server.

Return all critical connections in the network in any order.

 

Example 1:

Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
Output: [[1,3]]
Explanation: [[3,1]] is also accepted.

Example 2:

Input: n = 2, connections = [[0,1]]
Output: [[0,1]]

 

Constraints:

  • 2 <= n <= 105
  • n - 1 <= connections.length <= 105
  • 0 <= ai, bi <= n - 1
  • ai != bi
  • There are no repeated connections.
================================================ FILE: 12-integer-to-roman/12-Leetcode-Integer-to-roman.cpp ================================================ class Solution { public: string intToRoman(int num) { vector> vp{{1, "I"}, {4, "IV"}, {5, "V"}, {9, "IX"}, {10, "X"}, {40, "XL"}, {50, "L"}, {90, "XC"}, {100, "C"}, {400, "CD"}, {500, "D"}, {900, "CM"}, {1000, "M"}}; string s = ""; int j = vp.size() - 1; while(num != 0){ for(int i = j; i >= 0; i--){ if(vp[i].first <= num){ s += vp[i].second; num -= vp[i].first; j = i; break; } } } return s; } }; ================================================ FILE: 12-integer-to-roman/12-integer-to-roman.java ================================================ public class Solution { public String intToRoman(int A) { StringBuilder sb=new StringBuilder(); while(A!=0){ String str=Integer.toString(A); String num=""; for(int i=str.length()-1;i>=0;i--){ if(str.charAt(i)!='0'){ num=str.substring(i); break; } } String roman=getRoman(Integer.parseInt(num)); sb.insert(0,roman); A-=Integer.parseInt(num); } return sb.toString(); } public String getRoman(int a){ switch(a){ case 1: return "I"; case 2: return "II"; case 3: return "III"; case 4: return "IV"; case 5: return "V"; case 6: return "VI"; case 7: return "VII"; case 8: return "VIII"; case 9: return "IX"; case 10: return "X"; case 20: return "XX"; case 30: return "XXX"; case 40: return "XL"; case 50: return "L"; case 60: return "LX"; case 70: return "LXX"; case 80: return "LXXX"; case 90: return "XC"; case 100: return "C"; case 200: return "CC"; case 300: return "CCC"; case 400: return "CD"; case 500: return "D"; case 600: return "DC"; case 700: return "DCC"; case 800: return "DCCC"; case 900: return "CM"; case 1000: return "M"; case 2000: return "MM"; case 3000: return "MMM"; } return ""; } } ================================================ FILE: 12-integer-to-roman/NOTES.md ================================================ ​ ================================================ FILE: 12-integer-to-roman/README.md ================================================

12. Integer to Roman

Medium


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 an integer, convert it to a roman numeral.

 

Example 1:

Input: num = 3
Output: "III"
Explanation: 3 is represented as 3 ones.

Example 2:

Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.

Example 3:

Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

 

Constraints:

  • 1 <= num <= 3999
================================================ FILE: 120-triangle/120-triangle.java ================================================ class Solution { public int minimumTotal(List> list) { int sz=list.size(); if(sz==1) return list.get(0).get(0); int dp[]=new int[sz+1]; for(int row=sz-1;row>=0;row--) { int len=list.get(row).size(); for(int col=0;col120. 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?
================================================ FILE: 1207-unique-number-of-occurrences/1207-unique-number-of-occurrences.java ================================================ class Solution { public boolean uniqueOccurrences(int[] arr) { int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int num : arr) { min = Math.min(min, num); max = Math.max(max, num); } int[] frequency = new int[max - min + 1]; boolean[] frequency2 = new boolean[arr.length + 1]; for (int num : arr) { frequency[num - min]++; } for (int num : frequency) { if (num > 0) { if (frequency2[num]) return false; frequency2[num]=true; } } return true; } } ================================================ FILE: 1207-unique-number-of-occurrences/NOTES.md ================================================ ​ ================================================ FILE: 1207-unique-number-of-occurrences/README.md ================================================

1207. Unique Number of Occurrences

Easy


Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise.

 

Example 1:

Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.

Example 2:

Input: arr = [1,2]
Output: false

Example 3:

Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true

 

Constraints:

  • 1 <= arr.length <= 1000
  • -1000 <= arr[i] <= 1000
================================================ FILE: 1209-remove-all-adjacent-duplicates-in-string-ii/1209-remove-all-adjacent-duplicates-in-string-ii.java ================================================ class Solution { public String removeDuplicates(String s, int k) { int w = 0; int n = s.length(); int []count = new int[n]; char[] ar = s.toCharArray(); for(int i=0;i1209. Remove All Adjacent Duplicates in String II

Medium


You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.

We repeatedly make k duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.

 

Example 1:

Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.

Example 2:

Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation: 
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"

Example 3:

Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"

 

Constraints:

  • 1 <= s.length <= 105
  • 2 <= k <= 104
  • s only contains lower case English letters.
================================================ FILE: 1220-count-vowels-permutation/1220-count-vowels-permutation.java ================================================ class Solution { public int countVowelPermutation(int n) { int mod=(int)Math.pow(10,9)+7; int[]dp=new int[5]; for(int i=0;i<5;i++){ dp[i]=1; } for(int level=2;level<=n;level++){ int a= ((dp[1]+ dp[2])%mod +dp[4])%mod; int e= (dp[0] + dp[2])%mod; int i= (dp[1] + dp[3])%mod; int o=dp[2]; int u=(dp[2]+ dp[3])%mod; dp[0]=a; dp[1]=e; dp[2]=i; dp[3]=o; dp[4]=u; } return (((dp[0]+dp[1])%mod +(dp[2]+dp[3])%mod)%mod +dp[4])%mod; } } ================================================ FILE: 1220-count-vowels-permutation/NOTES.md ================================================ ​ ================================================ FILE: 1220-count-vowels-permutation/README.md ================================================

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
================================================ FILE: 1235-maximum-profit-in-job-scheduling/1235-maximum-profit-in-job-scheduling.java ================================================ class Solution { class Job implements Comparable{ int start; int end; int profit; Job(int start, int end, int profit) { this.start = start; this.end = end; this.profit = profit; } public int compareTo(Job otherJob) { return this.start - otherJob.start; } } public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { int n = startTime.length; Job[] jobs = new Job[n]; for (int i=0; i=0; i--) { dp[i] = Math.max(jobs[i].profit, dp[i+1]); for (int j=i+1; j < n; j++) { if (jobs[i].end <= jobs[j].start) { dp[i] = Math.max(dp[i], jobs[i].profit + dp[j]); break; } } } return dp[0]; } } ================================================ FILE: 1235-maximum-profit-in-job-scheduling/NOTES.md ================================================ ​ ================================================ FILE: 1235-maximum-profit-in-job-scheduling/README.md ================================================

1235. 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
================================================ FILE: 1239-maximum-length-of-a-concatenated-string-with-unique-characters/1239-maximum-length-of-a-concatenated-string-with-unique-characters.java ================================================ class Solution { public int solve(String strs[], int no, int a[], int index, int c) { if(index==c) return 0; int x=no & a[index]; if(x==0) return Math.max(strs[index].length()+solve(strs,no^a[index],a,index+1,c),solve(strs,no,a,index+1,c)); else return solve(strs,no,a,index+1,c); } public int maxLength(List arr) { int a[]=new int[arr.size()];int c=0;String strs[]=new String[a.length]; for(String s:arr) { int x=0,fl=0; for(char ch:s.toCharArray()) { int z=x|(1<<(ch-96)); if(x==z) { fl=1;break; } x=z; } if(fl==0) { a[c]=x; strs[c++]=s; } } return solve(strs,0,a,0,c); } } ================================================ FILE: 1239-maximum-length-of-a-concatenated-string-with-unique-characters/NOTES.md ================================================ ​ ================================================ FILE: 1239-maximum-length-of-a-concatenated-string-with-unique-characters/README.md ================================================

1239. Maximum Length of a Concatenated String with Unique Characters

Medium


You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.

Return the maximum possible length of s.

A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

 

Example 1:

Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All the valid concatenations are:
- ""
- "un"
- "iq"
- "ue"
- "uniq" ("un" + "iq")
- "ique" ("iq" + "ue")
Maximum length is 4.

Example 2:

Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers").

Example 3:

Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26
Explanation: The only string in arr has all 26 characters.

 

Constraints:

  • 1 <= arr.length <= 16
  • 1 <= arr[i].length <= 26
  • arr[i] contains only lowercase English letters.
================================================ FILE: 126-word-ladder-ii/126-word-ladder-ii.java ================================================ class Solution { public List> findLadders(String beginWord, String endWord, List wordList) { this.beginWord = beginWord; this.endWord = endWord; if (!sanityCheck(wordList)) { return new ArrayList<>(); } prepare(wordList); minTrans(); return trans; } private String beginWord; private String endWord; private Map w2p; private Map> p2w; private void minTrans() { Map minLens = new HashMap<>(); Map> prev = new HashMap<>(); List queue = new ArrayList<>(); int minLen = -1; minLens.put(endWord, 0); queue.add(endWord); int count = 0; while (count < queue.size()) { String node = queue.get(count++); int len = minLens.get(node) + 1; if (minLen != -1 && len > minLen) { break; } for (String pattern : w2p.get(node)) { for (String word : p2w.get(pattern)) { if (!minLens.containsKey(word)) { minLens.put(word, len); queue.add(word); prev.put(word, new HashSet<>()); if (word.equals(beginWord)) { minLen = len; } } else if (minLens.get(word) < len) { continue; } prev.get(word).add(node); } } } makeTrans(prev, minLens.getOrDefault(beginWord, -1)); } private List> trans; private Map> paths; private void makeTrans(Map> paths, int maxLen) { this.trans = new ArrayList<>(); this.paths = paths; if (maxLen == -1) { return; } String[] path = new String[maxLen + 1]; path[0] = beginWord; makeTransInternal(beginWord, 1, path); } void makeTransInternal(String start, int depth, String[] path) { if (depth == path.length - 1) { path[depth] = endWord; List result = new ArrayList<>(); for (String word : path) { result.add(word); } this.trans.add(result); return; } for (String word : paths.get(start)) { path[depth] = word; makeTransInternal(word, depth + 1, path); } } private boolean sanityCheck(List wordList) { for (String word : wordList) { if (word.equals(endWord)) { return true; } } return false; } private void prepare(List wordList) { // Prepare a word -> patterns map. w2p = new HashMap<>(); w2p.put(beginWord, getPatterns(beginWord)); for (String word : wordList) { w2p.put(word, getPatterns(word)); } // Prepare a pattern -> words map. p2w = new HashMap<>(); for (String word : w2p.keySet()) { for (String pattern : w2p.get(word)) { if (!p2w.containsKey(pattern)) { p2w.put(pattern, new ArrayList<>()); } p2w.get(pattern).add(word); } } } private String[] getPatterns(String word) { char[] wc = word.toCharArray(); char original; String[] patterns = new String[wc.length]; for (int i = 0; i < wc.length; ++i) { original = wc[i]; wc[i] = '*'; patterns[i] = new String(wc); wc[i] = original; } return patterns; } } ================================================ FILE: 126-word-ladder-ii/NOTES.md ================================================ ​ ================================================ FILE: 126-word-ladder-ii/README.md ================================================

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.
================================================ FILE: 1260-shift-2d-grid/1260-shift-2d-grid.java ================================================ class Solution { public List> shiftGrid(int[][] grid, int k) { int rowCount = grid.length;// Number of rows in grid. int colCount = grid[0].length;// Number of columns in grid. int gridCount = rowCount * colCount;// Number of cells (i.e. values) in grid. k = k % gridCount;// Limit k to max number of cells in grid. Avoid negatives in next lines. int kCol = (gridCount - k) % colCount;// Column to start copying from. int kRow = ((gridCount - k) % gridCount) / colCount;// Row to start copying from. int[] innRow = grid[kRow]; // Array for the row to start copying from. int[][] result = new int[rowCount][colCount]; // Create result matrix, to hold shifted values. for (int r = 0; r < rowCount; r++) { // Loop through "to" rows. int[] outRow = result[r];// Get row array to copy into, so only faster 1D reference in inner loop. for (int c = 0; c < colCount; c++) {// Loop through "to" columns. outRow[c] = innRow[kCol]; // Copy value from grid to result, shifting by copying. if (++kCol >= colCount) { // Next "from" column. If at end of row... kCol = 0; // Then start "from" columns at first column. if (++kRow >= rowCount) // When starting new column, next "from" row. If at end of grid... kRow = 0; // Then start "from" rows at first row. innRow = grid[kRow]; // Get row array to copy from, so only faster 1D reference when copying. } } } return (List)Arrays.asList(result); // Return result matrix, converting it to a List>. } } ================================================ FILE: 1260-shift-2d-grid/NOTES.md ================================================ ​ ================================================ FILE: 1260-shift-2d-grid/README.md ================================================

1260. Shift 2D Grid

Easy


Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.

In one shift operation:

  • Element at grid[i][j] moves to grid[i][j + 1].
  • Element at grid[i][n - 1] moves to grid[i + 1][0].
  • Element at grid[m - 1][n - 1] moves to grid[0][0].

Return the 2D grid after applying shift operation k times.

 

Example 1:

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

Example 2:

Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]

Example 3:

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

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m <= 50
  • 1 <= n <= 50
  • -1000 <= grid[i][j] <= 1000
  • 0 <= k <= 100
================================================ FILE: 1268-search-suggestions-system/1268-search-suggestions-system.java ================================================ class Solution { public List> suggestedProducts(String[] products, String searchWord) { List> ret = new ArrayList(); Arrays.sort(products); for(int i = 1; i <= searchWord.length(); i++) { List toAdd = new ArrayList(); String key = searchWord.substring(0,i); for(String product : products) { if(product.length() >= i && product.indexOf(key) == 0) { toAdd.add(product); if(toAdd.size() == 3) break; } } ret.add(toAdd); } return ret; } } ================================================ FILE: 1268-search-suggestions-system/NOTES.md ================================================ ​ ================================================ FILE: 1268-search-suggestions-system/README.md ================================================

1268. Search Suggestions System

Medium


You are given an array of strings products and a string searchWord.

Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.

Return a list of lists of the suggested products after each character of searchWord is typed.

 

Example 1:

Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [
["mobile","moneypot","monitor"],
["mobile","moneypot","monitor"],
["mouse","mousepad"],
["mouse","mousepad"],
["mouse","mousepad"]
]
Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"]
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"]
After typing mou, mous and mouse the system suggests ["mouse","mousepad"]

Example 2:

Input: products = ["havana"], searchWord = "havana"
Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]

Example 3:

Input: products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"
Output: [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]

 

Constraints:

  • 1 <= products.length <= 1000
  • 1 <= products[i].length <= 3000
  • 1 <= sum(products[i].length) <= 2 * 104
  • All the strings of products are unique.
  • products[i] consists of lowercase English letters.
  • 1 <= searchWord.length <= 1000
  • searchWord consists of lowercase English letters.
================================================ FILE: 128-longest-consecutive-sequence/128-longest-consecutive-sequence.java ================================================ class Solution { public int longestConsecutive(int[] nums) { Set num_set = new HashSet(); for (int num : nums) { num_set.add(num); } int longestStreak = 0; for (int num : nums) { if (!num_set.contains(num-1)){ int currentNum = num; int currentStreak = 1; while (num_set.contains(currentNum+1)) { currentNum += 1; currentStreak += 1; } longestStreak = Math.max(longestStreak, currentStreak); } } return longestStreak; } } ================================================ FILE: 128-longest-consecutive-sequence/NOTES.md ================================================ ​ ================================================ FILE: 128-longest-consecutive-sequence/README.md ================================================

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
================================================ FILE: 1293-shortest-path-in-a-grid-with-obstacles-elimination/1293-shortest-path-in-a-grid-with-obstacles-elimination.java ================================================ class Solution { class Node { int row; int col; int obstacles; Node(int row, int col, int obstacles){ this.row = row; this.col = col; this.obstacles = obstacles; } } private int[][] directions = {{1, 0}, {0, 1}, {0, -1}, {-1, 0}}; public int shortestPath(int[][] grid, int k) { int rows = grid.length; int cols = grid[0].length; int[][] visited = new int[rows][cols]; for(int i = 0; i < rows; i++) { Arrays.fill(visited[i], Integer.MAX_VALUE); } visited[0][0] = grid[0][0]; Queue queue = new LinkedList<>(); queue.add(new Node(0, 0, grid[0][0])); int result = 0; while(!queue.isEmpty()) { int size = queue.size(); for(int i = 0; i < size; i++) { Node node = queue.poll(); if(node.row == rows-1 && node.col == cols-1) { return result; } for(int t = 0; t < directions.length; t++) { int newRow = node.row + directions[t][0]; int newCol = node.col + directions[t][1]; if(newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) { int obstacles = node.obstacles + grid[newRow][newCol]; if(obstacles > k) { continue; } if(visited[newRow][newCol] > obstacles) { visited[newRow][newCol] = obstacles; queue.add(new Node(newRow, newCol, obstacles)); } } } } result++; } return -1; } } ================================================ FILE: 1293-shortest-path-in-a-grid-with-obstacles-elimination/NOTES.md ================================================ ​ ================================================ FILE: 1293-shortest-path-in-a-grid-with-obstacles-elimination/README.md ================================================

1293. Shortest Path in a Grid with Obstacles Elimination

Hard


You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.

Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.

 

Example 1:

Input: grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1
Output: 6
Explanation: 
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).

Example 2:

Input: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1
Output: -1
Explanation: We need to eliminate at least two obstacles to find such a walk.

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 40
  • 1 <= k <= m * n
  • grid[i][j] is either 0 or 1.
  • grid[0][0] == grid[m - 1][n - 1] == 0
================================================ FILE: 13-roman-to-integer/13-roman-to-integer.cpp ================================================ class Solution { public: int romanToInt(string s) { unordered_map mp{{'I',1},{'V',5},{'X',10},{'L',50},{'C',100,},{'D',500},{'M',1000}}; int ans = mp[s.back()]; for(int i=s.size()-2;i>=0;i--){ if(mp[s[i]] < mp[s[i+1]]) ans -= mp[s[i]]; else ans += mp[s[i]]; } return ans; } }; ================================================ FILE: 13-roman-to-integer/13-roman-to-integer.java ================================================ public class Solution { public int romanToInt(String A) { int ans=0; int i=0; while(igetValue(A.charAt(i))){ ans+=getValue(A.charAt(i+1))-getValue(A.charAt(i)); i+=2; }else{ ans+=getValue(A.charAt(i)); i++; } }else{ ans+=getValue(A.charAt(i)); i++; } } return ans; } int getValue(char ch){ switch(ch){ case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return -1; } } } ================================================ FILE: 13-roman-to-integer/NOTES.md ================================================ ​ ================================================ FILE: 13-roman-to-integer/README.md ================================================

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 ones 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
Explanation: III = 3.

Example 2:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 3:

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].
================================================ FILE: 1302-deepest-leaves-sum/1302-deepest-leaves-sum.java ================================================ class Solution { int deepestLevel = 0; int sum; public int deepestLeavesSum(TreeNode root) { deepestLeavesSum(root, 0); return sum; } public void deepestLeavesSum(TreeNode root,int level) { if (root == null) { return; } if (root.left == null && root.right == null && level == deepestLevel) { sum = sum + root.val; } if (root.left == null && root.right == null && level > deepestLevel) { deepestLevel = level; sum = root.val; } deepestLeavesSum(root.left, level + 1); deepestLeavesSum(root.right, level + 1); } } ================================================ FILE: 1302-deepest-leaves-sum/NOTES.md ================================================ ​ ================================================ FILE: 1302-deepest-leaves-sum/README.md ================================================

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
================================================ FILE: 1323-maximum-69-number/1323-maximum-69-number.java ================================================ class Solution { public int maximum69Number (int num) { char[] arr=(String.valueOf(num)).toCharArray(); for(int i=0;i1323. Maximum 69 Number

Easy


You are 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 <= 104
  • num consists of only 6 and 9 digits.
================================================ FILE: 1328-break-a-palindrome/1328-break-a-palindrome.java ================================================ class Solution { public String breakPalindrome(String palindrome) { if (palindrome.length() == 1){ return ""; } else { char[] arr = palindrome.toCharArray(); for (int i=0; i1328. Break a Palindrome

Medium


Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.

Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.

A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, "abcc" is lexicographically smaller than "abcd" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'.

 

Example 1:

Input: palindrome = "abccba"
Output: "aaccba"
Explanation: There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba".
Of all the ways, "aaccba" is the lexicographically smallest.

Example 2:

Input: palindrome = "a"
Output: ""
Explanation: There is no way to replace a single character to make "a" not a palindrome, so return an empty string.

 

Constraints:

  • 1 <= palindrome.length <= 1000
  • palindrome consists of only lowercase English letters.
================================================ FILE: 1329-sort-the-matrix-diagonally/1329-sort-the-matrix-diagonally.cpp ================================================ class Solution { public: vector> diagonalSort(vector>& mat) { // // Explanation // // A[i][j] on the same diagonal have same value of i - j // // For each diagonal, // // put its elements together, sort, and set them back. // // Complexity // // Time O(MNlogD), where D is the length of diagonal with D = min(M,N). // // Space O(MN) // solving with priority queue, 20ms // int n = mat.size(), m = mat[0].size(); // unordered_map, greater>> mp; // for(int i=0;i t; while(p < r and q < c){ t.push_back(mat[p][q]); p++;q++; } sort(t.begin(), t.end()); // placing back p=0,q=i,j=0; while(p t; p=i,q=0; while(p0){ int cnt=values[i]; while(cnt-->0){ mat[r][c]=i; r++;c++; } } } } } ================================================ FILE: 1329-sort-the-matrix-diagonally/NOTES.md ================================================ ​ ================================================ FILE: 1329-sort-the-matrix-diagonally/README.md ================================================

1329. Sort the Matrix Diagonally

Medium


A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2].

Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.

 

Example 1:

Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]

Example 2:

Input: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]
Output: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]

 

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • 1 <= mat[i][j] <= 100
================================================ FILE: 1329-sort-the-matrix-diagonally/SolutionCode.cpp ================================================ class Solution { public: void sortIt(int r,int c,int m,int n,vector> &v){ int i = r, j = c; vector a; while(i> diagonalSort(vector>& mat) { if(mat.size()==1) return mat; int m = mat.size(), n = mat[0].size(); //0 row for(int col = 0;col1332. Remove Palindromic Subsequences

Easy


You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.

Return the minimum number of steps to make the given string empty.

A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous.

A string is called palindrome if is one that reads the same backward as well as forward.

 

Example 1:

Input: s = "ababa"
Output: 1
Explanation: s is already a palindrome, so its entirety can be removed in a single step.

Example 2:

Input: s = "abb"
Output: 2
Explanation: "abb" -> "bb" -> "". 
Remove palindromic subsequence "a" then "bb".

Example 3:

Input: s = "baabb"
Output: 2
Explanation: "baabb" -> "b" -> "". 
Remove palindromic subsequence "baab" then "b".

 

Constraints:

  • 1 <= s.length <= 1000
  • s[i] is either 'a' or 'b'.
================================================ FILE: 1335-minimum-difficulty-of-a-job-schedule/1335-minimum-difficulty-of-a-job-schedule.java ================================================ class Solution { Integer[][] dp; int n; public int Helper(int idx, int[] arr, int d){ if(idx == n && d == 0) return 0; if(n - idx < d) return (int)1e5; // only for optimization not necessary if(d < 0) return (int)1e5; if(dp[idx][d] != null) return dp[idx][d]; int max = 0; int res = Integer.MAX_VALUE; for(int i = idx; i < n; ++i){ max = Math.max(arr[i], max); res = Math.min(res, max + Helper(i + 1, arr, d - 1)); } return dp[idx][d] = res; } public int minDifficulty(int[] jobDifficulty, int d) { this.n = jobDifficulty.length; this.dp = new Integer[n][d + 1]; if(n < d) return -1; return Helper(0, jobDifficulty, d); } } ================================================ FILE: 1335-minimum-difficulty-of-a-job-schedule/NOTES.md ================================================ ​ ================================================ FILE: 1335-minimum-difficulty-of-a-job-schedule/README.md ================================================

1335. Minimum Difficulty of a Job Schedule

Hard


You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i).

You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day.

You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i].

Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.

 

Example 1:

Input: jobDifficulty = [6,5,4,3,2,1], d = 2
Output: 7
Explanation: First day you can finish the first 5 jobs, total difficulty = 6.
Second day you can finish the last job, total difficulty = 1.
The difficulty of the schedule = 6 + 1 = 7 

Example 2:

Input: jobDifficulty = [9,9,9], d = 4
Output: -1
Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.

Example 3:

Input: jobDifficulty = [1,1,1], d = 3
Output: 3
Explanation: The schedule is one job per day. total difficulty will be 3.

 

Constraints:

  • 1 <= jobDifficulty.length <= 300
  • 0 <= jobDifficulty[i] <= 1000
  • 1 <= d <= 10
================================================ FILE: 1337-the-k-weakest-rows-in-a-matrix/1337-the-k-weakest-rows-in-a-matrix.java ================================================ class Solution { public int[] kWeakestRows(int[][] mat, int k) { int[]ans=new int[k]; int[][]freq=new int[mat.length][2]; for(int i=0;io1[0]-o2[0]); for(int i=0;i1337. 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.
================================================ FILE: 1338-reduce-array-size-to-the-half/1338-reduce-array-size-to-the-half.cpp ================================================ int minSetSize(vector& arr) { mapmp; for(int i=0;i>pq; for(auto it:mp) { pq.push({it.second,it.first}); } int size=arr.size()/2; int count=0; while(size>0 && !pq.empty()) { if(size pq=new PriorityQueue<>((a,b)->b.freq-a.freq); Map map=new HashMap<>(); for(int i:arr){ map.put(i,map.getOrDefault(i,0)+1); } for(Map.Entry entry : map.entrySet()){ pq.add(new Pair(entry.getKey(),entry.getValue())); } int ans=0; int size=arr.length; int sz=arr.length; while(sz>size/2){ ans++; Pair p=pq.remove(); sz-=p.freq; } return ans; } } ================================================ FILE: 1338-reduce-array-size-to-the-half/README.md ================================================

1338. Reduce Array Size to The Half

Medium


You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.

Return the minimum size of the set so that at least half of the integers of the array are removed.

 

Example 1:

Input: arr = [3,3,3,3,5,5,5,2,2,7]
Output: 2
Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
Possible sets of size 2 are {3,5},{3,2},{5,2}.
Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.

Example 2:

Input: arr = [7,7,7,7,7,7]
Output: 1
Explanation: The only possible set you can choose is {7}. This will make the new array empty.

 

Constraints:

  • 2 <= arr.length <= 105
  • arr.length is even.
  • 1 <= arr[i] <= 105
================================================ FILE: 1339-maximum-product-of-splitted-binary-tree/1339-maximum-product-of-splitted-binary-tree.java ================================================ class Solution { int mod = 1000000007; long max = 0; long total; public int maxProduct(TreeNode root) { this.total = dfs(root); traverse(root); return (int)(max%mod); } private int dfs(TreeNode root) { if(root==null) return 0; return root.val += dfs(root.left) + dfs(root.right); } private void traverse(TreeNode root) { if(root==null) return; max = Math.max(root.val*(total-root.val),max); traverse(root.left); traverse(root.right); } } ================================================ FILE: 1339-maximum-product-of-splitted-binary-tree/NOTES.md ================================================ ​ ================================================ FILE: 1339-maximum-product-of-splitted-binary-tree/README.md ================================================

1339. Maximum Product of Splitted Binary Tree

Medium


Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.

Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7.

Note that you need to maximize the answer before taking the mod and not after taking it.

 

Example 1:

Input: root = [1,2,3,4,5,6]
Output: 110
Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)

Example 2:

Input: root = [1,null,2,3,4,null,null,5,6]
Output: 90
Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)

 

Constraints:

  • The number of nodes in the tree is in the range [2, 5 * 104].
  • 1 <= Node.val <= 104
================================================ FILE: 1342-number-of-steps-to-reduce-a-number-to-zero/1342-number-of-steps-to-reduce-a-number-to-zero.java ================================================ class Solution { public int numberOfSteps(int num) { int count = 1; if(num == 0){return 0;} if( num / 2== 0 || num - 1 == 0){return count;} if(num % 2 == 0){ return count + numberOfSteps(num/2);} return count + numberOfSteps(num-1); } } ================================================ FILE: 1342-number-of-steps-to-reduce-a-number-to-zero/NOTES.md ================================================ ​ ================================================ FILE: 1342-number-of-steps-to-reduce-a-number-to-zero/README.md ================================================

1342. Number of Steps to Reduce a Number to Zero

Easy


Given an integer num, return the number of steps to reduce it to zero.

In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

 

Example 1:

Input: num = 14
Output: 6
Explanation: 
Step 1) 14 is even; divide by 2 and obtain 7. 
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3. 
Step 4) 3 is odd; subtract 1 and obtain 2. 
Step 5) 2 is even; divide by 2 and obtain 1. 
Step 6) 1 is odd; subtract 1 and obtain 0.

Example 2:

Input: num = 8
Output: 4
Explanation: 
Step 1) 8 is even; divide by 2 and obtain 4. 
Step 2) 4 is even; divide by 2 and obtain 2. 
Step 3) 2 is even; divide by 2 and obtain 1. 
Step 4) 1 is odd; subtract 1 and obtain 0.

Example 3:

Input: num = 123
Output: 12

 

Constraints:

  • 0 <= num <= 106
================================================ FILE: 135-candy/135-candy.java ================================================ public class Solution { public int candy(int[] ratings) { int[] candies = new int[ratings.length]; Arrays.fill(candies, 1); for (int i = 1; i < ratings.length; i++) { if (ratings[i] > ratings[i - 1]) { candies[i] = candies[i - 1] + 1; } } int sum = candies[ratings.length - 1]; for (int i = ratings.length - 2; i >= 0; i--) { if (ratings[i] > ratings[i + 1]) { candies[i] = Math.max(candies[i], candies[i + 1] + 1); } sum += candies[i]; } return sum; } } ================================================ FILE: 135-candy/NOTES.md ================================================ ​ ================================================ FILE: 135-candy/README.md ================================================

135. Candy

Hard


There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.

You are giving candies to these children subjected to the following requirements:

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.

Return the minimum number of candies you need to have to distribute the candies to the children.

 

Example 1:

Input: ratings = [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: ratings = [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.

 

Constraints:

  • n == ratings.length
  • 1 <= n <= 2 * 104
  • 0 <= ratings[i] <= 2 * 104
================================================ FILE: 1354-construct-target-array-with-multiple-sums/1354-construct-target-array-with-multiple-sums.java ================================================ class Solution { public boolean isPossible(int[] target) { long sum=0; int n=target.length; Queue pq=new PriorityQueue<>(Collections.reverseOrder()); for(int i:target){ sum+=i; pq.add(i); } while(sum!=n){ int largest=pq.remove(); sum-=largest; if(sum==1 || largest==1)return true; if(sum>largest || sum==0 || largest%sum==0)return false; largest%=sum; sum+=largest; pq.add(largest); } return true; } } ================================================ FILE: 1354-construct-target-array-with-multiple-sums/NOTES.md ================================================ ​ ================================================ FILE: 1354-construct-target-array-with-multiple-sums/README.md ================================================

1354. Construct Target Array With Multiple Sums

Hard


You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure :

  • let x be the sum of all elements currently in your array.
  • choose index i, such that 0 <= i < n and set the value of arr at index i to x.
  • You may repeat this procedure as many times as needed.

Return true if it is possible to construct the target array from arr, otherwise, return false.

 

Example 1:

Input: target = [9,3,5]
Output: true
Explanation: Start with arr = [1, 1, 1] 
[1, 1, 1], sum = 3 choose index 1
[1, 3, 1], sum = 5 choose index 2
[1, 3, 5], sum = 9 choose index 0
[9, 3, 5] Done

Example 2:

Input: target = [1,1,1,2]
Output: false
Explanation: Impossible to create target array from [1,1,1,1].

Example 3:

Input: target = [8,5]
Output: true

 

Constraints:

  • n == target.length
  • 1 <= n <= 5 * 104
  • 1 <= target[i] <= 109
================================================ FILE: 1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { TreeNode ans; TreeNode tar; public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) { tar=target; dfs(original,cloned); return ans; } public void dfs(TreeNode a,TreeNode b){ if(a==null)return; if(a==tar){ ans=b; return; } dfs(a.left,b.left); dfs(a.right,b.right); } } ================================================ FILE: 1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/README.md ================================================

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

 

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?

================================================ FILE: 1381. Design a Stack With Increment Operation/1381-Design-a-Stack-With-Increment-Operation.cpp ================================================ class CustomStack { public: // 1. // stack st; // int n; // CustomStack(int maxSize){ // n = maxSize; // } // void push(int x){ // if(st.size() < n){ // st.push(x); // } // } // int pop(){ // int t = -1; // if(!st.empty()){ // t = st.top(); // st.pop(); // } // return t; // } // void increment(int k, int val){ // stack ts; // int m; // if(k < st.size()){ // m = st.size() - k; // for(int i=0;i stack, inc; int n; CustomStack(int maxSize) { n = maxSize; } void push(int x) { if (stack.size() == n) return; stack.push_back(x); inc.push_back(0); } // jo bhi ho raha hain pop function m ho raha hain int pop() { int i = stack.size() - 1; if (i < 0) return -1; // if stack is empty if (i > 0) inc[i - 1] += inc[i]; // here if we have added more to current then increment to the previous values too. // like in case of 5, 100 and again 2, 100 // do dry run you will understand better. int res = stack[i] + inc[i]; stack.pop_back(); inc.pop_back(); return res; } void increment(int k, int val) { int i = min(k, (int)stack.size()) - 1; if (i >= 0) inc[i] += val; // here comes the use of increment vector } }; ================================================ FILE: 1383 Maximum Performance of a Team lc hard.cpp ================================================ #include using namespace std; class Solution { // TC: O(N * (logN + logK)) // SC: O(N + K) // where N = total number of candidates & K = size of team public: int maxPerformance(int n, vector& speed, vector& efficiency, int k) { int MOD = 1e9 + 7; vector> candidates(n); // building pair { efficiency, speed } to sort it later for (int i = 0; i < n; i++) candidates[i] = { efficiency[i], speed[i] }; // sort candidates in dsc sort(candidates.rbegin(), candidates.rend()); // Using Example 1: // speed: [2, 10, 3, 1 ,5, 8] and efficiency: [5, 4, 3, 9, 7, 2] // after sort, it becomes // candidates: [{9, 1}, {7 ,5}, {5, 2}, {4, 10}, {3, 3}, {2, 8}] long speedSum = 0, ans = 0; // we use priority queue here with greater to store the sum // i.e min heap (the smallest element goes on the top) priority_queue , greater> pq; // iterate each pair for (auto& [e, s] : candidates) { // put the speed to priority queue pq.push(s); // add to speedSum speedSum += s; // we only need to choose at most k engineers // hence if the queue size is greater than k // we need to remove a candidate if (pq.size() > k) { // who to remove? of course the one with smallest speed speedSum -= pq.top(); pq.pop(); } // a team is formed now, calculate the performance ans = max(ans, speedSum * e); } return ans % MOD; } }; ================================================ FILE: 1383-maximum-performance-of-a-team/1383-maximum-performance-of-a-team.java ================================================ class Solution { public int maxPerformance(int n, int[] speed, int[] efficiency, int k) { int[][] players = new int[n][2]; for (int i=0; i (p2[0] - p1[0])); // Priority-Queue to maintain players with highest relative speeds with efficiencies greater than the one under iteration. PriorityQueue speedQueue = new PriorityQueue<>(k); long teamPerformance = 0, teamSpeed = 0; for (int i=0; i= k) { teamSpeed -= speedQueue.remove(); } speedQueue.add(players[i][1]); teamSpeed += players[i][1]; teamPerformance = Math.max(teamPerformance, teamSpeed * players[i][0]); } return (int) (teamPerformance % 1000000007); } } ================================================ FILE: 1383-maximum-performance-of-a-team/README.md ================================================

1383. Maximum Performance of a Team

Hard


You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively.

Choose at most k different engineers out of the n engineers to form a team with the maximum performance.

The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.

Return the maximum performance of this team. Since the answer can be a huge number, return it modulo 109 + 7.

 

Example 1:

Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2
Output: 60
Explanation: 
We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.

Example 2:

Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3
Output: 68
Explanation:
This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.

Example 3:

Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4
Output: 72

 

Constraints:

  • 1 <= k <= n <= 105
  • speed.length == n
  • efficiency.length == n
  • 1 <= speed[i] <= 105
  • 1 <= efficiency[i] <= 108
================================================ FILE: 1396-design-underground-system/1396-design-underground-system.java ================================================ class UndergroundSystem { class Pair{ String place; int time; Pair(String p,int t){ place=p; time=t; } } Map inMap; Map> map; public UndergroundSystem() { inMap=new HashMap<>(); map=new HashMap<>(); } public void checkIn(int id, String p, int t) { inMap.put(id,new Pair(p,t)); } public void checkOut(int id, String stationName, int t) { Pair pair=inMap.get(id); String start=pair.place; int inTime=pair.time; String route=start+"-"+stationName; int avgTime=t-inTime; if(map.containsKey(route)){ ArrayList arr=map.get(route); arr.add(avgTime); map.put(route,arr); }else{ ArrayList arr=new ArrayList<>(); arr.add(avgTime); map.put(route,arr); } } public double getAverageTime(String start, String end) { String route=start+"-"+end; ArrayList arr=map.get(route); int len=arr.size(); double sum=0; for(int i:arr){ sum+=i; } return sum/len; } } /** * Your UndergroundSystem object will be instantiated and called as such: * UndergroundSystem obj = new UndergroundSystem(); * obj.checkIn(id,stationName,t); * obj.checkOut(id,stationName,t); * double param_3 = obj.getAverageTime(startStation,endStation); */ ================================================ FILE: 1396-design-underground-system/NOTES.md ================================================ ​ ================================================ FILE: 1396-design-underground-system/README.md ================================================

1396. Design Underground System

Medium


An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.

Implement the UndergroundSystem class:

  • void checkIn(int id, string stationName, int t)
    • A customer with a card ID equal to id, checks in at the station stationName at time t.
    • A customer can only be checked into one place at a time.
  • void checkOut(int id, string stationName, int t)
    • A customer with a card ID equal to id, checks out from the station stationName at time t.
  • double getAverageTime(string startStation, string endStation)
    • Returns the average time it takes to travel from startStation to endStation.
    • The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation.
    • The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation.
    • There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.

You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.

 

Example 1:

Input
["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"]
[[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]]

Output
[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]

Explanation
UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(45, "Leyton", 3);
undergroundSystem.checkIn(32, "Paradise", 8);
undergroundSystem.checkIn(27, "Leyton", 10);
undergroundSystem.checkOut(45, "Waterloo", 15);  // Customer 45 "Leyton" -> "Waterloo" in 15-3 = 12
undergroundSystem.checkOut(27, "Waterloo", 20);  // Customer 27 "Leyton" -> "Waterloo" in 20-10 = 10
undergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -> "Cambridge" in 22-8 = 14
undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -> "Cambridge", (14) / 1 = 14
undergroundSystem.getAverageTime("Leyton", "Waterloo");    // return 11.00000. Two trips "Leyton" -> "Waterloo", (10 + 12) / 2 = 11
undergroundSystem.checkIn(10, "Leyton", 24);
undergroundSystem.getAverageTime("Leyton", "Waterloo");    // return 11.00000
undergroundSystem.checkOut(10, "Waterloo", 38);  // Customer 10 "Leyton" -> "Waterloo" in 38-24 = 14
undergroundSystem.getAverageTime("Leyton", "Waterloo");    // return 12.00000. Three trips "Leyton" -> "Waterloo", (10 + 12 + 14) / 3 = 12

Example 2:

Input
["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"]
[[],[10,"Leyton",3],[10,"Paradise",8],["Leyton","Paradise"],[5,"Leyton",10],[5,"Paradise",16],["Leyton","Paradise"],[2,"Leyton",21],[2,"Paradise",30],["Leyton","Paradise"]]

Output
[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]

Explanation
UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(10, "Leyton", 3);
undergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -> "Paradise" in 8-3 = 5
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5
undergroundSystem.checkIn(5, "Leyton", 10);
undergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -> "Paradise" in 16-10 = 6
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5
undergroundSystem.checkIn(2, "Leyton", 21);
undergroundSystem.checkOut(2, "Paradise", 30); // Customer 2 "Leyton" -> "Paradise" in 30-21 = 9
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667

 

Constraints:

  • 1 <= id, t <= 106
  • 1 <= stationName.length, startStation.length, endStation.length <= 10
  • All strings consist of uppercase and lowercase English letters and digits.
  • There will be at most 2 * 104 calls in total to checkIn, checkOut, and getAverageTime.
  • Answers within 10-5 of the actual value will be accepted.
================================================ FILE: 14. Longest Common Prefix.py ================================================ def longestCommonPrefix(self, strs: List[str]) -> str: sub = "" counter = 0 for i in range(len(strs[0])): for j in range(len(strs)): if len(strs[j]) <= i: return sub if strs[j][i] == strs[0][i]: counter += 1 if counter == len(strs): sub += strs[0][i] counter = 0 else: return sub return sub ================================================ FILE: 1423-maximum-points-you-can-obtain-from-cards/1423-maximum-points-you-can-obtain-from-cards.java ================================================ class Solution { public int maxScore(int[] cardPoints, int k) { int n = cardPoints.length, l= 0, r = n - k ; int total = 0; for (int i = r; 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
================================================ FILE: 143-Reorder List.java ================================================ // Runtime: 11 ms, faster than 10.15% of Java online submissions for Reorder List. // Memory Usage: 54.4 MB, less than 29.31% of Java online submissions for Reorder List. class Solution { public void reorderList(ListNode head) { ListNode curr = head; Stack s = new Stack<>(); while(curr != null) { s.push(curr); curr = curr.next; } curr = head; int n = s.size(); if(n<=2) return; ListNode next; for(int i = 0; i < n/2; i++) { next = curr.next; curr.next = s.peek(); s.pop(); curr = curr.next; curr.next = next; curr = curr.next; } curr.next = null; } } ================================================ FILE: 1443-minimum-time-to-collect-all-apples-in-a-tree/1443-minimum-time-to-collect-all-apples-in-a-tree.java ================================================ class Solution { public int dfs(int node, int parent, Map> adj, List hasApple) { if (!adj.containsKey(node)) return 0; int totalTime = 0, childTime = 0; for (int child : adj.get(node)) { if (child == parent) continue; childTime = dfs(child, node, adj, hasApple); // childTime > 0 indicates subtree of child has apples. Since the root node of the // subtree does not contribute to the time, even if it has an apple, we have to check it // independently. if (childTime > 0 || hasApple.get(child)) totalTime += childTime + 2; } return totalTime; } public int minTime(int n, int[][] edges, List hasApple) { Map> adj = new HashMap<>(); for (int[] edge : edges) { int a = edge[0], b = edge[1]; adj.computeIfAbsent(a, value -> new ArrayList()).add(b); adj.computeIfAbsent(b, value -> new ArrayList()).add(a); } return dfs(0, -1, adj, hasApple); } } ================================================ FILE: 1443-minimum-time-to-collect-all-apples-in-a-tree/README.md ================================================

1443. Minimum Time to Collect All Apples in a Tree

Medium


Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.

The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.

 

Example 1:

Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]
Output: 8 
Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.  

Example 2:

Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]
Output: 6
Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.  

Example 3:

Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]
Output: 0

 

Constraints:

  • 1 <= n <= 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 <= ai < bi <= n - 1
  • fromi < toi
  • hasApple.length == n
================================================ FILE: 1448-count-good-nodes-in-binary-tree/1448-count-good-nodes-in-binary-tree.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { int count; public int goodNodes(TreeNode root) { if(root.left==null && root.right==null ){ return 1; } count=0; int curr=root.val; helper(root,curr); return count; } public void helper(TreeNode root,int curr){ if(root==null) return; if(root.val>=curr){ count++; curr=root.val; } helper(root.left,curr); helper(root.right,curr); } } ================================================ FILE: 1448-count-good-nodes-in-binary-tree/NOTES.md ================================================ ​ ================================================ FILE: 1448-count-good-nodes-in-binary-tree/README.md ================================================

1448. Count Good Nodes in Binary Tree

Medium


Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.

Return the number of good nodes in the binary tree.

 

Example 1:

Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.

Example 2:

Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.

Example 3:

Input: root = [1]
Output: 1
Explanation: Root is considered as good.

 

Constraints:

  • The number of nodes in the binary tree is in the range [1, 10^5].
  • Each node's value is between [-10^4, 10^4].
================================================ FILE: 1457 Pseudo-Palindromic Paths in a Binary Tree lc.cpp ================================================ class Solution { public: vector a; //map count nodes with same value int ans; // store ans bool checkPalin(){ int cnt=0; for(int i=1;i<10;i++){ if(a[i]&1){ cnt++; } } if(cnt>1) return false; else return true; } void solve(TreeNode *root){ if(!root) return; if(!root->left && !root->right){ a[root->val]++; if(checkPalin()) ans++; a[root->val]--; return ; } a[root->val]++; solve(root->left); solve(root->right); a[root->val]--; } int pseudoPalindromicPaths (TreeNode* root) { ans=0; a.resize(10,0); solve(root); return ans; } }; ================================================ FILE: 1457-pseudo-palindromic-paths-in-a-binary-tree/1457-pseudo-palindromic-paths-in-a-binary-tree.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { int ans; public int pseudoPalindromicPaths (TreeNode root) { int[] freq=new int[10]; ans=0; dfs(root,freq); return ans; } void dfs(TreeNode root,int[]freq){ if(root.left==null && root.right==null){ freq[root.val]++; boolean odd=false; for(int i=0;i<10;i++){ if(freq[i]%2!=0){ if(!odd){ odd=true; }else{ freq[root.val]--; return; } } } ans++; freq[root.val]--; return; } freq[root.val]++; if(root.left!=null)dfs(root.left,freq); if(root.right!=null)dfs(root.right,freq); freq[root.val]--; } } ================================================ FILE: 1457-pseudo-palindromic-paths-in-a-binary-tree/README.md ================================================

1457. Pseudo-Palindromic Paths in a Binary Tree

Medium


Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.

Return the number of pseudo-palindromic paths going from the root node to leaf nodes.

 

Example 1:

Input: root = [2,3,1,3,1,null,1]
Output: 2 
Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).

Example 2:

Input: root = [2,1,1,1,3,null,null,null,null,null,1]
Output: 1 
Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).

Example 3:

Input: root = [9]
Output: 1

 

Constraints:

  • The number of nodes in the tree is in the range [1, 105].
  • 1 <= Node.val <= 9
================================================ FILE: 1461-check-if-a-string-contains-all-binary-codes-of-size-k/1461-check-if-a-string-contains-all-binary-codes-of-size-k.java ================================================ class Solution { public static boolean hasAllCodes(String s, int k) { int need = 1 << k; boolean[] got = new boolean[need]; int allOne = need - 1; int hashVal = 0; for (int i = 0; i < s.length(); i++) { // calculate hash for s.substr(i-k+1,i+1) hashVal = ((hashVal << 1) & allOne) | (s.charAt(i) - '0'); // hash only available when i-k+1 > 0 if (i >= k - 1 && !got[hashVal]) { got[hashVal] = true; need--; if (need == 0) { return true; } } } return false; } } ================================================ FILE: 1461-check-if-a-string-contains-all-binary-codes-of-size-k/NOTES.md ================================================ ​ ================================================ FILE: 1461-check-if-a-string-contains-all-binary-codes-of-size-k/README.md ================================================

1461. Check If a String Contains All Binary Codes of Size K

Medium


Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.

 

Example 1:

Input: s = "00110110", k = 2
Output: true
Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.

Example 2:

Input: s = "0110", k = 1
Output: true
Explanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring. 

Example 3:

Input: s = "0110", k = 2
Output: false
Explanation: The binary code "00" is of length 2 and does not exist in the array.

 

Constraints:

  • 1 <= s.length <= 5 * 105
  • s[i] is either '0' or '1'.
  • 1 <= k <= 20
================================================ FILE: 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.java ================================================ class Solution { public int maxArea(int h, int w, int[] hc, int[] vc) { return (int)((getMax(h,hc)*getMax(w,vc))%1000000007); } public long getMax(int len,int[] cuts){ Arrays.sort(cuts); long from=0,max=0; for(int c:cuts){ max=Math.max(max,c-from); from=c; } return Math.max(max,len-from); } } ================================================ FILE: 1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/NOTES.md ================================================ ​ ================================================ FILE: 1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/README.md ================================================

1465. 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.
================================================ FILE: 1473-paint-house-iii/1473-paint-house-iii.java ================================================ class Solution { static final int MAX_COST = 1000001; public int minCost(int[] houses, int[][] cost, int m, int n, int target) { // dp(i, j, k): house, color, group int[][][] dp = new int[m][n][target]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < target; k++) { dp[i][j][k] = MAX_COST; } } } if (houses[0] == 0) { for (int j = 0; j < n; j++) { dp[0][j][target - 1] = cost[0][j]; } } else { int j = houses[0] - 1; dp[0][j][target - 1] = 0; } int lr = target - 1; for (int i = 1; i < m; i++) { int hr = m - i; if (hr >= target) { hr = target - 1; } if (houses[i] > 0) { int j = houses[i] - 1; for (int remaining = hr; remaining >= lr; remaining--) { // not change dp[i][j][remaining] = Math.min(dp[i][j][remaining], dp[i - 1][j][remaining]); // change if (houses[i - 1] > 0 && houses[i - 1] - 1 != j) { dp[i][j][remaining - 1] = Math.min(dp[i][j][remaining - 1], dp[i - 1][houses[i - 1] - 1][remaining]); } else { dp[i][j][remaining - 1] = Math.min(dp[i][j][remaining - 1], min(dp[i - 1], j, remaining)); } } if (lr == 1) { dp[i][j][0] = Math.min(dp[i][j][0], dp[i - 1][j][0]); } } else { for (int j = 0; j < n; j++) { for (int remaining = hr; remaining >= lr; remaining--) { // not change int a = dp[i - 1][j][remaining]; int b = cost[i][j]; dp[i][j][remaining] = Math.min(dp[i][j][remaining], dp[i - 1][j][remaining] + cost[i][j]); // change if (houses[i - 1] > 0 && houses[i - 1] - 1 != j) { dp[i][j][remaining - 1] = Math.min(dp[i][j][remaining - 1], dp[i - 1][houses[i - 1] - 1][remaining] + cost[i][j]); } else { dp[i][j][remaining - 1] = Math.min(dp[i][j][remaining - 1], min(dp[i - 1], j, remaining) + cost[i][j]); } } if (lr == 1) { dp[i][j][0] = Math.min(dp[i][j][0], dp[i - 1][j][0] + cost[i][j]); } } } if (lr > 1) { lr--; } } int min = dp[m - 1][0][0]; for (int j = 1; j < n; j++) { if (dp[m - 1][j][0] < min) { min = dp[m - 1][j][0]; } } return min < MAX_COST ? min : -1; } private int min(int[][] minCost, int j, int remaining) { int min = Integer.MAX_VALUE; for (int k = 0; k < minCost.length; k++) { if (k != j && minCost[k][remaining] < min) { min = minCost[k][remaining]; } } return min; } } ================================================ FILE: 1473-paint-house-iii/NOTES.md ================================================ ​ ================================================ FILE: 1473-paint-house-iii/README.md ================================================

1473. Paint House III

Hard


There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again.

A neighborhood is a maximal group of continuous houses that are painted with the same color.

  • For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}].

Given an array houses, an m x n matrix cost and an integer target where:

  • houses[i]: is the color of the house i, and 0 if the house is not painted yet.
  • cost[i][j]: is the cost of paint the house i with the color j + 1.

Return the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods. If it is not possible, return -1.

 

Example 1:

Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3
Output: 9
Explanation: Paint houses of this way [1,2,2,1,1]
This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].
Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.

Example 2:

Input: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3
Output: 11
Explanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2]
This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. 
Cost of paint the first and last house (10 + 1) = 11.

Example 3:

Input: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3
Output: -1
Explanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.

 

Constraints:

  • m == houses.length == cost.length
  • n == cost[i].length
  • 1 <= m <= 100
  • 1 <= n <= 20
  • 1 <= target <= m
  • 0 <= houses[i] <= n
  • 1 <= cost[i][j] <= 104
================================================ FILE: 1480-running-sum-of-1d-array/1480-running-sum-of-1d-array.java ================================================ class Solution { public int[] runningSum(int[] nums) { for(int i=1;i1480. Running Sum of 1d Array

Easy


Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).

Return the running sum of nums.

 

Example 1:

Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

Example 2:

Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].

Example 3:

Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]

 

Constraints:

  • 1 <= nums.length <= 1000
  • -10^6 <= nums[i] <= 10^6
================================================ FILE: 15. 3Sum/SolutionCode.cpp ================================================ class Solution { public: vector> threeSum(vector& nums) { set> s; sort(nums.begin(), nums.end()); int n = nums.size(); if(nums[0]==0 && nums[n-1]==0){ return {{0,0,0}}; } for(int i=0; i< n-2; i++){ int l = i + 1, r = n - 1; while(l < r){ int sum = nums[i] + nums[l] + nums[r]; if(sum == 0){ s.insert({nums[i], nums[l], nums[r]}); l++; }else if(sum<0){ l++; }else{ r--; } } } vector> v; for(auto i = s.begin(); i!=s.end(); i++){ v.push_back(*i); } return v; } }; // Second Better Approach : class Solution { public: vector> threeSum(vector& nums) { sort(nums.begin(), nums.end()); vector> res; for (unsigned int i=0; i0) && (nums[i]==nums[i-1])) continue; int l = i+1, r = nums.size()-1; while (l0) r--; else if (s<0) l++; else { res.push_back(vector {nums[i], nums[l], nums[r]}); while (l < r && nums[l]==nums[l+1]) l++; while (l < r && nums[r]==nums[r-1]) r--; l++; r--; } } } return res; } }; ================================================ FILE: 151. Reverse Words in a String.java ================================================ //151. Reverse Words in a String Leetcode class Solution { public String reverseWords(String s) { int len = s.length(); String k = "", a = ""; for (int i = len - 1; i >= 0; i--) { char currentChar = s.charAt(i); if (currentChar != ' ' && currentChar != '.' && currentChar != ',') { k = currentChar + k; } else { if (!k.isEmpty()) { a += (a.isEmpty() ? "" : " ") + k; k = ""; } } } if (!k.isEmpty()) { a += (a.isEmpty() ? "" : " ") + k; } return a; } } ================================================ FILE: 1519-number-of-nodes-in-the-sub-tree-with-the-same-label/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.java ================================================ class Solution { public int[] dfs(int node, int parent, Map> adj, char[] labels, int[] ans) { // Store count of all alphabets in the subtree of the node. int[] nodeCounts = new int[26]; nodeCounts[labels[node] - 'a'] = 1; if (!adj.containsKey(node)) return nodeCounts; for (int child : adj.get(node)) { if (child == parent) { continue; } int[] childCounts = dfs(child, node, adj, labels, ans); // Add frequencies of the child node in the parent node's frequency array. for (int i = 0; i < 26; i++) { nodeCounts[i] += childCounts[i]; } } ans[node] = nodeCounts[labels[node] - 'a']; return nodeCounts; } public int[] countSubTrees(int n, int[][] edges, String labels) { Map> adj = new HashMap<>(); for (int[] edge : edges) { int a = edge[0], b = edge[1]; adj.computeIfAbsent(a, value -> new ArrayList()).add(b); adj.computeIfAbsent(b, value -> new ArrayList()).add(a); } int[] ans = new int[n]; char[] label = labels.toCharArray(); dfs(0, -1, adj, label, ans); return ans; } } ================================================ FILE: 1519-number-of-nodes-in-the-sub-tree-with-the-same-label/NOTES.md ================================================ ​ ================================================ FILE: 1519-number-of-nodes-in-the-sub-tree-with-the-same-label/README.md ================================================

1519. Number of Nodes in the Sub-Tree With the Same Label

Medium


You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]).

The edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree.

Return an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i.

A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.

 

Example 1:

Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"
Output: [2,1,1,1,1,1,1]
Explanation: Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.
Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).

Example 2:

Input: n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"
Output: [4,2,1,1]
Explanation: The sub-tree of node 2 contains only node 2, so the answer is 1.
The sub-tree of node 3 contains only node 3, so the answer is 1.
The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.
The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.

Example 3:

Input: n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab"
Output: [3,2,1,1,1]

 

Constraints:

  • 1 <= n <= 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 <= ai, bi < n
  • ai != bi
  • labels.length == n
  • labels is consisting of only of lowercase English letters.
================================================ FILE: 1531-string-compression-ii/1531-string-compression-ii.java ================================================ /* We define the state dp[i][j]: The best solution for the first i chars in the string after at most j chars being removed; i.e., the minimum length after at most j chars being removed from s.substring(0, i). For each such substring, we can either delete or keep the last char, s[i - 1] - To delete, dp[i][j] = dp[i - 1][j - 1]. - To keep, we delete at most j chars in s.substring(0, i) that are different from the last character. - We then take the min value of them for dp[i][j] */ class Solution { public int getLengthOfOptimalCompression(String s, int k) { int n = s.length(); // dp[i][j]: the minimum length for the first i chars after at most j chars being removed. int[][] dp = new int[n + 1][k + 1]; // Initialize each cell of the dp 2-D array to n, the max value that each cell can have. This // is OK, as each dp[i][j] will have the min value bewteen dp[i][j] and its calculate value. // for (int[] i : dp) Arrays.fill(i, n); // this is a bit slower (100ms) for (int i = 0; i <= n; i++) { for (int j = 0; j <= k; j++) { dp[i][j] = n; } } // Minimum length of empty string after 0 removal is 0 dp[0][0] = 0; // iterate from 1 character substring to n-character substring for(int i = 1; i <= n; i++) { // We can delete at most i characters if i < k or k characters if i >= k. // Using "j <= k" alone here is OK but "j <= i && j <= k" speeds up a lot for(int j = 0; j <= i && j <= k; j++) { int count = 0; int del = 0; // delete the last character of the substring (j has to be greater than 1 to delete 1 character) if (j > 0) { dp[i][j] = dp[i - 1][j - 1]; } // Keep the last character of the substring, and starting from the end of the // substring, count the same characters as the last character, and remove characters // that are different. char lastChar = s.charAt(i - 1); for(int p = i; p >= 1; p--) { if (s.charAt(p - 1) == lastChar) { count++; } else { del++; // Bail out if no more removal is available if (del > j) { break; } } // After del number of removals from the end of substring we have "p - 1" characters left // in the substring and AT MOST "j - del" removals available dp[i][j] = Math.min(dp[i][j], dp[p - 1][j - del] + 1 + length(count)); } } } return dp[n][k]; } // Constraints is "1 <= s.length <= 100", then the max count is 100 when all 100 characters are the same // Note we don't add '1' after single characters. private int length(int count) { return count == 100 ? 3 : count >= 10 ? 2 : count > 1 ? 1 : 0; } } ================================================ FILE: 1531-string-compression-ii/NOTES.md ================================================ ​ ================================================ FILE: 1531-string-compression-ii/README.md ================================================

1531. String Compression II

Hard


Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3".

Notice that in this problem, we are not adding '1' after single characters.

Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.

Find the minimum length of the run-length encoded version of s after deleting at most k characters.

 

Example 1:

Input: s = "aaabcccd", k = 2
Output: 4
Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4.

Example 2:

Input: s = "aabbaa", k = 2
Output: 2
Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2.

Example 3:

Input: s = "aaaaaaaaaaa", k = 0
Output: 3
Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.

 

Constraints:

  • 1 <= s.length <= 100
  • 0 <= k <= s.length
  • s contains only lowercase English letters.
================================================ FILE: 1544-make-the-string-great/1544-make-the-string-great.java ================================================ class Solution { public String makeGood(String s) { Stack st=new Stack<>(); st.push(s.charAt(0)); for(int i=1;i1544. 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.
================================================ FILE: 1578-minimum-time-to-make-rope-colorful/1578-minimum-time-to-make-rope-colorful.java ================================================ class Solution { public int minCost(String colors, int[] neededTime) { int prev = 0; int res = 0; char arr[] = colors.toCharArray(); for (int i = 1; i < arr.length; i++) { if (arr[prev] != arr[i]) prev = i; else { if (neededTime[prev] < neededTime[i]) { res += neededTime[prev]; prev = i; } else { res += neededTime[i]; } } } return res; } } ================================================ FILE: 1578-minimum-time-to-make-rope-colorful/NOTES.md ================================================ ​ ================================================ FILE: 1578-minimum-time-to-make-rope-colorful/README.md ================================================

1578. Minimum Time to Make Rope Colorful

Medium


Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon.

Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope.

Return the minimum time Bob needs to make the rope colorful.

 

Example 1:

Input: colors = "abaac", neededTime = [1,2,3,4,5]
Output: 3
Explanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green.
Bob can remove the blue balloon at index 2. This takes 3 seconds.
There are no longer two consecutive balloons of the same color. Total time = 3.

Example 2:

Input: colors = "abc", neededTime = [1,2,3]
Output: 0
Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.

Example 3:

Input: colors = "aabaa", neededTime = [1,2,3,4,1]
Output: 2
Explanation: Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.
There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.

 

Constraints:

  • n == colors.length == neededTime.length
  • 1 <= n <= 105
  • 1 <= neededTime[i] <= 104
  • colors contains only lowercase English letters.
================================================ FILE: 1584-min-cost-to-connect-all-points/1584-min-cost-to-connect-all-points.java ================================================ class Solution { public int minCostConnectPoints(int[][] points) { int n = points.length; // Min-heap to store minimum weight edge at top. PriorityQueue> heap = new PriorityQueue<>((a, b) -> (a.getKey() - b.getKey()));; // Track nodes which are included in MST. boolean[] inMST = new boolean[n]; heap.add(new Pair(0, 0)); int mstCost = 0; int edgesUsed = 0; while (edgesUsed < n) { Pair topElement = heap.poll(); int weight = topElement.getKey(); int currNode = topElement.getValue(); // If node was already included in MST we will discard this edge. if (inMST[currNode]) { continue; } inMST[currNode] = true; mstCost += weight; edgesUsed++; for (int nextNode = 0; nextNode < n; ++nextNode) { // If next node is not in MST, then edge from curr node // to next node can be pushed in the priority queue. if (!inMST[nextNode]){ int nextWeight = Math.abs(points[currNode][0] - points[nextNode][0]) + Math.abs(points[currNode][1] - points[nextNode][1]); heap.add(new Pair(nextWeight, nextNode)); } } } return mstCost; } } ================================================ FILE: 1584-min-cost-to-connect-all-points/NOTES.md ================================================ ​ ================================================ FILE: 1584-min-cost-to-connect-all-points/README.md ================================================

1584. Min Cost to Connect All Points

Medium


You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].

The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.

Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.

 

Example 1:

Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Explanation: 

We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.

Example 2:

Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18

 

Constraints:

  • 1 <= points.length <= 1000
  • -106 <= xi, yi <= 106
  • All pairs (xi, yi) are distinct.
================================================ FILE: 16-3sum-closest/16-3sum-closest.java ================================================ class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int n = nums.length; int minDiff = Integer.MAX_VALUE; int result = Integer.MAX_VALUE; for(int i = 0; i < nums.length; i++) { int start = i + 1; int end = n - 1; while(start < end) { int sum = nums[i] + nums[start] + nums[end]; if(sum == target) { return sum; } int diff = Math.abs(target - sum); if(diff < minDiff) { minDiff = diff; result = sum; } if(sum > target) { end--; } else { start++; } } } return result; } } ================================================ FILE: 16-3sum-closest/NOTES.md ================================================ ​ ================================================ FILE: 16-3sum-closest/README.md ================================================

16. 3Sum Closest

Medium


Given an integer array nums of length n 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).

Example 2:

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

 

Constraints:

  • 3 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000
  • -104 <= target <= 104
================================================ FILE: 16. 3Sum Closest - leetcode/SolutionCode.cpp ================================================ class Solution { public: int threeSumClosest(vector& nums, int target) { sort(nums.begin(), nums.end()); int closestSum = nums[0] + nums[1] + nums[2], n = nums.size(); for(int i=0; i diff) closestSum = tmpSum; } } return closestSum; } }; ================================================ FILE: 160-intersection-of-two-linked-lists/160-intersection-of-two-linked-lists.java ================================================ public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode t1=headA; ListNode t2=headB; int n=0,m=0; while(t1!=null){ m++; t1=t1.next; } while(t2!=null){ n++; t2=t2.next; } t1=headA; t2=headB; int t=m-n; if(t>0){ m-=t; while(t>0){ t1=t1.next; t--; } }else{ t=-t; n-=t; while(t>0){ t2=t2.next; t--; } } while(n>0){ if(t1==t2) break; n--; t1=t1.next; t2=t2.next; } return t1; } } ================================================ FILE: 160-intersection-of-two-linked-lists/NOTES.md ================================================ ​ ================================================ FILE: 160-intersection-of-two-linked-lists/README.md ================================================

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?
================================================ FILE: 1631-path-with-minimum-effort/1631-path-with-minimum-effort.java ================================================ class Solution { public int minimumEffortPath(int[][] heights) { int[][] dirs = new int[][]{{-1,0},{1,0},{0,1},{0,-1}}; int numR = heights.length; int numC = heights[0].length; int[][] ans = new int[numR][numC]; for (int[] row : ans) { Arrays.fill(row,Integer.MAX_VALUE); } PriorityQueue queue = new PriorityQueue<>((a,b)->a[2]-b[2]); queue.offer(new int[]{0,0,0}); ans[0][0] = 0; while (!queue.isEmpty()) { int[] curr = queue.poll(); if (curr[0]==numR-1 && curr[1]==numC-1) return curr[2]; for (int i=0; i<4; i++) { int nextR = curr[0]+dirs[i][0]; int nextC = curr[1]+dirs[i][1]; if (nextR<0 || nextC<0 || nextR>=numR || nextC>=numC) continue; int diff = Math.abs(heights[nextR][nextC]-heights[curr[0]][curr[1]]); int max = Math.max(diff,curr[2]); if (max1631. Path With Minimum Effort

Medium


You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.

A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.

Return the minimum effort required to travel from the top-left cell to the bottom-right cell.

 

Example 1:

Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.

Example 2:

Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1
Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].

Example 3:

Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
Output: 0
Explanation: This route does not require any effort.

 

Constraints:

  • rows == heights.length
  • columns == heights[i].length
  • 1 <= rows, columns <= 100
  • 1 <= heights[i][j] <= 106
================================================ FILE: 1641-count-sorted-vowel-strings/1641-count-sorted-vowel-strings.java ================================================ class Solution { public int countVowelStrings(int n) { int[] countOfEach = new int[] { 1, 1, 1, 1, 1 }; for (int i = 0; i < n - 1; i++) { for (int j = 1; j < countOfEach.length; j++) { countOfEach[j] = countOfEach[j - 1] + countOfEach[j]; } } return sum(countOfEach); } private int sum(int[] arr) { int amount = 0; for (int num : arr) { amount += num; } return amount; } } ================================================ FILE: 1641-count-sorted-vowel-strings/NOTES.md ================================================ ​ ================================================ FILE: 1641-count-sorted-vowel-strings/README.md ================================================

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 
================================================ FILE: 1642-furthest-building-you-can-reach/1642-furthest-building-you-can-reach.java ================================================ class Solution { public int furthestBuilding(int[] h, int bricks, int l) { PriorityQueue pq=new PriorityQueue<>(); int n=h.length; for(int i=1;i0){ if(pq.size()0 && pq.peek()=br){ bricks-=br; }else{ return i-1; } } } } return n-1; } } ================================================ FILE: 1642-furthest-building-you-can-reach/NOTES.md ================================================ ​ ================================================ FILE: 1642-furthest-building-you-can-reach/README.md ================================================

1642. Furthest Building You Can Reach

Medium


You are given an integer array heights representing the heights of buildings, some bricks, and some ladders.

You start your journey from building 0 and move to the next building by possibly using bricks or ladders.

While moving from building i to building i+1 (0-indexed),

  • If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks.
  • If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks.

Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.

 

Example 1:

Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
Output: 4
Explanation: Starting at building 0, you can follow these steps:
- Go to building 1 without using ladders nor bricks since 4 >= 2.
- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.
- Go to building 3 without using ladders nor bricks since 7 >= 6.
- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.
It is impossible to go beyond building 4 because you do not have any more bricks or ladders.

Example 2:

Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
Output: 7

Example 3:

Input: heights = [14,3,19,3], bricks = 17, ladders = 0
Output: 3

 

Constraints:

  • 1 <= heights.length <= 105
  • 1 <= heights[i] <= 106
  • 0 <= bricks <= 109
  • 0 <= ladders <= heights.length
================================================ FILE: 1647-minimum-deletions-to-make-character-frequencies-unique/1647-minimum-deletions-to-make-character-frequencies-unique.java ================================================ class Solution { public int minDeletions(String s) { Set set = new HashSet<>(); int[] alpha = new int[26]; char[] arr =s.toCharArray(); for(char c:arr) { alpha[c-'a']++; } int count = 0; for(int i=0;i<26;i++) { if(alpha[i] != 0) { while(set.contains(alpha[i]) && alpha[i]>0) { alpha[i]--; count++; } set.add(alpha[i]); } } return count; } } ================================================ FILE: 1647-minimum-deletions-to-make-character-frequencies-unique/NOTES.md ================================================ ​ ================================================ FILE: 1647-minimum-deletions-to-make-character-frequencies-unique/README.md ================================================

1647. Minimum Deletions to Make Character Frequencies Unique

Medium


A string s is called good if there are no two different characters in s that have the same frequency.

Given a string s, return the minimum number of characters you need to delete to make s good.

The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1.

 

Example 1:

Input: s = "aab"
Output: 0
Explanation: s is already good.

Example 2:

Input: s = "aaabbbcc"
Output: 2
Explanation: You can delete two 'b's resulting in the good string "aaabcc".
Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".

Example 3:

Input: s = "ceabaacb"
Output: 2
Explanation: You can delete both 'c's resulting in the good string "eabaab".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).

 

Constraints:

  • 1 <= s.length <= 105
  • s contains only lowercase English letters.
================================================ FILE: 1657-determine-if-two-strings-are-close/1657-determine-if-two-strings-are-close.java ================================================ class Solution { public boolean closeStrings(String s1, String s2) { var freqs1 = new int[26]; for(var c1: s1.toCharArray()) { freqs1[c1 - 'a']++; } var freqs2 = new int[26]; for(var c2: s2.toCharArray()) { freqs2[c2 - 'a']++; } for(int i = 0; i < 26; i++) { if(freqs1[i] > 0 && freqs2[i] == 0) { return false; } if(freqs1[i] == 0 && freqs2[i] > 0) { return false; } } Arrays.sort(freqs1); Arrays.sort(freqs2); return Arrays.equals(freqs1, freqs2); } } ================================================ FILE: 1657-determine-if-two-strings-are-close/NOTES.md ================================================ ​ ================================================ FILE: 1657-determine-if-two-strings-are-close/README.md ================================================

1657. Determine if Two Strings Are Close

Medium


Two strings are considered close if you can attain one from the other using the following operations:

  • Operation 1: Swap any two existing characters.
    • For example, abcde -> aecdb
  • Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
    • For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)

You can use the operations on either string as many times as necessary.

Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.

 

Example 1:

Input: word1 = "abc", word2 = "bca"
Output: true
Explanation: You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc" -> "acb"
Apply Operation 1: "acb" -> "bca"

Example 2:

Input: word1 = "a", word2 = "aa"
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.

Example 3:

Input: word1 = "cabbba", word2 = "abbccc"
Output: true
Explanation: You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba" -> "caabbb"
Apply Operation 2: "caabbb" -> "baaccc"
Apply Operation 2: "baaccc" -> "abbccc"

 

Constraints:

  • 1 <= word1.length, word2.length <= 105
  • word1 and word2 contain only lowercase English letters.
================================================ FILE: 1658-minimum-operations-to-reduce-x-to-zero/1658-minimum-operations-to-reduce-x-to-zero.java ================================================ class Solution { public int minOperations(int[] nums, int x) { int k = 0; for(int i = 0; i < nums.length; ++i)k += nums[i]; k -= x; int globalMax = -1; int windowSum = 0; int left = 0; for (int i = 0; i < nums.length; i++) { windowSum += nums[i]; while (left <= i && windowSum > k) { windowSum -= nums[left]; ++left; } if(windowSum == k)globalMax = Math.max(globalMax, i - left + 1); } return globalMax==-1?-1:nums.length - globalMax; } } ================================================ FILE: 1658-minimum-operations-to-reduce-x-to-zero/NOTES.md ================================================ ​ ================================================ FILE: 1658-minimum-operations-to-reduce-x-to-zero/README.md ================================================

1658. Minimum Operations to Reduce X to Zero

Medium


You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.

Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1.

 

Example 1:

Input: nums = [1,1,4,2,3], x = 5
Output: 2
Explanation: The optimal solution is to remove the last two elements to reduce x to zero.

Example 2:

Input: nums = [5,6,7,8,9], x = 4
Output: -1

Example 3:

Input: nums = [3,2,20,1,1,3], x = 10
Output: 5
Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 104
  • 1 <= x <= 109
================================================ FILE: 1662-check-if-two-string-arrays-are-equivalent/1662-check-if-two-string-arrays-are-equivalent.java ================================================ class Solution { public boolean arrayStringsAreEqual(String[] word1, String[] word2) { StringBuilder s1 = new StringBuilder(); StringBuilder s2 = new StringBuilder(); for(int i = 0 ; i < Math.max(word1.length , word2.length) ; i++){ if(i < word1.length){ s1.append(word1[i]); } if(i1662. Check If Two String Arrays are Equivalent

Easy


Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.

A string is represented by an array if the array elements concatenated in order forms the string.

 

Example 1:

Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
Output: true
Explanation:
word1 represents string "ab" + "c" -> "abc"
word2 represents string "a" + "bc" -> "abc"
The strings are the same, so return true.

Example 2:

Input: word1 = ["a", "cb"], word2 = ["ab", "c"]
Output: false

Example 3:

Input: word1  = ["abc", "d", "defg"], word2 = ["abcddefg"]
Output: true

 

Constraints:

  • 1 <= word1.length, word2.length <= 103
  • 1 <= word1[i].length, word2[i].length <= 103
  • 1 <= sum(word1[i].length), sum(word2[i].length) <= 103
  • word1[i] and word2[i] consist of lowercase letters.
================================================ FILE: 1663-smallest-string-with-a-given-numeric-value/1663-smallest-string-with-a-given-numeric-value.java ================================================ class Solution { public String getSmallestString(int n, int k) { char ch[]=new char[n]; int i=0; while(i=k){ ch[i]='a'; i++; k--; }else{ break; } } i--; ch[i]=(char)(k%26+'a'); i++; while(i1663. Smallest String With A Given Numeric Value

Medium


The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.

The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8.

You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k.

Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.

 

Example 1:

Input: n = 3, k = 27
Output: "aay"
Explanation: The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.

Example 2:

Input: n = 5, k = 73
Output: "aaszz"

 

Constraints:

  • 1 <= n <= 105
  • n <= k <= 26 * n
================================================ FILE: 167-two-sum-ii-input-array-is-sorted/167-two-sum-ii-input-array-is-sorted.java ================================================ class Solution { public int[] twoSum(int[] numbers, int target) { int left = 0; int right = numbers.length - 1; boolean targetLocated = false; while (left < right && !targetLocated) { int mid = left + (right - left) / 2; int midVal = numbers[mid]; int curr = numbers[left] + numbers[right]; if(curr == target) { targetLocated = true; } else if (curr < target) { if (midVal + numbers[right] < target) { left = mid + 1; } else { left++; } } else { if (midVal + numbers[left] > target) { right = mid - 1; } else { right--; } } } int[] vals = new int[2]; vals[0] = left + 1; vals[1] = right + 1; return vals; } } ================================================ FILE: 167-two-sum-ii-input-array-is-sorted/NOTES.md ================================================ ​ ================================================ FILE: 167-two-sum-ii-input-array-is-sorted/README.md ================================================

167. Two Sum II - Input Array Is Sorted

Medium


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 <= index1 < index2 <= numbers.length.

Return the indices of the two numbers, index1 and index2, added by one 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.

Your solution must use only constant extra space.

 

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. We return [1, 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. We return [1, 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. We return [1, 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.
================================================ FILE: 1679-max-number-of-k-sum-pairs/1679-max-number-of-k-sum-pairs.java ================================================ class Solution { public int maxOperations(int[] nums, int k) { int ans=0; Arrays.sort(nums); int i=0; int j=nums.length-1; while(i using namespace std;; class Solution { public: // using bit manipulation TC: O(N), SC: O(1) int concatenatedBinary(int n) { int m = 1e9+7, l=0; // l is bit length to be shifted long res =0; for(int i =1; i<=n; i++){ if ((i & (i - 1)) == 0) l += 1; res = ((res << l) | i) % m; } return res; } }; ================================================ FILE: 1680-concatenation-of-consecutive-binary-numbers/1680-concatenation-of-consecutive-binary-numbers.java ================================================ class Solution { static String arr[] = new String[100001]; static int ans[] = new int[100001]; public void build() { for(int i=1; i<=100000; i++) { arr[i] = Integer.toBinaryString(i); } } int mod = 1000000007; public int getVal(int n) { int val = 0; for(int i=1; i<=n; i++) { for(int j=0; j1680. Concatenation of Consecutive Binary Numbers

Medium


Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7.

 

Example 1:

Input: n = 1
Output: 1
Explanation: "1" in binary corresponds to the decimal value 1. 

Example 2:

Input: n = 3
Output: 27
Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".
After concatenating them, we have "11011", which corresponds to the decimal value 27.

Example 3:

Input: n = 12
Output: 505379714
Explanation: The concatenation results in "1101110010111011110001001101010111100".
The decimal value of that is 118505380540.
After modulo 109 + 7, the result is 505379714.

 

Constraints:

  • 1 <= n <= 105
================================================ FILE: 1689-partitioning-into-minimum-number-of-deci-binary-numbers/1689-partitioning-into-minimum-number-of-deci-binary-numbers.java ================================================ class Solution { public int minPartitions(String n) { for(int i=9; i>=1; i--) { String ch = Integer.toString(i); if( n.contains(ch) )return i; } return 0; } } ================================================ FILE: 1689-partitioning-into-minimum-number-of-deci-binary-numbers/NOTES.md ================================================ ​ ================================================ FILE: 1689-partitioning-into-minimum-number-of-deci-binary-numbers/README.md ================================================

1689. Partitioning Into Minimum Number Of Deci-Binary Numbers

Medium


A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not.

Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n.

 

Example 1:

Input: n = "32"
Output: 3
Explanation: 10 + 11 + 11 = 32

Example 2:

Input: n = "82734"
Output: 8

Example 3:

Input: n = "27346209830709182346"
Output: 9

 

Constraints:

  • 1 <= n.length <= 105
  • n consists of only digits.
  • n does not contain any leading zeros and represents a positive integer.
================================================ FILE: 1695-maximum-erasure-value/1695-maximum-erasure-value.java ================================================ class Solution { public int maximumUniqueSubarray(int[] arr) { int res = 0; boolean[] check = new boolean[10001]; int l = 0; int r = 0; int temp=0; while(r1695. Maximum Erasure Value

Medium


You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.

Return the maximum score you can get by erasing exactly one subarray.

An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r).

 

Example 1:

Input: nums = [4,2,4,5,6]
Output: 17
Explanation: The optimal subarray here is [2,4,5,6].

Example 2:

Input: nums = [5,2,1,2,5,2,1,2,5]
Output: 8
Explanation: The optimal subarray here is [5,2,1] or [1,2,5].

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 104
================================================ FILE: 1696-jump-game-vi/1696-jump-game-vi.java ================================================ class Solution { public int maxResult(int[] nums, int k) { int n = nums.length; int result = 0; if(k > n) { k = n; } if(k < 1) { for(int i = 0; i < n; i++) { result += nums[i]; } return result; } int[] dp = new int[n]; dp[0] = nums[0]; for(int i = 1; i < n; i++) { dp[i] = Integer.MIN_VALUE; } int maxIndex = 0; for(int i = 1; i < n; i++) { if(maxIndex < i - k) { int max = Integer.MIN_VALUE; for(int j = maxIndex+1; j < n && j <= maxIndex+k; j++) { if(max <= dp[j]) { max = dp[j]; maxIndex = j; } } } dp[i] = Math.max(nums[i] + dp[maxIndex], dp[i]); if(dp[i] >= dp[maxIndex]) { maxIndex = i; } } return dp[n-1]; } } ================================================ FILE: 1696-jump-game-vi/NOTES.md ================================================ ​ ================================================ FILE: 1696-jump-game-vi/README.md ================================================

1696. Jump Game VI

Medium


You are given a 0-indexed integer array nums and an integer k.

You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive.

You want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array.

Return the maximum score you can get.

 

Example 1:

Input: nums = [1,-1,-2,4,-7,3], k = 2
Output: 7
Explanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.

Example 2:

Input: nums = [10,-5,-2,4,0,3], k = 3
Output: 17
Explanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.

Example 3:

Input: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2
Output: 0

 

Constraints:

  • 1 <= nums.length, k <= 105
  • -104 <= nums[i] <= 104
================================================ FILE: 17-letter-combinations-of-a-phone-number/17-letter-combinations-of-a-phone-number.java ================================================ class Solution { public static String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; public List letterCombinations(String digits) { List res = new ArrayList<>(); if(digits == null || digits.length() == 0){ return res; } dfs(digits, 0, new StringBuilder(), res); return res; } public void dfs(String digits, int index, StringBuilder sb, List res){ if(index == digits.length()){ res.add(sb.toString()); return; } String str = map[digits.charAt(index) - '0']; for(int i = 0; i < str.length(); i++){ sb.append(str.charAt(i)); dfs(digits, index + 1, sb, res); sb.deleteCharAt(sb.length() - 1); } } } ================================================ FILE: 17-letter-combinations-of-a-phone-number/NOTES.md ================================================ ​ ================================================ FILE: 17-letter-combinations-of-a-phone-number/README.md ================================================

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'].
================================================ FILE: 1704-determine-if-string-halves-are-alike/1704-determine-if-string-halves-are-alike.java ================================================ class Solution { public boolean halvesAreAlike(String s) { char[] ch=s.toCharArray(); int len=s.length(); int mid=len/2; int l=check(ch,0,mid-1); int r=check(ch,mid,len-1); if(l==r) { return true; } return false; } public int check(char[] ch,int start,int end){ int count=0; for(int i=start;i<=end;i++) { if(ch[i]=='a'||ch[i]=='e'||ch[i]=='i'||ch[i]=='o'||ch[i]=='u'||ch[i]=='A'||ch[i]=='E'||ch[i]=='I'||ch[i]=='O'||ch[i]=='U') { count++; } } return count; } } ================================================ FILE: 1704-determine-if-string-halves-are-alike/NOTES.md ================================================ ​ ================================================ FILE: 1704-determine-if-string-halves-are-alike/README.md ================================================

1704. Determine if String Halves Are Alike

Easy


You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.

Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.

Return true if a and b are alike. Otherwise, return false.

 

Example 1:

Input: s = "book"
Output: true
Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.

Example 2:

Input: s = "textbook"
Output: false
Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.

 

Constraints:

  • 2 <= s.length <= 1000
  • s.length is even.
  • s consists of uppercase and lowercase letters.
================================================ FILE: 1706-where-will-the-ball-fall/1706-where-will-the-ball-fall.java ================================================ class Solution { public int[] findBall(int[][] grid) { int result[] = new int[grid[0].length]; for (int i = 0; i < grid[0].length; i++) { result[i] = findBallDropColumn(0, i, grid); } return result; } public int findBallDropColumn(int row, int col, int[][] grid) { // base case; ball reached the last row if (row == grid.length) return col; int nextColumn = col + grid[row][col]; if (nextColumn < 0 || nextColumn > grid[0].length - 1 || grid[row][col] != grid[row][nextColumn]) { return -1; } return findBallDropColumn(row + 1, nextColumn, grid); } } ================================================ FILE: 1706-where-will-the-ball-fall/NOTES.md ================================================ ​ ================================================ FILE: 1706-where-will-the-ball-fall/README.md ================================================

1706. Where Will the Ball Fall

Medium


You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides.

Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.

  • A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1.
  • A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1.

We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a board redirects the ball into either wall of the box.

Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box.

 

Example 1:

Input: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]
Output: [1,-1,-1,-1,-1]
Explanation: This example is shown in the photo.
Ball b0 is dropped at column 0 and falls out of the box at column 1.
Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.
Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.
Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.
Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.

Example 2:

Input: grid = [[-1]]
Output: [-1]
Explanation: The ball gets stuck against the left wall.

Example 3:

Input: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]
Output: [0,1,2,3,4,-1]

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 100
  • grid[i][j] is 1 or -1.
================================================ FILE: 1710-maximum-units-on-a-truck/1710-maximum-units-on-a-truck.java ================================================ class Solution { public int maximumUnits(int[][] boxTypes, int truckSize) { int units = 0; int [] unitsVsBoxesCount = new int[1001];//value = number of boxes with i units per box for(int [] boxType : boxTypes) { //O(N) unitsVsBoxesCount[ boxType[1] ] += boxType[0]; } for(int i = 1000; i > 0; i--) { //O(1001) = O(1) if(unitsVsBoxesCount[i] > truckSize) { units += (truckSize * i); break; } else if (unitsVsBoxesCount[i] > 0) { units += (unitsVsBoxesCount[i] * i); truckSize -= unitsVsBoxesCount[i]; } } return units; } } ================================================ FILE: 1710-maximum-units-on-a-truck/NOTES.md ================================================ ​ ================================================ FILE: 1710-maximum-units-on-a-truck/README.md ================================================

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
================================================ FILE: 1721-swapping-nodes-in-a-linked-list/1721-swapping-nodes-in-a-linked-list.java ================================================ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode swapNodes(ListNode head, int k) { ListNode fast=head; ListNode slow=head; int count=1; while(fast !=null && count 1721. Swapping Nodes in a Linked List

Medium


You are given the head of a linked list, and an integer k.

Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

 

Example 1:

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

Example 2:

Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]

 

Constraints:

  • The number of nodes in the list is n.
  • 1 <= k <= n <= 105
  • 0 <= Node.val <= 100
================================================ FILE: 173-binary-search-tree-iterator/173-binary-search-tree-iterator.java ================================================ class BSTIterator { Deque stack = new ArrayDeque<>(); public BSTIterator(TreeNode root) { pushLeft(root); } public int next() { TreeNode node = stack.pollFirst(); pushLeft(node.right); return node.val; } public boolean hasNext() { return !stack.isEmpty(); } private void pushLeft(TreeNode root) { while (root != null) { stack.addFirst(root); root = root.left; } } } ================================================ FILE: 173-binary-search-tree-iterator/NOTES.md ================================================ ​ ================================================ FILE: 173-binary-search-tree-iterator/binary-search-tree-iterator.cpp ================================================ #include class BSTIterator { //I use Stack to store directed left children from root. // When next() be called, I just pop one element and process its right child as new root. stack stack; public: BSTIterator(TreeNode* root) { addElements(root); } int next() { TreeNode* temp = stack.top(); stack.pop(); addElements(temp->right); return temp->val; } bool hasNext() { return !stack.empty(); } private: void addElements(TreeNode* node){ for(;node != NULL; stack.push(node), node=node->left); } }; ================================================ FILE: 1742. Maximum Number of Balls in a Box(leetcode) ================================================ class Solution { public int countBalls(int lowLimit, int highLimit) { Mapmap=new HashMap<>(); int res=0; for(int i=lowLimit;i<=highLimit;i++){ int d=digitSum(i); map.put(d,map.getOrDefault(d,0)+1); res=Math.max(res,map.get(d)); }return res; } public int digitSum(int num){ int sum=0; while(num!=0){ sum=sum+(num%10); num=num/10; }return sum; } } ================================================ FILE: 1770 Maximum Score from Performing Multiplication Operations lc.cpp ================================================ #include using namespace std; class Solution { public: int m, n; int dfs(vector& nums, vector& mult, vector>& dp, int i, int j) { // i : *ptr at nums // j : *ptr at mult // if performed all oper, return 0 if (j == m) return 0; // memoizated before - return the value here if (dp[i][j] != INT_MIN) return dp[i][j]; return dp[i][j] = max( mult[j] * nums[i] + dfs(nums, mult, dp, i + 1, j + 1), mult[j] * nums[n - 1 - j + i] + dfs(nums, mult, dp, i, j + 1) ); } int maximumScore(vector& nums, vector& multipliers) { n = (int) nums.size(), m = (int) multipliers.size(); // init values that couldn't be reached. -1 will cause TLE. -2 would pass but it's not supposed to pass. vector> dp(m, vector(m, INT_MIN)); // or u can return dp[0][0] after running dfs return dfs(nums, multipliers, dp, 0, 0); } }; ================================================ FILE: 1770-maximum-score-from-performing-multiplication-operations/1770-maximum-score-from-performing-multiplication-operations.java ================================================ class Solution { public int maximumScore(int[] nums, int[] multipliers) { // For Right Pointer int n = nums.length; // Number of Operations int m = multipliers.length; int[][] dp = new int[m + 1][m + 1]; for (int op = m - 1; op >= 0; op--) { for (int left = op; left >= 0; left--) { dp[op][left] = Math.max(multipliers[op] * nums[left] + dp[op + 1][left + 1], multipliers[op] * nums[n - 1 - (op - left)] + dp[op + 1][left]); } } return dp[0][0]; } } ================================================ FILE: 1770-maximum-score-from-performing-multiplication-operations/NOTES.md ================================================ ​ ================================================ FILE: 1770-maximum-score-from-performing-multiplication-operations/README.md ================================================

1770. Maximum Score from Performing Multiplication Operations

Medium


You are given two integer arrays nums and multipliers of size n and m respectively, where n >= m. The arrays are 1-indexed.

You begin with a score of 0. You want to perform exactly m operations. On the ith operation (1-indexed), you will:

  • Choose one integer x from either the start or the end of the array nums.
  • Add multipliers[i] * x to your score.
  • Remove x from the array nums.

Return the maximum score after performing m operations.

 

Example 1:

Input: nums = [1,2,3], multipliers = [3,2,1]
Output: 14
Explanation: An optimal solution is as follows:
- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.
- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.
- Choose from the end, [1], adding 1 * 1 = 1 to the score.
The total score is 9 + 4 + 1 = 14.

Example 2:

Input: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]
Output: 102
Explanation: An optimal solution is as follows:
- Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.
- Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.
- Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.
- Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.
- Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. 
The total score is 50 + 15 - 9 + 4 + 42 = 102.

 

Constraints:

  • n == nums.length
  • m == multipliers.length
  • 1 <= m <= 103
  • m <= n <= 105
  • -1000 <= nums[i], multipliers[i] <= 1000
================================================ FILE: 179-Largest Number.java ================================================ // Heres the simple solution: // Runtime: 6ms // Memory: 42 MB // Faster than: 81.48% class Solution { public String largestNumber(int[] nums) { int n= nums.length; String [] s = new String[n]; for(int i = 0; i < n; i++) s[i] = ""+nums[i]; Arrays.sort(s, (a, b) -> (b+a).compareTo(a+b)); StringBuilder sb = new StringBuilder(); for(String str: s) sb.append(str); String result = sb+""; return result.startsWith("0")? "0" : result; } } ================================================ FILE: 1791. Find Center of Star Graph.java ================================================ class Solution { public int findCenter(int[][] edges) { int n=edges.length; List> adj=new ArrayList<>(); for(int i=0;i<=n+1;i++){ ArrayList list=new ArrayList<>(); adj.add(list); } for(int i=0;i1832. Check if the Sentence Is Pangram

Easy


A pangram is a sentence where every letter of the English alphabet appears at least once.

Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.

 

Example 1:

Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Explanation: sentence contains at least one of every letter of the English alphabet.

Example 2:

Input: sentence = "leetcode"
Output: false

 

Constraints:

  • 1 <= sentence.length <= 1000
  • sentence consists of lowercase English letters.
================================================ FILE: 1833-maximum-ice-cream-bars/1833-maximum-ice-cream-bars.java ================================================ class Solution { public int maxIceCream(int[] costs, int coins) { int maxCost = 0; for (int cost : costs) { if (cost > maxCost) { maxCost = cost; } } int[] numOfCosts = new int[maxCost + 1]; for (int cost : costs) { numOfCosts[cost]++; } int iceCreamBars = 0; for (int cost = 1; cost <= maxCost; cost++) { if (numOfCosts[cost] == 0) { continue; } if (coins < cost) { break; } int count = Math.min(numOfCosts[cost], coins / cost); coins -= count * cost; iceCreamBars += count; } return iceCreamBars; } } ================================================ FILE: 1833-maximum-ice-cream-bars/NOTES.md ================================================ ​ ================================================ FILE: 1833-maximum-ice-cream-bars/README.md ================================================

1833. Maximum Ice Cream Bars

Medium


It is a sweltering summer day, and a boy wants to buy some ice cream bars.

At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. 

Return the maximum number of ice cream bars the boy can buy with coins coins.

Note: The boy can buy the ice cream bars in any order.

 

Example 1:

Input: costs = [1,3,2,4,1], coins = 7
Output: 4
Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.

Example 2:

Input: costs = [10,6,8,7,7,8], coins = 5
Output: 0
Explanation: The boy cannot afford any of the ice cream bars.

Example 3:

Input: costs = [1,6,3,1,2,5], coins = 20
Output: 6
Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.

 

Constraints:

  • costs.length == n
  • 1 <= n <= 105
  • 1 <= costs[i] <= 105
  • 1 <= coins <= 108
================================================ FILE: 1834-single-threaded-cpu/1834-single-threaded-cpu.java ================================================ class Solution { public int[] getOrder(int[][] tasks) { // Sort based on min task processing time or min task index. // Store enqueue time, processing time, task index. PriorityQueue nextTask = new PriorityQueue((a, b) -> (a[1] != b[1] ? (a[1] - b[1]) : (a[2] - b[2]))); // Store task enqueue time, processing time, index. int sortedTasks[][] = new int[tasks.length][3]; for (int i = 0; i < tasks.length; ++i) { sortedTasks[i][0] = tasks[i][0]; sortedTasks[i][1] = tasks[i][1]; sortedTasks[i][2] = i; } Arrays.sort(sortedTasks, (a, b) -> Integer.compare(a[0], b[0])); int tasksProcessingOrder[] = new int[tasks.length]; long currTime = 0; int taskIndex = 0; int ansIndex = 0; // Stop when no tasks are left in array and heap. while (taskIndex < tasks.length || !nextTask.isEmpty()) { if (nextTask.isEmpty() && currTime < sortedTasks[taskIndex][0]) { // When the heap is empty, try updating currTime to next task's enqueue time. currTime = sortedTasks[taskIndex][0]; } // Push all the tasks whose enqueueTime <= currtTime into the heap. while (taskIndex < tasks.length && currTime >= sortedTasks[taskIndex][0]) { nextTask.add(sortedTasks[taskIndex]); ++taskIndex; } int processTime = nextTask.peek()[1]; int index = nextTask.peek()[2]; nextTask.remove(); // Complete this task and increment currTime. currTime += processTime; tasksProcessingOrder[ansIndex++] = index; } return tasksProcessingOrder; } } ================================================ FILE: 1834-single-threaded-cpu/NOTES.md ================================================ ​ ================================================ FILE: 1834-single-threaded-cpu/README.md ================================================

1834. Single-Threaded CPU

Medium


You are given n​​​​​​ tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the i​​​​​​th​​​​ task will be available to process at enqueueTimei and will take processingTimei to finish processing.

You have a single-threaded CPU that can process at most one task at a time and will act in the following way:

  • If the CPU is idle and there are no available tasks to process, the CPU remains idle.
  • If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
  • Once a task is started, the CPU will process the entire task without stopping.
  • The CPU can finish a task then start a new one instantly.

Return the order in which the CPU will process the tasks.

 

Example 1:

Input: tasks = [[1,2],[2,4],[3,2],[4,1]]
Output: [0,2,3,1]
Explanation: The events go as follows: 
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.

Example 2:

Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]
Output: [4,3,2,0,1]
Explanation: The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.

 

Constraints:

  • tasks.length == n
  • 1 <= n <= 105
  • 1 <= enqueueTimei, processingTimei <= 109
================================================ FILE: 188-best-time-to-buy-and-sell-stock-iv/188-best-time-to-buy-and-sell-stock-iv.java ================================================ class Solution { public int maxProfit(int k, int[] prices) { return DP(prices, k); } private int DP(int[] prices, int k) { int[] costs = new int[k+1]; int[] profits = new int[k+1]; //costs[0] = prices[0]; Arrays.fill(costs, Integer.MAX_VALUE); for (int currentPrice : prices) { for (int i = 0; i < k; i++) { costs[i+1] = Math.min(costs[i+1], currentPrice - profits[i]); profits[i+1] = Math.max(profits[i+1], currentPrice - costs[i+1]); } } return profits[k]; } } ================================================ FILE: 188-best-time-to-buy-and-sell-stock-iv/NOTES.md ================================================ ​ ================================================ FILE: 188-best-time-to-buy-and-sell-stock-iv/README.md ================================================

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
================================================ FILE: 188. Best Time to Buy and Sell Stock IV.cpp ================================================ class Solution { public: int maxProfit(int k, vector& prices) { if(k==0) return 0; // no transaction no profit vector> dp(k+1, vector(2)); // initialise // dp[k][0] - min cost that you need to spend on a stock // dp[k][1] - max profit that you can gain from a stock for(int i=0;i<=k;i++) dp[i][0] = INT_MAX; for(auto &price : prices){ for(int i=1;i<=k;i++){ // price - dp[i - 1][1] is how much you need to spend // i.e use the profit you earned from previous transaction to buy the stock // we want to minimize it dp[i][0] = min(dp[i][0], price - dp[i-1][1]); // price - dp[i][0] is how much you can achieve from previous min cost // we want to maximize it dp[i][1] = max(dp[i][1], price - dp[i][0]); } } // return max profit at most k transactions // or you can use `return dp.back()[1]; return dp[k][1]; } }; ================================================ FILE: 19-remove-nth-node-from-end-of-list/19-remove-nth-node-from-end-of-list.java ================================================ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head.next==null && n==1)return null; ListNode temp=head; int length=0; while(temp!=null){ length++; temp=temp.next; } if(length==n)return head.next; ListNode tem=head; for(int i=1;i19. 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?

================================================ FILE: 191-number-of-1-bits/191-number-of-1-bits.java ================================================ public class Solution { public int hammingWeight(int n) { int count = 0; while (n != 0) { n=n&(n-1); count++; } return count; } } ================================================ FILE: 191-number-of-1-bits/NOTES.md ================================================ ​ ================================================ FILE: 191-number-of-1-bits/README.md ================================================

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?
================================================ FILE: 1926-nearest-exit-from-entrance-in-maze/1926-nearest-exit-from-entrance-in-maze.java ================================================ class Solution { public int nearestExit(char[][] maze, int[] entrance) { int m = maze.length; int n = maze[0].length; Queue q = new LinkedList<>(); int ei = entrance[0]; int ej = entrance[1]; int[][] dvs = new int[][] { {1, 0}, {0, 1}, {-1, 0}, {0, -1} }; maze[ei][ej] = '+'; q.add(new int[] {ei, ej, 0}); while(!q.isEmpty()) { int[] val = q.poll(); for (int[] d: dvs) { int i1 = val[0] + d[0]; int j1 = val[1] + d[1]; if (i1 < 0 || j1 < 0 || i1 >= m || j1 >= n) { if (val[0] == ei && val[1] == ej) continue; return val[2]; } if (maze[i1][j1] == '.') { q.add(new int[] {i1, j1, val[2] + 1}); maze[i1][j1] = '+'; } } } return -1; } } ================================================ FILE: 1926-nearest-exit-from-entrance-in-maze/NOTES.md ================================================ ​ ================================================ FILE: 1926-nearest-exit-from-entrance-in-maze/README.md ================================================

1926. Nearest Exit from Entrance in Maze

Medium


You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.

In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.

Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.

 

Example 1:

Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
Output: 1
Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].
Initially, you are at the entrance cell [1,2].
- You can reach [1,0] by moving 2 steps left.
- You can reach [0,2] by moving 1 step up.
It is impossible to reach [2,3] from the entrance.
Thus, the nearest exit is [0,2], which is 1 step away.

Example 2:

Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
Output: 2
Explanation: There is 1 exit in this maze at [1,2].
[1,0] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell [1,0].
- You can reach [1,2] by moving 2 steps right.
Thus, the nearest exit is [1,2], which is 2 steps away.

Example 3:

Input: maze = [[".","+"]], entrance = [0,0]
Output: -1
Explanation: There are no exits in this maze.

 

Constraints:

  • maze.length == m
  • maze[i].length == n
  • 1 <= m, n <= 100
  • maze[i][j] is either '.' or '+'.
  • entrance.length == 2
  • 0 <= entrancerow < m
  • 0 <= entrancecol < n
  • entrance will always be an empty cell.
================================================ FILE: 1962-remove-stones-to-minimize-the-total/1962-remove-stones-to-minimize-the-total.java ================================================ public class Solution { public int minStoneSum(int[] piles, int k) { int sum = 0; int a[] = new int[10001]; for (int i : piles) { sum += i; a[i]++; } for (int i = 10000; i > 0 && k > 0; i--) { if (a[i] > 0) { int b = i / 2; sum -= Math.min(k, a[i]) * b; a[i - i / 2] += a[i]; k -= a[i]; } } return sum; } } ================================================ FILE: 1962-remove-stones-to-minimize-the-total/NOTES.md ================================================ ​ ================================================ FILE: 1962-remove-stones-to-minimize-the-total/README.md ================================================

1962. Remove Stones to Minimize the Total

Medium


You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times:

  • Choose any piles[i] and remove floor(piles[i] / 2) stones from it.

Notice that you can apply the operation on the same pile more than once.

Return the minimum possible total number of stones remaining after applying the k operations.

floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).

 

Example 1:

Input: piles = [5,4,9], k = 2
Output: 12
Explanation: Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are [5,4,5].
- Apply the operation on pile 0. The resulting piles are [3,4,5].
The total number of stones in [3,4,5] is 12.

Example 2:

Input: piles = [4,3,6,7], k = 3
Output: 12
Explanation: Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are [4,3,3,7].
- Apply the operation on pile 3. The resulting piles are [4,3,3,4].
- Apply the operation on pile 0. The resulting piles are [2,3,3,4].
The total number of stones in [2,3,3,4] is 12.

 

Constraints:

  • 1 <= piles.length <= 105
  • 1 <= piles[i] <= 104
  • 1 <= k <= 105
================================================ FILE: 1971-find-if-path-exists-in-graph/1971-find-if-path-exists-in-graph.java ================================================ class Solution { public boolean validPath(int n, int[][] edges, int start, int end) { boolean[] visited = new boolean[n]; visited[start] = true; boolean newVisited = true; while(!visited[end] && newVisited) { newVisited = false; for (int i = edges.length - 1; i > -1; i--) { if (visited[edges[i][0]]) { if (!visited[edges[i][1]]) { newVisited = visited[edges[i][1]] = true; } } else if (visited[edges[i][1]]){ newVisited = visited[edges[i][0]] = true; } } } return visited[end]; } } ================================================ FILE: 1971-find-if-path-exists-in-graph/README.md ================================================

1971. Find if Path Exists in Graph

Easy


There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.

You want to determine if there is a valid path that exists from vertex source to vertex destination.

Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.

 

Example 1:

Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2
Output: true
Explanation: There are two paths from vertex 0 to vertex 2:
- 0 → 1 → 2
- 0 → 2

Example 2:

Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
Output: false
Explanation: There is no path from vertex 0 to vertex 5.

 

Constraints:

  • 1 <= n <= 2 * 105
  • 0 <= edges.length <= 2 * 105
  • edges[i].length == 2
  • 0 <= ui, vi <= n - 1
  • ui != vi
  • 0 <= source, destination <= n - 1
  • There are no duplicate edges.
  • There are no self edges.
================================================ FILE: 199-binary-tree-right-side-view/199-binary-tree-right-side-view.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List rightSideView(TreeNode root) { List list=new ArrayList<>(); int level=0; rightView(root,list,level); return list; } void rightView(TreeNode root,List list,int level){ if(root==null)return; if(level==list.size()){ list.add(root.val); } rightView(root.right,list,level+1); rightView(root.left,list,level+1); } } ================================================ FILE: 199-binary-tree-right-side-view/NOTES.md ================================================ ​ ================================================ FILE: 199-binary-tree-right-side-view/README.md ================================================

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
================================================ FILE: 1991-find-the-middle-index-in-array/1991-find-the-middle-index-in-array.java ================================================ class Solution { public int findMiddleIndex(int[] nums) { int sum=0; for(int n:nums){ sum+=n; } int left=0; for(int i=0;i1991. Find the Middle Index in Array

Easy


Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).

A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].

If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0.

Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.

 

Example 1:

Input: nums = [2,3,-1,8,4]
Output: 3
Explanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4

Example 2:

Input: nums = [1,-1,4]
Output: 2
Explanation: The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0

Example 3:

Input: nums = [2,5]
Output: -1
Explanation: There is no valid middleIndex.

 

Constraints:

  • 1 <= nums.length <= 100
  • -1000 <= nums[i] <= 1000

 

Note: This question is the same as 724: https://leetcode.com/problems/find-pivot-index/

================================================ FILE: 1996-the-number-of-weak-characters-in-the-game/1996-the-number-of-weak-characters-in-the-game.cpp ================================================ #include using namespace std; class Solution{ public: // using hash_map + STL // approach /* rearrange order of attach in asc order count weak chars(those defense less than curr maxi defense) update maxidefense */ int numberOfWeakCharacters(vector>& properties){ int WC =0; // final res to be returned, WC = weak chars // return maxiDefense since 1 <= defense[i] <= 10^5, set inti value to x sinec x <1 int maxiDefense =0; // using hash_map to map the attack and defense with greater as a key compare map, greater> mp; for(auto x : properties) mp[x[0]].push_back(x[1]); // foreach attack for(auto x : mp){ // count num of weakchar and add it to WC, count_if() returns the number of elements in the given sequence for which the comparator function (third parameter) returns true. // STL iterator ==> x.second.begin() => __first, x.second.end() => __last, [&](int currDefense) => predicate WC+= count_if(x.second.begin(), x.second.end(), [&](int currDefense){ return currDefense < maxiDefense; }); // update maxidefense which is the maxi value of currdefense maxiDefense = max(maxiDefense, *max_element(x.second.begin(), x.second.end())); } return WC; } }; ================================================ FILE: 1996-the-number-of-weak-characters-in-the-game/1996-the-number-of-weak-characters-in-the-game.java ================================================ class Solution { public int numberOfWeakCharacters(int[][] prop) { /** Solution 1. here we sort the array in the increasing order of attack 1.1 if two attack has a same value then we sort the decreasing order of defense 2. compare the defense value and increasing answer count 2.1 chnage the defense value if it is greater */ //if attack same then decreasing order of defense else increasing order of attack Arrays.sort(prop,(a,b)-> a[0]==b[0]? b[1]-a[1] : a[0]-b[0]); int min=Integer.MIN_VALUE; int ans=0; for(int i=prop.length-1;i>=0;i--){ int[] arr=prop[i]; int att=arr[0]; int def=arr[1]; if(def= 0; i--) { maxDefense[i] = Math.max(maxDefense[i], maxDefense[i + 1]); } int weakCharacters = 0; for (int[] property : properties) { int attack = property[0]; int defense = property[1]; // If their is a greater defense for properties with greater attack if (defense < maxDefense[attack + 1]) { weakCharacters++; } } return weakCharacters; } } ================================================ FILE: 1996-the-number-of-weak-characters-in-the-game/NOTES.md ================================================ ​ ================================================ FILE: 1996-the-number-of-weak-characters-in-the-game/README.md ================================================

1996. The Number of Weak Characters in the Game

Medium


You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game.

A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei.

Return the number of weak characters.

 

Example 1:

Input: properties = [[5,5],[6,3],[3,6]]
Output: 0
Explanation: No character has strictly greater attack and defense than the other.

Example 2:

Input: properties = [[2,2],[3,3]]
Output: 1
Explanation: The first character is weak because the second character has a strictly greater attack and defense.

Example 3:

Input: properties = [[1,5],[10,4],[4,3]]
Output: 1
Explanation: The third character is weak because the second character has a strictly greater attack and defense.

 

Constraints:

  • 2 <= properties.length <= 105
  • properties[i].length == 2
  • 1 <= attacki, defensei <= 105
================================================ FILE: 200-number-of-islands/200-number-of-islands.java ================================================ class Solution { public int numIslands(char[][] grid) { int ans=0; int n=grid.length; int m=grid[0].length; for(int i=0;i= grid.length || j >= grid[i].length || grid[i][j] == '0') return; grid[i][j] = '0'; dfs(grid,i+1,j); dfs(grid,i-1,j); dfs(grid,i,j+1); dfs(grid,i,j-1); } } ================================================ FILE: 200-number-of-islands/NOTES.md ================================================ ​ ================================================ FILE: 200-number-of-islands/README.md ================================================

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'.
================================================ FILE: 2007 Find Original Array From Doubled Array lc.cpp ================================================ class Solution { public: vector findOriginalArray(vector& changed) { // hashmap approach // if the len of i/p is odd return {}, because double array must have even len if(changed.size() & 1) return {}; // count the freq of each number unordered_mapmp; for(auto x : changed) mp[x]++; vector res; // sort in asc sort(changed.begin(), changed.end()); // keep the unique elements only in changed changed.erase(unique(changed.begin(), changed.end()), changed.end()); // so that we can iterate from smallest to largest for(auto x : changed){ // if the numb of x is greater than mp[x*2], there'd be some mp[x] left therefore return {} here as a changed isn't a double array if(mp[x] >mp[x*2]) return {}; for(int i =0; i q=new LinkedList<>(); Arrays.sort(c); int i=0; int j=0; int[] ans=new int[n/2]; while(i0 && q.peek()==num){ ans[j++]=q.poll()/2; }else{ q.add(2*num); } i++; } return q.size()>0?new int[]{}:ans; } } //without sorting class Solution { public int[] findOriginalArray(int[] changed) { if(changed.length%2 != 0) return new int[0]; int max = Integer.MIN_VALUE; for(int num : changed) max = Math.max(max, num); if(max%2 != 0) return new int[0]; int[] cnts = new int[max+1]; for(int num : changed) cnts[num]++; int[] res = new int[changed.length/2]; if(cnts[0] % 2 != 0) return new int[0]; int idx = cnts[0]/2; for(int i = 1; i < cnts.length; i++) { if(cnts[i] == 0) continue; if(2*i > max || cnts[i] > cnts[2*i]) return new int[0]; int cnt = cnts[i]; cnts[2*i] -= cnt; while(cnt-- > 0) res[idx++] = i; } return res; } }class Solution { public int[] findOriginalArray(int[] changed) { if(changed.length%2 != 0) return new int[0]; int max = Integer.MIN_VALUE; for(int num : changed) max = Math.max(max, num); if(max%2 != 0) return new int[0]; int[] cnts = new int[max+1]; for(int num : changed) cnts[num]++; int[] res = new int[changed.length/2]; if(cnts[0] % 2 != 0) return new int[0]; int idx = cnts[0]/2; for(int i = 1; i < cnts.length; i++) { if(cnts[i] == 0) continue; if(2*i > max || cnts[i] > cnts[2*i]) return new int[0]; int cnt = cnts[i]; cnts[2*i] -= cnt; while(cnt-- > 0) res[idx++] = i; } return res; } } ================================================ FILE: 2007-find-original-array-from-doubled-array/NOTES.md ================================================ ​ ================================================ FILE: 2007-find-original-array-from-doubled-array/README.md ================================================

2007. Find Original Array From Doubled Array

Medium


An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array.

Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order.

 

Example 1:

Input: changed = [1,3,4,2,6,8]
Output: [1,3,4]
Explanation: One possible original array could be [1,3,4]:
- Twice the value of 1 is 1 * 2 = 2.
- Twice the value of 3 is 3 * 2 = 6.
- Twice the value of 4 is 4 * 2 = 8.
Other original arrays could be [4,3,1] or [3,1,4].

Example 2:

Input: changed = [6,3,0,1]
Output: []
Explanation: changed is not a doubled array.

Example 3:

Input: changed = [1]
Output: []
Explanation: changed is not a doubled array.

 

Constraints:

  • 1 <= changed.length <= 105
  • 0 <= changed[i] <= 105
================================================ FILE: 2095-delete-the-middle-node-of-a-linked-list/2095-delete-the-middle-node-of-a-linked-list.java ================================================ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode deleteMiddle(ListNode head) { if(head.next==null)return null; ListNode prev=null; ListNode slow=head; ListNode fast=head; while(fast!=null && fast.next!=null){ prev=slow; slow=slow.next; fast=fast.next.next; } prev.next=slow.next; return head; } } ================================================ FILE: 2095-delete-the-middle-node-of-a-linked-list/NOTES.md ================================================ ​ ================================================ FILE: 2131-longest-palindrome-by-concatenating-two-letter-words/2131-longest-palindrome-by-concatenating-two-letter-words.java ================================================ class Solution { public int longestPalindrome(String[] words) { int result=0; int[][]freq=new int[26][26]; for(String s:words){ int i=s.charAt(0)-'a'; int j=s.charAt(1)-'a'; if(freq[j][i]>0){ freq[j][i]--; result+=4; }else{ freq[i][j]++; } } for(int i=0;i<26;i++){ if(freq[i][i]>0){ result+=2; break; } } return result; } } ================================================ FILE: 2131-longest-palindrome-by-concatenating-two-letter-words/README.md ================================================

2131. Longest Palindrome by Concatenating Two Letter Words

Medium


You are given an array of strings words. Each element of words consists of two lowercase English letters.

Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.

Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0.

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

 

Example 1:

Input: words = ["lc","cl","gg"]
Output: 6
Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6.
Note that "clgglc" is another longest palindrome that can be created.

Example 2:

Input: words = ["ab","ty","yt","lc","cl","ab"]
Output: 8
Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8.
Note that "lcyttycl" is another longest palindrome that can be created.

Example 3:

Input: words = ["cc","ll","xx"]
Output: 2
Explanation: One longest palindrome is "cc", of length 2.
Note that "ll" is another longest palindrome that can be created, and so is "xx".

 

Constraints:

  • 1 <= words.length <= 105
  • words[i].length == 2
  • words[i] consists of lowercase English letters.
================================================ FILE: 2136-earliest-possible-day-of-full-bloom/2136-earliest-possible-day-of-full-bloom.java ================================================ class Solution { class Pair{ int plantTime; int growTime; Pair(int a,int b){ plantTime=a; growTime=b; } } public int earliestFullBloom(int[] plantTime, int[] growTime) { PriorityQueue pq=new PriorityQueue<>((a,b)->b.growTime-a.growTime); for(int i=0;i> combinationSum3(int k, int n) { List> res = new ArrayList<>(); List out = new ArrayList<>(); back(res,out,k,n,1); return res; } void back(List> res,List out,int currSize,int n,int limit) { if(out.size()==currSize && n ==0) { res.add(new ArrayList<>(out)); return ; } if(limit>9) { return ; } if(out.size()>currSize) { return ; } if(n<0) { return ; } out.add(limit); back(res,out,currSize,n-limit,limit+1); out.remove(out.size()-1); back(res,out,currSize,n,limit+1); } } ================================================ FILE: 216-combination-sum-iii/NOTES.md ================================================ ​ ================================================ FILE: 216-combination-sum-iii/README.md ================================================

216. Combination Sum III

Medium


Find all valid combinations of k numbers that sum up to n such that the following conditions are true:

  • Only numbers 1 through 9 are used.
  • Each number is used at most once.

Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.

 

Example 1:

Input: k = 3, n = 7
Output: [[1,2,4]]
Explanation:
1 + 2 + 4 = 7
There are no other valid combinations.

Example 2:

Input: k = 3, n = 9
Output: [[1,2,6],[1,3,5],[2,3,4]]
Explanation:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
There are no other valid combinations.

Example 3:

Input: k = 4, n = 1
Output: []
Explanation: There are no valid combinations.
Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.

 

Constraints:

  • 2 <= k <= 9
  • 1 <= n <= 60
================================================ FILE: 218-the-skyline-problem/218-the-skyline-problem.java ================================================ class Solution { class KeyPoint { public int key; public int height; public KeyPoint next = null; public KeyPoint(int key, int height) { this.key = key; this.height = height; } } public List> getSkyline(int[][] buildings) { List> res = new ArrayList<>(); KeyPoint dummy = new KeyPoint(-1, 0); // dummy head KeyPoint pre = dummy; for (int[] bd : buildings) { int L = bd[0]; int R = bd[1]; int H = bd[2]; while (pre.next != null && pre.next.key <= L) pre = pre.next; int preH = pre.height; if (pre.key == L) pre.height = Math.max(pre.height, H); else if (pre.height < H) { KeyPoint next = pre.next; pre.next = new KeyPoint(L, H); pre = pre.next; pre.next = next; } KeyPoint preIter = pre; KeyPoint curIter = pre.next; while (curIter != null && curIter.key < R) { preH = curIter.height; curIter.height = Math.max(curIter.height, H); if (curIter.height == preIter.height) preIter.next = curIter.next; else preIter = curIter; curIter = curIter.next; } if (preIter.height != preH && preIter.key != R && (curIter == null || curIter.key != R)) { KeyPoint next = preIter.next; preIter.next = new KeyPoint(R, preH); preIter.next.next = next; } } KeyPoint first = dummy; KeyPoint second = dummy.next; while (second != null) { if (second.height != first.height) res.add(Arrays.asList(second.key, second.height)); first = first.next; second = second.next; } return res; } } ================================================ FILE: 218-the-skyline-problem/NOTES.md ================================================ ​ ================================================ FILE: 218-the-skyline-problem/README.md ================================================

218. The Skyline Problem

Hard


A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.

The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]:

  • lefti is the x coordinate of the left edge of the ith building.
  • righti is the x coordinate of the right edge of the ith building.
  • heighti is the height of the ith building.

You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.

Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...]

 

Example 1:

Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
Explanation:
Figure A shows the buildings of the input.
Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.

Example 2:

Input: buildings = [[0,2,3],[2,5,3]]
Output: [[0,3],[5,0]]

 

Constraints:

  • 1 <= buildings.length <= 104
  • 0 <= lefti < righti <= 231 - 1
  • 1 <= heighti <= 231 - 1
  • buildings is sorted by lefti in non-decreasing order.
================================================ FILE: 2225-find-players-with-zero-or-one-losses/2225-find-players-with-zero-or-one-losses.java ================================================ class Solution { public List> findWinners(int[][] matches) { Map p=new HashMap<>(); int n=matches.length; int maxEle=0; for(int[] match:matches){ p.putIfAbsent(match[0],0); p.putIfAbsent(match[1],0); p.put(match[1],p.get(match[1])+1); maxEle=Math.max(maxEle,Math.max(match[0],match[1])); } List zeroes=new ArrayList<>(); List ones=new ArrayList<>(); for(int i=1;i<=maxEle;i++){ if(!p.containsKey(i))continue; if(p.get(i)==0){ zeroes.add(i); }else if(p.get(i)==1){ ones.add(i); } } List> ans=new ArrayList<>(); ans.add(zeroes); ans.add(ones); return ans; } } ================================================ FILE: 2225-find-players-with-zero-or-one-losses/NOTES.md ================================================ ​ ================================================ FILE: 2225-find-players-with-zero-or-one-losses/README.md ================================================

2225. Find Players With Zero or One Losses

Medium


You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match.

Return a list answer of size 2 where:

  • answer[0] is a list of all players that have not lost any matches.
  • answer[1] is a list of all players that have lost exactly one match.

The values in the two lists should be returned in increasing order.

Note:

  • You should only consider the players that have played at least one match.
  • The testcases will be generated such that no two matches will have the same outcome.

 

Example 1:

Input: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]
Output: [[1,2,10],[4,5,7,8]]
Explanation:
Players 1, 2, and 10 have not lost any matches.
Players 4, 5, 7, and 8 each have lost one match.
Players 3, 6, and 9 each have lost two matches.
Thus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].

Example 2:

Input: matches = [[2,3],[1,3],[5,4],[6,4]]
Output: [[1,2,5,6],[]]
Explanation:
Players 1, 2, 5, and 6 have not lost any matches.
Players 3 and 4 each have lost two matches.
Thus, answer[0] = [1,2,5,6] and answer[1] = [].

 

Constraints:

  • 1 <= matches.length <= 105
  • matches[i].length == 2
  • 1 <= winneri, loseri <= 105
  • winneri != loseri
  • All matches[i] are unique.
================================================ FILE: 2244-minimum-rounds-to-complete-all-tasks/2244-minimum-rounds-to-complete-all-tasks.java ================================================ class Solution { public int minimumRounds(int[] tasks) { Map freq = new HashMap(); // Store the frequencies in the map. for (int task : tasks) { freq.put(task, freq.getOrDefault(task, 0) + 1); } int minimumRounds = 0; // Iterate over the task's frequencies. for (int count : freq.values()) { // If the frequency is 1, it's not possible to complete tasks. if (count == 1) { return - 1; } if (count % 3 == 0) { // Group all the task in triplets. minimumRounds += count / 3; } else { // If count % 3 = 1; (count / 3 - 1) groups of triplets and 2 pairs. // If count % 3 = 2; (count / 3) groups of triplets and 1 pair. minimumRounds += count / 3 + 1; } } return minimumRounds; } } ================================================ FILE: 2244-minimum-rounds-to-complete-all-tasks/NOTES.md ================================================ ​ ================================================ FILE: 2244-minimum-rounds-to-complete-all-tasks/README.md ================================================

2244. Minimum Rounds to Complete All Tasks

Medium


You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.

Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.

 

Example 1:

Input: tasks = [2,2,3,3,2,4,4,4,4,4]
Output: 4
Explanation: To complete all the tasks, a possible plan is:
- In the first round, you complete 3 tasks of difficulty level 2. 
- In the second round, you complete 2 tasks of difficulty level 3. 
- In the third round, you complete 3 tasks of difficulty level 4. 
- In the fourth round, you complete 2 tasks of difficulty level 4.  
It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.

Example 2:

Input: tasks = [2,3,3]
Output: -1
Explanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.

 

Constraints:

  • 1 <= tasks.length <= 105
  • 1 <= tasks[i] <= 109
================================================ FILE: 2246-longest-path-with-different-adjacent-characters/2246-longest-path-with-different-adjacent-characters.java ================================================ class Solution { private int longestPath = 1; public int dfs(int currentNode, Map> children, String s) { // If the node is the only child, return 1 for the currentNode itself. if (!children.containsKey(currentNode)) { return 1; } // Longest and second longest path starting from currentNode (does not count the // currentNode itself). int longestChain = 0, secondLongestChain = 0; for (int child : children.get(currentNode)) { // Get the number of nodes in the longest chain starting from the child, // including the child. int longestChainStartingFromChild = dfs(child, children, s); // We won't move to the child if it has the same character as the currentNode. if (s.charAt(currentNode) == s.charAt(child)) { continue; } // Modify the longestChain and secondLongestChain if longestChainStartingFromChild // is bigger. if (longestChainStartingFromChild > longestChain) { secondLongestChain = longestChain; longestChain = longestChainStartingFromChild; } else if (longestChainStartingFromChild > secondLongestChain) { secondLongestChain = longestChainStartingFromChild; } } // Add "1" for the node itself. longestPath = Math.max(longestPath, longestChain + secondLongestChain + 1); return longestChain + 1; } public int longestPath(int[] parent, String s) { int n = parent.length; Map> children = new HashMap<>(); // Start from node 1, since root node 0 does not have a parent. for (int i = 1; i < n; i++) { children.computeIfAbsent(parent[i], value -> new ArrayList()).add(i); } dfs(0, children, s); return longestPath; } } ================================================ FILE: 2246-longest-path-with-different-adjacent-characters/NOTES.md ================================================ ​ ================================================ FILE: 2246-longest-path-with-different-adjacent-characters/README.md ================================================

2246. Longest Path With Different Adjacent Characters

Hard


You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.

You are also given a string s of length n, where s[i] is the character assigned to node i.

Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.

 

Example 1:

Input: parent = [-1,0,0,1,1,2], s = "abacbe"
Output: 3
Explanation: The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned.
It can be proven that there is no longer path that satisfies the conditions. 

Example 2:

Input: parent = [-1,0,0,0], s = "aabc"
Output: 3
Explanation: The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.

 

Constraints:

  • n == parent.length == s.length
  • 1 <= n <= 105
  • 0 <= parent[i] <= n - 1 for all i >= 1
  • parent[0] == -1
  • parent represents a valid tree.
  • s consists of only lowercase English letters.
================================================ FILE: 225-implement-stack-using-queues/225-implement-stack-using-queues.java ================================================ class MyStack { Queue q1,q2; boolean fis; public MyStack() { q1=new LinkedList<>(); q2=new LinkedList<>(); fis=true; } public void push(int x) { if(fis){ q1.add(x); }else{ q2.add(x); } } public int pop() { if(fis){ fis=false; while(q1.size()>1){ q2.add(q1.remove()); } int ele=q1.remove(); return ele; }else{ fis=true; while(q2.size()>1){ q1.add(q2.remove()); } int ele=q2.remove(); return ele; } } public int top() { if(fis){ fis=false; while(q1.size()>1){ q2.add(q1.remove()); } int ele=q1.peek(); q2.add(q1.remove()); return ele; }else{ fis=true; while(q2.size()>1){ q1.add(q2.remove()); } int ele=q2.peek(); q1.add(q2.remove()); return ele; } } public boolean empty() { return q1.isEmpty() && q2.isEmpty(); } } /** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * boolean param_4 = obj.empty(); */ ================================================ FILE: 225-implement-stack-using-queues/NOTES.md ================================================ ​ ================================================ FILE: 2256-minimum-average-difference/2256-minimum-average-difference.java ================================================ class Solution { public int minimumAverageDifference(int[] nums) { int n=nums.length; long left=0; long right=0; long minDiff=Integer.MAX_VALUE; int idx=-1; for(int i:nums)right+=i; for(int i=0;i2256. Minimum Average Difference

Medium


You are given a 0-indexed integer array nums of length n.

The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.

Return the index with the minimum average difference. If there are multiple such indices, return the smallest one.

Note:

  • The absolute difference of two numbers is the absolute value of their difference.
  • The average of n elements is the sum of the n elements divided (integer division) by n.
  • The average of 0 elements is considered to be 0.

 

Example 1:

Input: nums = [2,5,3,9,5,3]
Output: 3
Explanation:
- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.
- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.
- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.
- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.
- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.
- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.
The average difference of index 3 is the minimum average difference so return 3.

Example 2:

Input: nums = [0]
Output: 0
Explanation:
The only index is 0 so return 0.
The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.

 

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 105
================================================ FILE: 2279-maximum-bags-with-full-capacity-of-rocks/2279-maximum-bags-with-full-capacity-of-rocks.java ================================================ class Solution { public int maximumBags(int[] capacity, int[] rocks, int x) { int n=rocks.length; int[]diff=new int[n]; for(int i=0;i0){ if(i=diff[i]){ x-=diff[i]; i++; }else{ break; } } return i; } } ================================================ FILE: 2279-maximum-bags-with-full-capacity-of-rocks/NOTES.md ================================================ ​ ================================================ FILE: 2279-maximum-bags-with-full-capacity-of-rocks/README.md ================================================

2279. Maximum Bags With Full Capacity of Rocks

Medium


You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity and rocks. The ith bag can hold a maximum of capacity[i] rocks and currently contains rocks[i] rocks. You are also given an integer additionalRocks, the number of additional rocks you can place in any of the bags.

Return the maximum number of bags that could have full capacity after placing the additional rocks in some bags.

 

Example 1:

Input: capacity = [2,3,4,5], rocks = [1,2,4,4], additionalRocks = 2
Output: 3
Explanation:
Place 1 rock in bag 0 and 1 rock in bag 1.
The number of rocks in each bag are now [2,3,4,4].
Bags 0, 1, and 2 have full capacity.
There are 3 bags at full capacity, so we return 3.
It can be shown that it is not possible to have more than 3 bags at full capacity.
Note that there may be other ways of placing the rocks that result in an answer of 3.

Example 2:

Input: capacity = [10,2,2], rocks = [2,2,0], additionalRocks = 100
Output: 3
Explanation:
Place 8 rocks in bag 0 and 2 rocks in bag 2.
The number of rocks in each bag are now [10,2,2].
Bags 0, 1, and 2 have full capacity.
There are 3 bags at full capacity, so we return 3.
It can be shown that it is not possible to have more than 3 bags at full capacity.
Note that we did not use all of the additional rocks.

 

Constraints:

  • n == capacity.length == rocks.length
  • 1 <= n <= 5 * 104
  • 1 <= capacity[i] <= 109
  • 0 <= rocks[i] <= capacity[i]
  • 1 <= additionalRocks <= 109
================================================ FILE: 23-Merge-k-Sorted-Lists/23-Merge-k-Sorted-Lists.cpp ================================================ class Solution { public: ListNode* mergeKLists(vector& lists) { //pushing all list values into min heap priority_queue, greater > mh; for(auto head : lists){ while(head){ mh.push(head -> val); head = head -> next; } } //if there is no element in lists if(mh.size() == 0) return NULL; //creating head node of resultant list ListNode * head = new ListNode(mh.top()); mh.pop(); //we will traverse the head so storing it for returning ListNode * ans_head = head; //creating final list and poping the min heap int n = mh.size(); while(n--){ head -> next = new ListNode(mh.top()); mh.pop(); head = head -> next; } return ans_head; } }; ================================================ FILE: 23-Merge-k-Sorted-Lists/NOTES.md ================================================ ================================================ FILE: 23-Merge-k-Sorted-Lists/README.md ================================================

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` will not exceed `10^4^`. ================================================ FILE: 230-kth-smallest-element-in-a-bst/230-kth-smallest-element-in-a-bst.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { int count=0; int ans=-1; public int kthSmallest(TreeNode root, int k) { dfs(root,k); return ans; } public void dfs(TreeNode root,int k){ if(root==null)return; dfs(root.left,k); count++; if(count==k){ ans=root.val; return; } dfs(root.right,k); return; } } ================================================ FILE: 230-kth-smallest-element-in-a-bst/NOTES.md ================================================ ​ ================================================ FILE: 234-palindrome-linked-list/234-palindrome-linked-list.java ================================================ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public boolean isPalindrome(ListNode head) { ListNode node=head; int sz=0; while(node!=null){ node=node.next; sz++; } if(sz==1)return true; ListNode curr=head; ListNode prev=null; for(int i=0;i bool: if head is None: return True slow = head fast = head while fast.next is not None and fast.next.next is not None: slow = slow.next fast = fast.next.next mid = slow.next slow.next = None prev = None while mid is not None: temp = mid.next mid.next = prev prev = mid mid = temp while prev is not None and head is not None: if prev.val != head.val: return False prev = prev.next head = head.next return True ================================================ FILE: 234-palindrome-linked-list/NOTES.md ================================================ ​ ================================================ FILE: 234-palindrome-linked-list/README.md ================================================

234. 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?
================================================ FILE: 234-palindrome-linked-list/palindrome-linked-list.cpp ================================================ class Solution { public: bool isPalindrome(ListNode* head) { ListNode* slow = head, *fast = head; while(fast and fast->next){ slow=slow->next; fast=fast->next->next; } // reverse half of linkedlist ListNode* nextNode, *prev = NULL; while(slow){ nextNode = slow->next; slow->next = prev; prev = slow; slow = nextNode; } while(prev){ if(prev->val != head->val) return false; prev = prev->next; head = head->next; } return true; } }; ================================================ FILE: 234. Palindrome Linked List/SolutionCode.cpp ================================================ /* Approach : 1. Find mid point of linked list.Divide the LL into two respective LL's. 2. Now reverse either one of the LL. 3. Traverse both LL's simulatenously and if at any instant their data doesn't match -> return false; */ class Solution { public: ListNode* reverseNode(ListNode* head){ if(!head) return head; ListNode* nx = head->next, *prev = NULL, *curr = head; while(curr){ nx = curr->next; curr->next = prev; prev = curr; curr = nx; } return prev; } bool isPalindrome(ListNode* head) { if(!head) return true; ListNode *slow = head, *fast = head->next; while(fast && fast->next){ slow = slow->next; fast = fast->next; if(fast){ fast = fast->next; } } ListNode* tmp = slow->next; slow->next = NULL; ListNode* rev = reverseNode(tmp); while(rev && head){ if(rev->val != head->val) return false; rev = rev->next; head = head->next; } return true; } }; ================================================ FILE: 235-lowest-common-ancestor-of-a-binary-search-tree/235-lowest-common-ancestor-of-a-binary-search-tree.java ================================================ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(p.valroot.val && q.val>root.val) return lowestCommonAncestor(root.right,p,q); else return root; } } ================================================ FILE: 235-lowest-common-ancestor-of-a-binary-search-tree/235-lowest-common-ancestor-of-a-binary-search-tree.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': # Using Recursion if (root == p or root == q or not root): return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p , q) if left and right : return root #Found common ancestor elif left: return left elif right: return right ================================================ FILE: 235-lowest-common-ancestor-of-a-binary-search-tree/NOTES.md ================================================ ​ ================================================ FILE: 235-lowest-common-ancestor-of-a-binary-search-tree/README.md ================================================

235. Lowest Common Ancestor of a Binary Search Tree

Easy


Given a binary search tree (BST), find the lowest common ancestor (LCA) node 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.
================================================ FILE: 2359-find-closest-node-to-given-two-nodes/NOTES.md ================================================ ​ ================================================ FILE: 2359-find-closest-node-to-given-two-nodes/README.md ================================================

2359. Find Closest Node to Given Two Nodes

Medium


You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.

The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from i, then edges[i] == -1.

You are also given two integers node1 and node2.

Return the index of the node that can be reached from both node1 and node2, such that the maximum between the distance from node1 to that node, and from node2 to that node is minimized. If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1.

Note that edges may contain cycles.

 

Example 1:

Input: edges = [2,2,3,-1], node1 = 0, node2 = 1
Output: 2
Explanation: The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1.
The maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2.

Example 2:

Input: edges = [1,2,-1], node1 = 0, node2 = 2
Output: 2
Explanation: The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0.
The maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2.

 

Constraints:

  • n == edges.length
  • 2 <= n <= 105
  • -1 <= edges[i] < n
  • edges[i] != i
  • 0 <= node1, node2 < n
================================================ FILE: 236-lowest-common-ancestor-of-a-binary-tree/236-lowest-common-ancestor-of-a-binary-tree.java ================================================ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null) return root; return left != null ? left : right; } } ================================================ FILE: 236-lowest-common-ancestor-of-a-binary-tree/NOTES.md ================================================ ​ ================================================ FILE: 237-delete-node-in-a-linked-list/237-delete-node-in-a-linked-list.java ================================================ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public void deleteNode(ListNode node) { node.val = node.next.val; node.next = node.next.next; return; } } ================================================ FILE: 237-delete-node-in-a-linked-list/NOTES.md ================================================ ================================================ FILE: 2389-longest-subsequence-with-limited-sum/2389-longest-subsequence-with-limited-sum.java ================================================ class Solution { public int[] answerQueries(int[] nums, int[] queries) { Arrays.sort(nums); int n=queries.length; int[]ans=new int[n]; for(int i=0;iqueries[i])break; sum+=nums[j]; } ans[i]=j; } return ans; } } ================================================ FILE: 2389-longest-subsequence-with-limited-sum/NOTES.md ================================================ ​ ================================================ FILE: 2389-longest-subsequence-with-limited-sum/README.md ================================================

2389. Longest Subsequence With Limited Sum

Easy


You are given an integer array nums of length n, and an integer array queries of length m.

Return an array answer of length m where answer[i] is the maximum size of a subsequence that you can take from nums such that the sum of its elements is less than or equal to queries[i].

A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

 

Example 1:

Input: nums = [4,5,2,1], queries = [3,10,21]
Output: [2,3,4]
Explanation: We answer the queries as follows:
- The subsequence [2,1] has a sum less than or equal to 3. It can be proven that 2 is the maximum size of such a subsequence, so answer[0] = 2.
- The subsequence [4,5,1] has a sum less than or equal to 10. It can be proven that 3 is the maximum size of such a subsequence, so answer[1] = 3.
- The subsequence [4,5,2,1] has a sum less than or equal to 21. It can be proven that 4 is the maximum size of such a subsequence, so answer[2] = 4.

Example 2:

Input: nums = [2,3,4,5], queries = [1]
Output: [0]
Explanation: The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0.

 

Constraints:

  • n == nums.length
  • m == queries.length
  • 1 <= n, m <= 1000
  • 1 <= nums[i], queries[i] <= 106
================================================ FILE: 2389_longest_subsequence_with_limited_sum.cpp ================================================ class Solution { public: vector answerQueries(vector& n, vector& q) { vector v; sort(n.begin(),n.end()); for(int i =0;i& nums) { set s; for(int i =0;i= 0 && i < matrix.length && j >= 0 && j < matrix[0].length){ if(matrix[i][j] == target) return true; else if(matrix[i][j] > target) j--; else if(matrix[i][j] < target) i++; } return false; } } ================================================ FILE: 240-search-a-2d-matrix-ii/NOTES.md ================================================ ​ ================================================ FILE: 240-search-a-2d-matrix-ii/README.md ================================================

240. Search a 2D Matrix II

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 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
================================================ FILE: 242-valid-anagram/242-valid-anagram.java ================================================ class Solution { public boolean isAnagram(String s, String t) { var freqs = new int[26]; var freqt = new int[26]; for (var c : s.toCharArray()) { freqs[c - 'a']++; } for (var c : t.toCharArray()) { freqt[c - 'a']++; } for (int i = 0; i != 26; ++i) { if (freqs[i] != freqt[i]) { return false; } } return true; } } ================================================ FILE: 242-valid-anagram/NOTES.md ================================================ ​ ================================================ FILE: 242-valid-anagram/README.md ================================================

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?

================================================ FILE: 2421-number-of-good-paths/2421-number-of-good-paths.java ================================================ class UnionFind { int[] parent; int[] rank; public UnionFind(int size) { parent = new int[size]; for (int i = 0; i < size; i++) parent[i] = i; rank = new int[size]; } public int find(int x) { if (parent[x] != x) parent[x] = find(parent[x]); return parent[x]; } public void union_set(int x, int y) { int xset = find(x), yset = find(y); if (xset == yset) { return; } else if (rank[xset] < rank[yset]) { parent[xset] = yset; } else if (rank[xset] > rank[yset]) { parent[yset] = xset; } else { parent[yset] = xset; rank[xset]++; } } } class Solution { public int numberOfGoodPaths(int[] vals, int[][] edges) { Map> adj = new HashMap<>(); for (int[] edge : edges) { int a = edge[0], b = edge[1]; adj.computeIfAbsent(a, value -> new ArrayList()).add(b); adj.computeIfAbsent(b, value -> new ArrayList()).add(a); } int n = vals.length; // Mapping from value to all the nodes having the same value in sorted order of // values. TreeMap> valuesToNodes = new TreeMap<>(); for (int i = 0; i < n; i++) { valuesToNodes.computeIfAbsent(vals[i], value -> new ArrayList()).add(i); } UnionFind dsu = new UnionFind(n); int goodPaths = 0; // Iterate over all the nodes with the same value in sorted order, starting from // the lowest value. for (int value : valuesToNodes.keySet()) { // For every node in nodes, combine the sets of the node and its neighbors into // one set. for (int node : valuesToNodes.get(value)) { if (!adj.containsKey(node)) continue; for (int neighbor : adj.get(node)) { // Only choose neighbors with a smaller value, as there is no point in // traversing to other neighbors. if (vals[node] >= vals[neighbor]) { dsu.union_set(node, neighbor); } } } // Map to compute the number of nodes under observation (with the same values) // in each of the sets. Map group = new HashMap<>(); // Iterate over all the nodes. Get the set of each node and increase the count // of the set by 1. for (int u : valuesToNodes.get(value)) { group.put(dsu.find(u), group.getOrDefault(dsu.find(u), 0) + 1); } // For each set of "size", add size * (size + 1) / 2 to the number of goodPaths. for (int key : group.keySet()) { int size = group.get(key); goodPaths += size * (size + 1) / 2; } } return goodPaths; } } ================================================ FILE: 2421-number-of-good-paths/NOTES.md ================================================ ​ ================================================ FILE: 2429-minimize-xor/2429-minimize-xor.cpp ================================================ class Solution { public: int minimizeXor(int num1, int num2) { int c1 = __builtin_popcount(num1); int c2 = __builtin_popcount(num2); int ans = 0; for (int i = 31; i >= 0; i--) { if ((1 << i) & num1) { ans |= (1 << i); c2--; if (c2 == 0) break; } } if (c2 > 0) { for (int i = 0; i < 32; i++) { if (((1 << i) & num1) == 0) { ans |= 1 << i; c2--; } if (c2 == 0) break; } } return ans; } }; ================================================ FILE: 2429-minimize-xor/Notes.md ================================================ ================================================ FILE: 2429-minimize-xor/Readme.md ================================================ ## 2429. Minimize XOR **Difficulty - Medium** Given two positive integers num1 and num2, find the integer x such that: - x has the same number of set bits as num2, and - The value x XOR num1 is minimal. Note that XOR is the bitwise XOR operation. Return the integer x. The test cases are generated such that x is uniquely determined. The number of set bits of an integer is the number of 1's in its binary representation. ## Example 1 **Input:** num1 = 3, num2 = 5 **Output:** 3 **Explanation:** The binary representations of num1 and num2 are 0011 and 0101, respectively. The integer 3 has the same number of set bits as num2, and the value 3 XOR 3 = 0 is minimal. ## Example 2 **Input:** num1 = 1, num2 = 12 **Output:** 3 **Explanation:** The binary representations of num1 and num2 are 0001 and 1100, respectively. The integer 3 has the same number of set bits as num2, and the value 3 XOR 1 = 2 is minimal. ## Contraints - 1 <= num1, num2 <= 109 ================================================ FILE: 2453-destroy-sequential-targets/2453-destroy-sequential-targets.java ================================================ class Solution { public int destroyTargets(int[] nums, int space) { HashMap remCount = new HashMap<>(); HashMap remNum = new HashMap<>(); for(int e : nums){ int rem = e%space; remNum.put(rem, Math.min(e,remNum.getOrDefault(rem, Integer.MAX_VALUE) )); remCount.put(rem, remCount.getOrDefault(rem,0)+1); } int max = -1; int remMax=-1; int re = -1; for(int rem : remCount.keySet()){ if(remCount.get(rem)>max){ remMax = rem; max = remCount.get(rem); re = remNum.get(remMax); } } int result = Integer.MAX_VALUE; for(int key : remNum.keySet()){ if(remCount.get(key)==max){ result = Math.min(remNum.get(key), result); } } return result; } } ================================================ FILE: 2453-destroy-sequential-targets/NOTES.md ================================================ ​ ================================================ FILE: 268-missing-number/268-missing-number.java ================================================ class Solution { public int missingNumber(int[] nums) { int num=nums.length; for(int i=0;i268. Missing Number

Easy


Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

 

Example 1:

Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.

Example 2:

Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.

Example 3:

Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.

 

Constraints:

  • n == nums.length
  • 1 <= n <= 104
  • 0 <= nums[i] <= n
  • All the numbers of nums are unique.

 

Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

================================================ FILE: 284-peeking-iterator/284-peeking-iterator.java ================================================ // Java Iterator interface reference: // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html class PeekingIterator implements Iterator { int i; ArrayList arr; public PeekingIterator(Iterator iterator) { // initialize any member here. arr=new ArrayList<>(); while(iterator.hasNext()){ arr.add(iterator.next()); } i=0; } // Returns the next element in the iteration without advancing the iterator. public Integer peek() { return arr.get(i); } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. @Override public Integer next() { int val=arr.get(i); i++; return val; } @Override public boolean hasNext() { return i284. Peeking Iterator

Medium


Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations.

Implement the PeekingIterator class:

  • PeekingIterator(Iterator<int> nums) Initializes the object with the given integer iterator iterator.
  • int next() Returns the next element in the array and moves the pointer to the next element.
  • boolean hasNext() Returns true if there are still elements in the array.
  • int peek() Returns the next element in the array without moving the pointer.

Note: Each language may have a different implementation of the constructor and Iterator, but they all support the int next() and boolean hasNext() functions.

 

Example 1:

Input
["PeekingIterator", "next", "peek", "next", "next", "hasNext"]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 2, 2, 3, false]

Explanation
PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]
peekingIterator.next();    // return 1, the pointer moves to the next element [1,2,3].
peekingIterator.peek();    // return 2, the pointer does not move [1,2,3].
peekingIterator.next();    // return 2, the pointer moves to the next element [1,2,3]
peekingIterator.next();    // return 3, the pointer moves to the next element [1,2,3]
peekingIterator.hasNext(); // return False

 

Constraints:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000
  • All the calls to next and peek are valid.
  • At most 1000 calls will be made to next, hasNext, and peek.

 

Follow up: How would you extend your design to be generic and work with all types, not just integer?
================================================ FILE: 287-find-the-duplicate-number/287-find-the-duplicate-number.java ================================================ class Solution { public int findDuplicate(int[] nums) { int fast=0,slow=0; while(true){ slow=nums[slow]; fast=nums[nums[fast]]; if(slow==fast)break; } int slow2=0; while(true){ slow=nums[slow]; slow2=nums[slow2]; if(slow==slow2)break; } return slow; } } ================================================ FILE: 287-find-the-duplicate-number/NOTES.md ================================================ ​ ================================================ FILE: 287-find-the-duplicate-number/README.md ================================================

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?
================================================ FILE: 289-game-of-life/289-game-of-life.java ================================================ class Solution { public void gameOfLife(int[][] board) { int n=board.length; int m=board[0].length; int[][] ans=new int[n][m]; for(int i=0;i3){ ans[i][j]=0; }else if(board[i][j]==0 && ones==3){ ans[i][j]=1; } } } for(int i=0;i0){ ans+=mat[i-1][j]; } if(j>0){ ans+=mat[i][j-1]; } if(i>0 && j>0){ ans+=mat[i-1][j-1]; } if(j0 && j0 && i289. Game of Life

Medium


According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."

The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

  1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population.
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.

 

Example 1:

Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]

Example 2:

Input: board = [[1,1],[1,0]]
Output: [[1,1],[1,1]]

 

Constraints:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 25
  • board[i][j] is 0 or 1.

 

Follow up:

  • Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
  • In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
================================================ FILE: 29-divide-two-integers/29-divide-two-integers.java ================================================ class Solution { public int divide(int dividend, int divisor) { //the special situation if (dividend == 0) { return 0; } if (dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } //mark the different situation boolean sign = true; if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) { sign = false; } //change them both into negative number dividend = dividend > 0 ? -dividend : dividend; divisor = divisor > 0 ? -divisor : divisor; //if there are different,so it must be a negative number,just 0 minus the result return sign == false ? 0 - count(dividend, divisor) : count(dividend, divisor); } /** * This recursion main code is while,it just likes optimization of subtraction */ private int count(int a, int b) { //if 3*n==7 just plus 1,or 3*n>7 just plus 0 if (a >= b) { return a > b ? 0 : 1; } //the default number is 1,and 2,4,8...doubling int n = 1; int result = 0; int temp = b; while (a <= temp && temp < 0) { a -= temp; result += n; temp += temp; n += n; } return result + count(a, b); } } ================================================ FILE: 29-divide-two-integers/NOTES.md ================================================ ​ ================================================ FILE: 3-longest-substring-without-repeating-characters/3-longest-substring-without-repeating-characters.java ================================================ class Solution { public int lengthOfLongestSubstring(String s) { if(s.length() < 2) return s.length(); int max = 0; char[] split = s.toCharArray(); int[] map = new int[256]; for(int i = 0, j = 0; i < split.length; i++) { char c = split[i]; j = Math.max(j, map[c]); map[c] = i + 1; max = Math.max(max, i - j + 1); } return max; } } ================================================ FILE: 3-longest-substring-without-repeating-characters/NOTES.md ================================================ ​ ================================================ FILE: 3-longest-substring-without-repeating-characters/README.md ================================================

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.

 

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.
================================================ FILE: 30-substring-with-concatenation-of-all-words/30-substring-with-concatenation-of-all-words.java ================================================ class Solution { public List findSubstring(String str, String[] words) { if(str == null || str.length() == 0 || words == null || words.length == 0) { return new ArrayList<>(); } Map frequencyMap = new HashMap<>(); for(String word: words) { frequencyMap.put(word, frequencyMap.getOrDefault(word, 0) + 1); } int eachWordLength = words[0].length(); int totalWords = words.length; List result = new ArrayList<>(); for (int i = 0; i <= str.length() - (totalWords * eachWordLength); i++) { Map seenWords = new HashMap<>(); for (int j = 0; j < totalWords; j++) { int wordIndex = i + j * eachWordLength; String word = str.substring(wordIndex, wordIndex + eachWordLength); if(!frequencyMap.containsKey(word)) { break; } seenWords.put(word, seenWords.getOrDefault(word, 0) + 1); if(seenWords.get(word) > frequencyMap.get(word)) { break; } if(j + 1 == totalWords) { result.add(i); } } } return result; } } ================================================ FILE: 30-substring-with-concatenation-of-all-words/30-substring-with-concatenation-of-all-words.py ================================================ class Solution: def findSubstring(self, s: str, words: List[str]) -> List[int]: words_counter = Counter(words) WORDLEN = len(words[0]) MATCHLEN = (len(words) - 1) * WORDLEN res = [] stack = deque() for offset in range(WORDLEN): counter = words_counter.copy() for i in range(offset, len(s), WORDLEN): word = s[i: i + WORDLEN] while len(stack) and word not in counter: prev = stack.popleft() if prev == word: stack.append(word) break counter[prev] += 1 if word in counter: counter[word] -= 1 stack.append(word) if counter[word] == 0: del counter[word] if len(counter) == 0: res.append(i - MATCHLEN) stack.clear() # Clears stack in the cases there are left overs from previous offset return res ================================================ FILE: 30-substring-with-concatenation-of-all-words/NOTES.md ================================================ ​ ================================================ FILE: 30-substring-with-concatenation-of-all-words/README.md ================================================

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.
================================================ FILE: 300-longest-increasing-subsequence/300-longest-increasing-subsequence.java ================================================ class Solution { public int lengthOfLIS(int[] nums) { int[]dp=new int[nums.length]; Arrays.fill(dp,1); for(int i=nums.length-2;i>=0;i--){ for(int j=i+1;j300. 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?

================================================ FILE: 304-range-sum-query-2d-immutable/304-range-sum-query-2d-immutable.java ================================================ class NumMatrix { int[][]mat; int[][]sum; public NumMatrix(int[][] matrix) { mat=matrix; int n=matrix.length; int m=matrix[0].length; sum=new int[n][m]; for(int i=0;i304. 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.
================================================ FILE: 307-range-sum-query-mutable/307-range-sum-query-mutable.java ================================================ class NumArray { class SegmentTreeNode { int start, end; SegmentTreeNode left, right; int sum; public SegmentTreeNode(int start, int end) { this.start = start; this.end = end; this.left = null; this.right = null; this.sum = 0; } } SegmentTreeNode root = null; public NumArray(int[] nums) { root = buildTree(nums, 0, nums.length-1); } private SegmentTreeNode buildTree(int[] nums, int start, int end) { if (start > end) { return null; } else { SegmentTreeNode ret = new SegmentTreeNode(start, end); if (start == end) { ret.sum = nums[start]; } else { int mid = start + (end - start) / 2; ret.left = buildTree(nums, start, mid); ret.right = buildTree(nums, mid + 1, end); ret.sum = ret.left.sum + ret.right.sum; } return ret; } } void update(int i, int val) { update(root, i, val); } void update(SegmentTreeNode root, int pos, int val) { if (root.start == root.end) { root.sum = val; } else { int mid = root.start + (root.end - root.start) / 2; if (pos <= mid) { update(root.left, pos, val); } else { update(root.right, pos, val); } root.sum = root.left.sum + root.right.sum; } } public int sumRange(int i, int j) { return sumRange(root, i, j); } public int sumRange(SegmentTreeNode root, int start, int end) { if (root.end == end && root.start == start) { return root.sum; } else { int mid = root.start + (root.end - root.start) / 2; if (end <= mid) { return sumRange(root.left, start, end); } else if (start >= mid+1) { return sumRange(root.right, start, end); } else { return sumRange(root.right, mid+1, end) + sumRange(root.left, start, mid); } } } } /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * obj.update(index,val); * int param_2 = obj.sumRange(left,right); */ ================================================ FILE: 307-range-sum-query-mutable/NOTES.md ================================================ ​ ================================================ FILE: 307-range-sum-query-mutable/README.md ================================================

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. Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.

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.
================================================ FILE: 31-next-permutation/31-next-permutation.java ================================================ class Solution { public void nextPermutation(int[] a) { int N=a.length; int k=-1; for(int i=0;ia[k]){ l=i; } } int temp=a[k]; a[k]=a[l]; a[l]=temp; reverse(a,k+1,N-1); } public void reverse(int[]a,int i,int j){ while(i<=j-1){ int temp=a[i]; a[i]=a[j]; a[j]=temp; i++; j--; } } } ================================================ FILE: 31-next-permutation/NOTES.md ================================================ ​ ================================================ FILE: 31-next-permutation/README.md ================================================

31. Next Permutation

Medium


A permutation of an array of integers is an arrangement of its members into a sequence or linear order.

  • For example, for arr = [1,2,3], the following are considered permutations of arr: [1,2,3], [1,3,2], [3,1,2], [2,3,1].

The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).

  • For example, the next permutation of arr = [1,2,3] is [1,3,2].
  • Similarly, the next permutation of arr = [2,3,1] is [3,1,2].
  • While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement.

Given an array of integers nums, find the next permutation of nums.

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]

 

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 100
================================================ FILE: 31-next-permutation/nextPurmutation.cpp ================================================ /* Approach: There may be three possibilities for the given sequence, it could be in ascending, descending or mixed Order. Based upon that three subcases will be applied 1. Descending Order : For this we simply need to return a series in acending order i.e. a Sorted Array 2. Ascending Order : By just swapping last two unequal numbers of array, we could get a Required next Permutation. 3. Mixed Order : For this we need to find the right most local maxima, after that is find further two cases may arise: i) If a number exists in right of this local maxima which is less than this maxima and greater than element before maxima(let say that as midVal) In that cases swapping midVal with element just before local maxima will give, next premutaion, as that would be more close. ii) In case if no such Element Exists, in that case directly swapping local maxima with element before than will be right. After doing any of i or ii, we need to sort remainning right array in ascending order. */ // Code : class Solution { public: int findIfMidExists(vector& nums, int t){ int ans = -1; for(int i=t+1;inums[t-1]){ ans = i; } } return ans; } void nextPermutation(vector& nums) { if(nums.size()==1) return ; if(nums.size()==2){ swap(nums[0], nums[1]); return; } int n = nums.size(), mx = n-1, i=n-1; for(;i>=0;i--){ if(i==n-1 && nums[i]>nums[i-1]){ mx = n-1; break;} else if(i>0 && nums[i]>nums[i-1] && nums[i]>=nums[i+1]){ mx = i; break; } } // If Given series is in descending Order if(i<0){ sort(nums.begin(), nums.end()); return; } int midVal = findIfMidExists(nums,mx); if(midVal != -1){ swap(nums[mx-1], nums[midVal]); sort(nums.begin()+mx, nums.end()); return; } swap(nums[mx-1], nums[mx]); sort(nums.begin() + mx, nums.end()); } }; ================================================ FILE: 315-count-of-smaller-numbers-after-self/315-count-of-smaller-numbers-after-self.java ================================================ class Solution { public List countSmaller(int[] nums) { int n=nums.length; Integer[] ans=new Integer[n]; ans[n-1]=0; int ii=n-2; List arr=new ArrayList<>(); arr.add(nums[n-1]); for(int i=n-2;i>=0;i--){ int idx=dfs(arr,nums[i]); arr.add(idx,nums[i]); ans[ii]=idx; ii--; } return Arrays.asList(ans); } int dfs(List arr,int ele){ int l=0; int h=arr.size()-1; while(l<=h){ int mid=l+(h-l)/2; if(ele<=arr.get(mid)){ h=mid-1; }else{ l=mid+1; } } return l; } } ================================================ FILE: 315-count-of-smaller-numbers-after-self/NOTES.md ================================================ ​ ================================================ FILE: 315-count-of-smaller-numbers-after-self/README.md ================================================

315. Count of Smaller Numbers After Self

Hard


You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

 

Example 1:

Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation:
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.

Example 2:

Input: nums = [-1]
Output: [0]

Example 3:

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

 

Constraints:

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
================================================ FILE: 316-remove-duplicate-letters/316-remove-duplicate-letters.java ================================================ class Solution { public String removeDuplicateLetters(String s) { int[]freq=new int[26]; int[]done=new int[26]; for(char c:s.toCharArray()){ freq[c-97]++; } Deque stack=new ArrayDeque<>(); for(int i=0;i0 && stack.peek()>ch){ if(freq[stack.peek()-97]>0){ char out=stack.pop(); done[out-97]=0; }else{ break; } } done[ch-97]=1; stack.push(ch); } freq[ch-97]--; } StringBuilder sb=new StringBuilder(); while(stack.size()>0){ sb.append(stack.pop()); } return sb.reverse().toString(); } } ================================================ FILE: 316-remove-duplicate-letters/NOTES.md ================================================ ​ ================================================ FILE: 316-remove-duplicate-letters/README.md ================================================

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/

================================================ FILE: 318-maximum-product-of-word-lengths/318-maximum-product-of-word-lengths.java ================================================ class Solution { public int maxProduct(String[] words) { int n=words.length; int[] mask=new int[n]; for(int i=0; i318. Maximum Product of Word Lengths

Medium


Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.

 

Example 1:

Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: The two words can be "abcw", "xtfn".

Example 2:

Input: words = ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4
Explanation: The two words can be "ab", "cd".

Example 3:

Input: words = ["a","aa","aaa","aaaa"]
Output: 0
Explanation: No such pair of words.

 

Constraints:

  • 2 <= words.length <= 1000
  • 1 <= words[i].length <= 1000
  • words[i] consists only of lowercase English letters.
================================================ FILE: 32-longest-valid-parentheses/32-longest-valid-parentheses.java ================================================ public class Solution { public int longestValidParentheses(String s) { int left = 0, right = 0, maxlength = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { left++; } else { right++; } if (left == right) { maxlength = Math.max(maxlength, 2 * right); } else if (right >= left) { left = right = 0; } } left = right = 0; for (int i = s.length() - 1; i >= 0; i--) { if (s.charAt(i) == '(') { left++; } else { right++; } if (left == right) { maxlength = Math.max(maxlength, 2 * left); } else if (left >= right) { left = right = 0; } } return maxlength; } } ================================================ FILE: 32-longest-valid-parentheses/NOTES.md ================================================ ​ ================================================ FILE: 32-longest-valid-parentheses/README.md ================================================

32. Longest Valid Parentheses

Hard


Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

 

Example 1:

Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".

Example 2:

Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".

Example 3:

Input: s = ""
Output: 0

 

Constraints:

  • 0 <= s.length <= 3 * 104
  • s[i] is '(', or ')'.
================================================ FILE: 322-coin-change/322-coin-change.java ================================================ class Solution { public int coinChange(int[] coins, int amount) { int dp[]=new int[amount+1]; Arrays.fill(dp,amount+1); dp[0]=0; for(int coin:coins){ for(int i=coin;i<=amount;i++){//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
================================================ FILE: 326-power-of-three/326-power-of-three.java ================================================ public class Solution { public boolean isPowerOfThree(int n) { return n > 0 && 1162261467 % n == 0; } } ================================================ FILE: 326-power-of-three/326_Power_of_three.cpp ================================================ class Solution { public: bool isPowerOfThree(int n) { while(n>=3) { if(n%3 != 0) return false; n/=3; } return n==1; } }; ================================================ FILE: 326-power-of-three/NOTES.md ================================================ ​ ================================================ FILE: 326-power-of-three/README.md ================================================

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?
================================================ FILE: 329-longest-increasing-path-in-a-matrix/329-longest-increasing-path-in-a-matrix.java ================================================ class Solution { int[][] matrix, helper; int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; public int longestIncreasingPath(int[][] matrix) { helper = new int[matrix.length][matrix[0].length]; this.matrix= matrix; int path = 0; for(int i=0;i= 0 && i < matrix.length && j >= 0 && j < matrix[0].length && matrix[x][y] < matrix[i][j]) { helper[x][y] = Math.max(helper[x][y], dfs(i, j)); } } return ++helper[x][y]; } } ================================================ FILE: 329-longest-increasing-path-in-a-matrix/README.md ================================================

329. Longest Increasing Path in a Matrix

Hard


Given an m x n integers matrix, return the length of the longest increasing path in matrix.

From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).

 

Example 1:

Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].

Example 2:

Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

Example 3:

Input: matrix = [[1]]
Output: 1

 

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 231 - 1
================================================ FILE: 33-search-in-rotated-sorted-array/33-search-in-rotated-sorted-array.java ================================================ class Solution { public int search(int[] nums, int target) { int l=0,h=nums.length-1; while(l<=h){ int mid=(l+h)/2; if(nums[mid]==target){ return mid; } else if(nums[mid]>=nums[l]){ if(target>=nums[l] && targetnums[mid] && target<=nums[h]){ l=mid+1; }else{ h=mid-1; } } } return -1; } } ================================================ FILE: 33-search-in-rotated-sorted-array/README.md ================================================

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
================================================ FILE: 336-palindrome-pairs/336-palindrome-pairs.java ================================================ class Solution { public List> palindromePairs(String[] words) { List> ans=new ArrayList<>(); Map map= new HashMap<>(); int idx=0; for(String word:words){ StringBuilder sb=new StringBuilder(word); map.put(sb.reverse().toString(),idx++); } for(int i=0;i curr=new ArrayList<>(); curr.add(i); curr.add(map.get(s1)); ans.add(curr); } if(!s1.isEmpty() && map.containsKey(s2) && map.get(s2)!=i && isPal(s1)){ List curr=new ArrayList<>(); curr.add(map.get(s2)); curr.add(i); ans.add(curr); } } } return ans; } boolean isPal(String s){ int i=0; int j=s.length()-1; while(i336. Palindrome Pairs

Hard


Given a list of unique words, return all the pairs of the distinct indices (i, j) in the given list, so that the concatenation of the two words words[i] + words[j] is a palindrome.

 

Example 1:

Input: words = ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]

Example 2:

Input: words = ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: The palindromes are ["battab","tabbat"]

Example 3:

Input: words = ["a",""]
Output: [[0,1],[1,0]]

 

Constraints:

  • 1 <= words.length <= 5000
  • 0 <= words[i].length <= 300
  • words[i] consists of lower-case English letters.
================================================ FILE: 34-find-first-and-last-position-of-element-in-sorted-array/34-find-first-and-last-position-of-element-in-sorted-array.java ================================================ class Solution { public int[] searchRange(int[] nums, int target) { int[] ans=new int[2]; ans[0]=Integer.MAX_VALUE; ans[1]=Integer.MIN_VALUE; dfs(nums,target,ans,0,nums.length-1); if(ans[0]==Integer.MAX_VALUE){ ans[0]=-1; ans[1]=-1; } return ans; } void dfs(int[]nums,int target,int[]ans,int l,int h){ if(l<=h){ int mid=l+(h-l)/2; if(nums[mid]==target){ ans[0]=Math.min(ans[0],mid); ans[1]=Math.max(ans[1],mid); dfs(nums,target,ans,l,mid-1); dfs(nums,target,ans,mid+1,h); }else if(nums[mid]>target){ dfs(nums,target,ans,l,mid-1); }else{ dfs(nums,target,ans,mid+1,h); } } } } ================================================ FILE: 34-find-first-and-last-position-of-element-in-sorted-array/README.md ================================================

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
================================================ FILE: 341-flatten-nested-list-iterator/341-flatten-nested-list-iterator.java ================================================ public class NestedIterator implements Iterator { List list; int index = 0; public NestedIterator(List nestedList) { list = new ArrayList(); worker(nestedList); } void worker(List node) { if(node==null) { return; } for(NestedInteger next:node) { if(next.isInteger()) { list.add(next.getInteger()); } else { worker(next.getList()); } } } @Override public Integer next() { int val = list.get(index); index++; return val; } @Override public boolean hasNext() { return index341. Flatten Nested List Iterator

Medium


You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.

Implement the NestedIterator class:

  • NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList.
  • int next() Returns the next integer in the nested list.
  • boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.

Your code will be tested with the following pseudocode:

initialize iterator with nestedList
res = []
while iterator.hasNext()
    append iterator.next() to the end of res
return res

If res matches the expected flattened list, then your code will be judged as correct.

 

Example 1:

Input: nestedList = [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

Example 2:

Input: nestedList = [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].

 

Constraints:

  • 1 <= nestedList.length <= 500
  • The values of the integers in the nested list is in the range [-106, 106].
================================================ FILE: 342-power-of-four/342-power-of-four.java ================================================ class Solution { public boolean isPowerOfFour(int n) { if(n==0)return false; int x=(int)(Math.log(n)/Math.log(4)); if(Math.pow(4,x)==n)return true; return false; } } ================================================ FILE: 342-power-of-four/NOTES.md ================================================ ​ ================================================ FILE: 342-power-of-four/README.md ================================================

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?
================================================ FILE: 342-power-of-four/power of four.cpp ================================================ bool isPowerOfFour(int n) { long int ans=0; int i=0; while(ans<=n) { ans=pow(4,i); i++; if(ans==n) return true; } return false; } ================================================ FILE: 344-reverse-string/344-reverse-string.java ================================================ class Solution { public void reverseString(char[] s) { int n=s.length; for(int i=0;i344. 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:

================================================ FILE: 347-top-k-frequent-elements/347-top-k-frequent-elements.cpp ================================================ class Solution { public: vector topKFrequent(vector& nums, int k) { // 1. // unordered_map mp; // for(int i=0;i ans; // while(ans.size() < k){ // int f = INT_MIN; // int t; // for(auto it : mp){ // if(f < it.second){ // f = it.second; // t = it.first; // } // } // if(ans.size() < k) // ans.push_back(t); // mp.erase(t); // } // return ans; // by default the priority queue will sort the first value of pairs in descending order // 2. unordered_map mp; for(int i=0;i ans(k, 0); priority_queue> pq; for(auto it : mp){ pair p; p.first = it.second; p.second = it.first; pq.push(p); } int i=0; while(imap=new HashMap<>(); for(int i:nums){ map.put(i,map.getOrDefault(i,0)+1); } PriorityQueue pq=new PriorityQueue<>((a,b)->b[1]-a[1]); for(Map.Entry entry:map.entrySet()){ int[]a=new int[]{entry.getKey(),entry.getValue()}; pq.add(a); } int i=0; while(i347. 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.

================================================ FILE: 354-russian-doll-envelopes/354-russian-doll-envelopes.java ================================================ public class Solution { public int maxEnvelopes(int[][] envelopes) { if(envelopes.length < 2) return envelopes.length; Arrays.sort(envelopes, new EnvelopeComparator()); int[] dp = new int[envelopes.length]; int size = 0; for(int[] envelope: envelopes) { // binary search int left = 0, right = size, middle = 0; // right = size while(left < right) { middle = left + (right - left) / 2; if(dp[middle] < envelope[1]) left = middle + 1; else right = middle; } // left is the right position to 'replace' in dp array dp[left] = envelope[1]; if(left == size) size++; } return size; } class EnvelopeComparator implements Comparator { public int compare(int[] e1, int[] e2) { return e1[0] == e2[0] ? e2[1] - e1[1] : e1[0] - e2[0]; } } } ================================================ FILE: 354-russian-doll-envelopes/NOTES.md ================================================ ​ ================================================ FILE: 354-russian-doll-envelopes/README.md ================================================

354. Russian Doll Envelopes

Hard


You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.

One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.

Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).

Note: You cannot rotate an envelope.

 

Example 1:

Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

Example 2:

Input: envelopes = [[1,1],[1,1],[1,1]]
Output: 1

 

Constraints:

  • 1 <= envelopes.length <= 105
  • envelopes[i].length == 2
  • 1 <= wi, hi <= 105
================================================ FILE: 363-max-sum-of-rectangle-no-larger-than-k/363-max-sum-of-rectangle-no-larger-than-k.cpp ================================================ // problem is a combination of 2 problems first is max sum of rectangle and second is sum of subarray not greater than k class Solution { public: int maxSumSubmatrix(vector>& mat, int k) { int row = mat.size(); int col = mat[0].size(); int maxLen=INT_MIN; for(int left = 0; left < col; left++){ vector v(row, 0); for(int right = left; right < col; right++){ for(int i = 0; i < row; i++){ v[i] += mat[i][right]; } set s = {0}; int run_sum=0; for(int sum : v){ run_sum += sum; auto it = s.lower_bound(run_sum - k); if(it != s.end()) maxLen = max(maxLen, run_sum - *it); s.insert(run_sum); } } } return maxLen; } }; ================================================ FILE: 363-max-sum-of-rectangle-no-larger-than-k/363-max-sum-of-rectangle-no-larger-than-k.java ================================================ class Solution { public int maxSumSubmatrix(int[][] mat, int k) { int n=mat.length; int m=mat[0].length; //create prefix sum array int[][]pre=new int[n][m]; pre[0][0]=mat[0][0]; for(int i=1;i363. Max Sum of Rectangle No Larger Than K

Hard


Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k.

It is guaranteed that there will be a rectangle with a sum no larger than k.

 

Example 1:

Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).

Example 2:

Input: matrix = [[2,2,-1]], k = 3
Output: 3

 

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -100 <= matrix[i][j] <= 100
  • -105 <= k <= 105

 

Follow up: What if the number of rows is much larger than the number of columns?

================================================ FILE: 37-Sudoku-solver/37-Sudoku-solver.js ================================================ var solveSudoku = function(board) { function isValid(grid, row, col, k) { for (let i = 0; i < 9; i++) { const m = 3 * Math.floor(row / 3) + Math.floor(i / 3); const n = 3 * Math.floor(col / 3) + i % 3; if (grid[row][i] == k || grid[i][col] == k || grid[m][n] == k) { return false; } } return true; } function solve(grid) { for (let i = 0; i < 9; i++) { for (let j = 0; j < 9; j++) { if (grid[i][j] == '.') { for (let k = 1; k <= 9; k++) { if (isValid(grid, i, j, k)) { grid[i][j] = `${k}`; if (solve(grid)) { return true; } else { grid[i][j] = '.'; } } } return false; } } } return true; } solve(board) return board ; }; ================================================ FILE: 37-Sudoku-solver/README.md ================================================

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. Each of the digits 1-9 must occur exactly once in each column.
  3. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

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.

Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope.

Return the minimum time Bob needs to make the rope colorful.

 

Example 1:

Input: colors = "abaac", neededTime = [1,2,3,4,5]
Output: 3
Explanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green.
Bob can remove the blue balloon at index 2. This takes 3 seconds.
There are no longer two consecutive balloons of the same color. Total time = 3.

Example 2:

Input: colors = "abc", neededTime = [1,2,3]
Output: 0
Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.

Example 3:

Input: colors = "aabaa", neededTime = [1,2,3,4,1]
Output: 2
Explanation: Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.
There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.

 

Constraints:

  • n == colors.length == neededTime.length
  • 1 <= n <= 105
  • 1 <= neededTime[i] <= 104
  • colors contains only lowercase English letters.
================================================ FILE: 371-sum-of-two-integers/371-sum-of-two-integers.java ================================================ class Solution { public int getSum(int a, int b) { while(b!=0){ int ans=(a^b); int carry=(a&b)<<1; a=ans; b=carry; } return a; } } ================================================ FILE: 371-sum-of-two-integers/NOTES.md ================================================ ​ ================================================ FILE: 371-sum-of-two-integers/README.md ================================================

371. Sum of Two Integers

Medium


Given two integers a and b, return the sum of the two integers without using the operators + and -.

 

Example 1:

Input: a = 1, b = 2
Output: 3

Example 2:

Input: a = 2, b = 3
Output: 5

 

Constraints:

  • -1000 <= a, b <= 1000
================================================ FILE: 376-wiggle-subsequence/376-wiggle-subsequence.java ================================================ public class Solution { public int wiggleMaxLength(int[] nums) { if (nums.length < 2)return nums.length; int prevdiff = nums[1] - nums[0]; int count = prevdiff != 0 ? 2 : 1; for (int i = 2; i < nums.length; i++) { int diff = nums[i] - nums[i - 1]; if ((diff > 0 && prevdiff <= 0) || (diff < 0 && prevdiff >= 0)) { count++; prevdiff = diff; } } return count; } } ================================================ FILE: 376-wiggle-subsequence/NOTES.md ================================================ ​ ================================================ FILE: 376-wiggle-subsequence/README.md ================================================

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?

================================================ FILE: 377-combination-sum-iv/377-combination-sum-iv.java ================================================ class Solution { private int[] dp; public int combinationSum4(int[] nums, int target) { dp = new int[target + 1]; Arrays.fill(dp, -1); dp[0] = 1; return helper(nums, target); } private int helper(int[] nums, int target) { if (dp[target] != -1) return dp[target]; int res = 0; for (int num: nums) { if (target >= num) { res += helper(nums, target - num); } } return dp[target] = res; // res; } } ================================================ FILE: 377-combination-sum-iv/NOTES.md ================================================ ​ ================================================ FILE: 377-combination-sum-iv/README.md ================================================

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?

================================================ FILE: 378-kth-smallest-element-in-a-sorted-matrix/378-kth-smallest-element-in-a-sorted-matrix.java ================================================ class Solution { public int kthSmallest(int[][] mat, int k) { int[]arr=new int[mat.length*mat[0].length]; int idx=0; for(int i=0;i383. Ransom Note

Easy


Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

 

Example 1:

Input: ransomNote = "a", magazine = "b"
Output: false

Example 2:

Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 3:

Input: ransomNote = "aa", magazine = "aab"
Output: true

 

Constraints:

  • 1 <= ransomNote.length, magazine.length <= 105
  • ransomNote and magazine consist of lowercase English letters.
================================================ FILE: 383-ransom-note/ransom-note.cpp ================================================ class Solution { public: bool canConstruct(string ransomNote, string magazine) { ios_base::sync_with_stdio(false); cin.tie(NULL); vector magazineHash(26,0); // 26 char, start from 0 , // traverse magazing and keep count of each letter in magazineHash for(int i =0; magazine[i]!='\0'; ++i){ magazineHash[magazine[i]-'a'] +=1; } // now traverse ransomNote and keep decrementing count in magazineHash for(int i =0; ransomNote[i]!='\0'; ++i){ if(magazineHash[ransomNote[i]-'a'] == 0) return false; magazineHash[ransomNote[i]-'a'] -=1; // using up char to lead decrement it by value 1 } return true; // TC:O(N+M) -> where n is the length of the magazing and M is length of randomString } }; ================================================ FILE: 383-ransom-note/ransome-note-two-approaches.cpp ================================================ class Solution { public: bool canConstruct(string rn, string mag) { if(mag.size() < rn.size()) return false; // 1. // unordered_map m1, m2; // for(int i=0;i m2[rn[i]]){ // return false; // } // } // 2. vector arr(26, 0); for(int i=0;i387. First Unique Character in a String

Easy


Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

 

Example 1:

Input: s = "leetcode"
Output: 0

Example 2:

Input: s = "loveleetcode"
Output: 2

Example 3:

Input: s = "aabb"
Output: -1

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters.
================================================ FILE: 387-first-unique-character-in-a-string/first-unique-character-in-a-string.CPP ================================================ int firstUniqChar(string s) { unordered_mapmp; for(int i=0;i255) return false; // 1 after 8th digit, 100000000 int numberOfBytes = 0; if((data[i] & 128) == 0) { // 0xxxxxxx, 1 byte, 128(10000000) numberOfBytes = 1; } else if((data[i] & 224) == 192) { // 110xxxxx, 2 bytes, 224(11100000), 192(11000000) numberOfBytes = 2; } else if((data[i] & 240) == 224) { // 1110xxxx, 3 bytes, 240(11110000), 224(11100000) numberOfBytes = 3; } else if((data[i] & 248) == 240) { // 11110xxx, 4 bytes, 248(11111000), 240(11110000) numberOfBytes = 4; } else { return false; } for(int j=1;j=data.length) return false; if((data[i+j] & 192) != 128) return false; // 192(11000000), 128(10000000) } i=i+numberOfBytes-1; } return isValid; } } //Approach 2 class Solution { public boolean validUtf8(int[] data) { int f[]=new int[256]; for(int i=0;i<256;i++) { // storing All sequences in in array having data[i] as index. As 0<=data[i]<=255, stored in f array int count=0; for(int j=7;j>=0;j--) { if((i&(1<0) { count+=1; } else { break; } } if(count<=4) f[i]=count; // if starting 1's count <=4 storing in f array else f[i]=-1; //if starting 1's count>=5, it is not part of any utf-8 sequence making as -1 } int bytes=-1; int sequence=-1; for(int i=0;i00000000 then sequence becomes -1 bytes=f[data[i]]; if(bytes==1 && (data[i]&(1<<7))>0) { return false; } sequence=bytes-1; continue; } if(setBits==1) { // After having starting , remaining sequence should contain only 1's sequence-=1; } else { // otherwise returning false return false; } } if(sequence==0 || sequence == -1) { //At end sequence should be either 0 or -1 which means sequence completed for 0/1/2/3. for 0->sequence becomes -1, for 1,2,3->sequence becomes 0 return true; } return false; } } ================================================ FILE: 393-utf-8-validation/NOTES.md ================================================ ​ ================================================ FILE: 393-utf-8-validation/README.md ================================================

393. UTF-8 Validation

Medium


Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).

A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:

  1. For a 1-byte character, the first bit is a 0, followed by its Unicode code.
  2. For an n-bytes character, the first n bits are all one's, the n + 1 bit is 0, followed by n - 1 bytes with the most significant 2 bits being 10.

This is how the UTF-8 encoding would work:

     Number of Bytes   |        UTF-8 Octet Sequence
                       |              (binary)
   --------------------+-----------------------------------------
            1          |   0xxxxxxx
            2          |   110xxxxx 10xxxxxx
            3          |   1110xxxx 10xxxxxx 10xxxxxx
            4          |   11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

x denotes a bit in the binary form of a byte that may be either 0 or 1.

Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.

 

Example 1:

Input: data = [197,130,1]
Output: true
Explanation: data represents the octet sequence: 11000101 10000010 00000001.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.

Example 2:

Input: data = [235,140,4]
Output: false
Explanation: data represented the octet sequence: 11101011 10001100 00000100.
The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that's correct.
But the second continuation byte does not start with 10, so it is invalid.

 

Constraints:

  • 1 <= data.length <= 2 * 104
  • 0 <= data[i] <= 255
================================================ FILE: 399-evaluate-division/399-evaluate-division.java ================================================ class Solution { class Node{ String key; double val; Node(String k,double v){ key=k; val=v; } } public double[] calcEquation(List> equations, double[] values, List> queries) { Map>g=buildGraph(equations,values); double[]res=new double[queries.size()]; for(int i=0;i(),g); } return res; } private double dfs(String s,String d,Set vis,Map> g){ if(!(g.containsKey(s) && g.containsKey(d)))return -1.0; if(s.equals(d))return 1.0; vis.add(s); for(Node n:g.get(s)){ if(!vis.contains(n.key)){ double ans=dfs(n.key,d,vis,g); if(ans!=-1.0)return ans*n.val; } } return -1.0; } private Map> buildGraph(List> eq,double[] vals){ Map> g=new HashMap<>(); for(int i=0;i()); g.putIfAbsent(des,new ArrayList<>()); g.get(src).add(new Node(des,vals[i])); g.get(des).add(new Node(src,1/vals[i])); } return g; } } ================================================ FILE: 399-evaluate-division/NOTES.md ================================================ ​ ================================================ FILE: 399-evaluate-division/README.md ================================================

399. Evaluate Division

Medium


You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable.

You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?.

Return the answers to all queries. If a single answer cannot be determined, return -1.0.

Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.

 

Example 1:

Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000]
Explanation: 
Given: a / b = 2.0, b / c = 3.0
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
return: [6.0, 0.5, -1.0, 1.0, -1.0 ]

Example 2:

Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]
Output: [3.75000,0.40000,5.00000,0.20000]

Example 3:

Input: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]
Output: [0.50000,2.00000,-1.00000,-1.00000]

 

Constraints:

  • 1 <= equations.length <= 20
  • equations[i].length == 2
  • 1 <= Ai.length, Bi.length <= 5
  • values.length == equations.length
  • 0.0 < values[i] <= 20.0
  • 1 <= queries.length <= 20
  • queries[i].length == 2
  • 1 <= Cj.length, Dj.length <= 5
  • Ai, Bi, Cj, Dj consist of lower case English letters and digits.
================================================ FILE: 4-median-of-two-sorted-arrays/4-median-of-two-sorted-arrays.java ================================================ class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int[] nums = new int[nums1.length + nums2.length]; System.arraycopy(nums1, 0, nums, 0, nums1.length); System.arraycopy(nums2, 0, nums, nums1.length, nums2.length); Arrays.sort(nums); return (nums[nums.length >> 1] + nums[(nums.length - 1) >> 1]) / 2.0; } } ================================================ FILE: 4-median-of-two-sorted-arrays/NOTES.md ================================================ ​ ================================================ FILE: 406-queue-reconstruction-by-height/406-queue-reconstruction-by-height.java ================================================ class Solution { public int[][] reconstructQueue(int[][] people) { Arrays.sort(people, (o1, o2) -> o1[0] != o2[0] ? o2[0] - o1[0] : o1[1] - o2[1]); List tempRes = new LinkedList<>(); for (int[] person : people) { tempRes.add(person[1], person); } return tempRes.toArray(new int[people.length][]); } } ================================================ FILE: 406-queue-reconstruction-by-height/NOTES.md ================================================ ​ ================================================ FILE: 406-queue-reconstruction-by-height/README.md ================================================

406. Queue Reconstruction by Height

Medium


You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi.

Reconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue).

 

Example 1:

Input: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
Output: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]
Explanation:
Person 0 has height 5 with no other people taller or the same height in front.
Person 1 has height 7 with no other people taller or the same height in front.
Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.
Person 3 has height 6 with one person taller or the same height in front, which is person 1.
Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.
Person 5 has height 7 with one person taller or the same height in front, which is person 1.
Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.

Example 2:

Input: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]
Output: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]

 

Constraints:

  • 1 <= people.length <= 2000
  • 0 <= hi <= 106
  • 0 <= ki < people.length
  • It is guaranteed that the queue can be reconstructed.
================================================ FILE: 410-split-array-largest-sum/410-split-array-largest-sum.java ================================================ class Solution { public int splitArray(int[] nums, int m) { int max = Integer.MIN_VALUE; int sum = 0; // search range [max, sum]; for (int i = 0; i < nums.length; i++) { max = Math.max(max, nums[i]); sum += nums[i]; } int left = max; int right = sum; while (left < right) { int mid = left + (right - left) / 2; if (canSplit(nums, m, mid)) { right = mid; } else { left = mid + 1; } } // if (canSplit(nums, m, right)) return right; return left; } private boolean canSplit(int[] nums, int m, int largest) { int count = 1; int sum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; if (sum > largest) { count++; sum = nums[i]; } } return count <= m; } } ================================================ FILE: 410-split-array-largest-sum/NOTES.md ================================================ ​ ================================================ FILE: 410-split-array-largest-sum/README.md ================================================

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)
================================================ FILE: 417-pacific-atlantic-water-flow/417-pacific-atlantic-water-flow.java ================================================ class Solution { public List> pacificAtlantic(int[][] heights) { int rows = heights.length, cols = heights[0].length; boolean[][] pac = new boolean[rows][cols]; boolean[][] atl = new boolean[rows][cols]; for (int col = 0; col< cols; col++){ dfs(0, col, rows, cols, pac, heights[0][col], heights); dfs(rows-1, col,rows, cols, atl, heights[rows-1][col], heights); } for (int row = 0; row> result = new ArrayList>(); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++){ if (pac[i][j] && atl[i][j]) result.add(Arrays.asList(i,j)); } return result; } private void dfs(int row, int col, int rows, int cols, boolean[][] visited, int prevHeight, int[][] heights){ if (row < 0 || row >= rows || col < 0 || col >= cols || visited[row][col] || prevHeight > heights[row][col]) return; visited[row][col]= true; dfs(row+1, col, rows, cols, visited, heights[row][col], heights); dfs(row-1, col, rows, cols, visited, heights[row][col], heights); dfs(row, col+1, rows, cols, visited, heights[row][col], heights); dfs(row, col-1, rows, cols, visited, heights[row][col], heights); } } ================================================ FILE: 417-pacific-atlantic-water-flow/NOTES.md ================================================ ​ ================================================ FILE: 417-pacific-atlantic-water-flow/README.md ================================================

417. Pacific Atlantic Water Flow

Medium


There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.

The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).

The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.

Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.

 

Example 1:

Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Explanation: The following cells can flow to the Pacific and Atlantic oceans, as shown below:
[0,4]: [0,4] -> Pacific Ocean 
       [0,4] -> Atlantic Ocean
[1,3]: [1,3] -> [0,3] -> Pacific Ocean 
       [1,3] -> [1,4] -> Atlantic Ocean
[1,4]: [1,4] -> [1,3] -> [0,3] -> Pacific Ocean 
       [1,4] -> Atlantic Ocean
[2,2]: [2,2] -> [1,2] -> [0,2] -> Pacific Ocean 
       [2,2] -> [2,3] -> [2,4] -> Atlantic Ocean
[3,0]: [3,0] -> Pacific Ocean 
       [3,0] -> [4,0] -> Atlantic Ocean
[3,1]: [3,1] -> [3,0] -> Pacific Ocean 
       [3,1] -> [4,1] -> Atlantic Ocean
[4,0]: [4,0] -> Pacific Ocean 
       [4,0] -> Atlantic Ocean
Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.

Example 2:

Input: heights = [[1]]
Output: [[0,0]]
Explanation: The water can flow from the only cell to the Pacific and Atlantic oceans.

 

Constraints:

  • m == heights.length
  • n == heights[r].length
  • 1 <= m, n <= 200
  • 0 <= heights[r][c] <= 105
================================================ FILE: 417_Pacific Atlantic Water Flow.cpp ================================================ #include using namespace std; class Solution{ public: // using dfs int m, n; // this denotes cells reachable starting from atlantic and pacific edged cells resp vector > atlantic, pacific; vector > res; vector > pacificAtlantic(vector>& heights) { if(!size(heights)) return res; // check for null condition m = size(heights), n = size(heights[0]); // initializing row and col // taking bolean matrices(vector), to see whether a cell that can reach the atalantic of pacific atlantic = pacific = vector >(m, vector(n, false)); // perform dfs from all edge cells (ocean-connected cells) for(int i = 0; i < m; i++) dfs(heights, pacific, i, 0), dfs(heights, atlantic, i, n - 1); for(int i = 0; i < n; i++) dfs(heights, pacific, 0, i), dfs(heights, atlantic, m - 1, i); return res; } // define dfs void dfs(vector >& mat, vector >& visited, int i, int j){ if(visited[i][j]) return; visited[i][j] = true; // if cell reachable from both the oceans, insert into final result vector if(atlantic[i][j] && pacific[i][j]) res.push_back(vector{i, j}); // dfs from current cell only if height of next cell is greater /*down dir*/ if(i + 1 < m && mat[i + 1][j] >= mat[i][j]) dfs(mat, visited, i + 1, j); /*Up dir*/ if(i - 1 >= 0 && mat[i - 1][j] >= mat[i][j]) dfs(mat, visited, i - 1, j); /*right dir*/ if(j + 1 < n && mat[i][j + 1] >= mat[i][j]) dfs(mat, visited, i, j + 1); /*left dir*/ if(j - 1 >= 0 && mat[i][j - 1] >= mat[i][j]) dfs(mat, visited, i, j - 1); } }; int main(){ } ================================================ FILE: 42 Trapping Rain Water hd s18.cpp ================================================ #include using namespace std; class Solution { public: int trap(vector& height) { // using 2 pointers tech int i =0, j = height.size()-1, res =0, maxi =0, mini =0; // pointer i from left and j from right while(i <=j){ // take mini ht mini = min(height[i], height[j]); // find max, min ht maxi = max(maxi, mini); // unit of water being tapped is diff betn max_ht & min_ht res += maxi - mini; // move pointer i if ht[i] is smaller if(height[i] < height[j]) i++; // else move ptr j else j--; } return res; // TC: O(N), SC:O(1) } }; ================================================ FILE: 42-trapping-rain-water/42-trapping-rain-water.java ================================================ class Solution { public int trap(int[] h) { int n=h.length; int[] left=new int[n]; int[]right=new int[n]; left[0]=h[0]; for(int i=1;i=0;i--){ right[i]=Math.max(right[i+1],h[i]); } int ans=0; for(int i=0;i42. 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
================================================ FILE: 429-n-ary-tree-level-order-traversal/429-n-ary-tree-level-order-traversal.cpp ================================================ class Solution { public: vector> levelOrder(Node* root) { if(!root) return {}; vector> ans; queue q; q.push(root); while(!q.empty()){ int n = q.size(); vector v; for(int i=0;ival); for(Node* child : node->children) q.push(child); } ans.push_back(v); } return ans; } }; ================================================ FILE: 429-n-ary-tree-level-order-traversal/429-n-ary-tree-level-order-traversal.java ================================================ /* // Definition for a Node. class Node { public int val; public List children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List _children) { val = _val; children = _children; } }; */ class Solution { public List> levelOrder(Node root) { List> list=new ArrayList<>(); if(root==null)return list; Queue q=new LinkedList<>(); q.add(root); while(!q.isEmpty()){ int size=q.size(); List l=new ArrayList<>(); for(int i=0;i> levelOrder(Node root) { List> outter=new ArrayList<>(); if(root==null) return outter; Deque q=new LinkedList<>(); q.add(root); List inner=new ArrayList<>(); inner.add(root.val); outter.add(inner); while(q.size()>0){ //R P A int len=q.size(); inner=new ArrayList<>(); for(int i=0;i child=curr.children; if(child.size()==0) continue; int run=child.size(); for(int j=0;j0) outter.add(inner); } return outter; } } ================================================ FILE: 429-n-ary-tree-level-order-traversal/NOTES.md ================================================ ​ ================================================ FILE: 429-n-ary-tree-level-order-traversal/README.md ================================================

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]
================================================ FILE: 456-132-pattern/456-132-pattern.java ================================================ class Solution { public boolean find132pattern(int[] nums) { int len = nums.length; if (len < 3)return false; Deque stk = new ArrayDeque<>(); int k = -1; for (int i = len - 1; i >= 0; i--) { if (k > -1 && nums[k] > nums[i]) { return true; } while (!stk.isEmpty() && nums[i] > nums[stk.peek()]) { k = stk.pop(); } stk.push(i); } return false; } } ================================================ FILE: 456-132-pattern/NOTES.md ================================================ ​ ================================================ FILE: 456-132-pattern/README.md ================================================

456. 132 Pattern

Medium


Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].

Return true if there is a 132 pattern in nums, otherwise, return false.

 

Example 1:

Input: nums = [1,2,3,4]
Output: false
Explanation: There is no 132 pattern in the sequence.

Example 2:

Input: nums = [3,1,4,2]
Output: true
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

Example 3:

Input: nums = [-1,3,2,0]
Output: true
Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].

 

Constraints:

  • n == nums.length
  • 1 <= n <= 2 * 105
  • -109 <= nums[i] <= 109
================================================ FILE: 458-poor-pigs/458-poor-pigs.java ================================================ class Solution { public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { int rounds=(minutesToTest/minutesToDie)+1; return (int)Math.ceil(Math.log(buckets)/Math.log(rounds)); } } ================================================ FILE: 458-poor-pigs/NOTES.md ================================================ ​ ================================================ FILE: 458-poor-pigs/README.md ================================================

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. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.
  3. Wait for minutesToDie minutes. You may not feed any other pigs during this time.
  4. After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
  5. Repeat this process until you run out of time.

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
================================================ FILE: 462-minimum-moves-to-equal-array-elements-ii/462-minimum-moves-to-equal-array-elements-ii.java ================================================ class Solution { public int minMoves2(int[] nums) { Arrays.sort(nums); int i=0; int j=nums.length-1; int staps=0; while(i462. Minimum Moves to Equal Array Elements II

Medium


Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

In one move, you can increment or decrement an element of the array by 1.

Test cases are designed so that the answer will fit in a 32-bit integer.

 

Example 1:

Input: nums = [1,2,3]
Output: 2
Explanation:
Only two moves are needed (remember each move increments or decrements one element):
[1,2,3]  =>  [2,2,3]  =>  [2,2,2]

Example 2:

Input: nums = [1,10,2,9]
Output: 16

 

Constraints:

  • n == nums.length
  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109
================================================ FILE: 47-permutations-ii/47-permutations-ii.java ================================================ class Solution { List> lists; boolean[] added; public List> permuteUnique(int[] nums) { lists = new ArrayList<>(); Arrays.sort(nums); added = new boolean[nums.length]; permuteUnique(nums, new ArrayList<>()); return lists; } private void permuteUnique(int[] nums, List list) { if(list.size() == nums.length) { lists.add(new ArrayList(list)); return; } for(int i = 0; i < nums.length; i++) { if(added[i]) continue; // avoid permute duplicates if(i > 0 && nums[i] == nums[i - 1] && !added[i - 1]) continue; list.add(nums[i]); added[i] = true; permuteUnique(nums, list); list.remove(list.size() - 1); added[i] = false; } } } ================================================ FILE: 47-permutations-ii/NOTES.md ================================================ ​ ================================================ FILE: 47-permutations-ii/README.md ================================================

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
================================================ FILE: 473-matchsticks-to-square/473-matchsticks-to-square.java ================================================ import java.util.HashMap; class Solution { // The memoization cache to be used during recursion. public HashMap, Boolean> memo; // Array containing our matchsticks. public int[] nums; // Possible side of our square depending on the total sum of all the matchsticks.  public int possibleSquareSide; // Default constructor to initialise our memo cache. public Solution() { this.memo = new HashMap, Boolean>(); } // Main DP function. public boolean recurse(Integer mask, Integer sidesDone) { int total = 0; int L = this.nums.length; // The memo key for this recursion Pair memoKey = new Pair(mask, sidesDone); // Find out the sum of matchsticks used till now. for(int i = L - 1; i >= 0; i--) { if ((mask&(1 << i)) == 0) { total += this.nums[L - 1 - i]; } } // If the sum if divisible by our square's side, then we increment our number of complete sides formed variable. if (total > 0 && total % this.possibleSquareSide == 0) { sidesDone++; } // Base case. if (sidesDone == 3) { return true; } // Return precomputed results if (this.memo.containsKey(memoKey)) { return this.memo.get(memoKey); } boolean ans = false; int c = total / this.possibleSquareSide; // Remaining vlength in the current partially formed side. int rem = this.possibleSquareSide * (c + 1) - total; // Try out all remaining options (that are valid) for(int i = L - 1; i >= 0; i--) { if (this.nums[L - 1 - i] <= rem && (mask&(1 << i)) > 0) { if (this.recurse(mask ^ (1 << i), sidesDone)) { ans = true; break; } } } // Cache the computed results. this.memo.put(memoKey, ans); return ans; } public boolean makesquare(int[] nums) { // Empty matchsticks. if (nums == null || nums.length == 0) { return false; } // Find the perimeter of the square (if at all possible) int L = nums.length; int perimeter = 0; for(int i = 0; i < L; i++) { perimeter += nums[i]; } int possibleSquareSide = perimeter / 4; if (possibleSquareSide * 4 != perimeter) { return false; } this.nums = nums; this.possibleSquareSide = possibleSquareSide; return this.recurse((1 << L) - 1, 0); } } ================================================ FILE: 473-matchsticks-to-square/NOTES.md ================================================ ​ ================================================ FILE: 473-matchsticks-to-square/README.md ================================================

473. Matchsticks to Square

Medium


You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.

Return true if you can make this square and false otherwise.

 

Example 1:

Input: matchsticks = [1,1,2,2,2]
Output: true
Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.

Example 2:

Input: matchsticks = [3,3,3,3,4]
Output: false
Explanation: You cannot find a way to form a square with all the matchsticks.

 

Constraints:

  • 1 <= matchsticks.length <= 15
  • 1 <= matchsticks[i] <= 108
================================================ FILE: 474-ones-and-zeroes/474-ones-and-zeroes.java ================================================ class Solution { public static int findMaxForm(String[] strs, int m, int n) { int[][] dp = new int[m + 1][n + 1]; for(String str : strs){ int one = 0; int zero = 0; for(char c : str.toCharArray()){ if(c == '1') one++; else zero++; } for(int i = m; i >= zero; i--){ for(int j = n; j >= one; j--){ if(one <= j && zero <= i) dp[i][j] = Math.max(dp[i][j],dp[i - zero][j - one] + 1); } } } return dp[m][n]; } } ================================================ FILE: 474-ones-and-zeroes/NOTES.md ================================================ ​ ================================================ FILE: 474-ones-and-zeroes/README.md ================================================

474. Ones and Zeroes

Medium


You are given an array of binary strings strs and two integers m and n.

Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset.

A set x is a subset of a set y if all elements of x are also elements of y.

 

Example 1:

Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3
Output: 4
Explanation: The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.

Example 2:

Input: strs = ["10","0","1"], m = 1, n = 1
Output: 2
Explanation: The largest subset is {"0", "1"}, so the answer is 2.

 

Constraints:

  • 1 <= strs.length <= 600
  • 1 <= strs[i].length <= 100
  • strs[i] consists only of digits '0' and '1'.
  • 1 <= m, n <= 100
================================================ FILE: 48-rotate-image/48-Rotate-Image.cpp ================================================ class Solution { public: void rotate(vector>& mat) { int n = mat.size(); int m = mat[0].size(); 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
================================================ FILE: 5-longest-palindromic-substring/5-longest-palindromic-substring.java ================================================ class Solution { public String longestPalindrome(String s) { int n = s.length(); boolean dp[][] = new boolean[n][n]; int start = 0,end = 0; for(int gap = 0;gap < n;gap++){ for(int i = 0,j = gap;i< n && j < n;i++,j++){ if(gap == 0){ dp[i][j] = true; }else if(gap == 1){ if(s.charAt(i) == s.charAt(j)){ dp[i][j] = true; }else{ dp[i][j] = false; } }else{ if(s.charAt(i) == s.charAt(j) && dp[i+1][j-1] == true){ dp[i][j] = true; }else{ dp[i][j] = false; } } if(dp[i][j] == true){ if(j-i > end - start){ start = i; end = j; } } } } return s.substring(start,end + 1); } } ================================================ FILE: 5-longest-palindromic-substring/NOTES.md ================================================ ​ ================================================ FILE: 5-longest-palindromic-substring/README.md ================================================

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.
================================================ FILE: 50-powx-n/50-powx-n.java ================================================ class Solution { public double myPow(double x, int n) { if(n == 0) return (double)1; if(n < 0){ return 1 / x * myPow(1 / x , -(n + 1)); } return (n % 2 == 0 ? myPow(x * x , n / 2) : x * myPow(x * x , n / 2)); } } ================================================ FILE: 50-powx-n/NOTES.md ================================================ ​ ================================================ FILE: 50-powx-n/README.md ================================================

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
================================================ FILE: 509-fibonacci-number/509-fibonacci-number.java ================================================ class Solution{ static long mod = 1000000007; long[][] multiply(long [][]m1, long[][]m2){ long ans[][] =new long[2][2]; for(int i=0;i<2;i++) for(int j=0;j<2;j++) for(int k=0;k<2;k++) ans[i][j] += (m1[i][k]*m2[k][j])%mod; return ans; } long[][] matPow(long [][]mat,long n){ if(n == 1)return mat; long[][] ans = matPow(mat,n/2); ans = multiply(ans,ans); if((n&1) == 1)ans = multiply(ans,mat); return ans; } public int fib(int N){ long n = N; if(n==1 || n==0)return N; long mat[][] = {{1,1},{1,0}}; mat = matPow(mat,n-1); return (int) (mat[0][0]%mod); } } ================================================ FILE: 509-fibonacci-number/NOTES.md ================================================ ​ ================================================ FILE: 509-fibonacci-number/README.md ================================================

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
================================================ FILE: 51-n-queens/51-n-queens.java ================================================ class Solution { public List> solveNQueens(int n) { char[][] board=new char[n][n]; for(int i=0;i> res=new ArrayList<>(); solve(res, 0,board, leftRow, upperDiagonal, lowerDiagonal); return res; } public static void solve(List> res, int col, char[][] board, int[] leftRow, int[] upperDiagonal, int[] lowerDiagonal) { int n=board.length; if(col==n){ res.add(construct(board)); return; } for(int row=0;row construct(char[][] board){ List fans=new ArrayList<>(); for(int i=0;i51. 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
================================================ FILE: 52-n-queens-ii/52-n-queens-ii.java ================================================ class Solution { int count; public int totalNQueens(int n) { boolean[][]board=new boolean[n][n]; dfs(board,0); return count; } public void dfs(boolean[][]board,int row){ if(row==board.length){ count++; return; } for(int col=0;col52. 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
================================================ FILE: 53-maximum-subarray/53-maximum-subarray.java ================================================ class Solution { public int maxSubArray(int[] nums) { int max=Integer.MIN_VALUE; int temp=0; for(int i=0;imax)max=temp; if(temp<0)temp=0; } return max; } } ================================================ FILE: 53-maximum-subarray/Maximum Subarray.py ================================================ class Solution: def maxSubArray(self, nums: List[int]) -> int: current = 0 maxsum = nums[0] for i in range(len(nums)): current += nums[i] if current>maxsum: maxsum = current if current < 0: current = 0 return maxsum ================================================ FILE: 53-maximum-subarray/NOTES.md ================================================ ​ ================================================ FILE: 53-maximum-subarray/README.md ================================================

53. 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.

================================================ FILE: 535-encode-and-decode-tinyurl/535-encode-and-decode-tinyurl.java ================================================ public class Codec { // Encodes a URL to a shortened URL. public String encode(String s) { return s; } // Decodes a shortened URL to its original URL. public String decode(String s) { return s; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(url)); ================================================ FILE: 535-encode-and-decode-tinyurl/NOTES.md ================================================ ​ ================================================ FILE: 535-encode-and-decode-tinyurl/README.md ================================================

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.
================================================ FILE: 538-convert-bst-to-greater-tree/538-convert-bst-to-greater-tree.java ================================================ class Solution { int sum=0; public TreeNode convertBST(TreeNode root) { if(root==null) return null; convertBST(root.right); sum+=root.val; root.val=sum; convertBST(root.left); return root; } } ================================================ FILE: 538-convert-bst-to-greater-tree/NOTES.md ================================================ ​ ================================================ FILE: 538-convert-bst-to-greater-tree/README.md ================================================

538. Convert BST to Greater 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 the 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.

 

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]

 

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -104 <= Node.val <= 104
  • All the values in the tree are unique.
  • root is guaranteed to be a valid binary search tree.

 

Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/

================================================ FILE: 541-reverse-string-ii/541-reverse-string-ii.java ================================================ class Solution { public String reverseStr(String s, int k) { StringBuilder sb=new StringBuilder(); int i=0; if(k>s.length()) return sb.append(s).reverse().toString(); boolean flag=true; for(i=0;i541. Reverse String II

Easy


Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.

 

Example 1:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Example 2:

Input: s = "abcd", k = 2
Output: "bacd"

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of only lowercase English letters.
  • 1 <= k <= 104
================================================ FILE: 557 Reverse Words in a String III easy lc s22.cpp ================================================ #include using namespace std; class Solution { public: // 2 -pointer tech TC: O(N) -outer loops iterate over N chars to find start & end idx of every word, reverse word also iterates N times to perform N/2 swaps. thus , TC is O(N+N) = O(N) // SC: O(1) using const extra space to track last space idx string reverseWords(string s) { int lastSpaceIndex = -1; int len = (int)s.size(); for(int i = 0; i <= len; i++){ if(i== len || s[i] == ' '){ int start_i = lastSpaceIndex +1; int end_i = i-1; while(start_i < end_i){ char temp = s[start_i]; s[start_i] = s[end_i]; s[end_i] = temp; start_i++; end_i--; } lastSpaceIndex = i; } } return s; } }; ================================================ FILE: 557-reverse-words-in-a-string-iii/557-reverse-words-in-a-string-iii.java ================================================ class Solution { public String reverseWords(String sy) { String[] arr=sy.split(" "); for(int i=0;i& nums, int k) { unordered_map mp; int sum=0, ans=0; mp[sum] = 1; // we always have one subarray with sum 0 for(auto it : nums){ sum += it; // prefix sum if(mp.find(sum - k) != mp.end()) ans += mp[sum - k]; mp[sum]++; } return ans; } }; ================================================ FILE: 576-out-of-boundary-paths/576-out-of-boundary-paths.java ================================================ class Solution { int[][][] cache; int MOD = 1000_000_007; public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { cache = new int[m][n][maxMove + 1]; for(int[][] cc : cache) { for(int[] c : cc) { Arrays.fill(c, -1); } } return f(m, n, maxMove, startRow, startColumn); } int f(int m, int n, int max, int r, int c) { if(r < 0 || c < 0 || r == m || c == n) { return 1; } if(max == 0) { return 0; } if(cache[r][c][max] > -1) { return cache[r][c][max]; } long l = f(m, n, max - 1, r - 1, c) % MOD; l += f(m, n, max - 1, r + 1, c) % MOD; l += f(m, n, max - 1, r, c + 1) % MOD; l += f(m, n, max - 1, r, c - 1) % MOD; cache[r][c][max] = (int)(l % MOD); return cache[r][c][max]; } } ================================================ FILE: 576-out-of-boundary-paths/NOTES.md ================================================ ​ ================================================ FILE: 576-out-of-boundary-paths/README.md ================================================

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
================================================ FILE: 581-shortest-unsorted-continuous-subarray/581-shortest-unsorted-continuous-subarray.java ================================================ public class Solution { public int findUnsortedSubarray(int[] nums) { int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; boolean flag = false; for (int i = 1; i < nums.length; i++) { if (nums[i] < nums[i - 1]) flag = true; if (flag) min = Math.min(min, nums[i]); } flag = false; for (int i = nums.length - 2; i >= 0; i--) { if (nums[i] > nums[i + 1]) flag = true; if (flag) max = Math.max(max, nums[i]); } int l, r; for (l = 0; l < nums.length; l++) { if (min < nums[l]) break; } for (r = nums.length - 1; r >= 0; r--) { if (max > nums[r]) break; } return r - l < 0 ? 0 : r - l + 1; } } ================================================ FILE: 581-shortest-unsorted-continuous-subarray/NOTES.md ================================================ ​ ================================================ FILE: 581-shortest-unsorted-continuous-subarray/README.md ================================================

581. Shortest Unsorted Continuous Subarray

Medium


Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.

Return the shortest such subarray and output its length.

 

Example 1:

Input: nums = [2,6,4,8,10,9,15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

Example 2:

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

Example 3:

Input: nums = [1]
Output: 0

 

Constraints:

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

 

Follow up: Can you solve it in O(n) time complexity?
================================================ FILE: 583-delete-operation-for-two-strings/583-delete-operation-for-two-strings.java ================================================ class Solution { public int minDistance(String word1, String word2) { char[] s1= word1.toCharArray(); char[] s2 = word2.toCharArray(); int[][] DP = new int[s1.length+1][s2.length+1]; for (int i=s1.length-1;i>=0;--i){ for (int j=s2.length-1;j>=0;--j){ if(s1[i] == s2[j]){ DP[i][j]= 1+ DP[i+1][j+1]; }else{ DP[i][j]=Math.max(DP[i+1][j],DP[i][j+1]); } } } return word1.length()+word2.length()-(2*DP[0][0]); } } ================================================ FILE: 583-delete-operation-for-two-strings/NOTES.md ================================================ ​ ================================================ FILE: 583-delete-operation-for-two-strings/README.md ================================================

583. Delete Operation for Two Strings

Medium


Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.

In one step, you can delete exactly one character in either string.

 

Example 1:

Input: word1 = "sea", word2 = "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

Example 2:

Input: word1 = "leetcode", word2 = "etco"
Output: 4

 

Constraints:

  • 1 <= word1.length, word2.length <= 500
  • word1 and word2 consist of only lowercase English letters.
================================================ FILE: 59-spiral-matrix-ii/59-spiral-matrix-ii.java ================================================ class Solution { public int[][] generateMatrix(int n) { int ans[][] = new int[n][n]; fillMatrix(ans, 0 , 0, 1,'r'); return ans; } public void fillMatrix(int [][]ans, int i, int j, int cur, char dir){ if(i < 0 || j < 0 || i >=ans.length || j >= ans.length) return; if(ans[i][j] != 0) return; ans[i][j] = cur; if(dir == 'u'){ fillMatrix(ans, i-1,j,cur+1, 'u'); } fillMatrix(ans, i,j+1,cur+1, 'r'); fillMatrix(ans, i+1,j,cur+1, 'd'); fillMatrix(ans, i,j-1,cur+1, 'l'); fillMatrix(ans, i-1,j,cur+1, 'u'); } } ================================================ FILE: 59-spiral-matrix-ii/NOTES.md ================================================ ​ ================================================ FILE: 59-spiral-matrix-ii/README.md ================================================

59. Spiral Matrix II

Medium


Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

 

Example 1:

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

Example 2:

Input: n = 1
Output: [[1]]

 

Constraints:

  • 1 <= n <= 20
================================================ FILE: 6-zigzag-conversion/6-zigzag-conversion.java ================================================ class Solution { public String convert(String s, int numRows) { int strlen = s.length(); int n = numRows; StringBuilder sub = new StringBuilder(); if(n==1 || n > strlen) { return s; } for (int i = 0; i < n; i++) { int k = i; if(i==0 || i == n-1) { while(k6. Zigzag Conversion

Medium


The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

 

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P     I    N
A   L S  I G
Y A   H R
P     I

Example 3:

Input: s = "A", numRows = 1
Output: "A"

 

Constraints:

  • 1 <= s.length <= 1000
  • s consists of English letters (lower-case and upper-case), ',' and '.'.
  • 1 <= numRows <= 1000
================================================ FILE: 606-construct-string-from-binary-tree/606-construct-string-from-binary-tree.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { StringBuilder sb; public String tree2str(TreeNode root) { sb=new StringBuilder(); dfs(root); return sb.toString(); } public void dfs(TreeNode root){ if(root==null)return; sb.append(root.val); if(root.left==null && root.right==null)return; sb.append("("); dfs(root.left); sb.append(")"); if(root.right!=null){ sb.append("("); dfs(root.right); sb.append(")"); } } } ================================================ FILE: 606-construct-string-from-binary-tree/NOTES.md ================================================ ​ ================================================ FILE: 606-construct-string-from-binary-tree/README.md ================================================

606. Construct String from Binary Tree

Easy


Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.

Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.

 

Example 1:

Input: root = [1,2,3,4]
Output: "1(2(4))(3)"
Explanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)"

Example 2:

Input: root = [1,2,3,null,4]
Output: "1(2()(4))(3)"
Explanation: Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -1000 <= Node.val <= 1000
================================================ FILE: 609 Find Duplicate File in System lc med s19.cpp ================================================ #include using namespace std; class Solution { public: vector split(string str, char delim) { string line; vector res; stringstream ss(str); while (getline(ss, line, delim)) res.push_back(line); return res; } vector> findDuplicate(vector& paths) { vector> ans; unordered_map> m; for (auto p : paths) { vector path = split(p, ' '); string directoryPath; for (int i = 0; i < path.size(); i++) { if (i == 0) { directoryPath = path[i]; } else { string fileName = path[i].substr(0, path[i].find('(')); string fileContent = path[i].substr(path[i].find('(') + 1, path[i].find(')') - path[i].find('(') - 1); m[fileContent].push_back(directoryPath + "/" + fileName); } } } for (auto x : m) { if (x.second.size() > 1) { ans.push_back(x.second); } } return ans; } }; ================================================ FILE: 609-find-duplicate-file-in-system/609-find-duplicate-file-in-system.java ================================================ class Solution { public List> findDuplicate(String[] paths) { Map> map = new HashMap<>(); List> res = new ArrayList<>(); for(int i = 0; i < paths.length; i++){ String s = paths[i]; String[] str = s.split(" "); String prefix = str[0] + "/"; for(int j = 1; j < str.length; j++){ String nc = str[j]; int t = nc.length() - 1; while(t >= 0 && nc.charAt(t) != '(') t--; String name = nc.substring(0, t); String content = nc.substring(t + 1, nc.length() - 1); map.computeIfAbsent(content, a -> new ArrayList<>()); map.get(content).add(prefix + name); } } for(String key: map.keySet()){ if(map.get(key).size() > 1){ res.add(map.get(key)); } } return(res); } } ================================================ FILE: 609-find-duplicate-file-in-system/NOTES.md ================================================ ​ ================================================ FILE: 609-find-duplicate-file-in-system/README.md ================================================

609. Find Duplicate File in System

Medium


Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.

A group of duplicate files consists of at least two files that have the same content.

A single directory info string in the input list has the following format:

  • "root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"

It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory "root/d1/d2/.../dm". Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.

The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:

  • "directory_path/file_name.txt"

 

Example 1:

Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"]
Output: [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]]

Example 2:

Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"]
Output: [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]]

 

Constraints:

  • 1 <= paths.length <= 2 * 104
  • 1 <= paths[i].length <= 3000
  • 1 <= sum(paths[i].length) <= 5 * 105
  • paths[i] consist of English letters, digits, '/', '.', '(', ')', and ' '.
  • You may assume no files or directories share the same name in the same directory.
  • You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.

 

Follow up:

  • Imagine you are given a real file system, how will you search files? DFS or BFS?
  • If the file content is very large (GB level), how will you modify your solution?
  • If you can only read the file by 1kb each time, how will you modify your solution?
  • What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?
  • How to make sure the duplicated files you find are not false positive?
================================================ FILE: 62-unique-paths/62-unique-paths.java ================================================ class Solution { public int uniquePaths(int m, int n) { int[][] dp = new int[m+1][n+1]; return helper(m, n, dp); } private int helper(int m, int n, int[][] dp) { if(m<1 || n<1) return 0; if(m == 1 || n == 1) return 1; if(dp[m][n] != 0) return dp[m][n]; dp[m][n] = helper(m, n-1, dp) + helper(m-1, n, dp); return dp[m][n]; } } ================================================ FILE: 62-unique-paths/NOTES.md ================================================ ​ ================================================ FILE: 62-unique-paths/README.md ================================================

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
================================================ FILE: 622-design-circular-queue/622-design-circular-queue.java ================================================ class MyCircularQueue { int[] queue; int size; int used; int front; int rear; public MyCircularQueue(int k) { queue = new int[k]; size = k; } public boolean enQueue(int value) { if(isFull()) return false; queue[rear] = value; rear = (rear+1)%size; used++; return true; } public boolean deQueue() { if(isEmpty()) return false; front = (front+1)%size; used -- ; return true; } public int Front() { if(isEmpty()) return -1; return queue[front]; } public int Rear() { if(isEmpty()) return -1; return queue[(rear-1+size)%size]; } public boolean isEmpty() { return used ==0; } public boolean isFull() { return used == size; } } ================================================ FILE: 622-design-circular-queue/NOTES.md ================================================ ​ ================================================ FILE: 622-design-circular-queue/README.md ================================================

622. Design Circular Queue

Medium


Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".

One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.

Implementation the MyCircularQueue class:

  • MyCircularQueue(k) Initializes the object with the size of the queue to be k.
  • int Front() Gets the front item from the queue. If the queue is empty, return -1.
  • int Rear() Gets the last item from the queue. If the queue is empty, return -1.
  • boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful.
  • boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.
  • boolean isEmpty() Checks whether the circular queue is empty or not.
  • boolean isFull() Checks whether the circular queue is full or not.

You must solve the problem without using the built-in queue data structure in your programming language. 

 

Example 1:

Input
["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"]
[[3], [1], [2], [3], [4], [], [], [], [4], []]
Output
[null, true, true, true, false, 3, true, true, true, 4]

Explanation
MyCircularQueue myCircularQueue = new MyCircularQueue(3);
myCircularQueue.enQueue(1); // return True
myCircularQueue.enQueue(2); // return True
myCircularQueue.enQueue(3); // return True
myCircularQueue.enQueue(4); // return False
myCircularQueue.Rear();     // return 3
myCircularQueue.isFull();   // return True
myCircularQueue.deQueue();  // return True
myCircularQueue.enQueue(4); // return True
myCircularQueue.Rear();     // return 4

 

Constraints:

  • 1 <= k <= 1000
  • 0 <= value <= 1000
  • At most 3000 calls will be made to enQueue, deQueueFrontRearisEmpty, and isFull.
================================================ FILE: 623-add-one-row-to-tree/623-add-one-row-to-tree.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode addOneRow(TreeNode root, int val, int depth) { if(depth==1){ TreeNode head=new TreeNode(val); head.left=root; return head; } dfs(root,val,depth-1); return root; } public void dfs(TreeNode root,int val,int depth){ if(depth==1){ TreeNode lefty=root.left; TreeNode righty=root.right; TreeNode newLeft=new TreeNode(val); TreeNode newRight=new TreeNode(val); newLeft.left=lefty; root.left=newLeft; newRight.right=righty; root.right=newRight; return; } if(root.left!=null)dfs(root.left,val,depth-1); if(root.right!=null)dfs(root.right,val,depth-1); } } ================================================ FILE: 623-add-one-row-to-tree/NOTES.md ================================================ ​ ================================================ FILE: 623-add-one-row-to-tree/README.md ================================================

623. Add One Row to Tree

Medium


Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.

Note that the root node is at depth 1.

The adding rule is:

  • Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.
  • cur's original left subtree should be the left subtree of the new left subtree root.
  • cur's original right subtree should be the right subtree of the new right subtree root.
  • If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.

 

Example 1:

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

Example 2:

Input: root = [4,2,null,3,1], val = 1, depth = 3
Output: [4,2,null,1,1,3,null,null,1]

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • The depth of the tree is in the range [1, 104].
  • -100 <= Node.val <= 100
  • -105 <= val <= 105
  • 1 <= depth <= the depth of tree + 1
================================================ FILE: 629-k-inverse-pairs-array/629-k-inverse-pairs-array.java ================================================ public class Solution { public int kInversePairs(int n, int k) { int[][] dp = new int[n + 1][k + 1]; int M = 1000000007; for (int i = 1; i <= n; i++) { for (int j = 0; j <= k; j++) { if (j == 0) dp[i][j] = 1; else { int val = (dp[i - 1][j] + M - ((j - i) >= 0 ? dp[i - 1][j - i] : 0)) % M; dp[i][j] = (dp[i][j - 1] + val) % M; } } } return ((dp[n][k] + M - (k > 0 ? dp[n][k - 1] : 0)) % M); } } ================================================ FILE: 629-k-inverse-pairs-array/NOTES.md ================================================ ​ ================================================ FILE: 629-k-inverse-pairs-array/README.md ================================================

629. K Inverse Pairs Array

Hard


For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j].

Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 109 + 7.

 

Example 1:

Input: n = 3, k = 0
Output: 1
Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.

Example 2:

Input: n = 3, k = 1
Output: 2
Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.

 

Constraints:

  • 1 <= n <= 1000
  • 0 <= k <= 1000
================================================ FILE: 63-unique-paths-ii/63-unique-paths-ii.java ================================================ class Solution { public int uniquePathsWithObstacles(int[][] a) { int result = 0; int m = a.length; int n = a[0].length; int[] row = new int[n]; int prevCol; row[0] = 1 - a[0][0]; for (int i = 1; i < n; ++i) { if (a[0][i] == 1 || a[0][i-1] == 1) { row[i] = 0; continue; } row[i] = row[i-1]; } for (int i = 1; i < m; ++i) { if (a[i-1][0] == 1 || a[i][0] == 1) { row[0] = 0; } for (int j = 1; j < n; ++j) { if (a[i][j] == 1) { row[j] = 0; continue; } int tmp = 0; if (a[i-1][j] != 1) { tmp += row[j]; } if (a[i][j-1] != 1) { tmp += row[j-1]; } row[j] = tmp; } } return row[n-1]; } } ================================================ FILE: 63-unique-paths-ii/NOTES.md ================================================ ​ ================================================ FILE: 63-unique-paths-ii/README.md ================================================

63. Unique Paths II

Medium


You are given an m x n integer array grid. There is a robot 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.

An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle.

Return the number of possible unique paths that the robot can take to reach the bottom-right corner.

The testcases are generated so that the answer will be less than or equal to 2 * 109.

 

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.
================================================ FILE: 630-course-schedule-iii/630-course-schedule-iii.java ================================================ public class Solution { public int scheduleCourse(int[][] courses) { Arrays.sort(courses, (a, b) -> a[1] - b[1]); PriorityQueue < Integer > queue = new PriorityQueue < > ((a, b) -> b - a); int time = 0; for (int[] c: courses) { if (time + c[0] <= c[1]) { queue.offer(c[0]); time += c[0]; } else if (!queue.isEmpty() && queue.peek() > c[0]) { time += c[0] - queue.poll(); queue.offer(c[0]); } } return queue.size(); } } ================================================ FILE: 630-course-schedule-iii/README.md ================================================

630. Course Schedule III

Hard


There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi.

You will start on the 1st day and you cannot take two or more courses simultaneously.

Return the maximum number of courses that you can take.

 

Example 1:

Input: courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]
Output: 3
Explanation: 
There are totally 4 courses, but you can take 3 courses at most:
First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.
Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. 
Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. 
The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.

Example 2:

Input: courses = [[1,2]]
Output: 1

Example 3:

Input: courses = [[3,2],[4,3]]
Output: 0

 

Constraints:

  • 1 <= courses.length <= 104
  • 1 <= durationi, lastDayi <= 104
================================================ FILE: 637-average-of-levels-in-binary-tree/637-average-of-levels-in-binary-tree.cpp ================================================ class Solution { public: vector averageOfLevels(TreeNode* root) { queue q; q.push(root); vector v; while(!q.empty()){ int n = q.size(); double d=0; for(int i=0;ileft) q.push(node->left); if(node->right) q.push(node->right); q.pop(); d += node->val; } v.push_back(d/n); } return v; } }; // Same approach: // class Solution { // public: // vector ans; // void getAverage(TreeNode *root){ // queue q; // q.push(root); // while(!q.empty()){ // double size = q.size(); // double sum = 0; // for(int i = 0; i < size; i++){ // auto node = q.front(); // q.pop(); // sum += node->val; // if(node->left) // q.push(node->left); // if(node->right) // q.push(node->right); // } // ans.push_back(sum / size); // } // } // vector averageOfLevels(TreeNode* root) { // getAverage(root); // return ans; // } // }; ================================================ FILE: 637-average-of-levels-in-binary-tree/637-average-of-levels-in-binary-tree.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List averageOfLevels(TreeNode root) { List ans=new ArrayList<>(); Queue q=new LinkedList<>(); q.add(root); while(q.size()>0){ int sz=q.size(); int siz=sz; Double avg=0.00; while(siz-->0){ TreeNode curr=q.remove(); if(curr.left!=null)q.add(curr.left); if(curr.right!=null)q.add(curr.right); avg+=curr.val; } avg/=sz; ans.add(avg); } return ans; } } ================================================ FILE: 637-average-of-levels-in-binary-tree/README.md ================================================

637. Average of Levels in Binary Tree

Easy


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

 

Example 1:

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

Example 2:

Input: root = [3,9,20,15,7]
Output: [3.00000,14.50000,11.00000]

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -231 <= Node.val <= 231 - 1
================================================ FILE: 637-average-of-levels-in-binary-tree.py ================================================ class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: quene = [] res = [] quene.append(root) while(quene): qlen = len(quene) tmp = 0 for i in range(qlen): node = quene.pop(0) tmp += node.val if node.left: quene.append(node.left) if node.right: quene.append(node.right) res.append(tmp/qlen) return res ================================================ FILE: 647-palindromic-substrings/647-palindromic-substrings.java ================================================ class Solution { public int countSubstrings(String s) { char[] cs = s.toCharArray(); int res = 0; for(int i = 0;i= 0 && b < s.length(); a --, b ++){ if(cs[a] != cs[b]) break; res++; } //even cases for(int a = i, b = i + 1; a >= 0 && b < s.length(); a --, b ++){ if(cs[a] != cs[b]) break; res ++; } } return res; } } ================================================ FILE: 647-palindromic-substrings/NOTES.md ================================================ ​ ================================================ FILE: 653-two-sum-iv-input-is-a-bst/653-two-sum-iv-input-is-a-bst.java ================================================ public class Solution { public boolean findTarget(TreeNode root, int k) { return dfs(root, root, k); } private boolean dfs(TreeNode root, TreeNode cur, int target) { if(cur == null) return false; return search(root, cur, target - cur.val) || dfs(root, cur.left, target) || dfs(root, cur.right, target); } private boolean search(TreeNode root, TreeNode cur, int target) { if(root == null) return false; return (root.val == target && cur != root)|| (target > root.val && search(root.right, cur, target)) || (target < root.val && search(root.left, cur, target)); } } ================================================ FILE: 653-two-sum-iv-input-is-a-bst/NOTES.md ================================================ ​ ================================================ FILE: 653-two-sum-iv-input-is-a-bst/README.md ================================================

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

 

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
================================================ FILE: 658-find-k-closest-elements/658-find-k-closest-elements.java ================================================ class Solution { public List findClosestElements(int[] arr, int k, int x) { List ans=new ArrayList<>(); int idx=binSea(arr,x); int l=idx; int h=idx; while(k>0){ if(l==h){ ans.add(arr[l]); k--; l--; h++; }else{ int lefty=l<0?Integer.MAX_VALUE:Math.abs(x-arr[l]); int righty=hrighty){ ans.add(arr[h]); h++; k--; }else{ ans.add(arr[l]); l--; k--; } } } Collections.sort(ans); return ans; } public int binSea(int[]arr,int x){ int diff=Integer.MAX_VALUE; int idx=-1; for(int i=0;i658. Find K Closest Elements

Medium


Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.

An integer a is closer to x than an integer b if:

  • |a - x| < |b - x|, or
  • |a - x| == |b - x| and a < b

 

Example 1:

Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]

Example 2:

Input: arr = [1,2,3,4,5], k = 4, x = -1
Output: [1,2,3,4]

 

Constraints:

  • 1 <= k <= arr.length
  • 1 <= arr.length <= 104
  • arr is sorted in ascending order.
  • -104 <= arr[i], x <= 104
================================================ FILE: 659-split-array-into-consecutive-subsequences/659-split-array-into-consecutive-subsequences.cpp ================================================ class Solution { public: bool isPossible(vector& nums) { unordered_map available, required; for(int it : nums) available[it]++; for(int it : nums) { if(available[it] <= 0) continue; else if(required[it] > 0) { available[it]--; required[it]--; required[it+1]++; } else if(available[it] > 0 and available[it+1] > 0 and available[it+2] > 0) { available[it]--; available[it+1]--; available[it+2]--; required[it+3]++; } else return false; } return true; } }; ================================================ FILE: 659-split-array-into-consecutive-subsequences/659-split-array-into-consecutive-subsequences.java ================================================ class Solution { public boolean isPossible(int[] nums) { Mapcount=new HashMap<>(); for(int i:nums){ count.put(i,count.getOrDefault(i,0)+1); } Map end=new HashMap<>(); for(int i:nums){ if(count.get(i)>0){ count.put(i,count.get(i)-1); if(end.containsKey(i-1) && end.get(i-1)>0){ end.put(i,end.getOrDefault(i,0)+1); end.put(i-1,end.get(i-1)-1); }else if(count.containsKey(i+1) && count.containsKey(i+2) && count.get(i+1)>0 && count.get(i+2)>0){ count.put(i+1,count.get(i+1)-1); count.put(i+2,count.get(i+2)-1); end.put(i+2,end.getOrDefault(i+2,0)+1); }else{ return false; } } } return true; } } ================================================ FILE: 659-split-array-into-consecutive-subsequences/NOTES.md ================================================ ​ ================================================ FILE: 659-split-array-into-consecutive-subsequences/README.md ================================================

659. Split Array into Consecutive Subsequences

Medium


You are given an integer array nums that is sorted in non-decreasing order.

Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true:

  • Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).
  • All subsequences have a length of 3 or more.

Return true if you can split nums according to the above conditions, or false otherwise.

A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).

 

Example 1:

Input: nums = [1,2,3,3,4,5]
Output: true
Explanation: nums can be split into the following subsequences:
[1,2,3,3,4,5] --> 1, 2, 3
[1,2,3,3,4,5] --> 3, 4, 5

Example 2:

Input: nums = [1,2,3,3,4,4,5,5]
Output: true
Explanation: nums can be split into the following subsequences:
[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5
[1,2,3,3,4,4,5,5] --> 3, 4, 5

Example 3:

Input: nums = [1,2,3,4,4,5]
Output: false
Explanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.

 

Constraints:

  • 1 <= nums.length <= 104
  • -1000 <= nums[i] <= 1000
  • nums is sorted in non-decreasing order.
================================================ FILE: 665-non-decreasing-array/665-non-decreasing-array.java ================================================ class Solution { public boolean checkPossibility(int[] arr) { int index = helper(arr); if (index == -1) { return true; } int temp = arr[index]; arr[index] = arr[index + 1]; if (helper(arr) == -1) { return true; } arr[index] = temp; arr[index + 1] = temp; if (helper(arr) == -1) { return true; } return false; } public int helper(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { if (arr[i] > arr[i + 1]) { return i; } } return -1; } } ================================================ FILE: 665-non-decreasing-array/NOTES.md ================================================ ​ ================================================ FILE: 665-non-decreasing-array/README.md ================================================

665. Non-decreasing Array

Medium


Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.

We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).

 

Example 1:

Input: nums = [4,2,3]
Output: true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Example 2:

Input: nums = [4,2,1]
Output: false
Explanation: You can't get a non-decreasing array by modify at most one element.

 

Constraints:

  • n == nums.length
  • 1 <= n <= 104
  • -105 <= nums[i] <= 105
================================================ FILE: 669-trim-a-binary-search-tree/669-trim-a-binary-search-tree.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode trimBST(TreeNode root, int low, int high) { if(root==null)return null; if(root.valhigh){ return trimBST(root.left,low,high); } root.left=trimBST(root.left,low,high); root.right=trimBST(root.right,low,high); return root; } } ================================================ FILE: 669-trim-a-binary-search-tree/NOTES.md ================================================ ​ ================================================ FILE: 669-trim-a-binary-search-tree/README.md ================================================

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]

 

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
================================================ FILE: 680-valid-palindrome-ii/680-valid-palindrome-ii.java ================================================ class Solution { public boolean validPalindrome(String s) { int len = s.length(); if(len <= 2) return true; byte[] chars = s.getBytes(); for(int i=0,j=len-1; i680. Valid Palindrome II

Easy


Given a string s, return true if the s can be palindrome after deleting at most one character from it.

 

Example 1:

Input: s = "aba"
Output: true

Example 2:

Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.

Example 3:

Input: s = "abc"
Output: false

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters.
================================================ FILE: 682-baseball-game/682-baseball-game.java ================================================ class Solution { public int calPoints(String[] ops) { Deque st=new ArrayDeque<>(); for(int i=0;i682. Baseball Game

Easy


You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.

At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to the record and is one of the following:

  1. An integer x - Record a new score of x.
  2. "+" - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.
  3. "D" - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.
  4. "C" - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.

Return the sum of all the scores on the record.

 

Example 1:

Input: ops = ["5","2","C","D","+"]
Output: 30
Explanation:
"5" - Add 5 to the record, record is now [5].
"2" - Add 2 to the record, record is now [5, 2].
"C" - Invalidate and remove the previous score, record is now [5].
"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
The total sum is 5 + 10 + 15 = 30.

Example 2:

Input: ops = ["5","-2","4","C","D","9","+","+"]
Output: 27
Explanation:
"5" - Add 5 to the record, record is now [5].
"-2" - Add -2 to the record, record is now [5, -2].
"4" - Add 4 to the record, record is now [5, -2, 4].
"C" - Invalidate and remove the previous score, record is now [5, -2].
"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].
"9" - Add 9 to the record, record is now [5, -2, -4, 9].
"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].
"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].
The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.

Example 3:

Input: ops = ["1"]
Output: 1

 

Constraints:

  • 1 <= ops.length <= 1000
  • ops[i] is "C", "D", "+", or a string representing an integer in the range [-3 * 104, 3 * 104].
  • For operation "+", there will always be at least two previous scores on the record.
  • For operations "C" and "D", there will always be at least one previous score on the record.
================================================ FILE: 695-max-area-of-island/695-max-area-of-island.java ================================================ class Solution { public int maxAreaOfIsland(int[][] grid) { int max=0; for (int i=0;imax) max=area; } } } return max; } public static int iarea(int [][]grid,int i,int j){ if(i=0 && j>=0 && grid[i][j]==1){ grid[i] [j] =0; int up=iarea(grid,i-1,j); int down=iarea(grid, i+1,j); int left=iarea(grid, i,j-1); int right=iarea(grid,i,j+1); return 1+left+right+up+down; } return 0; } } ================================================ FILE: 695-max-area-of-island/NOTES.md ================================================ ​ ================================================ FILE: 695-max-area-of-island/README.md ================================================

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.
================================================ FILE: 695-max-area-of-island/SolutionCode.cpp ================================================ /* Approach: Since we have to find the maximum Island Area, so for if have any square Island we would consider it's adjacent(Top, Bottom, Left, Right), if they have value 1(which will mean it's land), similarily we would check thier adjacent square positions, so on...., now we could observe here that once a land position is picked then we have to continue searching for land positon in all 4 directions of square, after that only total Island area could be found, then we move to another position which is land and also not part of any previous calculated(Traversed) Islands, By Observing above it is quite clear that we need to apply, DFS algorithm. */ // Code Below : class Solution { public: int travelMap(int r, int c, vector> &grid){ if(r<0 || c<0 || r>=grid.size() || c>=grid[0].size() || grid[r][c]==0){ return 0; } // So as to make it marked as visited position. grid[r][c] = 0; // int Down = travelMap(r+1, c, grid); // int Right = travelMap(r, c+1, grid); // int Up = travelMap(r-1, c, grid); // int Left = travelMap(r, c-1, grid); // 1 extra area added for the Area of Current position return 1 + travelMap(r+1, c, grid) + travelMap(r, c+1, grid) + travelMap(r-1, c, grid) + travelMap(r, c-1, grid); } int maxAreaOfIsland(vector>& grid) { int mxArea = 0; for(int i=0;itarget) || (i>0 && sum[i] == sum[i-1]))continue; sum[i]+=arr[ind]; if(dfs(ind-1,arr,sum,k,target))return true; sum[i]-= arr[ind]; } return false; } } ================================================ FILE: 698-partition-to-k-equal-sum-subsets/README.md ================================================

698. Partition to K Equal Sum Subsets

Medium


Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.

 

Example 1:

Input: nums = [4,3,2,3,5,2,1], k = 4
Output: true
Explanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.

Example 2:

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

 

Constraints:

  • 1 <= k <= nums.length <= 16
  • 1 <= nums[i] <= 104
  • The frequency of each element is in the range [1, 4].
================================================ FILE: 7 Segment Display.java ================================================ class Solution { static String sevenSegments(String S, int N) { int sum=0; int nums[]={6,2,5,5,4,5,6,3,7,5}; for(int i=0;i=2*(N-j)){ s1.append("0"); sum-=6; j++; } while(j<=N && sum>0){ sum-=2; if(j==N && sum!=0){ sum+=2; if(sum==5) s1.append("2"); else if(sum==4) s1.append("4"); else if(sum==3) s1.append("7"); else if(sum==7) s1.append("8"); break; } else{ s1.append("1"); } j++; } return s1+""; } }; ================================================ FILE: 70-climbing-stairs/70-climbing-stairs.java ================================================ class Solution { public int climbStairs(int n) { int dp[] = new int[n+1]; dp[n] = 1; for(int i = n; i>=0; i--){ if(i+1<=n){ dp[i] = dp[i+1]; } if(i+2<=n){ dp[i] = dp[i+1] + dp[i+2]; } } return dp[0]; } } ================================================ FILE: 70-climbing-stairs/NOTES.md ================================================ ================================================ FILE: 70-climbing-stairs/README.md ================================================

70. 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
================================================ FILE: 700-search-in-a-binary-search-tree/700-search-in-a-binary-search-tree.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode searchBST(TreeNode root, int val) { if(root==null)return null; if(root.val>val){ return searchBST(root.left,val); }else if(root.val700. 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
================================================ FILE: 703-kth-largest-element-in-a-stream/703-kth-largest-element-in-a-stream.py ================================================ class KthLargest: def __init__(self, k: int, nums: List[int]): self.k=k self.nums=nums def add(self, val: int) -> int: self.nums.append(val) self.nums.sort() return self.nums[len(self.nums)-self.k] # Your KthLargest object will be instantiated and called as such: # obj = KthLargest(k, nums) # param_1 = obj.add(val) ================================================ FILE: 703-kth-largest-element-in-a-stream/NOTES.md ================================================ ​ ================================================ FILE: 704-binary-search/704-binary-search.java ================================================ class Solution { public int search(int[] nums, int target) { int start=0; int end=nums.length-1; while(start<=end){ int mid=(start+end)/2; if(nums[mid]==target){ return mid; }else if(nums[mid]>target){ end=mid-1; }else{ start=mid+1; } } return -1; } } ================================================ FILE: 704-binary-search/NOTES.md ================================================ ​ ================================================ FILE: 704-binary-search/README.md ================================================

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.
================================================ FILE: 705-design-hashset/705-design-hashset.java ================================================ class MyHashSet { boolean[] arr; public MyHashSet() { arr=new boolean[1000001]; } public void add(int key) { arr[key]=true; } public void remove(int key) { arr[key]=false; } public boolean contains(int key) { return arr[key]; } } /** * Your MyHashSet object will be instantiated and called as such: * MyHashSet obj = new MyHashSet(); * obj.add(key); * obj.remove(key); * boolean param_3 = obj.contains(key); */ ================================================ FILE: 705-design-hashset/NOTES.md ================================================ ​ ================================================ FILE: 705-design-hashset/README.md ================================================

705. Design HashSet

Easy


Design a HashSet without using any built-in hash table libraries.

Implement MyHashSet class:

  • void add(key) Inserts the value key into the HashSet.
  • bool contains(key) Returns whether the value key exists in the HashSet or not.
  • void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.

 

Example 1:

Input
["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
[[], [1], [2], [1], [3], [2], [2], [2], [2]]
Output
[null, null, null, true, false, null, true, null, false]

Explanation
MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1);      // set = [1]
myHashSet.add(2);      // set = [1, 2]
myHashSet.contains(1); // return True
myHashSet.contains(3); // return False, (not found)
myHashSet.add(2);      // set = [1, 2]
myHashSet.contains(2); // return True
myHashSet.remove(2);   // set = [1]
myHashSet.contains(2); // return False, (already removed)

 

Constraints:

  • 0 <= key <= 106
  • At most 104 calls will be made to add, remove, and contains.
================================================ FILE: 706-design-hashmap/706-design-hashmap.java ================================================ class MyHashMap { int[]map; public MyHashMap() { map=new int[1000001]; Arrays.fill(map,-1); } public void put(int key, int value) { map[key]=value; } public int get(int key) { if(map[key]==-1)return -1; return map[key]; } public void remove(int key) { map[key]=-1; } } /** * Your MyHashMap object will be instantiated and called as such: * MyHashMap obj = new MyHashMap(); * obj.put(key,value); * int param_2 = obj.get(key); * obj.remove(key); */ ================================================ FILE: 706-design-hashmap/NOTES.md ================================================ ​ ================================================ FILE: 706-design-hashmap/README.md ================================================

706. Design HashMap

Easy


Design a HashMap without using any built-in hash table libraries.

Implement the MyHashMap class:

  • MyHashMap() initializes the object with an empty map.
  • void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.
  • int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
  • void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.

 

Example 1:

Input
["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
Output
[null, null, null, 1, -1, null, 1, null, -1]

Explanation
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // The map is now [[1,1]]
myHashMap.put(2, 2); // The map is now [[1,1], [2,2]]
myHashMap.get(1);    // return 1, The map is now [[1,1], [2,2]]
myHashMap.get(3);    // return -1 (i.e., not found), The map is now [[1,1], [2,2]]
myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)
myHashMap.get(2);    // return 1, The map is now [[1,1], [2,1]]
myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]
myHashMap.get(2);    // return -1 (i.e., not found), The map is now [[1,1]]

 

Constraints:

  • 0 <= key, value <= 106
  • At most 104 calls will be made to put, get, and remove.
================================================ FILE: 713_Subarray_Product_Less_Than_K.cpp ================================================ class Solution { public: int numSubarrayProductLessThanK(vector& n, int k) { if(k<=1){ return 0; } int product=1,j=0,sub=0; for(int i =0;i=k){ product=product/n[j++]; } sub+=i-j+1; } return sub; } }; ================================================ FILE: 718-Maximum-Length-of-Repeated-Subarray.cpp ================================================ int findLength(vector& nums1, vector& nums2) { int n=nums1.size(); int m=nums2.size(); //INITIALIZATION vector>dp(n+1,vector(m+1)); for(int i=0;i> hashes = new HashMap(); int k = 0; for (int x: rolling(A, guess)) { hashes.computeIfAbsent(x, z -> new ArrayList()).add(k++); } int j = 0; for (int x: rolling(B, guess)) { for (int i: hashes.getOrDefault(x, new ArrayList())) if (Arrays.equals(Arrays.copyOfRange(A, i, i+guess), Arrays.copyOfRange(B, j, j+guess))) { return true; } j++; } return false; } public int findLength(int[] A, int[] B) { int lo = 0, hi = Math.min(A.length, B.length) + 1; while (lo < hi) { int mi = (lo + hi) / 2; if (check(mi, A, B)) lo = mi + 1; else hi = mi; } return lo - 1; } } ================================================ FILE: 718-maximum-length-of-repeated-subarray/NOTES.md ================================================ ​ ================================================ FILE: 718-maximum-length-of-repeated-subarray/README.md ================================================

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
================================================ FILE: 718-maximum-length-of-repeated-subarray/Solved Using DP.java ================================================ class Solution { public int findLength(int[] nums1, int[] nums2) { int n = nums1.length; int m = nums2.length; int[][] dp = new int[n+1][m+1]; int ans = 0; for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { if(nums1[i-1]==nums2[j-1]){ dp[i][j] = dp[i-1][j-1] + 1; ans = Math.max(ans, dp[i][j]); } else dp[i][j] = 0; } } return ans; } } ================================================ FILE: 718. Maximum Length of Repeated Subarray/718. Maximum Length of Repeated Subarray.cpp ================================================ class Solution { public: int findLength(vector& nums1, vector& nums2) { // same as longest common substring int n = nums1.size(), m = nums2.size(); int dp[n+1][m+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ if(i==0 || j==0) dp[i][j] = 0; } } int res = 0; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(nums1[i-1] == nums2[j-1]){ dp[i][j] = 1 + dp[i-1][j-1]; res = max(res, dp[i][j]); }else{ dp[i][j] = 0; } } } return res; } }; ================================================ FILE: 718. Maximum Length of Repeated Subarray lc med s20.cpp ================================================ #include using namespace std; class Solution { public: int findLength(vector& nums1, vector& nums2) { // dp space optmized int n = nums1.size(), m = nums2.size(), res = 0; // swap to ensure n >m if(n dp(n+1), dp2(n+1); for(int i = 1; i<=n; i++){ for(int j =1; j<=m; j++){ if(nums1[i-1] == nums2[j-1]){ // extend from the prev dp state dp[j] = dp2[j-1]+1; }else // reset to 0 dp[j] =0; // record the max len res = max(res, dp[j]); } // the curr state now becomes the prev state for nxt round dp2 = dp; } return res; } }; ================================================ FILE: 724-find-pivot-index/724-find-pivot-index.java ================================================ class Solution { public int pivotIndex(int[] nums) { int sum=0; for(int n:nums){ sum+=n; } int left=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/

================================================ FILE: 729-my-calendar-i/729-my-calendar-i.java ================================================ class MyCalendar { class TreeNode{ TreeNode left; TreeNode right; int start; int end; TreeNode(int start,int end){ this.start = start; this.end = end; } } TreeNode root; public MyCalendar() { } public boolean book(int start, int end) { if(root == null){ root = new TreeNode(start,end); return true; } return insert(root,start,end); } private boolean insert(TreeNode root, int start, int end){ if(end <= root.start){ if(root.left == null){ root.left = new TreeNode(start,end); return true; } return insert(root.left,start,end); } if(start >= root.end){ if(root.right == null){ root.right = new TreeNode(start,end); return true; } return insert(root.right,start,end); } return false; } } ================================================ FILE: 729-my-calendar-i/NOTES.md ================================================ 25-31 33-40 47-49 ​ ================================================ FILE: 729-my-calendar-i/README.md ================================================

729. My Calendar I

Medium


You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking.

A double booking happens when two events have some non-empty intersection (i.e., some moment is common to both events.).

The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end.

Implement the MyCalendar class:

  • MyCalendar() Initializes the calendar object.
  • boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false and do not add the event to the calendar.

 

Example 1:

Input
["MyCalendar", "book", "book", "book"]
[[], [10, 20], [15, 25], [20, 30]]
Output
[null, true, false, true]

Explanation
MyCalendar myCalendar = new MyCalendar();
myCalendar.book(10, 20); // return True
myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.
myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.

 

Constraints:

  • 0 <= start < end <= 109
  • At most 1000 calls will be made to book.
================================================ FILE: 732-my-calendar-iii/732-my-calendar-iii.java ================================================ class MyCalendarThree { private Map diff; public MyCalendarThree() { diff = new TreeMap<>(); } public int book(int start, int end) { diff.put(start, diff.getOrDefault(start, 0) + 1); diff.put(end, diff.getOrDefault(end, 0) - 1); int res = 0, cur = 0; for (int delta : diff.values()) { cur += delta; res = Math.max(res, cur); } return res; } } ================================================ FILE: 732-my-calendar-iii/NOTES.md ================================================ ​ ================================================ FILE: 732-my-calendar-iii/README.md ================================================

732. My Calendar III

Hard


A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)

You are given some events [start, end), after each given event, return an integer k representing the maximum k-booking between all the previous events.

Implement the MyCalendarThree class:

  • MyCalendarThree() Initializes the object.
  • int book(int start, int end) Returns an integer k representing the largest integer such that there exists a k-booking in the calendar.

 

Example 1:

Input
["MyCalendarThree", "book", "book", "book", "book", "book", "book"]
[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
Output
[null, 1, 1, 2, 3, 3, 3]

Explanation
MyCalendarThree myCalendarThree = new MyCalendarThree();
myCalendarThree.book(10, 20); // return 1, The first event can be booked and is disjoint, so the maximum k-booking is a 1-booking.
myCalendarThree.book(50, 60); // return 1, The second event can be booked and is disjoint, so the maximum k-booking is a 1-booking.
myCalendarThree.book(10, 40); // return 2, The third event [10, 40) intersects the first event, and the maximum k-booking is a 2-booking.
myCalendarThree.book(5, 15); // return 3, The remaining events cause the maximum K-booking to be only a 3-booking.
myCalendarThree.book(5, 10); // return 3
myCalendarThree.book(25, 55); // return 3

 

Constraints:

  • 0 <= start < end <= 109
  • At most 400 calls will be made to book.
================================================ FILE: 74-search-a-2d-matrix/74-search-a-2d-matrix.java ================================================ class Solution { int x; public boolean searchMatrix(int[][] matrix, int target) { x=target; int i=0; int n=matrix.length; int m=matrix[0].length; while(i=x){ return binarySearch(matrix,i); }else{ i++; } } return false; } public boolean binarySearch(int[][]matrix,int i){ int[]a=matrix[i]; int l=0; int h=a.length; while(l<=h){ int mid=(l+h)/2; if(a[mid]==x){ return true; }else if(a[mid]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
================================================ FILE: 743-network-delay-time/743-network-delay-time.java ================================================ class Solution { public int networkDelayTime(int[][] times, int n, int k) { final int INF = Integer.MAX_VALUE/2; int[][] graph = new int[n][n]; for(int i = 0; i < n; i++){ Arrays.fill(graph[i], INF); } for(int t[] : times){ int x = t[0] - 1, y = t[1] - 1; graph[x][y] = t[2]; } int[] dist = new int[n]; Arrays.fill(dist, INF); boolean[] visted = new boolean[n]; dist[k-1] = 0; for(int i = 0; i < n; i++){ int x = -1; for(int y = 0; y < n; y++){ if(!visted[y] && (x == -1 || dist[y] < dist[x])) x = y; } visted[x] = true; for(int y = 0; y < n; y++){ dist[y] = Math.min(dist[y], dist[x]+graph[x][y]); } } int ans = 0; for (int i = 0; i < n; i++) { ans = Math.max(ans, dist[i]); } return ans == INF ? -1 : ans; } } ================================================ FILE: 743-network-delay-time/NOTES.md ================================================ ​ ================================================ FILE: 743-network-delay-time/README.md ================================================

743. Network Delay Time

Medium


You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.

We will send a signal from a given node k. Return the time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.

 

Example 1:

Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2

Example 2:

Input: times = [[1,2,1]], n = 2, k = 1
Output: 1

Example 3:

Input: times = [[1,2,1]], n = 2, k = 2
Output: -1

 

Constraints:

  • 1 <= k <= n <= 100
  • 1 <= times.length <= 6000
  • times[i].length == 3
  • 1 <= ui, vi <= n
  • ui != vi
  • 0 <= wi <= 100
  • All the pairs (ui, vi) are unique. (i.e., no multiple edges.)
================================================ FILE: 745-prefix-and-suffix-search/745-prefix-and-suffix-search.java ================================================ class WordFilter { TrieNode trie; public WordFilter(String[] words) { trie = new TrieNode(); for (int weight = 0; weight < words.length; ++weight) { String word = words[weight] + "{"; for (int i = 0; i < word.length(); ++i) { TrieNode cur = trie; cur.weight = weight; for (int j = i; j < 2 * word.length() - 1; ++j) { int k = word.charAt(j % word.length()) - 'a'; if (cur.children[k] == null) cur.children[k] = new TrieNode(); cur = cur.children[k]; cur.weight = weight; } } } } public int f(String prefix, String suffix) { TrieNode cur = trie; for (char letter: (suffix + '{' + prefix).toCharArray()) { if (cur.children[letter - 'a'] == null) return -1; cur = cur.children[letter - 'a']; } return cur.weight; } } class TrieNode { TrieNode[] children; int weight; public TrieNode() { children = new TrieNode[27]; weight = 0; } } ================================================ FILE: 745-prefix-and-suffix-search/NOTES.md ================================================ ​ ================================================ FILE: 745-prefix-and-suffix-search/README.md ================================================

745. Prefix and Suffix Search

Hard


Design a special dictionary with some words that searchs the words in it by a prefix and a suffix.

Implement the WordFilter class:

  • WordFilter(string[] words) Initializes the object with the words in the dictionary.
  • f(string prefix, string suffix) Returns the index of the word in the dictionary, which has the prefix prefix and the suffix suffix. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.

 

Example 1:

Input
["WordFilter", "f"]
[[["apple"]], ["a", "e"]]
Output
[null, 0]

Explanation
WordFilter wordFilter = new WordFilter(["apple"]);
wordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = 'e".

 

Constraints:

  • 1 <= words.length <= 15000
  • 1 <= words[i].length <= 10
  • 1 <= prefix.length, suffix.length <= 10
  • words[i], prefix and suffix consist of lower-case English letters only.
  • At most 15000 calls will be made to the function f.
================================================ FILE: 746-min-cost-climbing-stairs/746-min-cost-climbing-stairs.java ================================================ class Solution { public int minCostClimbingStairs(int[] cost) { int[] mem = new int[cost.length]; mem[0]=cost[0]; mem[1]=cost[1]; for(int i=2;i746. 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
================================================ FILE: 76-minimum-window-substring/76-minimum-window-substring.java ================================================ class Solution { public String minWindow(String s, String t) { int[] cs = new int[256]; for (char ch : t.toCharArray()) { cs[ch]++; } int l = 0, r = 0, cnt = t.length(); int start = -1, end = s.length(); // substring [start, end) while (r < s.length()) { if (cs[s.charAt(r++)]-- > 0) { cnt--; } while (cnt == 0) { if (cs[s.charAt(l++)]++ == 0) { cnt++; } if (r - l + 1 < end - start) { start = l - 1; end = r; } } } return end - start > s.length() ? "" : s.substring(start, end); } } ================================================ FILE: 76-minimum-window-substring/NOTES.md ================================================ ​ ================================================ FILE: 76-minimum-window-substring/README.md ================================================

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?
================================================ FILE: 763-partition-labels/763-partition-labels.java ================================================ class Solution { public List partitionLabels(String s) { List ans = new ArrayList<>(); int[] lastIndex = new int[26]; for (int i = 0; i < 26; i++) { lastIndex[i] = s.lastIndexOf('a' + i); } int left = 0; int right; while (left < s.length()) { right = lastIndex[s.charAt(left) - 'a']; for (int i = left; i < right; i++) { right = Math.max(right, lastIndex[s.charAt(i) - 'a']); } ans.add(right - left + 1); // size: right -left + 1 left = right + 1; } return ans; } } ================================================ FILE: 763-partition-labels/NOTES.md ================================================ ​ ================================================ FILE: 763-partition-labels/README.md ================================================

763. 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.
================================================ FILE: 785-is-graph-bipartite/785-is-graph-bipartite.java ================================================ class Solution { public boolean isBipartite(int[][] graph) { boolean[]vis=new boolean[100]; boolean[]color=new boolean[100]; Queue q=new LinkedList<>(); for(int i=0;i785. 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.
================================================ FILE: 791-Custom-Sort-String-Leetcode.cpp ================================================ class Solution { public: string customSortString(string order, string s) { unordered_mapmp; for(auto it:s) mp[it]++; string ans=""; for(int i=0;i map = new HashMap<>(); for(String str:words){ map.put(str,map.getOrDefault(str,0)+1); } int ans = 0; char ch[] = s.toCharArray(); for(String str:map.keySet()){ char temp[] = str.toCharArray(); int i = 0; int j = 0; while(i792. Number of Matching Subsequences

Medium


Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.

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".

 

Example 1:

Input: s = "abcde", words = ["a","bb","acd","ace"]
Output: 3
Explanation: There are three strings in words that are a subsequence of s: "a", "acd", "ace".

Example 2:

Input: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]
Output: 2

 

Constraints:

  • 1 <= s.length <= 5 * 104
  • 1 <= words.length <= 5000
  • 1 <= words[i].length <= 50
  • s and words[i] consist of only lowercase English letters.
================================================ FILE: 802. Find Eventual Safe States.java ================================================ class Solution { public List eventualSafeNodes(int[][] graph) { int n=graph.length; List> adj=new ArrayList<>(); for(int i=0;i list=new ArrayList<>(); adj.add(list); } for(int i=0;i ans=new ArrayList<>(); for(int i=0;i> adj,int node,int[] vis,int[] dfsVis,int[] check){ vis[node]=1; dfsVis[node]=1; for(int e:adj.get(node)){ if(vis[e]==0){ if(dfs(adj,e,vis,dfsVis,check)){ check[node]=0; return true; } } if(dfsVis[e]==1){ check[node]=0; return true; } } dfsVis[node]=0; check[node]=1; return false; } } ================================================ FILE: 804-unique-morse-code-words/804-unique-morse-code-words.java ================================================ class Solution { //gou public int uniqueMorseRepresentations(String[] words) { String[] MORSE = new String[]{ ".-","-...","-.-.","-..",".","..-.","--.", "....","..",".---","-.-",".-..","--","-.", "---",".--.","--.-",".-.","...","-","..-", "...-",".--","-..-","-.--","--.."}; Set uniqueSet = new HashSet<>(); for (String word : words) { uniqueSet.add(convertToMorseStr(MORSE, word)); } return uniqueSet.size(); } private String convertToMorseStr(String[] MORSE, String word) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < word.length(); i++) { sb.append(MORSE[word.charAt(i)-'a']); } return sb.toString(); } } ================================================ FILE: 804-unique-morse-code-words/NOTES.md ================================================ ​ ================================================ FILE: 804-unique-morse-code-words/README.md ================================================

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.
================================================ FILE: 804-unique-morse-code-words/unique-morse-code.cpp ================================================ class Solution { public: int uniqueMorseRepresentations(vector& words) { vector morse = {".-","-...","-.-.","-..",".","..-.", "--.","....","..",".---","-.-",".-..","--","-.","---",".--.", "--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; unordered_set s; for(int i = 0; i < words.size(); i++){ string str = words[i]; string morseCode = ""; for(int j = 0; j < str.length(); j++){ morseCode += morse[str[j] - 'a']; } s.insert(morseCode); } return s.size(); } }; ================================================ FILE: 81-search-in-rotated-sorted-array-ii/81-search-in-rotated-sorted-array-ii.java ================================================ class Solution { public boolean search(int[] nums, int target) { int left=0; int right=nums.length-1; while(left<=right){ int mid=(left+right)/2; if(nums[mid]==target){ return true; } //case: when all left right and mid are same else if(nums[left]==nums[mid] && nums[right]==nums[mid]){ left++; right--; } //case: when mid is on higher level else if(nums[left]<=nums[mid]){ //when left to mid is increasing if(nums[left]<=target && nums[mid]>target){ right=mid-1; }else{ left=mid+1; } } //case: when mid is smaller than left else{ //when mid to right is increasing if(nums[mid]=target){ left=mid+1; }else{ right=mid-1; } } } return false; } } ================================================ FILE: 81-search-in-rotated-sorted-array-ii/NOTES.md ================================================ ​ ================================================ FILE: 81-search-in-rotated-sorted-array-ii/README.md ================================================

81. Search in Rotated Sorted Array II

Medium


There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).

Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= 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,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4].

Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.

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

 

Example 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Example 2:

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

 

Constraints:

  • 1 <= nums.length <= 5000
  • -104 <= nums[i] <= 104
  • nums is guaranteed to be rotated at some pivot.
  • -104 <= target <= 104

 

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

================================================ FILE: 814-binary-tree-pruning/814-binary-tree-pruning.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { Mapmap; boolean del; public TreeNode pruneTree(TreeNode root) { map=new HashMap<>(); int sum=root.val+sum(root.right)+sum(root.left); if(sum==0){ return null; } dfs(root); return root; } void dfs(TreeNode root){ if(root==null)return; if(sum(root.left)==0){ root.left=null; } if(sum(root.right)==0){ root.right=null; } dfs(root.left); dfs(root.right); } int sum(TreeNode root){ if(root==null)return 0; if(map.containsKey(root))return map.get(root); int sum=root.val+sum(root.left)+sum(root.right); map.putIfAbsent(root,sum); return sum; } } Approach-2 BY @Jay-Thesia class Solution { public TreeNode pruneTree(TreeNode root) { return helper(root)?null:root; } public boolean helper(TreeNode root){ if(root==null) return true; boolean left=helper(root.left); boolean right=helper(root.right); if(left) root.left=null; if(right) root.right=null; return root.val==0 && left && right; } } ================================================ FILE: 814-binary-tree-pruning/README.md ================================================

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.
================================================ FILE: 82-remove-duplicates-from-sorted-list-ii/82-remove-duplicates-from-sorted-list-ii.java ================================================ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ public class Solution { public ListNode deleteDuplicates(ListNode A) { ListNode head=null; ListNode curr=null; ListNode temp=A; while(temp!=null){ if(temp.next!=null){ int value=temp.val; if(temp.next.val==value){ while(temp!=null && temp.val==value){ temp=temp.next; } }else{ if(head==null){ head=temp; curr=temp; }else{ curr.next=temp; curr=curr.next; } temp=temp.next; curr.next=null; } }else{ if(head==null){ head=temp; curr=temp; }else{ curr.next=temp; curr=curr.next; } temp=temp.next; curr.next=null; } } return head; } } ================================================ FILE: 82-remove-duplicates-from-sorted-list-ii/NOTES.md ================================================ ​ ================================================ FILE: 82-remove-duplicates-from-sorted-list-ii/README.md ================================================

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.
================================================ FILE: 820-short-encoding-of-words/820-short-encoding-of-words.java ================================================ class Solution { public int minimumLengthEncoding(String[] words) { Trie trie = new Trie(); int sum = 0; Arrays.sort(words, (s1, s2) -> s2.length() - s1.length()); for (String word : words) { boolean isNew = trie.insert(word); if (isNew) { sum += word.length() + 1; } } return sum; } } // 定义tire class Trie { TrieNode root; public Trie() { root = new TrieNode(); } public boolean insert(String word) { boolean isNew = false; TrieNode node = root; for (int i = word.length() - 1; i >= 0; --i) { int index = word.charAt(i) - 'a'; if (node.children[index] == null) { isNew = true; node.children[index] = new TrieNode(); } node = node.children[index]; } return isNew; } } class TrieNode { TrieNode[] children = new TrieNode[26]; public TrieNode() {} } ================================================ FILE: 820-short-encoding-of-words/NOTES.md ================================================ ​ ================================================ FILE: 820-short-encoding-of-words/README.md ================================================

820. Short Encoding of Words

Medium


A valid encoding of an array of words is any reference string s and array of indices indices such that:

  • words.length == indices.length
  • The reference string s ends with the '#' character.
  • For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i].

Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words.

 

Example 1:

Input: words = ["time", "me", "bell"]
Output: 10
Explanation: A valid encoding would be s = "time#bell#" and indices = [0, 2, 5].
words[0] = "time", the substring of s starting from indices[0] = 0 to the next '#' is underlined in "time#bell#"
words[1] = "me", the substring of s starting from indices[1] = 2 to the next '#' is underlined in "time#bell#"
words[2] = "bell", the substring of s starting from indices[2] = 5 to the next '#' is underlined in "time#bell#"

Example 2:

Input: words = ["t"]
Output: 2
Explanation: A valid encoding would be s = "t#" and indices = [0].

 

Constraints:

  • 1 <= words.length <= 2000
  • 1 <= words[i].length <= 7
  • words[i] consists of only lowercase letters.
================================================ FILE: 823-binary-trees-with-factors/823-binary-trees-with-factors.java ================================================ class Solution { public int numFactoredBinaryTrees(int[] arr) { Arrays.sort(arr); int n = arr.length, mod = 1_000_000_007; long[] dp = new long[n]; long res = 0; Map idxs = new HashMap(); for (int i = 0; i < n; i++) { dp[i] = 1; for (int j = 0; j < i; j++) { if (arr[j]*arr[j] > arr[i]) break; if (arr[i] % arr[j] == 0 && idxs.containsKey(arr[i]/arr[j])) { if (arr[j]*arr[j] == arr[i]) { dp[i] += dp[j]*dp[j]; dp[i] %= mod; } else { dp[i] += 2*dp[j]*dp[idxs.get(arr[i]/arr[j])]; dp[i] %= mod; } } } idxs.put(arr[i], i); res += dp[i]; res %= mod; } return (int) res; } } ================================================ FILE: 823-binary-trees-with-factors/NOTES.md ================================================ ​ ================================================ FILE: 823-binary-trees-with-factors/README.md ================================================

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.
================================================ FILE: 838-push-dominoes/838-push-dominoes.java ================================================ class Solution { public String pushDominoes(String dominoes) { int n = dominoes.length(); char[] dArray = dominoes.toCharArray(); char start = '.'; char last = '.'; int stidx = 0; int i = 0; while(i0){ if(start=='R' && last=='L'){ int l = stidx; int r = i-1; while(l=stidx){ dArray[l]='L'; l--; } } else if(start=='R'){ int r = stidx; while(r838. 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 '.'.
================================================ FILE: 844-backspace-string-compare/844-backspace-string-compare.java ================================================ class Solution { public boolean backspaceCompare(String s, String t) { int sPointer = s.length() - 1; int tPointer = t.length() - 1; while (sPointer >= 0 || tPointer >= 0) { sPointer = getNextCharacterPosition(s, sPointer); // can be negative, empty string; tPointer = getNextCharacterPosition(t, tPointer); // can be negative, empty string; if ((sPointer < 0 && tPointer >= 0) || (tPointer < 0 && sPointer >= 0) || (sPointer >= 0 && tPointer >= 0) && (s.charAt(sPointer) != t.charAt(tPointer)) ) { return false; } sPointer--; tPointer--; } return true; } public int getNextCharacterPosition(String s, int start) { if (start < 0) { return start; } char c = s.charAt(start); int count = c == '#' ? 2 : 0; while (count > 0) { start--; if (start < 0) { start -= count; break; } c = s.charAt(start); if (c == '#') { count++; } else { count--; } } return start; } } ================================================ FILE: 844-backspace-string-compare/NOTES.md ================================================ ​ ================================================ FILE: 844-backspace-string-compare/README.md ================================================

844. Backspace String Compare

Easy


Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.

Note that after backspacing an empty text, the text will continue empty.

 

Example 1:

Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".

Example 2:

Input: s = "ab##", t = "c#d#"
Output: true
Explanation: Both s and t become "".

Example 3:

Input: s = "a#c", t = "b"
Output: false
Explanation: s becomes "c" while t becomes "b".

 

Constraints:

  • 1 <= s.length, t.length <= 200
  • s and t only contain lowercase letters and '#' characters.

 

Follow up: Can you solve it in O(n) time and O(1) space?

================================================ FILE: 845_Longest_Mountain_in_Array.cpp ================================================ class Solution { public: int longestMountain(vector& arr) { int ans = 0; for(int i =1;iarr[i+1]&&arr[i]>arr[i-1]){ int x =i,y=i; while(x>0&&arr[x]>arr[x-1]){ x--; } while(yarr[y+1]){ y++; } ans = max(ans,y-x+1); i=y; } } return ans; } }; ================================================ FILE: 856-score-of-parentheses/856-score-of-parentheses.java ================================================ class Solution { public int scoreOfParentheses(String S) { int ans = 0, bal = 0; for (int i = 0; i < S.length(); ++i) { if (S.charAt(i) == '(') { bal++; } else { bal--; if (S.charAt(i-1) == '(') ans += 1 << bal; } } return ans; } } ================================================ FILE: 856-score-of-parentheses/NOTES.md ================================================ ​ ================================================ FILE: 856-score-of-parentheses/README.md ================================================

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.
================================================ FILE: 86-partition-list/86-partition-list.java ================================================ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode partition(ListNode head, int x) { ListNode temp=head; ListNode small=new ListNode(-1); ListNode smallEnd=small; ListNode large=new ListNode(-1); ListNode currLarge=large; while(temp!=null){ ListNode curr=temp; temp=temp.next; curr.next=null; if(curr.val86. Partition List

Medium


Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

 

Example 1:

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

Example 2:

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

 

Constraints:

  • The number of nodes in the list is in the range [0, 200].
  • -100 <= Node.val <= 100
  • -200 <= x <= 200
================================================ FILE: 867-transpose-matrix/867-transpose-matrix.java ================================================ class Solution { public int[][] transpose(int[][] A) { int R = A.length, C = A[0].length; int[][] ans = new int[C][R]; for (int r = 0; r < R; ++r) for (int c = 0; c < C; ++c) ans[c][r] = A[r][c]; return ans; } } ================================================ FILE: 867-transpose-matrix/README.md ================================================

867. Transpose Matrix

Easy


Given a 2D integer array matrix, return the transpose of matrix.

The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.

 

Example 1:

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

Example 2:

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

 

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 1000
  • 1 <= m * n <= 105
  • -109 <= matrix[i][j] <= 109
================================================ FILE: 869-Reordered-Power-of-2/869-Reordered-Power-of-2.cpp ================================================ class Solution { public: bool reorderedPowerOf2(int n) { string res = to_string(n); sort(res.begin(), res.end()); for(int i =0; i<30; i++){ string res1 = to_string(1<= stations[i][0] && stations[i][1] > curMax) { curMax = stations[i][1]; curPos = i; } } if (curMax == 0) { break; } ans++; maxPos += curMax; stations[curPos][0] = Integer.MAX_VALUE; } return maxPos >= target ? ans : -1; } } ================================================ FILE: 871-minimum-number-of-refueling-stops/Minimum-Number-of-Refueling-Stops.cpp ================================================ class Solution { public: int minRefuelStops(int target, int startFuel, vector>& stations) { priority_queue pq; stations.push_back({target, 0}); int pumps=0; for(int i=0;i871. Minimum Number of Refueling Stops

Hard


A car travels from a starting position to a destination which is target miles east of the starting position.

There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas.

The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.

Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1.

Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.

 

Example 1:

Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.

Example 2:

Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can not reach the target (or even the first gas station).

Example 3:

Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation: We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel.  We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas.  We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.

 

Constraints:

  • 1 <= target, startFuel <= 109
  • 0 <= stations.length <= 500
  • 0 <= positioni <= positioni+1 < target
  • 1 <= fueli < 109
================================================ FILE: 871. Minimum Number of Refueling Stops.cpp ================================================ int minRefuelStops(int target, int sf, vector>& s) { priority_queuepq; int i=0,res; for(res=0;sf876. 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
================================================ FILE: 88-merge-sorted-array/88-merge-sorted-array.java ================================================ class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int index = m + n - 1; int index1 = m - 1; int index2 = n - 1; while (index1 >= 0 && index2 >= 0) { if (nums1[index1] > nums2[index2]) { nums1[index] = nums1[index1]; index1--; } else { nums1[index] = nums2[index2]; index2--; } index--; } while (index2 >= 0) { nums1[index--] = nums2[index2--]; } } } ================================================ FILE: 88-merge-sorted-array/NOTES.md ================================================ ​ ================================================ FILE: 88-merge-sorted-array/README.md ================================================

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?

================================================ FILE: 881-boats-to-save-people/881-boats-to-save-people.java ================================================ class Solution { public int numRescueBoats(int[] people, int limit) { Arrays.sort(people); int i = 0, j = people.length - 1; int ans = 0; while (i <= j) { ans++; if (people[i] + people[j] <= limit) i++; j--; } return ans; } } ================================================ FILE: 881-boats-to-save-people/NOTES.md ================================================ ​ ================================================ FILE: 881-boats-to-save-people/README.md ================================================

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
================================================ FILE: 890-find-and-replace-pattern/890-find-and-replace-pattern.java ================================================ class Solution { public static List findAndReplacePattern(String[] words, String pattern) { List list=new LinkedList<>(); for(int i=0;i890. 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.
================================================ FILE: 895-maximum-frequency-stack/895-maximum-frequency-stack.java ================================================ class FreqStack { Map cnt;//frequency count for every digit int max;//max frequency present for any num(we don't know which) //used to store frequency-wise stacks of inputs.eg. //([2,1,2,5,5,5])(1 freq-[2,1,5],2 freq-[2,5],3 freq-[5]) Map> stack;//stack assigned with num of frequencies public FreqStack() { //initialise our members cnt=new HashMap<>(); stack=new HashMap<>(); max=0; } public void push(int val) { //increment val count int valCnt=cnt.getOrDefault(val,0)+1; cnt.put(val,valCnt); //if current cal count is more than max if(valCnt>max){ max=valCnt; stack.put(max,new ArrayList<>());//add new stack for this new max count } stack.get(valCnt).add(val);//add this num to its stacks } public int pop() { //remove last element of max freq int res=stack.get(max).remove(stack.get(max).size()-1); cnt.put(res,cnt.get(res)-1);//reduce freq of number if(stack.get(max).size()==0){//if now this freq have no num left max--;//reduce the freq } return res; } } /** * Your FreqStack object will be instantiated and called as such: * FreqStack obj = new FreqStack(); * obj.push(val); * int param_2 = obj.pop(); */ ================================================ FILE: 895-maximum-frequency-stack/NOTES.md ================================================ ​ ================================================ FILE: 895-maximum-frequency-stack/README.md ================================================

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.
================================================ FILE: 897-increasing-order-search-tree/897-increasing-order-search-tree.java ================================================ class Solution { public TreeNode increasingBST(TreeNode root){ List list=new ArrayList<>(); inOrder(root,list); TreeNode newHead=new TreeNode(-1); TreeNode temp=newHead; for(int i=0;i list){ if(root==null)return; TreeNode lefty=root.left; root.left=null; TreeNode righty=root.right; root.right=null; inOrder(lefty,list); list.add(root); inOrder(righty,list); } } ================================================ FILE: 897-increasing-order-search-tree/NOTES.md ================================================ ​ ================================================ FILE: 897-increasing-order-search-tree/README.md ================================================

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
================================================ FILE: 905-sort-array-by-parity/905-sort-array-by-parity.java ================================================ class Solution { public int[] sortArrayByParity(int[] nums) { int left = 0, right = nums.length-1; while (left < right) { if (nums[left]%2 == 1) { if (nums[right]%2 == 0) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; left++; } right--; } else { left++; } } return nums; } } ================================================ FILE: 905-sort-array-by-parity/NOTES.md ================================================ ​ ================================================ FILE: 905-sort-array-by-parity/README.md ================================================

905. Sort Array By Parity

Easy


Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

Return any array that satisfies this condition.

 

Example 1:

Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Example 2:

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

 

Constraints:

  • 1 <= nums.length <= 5000
  • 0 <= nums[i] <= 5000
================================================ FILE: 91-decode-ways/91-decode-ways.java ================================================ class Solution { public int numDecodings(String s) { int[] dp=new int[s.length()]; if(s.charAt(0)=='0'){ return 0; } dp[0]=1; for(int i=1;i=10&&two<=26){ if(i==1){ dp[i]++; } else{ dp[i]+=dp[i-2]; } } } return dp[dp.length-1]; } } ================================================ FILE: 91-decode-ways/NOTES.md ================================================ ​ ================================================ FILE: 91-decode-ways/README.md ================================================

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 test cases are generated so that the answer fits 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 = "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).
================================================ FILE: 916-word-subsets/916-word-subsets.java ================================================ class Solution { public List wordSubsets(String[] A, String[] B) { int[] bmax = count(""); for (String b: B) { int[] bCount = count(b); for (int i = 0; i < 26; ++i) bmax[i] = Math.max(bmax[i], bCount[i]); } List ans = new ArrayList(); search: for (String a: A) { int[] aCount = count(a); for (int i = 0; i < 26; ++i) if (aCount[i] < bmax[i]) continue search; ans.add(a); } return ans; } public int[] count(String S) { int[] ans = new int[26]; for (char c: S.toCharArray()) ans[c - 'a']++; return ans; } } ================================================ FILE: 916-word-subsets/NOTES.md ================================================ ​ ================================================ FILE: 916-word-subsets/README.md ================================================

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.
================================================ FILE: 92-reverse-linked-list-ii/92-reverse-linked-list-ii.java ================================================ class Solution { public ListNode reverseBetween(ListNode head, int left, int right) { if (left == right || head == null) return head; ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy, post = dummy; for (int i = 1; i <= right+1; i++) { if (i < left) pre = pre.next; //Find the pre node (i.e. node before Start node) post = post.next; //Find the post node (i.e. node after End node) } ListNode start = pre.next; ListNode temp = post; //temp is reverse part which is followed by post node while (start != post) { ListNode next = start.next; start.next = temp; temp = start; start = next; } pre.next = temp; // pre node is followed by reversed part return dummy.next; } } ================================================ FILE: 92-reverse-linked-list-ii/NOTES.md ================================================ ​ ================================================ FILE: 92-reverse-linked-list-ii/README.md ================================================

92. Reverse Linked List II

Medium


Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

 

Example 1:

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

Example 2:

Input: head = [5], left = 1, right = 1
Output: [5]

 

Constraints:

  • The number of nodes in the list is n.
  • 1 <= n <= 500
  • -500 <= Node.val <= 500
  • 1 <= left <= right <= n

 

Follow up: Could you do it in one pass?
================================================ FILE: 923-3sum-with-multiplicity/923-3sum-with-multiplicity.java ================================================ class Solution { public int threeSumMulti(int[] A, int target) { int MOD = 1_000_000_007; // Initializing as long saves us the trouble of // managing count[x] * count[y] * count[z] overflowing later. long[] count = new long[101]; int uniq = 0; for (int x: A) { count[x]++; if (count[x] == 1) uniq++; } int[] keys = new int[uniq]; int t = 0; for (int i = 0; i <= 100; ++i) if (count[i] > 0) keys[t++] = i; long ans = 0; // Now, let's do a 3sum on "keys", for i <= j <= k. // We will use count to add the correct contribution to ans. for (int i = 0; i < keys.length; i++) { int x = keys[i]; int T = target - x; int j = i, k = keys.length - 1; while (j <= k) { int y = keys[j], z = keys[k]; if (y + z < T) { j++; } else if (y + z > T) { k--; } else { // # x+y+z == T, now calc the size of the contribution if (i < j && j < k) { ans += count[x] * count[y] * count[z]; } else if (i == j && j < k) { ans += count[x] * (count[x] - 1) / 2 * count[z]; } else if (i < j && j == k) { ans += count[x] * count[y] * (count[y] - 1) / 2; } else { // i == j == k ans += count[x] * (count[x] - 1) * (count[x] - 2) / 6; } ans %= MOD; j++; k--; } } } return (int) ans; } } ================================================ FILE: 923-3sum-with-multiplicity/NOTES.md ================================================ ​ ================================================ FILE: 923-3sum-with-multiplicity/README.md ================================================

923. 3Sum With Multiplicity

Medium


Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target.

As the answer can be very large, return it modulo 109 + 7.

 

Example 1:

Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20
Explanation: 
Enumerating by the values (arr[i], arr[j], arr[k]):
(1, 2, 5) occurs 8 times;
(1, 3, 4) occurs 8 times;
(2, 2, 4) occurs 2 times;
(2, 3, 3) occurs 2 times.

Example 2:

Input: arr = [1,1,2,2,2,2], target = 5
Output: 12
Explanation: 
arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:
We choose one 1 from [1,1] in 2 ways,
and two 2s from [2,2,2,2] in 6 ways.

 

Constraints:

  • 3 <= arr.length <= 3000
  • 0 <= arr[i] <= 100
  • 0 <= target <= 300
================================================ FILE: 936-stamping-the-sequence/936-stamping-the-sequence.java ================================================ class Solution { public int[] movesToStamp(String stamp, String target) { char[] s = stamp.toCharArray(); char[] t = target.toCharArray(); int m = s.length, n = t.length, count = 0; // count chars replaced successfully boolean[] visited = new boolean[n]; int[] res = new int[n]; int top = res.length; while (count < n) { boolean stamped = false; for (int i = 0; i <= n - m; i++) if (!visited[i] && canStamp(i, s, t)) { visited[i] = true; // System.out.printf("%s%d\n%s\n%s%s\n\n", " ".repeat(i), i, new String(t), " ".repeat(i), new String(s)); count = stamp(i, s, t, count); stamped = true; // successfully stamped this round res[--top] = i; // add result if (count == n) break; // all stamped } if (!stamped) return new int[0]; // nothing found, return an empty array } return Arrays.copyOfRange(res, top, res.length); } private int stamp(int start, char[] s, char[] t, int count) { for (int i = 0; i < s.length; i++) if (t[start + i] != '*') { t[start + i] = '*'; count++; } return count; } private boolean canStamp(int start, char[] s, char[] t) { int count = 0; for (int i = 0; i < s.length; i++) { if (t[start + i] == '*') count++; else if (t[start + i] != '*' && s[i] != t[start + i]) return false; } return count != s.length; } } /* Case 0: "abc" "abababcbcbababcbc" 4 abababcbcbababcbc abc 6 abab***bcbababcbc abc 12 abab*****bababcbc abc 14 abab*****bab***bc abc 2 abab*****bab***** abc 10 ab*******bab***** abc 0 ab*******b******* abc 8 *********b******* abc Case 1: "abc" "ababc" 2 ababc abc 0 ab*** abc "abca" "aabcaca" 1 aabcaca abca 3 a****ca abca 0 a****** abca */ ================================================ FILE: 936-stamping-the-sequence/NOTES.md ================================================ ​ ================================================ FILE: 936-stamping-the-sequence/README.md ================================================

936. Stamping The Sequence

Hard


You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'.

In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp.

  • For example, if stamp = "abc" and target = "abcba", then s is "?????" initially. In one turn you can:
    • place stamp at index 0 of s to obtain "abc??",
    • place stamp at index 1 of s to obtain "?abc?", or
    • place stamp at index 2 of s to obtain "??abc".
    Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s).

We want to convert s to target using at most 10 * target.length turns.

Return an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns, return an empty array.

 

Example 1:

Input: stamp = "abc", target = "ababc"
Output: [0,2]
Explanation: Initially s = "?????".
- Place stamp at index 0 to get "abc??".
- Place stamp at index 2 to get "ababc".
[1,0,2] would also be accepted as an answer, as well as some other answers.

Example 2:

Input: stamp = "abca", target = "aabcaca"
Output: [3,0,1]
Explanation: Initially s = "???????".
- Place stamp at index 3 to get "???abca".
- Place stamp at index 0 to get "abcabca".
- Place stamp at index 1 to get "aabcaca".

 

Constraints:

  • 1 <= stamp.length <= target.length <= 1000
  • stamp and target consist of lowercase English letters.
================================================ FILE: 936-stamping-the-sequence/Stamping The Sequence.cpp ================================================ class Solution { public: // Function to check whether the substring can be replaced with stamp bool canReplace(string &stamp, string &target, int i, int n) { for(int p=0; p movesToStamp(string stamp, string target) { int n = stamp.length(), m = target.length(), cnt = 0; vector ans; vector visited(m,false); while(cnt < m) { bool f = false; for(int i=0; i<=m-n; i++) if(!visited[i] and canReplace(stamp, target, i, n)) { replace(stamp, target, i, n, cnt); ans.push_back(i); visited[i] = f = true; } if(!f) break; } if(cnt < m) return {}; reverse(ans.begin(), ans.end()); return ans; } }; ================================================ FILE: 936-stamping-the-sequence/stamping-the-sequence.cpp ================================================ // What I basiclly did here is trying to reverse the whole operations. // The operation token later will be more apperant than the operation token before. The letters which stamped later will cover the letters stamped before and we really don't care about the letters which are covered. // * * * * * * * // * * * |a b c a| // |a b c a| b c a // a |a b c a| c a // We just try to match the stamp with the target. Since we do not care about the letters which are coverd by others, so we can apply a * match any letters. For example: // "aabcaca" -> "a****ca" -> "*****ca"->"*******" class Solution { public: vector movesToStamp(string stamp, string target) { vector ans; vector output; string str = target; string aim(target.length(),'*'); while(str != aim){ int tmp = remove(str,stamp); // index of first match case when stamp is found in str or target. if(tmp == str.length()) return output; ans.push_back(tmp); } for(int iter=ans.size()-1;iter>=0;--iter) output.push_back(ans[iter]); return output; } int remove(string& str, string stamp){ for(int iter=0;iter inorderTraversal(TreeNode root) { List list=new ArrayList<>(); inOrder(root,list); return list; } void inOrder(TreeNode root,List list){ if(root==null)return; inOrder(root.left,list); list.add(root.val); inOrder(root.right,list); } } ================================================ FILE: 94-binary-tree-inorder-traversal/Binary Tree InOrder Traversal lc.cpp ================================================ #include using namespace std; /** * 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 res; void inorder(TreeNode* node){ if(!node) return; // traverse the left node inorder(node->left); // do something with node value here res.push_back(node->val); // traverse right inorder(node->right); } vector inorderTraversal(TreeNode* root) { inorder(root); return res; } }; ================================================ FILE: 94-binary-tree-inorder-traversal/NOTES.md ================================================ ​ ================================================ FILE: 94-binary-tree-inorder-traversal/README.md ================================================

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]

 

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?
================================================ FILE: 94. Binary Tree Inorder Traversal.cpp ================================================ class Solution { public: void solve(TreeNode *root,vector &result) { if(root == NULL){ return ; } solve(root->left,result); result.push_back(root->val); solve(root->right,result); } vector inorderTraversal(TreeNode* root) { vector result; solve(root,result); return result; } }; ================================================ FILE: 948 Bag of Tokens lc med.cpp ================================================ class Solution { public: int bagOfTokensScore(vector& tokens, int power) { // approach 2 pointer tech // sort, then define 2 pointer , start =0, and end // check sort(tokens.begin(), tokens.end()); int left_start =0, right_end = tokens.size()-1; int score =0; // initializing score 0 while(left_start<=right_end){ if(power>=tokens[left_start]){ power-=tokens[left_start++]; score++; }else{ if(power+tokens[right_end]>= tokens[left_start] && score!=0 && right_end !=left_start){ power+= tokens[right_end--]; score--; }else break; } } return score; } }; ================================================ FILE: 948-bag-of-tokens/948-bag-of-tokens.java ================================================ class Solution { public int bagOfTokensScore(int[] tokens, int power) { Arrays.sort(tokens); int i=0; int j=tokens.length-1; int ans=0; int curr=0; while(i<=j){ if(power>=tokens[i]){ power-=tokens[i]; curr++; ans=Math.max(ans,curr); i++; }else{ if(curr==0)break; power+=tokens[j]; curr--; j--; } } return ans; } } ================================================ FILE: 948-bag-of-tokens/NOTES.md ================================================ ​ ================================================ FILE: 948-bag-of-tokens/README.md ================================================

948. Bag of Tokens

Medium


You have an initial power of power, an initial score of 0, and a bag of tokens where tokens[i] is the value of the ith token (0-indexed).

Your goal is to maximize your total score by potentially playing each token in one of two ways:

  • If your current power is at least tokens[i], you may play the ith token face up, losing tokens[i] power and gaining 1 score.
  • If your current score is at least 1, you may play the ith token face down, gaining tokens[i] power and losing 1 score.

Each token may be played at most once and in any order. You do not have to play all the tokens.

Return the largest possible score you can achieve after playing any number of tokens.

 

Example 1:

Input: tokens = [100], power = 50
Output: 0
Explanation: Playing the only token in the bag is impossible because you either have too little power or too little score.

Example 2:

Input: tokens = [100,200], power = 150
Output: 1
Explanation: Play the 0th token (100) face up, your power becomes 50 and score becomes 1.
There is no need to play the 1st token since you cannot play it face up to add to your score.

Example 3:

Input: tokens = [100,200,300,400], power = 200
Output: 2
Explanation: Play the tokens in this order to get a score of 2:
1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1.
2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0.
3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1.
4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.

 

Constraints:

  • 0 <= tokens.length <= 1000
  • 0 <= tokens[i], power < 104
================================================ FILE: 96-Unique Binary Search Trees.java ================================================ // Using Memoization public static int helper(int n, int[] dp) { if(n<=1) return dp[n] = 1; if(dp[n] != -1) { return dp[n]; } int ans = 0; for(int i = 0; i < n; i++) { ans += helper(i, dp) * helper(n-i-1, dp); } return dp[n] = ans; } public int numTrees(int n) { int[] dp = new int[n+1]; Arrays.fill(dp, -1); return helper(n, dp); } // Using Tabulation public int numTrees(int n) { int[] dp = new int[n+1]; dp[0] = 1; dp[1] = 1; for(int i = 2; i <= n; i++) { for(int j =0; j < i; j++) { dp[i] += (dp[j] * dp[i-j-1]); } } return dp[n]; } ================================================ FILE: 967-numbers-with-same-consecutive-differences/967-numbers-with-same-consecutive-differences.java ================================================ class Solution { List ans; public int[] numsSameConsecDiff(int n, int k) { ans=new ArrayList<>(); for(int i=1;i<10;i++){ dfs(i,n,k); } int[] arr=new int[ans.size()]; int i=0; for(int ele:ans){ arr[i++]=ele; } return arr; } void dfs(int num,int n,int k){ if((int)Math.floor(Math.log10(num) + 1)==n){ ans.add(num); return; } int last=num%10; if(k==0){ dfs(num*10+(last+k),n,k); return; } if(last+k<10){ dfs(num*10+(last+k),n,k); } if(last-k>-1){ dfs(num*10+(last-k),n,k); } } } ================================================ FILE: 967-numbers-with-same-consecutive-differences/NOTES.md ================================================ ​ ================================================ FILE: 967-numbers-with-same-consecutive-differences/README.md ================================================

967. Numbers With Same Consecutive Differences

Medium


Return all non-negative integers of length n such that the absolute difference between every two consecutive digits is k.

Note that every number in the answer must not have leading zeros. For example, 01 has one leading zero and is invalid.

You may return the answer in any order.

 

Example 1:

Input: n = 3, k = 7
Output: [181,292,707,818,929]
Explanation: Note that 070 is not a valid number, because it has leading zeroes.

Example 2:

Input: n = 2, k = 1
Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]

 

Constraints:

  • 2 <= n <= 9
  • 0 <= k <= 9
================================================ FILE: 968-binary-tree-cameras/968-binary-tree-cameras.java ================================================ class Solution { private int NOT_MONITORED = 0; private int MONITORED_NOCAM = 1; private int MONITORED_WITHCAM = 2; private int cameras = 0; public int minCameraCover(TreeNode root) { int top = dfs(root); return top == NOT_MONITORED ? cameras+1 :cameras; } private int dfs (TreeNode root){ if(root == null)return MONITORED_NOCAM; int left = dfs(root.left); int right = dfs(root.right); if (left == MONITORED_NOCAM && right == MONITORED_NOCAM) { return NOT_MONITORED; } else if (left == NOT_MONITORED || right == NOT_MONITORED) { cameras++; return MONITORED_WITHCAM; } else { return MONITORED_NOCAM; } } } ================================================ FILE: 968-binary-tree-cameras/NOTES.md ================================================ ​ ================================================ FILE: 968-binary-tree-cameras/README.md ================================================

968. Binary Tree Cameras

Hard


You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.

Return the minimum number of cameras needed to monitor all nodes of the tree.

 

Example 1:

Input: root = [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to monitor all nodes if placed as shown.

Example 2:

Input: root = [0,0,null,0,null,0,null,null,0]
Output: 2
Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.

 

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • Node.val == 0
================================================ FILE: 97-interleaving-string/97-interleaving-string.java ================================================ class Solution { public boolean isInterleave(String s1, String s2, String s3) { boolean[][] canReach = new boolean[s1.length()][s2.length()]; return isInterleaveHelper(s1, s2, s3, 0, 0, 0, canReach); } private boolean isInterleaveHelper(String s1, String s2, String s3, int i1, int i2, int i3, boolean[][] canReach) { if (i3 == s3.length()) { if (i1 == s1.length() && i2 == s2.length()) return true; return false; } if (i1 == s1.length()) { return s2.substring(i2, s2.length()).equals(s3.substring(i3, s3.length())); } if (i2 == s2.length()) { return s1.substring(i1, s1.length()).equals(s3.substring(i3, s3.length())); } if (canReach[i1][i2]) return false; canReach[i1][i2] = true; boolean s1Match = (s1.charAt(i1) == s3.charAt(i3)); boolean s2Match = (s2.charAt(i2) == s3.charAt(i3)); if (s1Match && s2Match) { return isInterleaveHelper(s1, s2, s3, i1 + 1, i2, i3 + 1, canReach) || isInterleaveHelper(s1, s2, s3, i1, i2 + 1, i3 + 1, canReach); } else if (s1Match) { return isInterleaveHelper(s1, s2, s3, i1 + 1, i2, i3 + 1, canReach); } else if (s2Match) { return isInterleaveHelper(s1, s2, s3, i1, i2 + 1, i3 + 1, canReach); } else { return false; } } } ================================================ FILE: 97-interleaving-string/NOTES.md ================================================ ​ ================================================ FILE: 97-interleaving-string/README.md ================================================

97. Interleaving String

Medium


Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.

An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that:

  • s = s1 + s2 + ... + sn
  • t = t1 + t2 + ... + tm
  • |n - m| <= 1
  • The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ...

Note: a + b is the concatenation of strings a and b.

 

Example 1:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true

Example 2:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false

Example 3:

Input: s1 = "", s2 = "", s3 = ""
Output: true

 

Constraints:

  • 0 <= s1.length, s2.length <= 100
  • 0 <= s3.length <= 200
  • s1, s2, and s3 consist of lowercase English letters.

 

Follow up: Could you solve it using only O(s2.length) additional memory space?

================================================ FILE: 98-validate-binary-search-tree/98-validate-binary-search-tree.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean isValidBST(TreeNode root) { return dfs(root,Long.MIN_VALUE,Long.MAX_VALUE); } boolean dfs(TreeNode root,long lower,long upper){ if(root==null)return true; if(root.val<=lower || root.val>=upper)return false; return dfs(root.left,lower,root.val) && dfs(root.right,root.val,upper); } } ================================================ FILE: 98-validate-binary-search-tree/NOTES.md ================================================ ​ ================================================ FILE: 98-validate-binary-search-tree/README.md ================================================

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
================================================ FILE: 981-time-based-key-value-store/981-time-based-key-value-store.java ================================================ class TimeValue { public int time; public String value; public TimeValue(int time, String value) { this.time = time; this.value = value; } public String toString() { return "TimeValue with time " + this.time + " and value " + this.value; } } class TimeMap { private Map> map = new HashMap<>(); public TimeMap() { } public void set(String key, String value, int timestamp) { // Add the given (key, timestamp) combination TimeValue newTimeValue = new TimeValue(timestamp, value); if (!this.map.containsKey(key)) { this.map.put(key, new ArrayList<>()); } this.map.get(key).add(newTimeValue); // System.out.println(this.map.get(key)); } public String get(String key, int timestamp) { List list = this.map.get(key); if (list == null) { return ""; } // Binary search int left = 0; int right = list.size() - 1; TimeValue best = null; while (left <= right) { int mid = left + (right - left) / 2; if (list.get(mid).time <= timestamp) { // Valid time best = list.get(mid); left = mid + 1; } else { right = mid - 1; } } return (best != null ? best.value : ""); } } ================================================ FILE: 981-time-based-key-value-store/NOTES.md ================================================ ​ ================================================ FILE: 981-time-based-key-value-store/README.md ================================================

981. Time Based Key-Value Store

Medium


Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.

Implement the TimeMap class:

  • TimeMap() Initializes the object of the data structure.
  • void set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp.
  • String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns "".

 

Example 1:

Input
["TimeMap", "set", "get", "get", "set", "get", "get"]
[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
Output
[null, null, "bar", "bar", null, "bar2", "bar2"]

Explanation
TimeMap timeMap = new TimeMap();
timeMap.set("foo", "bar", 1);  // store the key "foo" and value "bar" along with timestamp = 1.
timeMap.get("foo", 1);         // return "bar"
timeMap.get("foo", 3);         // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar".
timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4.
timeMap.get("foo", 4);         // return "bar2"
timeMap.get("foo", 5);         // return "bar2"

 

Constraints:

  • 1 <= key.length, value.length <= 100
  • key and value consist of lowercase English letters and digits.
  • 1 <= timestamp <= 107
  • All the timestamps timestamp of set are strictly increasing.
  • At most 2 * 105 calls will be made to set and get.
================================================ FILE: 985 Sum of Even Numbers After Queries lc med.cpp ================================================ #include using namespace std; class Solution { public: vector sumEvenAfterQueries(vector& nums, vector>& queries) { int S =0; for(auto x : nums) if(x%2==0) S+=x; vectorres; for(auto q : queries ){ int val = q[0], idx = q[1]; // if original nums[idx] is even, then we deduct it from evenSum if(nums[idx] % 2==0) S-=nums[idx]; // in-place update nums nums[idx]+=val; // check if we need to update evenSum for the new value if (nums[idx] % 2 == 0) S += nums[idx]; // then we have evenSum after this query, push it to ans res.push_back(S); } return res; } }; ================================================ FILE: 985-sum-of-even-numbers-after-queries/985-sum-of-even-numbers-after-queries.java ================================================ class Solution { public int[] sumEvenAfterQueries(int[] nums, int[][] queries) { int sum=0; for(int i:nums){ if((i&1)==0)sum+=i; } int[]ans=new int[queries.length]; for(int i=0;i985. Sum of Even Numbers After Queries

Medium


You are given an integer array nums and an array queries where queries[i] = [vali, indexi].

For each query i, first, apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values of nums.

Return an integer array answer where answer[i] is the answer to the ith query.

 

Example 1:

Input: nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: [8,6,2,4]
Explanation: At the beginning, the array is [1,2,3,4].
After adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.

Example 2:

Input: nums = [1], queries = [[4,0]]
Output: [0]

 

Constraints:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • 1 <= queries.length <= 104
  • -104 <= vali <= 104
  • 0 <= indexi < nums.length
================================================ FILE: 987-vertical-order-traversal-of-a-binary-tree/987-vertical-order-traversal-of-a-binary-tree.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { Map> map; int min; public List> verticalTraversal(TreeNode root) { map=new HashMap<>(); min=Integer.MAX_VALUE; dfs(root,0,0); List> ans=new ArrayList<>(); while(map.containsKey(min)){ PriorityQueuepq=map.get(min); List ls=new ArrayList<>(); while(pq.size()>0){ ls.add(pq.remove()[0]); } ans.add(ls); min++; } return ans; } void dfs(TreeNode root,int row,int col){ if(root==null)return; min=Math.min(min,col); PriorityQueue pq; if(map.containsKey(col)){ pq=map.get(col); }else{ pq=new PriorityQueue<>((a,b)->{ if(a[1]==b[1]){ return a[0]-b[0]; } return a[1]-b[1]; }); } pq.add(new int[]{root.val,row}); map.put(col,pq); dfs(root.left,row+1,col-1); dfs(root.right,row+1,col+1); } } ################ Approach-2 by @Jay-Thesia ###########################3 class Solution { class Pair{ TreeNode value; int hdist; Pair(TreeNode value,int hdist){ this.value=value; this.hdist=hdist; } } public List> verticalTraversal(TreeNode root) { List> outter=new ArrayList<>(); TreeMap> tm=new TreeMap(); Deque q=new LinkedList<>(); q.add(new Pair(root,0)); while(q.size()>0){ int len=q.size(); HashMap> hm=new HashMap<>(); for(int i=0;i inner=hm.getOrDefault(cHdist,new ArrayList<>()); inner.add(cVal.val); Collections.sort(inner); hm.put(cHdist,new ArrayList<>(inner)); if(cVal.left!=null) q.add(new Pair(cVal.left,cHdist-1)); if(cVal.right!=null) q.add(new Pair(cVal.right,cHdist+1)); } for(Map.Entry> item:hm.entrySet()){ ArrayList list=tm.getOrDefault(item.getKey(),new ArrayList<>()); list.addAll(item.getValue()); tm.put(item.getKey(),list); } } return new ArrayList<>(tm.values()); } } ================================================ FILE: 987-vertical-order-traversal-of-a-binary-tree/NOTES.md ================================================ key=col val=pq -> sorting acc to row || val [0] -> val [1] -> row ================================================ FILE: 987-vertical-order-traversal-of-a-binary-tree/README.md ================================================

987. Vertical Order Traversal of a Binary Tree

Hard


Given the root of a binary tree, calculate the vertical order traversal of the binary tree.

For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).

The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.

Return the vertical order traversal of the binary tree.

 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Explanation:
Column -1: Only node 9 is in this column.
Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
Column 1: Only node 20 is in this column.
Column 2: Only node 7 is in this column.

Example 2:

Input: root = [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
Column -2: Only node 4 is in this column.
Column -1: Only node 2 is in this column.
Column 0: Nodes 1, 5, and 6 are in this column.
          1 is at the top, so it comes first.
          5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
Column 1: Only node 3 is in this column.
Column 2: Only node 7 is in this column.

Example 3:

Input: root = [1,2,3,4,6,5,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
This case is the exact same as example 2, but with nodes 5 and 6 swapped.
Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.

 

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • 0 <= Node.val <= 1000
================================================ FILE: 99-recover-binary-search-tree/99-recover-binary-search-tree.java ================================================ class Solution { TreeNode prev = null; TreeNode first = null; TreeNode second = null; public void recoverTree(TreeNode root) { inorder(root); swap(first,second); } public void swap(TreeNode a, TreeNode b) { int temp = a.val; a.val=b.val; b.val=temp; } public void inorder(TreeNode root) { if(root!=null) { if(root.left!=null) { inorder(root.left); } if(prev!=null && prev.val>root.val) { if(first==null) { first=prev; } if(first!=null) { second=root; } } prev=root; if(root.right!=null) { inorder(root.right); } } } } ================================================ FILE: 99-recover-binary-search-tree/README.md ================================================

99. Recover Binary Search Tree

Medium


You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.

 

Example 1:

Input: root = [1,3,null,null,2]
Output: [3,1,null,null,2]
Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.

Example 2:

Input: root = [3,1,4,null,null,2]
Output: [2,1,4,null,null,3]
Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.

 

Constraints:

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

 

Follow up: A solution using O(n) space is pretty straight-forward. Could you devise a constant O(1) space solution?
================================================ FILE: 990-satisfiability-of-equality-equations/990-satisfiability-of-equality-equations.java ================================================ class Solution { int[] parent = new int[26]; public int find(int x) { // with path compression if (parent[x] == x) return x; return parent[x] = find(parent[x]); // without path compression // return parent[x] == x ? x : find(parent[x]); } // the idea is to put all characters in the same group if they are equal // in order to do that, we can use Disjoint Set Union (dsu) aka Union Find // for dsu tutorial, please check out https://wingkwong.github.io/leetcode-the-hard-way/tutorials/graph-theory/disjoint-set-union public boolean equationsPossible(String[] equations) { int n = equations.length; // at the beginning, put each character index in its own group // so we will have 26 groups with one character each // i.e. 'a' in group 0, 'b' in group 1, ..., 'z' in group 25 for (int i = 0; i < 26; i++) parent[i] = i; for (String e : equations) { // if two character is equal, if (e.charAt(1) == '=') { // e.g. a = b // then we group them together // how? we use `find` function to find out the parent group of the target character index // then update parent. a & b would be in group 1 (i.e. a merged into the group where b belongs to) // or you can also do `parent[find(e.charAt(3)- 'a')] = find(e.charAt(0) - 'a');` (i.e. b merged into the group where a belongs to) parent[find(e.charAt(0)- 'a')] = find(e.charAt(3) - 'a'); } } // handle != case for (String e : equations) { // if two characters are not equal // then which means their parent must not be equal if (e.charAt(1) == '!' && find(e.charAt(0) - 'a') == find(e.charAt(3) - 'a')) { return false; } } return true; } } ================================================ FILE: 990-satisfiability-of-equality-equations/NOTES.md ================================================ ​ ================================================ FILE: 990-satisfiability-of-equality-equations/README.md ================================================

990. Satisfiability of Equality Equations

Medium


You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: "xi==yi" or "xi!=yi".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names.

Return true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise.

 

Example 1:

Input: equations = ["a==b","b!=a"]
Output: false
Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.
There is no way to assign the variables to satisfy both equations.

Example 2:

Input: equations = ["b==a","a==b"]
Output: true
Explanation: We could assign a = 1 and b = 1 to satisfy both equations.

 

Constraints:

  • 1 <= equations.length <= 500
  • equations[i].length == 4
  • equations[i][0] is a lowercase letter.
  • equations[i][1] is either '=' or '!'.
  • equations[i][2] is '='.
  • equations[i][3] is a lowercase letter.
================================================ FILE: 991-broken-calculator/991-broken-calculator.java ================================================ class Solution { public int brokenCalc(int startValue, int target) { int ans = 0; while (target > startValue) { ans++; if (target % 2 == 1) target++; else target /= 2; } return ans + startValue - target; } } ================================================ FILE: 991-broken-calculator/NOTES.md ================================================ ​ ================================================ FILE: 991-broken-calculator/README.md ================================================

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
================================================ FILE: Add 1 to linked list.java ================================================ class Solution { public static Node addOne(Node head) { //code here. Node newHead=reverse(head); Node list=newHead; while(list!=null){ if(list.data<9){ list.data++; break; }else{ if(list.next==null){ list.next=new Node(0); } list.data=0; list=list.next; } } return reverse(newHead); } public static Node reverse(Node head){ Node cur=head; Node prev=null; while(cur!=null){ Node temp=cur.next; cur.next=prev; prev=cur; cur=temp; } return prev; } } ================================================ FILE: Add Binary Strings.java ================================================ import java.math.BigInteger; public class Solution { public String addBinary(String A, String B) { BigInteger a = new BigInteger(A, 2); BigInteger b = new BigInteger(B, 2); BigInteger c=a.add(b); return c.toString(2); } } ========================================================== public class Solution { public String addBinary(String A, String B) { StringBuilder sb = new StringBuilder(); int i = A.length() - 1; int j = B.length() - 1; int carry = 0; while(i>=0||j>=0){ int sum = carry; if(i>=0) sum =sum+A.charAt(i)-'0'; if(j>=0) sum += B.charAt(j)-'0'; sb.append(sum%2); carry = sum/2; i--;j--; } if(carry!=0) sb.append(carry); return sb.reverse().toString(); } } ================================================ FILE: Add Digits.java ================================================ class Solution { public int addDigits(int num) { if(num % 9 == 0 && num != 0) return 9; return num % 9; } } ================================================ FILE: Add One To Array.java ================================================ public class Solution { public int[] plusOne(int[] a) { //if all elements are 9 than increase size if(allNines(a)){ int[]ans=new int[a.length+1]; ans[0]=1; return ans; }else{ // add 1 to specified position for(int i=a.length-1;i>=0;i--){ if(a[i]+1<10){ a[i]=a[i]+1; break; }else{ a[i]=0; } } //check if there are preceding zeroes if yes then store index of first nonzero digit index int start=0; for(int i=0;i=0 || j>=0){ int sum=carry; if(i>=0)sum+=a.charAt(i)-'0'; if(j>=0)sum+=b.charAt(j)-'0'; carry=sum>1? 1:0; sb.append(sum%2); i--; j--; } if(carry != 0) sb.append(carry); return sb.reverse().toString(); } } ================================================ FILE: Adding Array Elements.java ================================================ class Solution { int minOperations(int[] arr, int n, int k) { // code here if(n==1)return 0; PriorityQueue pq=new PriorityQueue<>(); for(int i:arr)pq.add(i); int count=0; while(pq.size()>1){ if(pq.peek()>=k)break; int f=pq.remove(); int s=pq.remove(); int sum=f+s; count++; pq.add(sum); } if(pq.peek()

You have got a maze, which is a n*n Grid. Every cell of the maze contains these numbers 1, 2 or 3. 
If it contains 
1 : means we can go Right from that cell only.
If it contains 
2 : means we can go Down from that cell only.
If it contains 
3 : means we can go Right and Down to both paths from that cell.
We cant go out of the maze at any time.
Initially, You are on the Top Left Corner of The maze(Entry). And, You need to go to the Bottom Right Corner of the Maze(Exit).
You need to find the total number of paths from Entry to Exit Point.
There may be many paths but you need to select that path which contains the maximum number of Adventure.
The Adventure on a path is calculated by taking the sum of all the cell values thatlies
in the path.
 

Example 1:

Input: matrix = {{1,1,3,2,1},{3,2,2,1,2},
{1,3,3,1,3},{1,2,3,1,2},{1,1,1,3,1}}
Output: {4,18}
Explanation: There are total 4 Paths Available 
out of which The Max Adventure is 18. Total 
possible Adventures are 18,17,17,16. Of these 
18 is the maximum.

 

Your Task:
You don't need to read or print anything. Your task is to complete the function FindWays() which takes matrix as input parameter and returns a list containg total number of ways to reach at (n, n) modulo 109 + 7 and maximum number of Adventure.

 

Expected Time Complexity: O(n2)
Expected Space Complexity: O(n2)

 

Constraints:
1 <= n <= 100 

================================================ FILE: Adventure in a Maze - GFG/adventure-in-a-maze.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { int n = Integer.parseInt(br.readLine().trim()); int[][] matrix = new int[n][n]; for(int i = 0; i < n; i++){ String[] s = br.readLine().trim().split(" "); for(int j = 0; j < n; j++) matrix[i][j] = Integer.parseInt(s[j]); } Solution obj = new Solution(); int[] ans = obj.FindWays(matrix); for(int i = 0; i < ans.length; i++){ System.out.print(ans[i] + " "); } System.out.println(); } } } // } Driver Code Ends //User function Template for Java class Solution{ static int MOD = 1000000007; public int[] FindWays(int[][] matrix){ int n = matrix.length; int max_dp[][] = new int[n][n]; int count_dp[][] = new int[n][n]; for(int i=n-1; i>=0; i--){ for(int j=n-1; j>=0; j--){ if(i==n-1 && j==n-1){ count_dp[i][j] = 1; max_dp[i][j] = matrix[i][j]; }else{ int val = matrix[i][j]; if(val==1){ if(j+1 using namespace std; // } Driver Code Ends // User function Template for C++ class Solution{ void solve(int i,vector> v,vector &vis,string &res){ vis[i] = 1; for(auto a:v[i]){ if(!vis[a]) solve(a,v,vis,res); } char ch = i+'a'; res =ch+res; } public: string findOrder(string dict[], int n, int k) { vector> v(k); int i,j; for(i=0;i vis(k,0); string res = ""; for(i=0;i> t; while (t--) { int N, K; cin >> N >> K; string dict[N]; for (int i = 0; i < N; i++) cin >> dict[i]; Solution obj; string ans = obj.findOrder(dict, N, K); order = ""; for (int i = 0; i < ans.size(); i++) order += ans[i]; string temp[N]; std::copy(dict, dict + N, temp); sort(temp, temp + N, f); bool f = true; for (int i = 0; i < N; i++) if (dict[i] != temp[i]) f = false; if(f)cout << 1; else cout << 0; cout << endl; } return 0; } // } Driver Code Ends ================================================ FILE: All Elements in Two Binary Search Trees.java ================================================ class Solution { public List getAllElements(TreeNode root1, TreeNode root2) { LinkedList ret = new LinkedList<>(); List ret2 = new ArrayList<>(); dfs(root1, ret); dfs2(root2, ret2, ret); if (ret.size()>0) ret2.addAll(ret); return ret2; } private void dfs(TreeNode node, LinkedList ret) { if (node==null) return; if (node.left!=null) dfs(node.left, ret); ret.add(node.val); if (node.right!=null) dfs(node.right, ret); } private void dfs2(TreeNode node, List ret, LinkedList ex) { if (node==null) return; if (node.left!=null) dfs2(node.left, ret, ex); while(!ex.isEmpty() && ex.peekFirst() specialStrings(ArrayList A) { ArrayList ans=new ArrayList<>(); dfs(ans,A,new StringBuilder()); return ans; } void dfs(ArrayList ans,ArrayList arr,StringBuilder sb){ if(sb.length()==arr.size()){ ans.add(sb.toString()); return; } String s=arr.get(sb.length()); for(int i=0;i> lists; boolean[] added; public ArrayList> permute(ArrayList nums) { lists = new ArrayList<>(); Collections.sort(nums); added = new boolean[nums.size()]; permuteUnique(nums, new ArrayList<>()); return lists; } private void permuteUnique(ArrayList nums, List list) { if(list.size() == nums.size()) { lists.add(new ArrayList(list)); return; } for(int i = 0; i < nums.size(); i++) { if(added[i]) continue; if(i > 0 && nums.get(i) == nums.get(i-1) && !added[i - 1]) continue; list.add(nums.get(i)); added[i] = true; permuteUnique(nums, list); list.remove(list.size() - 1); added[i] = false; } } } ================================================ FILE: Allocate minimum number of pages.cpp ================================================ class Solution { public: //Function to find minimum number of pages. bool allocationPoss(int p,int M,int A[],int n){ int stds = 0, pages = p; for(int i=0;ip) return false; if(A[i]+pages>p){ stds++; pages = A[i]; }else pages+=A[i]; if(stds>M) return false; } return true; } int findPages(int A[], int N, int M) { if(M>N) return -1; int start = A[0],end = A[0]; for(int i=1;i st,st1; for(int i=n-1;i>=0;i--){ if(arr[i]>=0) st.push(arr[i]); else st1.push(arr[i]); } for(int i=0;i=0){ //need pos if(needNeg==false){ needNeg=true; }else{ //find neg int j=i+1; while(j=0){ j++; } if(j==n)return; int ele=arr[j]; j--; while(j>=i){ arr[j+1]=arr[j]; j--; } arr[i]=ele; needNeg=false; } }else{ //needed neg if(needNeg==true){ needNeg=false; }else{ //find pos int j=i+1; while(j=i){ arr[j+1]=arr[j]; j--; } arr[i]=ele; needNeg=true; } } } } } ================================================ FILE: Anagram of String.java ================================================ class GfG { public int remAnagrams(String s,String s1){ //add code here. int[]fq=new int[26]; for(char c:s.toCharArray()){ fq[c-'a']++; } for(char c:s1.toCharArray()){ fq[c-'a']--; } int ans=0; for(int i:fq){ ans+=Math.abs(i); } return ans; } } ================================================ FILE: Anagrams.java ================================================ public class Solution { // DO NOT MODIFY THE LIST. IT IS READ ONLY public ArrayList> anagrams(final List A) { ArrayList> ans=new ArrayList<>(); HashMap,Integer> map=new HashMap<>(); int listIndex=0; for(int i=0;i curr=new HashMap<>(); for(char c:s.toCharArray())curr.put(c,curr.getOrDefault(c,0)+1); if(!map.containsKey(curr)){ map.put(curr,listIndex); ans.add(new ArrayList<>()); ans.get(listIndex).add(i+1); listIndex++; }else{ int idx=map.get(curr); ans.get(idx).add(i+1); } } return ans; } } ================================================ FILE: Anti Diagonals.py ================================================ class Solution: def diagonal(self, A): output=[] outputIndex=0 # UPPER for i in range(0, len(A)): x = 0 y = i output.append([]) for j in range(i+1): output[outputIndex].append(A[x][y]) x += 1 y -= 1 outputIndex += 1 # LOWER for i in range(1, len(A)): x = i y = len(A) - 1 output.append([]) for j in range(len(A)-i): output[outputIndex].append(A[x][y]) x += 1 y -= 1 outputIndex += 1 return output ================================================ FILE: Arithmetic Slices.java ================================================ class Solution { public int numberOfArithmeticSlices(int[] nums) { int n = nums.length; if (n<3){ return 0; } int ans=0; int[] dp = new int[n]; for(int i=2;i A, final List B, final List C) { int diff = Integer.MAX_VALUE; int res_i =0, res_j = 0, res_k = 0; int i = 0, j = 0, k = 0; while (i < A.size() && j < B.size() && k < C.size()){ int minimum = Math.min(A.get(i), Math.min(B.get(j), C.get(k))); int maximum = Math.max(A.get(i), Math.max(B.get(j), C.get(k))); // Update result if current diff is // less than the min diff so far if (maximum-minimum < diff){ res_i = i; res_j = j; res_k = k; diff = maximum - minimum; } // We can't get less than 0 // as values are absolute if (diff == 0) break; // Increment index of array // with smallest value if (A.get(i)== minimum) i++; else if (B.get(j) == minimum) j++; else k++; } int minimum = Math.min(A.get(res_i), Math.min(B.get(res_j), C.get(res_k))); int maximum = Math.max(A.get(res_i), Math.max(B.get(res_j), C.get(res_k))); return maximum-minimum; } public int abs(int a){ if(a<0){ return -a; } return a; } } ================================================ FILE: Array Partition - GFG/README.md ================================================ # Array Partition ## Hard

Given an array of N integers, you have to find if it is possible to partition the array with following rules:

  • Each element should belong to exactly one partition.
  • Each partition should have atleast K elements.
  • Absolute difference between any pair of elements in the same partition should not exceed M.

Example 1:

Input:
N = 5
K = 2
M = 3
A[] = {8, 3, 9, 1, 2}
Output:
YES
Explanation:
We can partition the array into two 
partitions: {8, 9} and {3, 1, 2} such that
all rules are satisfied.

Your Task:
You don't need to read input or print anything. Your task is to complete the function partitionArray() which takes the number of elements N, integer K, integer and array A[ ] as input parameters and returns true if we can partition the array such that all rules are satisfied, else returns false.

Expected Time Complexity: O(N * Log(N))
Expected Auxiliary Space: O(N)

Constraints:
1 ≤ N ≤ 2*105
1 ≤ K ≤ N
1 ≤ M ≤ 109
1 ≤ A[i] ≤ 109

================================================ FILE: Array Partition - GFG/array-partition.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; import java.lang.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int test = Integer.parseInt(br.readLine()); while(test-- > 0) { String [] str = br.readLine().trim().split(" "); int N = Integer.parseInt(str[0]); int K = Integer.parseInt(str[1]); int M = Integer.parseInt(str[2]); int [] A = new int[N]; str = br.readLine().trim().split(" "); for(int i = 0; i < N; i++) A[i] = Integer.parseInt(str[i]); Solution obj = new Solution(); boolean ans = obj.partitionArray(N, K, M, A); if(ans){ System.out.println("YES"); } else{ System.out.println("NO"); } } } }// } Driver Code Ends //User function Template for Java class Solution{ boolean rec( int start , int[] A , int K , int M ){ int n = A.length ; if(start >= n) return true ; for ( int i = start + K - 1 ; i < n ; i ++ ){ if( (A[i] - A[start]) > M) return false ; if(rec(i+1 , A , K , M )) return true ; } return false ; } boolean partitionArray(int N, int K, int M, int [] A){ // code here Arrays.sort(A); return rec(0 , A , K , M ) ; } } ================================================ FILE: Array Sum.java ================================================ public class Solution { public int[] addArrays(int[] A, int[] B) { int n1=A.length; int n2=B.length; int[] sum = new int[n1>n2?n1:n2]; int i=n1-1; int j=n2-1; int k=sum.length-1; int c=0; while(k>=0){ int d = c; if(i>=0){ d+=A[i]; } if(j>=0){ d+=B[j]; } c=d/10; d=d%10; sum[k]=d; i--; j--; k--; } if(c!=0){ int[] ans = new int[(n1>n2?n1:n2) + 1]; ans[0]=c; for (i = 0; i < ans.length-1; i++) ans[i+1] = sum[i]; return ans; } return sum; } } ================================================ FILE: Array to BST - GFG/README.md ================================================ # 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

 

================================================ FILE: Array to BST - GFG/array-to-bst.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { int n = Integer.parseInt(br.readLine().trim()); int[] nums = new int[n]; String[] S = br.readLine().trim().split(" "); for(int i = 0; i < n; i++){ nums[i] = Integer.parseInt(S[i]); } Solution obj = new Solution(); int[] ans = obj.sortedArrayToBST(nums); for(int i = 0; i < ans.length; i++) System.out.print(ans[i] + " "); System.out.println(); } } } // } Driver Code Ends //User function Template for Java class Solution{ public void fillArray(int[] res,int[] n, int s, int e, int[] i){ if(s>e)return; int mid=s+(e-s)/2; res[i[0]]=n[mid]; i[0]++; fillArray(res,n,s,mid-1,i); fillArray(res,n,mid+1,e,i); } public int[] sortedArrayToBST(int[] n){ int[] res=new int[n.length], i=new int[1]; int s=0,e=n.length-1; fillArray(res,n,s,e,i); return res; } } ================================================ FILE: Assign Mice to Holes.java ================================================ public class Solution { public int mice(int[] A, int[] B) { Arrays.sort(A); Arrays.sort(B); int ans=0; for(int i=0;i

You are the head of a firm and you have to assign jobs to people. You have N persons working under you and you have N jobs that are to be done by these persons. Each person has to do exactly one job and each job has to be done by exactly one person. Each person has his own capability (in terms of time taken) to do any particular job. Your task is to assign the jobs to the persons in such a way that the total time taken is minimum. A job can be assigned to only one person and a person can do only one job.

 

Example 1:

Input:
N = 2
Arr[] = {3, 5, 10, 1}
Output:
4
Explanation:
The first person takes times 3 and 5
for jobs 1 and 2 respectively. The second
person takes times 10 and 1 for jobs 1 and
2 respectively. We can see that the optimal
assignment will be to give job 1 to person 1
and job 2 to person 2 for a total for 3+1 = 4.

Example 2:

Input:
N = 3
Arr[] = {2, 1, 2, 9, 8, 1, 1, 1, 1}
Output:
3 
Explanation: 
The optimal arrangement would be to assign 
job 1 to person 3,job 2 to person 1 and job 
3 to person 2.

 

Your Task:
You don't need to read input or print anything. Your task is to complete the function assignmentProblem() which takes an Integer N and an array Arr[] of size N2 as input and returns the time taken for the best possible assignment.

 

Expected Time Complexity: O(N2)
Expected Auxiliary Space: O(N2)

 

Constraints:
1 <= N <= 30
1 <= Arr[i] <= 100

================================================ FILE: Assignment Problem - GFG/assignment-problem.cpp ================================================ // { Driver Code Starts #include using namespace std; // } Driver Code Ends class Solution { public: int cost[31][31]; //cost matrix int n, max_match; //n workers and n jobs int lx[31], ly[31]; //labels of X and Y parts int xy[31]; //xy[x] - vertex that is matched with x, int yx[31]; //yx[y] - vertex that is matched with y bool S[31], T[31]; //sets S and T in algorithm int slack[31]; //as in the algorithm description int slackx[31]; //slackx[y] such a vertex, that int prev_ious[31]; //array for memorizing alternating p void init_labels() { memset(lx, 0, sizeof(lx)); memset(ly, 0, sizeof(ly)); for (int x = 0; x < n; x++) for (int y = 0; y < n; y++) lx[x] = max(lx[x], cost[x][y]); } void update_labels() { int x, y; int delta = 99999999; //init delta as infinity for (y = 0; y < n; y++) //calculate delta using slack if (!T[y]) delta = min(delta, slack[y]); for (x = 0; x < n; x++) //update X labels if (S[x]) lx[x] -= delta; for (y = 0; y < n; y++) //update Y labels if (T[y]) ly[y] += delta; for (y = 0; y < n; y++) //update slack array if (!T[y]) slack[y] -= delta; } void add_to_tree(int x, int prev_iousx) //x - current vertex,prev_iousx - vertex from X before x in the alternating path, //so we add edges (prev_iousx, xy[x]), (xy[x], x) { S[x] = true; //add x to S prev_ious[x] = prev_iousx; //we need this when augmenting for (int y = 0; y < n; y++) //update slacks, because we add new vertex to S if (lx[x] + ly[y] - cost[x][y] < slack[y]) { slack[y] = lx[x] + ly[y] - cost[x][y]; slackx[y] = x; } } void augment() //main function of the algorithm { if (max_match == n) return; //check wether matching is already perfect int x, y, root; //just counters and root vertex int q[31], wr = 0, rd = 0; //q - queue for bfs, wr,rd - write and read //pos in queue memset(S, false, sizeof(S)); //init set S memset(T, false, sizeof(T)); //init set T memset(prev_ious, -1, sizeof(prev_ious)); //init set prev_ious - for the alternating tree for (x = 0; x < n; x++) //finding root of the tree { if (xy[x] == -1) { q[wr++] = root = x; prev_ious[x] = -2; S[x] = true; break; } } for (y = 0; y < n; y++) //initializing slack array { slack[y] = lx[root] + ly[y] - cost[root][y]; slackx[y] = root; } //second part of augment() function while (true) //main cycle { while (rd < wr) //building tree with bfs cycle { x = q[rd++]; //current vertex from X part for (y = 0; y < n; y++) //iterate through all edges in equality graph if (cost[x][y] == lx[x] + ly[y] && !T[y]) { if (yx[y] == -1) break; //an exposed vertex in Y found, so //augmenting path exists! T[y] = true; //else just add y to T, q[wr++] = yx[y]; //add vertex yx[y], which is matched //with y, to the queue add_to_tree(yx[y], x); //add edges (x,y) and (y,yx[y]) to the tree } if (y < n) break; //augmenting path found! } if (y < n) break; //augmenting path found! update_labels(); //augmenting path not found, so improve labeling wr = rd = 0; for (y = 0; y < n; y++) //in this cycle we add edges that were added to the equality graph as a //result of improving the labeling, we add edge (slackx[y], y) to the tree if //and only if !T[y] && slack[y] == 0, also with this edge we add another one //(y, yx[y]) or augment the matching, if y was exposed if (!T[y] && slack[y] == 0) { if (yx[y] == -1) //exposed vertex in Y found - augmenting path exists! { x = slackx[y]; break; } else { T[y] = true; //else just add y to T, if (!S[yx[y]]) { q[wr++] = yx[y]; //add vertex yx[y], which is matched with //y, to the queue add_to_tree(yx[y], slackx[y]); //and add edges (x,y) and (y, //yx[y]) to the tree } } } if (y < n) break; //augmenting path found! } if (y < n) //we found augmenting path! { max_match++; //increment matching //in this cycle we inverse edges along augmenting path for (int cx = x, cy = y, ty; cx != -2; cx = prev_ious[cx], cy = ty) { ty = xy[cx]; yx[cy] = cx; xy[cx] = cy; } augment(); //recall function, go to step 1 of the algorithm } }//end of augment() function int hungarian() { int ret = 0; //weight of the optimal matching max_match = 0; //number of vertices in current matching memset(xy, -1, sizeof(xy)); memset(yx, -1, sizeof(yx)); init_labels(); //step 0 augment(); //steps 1-3 for (int x = 0; x < n; x++) //forming answer there ret += cost[x][xy[x]]; return ret; } int assignmentProblem(int Arr[], int N) { n = N; for(int i=0; i> t; while (t--) { int n; cin>>n; int Arr[n*n]; for(int i=0; i>Arr[i]; Solution ob; cout << ob.assignmentProblem(Arr,n) << endl; } return 0; } // } Driver Code Ends ================================================ FILE: Assignment Problem - GFG/assignment-problem.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { int N = Integer.parseInt(read.readLine()); String S[] = read.readLine().split(" "); int[] Arr = new int[N*N]; for(int i=0; i0){ for(int col=0;col averageOfLevels(TreeNode* root) { vector ans; queue q; q.push(root); // while there are nodes remaining to be visited while(!q.empty()){ double temp = q.size(); double sum = 0; // iterating each level of binary tree for(int i = 0; i < temp; i++){ auto tt = q.front(); q.pop(); sum += (tt->val); // check for not NULL and pushing into queue. if(tt->left){ q.push(tt->left); } if(tt->right){ q.push(tt->right); } } ans.push_back(sum/ temp); } return ans; } }; ================================================ FILE: Average of levels in binary tree.java ================================================ class Solution { public List averageOfLevels(TreeNode root) { List result=new ArrayList<>(); Queue que=new LinkedList<>(); que.add(root); while(!que.isEmpty()){ int size=que.size(); double sum=0; for(int i=0;i&pq) { if(!root) return; pq.push(root->data); recur(root->left,pq); recur(root->right,pq); } void change(Node *root,priority_queue&pq) { if(!root or pq.empty()) return; root->data=pq.top(); pq.pop(); change(root->right,pq); change(root->left,pq); } void convertToMaxHeapUtil(Node* root) { // Your code goes here priority_queuepq; recur(root,pq); change(root,pq); } }; ================================================ FILE: BST to greater sum tree - GFG/README.md ================================================ # BST to greater sum tree ## Medium

Given a BST, transform it into greater sum tree where each node contains sum of all nodes greater than that node.

Example 1:

Input:
           2
         /    \
        1      6
              /  \
             3    7
Output: 18 16 13 7 0
Explanation:
Every node is replaced with the 
sum of nodes greater than itself. 
The resultant tree is:
               16
             /    \
           18       7
                  /   \
                 13    0

Example 2:

Input:
          2
         /
        1
Output: 2 0
Explanation:
The resultant tree is :
             0
            /
          2
Your task :
You don't have to read input or print anything. Your task is to complete the function transformTree() which takes the root of the tree as input and transforms the BST to a greater sum tree.
Note : The driver code prints the inorder traversal of the transformed BST.
 
Expected Time Complexity: O(N), N = number of nodes
Expected Auxiliary Space: O(N), N = number of nodes
 
Constraints :
1 ≤ N ≤ 104

================================================ FILE: BST to greater sum tree - GFG/bst-to-greater-sum-tree.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.LinkedList; import java.util.Queue; import java.io.*; import java.util.*; class Node{ int data; Node left; Node right; Node(int data){ this.data = data; left=null; right=null; } } class Tree { static Node buildTree(String str){ if(str.length()==0 || str.charAt(0)=='N'){ return null; } String ip[] = str.split(" "); // Create the root of the tree Node root = new Node(Integer.parseInt(ip[0])); // Push the root to the queue Queue queue = new LinkedList<>(); queue.add(root); // Starting from the second element int i = 1; while(queue.size()>0 && i < ip.length) { // Get and remove the front of the queue Node currNode = queue.peek(); queue.remove(); // Get the current node's value from the string String currVal = ip[i]; // If the left child is not null if(!currVal.equals("N")) { // Create the left child for the current node currNode.left = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.left); } // For the right child i++; if(i >= ip.length) break; currVal = ip[i]; // If the right child is not null if(!currVal.equals("N")) { // Create the right child for the current node currNode.right = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.right); } i++; } return root; } static void inOrder(Node root) { if(root == null) return; inOrder(root.left); System.out.print(root.data+" "); inOrder(root.right); } public static void main (String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t > 0){ String s = br.readLine(); Node root = buildTree(s); Solution g = new Solution(); g.transformTree(root); inOrder(root); System.out.println(); t--; } } } // } Driver Code Ends //User function Template for Java /*class Node{ int data; Node left; Node right; Node(int data){ this.data = data; left=null; right=null; } } */ class Solution { static int sum; public static void transformTree (Node root) { //code here sum=0; dfs(root); } static void dfs(Node root){ if(root==null)return; dfs(root.right); int temp=root.data; root.data=sum; sum+=temp; dfs(root.left); } } ================================================ FILE: BST to max heap GFG/BstToMaxHeap.cpp ================================================ void helper1(Node *root,vector&ans){ if(root==NULL){ return; } helper1(root->left,ans); ans.push_back(root->data); helper1(root->right,ans); } void helper2(Node *root,vector&ans,int &index){ if(root==NULL)return; helper2(root->left,ans,index); helper2(root->right,ans,index); root->data=ans[index]; index++; } void convertToMaxHeapUtil(Node* root) { vectorans; helper1(root,ans); int index=0; helper2(root,ans,index); } ================================================ FILE: BST to max heap gfg med.cpp ================================================ //{ Driver Code Starts //Initial Template for C++ #include using namespace std; struct Node { int data; Node *left, *right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ Node* newNode(int val) { Node* temp = new Node; temp->data = val; temp->left = NULL; temp->right = NULL; return temp; } 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; } void postorderTraversal(Node* root) { if (!root) return; // recur on left subtree postorderTraversal(root->left); // then recur on right subtree postorderTraversal(root->right); // print the root's data cout << root->data << " "; } class Solution{ public: vector v; int i =0; void postorder(Node* root){ if(!root) return; postorder(root->left); postorder(root->right); root->data = v[i++]; } void inorder(Node *root){ if(!root) return; inorder(root->left); v.push_back(root->data); inorder(root->right); } void convertToMaxHeapUtil(Node* root) { // Your code goes here inorder(root); postorder(root); } }; int main() { int t; cin >> t; getchar(); while (t--) { string inp, ch; getline(cin, inp); struct Node* root = buildTree(inp); Solution ob; ob.convertToMaxHeapUtil(root); postorderTraversal(root); cout << "\n"; } return 0; } ================================================ FILE: BST-to-max-Heap/BSTtoMaxHeap.java ================================================ class Solution { static int i=0; public static void convertToMaxHeapUtil(Node root) { //code here ArrayList nodes=new ArrayList<>(); i=0; inOrder(root, nodes); } public static void inOrder(Node root, ArrayList nodes) { if(root==null) return ; inOrder(root.left, nodes); nodes.add(root.data); //adding data to ArrayList stores in Ascending order inOrder(root.right, nodes); root.data=nodes.get(i++); //Modifying root value in postOrder Traversal, so that All Left and Right Nodes store lesser value compared to root as ArrayList stores in Ascending Order } } ================================================ FILE: BST-to-max-Heap/Solution.cpp ================================================ class Solution{ public: Node* helper(Node* root){ if(!root)return NULL; Node* left=helper(root->left); Node* right=helper(root->right); if(!left&&!right)return root; if(!left&&right){ if(right->data>root->data){swap(root->data,right->data);helper(root->right);} } else if(left&&!right){ if(left->data>root->data){swap(root->data,left->data); helper( root->left);} } else{ if(left->data>root->data){swap(root->data,left->data); helper( root->left);} if(right->data>root->data){swap(root->data,right->data);helper(root->right);} } return root; } void convertToMaxHeapUtil(Node* root) { helper(root); } }; ================================================ FILE: BST-to-max-Heap/question.md ================================================ ### BST to max heap **Medium**Accuracy: **70.68%**Submissions: **4473**Points: **4** Given a Binary Search Tree. Convert a given BST into a Special Max Heap with the condition that all the values in the left subtree of a node should be less than all the values in the right subtree of the node. This condition is applied on all the nodes in the so converted Max Heap. **Example 1:** ``` Input : 4 / \ 2 6 / \ / \ 1 3 5 7 Output : 1 2 3 4 5 6 7 Exaplanation : 7 / \ 3 6 / \ / \ 1 2 4 5 The given BST has been transformed into a Max Heap and it's postorder traversal is 1 2 3 4 5 6 7. ``` **Your task :** You don't need to read input or print anything. Your task is to complete the function convertToMaxHeapUtil() which takes the root of the tree as input and converts the BST to max heap. Note : The driver code prints the postorder traversal of the converted BST. **Expected Time Complexity : **O(n) **Expected Auxiliary Space : **O(n) **Constraints :** 1 ≤ n ≤ 10^5^ ================================================ FILE: Bag Of Tokens.java ================================================ class Solution { public int bagOfTokensScore(int[] tokens, int power) { int ans=0; Arrays.sort(tokens); //sorted the tokens as in question they mentioned to take in any order int i=0, j=tokens.length-1, steps=0; while(i<=j) { if(tokens[i]<=power) { //if current value is less than equal to power we reduce power and increase steps power-=tokens[i]; steps+=1; i+=1; } else { //else we need to increase power to continue further if(steps>0) { //if steps > 0, we can increase power and reduces steps by 1 power+=tokens[j]; j-=1; steps-=1; } else { // if steps ==0 , we cannot increase power according to question and we cannot increase power. As array is sorted, we cannot increase steps as power is less than all other tokens hence break loop break; } } ans=Math.max(ans, steps); // At each step calculate max Ans as we no need to consider all the tokens } return ans; } } ================================================ FILE: Balance Array.java ================================================ class Solution: # @param A : list of integers # @return an integer def solve(self, A): arr=A s1=0 s2=0 n=len(A) s3=0 s4=0 for i in range(n): if i%2: s2+=arr[i] else: s1+=arr[i] c=0 for i in range(n): if i%2: s2-=arr[i] if s2+s4==s1+s3: c+=1 s3+=arr[i] else: s1-=arr[i] if s2+s4==s3+s1: c+=1 s4+=arr[i] return c ================================================ FILE: Balanced Binary Tree.java ================================================ public class Solution { public int isBalanced(TreeNode A) { if(A==null) return 1; Queue queue=new LinkedList<>(); queue.add(A); while(!queue.isEmpty()){ TreeNode current=queue.remove(); if(Math.abs(getHeight(current.left)-getHeight(current.right))>1) return 0; if(current.left!=null) queue.add(current.left); if(current.right!=null) queue.add(current.right); } return 1; } int getHeight(TreeNode root){ if(root==null) return -1; else return 1+Math.max(getHeight(root.left),getHeight(root.right)); } } ================================================ FILE: Balanced Parantheses!.java ================================================ public class Solution { public int solve(String A) { ArrayDeque st=new ArrayDeque<>(); for(int i=0;i0)return 0; return 1; } } ================================================ FILE: Ball Coloring.cpp ================================================ class Solution { public: unsigned long long int noOfWays(unsigned long long int n){ // code here if(n<3){ return n*2; } else{ return ((n*n)-(n-2)); } } }; ================================================ FILE: Ball coloring.cpp ================================================ class Solution { public: unsigned long long int noOfWays(unsigned long long int n){ // code here if(n<3){ return n*2; } else{ return ((n*n)-(n-2)); } } }; ================================================ FILE: Ball coloring.java ================================================ class Solution { static long noOfWays(long n){ // code here return 2 + n * (n - 1); } } ================================================ FILE: Ball coloring.py ================================================ class Solution: def noOfWays (self, n): return (n*(n-1))+2; ================================================ FILE: Ball-Coloring/ball_coloring.java ================================================ class Solution{ static long noOfWays(long n){ // code here return (n*(n-1)+2); } } ================================================ FILE: Ball-Coloring/question.md ================================================ Given n balls . All of them are initially uncolored . You have to color the balls with two colors RED and BLUE such that there can be atmost 2 positions where a RED ball is touching BLUE ball or vice versa. You have to color all the balls.Find the number of ways in which balls can be colored. **Example 1:** ``` Input: n = 1 Output: 2 Explanation: Possible ways to color are {{R},{B}}. So the answer is 2 . ``` **Example 2:** ``` Input: n = 2 Output: 4 Explanation: Possible ways to color are {{RB},{BR},{RR},{BB}}.So the answer is 4. ``` **Your Task: ** You dont need to read input or print anything. Complete the function **noOfWays() **which takes n as input parameter and returns the number of ways in which balls can be colored. **Expected Time Complexity:** O(1) **Expected Auxiliary Space:** O(1) **Constraints:** 1<= n <=10^5^ ================================================ FILE: Best Time to Buy and Sell Stock IV.java ================================================ class Solution { public int maxProfit(int k, int[] prices) { int [][][]dp=new int[k+1][prices.length+1][2]; for(int i=0;i=prices.length) return 0; if(k==0) return 0; if(dp[k][ind][buy]!=-1) { return dp[k][ind][buy]; } int ans1=0, ans2=0, ans3=0, ans4=0; if(buy==0) { ans1=maximumProfit(prices, k, ind+1, buy, dp); //not buying in this index and continuing ans2=-prices[ind]+maximumProfit(prices, k, ind+1, 1, dp); //buying at this index by passing 1 by subtracting the current amount and continuing } else { ans3=maximumProfit(prices, k, ind+1, buy, dp); //not selling at this index and continuing ans4=(prices[ind])+maximumProfit(prices, k-1, ind+1, 0, dp); //selling at this index by adding current index amount and reducing transactions by 1 and continuing } return dp[k][ind][buy]=Math.max(ans1, Math.max(ans2, Math.max(ans3, ans4))); // taking maximum of all these combinations } } ================================================ FILE: Best Time to Buy and Sell Stock.java ================================================ class Solution { public int maxProfit(int[] prices) { int min=Integer.MAX_VALUE; int max=0; for(int i=0;i

Geek is organising a bike race with N bikers. The initial speed of the ith biker is denoted by Hi Km/hr and the acceleration of ith biker as Ai Km/Hr2. A biker whose speed is 'L' or more, is considered be a fast biker. The total speed on the track for every hour is calculated by adding the speed of each fast biker in that hour. When the total speed on the track is 'M' kilometers per hour or more, the safety alarm turns on. 
Find the minimum number of hours after which the safety alarm will start.


Example 1:

Input: 
N = 3, M = 400, L = 120
H = {20, 50, 20}
A = {20, 70, 90}
Output: 3
Explaination: 
Speeds of all the Bikers at ith hour
Biker1= [20  40  60  80 100] 
Biker2= [50 120 190 260 330]
Biker3= [20 110 200 290 380] 

Initial Speed on track  = 0 
because none of the biker's speed is fast enough.
Speed on track after 1st Hour= 120
Speed on track after 2nd Hour= 190+200=390
Speed on track after 3rd Hour= 260+290=550
Alarm will start at 3rd Hour.


Example 2:

Input: 
N = 2, M = 60, L = 120
H = {50, 30}
A = {20, 40}
Output: 3
Explaination: 
Speeds of all the Bikers at ith hour
Biker1= [50 70  90 110 130] 
Biker2= [30 70 110 150 190]

Initial Speed on track = 0 because none of the 
biker's speed is fast enough.
Speed on track at 1st Hour= 0
Speed on track at 2nd Hour= 0
Speed on track at 3rd Hour= 150
Alarm will buzz at 3rd Hour.


Your Task:
You do not need to read input or print anything. Your task is to complete the function buzzTime() which takes N, M, L and array H and array A as input parameters and returns the time when alarm buzzes.


Expected Time Complexity: O(N*log(max(L,M)))
Expected Auxiliary Space: O(1)


Constraints:
1 ≤ N ≤ 105
1 ≤ L, M ≤ 1010
1 ≤ Hi, Ai ≤ 109  

================================================ FILE: Bike Racing - GFG/bike-racing.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[])throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); while(t-- > 0){ String a[] = in.readLine().trim().split("\\s+"); int N = Integer.parseInt(a[0]); long M = Long.parseLong(a[1]); long L = Long.parseLong(a[2]); long H[] = new long[N]; long A[] = new long[N]; for(int i = 0; i < N; i++){ String a1[] = in.readLine().trim().split("\\s+"); H[i] = Long.parseLong(a1[0]); A[i] = Long.parseLong(a1[1]); } Solution ob = new Solution(); System.out.println(ob.buzzTime(N, M, L, H, A)); } } }// } Driver Code Ends //User function Template for Java class Solution{ static boolean check(long T, long L, long S[], long A[], long N, long M){ long ans = 0; for(int i=0;i=L ? x : 0); } return ans >= M; } static long buzzTime(long N, long M, long L, long H[], long A[]) { long low,high,mid; low = 0; high = M; while(low largestSquare(ArrayList> M, int R, int C, int K, int Q, int[] q_i, int[] q_j) { // code here ArrayList ans=new ArrayList<>(); int[][]dp=new int[R][C]; dp[0][0]=M.get(0).get(0); for(int i=1;i0)count-=dp[x2][y1-1]; if(x1>0)count-=dp[x1-1][y2]; if(x1>0 && y1>0)count+=dp[x1-1][y1-1]; if(count<=K){ curr=2*k+1; l=k+1; }else{ h=k-1; } } ans.add(curr); } return ans; } }; ================================================ FILE: Binary Tree Pruning lc.cpp ================================================ #include using namespace std; class Solution { public: // TC: O(N) where N is the number of the nodes in the tree // SC: O(H) where H is the height of the tree // In worse case, H can be N when it is a left skewed binary tree / right skewed binary tree TreeNode* pruneTree(TreeNode* root) { // if root is nullptr, then return nullptr if(!root) return nullptr; // DFS on left sub tree root->left = pruneTree(root->left); // DFS on right sub tree root->right = pruneTree(root->right); // !root->left means left sub tree does not contain 1 // !root->right means right sub tree does not contain 1 // !root->val means curr_node val is 0 // for this case , return nullptr else keep node return(!root->left && !root->right && !root->val) ? nullptr : root; } }; ================================================ FILE: Binary Tree Pruning.java ================================================ class Solution { public TreeNode pruneTree(TreeNode root) { make(root); //In this function checked all childs of root, whether they contain root node 1 as sub tree, if does not exist removed the node if(root.left==null && root.right==null && root.val==0) return null; // This is the case when only single node present and it is 0 In that case we should return null return root; } public boolean make(TreeNode root) { if(root==null) return false; boolean left=make(root.left); boolean right=make(root.right); if(left==false) { if(root.left!=null) root.left=null; } if(right==false) { if(root.right!=null) root.right=null; } if(left==true || right==true) return true; if(root.val==1) return true; return false; } } ================================================ FILE: Bipartite Graph - GFG/README.md ================================================ # Bipartite Graph ## Medium

Given an adjacency list of a graph adj  of V no. of vertices having 0 based index. Check whether the graph is bipartite or not.
 

Example 1:

Input: 

Output: 1
Explanation: The given graph can be colored 
in two colors so, it is a bipartite graph.

Example 2:

Input:

Output: 0
Explanation: The given graph cannot be colored 
in two colors such that color of adjacent 
vertices differs. 

 

Your Task:
You don't need to read or print anything. Your task is to complete the function isBipartite() which takes V denoting no. of vertices and adj denoting adjacency list of the graph and returns a boolean value true if the graph is bipartite otherwise returns false.

 

Expected Time Complexity: O(V + E)
Expected Space Complexity: O(V)

Constraints:
1 ≤ V, E ≤ 105

================================================ FILE: Bipartite Graph - GFG/bipartite-graph.java ================================================ // { Driver Code Starts import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String[] S = br.readLine().trim().split(" "); int V = Integer.parseInt(S[0]); int E = Integer.parseInt(S[1]); ArrayList> adj = new ArrayList<>(); for(int i = 0; i < V; i++){ adj.add(new ArrayList()); } for(int i = 0; i < E; i++){ String[] s = br.readLine().trim().split(" "); int u = Integer.parseInt(s[0]); int v = Integer.parseInt(s[1]); adj.get(u).add(v); adj.get(v).add(u); } Solution obj = new Solution(); boolean ans = obj.isBipartite(V, adj); if(ans) System.out.println("1"); else System.out.println("0"); } } }// } Driver Code Ends class Solution { public boolean isBipartite(int V, ArrayList>adj) { boolean[] vis=new boolean[V+1]; boolean[] color=new boolean[V+1]; Queue q=new LinkedList<>(); for(int i=0;i using namespace std; // } Driver Code Ends // User function Template for C++ class Solution{ public: int countBits(int N, long long int A[]) { int m=log2(*max_element(A,A+N)); int mod=1000000007; int r=0; for(int i=0;i<=m;i++) { long long c=0; for(int j=0;j>t; while(t--){ int N; cin>>N; long long int A[N]; for(int i = 0;i < N; i++) cin>>A[i]; Solution ob; cout<=0;i--){ int bit=(X>>i)&1; if(bit==1){ p=p|(1< using namespace std; bool isPossible(int arr[],int m,int n,int mid) { int StudentCount = 1; int pageSum = 0; for(int i = 0; i m || arr[i] > mid) { return false; } pageSum = arr[i]; } } return true; } int allocatedBooK(int arr[],int m,int n) { int start = 0; int sum = 0; for(int i =0;i

Given an array p[] of length n used to denote the dimensions of a series of matrices such that dimension of i'th matrix is p[i] * p[i+1]. There are a total of n-1 matrices. Find the most efficient way to multiply these matrices together. 
The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications such that you need to perform minimum number of multiplications. There are many options to multiply a chain of matrices because matrix multiplication is associative i.e. no matter how one parenthesize the product, the result will be the same.


Example 1:

Input: 
n = 5
p[] = {1, 2, 3, 4, 5}
Output: (((AB)C)D)
Explaination: The total number of 
multiplications are (1*2*3) + (1*3*4) 
+ (1*4*5) = 6 + 12 + 20 = 38.

 

Example 2:

Input: 
n = 3
p = {3, 3, 3}
Output: (AB)
Explaination: The total number of 
multiplications are (3*3*3) = 27.

 

Your Task:
You do not need to read input or print anything. Your task is to complete the function matrixChainOrder() which takes n and p[] as input parameters and returns the string with the proper order of parenthesis for n-1 matrices. Use uppercase alphabets to denote each matrix.


Expected Time Complexity: O(n3)
Expected Auxiliary Space: O(n2)


Constraints:
2 ≤ n ≤ 26 
1 ≤ p[i] ≤ 500 

================================================ FILE: Brackets in Matrix Chain Multiplication - GFG/brackets-in-matrix-chain-multiplication.cpp ================================================ // { Driver Code Starts // Initial Template for C++ #include using namespace std; // } Driver Code Ends // User function Template for C++ class Solution { // Cache map> dp; public: string matrixChainOrder(int A[], int n) { return matrixChainOrderUtil(A, 0, n - 1).second; } pair matrixChainOrderUtil(int p[], int l, int r) { // Base case /* For [1, 2, 3], base case will hit when l = 0, r = 1 or l = 1, r = 2 or we can say we are at matrix A or B l = 0 -> A l = 1 -> B so on.. */ if(l + 1 == r) return {0, "" + string(1, l + 'A')}; string key = to_string(l) + ";" + to_string(r); if(dp.count(key)) return dp[key]; int currMin = INT_MAX; string minString; for(int k = l + 1; k < r; k++) { auto p1 = matrixChainOrderUtil(p, l, k), p2 = matrixChainOrderUtil(p, k, r); if(p1.first + p2.first + p[l] * p[k] * p[r] < currMin) { currMin = p1.first + p2.first + p[l] * p[k] * p[r]; // Multiply te 2 strings minString = p1.second + p2.second; } } // Enclose them in brackets and return return dp[key] = {currMin, "(" + minString + ")"}; } }; // { Driver Code Starts. int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int p[n]; for(int i = 0;i < n;i++) cin>>p[i]; Solution ob; cout< 0){ int n = Integer.parseInt(in.readLine()); String a[] = in.readLine().trim().split("\\s+"); int p[] = new int[n]; for(int i = 0;i < n;i++) p[i] = Integer.parseInt(a[i]); Solution ob = new Solution(); System.out.println(ob.matrixChainOrder(p, n)); } } }// } Driver Code Ends //User function Template for Java class Solution{ static char matrix; static String ans; static String matrixChainOrder(int p[], int n){ // code here matrix='A'; ans=""; int[][]dp=new int[n][n]; int[][]path=new int[n][n]; for(int pair=2;pair

2 players A and B take turns alternatively to play a game in which they have N numbers on a paper. In one turn, a player can replace one of the numbers by any of its factor (except for 1 & the number itself). The player who is unable to make a move looses the game. Find the winner of the game if A starts the game and both play optimally.
 

Example 1:

Input: nums = [5, 7, 3]
Output: B
Explanation: Since all the numbers are prime,
so A will not be able to make the first move. 


Example 2:

Input: nums = [2, 4, 7, 11]
Outptut: A
Explanation: In the first move A will replace 4
by 2, so the numbers will become [2, 2, 7, 11]
now B will not be able to make a move since all 
the remaining numbers can only be divided by 1 
or the number itself.  

Your Task:
You don't need to read or print anything. Your task is to complete the function brainGame() which takes the list of numbers as input parameter and returns true if A wins and false if B wins.

 

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

 

Constraints
1 <= N <= 1000
1 <= nums[i] <= 1000

================================================ FILE: Brain Game - GFG/brain-game.cpp ================================================ // { Driver Code Starts #include using namespace std; // } Driver Code Ends class Solution{ public: bool brainGame(vectornums) { // Code here. vectora(1005); for(int i=2;i<=1000;i++){ for(int j=2*i;j<=1000;j+=i){ a[j]=max(a[j],a[i]+1); } } int x=0; for(int i=0;i> tc; while(tc--){ int n; cin >> n; vectornums(n); for(int i = 0; i < n; i++)cin >> nums[i]; Solution ob; bool ans = ob.brainGame(nums); if(ans) cout << "A\n"; else cout << "B\n"; } return 0; } // } Driver Code Ends ================================================ FILE: Brain Game - GFG/brain-game.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { int n = Integer.parseInt(br.readLine().trim()); String s = br.readLine().trim(); String[] S = s.split(" "); int[] nums = new int[n]; for(int i = 0; i < n; i++){ nums[i] = Integer.parseInt(S[i]); } Solution ob = new Solution(); boolean ans = ob.brainGame(nums); if(ans) System.out.println("A"); else System.out.println("B"); } } } // } Driver Code Ends //User function Template for Java //2 //2 4 4 0 //00010 class Solution { public boolean brainGame(int[] nums) { int ans=0; for(int num:nums){ if(!isPrime(num))ans=ans^(primeFactors(num)-1); } return ans!=0; } int primeFactors(int n) { int ans = 0; int num =n; for(int i=2; i<=num/2; i++) { while(n%i == 0) { ans++; n/= i; } } return ans; } boolean isPrime(int n){ for(int i=2;i<=Math.sqrt(n);i++){ if(n%i==0) return false; } return true; } } ================================================ FILE: Breadth first search.cpp ================================================ #include #include #include using namespace std; void bfs(int node,vector* adj,vector* visited) { queue q; q.push(node); visited[node]=1; while(!q.empty()) { int node=q.front(); q.pop(); cout<>n>>e; // n is number of vertix // e is number of edges vector adj[n]; while(e--) { int u,v; cin>>u>>v; adj[u].push_back(v); adj[v].push_back(u); } vector visited(n,0); for(int i=0;i

In the game of Broken Blocks, the player is allowed to move on m x n blocks i.e. levels and stone blocks on each level such that one level is vertically above the previous level (as in a staircase), with some of its stone blocks replaced by wooden blocks.
The player at the start of the game is present on the ground level (which should be considered as level 0 or it can be considered as level -1). The player can start from any of the blocks present on the level 0 and start moving further to next levels. The player can only move to the stone-block just above to the present stone-block or diagonally to the left or to the right. The player cant move on the same level.
If the player steps on any of the wooden block (denoted by -1), he will fall off the board and die as the wood-block will not able to hold players weight. Each of the stone-block has some gold coins present on it (wooden blocks doesnt have any coins on them). If at any point the player cant move to further level due to any reason, the game ends and his present total coin score will be considered.
The players aim is to collect as many gold coins as he can without falling off the board.

 

Example 1:

Input: matrix = {{2,5,6},{-1,3,2},{4,-1,5}}
Output: 14
Explanation: Assume 0-based indexing.The matrix 
is:
2 5 6 (level 0)
-1 3 2 (level 1)
4 -1 5 (lever 2)
The player can collect maximum number of coins 
by moving through:matrix[0][2] + matrix[1][1] 
+ matrix[2][2] = 6 + 3 + 5 = 14 coins.

Example 2:

Input: matrix = {{-1,2,3,4},{5,-1,-1,2},
{4,3,-1,-1}}
Output: 11
Explanation: The matrix is:
-1 2 3 4(level 0)
5 -1 -1 2(level 1)
4 3 -1 1(level 2)
The player can collect maximum number of coins 
by moving through:a[0][1] + a[1][0] + a[2][0] 
= 2 + 5 + 4 = 11 coins.

 

Your Task:
You don't need to read or print anything. Your task is to complete the function MaxGold() which takes matrix as input parameter and returns the maximum number of gold coins.

 

Expected Time Complexity: O(n*m)
Expected Space Complexity: O(1)

================================================ FILE: Broken blocks - GFG/broken-blocks.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String[] S = br.readLine().trim().split(" "); int m = Integer.parseInt(S[0]); int n = Integer.parseInt(S[1]); int[][] matrix = new int[m][n]; for(int i = 0; i < m; i++){ String[] s = br.readLine().trim().split(" "); for(int j = 0; j < n; j++) matrix[i][j] = Integer.parseInt(s[j]); } Solution obj = new Solution(); int ans = obj.MaxGold(matrix); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution { int[][]dp; public int MaxGold(int[][] a){ int ans=0; dp=new int[a.length][a[0].length]; for(int i=0;i parent; queue Q; Q.push(root); while(!Q.empty()) { int sz = Q.size(); while(sz--) { Node* cur = Q.front(); Q.pop(); if(cur->data == target) start = cur; if(cur->left) { Q.push(cur->left); parent[cur->left] = cur; } if(cur->right) { Q.push(cur->right); parent[cur->right] = cur; } } } Q.push(start); set burned; int t = -1; while(!Q.empty()) { int sz = Q.size(); while(sz--) { Node* cur = Q.front(); Q.pop(); burned.insert(cur->data); if(cur != root and burned.find(parent[cur]->data) == burned.end()) Q.push(parent[cur]); if(cur->left and burned.find(cur->left->data) == burned.end()) Q.push(cur->left); if(cur->right and burned.find(cur->right->data) == burned.end()) Q.push(cur->right); } t++; } return t; } }; ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at sagar.0dev@gmail.com. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. ================================================ FILE: CONTRIBUTING.md ================================================ # 🔥Best repository for you to start your open source journey!! ## 🔼 Prerequisite required to Contribute ### Contributing Code - Git/GitHub - Programming Language - Data structures and algorithms - Problem solving ### Contributing in docs/repo maintainance/others - Git/GitHub - Markdown/Html - GitHub Actions/Yaml - CI/CD --- ## ✅ How to Contribute ### Pull Requests > **Must Use PR templates according to your requirement.** ### 💻Code PRs - Currently, we only cover problems of [LeetCode](https://leetcode.com/problemset/all/), [GeeksForGeeks](https://practice.geeksforgeeks.org/explore?page=1&sortBy=submissions) and [InterviewBit](https://practice.geeksforgeeks.org/explore?page=1&sortBy=submissions). Problems of other good platforms can be accepted(ONLY AFTER [DISCUSSIONS](https://github.com/Sagar0-0/DsA/discussions)). - We maintain the structure of repositroy by creating specific directories corresponding to coding platoforms i.e. [Leetcode](https://github.com/Sagar0-0/DsA/tree/main/Leetcode), [GFG](https://github.com/Sagar0-0/DsA/tree/main/GFG), [Interviewbit](https://github.com/Sagar0-0/DsA/tree/main/Interviewbit). - ⚠️Please contribute your code in the right directory!! Example - LeetCode questions should be in the [LeetCode directory](https://github.com/Sagar0-0/DsA/tree/main/Leetcode) and same for others. - [LeetHub](https://github.com/QasimWani/LeetHub) users, only you can upload your code in the [main directory](https://github.com/Sagar0-0/DsA) from now.(when using extension) - **MUST CHECK** if that question already exists or not!! Follow following steps: Example- A solution named "Nine divisors.java" is to be added, then first check if any directory(or new PR) with the name "Nine divisors" exists or not and if yes, then move to "Nine divisors" directory and then add your code there(if java file exists then append in that file) or if that folder doesn't exists then create a folder/directory with the name "Nine divisors" and then add your code. [How to create a folder/directory?](https://stackoverflow.com/a/34259067/16775065) - File naming convention: - Every word in the file should be separated by a space. eg. "Rat in the maze" , "19. Remove Nth Node From End of List", etc. - ❌No other naming format will be accepted from now.(to maintian the structure) - Do not use "/" in the name of any file!(this will leads to creating a directory) - We strictly avoid removing the code of other contributors. - Check [Beginner's Guide](https://youtu.be/7r05126pOk8) for any issues faced. #### Migration PRs > Help us structure this repository. - Select a code file from the main/home directory **that was not contributed by LeetHub extension**. - Add it to the directory of their corresponding coding platform(with a folder name of that problem). Eg. "Nine divisors.java" file should be in the directory "GFG/Nine divisors". - Delete that file from the home directory. ### ❌Note: Creating multiple wrong PRs can lead to a permanent ban.❌ ================================================ FILE: Can Make Triangle.java ================================================ class Solution { int[] canMakeTriangle(int A[], int N) { // code here int[]ans=new int[N-2]; for(int i=0;ic && a+c>b && b+c>a){ return true; } return false; } } ================================================ FILE: Can Place Flowers.java ================================================ class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { if(n==0) return true; if(flowerbed.length==1 && flowerbed[0]==0) return true; if(flowerbed[0]==0 && flowerbed[1]==0 && n>0){ n--; flowerbed[0]=1; } if(flowerbed[flowerbed.length-1]==0 && flowerbed[flowerbed.length-2]==0 && n>0){ n--; flowerbed[flowerbed.length-1]=1; } for(int i=1;i0;i++){ //condition when we need to ignore if(flowerbed[i-1] == 1 || flowerbed[i+1]==1 || flowerbed[i]==1) continue; flowerbed[i]=1; n--; if(n==0) return true; } return n==0; } } ================================================ FILE: Capacity To Ship Packages Within D Days.java ================================================ class Solution { static int leastWeightCapacity(int[] a, int n, int d) { // code here int min=largest(a); int max=sum(a); int res=0; while(min<=max){ int mid=(min+max)/2; if(isValid(a,d,mid)){ res=mid; max=mid-1; }else{ min=mid+1; } } return res; } static boolean isValid(int[]a,int k,int res){ int day=1,sum=0; for(int i=0;ires){ day++; sum=a[i]; }else{ sum+=a[i]; } } return day<=k; } static int sum(int[]a){ int sum=0; for(int i:a){ sum+=i; } return sum; } static int largest(int[]arr) { int i; // Initialize maximum element int max = arr[0]; // Traverse array elements from second and // compare every element with current max for (i = 1; i < arr.length; i++) if (arr[i] > max) max = arr[i]; return max; } }; ================================================ FILE: Capitalize the Title ================================================ class Solution { public String capitalizeTitle(String s) { List list=new ArrayList<>(); String word=""; for(int i=0;i2){ //uppercase first char str=str.substring(0, 1).toUpperCase() + str.substring(1); } if(i==0){ s+=str; }else{ s+=" "+str; } } return s; } } ================================================ FILE: Case-specific Sorting of Strings.java ================================================ class Solution { //Function to perform case-specific sorting of strings. public static String caseSort(String str) { // Your code here char[] arr=str.toCharArray(); Arrays.sort(arr); int upper=-1; int lower=-1; if(arr[0]<97){ upper=0; } for(int i=0;i=97){ lower=i; break; } } if(upper==-1 || lower==-1)return new String(arr); StringBuilder sb=new StringBuilder(); for(int i=0;i=97){ sb.append(arr[lower]); lower++; }else{ sb.append(arr[upper]); upper++; } } return sb.toString(); } } ================================================ FILE: Case-specific Sorting of Strings.py ================================================ class Solution: #Function to perform case-specific sorting of strings. def caseSort(self,s,n): #code here up,low=[],[] res=[] for i in s: if i.isupper(): up.append(i) elif i.islower(): low.append(i) up.sort() low.sort() x,y=0,0 for i in s: if i.isupper(): res.append(up[x]) x+=1 elif i.islower(): res.append(low[y]) y+=1 ans=''.join(res) return ans ================================================ FILE: Case-specific Sorting string.cpp ================================================ include using namespace std; // } Driver Code Ends class Solution { public: //Function to perform case-specific sorting of strings. string caseSort(string str, int n) { vectorsmall; vectorcap; for(int i=0;i=65&&str[i]<92){ cap.push_back(i); } else{ small.push_back(i); } } sort(str.begin(),str.end()); int s=0,c=0; char ans[n+1]; for(int i=0;i=65&&str[i]<92){ ans[cap[c]]=str[i]; c++; } else{ ans[small[s]]=str[i]; s++; } } ans[n]='\0'; return ans; } }; //{ Driver Code Starts. int main() { int t; cin>>t; while(t--) { int n; cin>>n; string str; cin>>str; Solution obj; cout<key){ if(root.data 0) { champagneTower[row + 1][column] += splittingWine; champagneTower[row + 1][column + 1] += splittingWine; } } } return Math.min(1, champagneTower[query_row][query_glass]); } } //====================================================================================================== class Solution { public double champagneTower(int poured, int queryRow, int queryGlass) { if (poured == 0) return 0; var prevRow = new ArrayList<>(List.of((double) poured)); while (queryRow-- > 0) { var currentRow = new ArrayList(); var champagneInEnds = Math.max(0, (prevRow.get(0) - 1) / 2); // min champagne can be 0 currentRow.add(champagneInEnds); // first glass for (var i = 1; i < prevRow.size(); i++) currentRow.add(Math.max(0, (prevRow.get(i - 1) - 1) / 2) + // flow from top-left glass Math.max(0, (prevRow.get(i) - 1) / 2)); // flow from top-right glass currentRow.add(champagneInEnds); // last glass prevRow = currentRow; } return Math.min(1, prevRow.get(queryGlass)); // max champagne can be 1 } } ================================================ FILE: Change Bits - GFG/README.md ================================================ # Change Bits ## Easy

Given a number N, complete the following tasks,
Task 1. Generate a new number from N by changing the zeroes in the binary representation of N to 1.
Task  2. Find the difference between N and the newly generated number.

 

Example 1:

Input: N = 8 
Output: 7 15
Explanation:
There are 3 zeroes in binary representation
of 8. Changing them to 1 will give 15.
Difference between these two is 7.


Example 2:

Input: N = 6 
Output: 1 7
Explanation:
There is 1 zero in binary representation
of 6. Changing it to 1 will give 7.
Difference between these two is 1.

 

Your Task:
You don't need to read input or print anything. Your task is to complete the function changeBits() which takes an integer N as input parameter and returns a list of two integers containing the difference and the generated number respectively.

 

Expected Time Complexity: O(log(N))
Expected Auxiliary Space: O(1)

 

Constraints:
0 <= N <= 108

================================================ FILE: Change Bits - GFG/change-bits.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { int N = Integer.parseInt(read.readLine()); Solution ob = new Solution(); int[] ans = ob.changeBits(N); System.out.println(ans[0]+ " "+ ans[1]); } } }// } Driver Code Ends //User function Template for Java class Solution { static int[] changeBits(int N) { int newNum=0; int n=N; while(n>0){ newNum|=1; newNum=newNum<<=1; n=n>>1; } newNum=newNum>>1; int diff=Math.abs(N-newNum); int ans[]=new int[]{diff,newNum}; return ans; } }; ================================================ FILE: Check Mirror in N-ary tree.java ================================================ class Solution { static int checkMirrorTree(int n, int e, int[] A, int[] B) { // code here HashMap> mp = new HashMap>(); for(int i=0;i ls = mp.get(A[i]); ls.push(A[i+1]); mp.put(A[i],ls); } else{ Stack ls = new Stack(); ls.push(A[i+1]); mp.put(A[i],ls); } i++; } for(int i=0;i ls = new Stack(); ls = mp.get(B[i]); if(ls.pop()!=B[i+1]){ return 0; } mp.put(B[i],ls); } i++; } return 1; } }; ================================================ FILE: Check Palindrome!.java ================================================ public class Solution { public int solve(String s) { int[]arr=new int[26]; for(char c:s.toCharArray()){ arr[c-'a']++; } boolean one=false; for(int i:arr){ if(i%2==1){ if(one){ return 0; }else{ one=true; } } } return 1; } } ================================================ FILE: Check if Every Row and Column Contains All Numbers ================================================ class Solution { public boolean checkValid(int[][] matrix) { int n=matrix.length; int[][] check=new int[n][n]; for(int row=0;row= 0){ for(int d1: dir){ col1 = d1 + c1; for(int d2: dir){ col2 = d2 + c2; if(inRange(col1, col) && inRange(col2, col)){ dp[i][col1][col2] = Math.max(dp[i][col1][col2], prev+(col1 == col2 ? grid[i][col1] : (grid[i][col1] + grid[i][col2]))); max = Math.max(max, dp[i][col1][col2]); } } } } } } } return max; } public boolean inRange(int val, int limit){ return 0 <= val && val < limit; } } ================================================ FILE: Chips Factory.java ================================================ public class Solution { public int[] solve(int[] A) { int n=A.length; int[]ans=new int[n]; int i=0; for(int num:A){ if(num!=0){ ans[i]=num; i++; } } return ans; } } ================================================ FILE: Chocolate_Distribution_Problem_gfg.cpp ================================================ #include using namespace std; class Solution{ public: long long findMinDiff(vector a, long long n, long long m){ // sliding window approach if(n

You are given a string s of lower case english alphabets. You can choose any two characters in the string and replace all the occurences of the first character with the second character and replace all the occurences of the second character with the first character. Your aim is to find the lexicographically smallest string that can be obtained by doing this operation at most once.

Example 1:

Input:
A = "ccad"
Output: "aacd"
Explanation:
In ccad, we choose a and c and after 
doing the replacement operation once we get, 
aacd and this is the lexicographically
smallest string possible. 

 

Example 2:

Input:
A = "abba"
Output: "abba"
Explanation:
In abba, we can get baab after doing the 
replacement operation once for a and b 
but that is not lexicographically smaller 
than abba. So, the answer is abba. 


Your Task:  
You don't need to read input or print anything. Your task is to complete the function chooseandswap() which takes the string A as input parameters and returns the lexicographically smallest string that is possible after doing the operation at most once.

Expected Time Complexity: O(|A|) length of the string A
Expected Auxiliary Space: O(1)

 

Constraints:
1<= |A| <=105

 

================================================ FILE: Choose and Swap - GFG/choose-and-swap.java ================================================ // { Driver Code Starts //Initial Template for Java //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[])throws IOException { Solution obj = new Solution(); BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { String A = read.readLine().trim(); String ans = obj.chooseandswap(A); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution{ String chooseandswap(String A){ int hash[] = new int[26]; Arrays.fill(hash, -1); //get first occurence of every char for(int i=A.length()-1; i>=0; i--) hash[A.charAt(i)-97] = i; for(int i=0; ii){ String temp1 = A.replaceAll(String.valueOf(ch), "X"); String temp2 = temp1.replaceAll(String.valueOf(st), String.valueOf(ch)); String temp3 = temp2.replaceAll("X", String.valueOf(st)); return temp3; } st+=1; } } return A; } } ================================================ FILE: Climbing Stairs.java ================================================ public class Solution { public int solve(ArrayList A) { int n = A.size(); int steps = A.get(0); int dp[] = new int[n]; dp[0] = steps; dp[1] = steps + A.get(1); for(int i = 2; i < n; i++){ dp[i] = Math.min(dp[i-1], dp[i-2]) + A.get(i); } return dp[n-1]; } } ================================================ FILE: Clone Graph.java ================================================ class Solution { Map map = new HashMap<>(); public Node cloneGraph(Node node) { if (node == null) return node; if(map.containsKey(node)) return map.get(node); Node clonedGraph = new Node(node.val, new ArrayList<>()); map.put(node, clonedGraph); for(Node oldNeb : node.neighbors) { Node clonedNeb = cloneGraph(oldNeb); clonedGraph.neighbors.add(clonedNeb); } return map.get(node); } } //================================================================================ class Solution { public Node cloneGraph(Node node) { if(node==null) return null; Map map = new HashMap(); Queue queue = new LinkedList(); queue.add(node); map.put(node,new Node(node.val)); while(!queue.isEmpty()){ Node curr = queue.poll(); for(Node neighbor : curr.neighbors){ if(!map.containsKey(neighbor)){ map.put(neighbor,new Node(neighbor.val)); queue.add(neighbor); } map.get(curr).neighbors.add(map.get(neighbor)); } } return map.get(node); } } ================================================ FILE: Clone a stack without using extra space ================================================ class Solution { void clonestack(Stack st, Stack cloned) { int n=st.size(); int i=n; while(n>0){ while(!st.isEmpty()){ cloned.push(st.pop()); } int x=cloned.pop(); i=n-1; while(!cloned.isEmpty() && i>0){ st.push(cloned.pop()); i--; } cloned.push(x); n--; } return ; } } ================================================ FILE: Closest Palindrome - GFG/README.md ================================================ # Closest Palindrome ## Hard

Given a number num, our task is to find the closest Palindrome number whose absolute difference with given number is minimum. If 2 Palindome numbers have same absolute difference from the given number, then find the smaller one.
 

Example 1:

Input: num = 9
Output: 9
Explanation: 9 itself is a palindrome
number.

Example 2:

Input: num = 489
Output: 494
Expnataion: closest palindrome numbers from
489 are 484 and 494. Absolute difference between
489 and 494 is equal to the absolute difference
between 484 and 489 but 484 is smaller than 494.

 

Your Task:
You don't need to read or print anyhting. Your task is to complete the function closestPalindrome() which takes num as input parameter and returns the closest palindrome.

 

Expected Time Complexity: O(log10num)
Expected Space Complexity: O(1)

 

Constraints:
1 <= num <= 1014

================================================ FILE: Closest Palindrome - GFG/closest-palindrome.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { long num = Long.parseLong(br.readLine().trim()); Solution obj = new Solution(); long ans = obj.closestPalindrome(num); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution { public long closestPalindrome(long num) { String number = String.valueOf(num); if(isPalindrome(number)) { return num; } if(number.charAt(0)=='1' && Long.parseLong(number.substring(1))==0) { return num-1; } int n = number.length(); boolean hasEvenDigits = n%2==0; String palRootStr = hasEvenDigits ? number.substring(0, n/2) : number.substring(0, n/2+1); long palRoot = Long.parseLong(palRootStr); //Equal long equal = toPal("" + palRoot, hasEvenDigits); long diffEqual = Math.abs(num-equal); //Bigger long bigger = toPal("" + (palRoot+1), hasEvenDigits); long diffBigger = Math.abs(num-bigger); //Smaller long smaller = toPal("" + (palRoot-1), hasEvenDigits); long diffSmaller = Math.abs(num-smaller); long closest = diffBigger

There are N piles of coins each containing  Ai (1<=i<=N) coins. Find the minimum number of coins to be removed such that the absolute difference of coins in any two piles is at most K.
Note: You can also remove a pile by removing all the coins of that pile.


Example 1:

Input:
N = 4, K = 0
arr[] = {2, 2, 2, 2}
Output:
0
Explanation:
For any two piles the difference in the
number of coins is <=0. So no need to
remove any coins. 
Example 2:
Input:
N = 6, K = 3
arr[] = {1, 5, 1, 2, 5, 1} 
Output :
2
Explanation:
If we remove one coin each from both
the piles containing 5 coins , then
for any two piles the absolute difference
in the number of coins is <=3. 


Your Task:  
You don't need to read input or print anything. Your task is to complete the function minSteps() which takes 2 integers N, and K and an array A of size N as input and returns the minimum number of coins that need to be removed.


Expected Time Complexity: O(N*logN)
Expected Auxiliary Space: O(N)


Constraints:
1 ≤ N ≤ 105
0 ≤ K ≤ 104

1 ≤ A[i] ≤ 103

================================================ FILE: Coin Piles - GFG/coin-piles.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { String S1[] = read.readLine().split(" "); int N = Integer.parseInt(S1[0]); int K = Integer.parseInt(S1[1]); String S[] = read.readLine().split(" "); int[] A = new int[N]; for(int i=0; i= 0 ; i--){ subset[i] = arr[i] + subset[i+1]; } int min = Integer.MAX_VALUE; int sum = 0; for(int i =0; i< n; i++){ int ind = findUpper(arr , arr[i] + k , i , n-1); if(ind == -1){ min = Math.min(min , sum); continue; } int curr = subset[ind] - ((n - ind) *(arr[i]+k)); curr += sum; min = Math.min(min , curr); sum += arr[i]; } return min; } static int findUpper(int[] arr , int target, int s , int e){ int ans = -1; while(s <= e){ int mid = (s+e)/2; if(arr[mid] > target){ ans = mid; e = mid - 1; }else{ s = mid + 1; } } return ans; } }; ================================================ FILE: Coins of Geekland.java ================================================ class Solution { public int Maximum_Sum(int mat[][],int N,int K){ // Your code goes here int max=Integer.MIN_VALUE; for(int i=0;i<=N-K;i++){ for(int j=0;j<=N-K;j++){ max=Math.max(max,sum(mat,i,j,K)); } } return max; } public int sum(int[][]arr,int row, int col, int k){ int sum=0; int i=row; while(i> ans; int n; Set> set; public ArrayList> combinationSum(ArrayList a, int b) { Collections.sort(a); n=b; set=new HashSet<>(); ans=new ArrayList<>(); dfs(0,a,new ArrayList<>(),0); return ans; } void dfs(int idx,ArrayList a,ArrayList curr,int sum){ if(sum==n){ if(!set.contains(curr)){ set.add(curr); ans.add(new ArrayList<>(curr)); return; } } if(idx==a.size())return; for(int i=idx;i> ans; ArrayList arr; int target; public ArrayList> combinationSum(ArrayList A, int B){ ans=new ArrayList<>(); target=B; Collections.sort(A); arr=A; dfs(0,0,new ArrayList<>()); return ans; } public void dfs(int sum,int index,ArrayList curr){ if(sum>target)return; if(sum==target){ if(!ans.contains(curr)){ ans.add(new ArrayList<>(curr)); } } for(int i=index;iindex && ele==arr.get(i-1))continue; curr.add(ele); sum+=ele; dfs(sum,i,curr); curr.remove(curr.size()-1); sum-=ele; } } } ================================================ FILE: Combinations.java ================================================ public class Solution { ArrayList> ans; int n; int k; public ArrayList> combine(int n, int k) { ans=new ArrayList<>(); this.n=n; this.k=k; dfs(1,new ArrayList<>()); return ans; } public void dfs(int curr,ArrayList curList){ if(curList.size()==k){ ans.add(new ArrayList<>(curList)); return; } for(int i=curr;i<=n;i++){ curList.add(i); dfs(i+1,curList); curList.remove(curList.size()-1); } } } ================================================ FILE: Compare Version Numbers.java ================================================ class Solution { public int compareVersion(String version1, String version2) { String[] str1 = version1.split("\\."); String[] str2 = version2.split("\\."); int max = Math.max(str1.length,str2.length); for(int i=0;i= str1.length ? 0 : Integer.parseInt(str1[i]); int num2 = i >= str2.length ? 0 : Integer.parseInt(str2[i]); if(num1 < num2) return -1; if(num1 > num2) return 1; } return 0; } } //================================================================================== //Two pointer (Faster) public class Solution { public int compareVersion(String version1, String version2) { int i = 0, j = 0; int currentVersion1, currentVersion2; while(i < version1.length() || j < version2.length()) { currentVersion1 = 0; while(i < version1.length() && version1.charAt(i) != '.'){ currentVersion1 = currentVersion1 * 10 + (version1.charAt(i) - '0'); i++; } currentVersion2 = 0; while(j < version2.length() && version2.charAt(j) != '.'){ currentVersion2 = currentVersion2 * 10 + (version2.charAt(j) - '0'); j++; } if(currentVersion1 > currentVersion2) return 1; if(currentVersion2 > currentVersion1) return -1; i++; j++; } return 0; } } ================================================ FILE: Complete Binary Tree.java ================================================ class GfG { boolean isCompleteBT(Node root) { //add code here. Queue q=new LinkedList<>(); q.add(root); boolean foundNull=false; while(!q.isEmpty()){ int sz=q.size(); while(sz-->0){ Node node=q.remove(); if(node==null){ foundNull=true; }else{ if(foundNull){ return false; }else{ q.add(node.left); q.add(node.right); } } } } return true; } } ================================================ FILE: Composite And Prime.java ================================================ Without using DP class Solution { public boolean isPrime(int a){ if(a==1){ return false; } else if(a==2 || a==3){ return true; } else if(a%2==0 || a%3==0){ return false; } else{ for(int i=5;i<=Math.sqrt(a);i+=6){ if(a%i==0 || a%(i+2)==0){ return false; } } return true; } } public int Count(int l, int r) { long countp=0; long countc=0; for(int i=l;i<=r;i++){ if(isPrime(i)==true){ countp++; } else{ countc++; } } int a=(int)(countc-countp); if(l==1 || r==1){ a=a-1; } return a; } } //long to avoid integer overflow exception(if exists) ================================================ FILE: Composite and Prime gfg med s18.cpp ================================================ #include using namespace std; class Solution { public: vectorisprime; vector count; void isPrime(int n){ bool prime[n+1]; count.resize(n+1,0); memset(prime, true, sizeof(prime)); for(int ip =2; ip*ip<=n; ip++){ if(prime[ip]== true){ for(int i=ip*2; i<=n; i+=ip) prime[i] = false; } } int c =0; for(int p=2; p<=n; p++){ c+=(prime[p]== true); count[p] = c; } } int Count(int L, int R){ // Code here isPrime(R); int ans = (R-L+1)-2*(count[R]-count[L-1]); // 1 is neither prime or comp if(L==1) ans--; return ans; } }; int main(){ int tc; cin >> tc; while(tc--){ int L, R; cin >> L >> R; Solution obj; int ans = obj.Count(L, R); cout << ans << "\n"; } return 0; } ================================================ FILE: Composite and Prime.cpp ================================================ //{ Driver Code Starts #include using namespace std; // } Driver Code Ends class Solution { public: int Count(int L, int R){ // Code here //using the Sieve of Eratosthenes vectorv(R+1, true); //initially considering all number as prime for(int i=2; i*i<=R; i++){ for(int j=i*i; j<=R; j+=i){ v[j] = false; //marking all composite numbers as false } } int composite=0, prime=0; for(int i=L; i<=R; i++){ if(i==1) //since 1 is neither prime nor composite continue; else if(v[i]==true) prime++; else composite++; } return composite-prime; } }; //{ Driver Code Starts. int main(){ int tc; cin >> tc; while(tc--){ int L, R; cin >> L >> R; Solution obj; int ans = obj.Count(L, R); cout << ans << "\n"; } return 0; } // } Driver Code Ends ================================================ FILE: Composite and Prime.java ================================================ class Solution { public int Count(int L, int R) { // code here int primes=0; int comp=0; boolean[]prime=new boolean[R+1]; Arrays.fill(prime,true); prime[0]=false; prime[1]=false; for(int i=2;i<=R;i++){ if(prime[i]){ for(int j=2*i;j<=R;j+=i){ prime[j]=false; } } } for(int i=L;i<=R;i++){ if(prime[i]){ primes++; }else{ comp++; } } if(L==1){ comp--; } return comp-primes; } } ================================================ FILE: Composite and Prime.py ================================================ #User function Template for python3 class Solution: def Count(self, l, r): size = r sieve = [i for i in range(size+1)] for i in range(2, size+1): if sieve[i] == i: j = i * 2 while j < size+1: sieve[j] = i j += i comps = primes = 0 for i in range(max(l, 2), r+1): if sieve[i] == i: primes += 1 else: comps += 1 return comps - primes #{ # Driver Code Starts #Initial Template for Python 3 if __name__ == '__main__': T=int(input()) for i in range(T): L, R = input().split() L = int(L); R = int(R) ob = Solution() ans = ob.Count(L, R) print(ans) # } Driver Code Ends ================================================ FILE: Composite-and-prime.cpp ================================================ class Solution{ public: bool isPrime(int num){ if(num <= 1) return false; int cnt = 0; for(int i = 2; i <= sqrt(num); i++){ if(num % i == 0) return false; } return true; } int Count(int L, int R){ int p = 0, c = 0; for(int i = L; i <= R; i++){ if(i == 1) continue; if(isPrime(i)) p++; else c++; } return c - p; } }; ================================================ FILE: Compute Before Matrix.java ================================================ class Solution{ public int[][] computeBeforeMatrix(int N, int M,int[][] after ){ // Code here int[][]before=new int[N][M]; for(int row=0;row0){ before[row][col]=after[row][col]-after[row][col-1]; }else if(col==0 && row>0){ before[row][col]=after[row][col]-after[row-1][col]; }else{ before[row][col]=after[row][col]-(after[row-1][col]-after[row-1][col-1]+after[row][col-1] ); } } } return before; } } ================================================ FILE: Concatenate two numbers.java ================================================ class Solution { long countPairs(int N, int X, int numbers[]) { // code here long c=0; Map a=new HashMap(); for(int i=0;i A) { Queuepq=new PriorityQueue<>(); for(int i:A)pq.add(i); int ans=0; while(pq.size()>1){ int sum=pq.remove()+pq.remove(); ans+=sum; pq.add(sum); } return ans; } } ================================================ FILE: Consecutive Parent - Child.java ================================================ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { public int consecutiveNodes(TreeNode A) { if(A.left==null && A.right==null)return 0; int ans=0; if(A.left!=null){ if(A.left.val==A.val-1 || A.left.val==A.val+1)ans++; ans+=consecutiveNodes(A.left); } if(A.right!=null){ if(A.right.val==A.val-1 || A.right.val==A.val+1)ans++; ans+=consecutiveNodes(A.right); } return ans; } } ================================================ FILE: Construct BST from Preorder.java ================================================ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { int i=0; public TreeNode constructBST(int[] A) { return bstFromPreOrder(A,Integer.MAX_VALUE); } public TreeNode bstFromPreOrder(int[] preorder ,int bound){ if(i== preorder.length || preorder[i]>=bound) return null; TreeNode root = new TreeNode(preorder[i++]); root.left = bstFromPreOrder(preorder, root.val); root.right = bstFromPreOrder(preorder, bound); return root; } } ================================================ FILE: Construct Binary Tree From Inorder And Preorder.java ================================================ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { ArrayList preorder, inorder; public TreeNode buildTree(ArrayList preorder, ArrayList inorder) { if (preorder == null || inorder == null || preorder.size() == 0 || inorder.size() == 0) return null; if (preorder.size() != inorder.size()) return null; this.preorder = preorder; this.inorder = inorder; return rec(0, preorder.size() - 1, 0); } private TreeNode rec(int start, int end, int index) { if (start > end) return null; TreeNode root = new TreeNode(preorder.get(index)); int i = start; for (; i <= end; i++) { if (inorder.get(i).intValue() == root.val) break; } root.left = rec(start, i - 1, index + 1); root.right = rec(i + 1, end, index + i - start + 1); return root; } } ================================================ FILE: Construct String With Repeat Limit.java ================================================ class Solution { public String repeatLimitedString(String s, int repeatLimit) { int [] arr = new int [26]; for (char c : s.toCharArray()){ arr[c - 'a']++; } StringBuilder sb = new StringBuilder(); int r; int nxt = 25; for (int i = 25, j = 25; i >= 0; --i){ r = repeatLimit; while (arr[i] > 0 && r > 0 ){ --r; --arr[i]; sb.append((char)('a' + i)); } if (arr[i] > 0){ while(nxt >= i || (nxt >= 0 && arr[nxt] == 0) ) --nxt; if (nxt < 0) break; --arr[nxt]; sb.append((char)('a' + nxt)); ++i; } } return sb.toString(); } } ================================================ FILE: Construct String from Binary Tree lc easy.cpp ================================================ #include using namespace std; /** * 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: string res =""; void recur(TreeNode* root){ if(!root) return; res+=to_string(root->val); if(!root->left && !root->right) return; res+="("; recur(root->left); res+=")"; if(root->right){ res+="("; recur(root->right); res+=")"; } } string tree2str(TreeNode* root) { // recursion recur(root); return res; } // TC: O(N) }; ================================================ FILE: Construct String from Binary Tree.java ================================================ class Solution { StringBuilder sb=new StringBuilder(); public String tree2str(TreeNode root) { str(root); return sb.toString(); } public void str(TreeNode root) { if(root==null) { return ; } if(root.left==null && root.right==null) { //when there is no childs, adding just node value sb.append(""+root.val); return ; } sb.append(""+root.val+"("); str(root.left); //irrespective of left child present or not we should add ()-> so calling left child sb.append(")"); if(root.right!=null) { //If right child not present no need to add any () sb.append("("); str(root.right); sb.append(")"); } } } ================================================ FILE: Container With Most Water.java ================================================ public class Solution { public int maxArea(int[] A) { if(A.length<=1)return 0; int ans=Integer.MIN_VALUE; int i=0; int j=A.length-1; while(i map = new HashMap<>(); map.put(0, -1); int maxlen = 0, count = 0; for (int i = 0; i < nums.length; i++) { count = count + (nums[i] == 1 ? 1 : -1); if (map.containsKey(count)) { maxlen = Math.max(maxlen, i - map.get(count)); } else { map.put(count, i); } } return maxlen; } } ============================================================================================ //Faster //using array public class Solution { public int findMaxLength(int[] nums) { int[] arr = new int[2 * nums.length + 1]; Arrays.fill(arr, -2); arr[nums.length] = -1; int maxlen = 0, count = 0; for (int i = 0; i < nums.length; i++) { count = count + (nums[i] == 0 ? -1 : 1); if (arr[count + nums.length] >= -1) { maxlen = Math.max(maxlen, i - arr[count + nums.length]); } else { arr[count + nums.length] = i; } } return maxlen; } } ================================================ FILE: Convert Sorted List to Binary Search Tree.java ================================================ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ /** * Definition for singly-linked list. * class ListNode { * public int val; * public ListNode next; * ListNode(int x) { val = x; next = null; } * } */ public class Solution { public TreeNode sortedListToBST(ListNode a) { return dfs(a); } public TreeNode dfs(ListNode a){ if(a.next==null)return new TreeNode(a.val); ListNode prev=null; ListNode slow=a; ListNode fast=a; while(fast.next!=null && fast.next.next!=null){ prev=slow; slow=slow.next; fast=fast.next.next; } if(prev!=null)prev.next=null; ListNode next=slow.next; slow.next=null; TreeNode root=new TreeNode(slow.val); if(!slow.equals(a))root.left=dfs(a); root.right=dfs(next); return root; } } ================================================ FILE: Convert the amount in number to words.java ================================================ public class Solution { private static class Place { int unit; String name; public Place (int unit, String name) { this.unit = unit; this.name = name; } } private static final Place[] places = new Place[]{ new Place(10000000, "crore"), new Place(100000, "lakh"), new Place(1000, "thousand"), new Place(100, "hundred") }; private static final String[] tens = new String[]{ "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; private static final String[] units = new String[]{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private String f(long amount) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < places.length; i++) { Place place = places[i]; int qty = (int)(amount / place.unit); if (qty > 0) { String toAdd = ""; if (qty > 10) { toAdd = f (qty) + "-" + place.name; } else { toAdd = units[qty] + "-" + place.name; } if (sb.length() > 0) { sb.append("-"); } sb.append(toAdd); } amount -= (long) qty * place.unit; } if (sb.length() > 0 && amount > 0) { sb.append("-and-"); } int ten = (int)(amount / 10); boolean shouldAddAnd = false; if (ten > 1) { sb.append(tens[ten]); amount -= 10 * ten; shouldAddAnd = true; } if (amount > 0) { if (shouldAddAnd) { sb.append("-"); } sb.append(units[(int)amount]); } return sb.toString(); } public int solve(String A, String B) { long amount = Long.parseLong(A); String b = f(amount); return b.equals(B) ? 1 : 0; } } ================================================ FILE: Convert to Palindrome.java ================================================ public class Solution { public int solve(String A) { int n=A.length(); int lo=0,hi=n-1,flag=0; while(lo

Given a Binary Search Tree (BST) and a range l-h(inclusive), count the number of nodes in the BST that lie in the given range.

  • The values smaller than root go to the left side
  • The values greater and equal to the root go to the right side

Example 1:

Input:
      10
     /  \
    5    50
   /    /  \
  1    40  100
l = 5, h = 45
Output: 3
Explanation: 5 10 40 are the node in the
range

Example 2:

Input:
     5
    /  \
   4    6
  /      \
 3        7
l = 2, h = 8
Output: 5
Explanation: All the nodes are in the
given range.

Your Task:
This is a function problem. You don't have to take input. You are required to complete the function getCountOfNode() that takes root, l ,h as parameters and returns the count.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(Height of the BST).

Constraints:
1 <= Number of nodes <= 100
1 <= l < h < 103

================================================ FILE: Count BST nodes that lie in a given range - GFG/count-bst-nodes-that-lie-in-a-given-range.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.LinkedList; import java.util.Queue; import java.io.*; import java.util.*; class Node{ int data; Node left; Node right; Node(int data){ this.data = data; left=null; right=null; } } class GfG { static Node buildTree(String str){ if(str.length()==0 || str.charAt(0)=='N'){ return null; } String ip[] = str.split(" "); // Create the root of the tree Node root = new Node(Integer.parseInt(ip[0])); // Push the root to the queue Queue queue = new LinkedList<>(); queue.add(root); // Starting from the second element int i = 1; while(queue.size()>0 && i < ip.length) { // Get and remove the front of the queue Node currNode = queue.peek(); queue.remove(); // Get the current node's value from the string String currVal = ip[i]; // If the left child is not null if(!currVal.equals("N")) { // Create the left child for the current node currNode.left = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.left); } // For the right child i++; if(i >= ip.length) break; currVal = ip[i]; // If the right child is not null if(!currVal.equals("N")) { // Create the right child for the current node currNode.right = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.right); } i++; } return root; } static void printInorder(Node root) { if(root == null) return; printInorder(root.left); System.out.print(root.data+" "); printInorder(root.right); } public static void main (String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t > 0){ String s = br.readLine(); String[] ab = br.readLine().trim().split(" "); int a = Integer.parseInt(ab[0]); int b = Integer.parseInt(ab[1]); Node root = buildTree(s); Solution g = new Solution(); System.out.println(g.getCount(root,a,b)); t--; } } } // } Driver Code Ends // A Binary Search Tree node class Solution { int ans; //Function to count number of nodes in BST that lie in the given range. int getCount(Node root,int l, int h) { //Your code here ans=0; dfs(root,l,h); return ans; } void dfs(Node root,int l,int h){ if(root==null)return; if(root.data>=l && root.data<=h){ ans++; dfs(root.left,l,h); dfs(root.right,l,h); }else if(root.data words1Set=new HashSet<>(); HashSet words1Duplicates=new HashSet<>(); HashSet words12Set=new HashSet<>(); HashSet words12Duplicates=new HashSet<>(); for(String s: words1) { if (words1Set.contains(s)) words1Duplicates.add(s); else words1Set.add(s); } for(String s: words1Duplicates) words1Set.remove(s); for(String s: words2) { if (words1Set.contains(s)) { if (words12Set.contains(s)) words12Duplicates.add(s); else words12Set.add(s); } } return words12Set.size()-words12Duplicates.size(); } } ================================================ FILE: Count Integers With Even Digit Sum.py ================================================ def getSum(n): sum = 0 for digit in str(n): sum += int(digit) return sum class Solution: def countEven(self, num: int) -> int: count=0 val=2 while val<=num: if getSum(val)%2==0: count+=1; val+=1 return count ================================================ FILE: Count Operations to Obtain Zero.java ================================================ class Solution { public int countOperations(int num1, int num2) { int ans=0; while(num1>0 && num2>0){ if(num1>=num2){ num1=num1-num2; }else{ num2=num2-num1; } ans++; } return ans; } } ================================================ FILE: Count Palindromic Subsequence.cpp ================================================ #include using namespace std; // } Driver Code Ends class Solution{ #define ll long long int private: ll solve(string& s,int i,int j,vector> &dp){ int mod =1e9+7; if(i==j){ return 1; } if(i>j){ return 0; } if(dp[i][j] != -1){ return dp[i][j]; } if(s[i] == s[j]){ dp[i][j] = ( 1 + solve(s,i+1,j,dp) + solve(s,i,j-1,dp) )%mod; }else{ dp[i][j] = ((solve(s,i+1,j,dp) + solve(s,i,j-1,dp) - solve(s,i+1,j-1,dp))%mod+mod)%mod ; } return dp[i][j]; } public: /*You are required to complete below method */ ll countPS(string str) { //Your code here int n = str.size(); vector> dp(n,vector(n,-1)); return solve(str,0,n-1,dp); } }; //{ Driver Code Starts. // Driver program int main() { int t; cin>>t; while(t--) { string str; cin>>str; Solution ob; long long int ans = ob.countPS(str); cout< arr=new ArrayList<>(); arr.add(a[n-1]); for(int i=n-2;i>=0;i--){ int idx=dfs(arr,a[i],0,arr.size()-1); ans[ii]=idx; ii--; arr.add(idx,a[i]); } // for(int i:arr)System.out.print(i+" "); return ans; } int dfs(List arr,int key,int l,int h){ if(l<=h){ int mid=l+(h-l)/2; if(arr.get(mid)>=key){ return dfs(arr,key,l,mid-1); } return dfs(arr,key,mid+1,h); } return l; } } ================================================ FILE: Count Words Obtained After Adding a Letter ================================================ class Solution { public int wordCount(String[] a, String[] b) { int m=a.length; int n=b.length; Set set=new HashSet<>(); for(int i=0;i

Given a string str consisting of digits, one may group these digits into sub-groups while maintaining their original order.
The task is to count number of groupings such that for every sub-group except the last one, sum of digits in a sub-group is less than or equal to sum of the digits in the sub-group immediately on its right.

For example, a valid grouping of digits of number 1119 is (1-11-9). Sum of digits in first subgroup is 1, next subgroup is 2, and last subgroup is 9. Sum of every subgroup is less than or equal to its immediate right.
 

Example 1: 

Input: str = "1119"
Output: 7
Explanation: [1-119], [1-1-19], [1-11-9], 
[1-1-1-9], [11-19], [111-9] and [1119] 
are seven sub-groups.


Example 2:

Input: str = "12"
Output: 2
Explanation: [1-2] and [12] are two sub-groups.

 

Your Task:
You don't need to read or print anything. Your task is to complete the function TotalCount() which takes the string str as input parameter and returns total possible groupings.

Expected Time Complexity: O(N * N ) where N is length of string.
Expected Space Complexity: O(N * N)

 

Constraints:
1 <= length of string <= 100

================================================ FILE: Count digit groupings of a number - GFG/count-digit-groupings-of-a-number.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String str = br.readLine().trim(); Solution ob = new Solution(); int ans = ob.TotalCount(str); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution{ public int TotalCount(String str){ int sum = 0; for(int i=0; i=0;i--){ curr += str.charAt(i)-'0'; if(curr<=currsum)ans += backtrack(str,curr,i-1, dp); } return dp[currsum][index] = ans; } } ================================================ FILE: Count occurrences of a given word in a 2-d array(dynamic programming).cpp ================================================ class Solution{ public: void solve(int i, int j, vector > &mat, string target,int index, int &ans){ int row=mat.size(); int col=mat[0].size(); if(i<0 or i>=row or j<0 or j>=col or index==target.length() or mat[i][j]=='1' or target[index]!=mat[i][j]) return; if(index==target.length()-1 && target[index]==mat[i][j]) ans++; index++; char temp=mat[i][j]; mat[i][j]='1'; solve(i,j-1,mat,target,index,ans); solve(i,j+1,mat,target,index,ans); solve(i-1,j,mat,target,index,ans); solve(i+1,j,mat,target,index,ans); mat[i][j]=temp; } int findOccurrence(vector > &mat, string target){ int row=mat.size(); int col=mat[0].size(); int ans=0; for(int i=0;i> &mat,string &target) { if(i < 0 || j < 0 || i==m || j==n || x >= target.size() || mat[i][j] != target[x]) return false; return true; } void solve(int i,int j,int m,int n,int x,vector> &mat,string &target) { if(isSafe(i,j,m,n,x,mat,target)) { if(x == target.size()-1) { ans++; return; } int dx[4] = {1,-1,0,0}; int dy[4] = {0,0,1,-1}; char temp = mat[i][j]; mat[i][j] = '/'; for(int k=0; k<4; k++) { int nx = i+dx[k]; int ny = j+dy[k]; solve(nx,ny,m,n,x+1,mat,target); } mat[i][j] = temp; } } int findOccurrence(vector > &mat, string target){ int m = mat.size(); int n = mat[0].size(); int x = 0; for(int i=0; i=target.length() || target.charAt(idx)!=mat[i][j])return; if(idx==target.length()-1){ ans++; return; } char ch=mat[i][j]; mat[i][j]='0'; dfs(mat,i+1,j,target,idx+1); dfs(mat,i-1,j,target,idx+1); dfs(mat,i,j+1,target,idx+1); dfs(mat,i,j-1,target,idx+1); mat[i][j]=ch; } } ================================================ FILE: Count occurrences of a given word in a 2-d array.py ================================================ class Solution: def findOccurrence(self,mat,target): cnt = 0 m, n = len(mat), len(mat[0]) seen = set() def dfs(r, c, target): nonlocal cnt, m, n if not target: cnt += 1 return if r < 0 or r >= m or c < 0 or c >= n or (r, c) in seen or mat[r][c] != target[0]: return seen.add((r, c)) dfs(r+1, c, target[1:]) dfs(r-1, c, target[1:]) dfs(r, c+1, target[1:]) dfs(r, c-1, target[1:]) seen.remove((r, c)) for r in range(len(mat)): for c in range(len(mat[0])): if mat[r][c] != target[0]: continue dfs(r, c, target) return cnt//4 ================================================ FILE: Count pairs in array divisible by K - GFG/README.md ================================================ # Count pairs in array divisible by K ## Medium

Given an array A[] and positive integer K, the task is to count total number of pairs in the array whose sum is divisible by K.

Example 1:

Input : 
A[] = {2, 2, 1, 7, 5, 3}, K = 4
Output : 5
Explanation : 
There are five pairs possible whose sum
is divisible by '4' i.e., (2, 2), 
(1, 7), (7, 5), (1, 3) and (5, 3)

Example 2:

Input : 
A[] = {5, 9, 36, 74, 52, 31, 42}, K = 3
Output : 7 
Explanation : 
There are seven pairs whose sum is divisible by 3, 
i.e, (9, 36), (9,42), (74, 52), (36, 42), (74, 31), 
(31, 5) and (5, 52).
Your task :
You don't have to read input or print anything. Your task is to complete the function countKdivPairs() which takes the array, it's size and an integer K as input and returns the count of pairs whose sum is divisible by K.
 
Expected Time Complexity : O(n)
Expected Auxiliary Space : O(k)
 
Constraints :
1 <= N <=10^6
1 <= A[i] <= 10^6
1 <= K <= 100

================================================ FILE: Count pairs in array divisible by K - GFG/count-pairs-in-array-divisible-by-k.java ================================================ // { Driver Code Starts import java.util.*; import java.io.*; import java.lang.*; class GFG { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases while(t-->0){ int n = Integer.parseInt(br.readLine().trim()); String inputLine[] = br.readLine().trim().split(" "); int arr[] = new int[n]; for(int i=0; i

Given N, the number of plots on either sides of the road. Find the total ways to construct buildings in the plots such that there is a space between any 2 buildings. All plots on one side of the road are continuous.
Lets suppose * represents a plot, then for N=3, the plots can be represented as * * * | | * * *                               

Where | | represents the road.                                                                                                                                                                  
Note: As the answer can be very large, print it mod 1000000007

 

Example 1:

Input: N = 3
Output: 25
Explanation: 3 plots, which means possible
ways for one side are BSS, BSB, SSS, SBS,
SSB where B represents a building and S
represents an empty space Total possible 
ways are 25, because a way to place on one
side can correspond to any of 5 ways on other
side.

Example 2:

Input: N = 10
Output: 20736
Explanation: There are 20736 ways for N = 10.

 

Your Task:
You don't need to read or print anything. Your task is to complete the function ToralWays() which takes N as input parameter and returns the total possible ways modulo 109 + 7.

 

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

 

Constraints:
1 <= N <= 100000

================================================ FILE: Count possible ways to construct buildings - GFG/count-possible-ways-to-construct-buildings.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { int N = Integer.parseInt(br.readLine().trim()); Solution ob = new Solution(); int ans = ob.TotalWays(N); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution { public int TotalWays(int N) { // Code here long i,ans=0,inf = 1000000007; long s = 1,b=1; while(N-->1){ i = s%inf; s = (s%inf+b%inf); b = i; } s = s%inf + b%inf; return (int)((s*s)%inf); } } ================================================ FILE: Count subsequences of type a^i, b^j, c^k - GFG/README.md ================================================ # Count subsequences of type a^i, b^j, c^k ## Medium

Given a string S, the task is to count number of subsequences of the form aibjck, where i >= 1, j >=1 and k >= 1.

Note: 
1. Two subsequences are considered different if the set of array indexes picked for the 2 subsequences are different.
2.  For large test cases, the output value will be too large, return the answer MODULO 10^9+7

 

Example 1:

Input:
S = "abbc"
Output: 3
Explanation: Subsequences are abc, abc and abbc.


Example 2:

Input:
S = "abcabc"
Output: 7
Explanation: Subsequences are abc, abc,
abbc, aabc abcc, abc and abc.


Your Task:
You don't need to read input or print anything. Your task is to complete the function fun() which takes the string S as input parameter and returns the number of subsequences which follows given condition.


Expected Time Complexity: O(Length of String).
Expected Auxiliary Space: O(1) .


Constraints:
1 <= |S| <= 105

================================================ FILE: Count subsequences of type a^i, b^j, c^k - GFG/count-subsequences-of-type-ai-bj-ck.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main (String[] args) { Scanner sc = new Scanner (System.in); int t = Integer.parseInt(sc.next()); while(t>0) { String s = sc.next(); Solution T = new Solution(); System.out.println(T.fun(s)); t--; } } } // } Driver Code Ends //User function Template for Java class Solution{ public int fun(String s){ HashMap mp = new HashMap <>(); mp.put('a',0); mp.put('b',0); mp.put('c',0); for(int i = s.length()-1;i >= 0;i--) { if(s.charAt(i) == 'c') mp.put('c', (2*mp.get('c')+1) % 1000000007 ); else if(s.charAt(i) == 'b') mp.put('b', ( (2*mp.get('b'))% 1000000007 + mp.get('c') ) % 1000000007 ); else if(s.charAt(i) == 'a') mp.put('a', ( (2*mp.get('a'))% 1000000007 + mp.get('b') ) % 1000000007 ); } return mp.get('a'); } } ================================================ FILE: Count the paths - GFG/README.md ================================================ # Count the paths ## Easy

Given a directed acyclic graph(DAG) with n nodes labeled from 0 to n-1. Given edges, s and d ,count the number of ways to reach from s to d.There is a directed Edge from vertex edges[i][0] to the vertex edges[i][1].

 

Example:

Input: edges = {{0,1},{0,3},{1,2},{3,2}}, 
n = 4, s = 0, d = 2
Output: 2
Explanation: There are two ways to reach at 
2 from 0. These are-
1. 0->1->2
2. 0->3->2

 

Your Task:
You don't need to read or print anything. Your task is to complete the function possible_paths() which takes edges, n, s and d as input parameter and returns the number of ways to reach from s to d.

 

Expected Time Compelxity: O(2n)
Expected Space Complexity: O(n+e)

where e is the number of edges in the graph.
 

Constraints:
1 <= n <= 15
0 <= s, d <= n-1

================================================ FILE: Count the paths - GFG/count-the-paths.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String[] S = br.readLine().trim().split(" "); int n = Integer.parseInt(S[0]); int m = Integer.parseInt(S[1]); int s = Integer.parseInt(S[2]); int d = Integer.parseInt(S[3]); int[][] edges = new int[m][2]; for(int i = 0; i < m; i++){ String[] S1 = br.readLine().trim().split(" "); edges[i][0] = Integer.parseInt(S1[0]); edges[i][1] = Integer.parseInt(S1[1]); } Solution obj = new Solution(); int ans = obj.possible_paths(edges, n, s, d); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution { Map> map; int ans; int des; public int possible_paths(int[][] edges, int n, int s, int d) { des=d; ans=0; map=new HashMap<>(); for(int[]e:edges){ int src=e[0]; int des=e[1]; map.putIfAbsent(src,new ArrayList<>()); map.get(src).add(des); } dfs(s); return ans; } void dfs(int curr){ if(curr==des){ ans++; return; } if(!map.containsKey(curr))return; ArrayList arr=map.get(curr); for(int neb:arr){ dfs(neb); } } } ================================================ FILE: Count-occurrences-of-a-given-string-in-2d-array.cpp ================================================ class Solution{ public: int ans = 0; void dfs(int i, int j, vector> &mat, string target, int ind, string s){ if(i < 0 || j < 0 || i >= mat.size() || j >= mat[0].size() || mat[i][j] != target[ind]) return; if(ind == target.size()-1){ ans++; return; } char ch = mat[i][j]; mat[i][j] = '0'; dfs(i+1,j,mat,target,ind+1,s+mat[i][j]); dfs(i,j+1,mat,target,ind+1,s+mat[i][j]); dfs(i-1,j,mat,target,ind+1,s+mat[i][j]); dfs(i,j-1,mat,target,ind+1,s+mat[i][j]); mat[i][j] = ch; } int findOccurrence(vector > &mat, string target){ int n = mat.size(); int m = mat[0].size(); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(mat[i][j] == target[0]){ dfs(i,j,mat,target,0,""); } } } return ans; } }; ================================================ FILE: Count_occurences_of_a_given_word_in_a_2-d_array/Solution.java ================================================ class Solution { // write your code here int result = 0; boolean isSafe(char mat[][],int r,int c) { int rLen = mat.length,cLen = mat[0].length; if((r >= 0 && r < rLen)&&(c >= 0 && c < cLen)) return true; return false; } public void dfs(char mat[][],int i,int r, int c,String target) { if(!isSafe(mat,r,c)) return; if(i == target.length()) return; char ch = target.charAt(i); if(ch != mat[r][c]) return; if(i == target.length()-1) { result+=1; return; } mat[r][c] = '$'; dfs(mat,i+1,r+1,c,target); dfs(mat,i+1,r-1,c,target); dfs(mat,i+1,r,c+1,target); dfs(mat,i+1,r,c-1,target); mat[r][c] = ch; } public int findOccurrence(char mat[][], String target) { for(int i = 0;i < mat.length;i++) for(int j = 0; j < mat[i].length;j++) if(mat[i][j] == target.charAt(0)) dfs(mat,0,i,j,target); return result; } } ================================================ FILE: Count_occurences_of_a_given_word_in_a_2-d_array/question.md ================================================ Find the number of occurrences of a given search word in a 2d-Array of characters where the word can go up, down, left, right and around 90 degree bends. **Example 1:** ``` Input: R = 4, C = 5 mat = {{S,N,B,S,N}, {B,A,K,E,A},   {B,K,B,B,K}, {S,E,B,S,E}} target = SNAKES Output: 3 Explanation: S N B S N B A K E A B K B B K S E B S E Total occurrence of the word is 3 and denoted by color. ``` **Example 2:** ``` Input: R = 3, C = 3 mat = {{c,a,t},   {a,t,c},   {c,t,a}} target = cat Output: 5 Explanation: Same explanation as first example. ``` **Your task:** You dont need to read input or print anything. Your task is to complete the function **findOccurrence()** which takes the mat contaning N*M 2-d array of character and target as input parameters and returns thethe number of occurrences of target. **Expected Time Complexity: **O(R*C*2 ^2*len^ ), Where len is length of target String. **Expected Auxiliary Space: **O(1) **Constraints:** 1 ≤ len ≤ 15 1 ≤ R, C ≤ 50 ================================================ FILE: Counting Bits.java ================================================ class Solution { public int[] countBits(int n) { int[]ans=new int[n+1]; for(int i=1;i>1]+(i&1); return ans; } } ================================================ FILE: Counts Zeros Xor Pairs - GFG/README.md ================================================ # Counts Zeros Xor Pairs ## Easy

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

 

================================================ FILE: Counts Zeros Xor Pairs - GFG/counts-zeros-xor-pairs.java ================================================ // { Driver Code Starts //Initial Template for Java //Initial Template for Java //Initial Template for Java //Initial Template for Java //Initial Template for Java /*package whatever //do not write package name here */ import java.io.*; import java.util.*; class Array { // Driver code public static void main (String[] args) throws IOException{ // Taking input using buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testcases = Integer.parseInt(br.readLine()); // looping through all testcases while(testcases-- > 0){ String line = br.readLine(); String[] element = line.trim().split("\\s+"); int sizeOfArray = Integer.parseInt(element[0]); int arr [] = new int[sizeOfArray]; line = br.readLine(); String[] elements = line.trim().split("\\s+"); for(int i = 0;i

There are a total of n tasks you have to pick, labeled from 0 to n-1. Some tasks may have prerequisites tasks, for example to pick task 0 you have to first finish tasks 1, which is expressed as a pair: [0, 1]
Given the total number of n tasks and a list of prerequisite pairs of size m. Find a ordering of tasks you should pick to finish all tasks.

Note: There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all tasks, return an empty array. Returning any correct order will give the output as 1, whereas any invalid order will give the output 0.


Example 1:

Input:
n = 2, m = 1
prerequisites = {{1, 0}}
Output:
1
Explanation:
The output 1 denotes that the order is
valid. So, if you have, implemented
your function correctly, then output
would be 1 for all test cases.
One possible order is [0, 1].

Example 2:

Input:
n = 4, m = 4
prerequisites = {{1, 0},
                 {2, 0},
                 {3, 1},
                 {3, 2}}
Output:
1
Explanation:
There are a total of 4 tasks to pick.
To pick task 3 you should have finished
both tasks 1 and 2. Both tasks 1 and 2
should be pick after you finished task 0.
So one correct task order is [0, 1, 2, 3].
Another correct ordering is [0, 2, 1, 3].
Returning any of these order will result in
a Output of 1.


Your Task:
The task is to complete the function findOrder() which takes two integers n, and m and a list of lists of size m*2 denoting the prerequisite pairs as input and returns any correct order to finish all the tasks. Return an empty array if it's impossible to finish all tasks.


Constraints:
1 ≤ n ≤ 104
0 ≤ m ≤ 105
0 ≤ prerequisites[0], prerequisites[1] ≤ 105
All prerequisite pairs are unique
prerequisites[0] ≠ prerequisites[1]


Expected Time Complexity: O(n+m).
Expected Auxiliary Space: O(n+m).

================================================ FILE: Course Schedule - GFG/course-schedule.java ================================================ // { Driver Code Starts //Initial template for JAVA import java.util.*; import java.io.*; import java.lang.*; class Main { public static void main(String[] args) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { ArrayList> list = new ArrayList<>(); String st[] = read.readLine().trim().split("\\s+"); int n = Integer.parseInt(st[0]); int m = Integer.parseInt(st[1]); for (int i = 0; i < n; i++) list.add(i, new ArrayList()); ArrayList> prerequisites = new ArrayList<>(); for (int i = 1; i <= m; i++) { String s[] = read.readLine().trim().split("\\s+"); int u = Integer.parseInt(s[0]); int v = Integer.parseInt(s[1]); list.get(v).add(u); ArrayList pair = new ArrayList<>(); pair.add(u); pair.add(v); prerequisites.add(pair); } int[] res = new Solution().findOrder(n, m, prerequisites); if(res.length==0) System.out.println("No Ordering Possible"); else { if (check(list, n, res) == true) System.out.println("1"); else System.out.println("0"); } } } static boolean check(ArrayList> list, int V, int[] res) { int[] map = new int[V]; for (int i = 0; i < V; i++) { map[res[i]] = i; } for (int i = 0; i < V; i++) { for (int v : list.get(i)) { if (map[i] > map[v]) return false; } } return true; } } // } Driver Code Ends class Solution{ static int[] findOrder(int n, int m, ArrayList> prereq){ int indegree[] = new int[n]; //Calculate the indegree of each node. for(int i=0; i> adj = new ArrayList<>(); for(int i=0; i()); } for(int i=0; i queue = new ArrayDeque<>(); boolean visited[] = new boolean[n]; for(int i=0; i printCousins(Node root, Node find) { //code here Queue q=new LinkedList<>(); ArrayList ans=new ArrayList<>(); q.offer(root); boolean flag=false; while(!q.isEmpty()){ int sz=q.size(); if(flag){ while(!q.isEmpty()){ ans.add(q.remove().data); } break; } for(int i=0;i q=new LinkedList<>(); q.add(A); while(q.size()>0){ int sz=q.size(); for(int i=0;i (a[0] == b[0]) ? Integer.compare(b[1], a[1]) : Integer.compare(a[0], b[0])); int noOfWeakCharacters = 0; int len = properties.length; // improvization here - // we need to keep track of the max value int max = properties[len-1][1]; for(int i = len-2; i>=0 ;i--) { if(properties[i][1] < max) { noOfWeakCharacters++; } else { max = properties[i][1]; } } return noOfWeakCharacters; } } ================================================ FILE: Delete and Earn.java ================================================ class Solution { private HashMap points = new HashMap<>(); private HashMap cache = new HashMap<>(); private int maxPoints(int num) { // Check for base cases if (num == 0) { return 0; } if (num == 1) { return points.getOrDefault(1, 0); } if (cache.containsKey(num)) { return cache.get(num); } // Apply recurrence relation int gain = points.getOrDefault(num, 0); cache.put(num, Math.max(maxPoints(num - 1), maxPoints(num - 2) + gain)); return cache.get(num); } public int deleteAndEarn(int[] nums) { int maxNumber = 0; // Precompute how many points we gain from taking an element for (int num : nums) { points.put(num, points.getOrDefault(num, 0) + num); maxNumber = Math.max(maxNumber, num); } return maxPoints(maxNumber); } } //================================================================================== class Solution { public int deleteAndEarn(int[] nums) { int[] count = new int[10001]; for (int n : nums) { count[n]++; }; int withPrev = 0; int withoutPrev = 0; int prev = -1; for (int i = 0; i < count.length; i++) { if (count[i] == 0) continue; int currentMax = Math.max(withPrev, withoutPrev); if (i - prev == 1) { withPrev = withoutPrev + count[i] * i; withoutPrev = currentMax; } else { withPrev = currentMax + count[i] * i; withoutPrev = currentMax; } prev = i; } return Math.max(withPrev, withoutPrev); } } ================================================ FILE: Delete nodes greater than k.java ================================================ class Solution { public Node deleteNode(Node root,int k) { //add code here. if(root==null)return null; if(root.data>=k){ root.left=deleteNode(root.left,k); return root.left; }else{ root.right=deleteNode(root.right,k); } return root; } } ================================================ FILE: Deserialize.java ================================================ public class Solution { public ArrayList deserialize(String A) { int i=0; ArrayList arr=new ArrayList<>(); StringBuilder sb=new StringBuilder(); while(i='0' && A.charAt(i)<='9'){ arr.add(sb.toString()); sb.setLength(0); while(A.charAt(i)<'a')i++; }else if(A.charAt(i)=='~'){ i++; }else{ sb.append(A.charAt(i)); i++; } } return arr; } } ================================================ FILE: Design Add and Search Words Data Structure.java ================================================ class WordDictionary { private WordDictionary[] children; boolean isEndOfWord; // Initialize your data structure here. public WordDictionary() { children = new WordDictionary[26]; isEndOfWord = false; } // Adds a word into the data structure. public void addWord(String word) { WordDictionary curr = this; for(char c: word.toCharArray()){ if(curr.children[c - 'a'] == null) curr.children[c - 'a'] = new WordDictionary(); curr = curr.children[c - 'a']; } curr.isEndOfWord = true; } // Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. public boolean search(String word) { WordDictionary curr = this; for(int i = 0; i < word.length(); ++i){ char c = word.charAt(i); if(c == '.'){ for(WordDictionary ch: curr.children) if(ch != null && ch.search(word.substring(i+1))) return true; return false; } if(curr.children[c - 'a'] == null) return false; curr = curr.children[c - 'a']; } return curr != null && curr.isEndOfWord; } } ================================================ FILE: Design Bitset.java ================================================ class Bitset { int size; Set one = new HashSet<>(); Set zero = new HashSet<>(); public Bitset(int size) { this.size = size; for(int i=0;i s = one; one = zero; zero = s; } public boolean all() { return one.size() == size; } public boolean one() { return one.size()>=1; } public int count() { return one.size(); } public String toString() { StringBuilder sb= new StringBuilder(); for(int i=0;i class BrowserHistory { public: // // 1. using 2 stacks // stack ur, fb; // BrowserHistory(string homepage) { // ur.push(homepage); // fb = stack(); // } // void visit(string url) { // ur.push(url); // fb = stack(); // } // string back(int steps) { // while(steps>0 and ur.size() > 1){ // fb.push(ur.top()); // ur.pop(); // steps--; // } // return ur.top(); // } // string forward(int steps) { // while(steps>0 and fb.size()>0){ // ur.push(fb.top()); // fb.pop(); // steps--; // } // return ur.top(); // } // 2. using array of strings more efficient than 1. string ur[5000]; int cur=0, end=0; BrowserHistory(string homepage) { ur[0] = homepage; } void visit(string url) { cur++; ur[cur] = url; end = cur; } string back(int steps) { if(steps>cur) cur=0; else cur-=steps; return ur[cur]; } string forward(int steps) { if(cur+steps>end) cur=end; else cur+=steps; return ur[cur]; } }; ================================================ FILE: Diagonal Traversal of Binary Tree - GFG/README.md ================================================ # Diagonal Traversal of Binary Tree ## Medium

Given a Binary Tree, print the diagonal traversal of the binary tree.

Consider lines of slope -1 passing between nodes. Given a Binary Tree, print all diagonal elements in a binary tree belonging to same line.

Example 1:

Input :
            8
         /     \
        3      10
      /   \      \
     1     6     14
         /   \   /
        4     7 13
Output : 8 10 14 3 6 7 13 1 4
Explanation:
unnamed
Diagonal Traversal of binary tree : 
 8 10 14 3 6 7 13 1 4

Your Task:
You don't need to read input or print anything. The task is to complete the function diagonal() that takes the root node as input argumets and returns the diagonal traversal of the given tree.

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).

Here N is number of nodes.

Constraints:
1 <= Number of nodes<= 105
1 <= Data of a node<= 105

 

================================================ FILE: Diagonal Traversal of Binary Tree - GFG/diagonal-traversal-of-binary-tree.java ================================================ // { Driver Code Starts //Initial Template for Java //Contributed by Sudarshan Sharma import java.util.LinkedList; import java.util.Queue; import java.io.*; import java.util.*; class Node{ int data; Node left; Node right; Node(int data){ this.data = data; left=null; right=null; } } class GfG { static Node buildTree(String str){ if(str.length()==0 || str.charAt(0)=='N'){ return null; } String ip[] = str.split(" "); // Create the root of the tree Node root = new Node(Integer.parseInt(ip[0])); // Push the root to the queue Queue queue = new LinkedList<>(); queue.add(root); // Starting from the second element int i = 1; while(queue.size()>0 && i < ip.length) { // Get and remove the front of the queue Node currNode = queue.peek(); queue.remove(); // Get the current node's value from the string String currVal = ip[i]; // If the left child is not null if(!currVal.equals("N")) { // Create the left child for the current node currNode.left = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.left); } // For the right child i++; if(i >= ip.length) break; currVal = ip[i]; // If the right child is not null if(!currVal.equals("N")) { // Create the right child for the current node currNode.right = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.right); } i++; } return root; } static void printInorder(Node root) { if(root == null) return; printInorder(root.left); System.out.print(root.data+" "); printInorder(root.right); } public static void main (String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t-- > 0){ String s = br.readLine(); Node root = buildTree(s); Tree g = new Tree(); ArrayList diagonalNode = g.diagonal(root); for(int i = 0 ;i diagonal(Node root) { //add your code here. Queue q=new LinkedList<>(); ArrayList ans=new ArrayList<>(); q.add(root); while(!q.isEmpty()){ Node temp=q.remove(); while(temp!=null){ if(temp.left!=null){ q.add(temp.left); } ans.add(temp.data); temp=temp.right; } } return ans; } } ================================================ FILE: Different Bits Sum Pairwise.java ================================================ public class Solution { public int cntBits(ArrayList A) { long total = 0, n = A.size(); for (int j=0;j<32;j++) { long bitCount = 0; for (int i=0;i> j) & 1; total += (bitCount % (1000000007) *(n - bitCount) % (1000000007)) % (1000000007) ; } total = (total*2) % (1000000007); return (int)total; } } ================================================ FILE: Diffk II.java ================================================ public class Solution { // DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY public int diffPossible(final int[] A, int B) { Set set=new HashSet<>(); for(int i:A){ if(set.contains(i-B) || set.contains(B+i))return 1; set.add(i); } return 0; } } ================================================ FILE: Diffk.java ================================================ public class Solution { public int diffPossible(int[] a, int k) { int i=0; int j=1; while(ik){ if(i==j-1){ j++; } i++; } } return 0; } } ================================================ FILE: Digital Root.java ================================================ public class Solution { public int solve(int A) { while(A>9){ int temp=0; while(A!=0){ temp+=(A%10); A/=10; } A=temp; } return A; } } ================================================ FILE: Dijkstra’s_Algorithm_Shortest_distance.cpp ================================================ #include using namespace std; void dij(vector> adj[], int n, int src) { vector vis(n, 0); priority_queue, vector>, greater>> pq; vector dis(n, INT_MAX); pq.push({0, src}); dis[src] = 0; while (!pq.empty()) { int dist = pq.top().first; int prev = pq.top().second; pq.pop(); vector>::iterator it; for (it = adj[prev].begin(); it != adj[prev].end(); it++) { int next = it->first; int nextdist=it->second; if (dis[next] > dis[prev] + nextdist) { dis[next] = dis[prev] + nextdist; pq.push({dis[next],next}); } } } for (int i = 0; i < dis.size(); i++) { dis[i]==INT_MAX?cout<<"INF"<<" ":cout<> m >> n; vector> adj[m]; for (int i = 0; i < n; i++) { int x, y, w; cin >> x >> y >> w; adj[x].push_back({y, w}); } int src; cin >> src; dij(adj, m, src); } ================================================ FILE: Distance from the Source (Bellman-Ford Algorithm).java ================================================ class Solution { static int[] bellman_ford(int V, ArrayList> adj, int S) { // Write your code here int[]distance=new int[V]; Arrays.fill(distance,100000000); distance[S]=0; for(int i=1;i a:adj){ int src=a.get(0); int des=a.get(1); int weight=a.get(2); if(distance[src] + weight < distance[des]){ distance[des]=distance[src] + weight; } } } return distance; } } ================================================ FILE: Distinct Numbers in Window.java ================================================ public class Solution { public ArrayList dNums(ArrayList a, int B) { ArrayList ans=new ArrayList<>(); int n=a.size(); if(B>n)return ans; Map map=new HashMap<>(); for(int i=0;i set=new HashSet<>(); int n=s.length(); for(int i=0;i=0 && right=0 && right A) { int sum=0; if(A.size()==1 && A.get(0)==0) return 1; boolean zero=false; boolean even=false; for(int i:A){ if(i==0)zero=true; if(i%2==0 && i!=0)even=true; sum+=i; } if(sum%3==0 && zero && even)return 1; return 0; } } ================================================ FILE: Dungeon Princess.java ================================================ public class Solution { public int calculateMinimumHP(int[][] A) { int m=A.length; int n=A[0].length; A[m-1][n-1]=Math.max(1,-1*A[m-1][n-1]+1); for(int i=m-1;i>=0;i--){ for(int j=n-1;j>=0;j--){ if(i==m-1 && j==n-1){ continue; }else if(i==m-1){ A[i][j]=Math.max(1,A[i][j+1]-A[i][j]); }else if(j==n-1){ A[i][j]=Math.max(1,A[i+1][j]-A[i][j]); }else{ A[i][j]=Math.max(1,Math.min(A[i+1][j],A[i][j+1])-A[i][j]); } } } return A[0][0]; } } ================================================ FILE: Earthquake and the Paint Shop - GFG/README.md ================================================ # Earthquake and the Paint Shop ## Easy

Geek's Paint Shop is one of the famous shop in Geekland, but 2014 Earthquake caused disarrangement of the items in his shop. Each item in his shop is a 40-digit alpha numeric code .
Now Chunky wants to retain the reputation of his shop, for that he has to arrange all the distinct items in lexicographical order.
Your task is to arrange the all the distinct items in lexicographical ascending order and print them along with their count.

Example 1:

Input:
N = 3
A[] =
["2234597891 zmxvvxbcij 8800654113 jihgfedcba",
"1234567891 abcdefghij 9876543219 jihgfedcba",
"2234597891 zmxvvxbcij 8800654113 jihgfedcba"]
Output:
1234567891 abcdefghij 9876543219 jihgfedcba 1
2234597891 zmxvvxbcij 8800654113 jihgfedcba 2
Explanation:
We have 3 items (40 digit alphanumeric codes) 
here. We arrange the items based on the 
lexicographical order of their alpha-numeric 
code. Distinct items are printed only once. 
The count of the items describes how many 
such items are there, so items that appear 
more than once have their count greater than 1.

Example 2:

Input:
N = 2
A[] =
["3122049353 onafrnbhtr 9822827304 yzfhdgzcvx", 
"2992299540 lpvkgykmlk 6946169466 vdqwvywwgg", 
Output:
2992299540 lpvkgykmlk 6946169466 vdqwvywwgg  1
3122049353 onafrnbhtr 9822827304 yzfhdgzcvx  1
Explanation:
Out of the 2 items here no one is repeated.

Your Task:
You don't need to read input or print anything. Your task is to complete the function sortedStrings() which takes an integer N and an array of strings A[ ] and returns the array in sorted order along with the frequency of each distinct string.

Expected Time Complexity:O(NlogN)
Expected Auxillary Space:O(N)

Constraints:
1 ≤ N ≤ 10000

================================================ FILE: Earthquake and the Paint Shop - GFG/earthquake-and-the-paint-shop.java ================================================ //{ Driver Code Starts // Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { int N = Integer.parseInt(read.readLine()); String s[] = new String[N]; for (int i = 0; i < N; i++) s[i] = read.readLine(); Solution ob = new Solution(); alphanumeric ans[] = ob.sortedStrings(N, s); for (int i = 0; i < ans.length; i++) System.out.println(ans[i].name + " " + ans[i].count); } } } // } Driver Code Ends // User function Template for Java class alphanumeric { public String name; public int count; alphanumeric(String name, int count) { this.name = name; this.count = count; } }; class Solution { alphanumeric[] sortedStrings(int N, String A[]) { TreeMap mp = new TreeMap<>(); for(String s: A){ mp.put(s,mp.getOrDefault(s,0)+1); } int k = mp.size(); alphanumeric[] ans = new alphanumeric[k]; int t = 0; for(String s:mp.keySet()){ ans[t++] = new alphanumeric(s,mp.get(s)); } return ans; } }; ================================================ FILE: Egg Dropping Puzzle.java ================================================ class Solution { //Function to find minimum number of attempts needed in //order to find the critical floor. static int eggDrop(int n, int k) { // Your code here int[][]dp=new int[n+1][k+1]; //eggs are 1 for(int j=1;j<=k;j++){ dp[1][j]=j; } //f;oors are 1 for(int i=0;i<=n;i++){ dp[i][1]=1; } for(int i=2;i<=n;i++){ for(int j=2;j<=k;j++){ int res=j; for(int t=1;t<=j;t++){ //break int temp1=1+ dp[i-1][t-1]; //not break int temp2=1+ dp[i][j-t]; //worst case int ans=Math.max(temp1,temp2); res=Math.min(res,ans); } dp[i][j]=res; } } return dp[n][k]; } } ================================================ FILE: Elements in the Range.java ================================================ class Solution { boolean check_elements(int arr[], int n, int A, int B) { if(B-A>=n)return false; for(int i=0;i=A && Math.abs(arr[i])<=B){ int ind=Math.abs(arr[i])-A; if(arr[ind]>0)arr[ind]*=-1; } } for(int i=0;i<=B-A;i++){ if(arr[i]>0)return false; } return true; } } ================================================ FILE: Equivalent Sub-Arrays - GFG/README.md ================================================ # Equivalent Sub-Arrays ## Medium

Given an array arr[] of n integers. Count the total number of sub-array having total distinct elements same as that of total distinct elements of the original array.

 

Example 1:

Input:
N=5
arr[] = {2, 1, 3, 2, 3} 
Output: 5
Explanation:
Total distinct elements in array is 3
Total sub-arrays that satisfy the condition
are:
Subarray from index 0 to 2
Subarray from index 0 to 3
Subarray from index 0 to 4
Subarray from index 1 to 3
Subarray from index 1 to 4


Example 2:

Input:
N=5
arr[] = {2, 4, 4, 2, 4} 
Output: 9


Your Task:
Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function countDistinctSubarray() that takes array arr and integer n  as parameters and returns the desired result.

 

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).

 

Constraints:
1 ≤ N ≤ 104

 

================================================ FILE: Equivalent Sub-Arrays - GFG/equivalent-sub-arrays.java ================================================ // { Driver Code Starts //Initial Template for Java //Initial Template for Java import java.io.*; import java.util.*; // } Driver Code Ends //User function Template for Java class Solution { // Method to calculate distinct sub-array static int countDistinctSubarray(int arr[], int n) { int res = 0; HashSet set = new HashSet<>(); HashMap map = new HashMap<>(); for(int i : arr)set.add(i); for(int j = 0,i = 0;i < arr.length;i++){ map.put(arr[i],map.getOrDefault(arr[i],0) + 1); if(map.size() == set.size()) res = res + (arr.length - i); while(map.size() >= set.size() && j <= i){ map.put(arr[j],map.get(arr[j]) - 1); if(map.get(arr[j]) <= 0) map.remove(arr[j]); if(map.size() == set.size()) res = res + (arr.length - i); j++; } } return res; } } // { Driver Code Starts. // Driver class class Array { // Driver code public static void main (String[] args) throws IOException{ // Taking input using buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testcases = Integer.parseInt(br.readLine()); // looping through all testcases while(testcases-- > 0){ int n=Integer.parseInt(br.readLine()); String line1 = br.readLine(); String[] a1 = line1.trim().split("\\s+"); int a[]=new int[n]; for(int i=0;i

Given an adjacency matrix representation of an unweighted undirected graph named graph, which has N vertices. You have to find out if there is an eulerian path present in the graph or not.
Note: The graph consists of a single component

Example 1:

Input: N = 5
graph = {{0, 1, 0, 0, 1}, 
         {1, 0, 1, 1, 0}, 
         {0, 1, 0, 1, 0}, 
         {0, 1, 1, 0, 0}, 
         {1, 0, 0, 0, 0}}
Output: 1
Explaination: There is an eulerian path. 
The path is 5->1->2->4->3->2.

Example 2:

Input: N = 5
graph = {{0, 1, 0, 1, 1}, 
         {1, 0, 1, 0, 1}, 
         {0, 1, 0, 1, 1}, 
         {1, 1, 1, 0, 0}, 
         {1, 0, 1, 0, 0}}
Output: 0
Explaination: There is no eulerian path in 
the graph.

Your Task:
You do not need to read input or print anything. Your task is to complete the function eulerPath() which takes N and graph as input parameters and returns 1 if there is an eulerian path. Otherwise returns 0.

Expected Time Complexity: O(N2)
Expected Auxiliary Space: O(N2)

Constraints:
1 ≤ N ≤ 50 

================================================ FILE: Eulerian Path in an Undirected Graph - GFG/eulerian-path-in-an-undirected-graph.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[])throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); while(t-- > 0){ int N = Integer.parseInt(in.readLine()); int graph[][] = new int[N][N]; for(int i = 0;i < N;i++){ String a[] = in.readLine().trim().split("\\s+"); for(int j = 0;j < N;j++) graph[i][j] = Integer.parseInt(a[j]); } Solution ob = new Solution(); System.out.println(ob.eulerPath(N, graph)); } } }// } Driver Code Ends //User function Template for Java class Solution{ static int eulerPath(int n, int arr[][]){ // code here int count = 0; for(int ar[]: arr){ int sum = 0; for(int i: ar){ sum+=i; } if(sum%2==0)count++; if(count==(n-2))return 1; } return 0; } } ================================================ FILE: Evaluate Expression To True.java ================================================ public class Solution { int [][] DT = new int[151][151]; int [][] DF = new int[151][151]; int mod = 1003; public int cnttrue(String A) { for (int[] row: DT) Arrays.fill(row, -1); for (int[] row: DF) Arrays.fill(row, -1); return solveTrue(A, 0, A.length()-1)%1003; } int solveTrue(String A, int i, int j){ if(i>j) return 0; if(i==j){ return A.charAt(i)=='T' ? 1 : 0; } if(DT[i][j] != -1){ return DT[i][j]; } int count = 0; for(int k=i; kj) return 0; if(i==j){ return A.charAt(i)=='F' ? 1 : 0; } if(DF[i][j] != -1){ return DF[i][j]; } int count = 0; for(int k=i; k stack=new ArrayDeque<>(); int i=0; while(i

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

================================================ FILE: Even and Odd - GFG/even-and-odd.java ================================================ // { Driver Code Starts import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { int N = Integer.parseInt(read.readLine()); String S[] = read.readLine().split(" "); int[] arr = new int[N]; for(int i=0; i=2){ ans++; break; } } return ans; } } ================================================ FILE: Excel Column Title.java ================================================ public class Solution { public String convertToTitle(int n) { String ans=""; while(n!=0){ n--; int rem=n%26; ans=(char)(rem+65)+ans; n=n/26; } return ans; } } ================================================ FILE: Excel Sheet Column Number.java ================================================ class Solution { public int titleToNumber(String columnTitle) { int ans = 0; for(char c : columnTitle.toCharArray()){ ans = ans * 26 + (int)(c-'A')+ 1; } return ans; } } //=========================================================== class Solution { public int titleToNumber(String columnTitle) { if(columnTitle == null || columnTitle.length() == 0){ return 0; } int multipier = 0, result = 0; for(int i = columnTitle.length() -1 ; i >= 0 ; i-- ){ int val = columnTitle.charAt(i) - 'A'+1; result = (int) (val * Math.pow(26,multipier)) + result; multipier += 1; //System.out.println(val+" result : "+result+" multipier :"+multipier); } return result; } } ================================================ FILE: Exceptionally odd.java ================================================ class Solution { int getOddOccurrence(int[] arr, int n) { // code here int ans=0; for(int i:arr)ans=ans^i; return ans; } } ================================================ FILE: Fact Digit Sum/Fact-Digit-Sum.cpp ================================================ class Solution{ public: long factorial(long n){ if(n==0) return 1; return n*factorial(n-1); } vector FactDigit(int N) { // Code here vector ans; while(N != 0){ for(int i=9;i>=0;i--){ if(N >= factorial(i)){ ans.push_back(i); N -= factorial(i); break; } } } sort(ans.begin(), ans.end()); return ans; } }; ================================================ FILE: Fact Digit Sum.cpp ================================================ class Solution{ public: vector FactDigit(int N) { // Code here vector fact(10,1); for(int i=1; i<10; i++) fact[i] = (fact[i-1]*i); vector ans; int f = 9; while(N) { if(fact[f] <= N) { N -= fact[f]; ans.push_back(f); } else f--; } sort(ans.begin(), ans.end()); return ans; } }; ================================================ FILE: Fact Digit Sum.java ================================================ class Solution { ArrayList FactDigit(int N) { // code here ArrayList ans=new ArrayList<>(); int[]fact=new int[10]; fact[0]=1; for(int i=1;i<10;i++){ fact[i]=i*fact[i-1]; } for(int i=9;i>=1;i--){ while(N>=fact[i]){ N-=fact[i]; ans.add(i); } } Collections.reverse(ans); return ans; } } ================================================ FILE: Farthest number - GFG/README.md ================================================ # Farthest number ## Medium

Given an array Arr[] of size N. For every element in the array, the task is to find the index of the farthest element in the array to the right which is smaller than the current element. If no such number exists then print -1.
Note: 0 based indexing.


Example 1:

Input: 
N=5
Arr[] = {3, 1, 5, 2, 4}
Output: 
3 -1 4 -1 -1
Explanation:
Arr[3] is the farthest smallest element
to the right of Arr[0].
Arr[4] is the farthest smallest element
to the right of Arr[2].
And for the rest of the elements, there is
no smaller element to their right.

Example 2:

Input: 
N=5
Arr[] = {1, 2, 3, 4, 0}
Output: 
4 4 4 4 -1


Your Task: 
You don't need to read input or print anything. Your task is to complete the function farNumber() which takes the N (number of elements in Array Arr) ,Arr[], and returns the array of farthest element to the right for every element of the array.


Expected Time Complexity: O(N*logN)
Expected Auxiliary Space: O(N)


Constraints:
1 N 1e5
0
Arr[i]  1e9 

================================================ FILE: Farthest number - GFG/farthest-number.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while(t > 0){ int N = Integer.parseInt(br.readLine()); int[] Arr = new int[N]; String line = br.readLine(); String[] strs = line.trim().split("\\s+"); for(int i=0; ii){ if(a[j] rank[rootY]) root[rootY] = rootX; else if (rank[rootX] < rank[rootY]) root[rootX] = rootY; else { root[rootY] = rootX; rank[rootY]++; } size--; } } public int getSets() { return size; } } ================================================ FILE: Fill the Tank - GFG/README.md ================================================ # Fill the Tank ## Medium

In a city, N water tanks are connected by pipeline(As a tree) where the ith tank has a capacity cap[i]. The ith element of the given Edge array of length N-1 represents that there is a pipeline between Edge[i][0] and Edge[i][1] tank. Since people working at the city corporation are lazy they usually select one of the tank and pour complete amount of water into it, when the tank is filled, the excess water evenly flows to the connected tanks. The head of city corporation has instructed to pour minimum amount of water into the selected tank so that all other tank is filled. As the labours of the corporation are not intelligent enough to figure out the minimum amount of water required to fill all the tanks they have asked your help. Also Maximum amount of water available with city corporation is 1018.

NOTE: If the tank if full, the water flows to all of its connected tanks except the tank from which the water had come to it. i.e, to all tanks except the source for that particular tank. If it has no option to flow the water is considered to be wasted. S is the source tank.

Example 1:

Input:
N = 4 and S = 1
Edges = [[1, 2], [1, 3], [2, 4]]
Cap = [1, 1, 1, 1]
Output: 5
Explanation:
Initially 5 unit of water is poured into 
tank 1. 2 unit of it flows to tank 2 and 
2 unit of it flows into tank 3. From 2 
unit of water in tank 2, 1 unit flows into 
tank 4 and 1 unit from tank 3 is wasted.



 

Example 2:

Input:
N = 3 and S = 2
Edges = [[1, 2], [2, 3]]
Cap = [1, 1, 1]
Output: 3


Your Task:  
You don't need to read input or print anything. Your task is to complete the function minimum_amount() which takes an integer N, an integer S, 2-d array Edges, and an array Cap of length N as input parameters and returns the minimum amount of water required to fill all the tanks. If it is not possible to fill all the tanks print -1.

Expected Time Complexity: O(N*log(S))
Expected Auxiliary Space: O(1)

 

Constraints:
1 ≤ n ≤ 100000
1 ≤ s,u,v ≤ n
1 ≤ capacity of each tank ≤ 1000000007

================================================ FILE: Fill the Tank - GFG/fill-the-tank.java ================================================ // { Driver Code Starts import java.io.*; import java.util.*; class GFG { public static void main(String args[])throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { String input_line[] = read.readLine().trim().split("\\s+"); int N = Integer.parseInt(input_line[0]); int S = Integer.parseInt(input_line[1]); String input_line1[] = read.readLine().trim().split("\\s+"); int cap[] = new int[N]; for(int i=0;i> adj = new ArrayList<>(); for(int i=0; i<=N; i++){ adj.add(new ArrayList<>()); } for(int i=0; i> adj, int s, int[] cap, boolean[] visited){ long res = -1; visited[s] = true; int sz = 0; for(int x: adj.get(s)){ if(visited[x])continue; sz++; long cur = ans(adj,x,cap,visited); if(cur>10E17) visited[0] = true; res = Math.max(res,cur); } long curAns = res*sz + cap[s-1]; if(curAns>10E17) visited[0] = true; return curAns; } } ================================================ FILE: Filling Bucket - GFG/README.md ================================================ # Filling Bucket ## Medium

Given a Bucket having a capacity of N litres and the task is to determine that by how many ways you can fill it using two bottles of capacity of 1 Litre and 2 Litre only. Find the answer modulo 108.

Example 1:

Input:
3
Output:
3 
Explanation:
Let O denote filling by 1 litre bottle and
T denote filling by 2 litre bottle.
So for N = 3, we have :
{OOO,TO,OT}. Thus there are 3 total ways.

Example 2:

Input:
4
Output:
5 
Explanation:
Let O denote filling by 1 litre bottle and
T denote filling by 2 litre bottle.
So for N = 4, we have :
{TT,OOOO,TOO,OTO,OOT} thus there are 5 total ways.

Your Task:
You don't need to read input or print anything. Your task is to complete the function fillingBucket() which takes an Integer N as input and returns the number of total ways possible.

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

Constraints:
1 <= N <= 105

================================================ FILE: Filling Bucket - GFG/filling-bucket.java ================================================ //{ Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { int N = Integer.parseInt(read.readLine()); Solution ob = new Solution(); System.out.println(ob.fillingBucket(N)); } } } // } Driver Code Ends //User function Template for Java class Solution { static int fillingBucket(int N) { // code here if(N==1)return 1; int prev=2; int secPrev=1; int mod=100000000; for(int i=0;i findAnagrams(String s, String p) { int ns = s.length(), np = p.length(); List results = new ArrayList<>(); int[] charMap = new int[26]; for (char c:p.toCharArray()) { charMap[c - 'a']++; } for (int i = 0; i < ns; i++) { char c = s.charAt(i); charMap[c - 'a']--; if (i >= np) { char last = s.charAt(i - np); charMap[last - 'a']++; } if (i >= np - 1) { boolean valid = true; for (int j = 0; j < 26; j++) { if (charMap[j] != 0) { valid = false; break; } } if (valid) { results.add(i - np + 1); } } } return results; } } ================================================ FILE: Find Last Digit.java ================================================ import java.math.BigInteger; public class Solution { public int solve(String A, String B) { int n=A.length(); if(A.charAt(n-1)=='1'){ return 1; }else if(A.charAt(n-1)=='0'){ return 0; }else if(A.charAt(n-1)=='5'){ return 5; }else if(A.charAt(n-1)=='6'){ return 6; }else if(A.charAt(n-1)=='2'){ int pattern[]=new int[]{2,4,8,6}; BigInteger in=new BigInteger(B); BigInteger sz=BigInteger.valueOf(4); int x=in.mod(sz).intValue(); if(x==0)return pattern[3]; return pattern[x-1]; }else if(A.charAt(n-1)=='3'){ int pattern[]=new int[]{3,9,7,1}; BigInteger in=new BigInteger(B); BigInteger sz=BigInteger.valueOf(4); int x=in.mod(sz).intValue(); if(x==0)return pattern[3]; return pattern[x-1]; }else if(A.charAt(n-1)=='4'){ int pattern[]=new int[]{4,6}; BigInteger in=new BigInteger(B); BigInteger sz=BigInteger.valueOf(2); int x=in.mod(sz).intValue(); if(x==0)return pattern[1]; return pattern[x-1]; }else if(A.charAt(n-1)=='7'){ int pattern[]=new int[]{7,9,3,1}; BigInteger in=new BigInteger(B); BigInteger sz=BigInteger.valueOf(4); int x=in.mod(sz).intValue(); if(x==0)return pattern[3]; return pattern[x-1]; }else if(A.charAt(n-1)=='8'){ int pattern[]=new int[]{8,4,2,6}; BigInteger in=new BigInteger(B); BigInteger sz=BigInteger.valueOf(4); int x=in.mod(sz).intValue(); if(x==0)return pattern[3]; return pattern[x-1]; }else if(A.charAt(n-1)=='9'){ int pattern[]=new int[]{9,1}; BigInteger in=new BigInteger(B); BigInteger sz=BigInteger.valueOf(2); int x=in.mod(sz).intValue(); if(x==0)return pattern[1]; return pattern[0]; } return 1; } } ================================================ FILE: Find Missing And Repeating.java ================================================ class Solve { int[] findTwoElement(int arr[], int n) { // code here int[]ans=new int[2]; for(int i=0;i0){ ans[1]=i+1; break; } } return ans; } } ================================================ FILE: Find Original Array From Doubled Array.java ================================================ class Solution { public int[] findOriginalArray(int[] changed) { int f[]=new int[100001]; if(changed.length%2==1) return new int[0]; // if Array Length is odd cant find for(int i=0;i0) { if(k*2>100000 || f[k*2]==0) return new int[0]; //As Array values always <=100000 and cant be greater values cannot find k*2>1000000 which is false and id the frequency of k*2==0 means return false else { f[k*2]-=1; f[k]-=1; res[ind++]=i; } } } return res; } } ================================================ FILE: Find Prime numbers in a range.java ================================================ class Solution { ArrayList primeRange(int M, int N) { // code here ArrayList list=new ArrayList<>(); for(int i=M;i<=N;i++){ if(isPrime(i))list.add(i); } return list; } boolean isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } } ================================================ FILE: Find Second Smallest and Second Largest Element in an array without sorting/Find-Second-Smallest-and-Second-Largest-Element-in-an-array-with-out-sorting.cpp ================================================ // Find Second Smallest and Second Largest Element in an array without sorting #include using namespace std; int main() { int arr[6] = {1, 2, 4, 7, 7, 5}; int n = sizeof(arr) / sizeof(arr[0]); int small = INT_MAX, second_small = INT_MAX, large = INT_MIN, second_large = INT_MIN; for (int i = 0; i < n; i++) { if (arr[i] < small) // if any number is still smaller than the current smaller then update second smaller and small number { second_small = small; small = arr[i]; } else if (arr[i] < second_small and arr[i] != small) second_small = arr[i]; if (arr[i] > large) { second_large = large; // if any number is still larger thab the current largest then update the second largest and large number large = arr[i]; } else if (arr[i] > second_large and arr[i] != large) second_large = arr[i]; } cout << small << " " << large << '\n'; cout << second_small << " " << second_large << '\n'; } ================================================ FILE: Find Three Consecutive Integers That Sum to a Given Number.py ================================================ class Solution: def sumOfThree(self, num: int) -> List[int]: x=num//3 a=[x-1,x,x+1] if 3*x !=num: return [] return a ================================================ FILE: Find Transition Point - GFG/README.md ================================================ # Find Transition Point ## Easy

Given a sorted array containing only 0s and 1s, find the transition point. 


Example 1:

Input:
N = 5
arr[] = {0,0,0,1,1}
Output: 3
Explanation: index 3 is the transition 
point where 1 begins.


Example 2:

Input:
N = 4
arr[] = {0,0,0,0}
Output: -1
Explanation: Since, there is no "1",
the answer is -1.


Your Task:
You don't need to read input or print anything. The task is to complete the function transitionPoint() that takes array and N as input parameters and returns the 0 based index of the position where "0" ends and "1" begins. If array does not have any 1s, return -1. If array does not have any 0s, return 0.


Expected Time Complexity: O(LogN)
Expected Auxiliary Space: O(1)


Constraints:
1 ≤ N ≤ 500000
0 ≤ arr[i] ≤ 1

================================================ FILE: Find Transition Point - GFG/find-transition-point.java ================================================ // { Driver Code Starts import java.util.*; class Sorted_Array { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while (T > 0) { int n = sc.nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } GfG obj = new GfG(); System.out.println(obj.transitionPoint(arr, n)); T--; } } }// } Driver Code Ends class GfG { int transitionPoint(int arr[], int n){ int i=0; int j=n; int mid; while(i A) { if(A.size()==1)return A.get(0); for(int i=0;iA.get(i+1))return A.get(i); }else if(i==A.size()-1){ if(A.get(A.size()-1)>A.get(i-2))return A.get(A.size()-1); }else{ if(A.get(i)>A.get(i+1) && A.get(i)>A.get(i-1))return A.get(i); } } return -1; } } ================================================ FILE: Find all distinct subset (or subsequence) sums - GFG/Find all distinct subset (or subsequence) sums.cpp ================================================ // two solutions: // 1. class Solution { public: set s; int dp[101][10001]; vector DistinctSum(vectornums){ int n = nums.size(); memset(dp, -1, sizeof(dp)); solve(0, nums, n); vector ans; for(auto& val: s) { ans.push_back(val); } return ans; } void solve(int sum, vector& nums, int n) { if(n==0) { s.insert(sum); return; } if(dp[n][sum]==1) return; solve(sum+nums[n-1], nums, n-1); solve(sum, nums, n-1); dp[n][sum] = 1; } }; // 2. class Solution { public: vector DistinctSum(vector nums){ // Code here set st; st.insert(0); for(auto num : nums){ vector v; for(auto i : st) v.push_back(i + num); for(auto vv : v) st.insert(vv); } nums.clear(); for(auto it : st) nums.push_back(it); return nums; } }; ================================================ FILE: Find all distinct subset (or subsequence) sums.java ================================================ class Solution { public int[] DistinctSum(int[] nums) { // Code here boolean[][]dp=new boolean[101][10001]; Set set=new HashSet<>(); dfs(nums,0,0,set,dp); int[] ans=new int[set.size()]; int i=0; for(int ele:set){ ans[i]=ele; i++; } Arrays.sort(ans); return ans; } void dfs(int[]nums,int i,int sum,Set set,boolean[][]dp){ if(i==nums.length){ set.add(sum); return; } if(dp[i][sum])return; dp[i][sum]=true; dfs(nums,i+1,sum,set,dp); dfs(nums,i+1,sum+nums[i],set,dp); } } ================================================ FILE: Find all possible paths from top to bottom - GFG/README.md ================================================ # Find all possible paths from top to bottom ## Easy

Given a N x M grid. Find All possible paths from top left to bottom right.From each cell you can either move only to right or down.

Example 1:

Input: 1 2 3
       4 5 6
Output: 1 4 5 6
        1 2 5 6 
        1 2 3 6
Explanation: We can see that there are 3 
paths from the cell (0,0) to (1,2).

Example 2:

Input: 1 2
       3 4
Output: 1 2 4
        1 3 4

Your Task:
You don't need to read input or print anything. Your task is to complete the function findAllPossiblePaths() which takes two integers n,m and grid[][]  as input parameters and returns all possible paths from the top left cell to bottom right cell in a 2d array.

Expected Time Complexity: O(2^N*M)
Expected Auxiliary Space: O(N)


Constraints:
1 <= n,m <= 10 
1 <= grid[i][j] <= n*m
n * m < 20

 

================================================ FILE: Find all possible paths from top to bottom - GFG/find-all-possible-paths-from-top-to-bottom.java ================================================ // { Driver Code Starts import java.io.*; import java.util.*; class IntArray { public static int[] input(BufferedReader br, int n) throws IOException { String[] s = br.readLine().trim().split(" "); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = Integer.parseInt(s[i]); return a; } public static void print(int[] a) { for(int e : a) System.out.print(e + " "); System.out.println(); } public static void print(ArrayList a) { for(int e : a) System.out.print(e + " "); System.out.println(); } } class IntMatrix { public static int[][] input(BufferedReader br, int n, int m) throws IOException { int[][] mat = new int[n][]; for(int i = 0; i < n; i++) { String[] s = br.readLine().trim().split(" "); mat[i] = new int[s.length]; for(int j = 0; j < s.length; j++) mat[i][j] = Integer.parseInt(s[j]); } return mat; } public static void print(int[][] m) { for(var a : m) { for(int e : a) System.out.print(e + " "); System.out.println(); } } public static void print(ArrayList> m) { for(var a : m) { for(int e : a) System.out.print(e + " "); System.out.println(); } } } class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t; t = Integer.parseInt(br.readLine()); while(t-- > 0){ int[] a = IntArray.input(br, 2); int[][] grid = IntMatrix.input(br, a[0], a[1]); Solution obj = new Solution(); ArrayList> res = obj.findAllPossiblePaths(a[0],a[1], grid); IntMatrix.print(res); } } } // } Driver Code Ends class Solution { public static ArrayList> findAllPossiblePaths(int n,int m, int[][] grid) { // code here ArrayList> ans=new ArrayList<>(); ArrayList curr=new ArrayList<>(); int i=0; int j=0; curr.add(grid[0][0]); dfs(ans,curr,i,j,grid); return ans; } static void dfs(ArrayList> ans,ArrayListcurr,int i,int j,int[][]grid){ if(i==grid.length-1 && j==grid[0].length-1){ ans.add(new ArrayList<>(curr)); return; } if(valid(i+1,j,grid)){ curr.add(grid[i+1][j]); dfs(ans,curr,i+1,j,grid); curr.remove(curr.size()-1); } if(valid(i,j+1,grid)){ curr.add(grid[i][j+1]); dfs(ans,curr,i,j+1,grid); curr.remove(curr.size()-1); } } static boolean valid(int i,int j,int[][]grid){ if(i==grid.length || j==grid[0].length)return false; return true; } } ================================================ FILE: Find an Replace in String - GFG/README.md ================================================ # Find an Replace in String ## Medium

Given a string S on which you need to perform Q replace operations.
Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y. The rule is that if x starts at position i in the original string S, then we will replace that occurrence of x with y. If not, we do nothing.
Note:
All these operations occur simultaneously. It's guaranteed that there won't be any overlap in replacement: for example, S = "abc", indexes = [0,1], sources = ["ab", "bc"] is not a valid test case.


Example 1:

Input: 
S = "gforks"
Q = 2
index[] = {0, 4}
sources[] = {"g", "ks"}
targets[] = {"geeks", "geeks"}
Output: 
geeksforgeeks
Explanation:
"g" starts at index 0, so, it's reaplaced by
"geeks". Similarly, "ks" starts at index 4,
and is replaced by "geeks".

Example 2:

Input: 
S = "gforks"
Q = 2
index[] = {0, 3}
sources[] = {"g", "ss"}
targets[] = {"geeks", "geeks"}
Output: 
geeksforks
Explanation:
"g" starts at index 0, so, it's reaplaced by
"geeks". "ss" doesn't start at index 3 in
original S, so it's not replaced.


Your Task:
You don't need to read input or print anything. You only need to complete the function findAndReplace() that takes a string S, an integer Q, and 3 arrays index, sources, and targets of size Q, as input and returns the new string after all the operations. index[i], sources[i], and targets[i] denotes the index, sources, and targets for ith query.


Expected Time Complexity:  O(|S| * Q)
Expected Auxilliary Space: O(Q)

 

Constraints:
1 ≤ |S| ≤ 104
1 ≤ Q ≤ 100
1 ≤ length of sourcesi, targetsi ≤ 100

================================================ FILE: Find an Replace in String - GFG/find-an-replace-in-string.java ================================================ // { Driver Code Starts import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { String S = read.readLine(); int Q = Integer.parseInt(read.readLine()); int[] index = new int[Q]; String[] sources = new String[Q]; String[] targets = new String[Q]; String S1[] = read.readLine().split(" "); String S2[] = read.readLine().split(" "); String S3[] = read.readLine().split(" "); for(int i=0 ; i

Given a linked list of size N. The task is to complete the function countNodesinLoop() that checks whether a given Linked List contains a loop or not and if the loop is present then return the count of nodes in a loop or else return 0. C is the position of the node to which the last node is connected. If it is 0 then no loop.

Example 1:

Input:
N = 10
value[]={25,14,19,33,10,21,39,90,58,45}
C = 4
Output: 7
Explanation: The loop is 45->33. So
length of loop is 33->10->21->39->
90->58->45 = 7. The number 33 is
connected to the last node to form the
loop because according to the input the
4th node from the beginning(1 based
index) will be connected to the last
node for the loop.

Example 2:

Input:
N = 2
value[] = {1,0}
C = 1
Output: 2
Explanation: The length of the loop
is 2.

Your Task:
The task is to complete the function countNodesinLoop() which contains the only argument as reference to head of linked list and return the lenght of the loop ( 0 if there is no loop).

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

Constraints:
1 <= N <= 500
0 <= C <= N-1

================================================ FILE: Find length of Loop - GFG/find-length-of-loop.java ================================================ // { Driver Code Starts // driver code import java.util.*; import java.io.*; import java.lang.*; class Node { int data; Node next; Node(int x) { data = x; next = null; } } class GFG { public static void makeLoop(Node head, Node tail, int x){ if (x == 0) return; Node curr = head; for(int i=1; i 0) { int n = sc.nextInt(); int num = sc.nextInt(); Node head = new Node(num); Node tail = head; for(int i=0; i> findPairsWithGivenSum(Node *head, int target) { // code here vector> ans; Node* front = head; Node* rear = head; while(rear->next) rear = rear->next; while(front->data < rear->data) { int num1 = front->data, num2 = rear->data; if(num1 + num2 == target) { ans.push_back({num1, num2}); front = front->next; } else if(num1 + num2 > target) rear = rear->prev; else front = front->next; } return ans; } }; ================================================ FILE: Find pairs with given sum in doubly linked list.java ================================================ class Solution { public static ArrayList> findPairsWithGivenSum(int target, Node head) { // code here Node tail=head; while(tail.next!=null)tail=tail.next; ArrayList> ans=new ArrayList<>(); while(head!=tail){ if(head.data+tail.data==target){ ArrayList pair=new ArrayList<>(); pair.add(head.data); pair.add(tail.data); ans.add(pair); tail=tail.prev; }else if(head.data+tail.data>target){ tail=tail.prev; }else{ head=head.next; } } return ans; } ================================================ FILE: Find rectangle with corners as 1.java ================================================ public class Solution { static boolean ValidCorner(int mat[][]) { int n=mat.length; int m=mat[0].length; for(int i=0;i=2){ return true; } } } return false; } } ================================================ FILE: Find the Difference.java ================================================ class Solution { public char findTheDifference(String s, String t) { int diff = 0; int i = 0; for( i = 0; i < s.length(); i++) { diff = diff ^ s.charAt(i) ^ t.charAt(i); } diff = diff ^ t.charAt(i); return (char) diff; } } ================================================ FILE: Find the Maximum Flow - GFG/README.md ================================================ # Find the Maximum Flow ## Hard

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

================================================ FILE: Find the Maximum Flow - GFG/find-the-maximum-flow.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0){ String input_line[] = read.readLine().trim().split("\\s+"); int N = Integer.parseInt(input_line[0]); int M = Integer.parseInt(input_line[1]); ArrayList> Edges = new ArrayList>(); input_line = read.readLine().trim().split("\\s+"); for(int i=0;i e = new ArrayList(); e.add(Integer.parseInt(input_line[3*i])); e.add(Integer.parseInt(input_line[3*i+1])); e.add(Integer.parseInt(input_line[3*i+2])); Edges.add(e); } Solution ob = new Solution(); int ans = ob.solve(N, M, Edges); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution { int bfs(int[][] g,int[] p,int source,int sink,int n){ int mn=Integer.MAX_VALUE; Arrays.fill(p,-1); boolean[] vis=new boolean[n]; Queue q=new LinkedList<>(); q.add(source); vis[source]=true; p[source]=-1; while(!q.isEmpty()){ int u = q.remove(); for(int v=0;v> Edges) { // code here int g[][] = new int[N][N]; for(int i=0;i leftSmaller(int n, int a[]){ // code here vector ans(n); stack s; s.push(-1); for(int i=0;i=a[i]){ s.pop(); } ans[i] = s.top(); } s.push(a[i]); } return ans; } }; ================================================ FILE: Find the number of islands.java ================================================ class axis{ int x; int y; public axis(int x,int y){ this.x=x; this.y=y; } @Override public boolean equals(Object o){ if (o == this) return true; if (!(o instanceof axis)) return false; axis a = (axis) o; return x==a.x && y==a.y; } } class Solution { // Function to find the number of islands. public int numIslands(char[][] grid) { // Code here int count=0; for(int i=0;i stack=new ArrayDeque<>(); stack.push(ax); while(!stack.isEmpty()){ axis a=stack.pop(); int i=a.x; int j=a.y; grid[i][j]='0'; if((i-1)>=0){ if(grid[i-1][j]=='1'){ stack.push(new axis(i-1,j)); } } if((i-1)>=0 && j+1=0){ if(grid[i+1][j-1]=='1'){ stack.push(new axis(i+1,j-1)); } } if(j-1>=0){ if(grid[i][j-1]=='1'){ stack.push(new axis(i,j-1)); } } if(j-1>=0 && i-1>=0){ if(grid[i-1][j-1]=='1'){ stack.push(new axis(i-1,j-1)); } } } } } ================================================ FILE: Find whether path exist - GFG/README.md ================================================ # Find whether path exist ## Medium

Given a grid of size n*n filled with 0, 1, 2, 3. Check whether there is a path possible from the source to destination. You can traverse up, down, right and left.
The description of cells is as follows:

  • A value of cell 1 means Source.
  • A value of cell 2 means Destination.
  • A value of cell 3 means Blank cell.
  • A value of cell means Wall.

Note: There are only a single source and a single destination.
 

Example 1:

Input: grid = {{3,0,3,0,0},{3,0,0,0,3}
,{3,3,3,3,3},{0,2,3,0,0},{3,0,0,1,3}}
Output: 0
Explanation: The grid is-
3 0 3 0 0 
3 0 0 0 3 
3 3 3 3 3 
0 2 3 0 0 
3 0 0 1 3 
There is no path to reach at (3,1) i,e at 
destination from (4,3) i,e source.

Example 2:

Input: grid = {{1,3},{3,2}}
Output: 1
Explanation: The grid is-
1 3
3 2
There is a path from (0,0) i,e source to (1,1) 
i,e destination.

 

Your Task:
You don't need to read or print anything. Your task is to complete the function is_Possible() which takes the grid as input parameter and returns boolean value true if there is a path otherwise returns false.

 

Expected Time Complexity: O(n2)
Expected Auxiliary Space: O(n2)

 

Constraints:
1 ≤ n ≤ 500

================================================ FILE: Find whether path exist - GFG/find-whether-path-exist.java ================================================ // { Driver Code Starts import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { int n = Integer.parseInt(br.readLine().trim()); int[][] grid = new int[n][n]; for(int i = 0; i < n; i++){ String[] S = br.readLine().trim().split(" "); for(int j = 0; j < n; j++){ grid[i][j] = Integer.parseInt(S[j]); } } Solution obj = new Solution(); boolean ans = obj.is_Possible(grid); if(ans) System.out.println("1"); else System.out.println("0"); } } }// } Driver Code Ends class Solution { boolean res=false; //Function to find whether a path exists from the source to destination. public boolean is_Possible(int[][] grid){ int n=grid.length; int m=grid[0].length; boolean vis[][]=new boolean[n][m]; for(int i=0;i

Consider a special family of Engineers and Doctors with following rules :

  1. Everybody has two children.
  2. First child of an Engineer is an Engineer and second child is a Doctor.
  3. First child of an Doctor is Doctor and second child is an Engineer.
  4. All generations of Doctors and Engineers start with Engineer.

We can represent the situation using below diagram:

                E
           /        \
          E          D
        /   \       /  \
       E     D     D    E
      / \   / \   / \   / \
     E   D D   E  D  E  E  D

Given level and position(pos) of a person in above ancestor tree, find profession of the person.

Example 1:

Input: level = 4, pos = 2
Output: Doctor
Explaination: It is shown in the tree given 
in question.

Example 2:

Input: level = 3, pos = 4
Output: Engineer
Explaination: Already given in the tree in 
question.

Your Task:
You do not need to read input or print anything. Your task is to complete the function profession() which takes level and pos as input parameters and returns 'd' if it is a doctor. Otherwise return 'e'. The driver code will output Doctor for 'd' and Engineer for 'e' itself.

Expected Time Complexity: O(log(pos))
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ level ≤ 109
1 ≤ pos ≤ min(109, 2level-1)

================================================ FILE: Finding Profession - GFG/finding-profession.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[])throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); while(t-- > 0){ String a[] = in.readLine().trim().split("\\s+"); int level = Integer.parseInt(a[0]); int pos = Integer.parseInt(a[1]); Solution ob = new Solution(); if(ob.profession(level, pos) == 'd') System.out.println("Doctor"); else System.out.println("Engineer"); } } }// } Driver Code Ends //User function Template for Java class Solution{ static int countSetBits(int n) { int count = 0; while (n != 0) { n &= (n-1) ; count++; } return count; } static char profession(int level, int pos){ // Count set bits in 'pos-1' int c = countSetBits(pos-1); // If set bit count is odd, then doctor, else engineer return (c%2 == 1)? 'd' : 'e'; } } ================================================ FILE: Firing employees.java ================================================ class Solution { static int firingEmployees(int arr[], int n) { // code here int ans=0; int[]dp=new int[n]; for(int i=0;i A) { A.removeIf(val -> val <=0); Collections.sort(A); for(int j = 0;j A) { Set set=new HashSet<>(); int ans=-1; for(int i=A.size()-1;i>=0;i--){ int num=A.get(i); if(set.contains(num)){ ans=num; }else{ set.add(num); } } return ans; } } ================================================ FILE: Flip.java ================================================ public class Solution { public ArrayList flip(String A) { ArrayList al = new ArrayList<>(); int max = 0; int diff = 0; int start = 0; boolean solFound = false; int[] ans = new int[2]; for(int i = 0; i < A.length(); i++) { char c = A.charAt(i); diff += (c == '0') ? 1 : -1; if(diff < 0) { diff = 0; start = (c == '0') ? i : i + 1; } else { if(max < diff) { max = diff; if(al.isEmpty()){ al.add(start); al.add(i); } else { al.set(0, start); al.set(1, i); } solFound = true; } } } if(!solFound) { return new ArrayList<>(); } al.set(0, al.get(0)+1); al.set(1, al.get(1)+1); return al; } } ================================================ FILE: Foldable Binary Tree.cpp ================================================ <<<<<<< HEAD // function that checks it tree with roots are mirror of each other bool isFoldableUtil(Node *n1, Node *n2){ // if both left and right subtrees are null if(!n1 && !n2) return true; // if one tree is null and not other return false if(!n1 || !n2) return false; // check whether left and right subtrees are mirror return isFoldableUtil(n1->left, n2->right) && isFoldableUtil(n1->right, n2->left); } ======= >>>>>>> upstream/main //Function to check whether a binary tree is foldable or not. bool IsFoldable(Node* root) { // Your code goes here <<<<<<< HEAD if(!root) return true; return isFoldableUtil(root->left, root->right); } // TC: O(n) -> where n is the number of nodes in binary tree ======= if(!root) return true; return checkMirror(root->left, root->right); } bool checkMirror(Node* root1, Node* root2) { if(!root1 and !root2) return true; if(!root1 or !root2) return false; return checkMirror(root1->left, root2->right) and checkMirror(root1->right, root2->left); } ////Another approach but takes more space than above solution /* bool IsFoldable(Node* root) { // Your code goes here queue Q; Q.push(root); while(!Q.empty()) { int sz = Q.size(); vector arr; while(sz--) { Node* cur = Q.front(); Q.pop(); if(cur) { arr.push_back(true); Q.push(cur->left); Q.push(cur->right); } else arr.push_back(false); } int n = arr.size(); for(int i=0; i>>>>>> upstream/main ================================================ FILE: Foldable Binary Tree.java ================================================ class Tree { //Function to check whether a binary tree is foldable or not. boolean IsFoldable(Node node) { // your code if(node==null)return true; return dfs(node.left,node.right); } boolean dfs(Node a,Node b){ if(a==null && b==null)return true; if(a==null || b==null)return false; return dfs(a.left,b.right) && dfs(a.right,b.left); } } ================================================ FILE: Form a palindrome - GFG/README.md ================================================ # 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

================================================ FILE: Form a palindrome - GFG/form-a-palindrome.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[])throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { String S = read.readLine().trim(); Solution ob = new Solution(); System.out.println(ob.findMinInsertions(S)); } } }// } Driver Code Ends //User function Template for Java class Solution{ private static Integer[][] dp; private static int find(int l, int r, String s){ if(l > r){ return 0; } if(dp[l][r] != null){ return dp[l][r]; } if(s.charAt(l) == s.charAt(r)){ return dp[l][r] = find(l+1, r-1, s); }else{ return dp[l][r] = 1 + Math.min(find(l+1, r, s), find(l, r-1, s)); } } int findMinInsertions(String S){ dp = new Integer[S.length()][S.length()]; return find(0, S.length()-1, S); } } ================================================ FILE: Form coils in a matrix - GFG/README.md ================================================ # Form coils in a matrix ## Medium

Given a positive integer n that represents dimensions of a 4n x 4n matrix with values from 1 to 4*n*4*n filled from left to right and top to bottom. Your task is to form two coils from matrix and print the coils.

Follow the given examples for better understanding.

 

Example 1:

Input:
n = 1
Output:
10 6 2 3 4 8 12 16
7 11 15 14 13 9 5 1 
Explanation:
The matrix is 
1  2  3  4
5  6  7  8
9  10 11 12
13 14 15 16
So, the two coils are as given in the Ouput.

Example 2:

Input:
n = 2
Output:
36 28 20 21 22 30 38 46
54 53 52 51 50 42 34 26
18 10 2 3 4 5 6 7 8
16 24 32 40 48 56 64

29 37 45 44 43 35 27 19
11 12 13 14 15 23 31 39
47 55 63 62 61 60 59 58
57 49 41 33 25 17 9 1  
Explanation:


Your Task:
You don't need to read input or print anything. Your task is to complete the function formCoils() which takes an Integer n as input and returns a vector of two vectors representing coil1 and coil2.

 

Expected Time Complexity: O(n2)
Expected Auxiliary Space: O(n2)

 

Constraints:
1 <= n <= 20

================================================ FILE: Form coils in a matrix - GFG/form-coils-in-a-matrix.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { int n = Integer.parseInt(read.readLine()); Solution ob = new Solution(); int[][] ptr = ob.formCoils(n); for(int i=0; i<2; i++) { for(int j=0; j= left){ if(dir == 0){ for(int i = down ; i >= top ; i --){ ans[idx] = arr[i][right]; idx++; } right--; down--; } else if(dir == 1){ for(int i = right ; i >= left ; i --){ ans[idx] = arr[top][i]; idx++; } right--; top++; } else if(dir == 2){ for(int i = top ; i <= down ; i ++){ ans[idx] = arr[i][left]; idx++; } top++; left++; } else if(dir == 3){ for(int i = left ; i <= right ; i ++){ ans[idx] = arr[down][i]; idx++; } down--; left++; } dir = (dir+1)%4; } int [][]res = new int[2][8*n*n]; int x = ans.length-1; for(int j = 0 ; j < res[0].length ; j ++) { res[0][j] = ans[x]; x--; } top = 0; down = 4*n-1; left = 0; right = 4*n-2; dir = 0; idx = 0; while (top <= down && right >= left){ if(dir == 0){ for(int i = top ; i <= down ; i ++){ ans[idx] = arr[i][left]; idx++; } top++; left++; } else if(dir == 1){ for(int i = left ; i <= right ; i ++){ ans[idx] = arr[down][i]; idx++; } down--; left++; } else if(dir == 2){ for(int i = down ; i >= top ; i --){ ans[idx] = arr[i][right]; idx++; } right--; down--; } else if(dir == 3){ for(int i = right ; i >= left ; i --){ ans[idx] = arr[top][i]; idx++; } right--; top++; } dir = (dir+1)%4; } x = ans.length-1; for(int j = 0 ; j < res[0].length ; j ++) { res[1][j] = ans[x]; x--; } return res; } } ================================================ FILE: Fraction Trouble - GFG/README.md ================================================ # Fraction Trouble ## Easy

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

================================================ FILE: Fraction Trouble - GFG/fraction-trouble.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String[] input = new String[2]; input = br.readLine().split(" "); int n = Integer.parseInt(input[0]); int d = Integer.parseInt(input[1]); Solution ob = new Solution(); int[] ans = ob.numAndDen(n,d); for(int i = 0; i < ans.length; i++) { System.out.print(ans[i] + " "); } System.out.println(); } } } // } Driver Code Ends class Solution { public int[] numAndDen(int n, int d) { int num = 0; int den = 1; for (int q = 10000; q >= 2; q--){ int p = (n * q - 1) / d; if (p * den >= num * q){ den = q; num = p; } } int tot = gcdnumber(num,den); int [] ans = new int[2]; ans[0] = num/tot; ans[1] = den/tot; return ans; } static int gcdnumber(int a, int b) { if (b == 0) return a; return gcdnumber(b, a % b); } } ================================================ FILE: Fraction.java ================================================ public class Solution { public String fractionToDecimal(int numerator, int denominator) { long a=numerator,b=denominator; if(a%b==0) return String.valueOf(a/b); Map map=new HashMap<>(); StringBuilder res=new StringBuilder(); if((a>0&&b<0)||(a<0&&b>0)) res.append("-"); a=Math.abs(a); b=Math.abs(b); res.append(a/b+"."); a=(a%b)*10; while(!map.containsKey(a)){ map.put(a,res.length()); res.append(String.valueOf(a/b)); a=(a%b)*10; if(a==0) return res.toString(); } return res.insert(map.get(a),"(").append(")").toString(); } } ================================================ FILE: Friends Pairing Problem DP.java ================================================ class Solution { public long countFriendsPairings(int n) { long mod = 1000000007; long[] dp = new long[n+1]; return helper(n,dp,mod); } long helper(int n,long[] dp,long mod){ if(n<=2) return n; if(dp[n]!=0) return dp[n]; return dp[n] = (helper(n-1,dp,mod) + ((n-1)*helper(n-2,dp,mod)))%mod; } } ================================================ FILE: Friends Pairing Problem.cpp ================================================ class Solution { public: //defining mod long long MOD = 1000000007; int countFriendsPairings(int n) { //numbers less than 3 will have the same answer if(n < 3) return n; //defining and storing base conditions long long prev1 = 1; long long prev2 = 2; //using tabulation based on the pattern observed for(long long i = 3; i <= n; i++) { long long temp = prev2 % MOD; prev2 = (((((i-1) % MOD)*(prev1 % MOD))%MOD) + (prev2 % MOD))%MOD; prev1 = temp; } return prev2; } }; ================================================ FILE: Friends Pairing Problem.java ================================================ class Solution { public long countFriendsPairings(int n) { //code here if(n<=2)return n; long mod=(int)Math.pow(10,9)+7; long secPrev=1; long prev=2; long curr=0; for(int i=3;i<=n;i++){ curr=(prev+(((i-1)%mod)*(secPrev%mod))%mod)%mod; secPrev=prev; prev=curr; } return curr; } } ================================================ FILE: GFG/0 -1 Knapsack Problem/0 - 1 Knapsack Problem.java ================================================ class Solution { //Function to return max value that can be put in knapsack of capacity W. // below function is recursion+dp version of the problem, problem can be solved using only this function also static int myfunc(int w, int wt[], int val[], int n, int[][] ans){ if(w==0 || n==0) return 0; if(ans[w][n]!=-1) return ans[w][n]; if(wt[n-1]>w){ return ans[w][n]=myfunc(w,wt,val,n-1,ans); } return ans[w][n] = Math.max(val[n-1] + myfunc(w-wt[n-1],wt,val,n-1,ans), myfunc(w,wt,val,n-1,ans)); } static int knapSack(int W, int wt[], int val[], int n) { // your code here int[][] ans = new int[W+1][n+1]; // below is the memoization version (iterative approach) of the problem for(int i=1;ii){ ans[i][j] = ans[i][j-1]; }else{ ans[i][j] = Math.max(val[j-1]+ans[i-wt[j-1]][j-1],ans[i][j-1]); } } } // return myfunc(W, wt, val, n, ans); // call for using recursion + dp approach return ans[W][n]; } } ================================================ FILE: GFG/2D Hopscotch/2D Hopscotch.java ================================================ class Solution{ static int hopscotch(int n, int m, int mat[][], int ty, int i, int j) { // code here int ans=0; if(ty==0) { if(isValid(i+1,j,n,m)) ans+=mat[i+1][j]; //down if(isValid(i-1,j,n,m)) ans+=mat[i-1][j]; //up if(isValid(i,j+1,n,m)) ans+=mat[i][j+1]; //right if(isValid(i,j-1,n,m)) ans+=mat[i][j-1]; //left if(j%2==0) { if(isValid(i-1,j+1,n,m)) ans+=mat[i-1][j+1]; // right-up if(isValid(i-1,j-1,n,m)) ans+=mat[i-1][j-1]; // left-up } else { if(isValid(i+1,j+1,n,m)) ans+=mat[i+1][j+1]; // right-down if(isValid(i+1,j-1,n,m)) ans+=mat[i+1][j-1]; // left-down } } else { if(isValid(i+2,j,n,m)) ans+=mat[i+2][j]; // down if(isValid(i-2,j,n,m)) ans+=mat[i-2][j]; // up if(isValid(i,j+2,n,m)) ans+=mat[i][j+2]; // front if(isValid(i,j-2,n,m)) ans+=mat[i][j-2]; // back if(j%2==0) { if(isValid(i+1,j+1,n,m)) ans+=mat[i+1][j+1]; // right-down if(isValid(i-2,j+1,n,m)) ans+=mat[i-2][j+1]; // right-up if(isValid(i+1,j-1,n,m)) ans+=mat[i+1][j-1]; // left-down if(isValid(i-2,j-1,n,m)) ans+=mat[i-2][j-1]; // left-up if(isValid(i+1,j+2,n,m)) ans+=mat[i+1][j+2]; // right-down-right-down if(isValid(i+1,j-2,n,m)) ans+=mat[i+1][j-2]; // left-down-left-down if(isValid(i-1,j+2,n,m)) ans+=mat[i-1][j+2]; // right-up-right-up if(isValid(i-1,j-2,n,m)) ans+=mat[i-1][j-2]; // left-up-left-up } else { if(isValid(i-1,j+1,n,m)) ans+=mat[i-1][j+1]; // right-up if(isValid(i+2,j+1,n,m)) ans+=mat[i+2][j+1]; // right-down if(isValid(i-1,j-1,n,m)) ans+=mat[i-1][j-1]; // left-up if(isValid(i+2,j-1,n,m)) ans+=mat[i+2][j-1]; // left-down if(isValid(i-1,j+2,n,m)) ans+=mat[i-1][j+2]; // right-up-right-up if(isValid(i-1,j-2,n,m)) ans+=mat[i-1][j-2]; // left-up-left-up if(isValid(i+1,j+2,n,m)) ans+=mat[i+1][j+2]; // right-down-right-down if(isValid(i+1,j-2,n,m)) ans+=mat[i+1][j-2]; // left-down-left-down } } return ans; } static boolean isValid(int i,int j,int n,int m){ return i>=0 && j>=0 && i threeDivisors(ArrayList query, int qn){ // code here int n=0; for(Long q:query){ n=Math.max(n,(int)Math.sqrt(q)); } boolean[] prime=new boolean[n+1]; Arrays.fill(prime,true); for(int i=2;i<=n;i++){ if(prime[i]){ for(int j=i+i;j<=n;j+=i){ prime[j]=false; } } } int[]dp=new int[n+1]; for(int i=2;i<=n;i++){ dp[i]=dp[i-1]; if(prime[i]){ dp[i]++; } } ArrayList ans=new ArrayList<>(); for(Long q:query){ int root=(int)Math.sqrt(q); ans.add(dp[root]); } return ans; } } ================================================ FILE: GFG/A Game of LCM/A Game of LCM.java ================================================ class Solution { long maxGcd(int N) { // code here return Math.max(solve(N),solve(N-1)); } long solve(int n){ long ans=n; int added=0; for(int i=n-1;i>=1;i--){ if(gcd(ans,i)==1L){ ans*=i; added++; } if(added==3)return ans; } return ans; } long gcd(long a,long b){ if(a==0)return b; return gcd(b%a,a); } } ================================================ FILE: GFG/A difference of values and indexes/A difference of values and indexes.java ================================================ class Solution{ // Function for finding maximum and value pair public static int maxDistance (int arr[], int n) { //Complete the function int max=Integer.MIN_VALUE; int min=Integer.MAX_VALUE; int max2=Integer.MIN_VALUE; int min2=Integer.MAX_VALUE; for(int i=0;i=0 || j>=0){ int a= i>=0?A.charAt(i)-'0':0; int b= j>=0?B.charAt(j)-'0':0; int total=a+b+carry; if(total==0){ carry=0; sb.append('0'); }else if(total==1){ carry=0; sb.append('1'); }else if(total==2){ carry=1; sb.append('0'); }else{ carry=1; sb.append('1'); } i--; j--; } if(carry==1)sb.append('1'); while(sb.charAt(sb.length()-1)=='0')sb.setLength(sb.length()-1); return sb.reverse().toString(); } } ================================================ FILE: GFG/Aggressive Cows/Aggressive Cows.java ================================================ class Solution { public static int solve(int n, int k, int[] stalls) { Arrays.sort(stalls); int l=1; int h=stalls[n-1]-stalls[0]; while(l<=h){//log (10^9)== 9*log(10) = 30 int mid=(l+h)/2; if(isPossible(k,stalls,mid)){ l=mid+1; }else{ h=mid-1; } } return h;// (n) } static boolean isPossible(int k,int[]arr,int minDis){ int cnt=1; int prevCow=arr[0]; for(int i=1;i=minDis){ prevCow=arr[i]; cnt++; } } return cnt>=k; } } ================================================ FILE: GFG/Akku and Binary Numbers/Akku and Binary Numbers.java ================================================ class Solution{ void precompute(){ // Code Here } long solve(long L, long R){ // Code here long ans=0; for(int i=0;i<63;i++){ for(int j=i+1;j<63;j++){ for(int k=j+1;k<63;k++){ long curr=0; curr|=(1L<=L && curr<=R){ ans++; } } } } return ans; } } ================================================ FILE: GFG/Alex Travelling/Alex Travelling.cpp ================================================ class Solution { public: int minimumCost(vector>& flights, int n, int k) { // code here unordered_map> > adj; for(int i = 0; i < flights.size(); i++) { int u = flights[i][0]; int v = flights[i][1]; int w = flights[i][2]; adj[u].push_back({v,w}); } vector dist(n+1, INT_MAX); set> s; //distNode, node dist[k] = 0; s.insert({0, k}); while(!s.empty()) { auto top = *(s.begin()); s.erase(s.begin()); int distNode = top.first; int node = top.second; for(auto neigh : adj[node]) { if(distNode + neigh.second < dist[neigh.first]) { dist[neigh.first] = distNode + neigh.second; s.insert({dist[neigh.first], neigh.first}); } } } int ans = 0; for(int i = 1; i <= n; i++) { if(dist[i] == INT_MAX) return -1; ans = max(ans, dist[i]); // cout<> map=new HashMap<>(); for(int[]i:flights){ int u=i[0]; int v=i[1]; int w=i[2]; map.putIfAbsent(u,new ArrayList<>()); map.get(u).add(new Pair(v,w)); } int[]dis=new int[n+1]; int ans=0; Queue q=new LinkedList<>(); q.add(new Pair(k,dis[k])); while(!q.isEmpty()){ Pair curr=q.remove(); int node=curr.node; int cost=curr.weight; if(!map.containsKey(node))continue; for(Pair p:map.get(node)){ int neb=p.node; int nebCost=p.weight; if((dis[neb]==0 || dis[neb]>cost+nebCost) && neb!=k){ dis[neb]=cost+nebCost; q.add(new Pair(neb,dis[neb])); } } } for(int i=1;i1)return "-1"; boolean isVowel=false; if(noOfVowels>noOfCons){ isVowel=true; }else if(noOfCons>noOfVowels){ isVowel=false; }else{ if(smallestVowel S.charAt(i)) { firstVowel = S.charAt(i); } } else { if(firstConsonant > S.charAt(i)) { firstConsonant = S.charAt(i); } } } int j=firstConsonant -'a'; int i=firstVowel -'a'; StringBuilder sb = new StringBuilder(); if(S.length()%2==0) { if(vowels!=consonants) return "-1"; if(firstVowel < firstConsonant) { sb.append(firstVowel); f[firstVowel - 'a']-=1; } return getRes(f, i, j, sb); } else { if(Math.abs(vowels-consonants) > 1) { return "-1"; } if(vowels-consonants==1) { sb.append(firstVowel); f[firstVowel - 'a']-=1; } return getRes(f, i, j, sb); } } public String getRes(int []f, int i, int j, StringBuilder sb) { while(j<26) { if(f[j]==0) { j+=1; continue; } else { if(j==0 || j==4 || j==8 || j==14 || j==20) { j+=1; continue; } else { sb.append((char)('a'+j)); f[j]-=1; } } if(f[i]==0) { i=getNextVowel(f); } if(i!=-1) { sb.append((char)('a'+i)); f[i]-=1; } else { break; } } return sb.toString(); } public int getNextVowel(int f[]) { if(f[0]!=0) return 0; if(f[4]!=0) return 4; if(f[8]!=0) return 8; if(f[14]!=0) return 14; if(f[20]!=0) return 20; return -1; } public int countVowels(String s, boolean isVowel) { int count = 0; for(int i=0;i& arr, int k){ sort(arr.begin(), arr.end()); int l = 0, r = 0, len = 0; while(r articulationPoints(int V,ArrayList> adj) { // Code here time=0; ArrayList ans=new ArrayList<>(); boolean[]ap=new boolean[V]; int[]parent=new int[V]; boolean[]vis=new boolean[V]; int[]minDis=new int[V]; int[]dis=new int[V]; Arrays.fill(parent,-1); for(int i=0;i> adj,int[]parent,boolean[]vis, int[]minDis,int[]dis){ vis[u]=true; int children=0; dis[u]=minDis[u]=time; time++; for(int v:adj.get(u)){ if(!vis[v]){ children++; parent[v]=u; dfs(v,ap,adj,parent,vis,minDis,dis); minDis[u]=Math.min(minDis[u],minDis[v]); if(parent[u]==-1 && children>1){ ap[u]=true; }else if(parent[u]!=-1 && minDis[v]>=dis[u]){ ap[u]=true; } }else{ minDis[u]=Math.min(minDis[u],dis[v]); } } } } ================================================ FILE: GFG/Asteroid Collision/Asteroid Collision.cpp ================================================ class Solution { public: vector asteroidCollision(int N, vector &asteroids) { stack s; int i = 0; while(i < N){ if(s.empty()){ s.push(asteroids[i]); ++i; } else{ if((asteroids[i] > 0 && s.top() > 0) || (asteroids[i] < 0 && s.top() < 0) || (asteroids[i] > 0 && s.top() < 0)){ s.push(asteroids[i]); ++i; } else if(asteroids[i] < 0 && s.top() > 0){ int a = s.top(); s.pop(); if(a == abs(asteroids[i])) ++i; else if(a > abs(asteroids[i])){ s.push(a); ++i; } else if(a < abs(asteroids[i])){ continue; } } } } vector ans; while(!s.empty()){ int a = s.top(); s.pop(); ans.push_back(a); } reverse(ans.begin(), ans.end()); return ans; } }; ================================================ FILE: GFG/Asteroid Collision/Asteroid Collision.java ================================================ class Solution { public static int[] asteroidCollision(int N, int[] arr) { // code here Stack st=new Stack<>(); for(int num:arr){ if(num<0){ while(!st.isEmpty() && st.peek()>0 && st.peek()0)ans[i--]=st.pop(); return ans; } } ================================================ FILE: GFG/Balanced string/Balanced string.java ================================================ class Solution { static String BalancedString(int N) { // code here StringBuilder ans=new StringBuilder(); String full="abcdefghijklmnopqrstuvwxyz"; int n=N; while(N>26){ ans.append(full); N-=26; } if(N%2==0){//even for(int i=0;i0){ sum+=(n%10); n/=10; } if(sum%2==0){//even for(int i=0;i<(N+1)/2;i++)ans.append((char)('a'+i)); for(int i=26-N/2;i<26;i++)ans.append((char)('a'+i)); }else{//odd for(int i=0;im) start=mid+1; else return "Yes"; } return "No"; } public int calculateDigits(int n, int m) { int dig=0; while(n>0) { dig+=1; n=n/m; } return dig; } } ================================================ FILE: GFG/Base Equivalence/Base Equivalence.java ================================================ //User function Template for Java class Solution { String baseEquiv(int n, int m) { // code here int i=2; while(i<=32){ int digit=(int)(Math.log(n)/Math.log(i))+1; if(digit==m)return "Yes"; i++; } return "No"; } } ================================================ FILE: GFG/Binary Tree to DLL/Binary Tree to DLL.cpp ================================================ /* This code is contributed by - Aman Bhatt (https://github.com/bhattaman0001) Anish Mandal (https://github.com/AnishMandal939) */ // there are 2 approaches another one is below Node * bToDLL(Node *root) { // your code here // TC: O(1) using morris inorder traversal Node* curr = root, *head = NULL; while(curr != NULL){ if(curr->left != NULL){ Node* traversal = curr->left; while(traversal->right != NULL && traversal->right != curr) traversal = traversal->right; if(traversal->right == NULL){ traversal->right = curr; Node *tmp = curr->left; curr->left = traversal; curr=tmp; continue; } } if(head == NULL) head = curr; //cout<right->data<right; if(traversal != NULL && traversal->left != curr){ while(traversal->left != NULL) traversal = traversal->left; Node* tmp = curr->right; traversal->left = curr; curr->right = traversal; curr = tmp; } else curr = curr->right; } return head; } // 2. another approach // it is not complex just added comments that's why it is looking big struct Node { int data; struct Node* left; struct Node* right; Node(int x){ data = x; left = right = NULL; } }; // This function should return head to the DLL class Solution { public: Node *p = NULL, *h = NULL; void inorder(Node* root){ if(!root) return; inorder(root->left); root->left = p; p = root; inorder(root->right); } //Function to convert binary tree to doubly linked list and return it. Node * bToDLL(Node *root) { // your code here inorder(root); // making one traversal from left to right of doubly linkedList // making another traversal from right to left of DLL // if you are heading from right to left then for DLL your next is right and prev is left // if you are heading from left to right then for DLL your next is left and prev is right Node* t = p, *p1 = NULL; t->right = p1; while(t->left != NULL){ p1 = t; t = t->left; t->right = p1; } h = t; return h; } }; ================================================ FILE: GFG/Binary Tree to DLL/Binary Tree to DLL.java ================================================ class Solution { //Function to convert binary tree to doubly linked list and return it. Node bToDLL(Node root) { // Your code here Node[] arr=dfs(root); return arr[0]; } Node[] dfs(Node root){ if(root.left==null && root.right==null){ return new Node[]{root,root}; } if(root.left==null){ Node[] righty=dfs(root.right); root.right=righty[0];// 10 -> 36 righty[0].left=root;// 10 <- 36 return new Node[]{root,righty[1]};//10,15 } Node[] lefty=dfs(root.left); lefty[1].right=root;//30 -> 10 root.left=lefty[1];// 30 <-10 if(root.right==null){ return new Node[]{lefty[0],root};//25,10 } Node[] righty=dfs(root.right); root.right=righty[0];// 10 -> 36 righty[0].left=root;// 10 <- 36 return new Node[]{lefty[0],righty[1]};//25,15 } } Approach 2: Solution Explain: 1. make an arraylist 2. put all the elements of the tree in inorder fashion 3. now traverse that arraylist and construct left as prev and right as arraylist next element 4. Time complexity= o(N)(inorder and traversal of arraylist) and space = O(N) bez of arraylist class Solution { Node bToDLL(Node root) { if(root==null || root.left==null && root.right==null){ return root; } //make ArrayList ArrayList al=new ArrayList<>(); //put all the element's in inorder to al inorder(root,al); Node dummy=al.get(0); //take two nodes prev and curr for doubly linked list Node prev=null; Node curr=null; //counter for traversing arraylist int i=0; //create doubly linked list while(i al){ if(root==null) return; inorder(root.left,al); al.add(root); inorder(root.right,al); } } Contributed by @Jay-Thesia ================================================ FILE: GFG/Black and White/Black and White.java ================================================ class BlackAndWhite { //Function to find out the number of ways we can place a black and a //white Knight on this chessboard such that they cannot attack each other. static long numOfWays(int N, int M) { // add your code here long ans=0L; long mod=1000000007; int[][]dirs=new int[][]{{1,2},{-1,2},{1,-2},{-1,-2},{2,1},{-2,1},{2,-1},{-2,-1}}; for(int i=0;i=0 && j>=0 && i st=new Stack<>(); for(char c:str.toCharArray()){ while(!st.isEmpty() && st.peek()>c && k>0){ st.pop(); k--; } st.push(c); } while(!st.isEmpty() && k>0){ st.pop(); k--; } StringBuilder sb=new StringBuilder(); while(!st.isEmpty()){ sb.append(st.pop()); } while(sb.length()>0 && sb.charAt(sb.length()-1)=='0'){ sb.setLength(sb.length()-1); } if(sb.length()==0)return "0"; return sb.reverse().toString(); } } ================================================ FILE: GFG/Burst Balloons/Burst Balloons.java ================================================ class Solution { static Integer[][]dp; public static int maxCoins(int N, int[] arr) { // code here dp=new Integer[N+3][N+3]; int[]newArr=new int[N+2]; newArr[0]=1; newArr[N+1]=1; for(int i=0;i=maxValue) return false; return isBST(root.left,minValue,root.data)&&isBST(root.right,root.data,maxValue); } boolean isBST(Node root) { // code here. return isBST(root,Integer.MIN_VALUE,Integer.MAX_VALUE); } } ================================================ FILE: GFG/Check if all levels of two trees are anagrams or not/Check if all levels of two trees are anagrams or not.java ================================================ class Solution { public static boolean areAnagrams(Node node1, Node node2) { // code here Queue q1=new LinkedList<>(); Queue q2=new LinkedList<>(); q1.add(node1); q2.add(node2); while(!q1.isEmpty() && !q1.isEmpty()){ int sz1=q1.size(); int sz2=q2.size(); if(sz1!=sz2)return false; Map map=new HashMap<>(); for(int i=0;ii)return 0; else{ i++; j++; } }else{ return 0; } }else{ if(T.charAt(j)=='B'){ if(j6){ total-=dp[i-6]; } dp[i]=total*2; total+=(total*2); } return total; } } ================================================ FILE: GFG/Complement/Complement.java ================================================ //GFG dsa self-paced Coupon code: SAGARGFGPOTD class Solve { Vector findRange(String str, int n) { // code here int count=0; int l=-1; int max=0; int ansL=-1; int ansR=-1; for(int i=0;imax){ max=count; ansL=l; ansR=i; } } Vector ans=new Vector<>(); if(ansL==-1){ ans.add(-1); }else{ ans.add(ansL+1); ans.add(ansR+1); } return ans; } } ================================================ FILE: GFG/Construct Binary Tree from String with bracket representation/Construct Binary Tree from String with bracket representation.cpp ================================================ class Solution{ int ind = 0; Node* solve(string str) { if(str.length() == 0 || ind >= str.length()) return NULL; //calculate num int num = 0; while(ind < str.length() && str[ind] != '(' && str[ind] != ')') { int val = (int)(str[ind]-'0'); num = num*10 + val; ind++; } //create new root Node* root = NULL; if(num > 0) root = new Node(num); //for left child if(ind < str.length() && str[ind] == '(') { ind++; root->left = solve(str); } if(ind < str.length() && str[ind] == ')') { ind++; return root; } //for right child if(ind < str.length() && str[ind] == '(') { ind++; root->right = solve(str); } if(ind < str.length() && str[ind] == ')') { ind++; } return root; } public: // function to construct tree from string Node *treeFromString(string str){ if(str.length() == 0) return NULL; return solve(str); } }; ================================================ FILE: GFG/Construct Binary Tree from String with bracket representation/Construct Binary Tree from String with bracket representation.java ================================================ class Solution { public static Node treeFromString(String s) { // code here int[] idx=new int[]{0}; return dfs(idx,s); } static Node dfs(int[] idx,String s){ if(idx[0]>=s.length() || s.charAt(idx[0])==')'){ idx[0]++; return null; } int num=0; while(idx[0]>j))>0){ dp[i][bitmask]+=dp[j][bitmask ^ (1< using namespace std; class Solution { public: int mod = 1e9+7; long long int mem(int i, int j, int m, int n, vector> &dp){ if(i== m-1 and j == n-1) return 1; if(i >=m or j >=n) return 0; if(dp[i][j]!=-1) return dp[i][j]; return dp[i][j] = (mem(i+1,j,m,n, dp)+ mem(i,j+1,m,n,dp))%mod; }; long long int numberOfPaths(int m, int n){ // code here vector> dp(m, vector(n,-1)); return mem(0,0,m,n,dp)%mod; } }; int main() { int t; cin >> t; while (t--) { int n, m; cin >> m >> n; Solution ob; cout< > dp(m+1,vector (n+1,1)); for(int i=1; ik){ ans++; int left=i-(recent+1); int right=n-1-i; ans+=left; ans+=right; ans+=(left*right); recent=i; } } return ans; } } // Method 2 class Solution { long countSubarray(int arr[], int n, int k) { // code here int dy[]=new int[n]; int zero=-1; for(int i=0;ik) dy[i]=n-i; else { dy[i]=zero; zero-=1; } } long ans=0; long curZero=0; long zeros=0; for(int i=0;i0) { curZero=zeros; ans+=dy[i]+curZero; } else { ans+=curZero; zeros=Math.abs(dy[i]); } } return ans; } } ================================================ FILE: GFG/Count of Subarrays/README.md ================================================ # Count of Subarrays Given an array of N positive integers Arr1, Arr2 ............ Arrn. The value of each contiguous subarray of given array is the maximum element present in that subarray. The task is to return the number of subarrays having value strictly greater than K. **Example 1:** ``` Input: N = 3, K = 2 Arr[] = {3, 2, 1} Output: 3 Explanation: The subarrays having value strictly greater than K are: [3], [3, 2] and [3, 2, 1]. Thus there are 3 such subarrays. ``` **Example 2:** ``` Input: N = 4, K = 1 Arr[] = {1, 2, 3, 4} Output: 9 Explanation: There are 9 subarrays having value strictly greater than K. ``` *** **Your Task:** Complete the function **countSubarray()** which takes an array arr, two integers n, k, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs. *Expected Time Complexity:* O(N) *Expected Auxiliary Space:* O(1) Constraints: 1 <= N <= 105 1 <= Arr[i] <= 105 ================================================ FILE: GFG/Count the Substring/Count the Substring.cpp ================================================ class Solution{ public: long long countSubstring(string s){ // start writing from here long long ans=0; unordered_map help; // start unodering vector dp(s.size(),0); // define the vector size long long sum=-1; if(s[0]=='1'){ dp[0]=1; ans=1; sum=1; } help[sum]=0; help[0]=-1; for(int i=1;i= zeroes int cnt=n; int minus=0; for(int i=0;i countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n) { //Your code goes here vector ans; sort(arr2, arr2+n); for(int i=0; i countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n) { // add your code here Arrays.sort(arr2);//O(nlogn) ArrayList ans=new ArrayList<>(); for(int i=0;i> B) { ArrayList[] graph=new ArrayList[vtces]; int edge=B.size(); for(int i=0;i(); } //make 0 base vertex for(int i=0;i [] graph,int src,boolean[] visited){ visited[src]=true; for(Edge e:graph[src]){ if(visited[e.nbr]==false){ isCycle(graph,e.nbr,visited); }else{ return true; } } visited[src]=false; return false; } } class Edge{ int src; int nbr; Edge(int src,int nbr){ this.src=src; this.nbr=nbr; } } ================================================ FILE: GFG/Cycle in Undirected Graph/Cycle in Undirected Graph.java ================================================ public class Solution { public int solve(int A, ArrayList> B) { ArrayList> adj = new ArrayList<>(); boolean vis[] = new boolean[A+1]; for(int i=0;i<=A;i++){ adj.add(new ArrayList()); } for(ArrayList edge:B){ adj.get(edge.get(0)).add(edge.get(1)); adj.get(edge.get(1)).add(edge.get(0)); } for(int i=1;i<=A;i++){ if(vis[i]==false){ if(dfs(adj,vis,i,-1))return 1; } } return 0; } public boolean dfs(ArrayList> adj, boolean vis[],int node,int parent){ vis[node] = true; for(int it:adj.get(node)){ if(!vis[it]){ if(dfs(adj,vis,it,node))return true; }else{ if(it!=parent)return true; } } return false; } } ================================================ FILE: GFG/Decode the string/Decode the string.cpp ================================================ class Solution{ public: string decodedString(string s){ string res=""; stack st; st.push(s[0]); for(int i=1;i='0'&&st.top()<='9'){ rnum=st.top()+rnum; st.pop(); } string sr=res; for(int j=0;j nums=new Stack<>(); Stack st=new Stack<>(); int i=0; while(i='0' && s.charAt(i)<='9'){ int n=0; while(s.charAt(i)>='0' && s.charAt(i)<='9'){ n=n*10+(s.charAt(i)-'0'); i++; } nums.push(n); }else{ if(s.charAt(i)==']'){ int n=nums.pop(); StringBuilder inner=new StringBuilder(); while(!st.peek().equals("[")){ inner.append(st.pop()); } st.pop(); StringBuilder newStr=new StringBuilder(); while(n>0){ newStr.append(inner); n--; } st.push(newStr.toString()); }else{ st.push(""+s.charAt(i)); } i++; } } StringBuilder sb=new StringBuilder(); while(st.size()>0){ sb.append(st.pop()); } return sb.reverse().toString(); } } //Method 2 Using single stack class Solution{ static String decodedString(String s){ // code here Stack st=new Stack<>(); for(int i=0;i1 || (st.peek().length()==1 && st.peek().charAt(0)!='['))) { //popping all and adding to sb until we come across '[' sb.append(st.pop()); } st.pop(); while(!st.isEmpty() && (st.peek().length()==1 && st.peek().charAt(0)>='0' && st.peek().charAt(0)<='9')) { num.append(""+st.pop()); } int times=1; if(num.length()>0) times=Integer.valueOf(num.reverse().toString()); StringBuilder toAppend=new StringBuilder(); for(int j=0;j q=new LinkedList<>(); for(int i=0;i0){ int[]idx=q.remove(); int x=idx[0]; int y=idx[1]; ans[x][y]=dis; for(int[]dir:dirs){ int i=x+dir[0]; int j=y+dir[1]; if(i>=0 && j>=0 && i sortedStrings(int N, vector A) { // code here vectorans; mapmp; for(int i=0;i> &enemy) { if(k==0) return n*m; vector r(n+1,false), c(m+1, false); for(int i=0;i rows=new ArrayList<>(); rows.add(-1); for(int[]i:enemy){ rows.add(i[0]-1); } rows.add(n); Collections.sort(rows); int maxRow=0; for(int i=1;i cols=new ArrayList<>(); cols.add(-1); for(int[]i:enemy){ cols.add(i[1]-1); } cols.add(m); Collections.sort(cols); int maxCol=0; for(int i=1;icapacity) { long mod=1e9+7; sort(capacity.begin(),capacity.end()); long ans=1; for(int i=0;i dp(N+1); dp[0]=0; dp[1]=1; dp[2]=2; for(int i=3;i<=N;i++) dp[i]=(dp[i-1]+dp[i-2])%mod; return dp[N]; } }; ================================================ FILE: GFG/Filling Bucket/Filling Bucket.java ================================================ class Solution { static int fillingBucket(int N) { // code here if(N==1)return 1; int prev=2; int secPrev=1; int mod=100000000; for(int i=0;i using namespace std; class Solution { public: int safePos(int n, int k) { // code here if(n==1) return 1; int p = safePos(n-1, k); return (p+k-1)%n +1; } }; int main() { int t; cin >> t; while (t--) { int n,k; cin>>n>>k; Solution ob; cout << ob.safePos(n,k) << endl; } return 0; } ================================================ FILE: GFG/Find The Safe Position/Find the Safe Position.java ================================================ class Solution { static int safePos(int n, int k) { ArrayListaa=new ArrayList(); for(int i=0;i m; for(int i = 0; i < N; i++) m[start[i]]++; for(int i = 0; i < N; i++) m[end[i]]--; int cnt = 0; int sum = 0; for(auto i : m) { sum += i.second; cnt = max(cnt , sum); } return cnt; } }; ================================================ FILE: GFG/Find minimum number of Laptops required/Find minimum number of Laptops required.java ================================================ //1. sort according to our starting time //2. use priorityq to check minimum end time of previous laptop to be free //3. compare that with start time of our new job class Solution { public int minLaptops(int n, int[] start, int[] end) { // code here int[][] arr=new int[n][2]; for(int i=0;i{ if(a[0]!=b[0])return a[0]-b[0]; return a[1]-b[1]; }); int ans=1; PriorityQueue pq=new PriorityQueue<>(); pq.add(arr[0][1]); int i=1; while(i>= 1; } return S[N] ^ flip; } }; ================================================ FILE: GFG/Find the first node of loop in linked list/Find the first node of loop in linked list.java ================================================ class Solution { //Function to find first node if the linked list has a loop. public static int findFirstNode(Node head){ //code here Node slow=head; Node fast=head; while(fast!=null && fast.next!=null){ slow=slow.next; fast=fast.next.next; if(slow==fast)break; } if(fast==null || fast.next==null)return -1; Node temp=head; while(temp!=slow){ temp=temp.next; slow=slow.next; } return slow.data; } } ================================================ FILE: GFG/Find the longest string/Find the longest string.java ================================================ class TrieNode{ boolean isEnd; TrieNode[] arr; TrieNode(){ isEnd=false; arr = new TrieNode[26]; } } class Solution { static TrieNode root; public static String longestString(int n, String[] arr) { // code here root=new TrieNode(); for(String s:arr){ insert(s); } String ans=""; for(String s:arr){ if(s.length()ans.length()){ ans=s; }else if(s.length()==ans.length()){ if(s.compareTo(ans)<0){ ans=s; } } } } } return ans; } static boolean isPresent(String s){ TrieNode curr=root; for(char c:s.toCharArray()){ int index=c-'a'; curr=curr.arr[index]; if(curr.isEnd==false)return false; } return true; } static void insert(String s){ TrieNode curr=root; for(char c:s.toCharArray()){ int index=c-'a'; if(curr.arr[index]==null){ curr.arr[index]=new TrieNode(); } curr=curr.arr[index]; } curr.isEnd=true; } } ================================================ FILE: GFG/Find the maximum GCD of the siblings of a Binary Tree/Find the maximum GCD of the siblings of a Binary Tree.java ================================================ class Solution { int max_gcd; int ans; int maxGCD(Node root) { // code here ans=0; max_gcd=0; dfs(root); return ans; } int dfs(Node root){ if(root==null)return 0; int left=dfs(root.left); int right=dfs(root.right); if(left!=0 && right!=0){ int gcd=gcd(left,right); if(gcd>max_gcd){ max_gcd=gcd; ans=root.data; }else if(gcd==max_gcd && root.data>ans){ ans=root.data; } } return root.data; } int gcd(int a,int b){ if(a==0)return b; return gcd(b%a,a); } } ================================================ FILE: GFG/Fitting The Array/Fitting The Array s28.cpp ================================================ #include using namespace std; class Solution{ public: bool isFit(int arr[], int brr[], int n){ // code here sort(arr, arr+n); sort(brr, brr+n); for(int i=0; i>t; for(z=0;z>n; int arr[n+1], brr[n+1]; for(i=0;i>arr[i]; for(i=0;i>brr[i]; Solution ob; if(ob.isFit(arr, brr, n)) cout<<"YES\n"; else cout << "NO\n"; } return 0; } ================================================ FILE: GFG/Fitting The Array/Fitting The Array.cpp ================================================ class Solution{ public: bool isFit(int arr[], int brr[], int n){ // code here sort(arr, arr+n); sort(brr, brr+n); for(int i=0; i brr[i]) return false; return true; } }; ================================================ FILE: GFG/Fitting The Array/Fitting The Array.java ================================================ class Solution{ // Function for finding maximum and value pair public static boolean isFit (int arr[], int brr[], int n) { //Complete the function Arrays.sort(arr); Arrays.sort(brr); for(int i=0;ibrr[i]){ return false; } } return true; } } ================================================ FILE: GFG/Flatten binary tree to linked list/Flatten binary tree to linked list.java ================================================ class Solution { static Node curr; public static void flatten(Node root) { //code here curr=new Node(-1); dfs(root); } static void dfs(Node root){ if(root==null)return; Node leftSubtree=root.left; root.left=null; Node rightSubtree=root.right; root.right=null; curr.right=root; curr=curr.right; dfs(leftSubtree); dfs(rightSubtree); } } ================================================ FILE: GFG/Flatten binary tree to linked list/Readme.md ================================================ Given the root of a binary tree, flatten the tree into a "linked list": The "linked list" should use the same Node 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 : 1 / \ 2 5 / \ \ 3 4 6 Output : 1 2 3 4 5 6 Explanation: After flattening, the tree looks like this 1 \ 2 \ 3 \ 4 \ 5 \ 6 Here, left of each node points to NULL and right contains the next node in preorder.The inorder traversal of this flattened tree is 1 2 3 4 5 6. Example 2: Input : 1 / \ 3 4 / 2 \ 5 Output : 1 3 4 2 5 Explanation : After flattening, the tree looks like this 1 \ 3 \ 4 \ 2 \ 5 Here, left of each node points to NULL and right contains the next node in preorder.The inorder traversal of this flattened tree is 1 3 4 2 5. Your task: You don't have to read input or print anything. Your task is to complete the function flatten() which takes the root of the tree and flattens the tree into a linkes list without using any auxiliary space. Note : The driver code prints the inorder traversal of the flattened binary tree. Expected Time Complexity: O(n) Expected Auxiliary Space: O(1) Constraints : 1<=n<=10^5 ================================================ FILE: GFG/Flattening a Linked List/Flattening a Linked List.java ================================================ class GfG { Node flatten(Node root) { // Your code here Node nexty=root.next; while(nexty!=null){ Node second=nexty; nexty=nexty.next; second.next=null; root=merge(root,second); } return root; } Node merge(Node l1,Node l2){ Node head=new Node(0); Node curr=head; while(l1!=null && l2!=null){ if(l1.data<=l2.data){ curr.bottom=l1; l1=l1.bottom; }else{ curr.bottom=l2; l2=l2.bottom; } curr=curr.bottom; } if(l1!=null)curr.bottom=l1; if(l2!=null)curr.bottom=l2; return head.bottom; } } ================================================ FILE: GFG/Floyd Warshall/Floyd Warshall.java ================================================ class Solution { public void shortest_distance(int[][] mat) { // Code here int n=mat.length; for(int k=0;k>&mat) int n = mat.size(); for(int i = 0;i1->2 and the cost will be 1+6=7 which is less than 43. ``` *** **Your Task:** You don't need to read, return or print anything. Your task is to complete the function **shortest_distance()** which takes the matrix as input parameter and modifies the distances for every pair in-place. **Expected Time Complexity:** O(n3) **Expected Space Complexity:** O(1) **Constraints:** 1 <= n <= 100 -1 <= matrix[ i ][ j ] <= 1000 ================================================ FILE: GFG/Form a palindrome/Form a palindrome.py ================================================ #User function Template for python3 class Solution: def countMin(self, Str): arr = Str brr = arr[::-1] m = len(arr) n = len(brr) lcs = [[0]*(n+1) for _ in range(m+1)] for i in range(1,m+1): for j in range(1,n+1): if arr[i-1] == brr[j-1]: lcs[i][j] = 1 + lcs[i-1][j-1] else: lcs[i][j] = max(lcs[i-1][j], lcs[i][j-1]) return n - lcs[m][n] #{ # Driver Code Starts #Initial Template for Python 3 if __name__ == '__main__': t = int(input()) for _ in range(t): Str = input() solObj = Solution() print(solObj.countMin(Str)) # } Driver Code Ends ================================================ FILE: GFG/GCD Array/GCD Array.java ================================================ class Solution { public static int solve(int N, int K, int[] arr) { // code here for(int i=1;i factor = new ArrayList<>(); for(int i=1;i*i<=arr[N-1];i++) { if(arr[N-1]%i==0) { factor.add(i); factor.add(arr[N-1]/i); } } int ans=1; for(int fact : factor) { int count=0; for(int a : arr) { if(a%fact==0) { count++; } } if(count>=K) ans=Math.max(ans,fact); } return ans; } } ================================================ FILE: GFG/Geek and Number String/Geek and Number Str.cpp ================================================ int minLength(string s, int n) { string temp="12 21 34 43 56 65 78 87 09 90"; stackst; st.push(s[0]); for(int i=1;i0){ string str; str+=st.top(); str+=s[i]; if(temp.find(str)!=string::npos){ st.pop(); }else{ st.push(s[i]); } }else st.push(s[i]); } return st.size(); } ================================================ FILE: GFG/Geek and Strings/Geek and Strings.java ================================================ class Solution{ static class Trie { Trie child[]=new Trie[26]; int count[]=new int[26]; } static List prefixCount(int N, int Q, String li[], String query[]) { // code here List res=new ArrayList<>(); Trie head=null; head=new Trie(); Trie cur=head; for(int i=0;i=n || y<0 || y>=m || visited[x][y]==true || mat[x][y]=='#') return false; else return true; } public static int numberOfCells(int n, int m, int r, int c, int u, int d, char mat[][]) { Queue queue = new ArrayDeque<>(); boolean visited[][] = new boolean[n][m]; queue.offer(new Pair(r, c, u, d)); visited[r][c] = true; if(mat[r][c]=='#') return 0; int total_count = 1; while(!queue.isEmpty()) { Pair p = queue.poll(); if(isValid(p.x, p.y+1, visited, mat, n, m)) { total_count++; visited[p.x][p.y+1] = true; queue.offer(new Pair(p.x, p.y+1, p.u_left, p.d_left)); } if(isValid(p.x, p.y-1, visited, mat, n, m)) { total_count++; visited[p.x][p.y-1] = true; queue.offer(new Pair(p.x, p.y-1, p.u_left, p.d_left)); } if(p.d_left>0 && isValid(p.x+1, p.y, visited, mat, n, m)) { total_count++; visited[p.x+1][p.y] = true; queue.offer(new Pair(p.x+1, p.y, p.u_left, p.d_left-1)); } if(p.u_left>0 && isValid(p.x-1, p.y, visited, mat, n, m)) { total_count++; visited[p.x-1][p.y] = true; queue.offer(new Pair(p.x-1, p.y, p.u_left-1, p.d_left)); } } return total_count; } } // { Driver Code Starts. public class GFG { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int r = sc.nextInt(); int c = sc.nextInt(); int u = sc.nextInt(); int d = sc.nextInt(); char mat[][] = new char[n][m]; for(int i = 0; i < n; i++) { String s = sc.next(); for(int j = 0; j < m; j++) { mat[i][j] = s.charAt(j); } } Solution obj = new Solution(); System.out.println(obj.numberOfCells(n, m, r, c, u, d, mat)); } } } // } Driver Code Ends ================================================ FILE: GFG/Geek in a Maze/README.md ================================================ # Geek in a Maze ## Hard

Geek is in a maze of size N * M. Each cell in the maze is made of either '.' or '#'. An empty cell is represented by '.' and an obstacle is represented by '#'. If Geek starts at cell (R, C), find how many different empty cells he can pass through while avoiding the obstacles. He can move in any of the four directions but he can move up at most U times and he can move down atmost D times.

 

Example 1:

Input: 
N = 3, M = 3
R = 1, C = 0
U = 1, D = 1
mat = {{'.', '.', '.'},
       {'.', '#', '.'},
       {'#', '.', '.'}}
Output: 5
Explanation: Geek can reach 
(1, 0), (0, 0), (0, 1), (0, 2), (1, 2) 


Example 2:

Input: 
N = 3, M = 4
R = 1, C = 0
U = 1, D = 2 
mat = {{'.', '.', '.'}, 
       {'.', '#', '.'}, 
       {'.', '.', '.'},
       {'#', '.', '.'}} 
Output: 10
Explanation: Geek can reach all the 
cells except for the obstacles.

 

Your Task:  
You don't need to read input or print anything. Complete the function numberOfCells() which takes N, M, R, C, U, D and the two dimensional character array mat[][] as input parameters and returns the number of cells geek can visit( If he is standing on obstacle he can not move).


Constraints:
1 ≤ N*M ≤ 106
mat[i][j] = '#" or '.'
0 ≤ R ≤ N-1
0 ≤ C ≤ M-1

================================================ FILE: GFG/Grouping Of Numbers/Grouping Of Numbers.java ================================================ class Solution { static int maxGroupSize(int[] a, int N, int k) { // code here int[]dp=new int[k]; for(int i:a){ dp[i%k]++; } int maxSize=0; int i=1; int j=k-1; while(i0){ maxSize++; } if(i==j && dp[i]>0){ maxSize++; } return maxSize; } }; // Method 2: class Solution { static int maxGroupSize(int[] arr, int N, int K) { // code here int freq[]=new int[K]; for(int i=0;ifreq[end]) { freq[end]=0; } else { freq[start]=0; } } } else { if(freq[start]>0) freq[start]=1; } start+=1; end-=1; } if(freq[0]>0) freq[0]=1; int count=0; for(int i=0;i0) count+=freq[i]; } return count; } }; ================================================ FILE: GFG/Hamiltonian Path/Hamiltonian Path.cpp ================================================ } }; ================================================ FILE: GFG/Hamiltonian Path/Hamiltonian Path.java ================================================ class Solution { int n; boolean check(int N, int M, ArrayList> Edges) { // code here n=N; Map> map=new HashMap<>(); for(ArrayList edge:Edges){ int src=edge.get(0); int des=edge.get(1); map.putIfAbsent(src,new ArrayList<>()); map.putIfAbsent(des,new ArrayList<>()); map.get(src).add(des); map.get(des).add(src); } Set set=new HashSet<>(); for(int node=1;node<=N;node++){ if(dfs(node,set,map)){ return true; } } return false; } boolean dfs(int curr,Set set,Map> map){ set.add(curr); if(set.size()==n){ return true; } for(int neb:map.get(curr)){ if(!set.contains(neb) && dfs(neb,set,map)){ return true; } } set.remove(curr);//back.. return false; } } ================================================ FILE: GFG/Hamiltonian Path/README.md ================================================ ## Hamiltonian Path A Hamiltonian path, is a path in an undirected graph that visits each vertex exactly once. Given an undirected graph, the task is to check if a Hamiltonian path is present in it or not. **Example 1:** ``` Input: N = 4, M = 4 Edges[][]= { {1,2}, {2,3}, {3,4}, {2,4} } Output: 1 Explanation: There is a hamiltonian path: 1 -> 2 -> 3 -> 4 ``` **Example 2:** ``` Input: N = 4, M = 3 Edges[][] = { {1,2}, {2,3}, {2,4} } Output: 0 Explanation: It can be proved that there is no hamiltonian path in the given graph ``` *** **Your task:** You don't need to read input or print anything. Your task is to complete the function **check()** which takes the N (the number of vertices), M (Number of edges) and the list of Edges[][] (where Edges[i] denotes the undirected Edge between vertices Edge[i][0] and Edges[i][1] ) as input parameter and returns true (boolean value) if the graph contains Hamiltonian path,otherwise returns false. **Expected Time Complexity:** O(N!). **Expected Auxiliary Space:** O(N+M). **Constraints:** 1 ≤ N ≤ 10 1 ≤ M ≤ 15 Size of Edges[i] is 2 1 ≤ Edges[i][0],Edges[i][1] ≤ N ================================================ FILE: GFG/Help Ishaan/Help Ishaan.cpp ================================================ public: bool isPrime(int x){ if(x==1)return false; if(x==2||x==3) return true; if(x%2==0||x%3==0) return false; for(int i=5;i*i<=x;i+=6){ if(x%i==0||x%(i+2)==0) return false; } return true; } int NthTerm(int N){ // Code here if(isPrime(N)) return 0; int n1,n2; n1=N-1,n2=N+1; while(n1>1 && isPrime(n1)==0) n1--; while(isPrime(n2)==0) n2++; return (n1>1)?min(N-n1,n2-N):(n2-N); } }; ================================================ FILE: GFG/Help Ishaan/Help Ishaan.java ================================================ class Solution { public static boolean isPrime(int n){ if(n==1){ return false; } else if(n==2 || n==3){ return true; } else if(n%2==0 || n%3==0){ return false; } else{ for(int i=5;i<=Math.sqrt(n);i+=6){ if(n%(i)==0 || n%(i+2)==0){ return false; } } return true; } } public int NthTerm(int n) { if(isPrime(n)==true){ return 0; } else{ int diff=0; if(n-19<=0){ diff=0; } else{ diff=n-19; } int min=Integer.MAX_VALUE; for(int i=diff;i<(n+19);i++){ if(isPrime(i)){ min=Integer.min((int)Math.abs(i-n),min); } } return min; } } } // A different code for the same solution class Solution { public static boolean isPrime(int num){ if(num<2){ return false; } for(int i = 2; i<= Math.sqrt(num); i++){ if(num % i == 0){ return false; } } return true; } public int NthTerm(int n) { // code here int diff = 0; if(isPrime(n)){ return diff; } while(true){ if(isPrime(n+diff) || isPrime(n-diff)){ break; } diff++; } return diff; } } ================================================ FILE: GFG/Help Ishaan/README.md ================================================ ## Help Ishaan Ishaan has been given a task by his teacher. He needs to find the **Nth** term of a series. His teacher gives him some examples to help him out (Refer examples below). He is a bit weak in pattern searching so to help him his teacher told him that the **Nth term is related to prime numbers**. The Nth term is the **difference of N and the closest prime number to N.** Help him find the Nth term for a given N. **Example 1:** ``` Input: N = 10 Output: 1 Explanation: Closest prime to 10 is 11. ``` **Example 2:** ``` Input: N = 7 Output: 0 Explanation: Closest prime to 7 is 7. ``` **Your Task:** You don't need to read or print anything. Your task is to complete the function **NthTerm()** which takes **N** as input paramater and returns **Nth** term. **Expected Time Complexity:** O(N* √ N) **Expected Space Complexity:** O(1) **Constraints:** 1 <= N <= 100000 ================================================ FILE: GFG/Help a Thief/Help a thief.cpp ================================================ // { Driver Code Starts //Initial Template for C++ #include using namespace std; // } Driver Code Ends //User function Template for C++ class Solution { public: int maxCoins(int A[], int B[], int T, int N) { // code here vector> v; for (int i = 0; i < N; i++) { v.push_back({B[i], A[i]}); } sort(v.rbegin(), v.rend()); int k = 0; for (int i = 0; i < N; i++) { if (T == 0) { return k; } int p = min(v[i].second, T); k += p * v[i].first; T -= p; } return k; } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int T,N; cin>>T>>N; int A[N], B[N]; for(int i=0; i>A[i]; for(int i=0; i>B[i]; Solution ob; cout << ob.maxCoins(A,B,T,N) << endl; } return 0; } // } Driver Code Ends ================================================ FILE: GFG/Help a Thief/README.md ================================================ # Help a Thief!!! ## Easy

You have to help a thief to steal as many as GoldCoins as possible from a GoldMine. There he saw N Gold Boxes an each Gold Boxes consists of Ai Plates each plates consists of Bi Gold Coins. Your task is to print the maximum gold coins theif can steal if he can take a maximum of T plates.

 

Example 1:

Input:
T = 3, N = 3 
A[] = {1, 2, 3}
B[] = {3, 2, 1}
Output:
7
Explanation:
The thief will take 1 plate of coins
from the first box and 2 plate of coins
from the second plate. 3 + 2*2 = 7.

Example 2:

Input:
T = 0, N = 3 
A[] = {1, 3, 2}
B[] = {2, 3, 1}
Output:
0
Explanation:
The thief can't take any plates.
So he can't steal any coins.

 

Your Task:
You don't need to read input or print anything. Your task is to complete the function maxCoins() which takes 2 Integers T, and N and two arrays A and B of size N as input and returns the maximum number of gold coins the thief can steal if he can take a maximum of T plates.

 

Expected Time Complexity: O(N*logN)
Expected Auxiliary Space: O(N)

 

Constraints:
0 <= T,N <= 104
1 <= A[i] <= 104

1 <= B[i] <= 104

================================================ FILE: GFG/Help the Old Man/Help the old man.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[])throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); while(t-- > 0){ String a[] = in.readLine().trim().split("\\s+"); int N = Integer.parseInt(a[0]); int n = Integer.parseInt(a[1]); Solution ob = new Solution(); List ans = new ArrayList(); ans = ob.shiftPile(N, n); System.out.println(ans.get(0)+" "+ans.get(1)); } } }// } Driver Code Ends class Solution{ public static void hanoi(int N,int A,int B,int C,ArrayList> r){ if(N==0)return; hanoi(N-1,A,C,B,r); ArrayList z=new ArrayList(); z.add(A); z.add(B); r.add(z); hanoi(N-1,C,B,A,r); } static List shiftPile(int N, int n){ ArrayList> r=new ArrayList>(); hanoi(N,1,3,2,r); return r.get(n-1); } } ================================================ FILE: GFG/Help the Old Man/README.md ================================================ # Help the Old Man!!! ## Easy

A poor old man works in a palace for a living. One day the old man's wife met with an accident. She needed an immediate operation but the old man's savings were not enough for the operation. He went running to the king to beg for money. The king told that he will not only pay the full amount for the operation but also double his salary. But for that the old man had to pass a test. The king showed him a pile of glass plates kept one above another, each one being smaller than the one beneath. The plates were kept in box 1. He had to transfer the plates to box 3 using box 2. However, there were some constraints. The old man could only take one plate at a time and he could only place a smaller plate on top of a larger plate. He could take a plate only from the top. Help the old man do so. There are N plates and he has to tell the nth move in the format (i, j) where a plate is being moved from ith box to jth box.

Note:
Given any number of plates, they can be transferred from box 1 to box 3 using box 2 using the following steps.
Step 1: Transfer first N-1 plates from box 1 to box 2 using box 3.
Step 2: Transfer the remaining plate from box 1 to box 3.
Step 3: Transfer the first N-1 plates from box 2 to box 3 using box 1.

Example 1:

Input: N = 2, n = 2
Output: 1 3
Explaination:  The plate on top of box 1 is 
first transferred to box 2. The second plate 
from box 1 is transferred to box 3 and finally 
the plate from box 2 is transferred to box 3. 
In each situation, all the constraints are 
satisfied. You are required to print the 2nd 
move which is "Move plate from box 1 to box 3", 
hence 1 3.

Example 2:

Input: N = 3, n = 4.
Output: 1 3
Explaination: The movements of plates will 
be from 1 to 3. Then from 1 to 2. Then from 
3 to 2. And finally 4th move from 1 to 3.

Your Task:
You do not need to read input or print anyting. Your task is to complete the function shiftPile() which takes N and n as input parameters and returns the nth move in a list.

Expected Time Complexity: O(2N)
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ N ≤ 20
1 ≤ n ≤ 1000 

================================================ FILE: GFG/Hungry Pizza Lovers/Hungry pizza lovers.java ================================================ // { Driver Code Starts //Initial Template for Java //Initial Template for Java /*package whatever //do not write package name here */ import java.io.*; import java.util.*; class Array { // Driver code public static void main (String[] args) throws IOException{ // Taking input using buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testcases = Integer.parseInt(br.readLine()); // looping through all testcases while(testcases-- > 0){ String line = br.readLine(); String[] element = line.trim().split("\\s+"); int sizeOfArray = Integer.parseInt(element[0]); int arr [][] = new int[sizeOfArray][2]; for(int i = 0;i ans; ans = obj.permute(arr, sizeOfArray); for(int i: ans) System.out.println(i); } } } // } Driver Code Ends //User function Template for Java class Complete{ // Function for finding maximum and value pair public static ArrayList permute (int arr[][], int n) { Map map=new HashMap<>(); for(int i=0;iInteger.compare(a[0]+a[1],b[0]+b[1])); ArrayList ans=new ArrayList<>(); for(int i=0;i

Dominos Pizza has hungry customers waiting in the queue. Each unique order is placed by a customer at time x[i], and the order takes y[i] units of time to complete.
You have information on all n orders, Find the order in which all customers will receive their pizza and return it. If two or more orders are completed at the same time then sort them by non-decreasing order number.

Example 1:

Input : arr[ ] = {{4,1}, {6,2}, {7,6}, 
                       {8,1}, {1,3}}
Output : 5 1 2 4 3
Explanation:
Here an array can be transform to 
{5, 8, 13, 9, 4}. Here 5th index order 
received first then 1st order, 2nd order...
return {5, 1, 2, 4, 3}


Example 2:

Input : arr[ ] = {{1,1}, {1,1}, {1,1}} 
Output :  1 2 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 permute() that takes 2-d array (arr), sizeOfArray (n), and return the array of order in which customers will receive their pizza. The driver code takes care of the printing.

Expected Time Complexity: O(N*LOG(N)).
Expected Auxiliary Space: O(N).

Constraints:
1 ≤ N ≤ 105
1 ≤ arr[i][0], arr[i][1] ≤ 105

================================================ FILE: GFG/IPL/IPL.cpp ================================================ vector max_of_subarrays(vector arr, int n, int k) { dequepq; vectorans; for(int i=0;i=k-1){ ans.push_back(arr[pq.front()]); } } return ans; } ================================================ FILE: GFG/IPL 2021 - Match Day 2/IPL 2021 - Match Day 2 gfg med s22.cpp ================================================ #include using namespace std; class Solution { public: vector max_of_subarrays(vector arr, int n, int k) { // your code here vectorres; multisetm; for(int i =0; i> t; while (t--) { int n, k; cin >> n >> k; vector arr(n); for (int i = 0; i < n; i++) cin >> arr[i]; Solution ob; vector res = ob.max_of_subarrays(arr, n, k); for (int i = 0; i < res.size(); i++) cout << res[i] << " "; cout << endl; } return 0; } ================================================ FILE: GFG/Ishaan Loves Chocolates/Ishaan loves chocolates.py ================================================ #User function Template for python3 def chocolates (arr, n): return min(arr) #{ # Driver Code Starts #Initial Template for Python 3 for _ in range(0,int(input())): n = int(input()) arr = list(map(int, input().strip().split())) ans = chocolates(arr, n) print(ans) # } Driver Code Ends ================================================ FILE: GFG/Ishaan Loves Chocolates/README.md ================================================ # Ishaan Loves Chocolates ## Easy

As we know, Ishaan has a love for chocolates. He has bought a huge chocolate bar that contains N chocolate squares. Each of the squares has a tastiness level which is denoted by an array A[].
Ishaan can eat the first or the last square of the chocolate at once. Ishaan has a sister who loves chocolates too and she demands the last chocolate square. Now, Ishaan being greedy eats the more tasty square first. 
Determine the tastiness level of the square which his sister gets.

Example 1:

Input : arr[ ] = {5, 3, 1, 6, 9}
Output : 1
Explanation:
Initially: 5 3 1 6 9
In first step: 5 3 1 6
In Second step: 5 3 1
In Third step: 3 1
In Fourth step: 1
Return 1



Example 2:

Input : arr[ ] = {5, 9, 2, 6} 
Output :  2

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 chocolates() that takes an array (arr), sizeOfArray (n) and return the tastiness level of the square which his sister gets. The driver code takes care of the printing.

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).

 

Constraints : 
1 ≤ N ≤ 105
1 ≤ A[i] ≤ 109

================================================ FILE: GFG/Josephus problem/Josephus problem.java ================================================ class Solution { public int josephus(int n, int k) { //Your code here if(n==1)return n; return (josephus(n-1,k)+(k-1))%n +1; } } ================================================ FILE: GFG/Jump Game/Jump game.java ================================================ // { Driver Code Starts import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { int N = Integer.parseInt(read.readLine()); String S1[] = read.readLine().split(" "); int[] A = new int[N]; for(int i=0; i=0;i--) { step++; if(A[i]>=step)step=0; } if(step==0)return 1; return 0; } } ================================================ FILE: GFG/Jump Game/README.md ================================================ # Jump Game ## Medium

Given an positive integer N and a list of N integers A[]. Each element in the array denotes the maximum length of jump you can cover. Find out if you can make it to the last index if you start at the first index of the list.


Example 1:

Input:
N = 6
A[] = {1, 2, 0, 3, 0, 0} 
Output:
1
Explanation:
Jump 1 step from first index to
second index. Then jump 2 steps to reach 
4th index, and now jump 2 steps to reach
the end.

Example 2:

Input:
N = 3
A[] =  {1, 0, 2}
Output:
0
Explanation:
You can't reach the end of the array.


Your Task:
You don't need to read input or print anything. Your task is to complete the function canReach() which takes a Integer N and a list A of size N as input and returns 1 if the end of the array is reachable, else return 0.


Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)


Constraints:
1 <= N <= 105
0 <= A[i] <= 105

================================================ FILE: GFG/Jumping Numbers/Jumping Numbers.cpp ================================================ class Solution { public: long long jumpingNums(long long x) { // code here if(x<=9)return x; queueq; for(int i=0; i<=9; i++)q.push(i); int ans = INT_MIN; while(q.size()>0){ int digit = q.front(); q.pop(); ans = max(ans,digit); int rem = digit%10; int num1 = digit*10 + rem - 1; int num2 = digit*10 + rem + 1; if(rem == 0){ if(num2<=x) q.push(num2); } else if(rem==9){ if(num1<=x)q.push(num1); } else{ if(num1<=x) q.push(num1); if(num2<=x)q.push(num2); } } return ans; } }; ================================================ FILE: GFG/Jumping Numbers/README.md ================================================ ## Jumping Numbers Given a positive number X. Find the largest Jumping Number which is smaller than or equal to X. Jumping Number: A number is called Jumping Number if all adjacent digits in it differ by only 1. All single-digit numbers are considered as Jumping Numbers. For example 7, 8987 and 4343456 are Jumping numbers but 796, 677 and 89098 are not. **Example 1:** ``` Input: X = 10 Output: 10 Explanation: 10 is the largest Jumping Number possible for X = 10. ``` **Example 2:** ``` Input: X = 50 Output: 45 Explanation: 45 is the largest Jumping Number possible for X = 50. ``` **Your Task:** You don't need to read input or print anything. Your task is to complete the function **jumpingNums()** which takes an Integer X as input and returns the largest Jumping Number less than or equal to X. Expected Time Complexity: O(k), where k is no of jumping numbers Expected Auxiliary Space: O(k), where k is no of jumping numbers Constraints: 1 <= X <= 109 ================================================ FILE: GFG/K-Ary Tree/README.md ================================================ # K-Ary Tree ## Easy

Find the number of leaf nodes in a full k-ary tree of height m.
Note: You have to return the answer module 109+7.

 

Example 1:

Input:
k = 2, m = 2
Output:
4
Explanation:
A full Binary tree of height 2 has 4 leaf nodes. 

Example 2:

Input:
k = 2, m = 1
Output:
2
Explanation:
A full Binary tree of height 1 has 2 leaf nodes.

 

Your Task:
You don't need to read input or print anything. Your task is to complete the function karyTree() which takes 2 Integers k, and m as input and returns the number of leaf nodes in a full k-ary Tree.

 

Expected Time Complexity: O(log(m))
Expected Auxiliary Space: O(1)

 

Constraints:
1 <= k,m <= 108

================================================ FILE: GFG/Knight Walk/Knight Walk.cpp ================================================ /* This code is contributed by: - Shubham Kumar Jha (https://github.com/Shubhamjha1710) - Adarsh Urmaliya (https://github.com/Satellite-system) */ class Solution { public: int minStepToReachTarget(vector&KnightPos, vector&TargetPos, int N) { queue> q; vector> visit(N+1 , vector(N+1, false)); q.push({KnightPos[0] , KnightPos[1]}); visit[KnightPos[0]][KnightPos[1]] = 1; int lvl = -1; vector> dir = {{-1,-2},{-2,-1},{-2,1},{-1,2},{1,-2},{2,-1},{2,1},{1,2}}; while(q.empty() == false) { lvl += 1; int sz = q.size(); for(int k = 0;k= 1 && ny >= 1 && nx <= N && ny <= N) && visit[nx][ny] == false) { q.push({nx , ny}); visit[nx][ny] = true; } } } } return -1; // Code here } }; /* Another Approach : Store the number of steps it taken to each square and from them find the minimum Distance Steps needed to reach Target Position. Steps to reach other squares from starting Square could be find By BFS Algorithm, so we will use this Algorithm. First initialize Stating position as steps 0, now from each position we have total 8 Possible pos(positions), where we could traverse(given that those are valid positions, and have never been visited before), and store stps in vector. Whenever we encounter the target positon, we return it as we are using BFS algorithm, that's why whenever we react to target position, then that would be our First time when we have reached that position, hence will be in shortest steps. */ class Solution { public: bool isValid(int r, int c, int n){ if(r<=0 || c<=0 || r>n || c>n) return false; return true; } int minStepToReachTarget(vector&KnightPos, vector&TargetPos, int N){ if(KnightPos[0]==TargetPos[0] && KnightPos[1]==TargetPos[1]){ return 0; } queue> st; vector> dis(N+2, vector(N+2, -1)); st.push({KnightPos[0], KnightPos[1]}); dis[KnightPos[0]][KnightPos[1]] = 0; vector> pos={{1,2}, {2,1}, {-1,2}, {1,-2}, {-1,-2}, {-2,-1}, {-2,1}, {2,-1}}; while(!st.empty()){ pair tp = st.front(); st.pop(); for(int j=0;j<8; ++j){ int nr = tp.first + pos[j][0], nc = tp.second+pos[j][1]; if(isValid(nr, nc, N) && dis[nr][nc]==-1){ st.push({nr, nc}); dis[nr][nc] = 1 + dis[tp.first][tp.second]; } if(nr==TargetPos[0] && nc==TargetPos[1]) return 1 + dis[tp.first][tp.second]; } } return dis[TargetPos[0]][TargetPos[1]]; } }; ================================================ FILE: GFG/Knight Walk/Knight Walk.java ================================================ class Pair{ int i; int j; int dist; Pair(int i,int j,int d){ this.i=i; this.j=j; this.dist=d; } } class Solution { public int minStepToReachTarget(int KnightPos[], int TargetPos[], int N) { // Code here int[] x=new int[]{1,1,2,2,-1,-1,-2,-2}; int[]y=new int[]{2,-2,1,-1,2,-2,1,-1}; Queue q=new LinkedList<>(); q.add(new Pair(KnightPos[0],KnightPos[1],0)); boolean [][]vis=new boolean[N+1][N+1]; vis[KnightPos[0]][KnightPos[1]]=true; while(q.size()>0){ int sz=q.size(); while(sz-->0){ Pair curr=q.remove(); int i=curr.i; int j=curr.j; int dist=curr.dist; if(i==TargetPos[0] && j==TargetPos[1])return dist; for(int k=0;k<8;k++){ if(isValid(i+x[k],j+y[k],vis,N)){ q.add(new Pair(i+x[k],j+y[k],dist+1)); vis[i+x[k]][j+y[k]]=true; } } } } return -1; } boolean isValid(int i,int j,boolean[][]vis,int N){ if(i<1 || j<1 || i>N || j>N || vis[i][j]){ return false; } return true; } } ================================================ FILE: GFG/Kth smallest element/Kth smallest element.py ================================================ #User function Template for python3 import heapq class Solution: def kthSmallest(self,arr, l, r, k): ''' 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 ''' heap = [] for i in arr: heapq.heappush(heap, i) for i in range(k-1): heapq.heappop(heap) return heapq.heappop(heap) #{ # Driver Code Starts #Initial Template for Python 3 #contributed by RavinderSinghPB if __name__ == '__main__': import random t=int(input()) for tcs in range(t): n=int(input()) arr=list(map(int,input().strip().split())) k=int(input()) ob=Solution() print(ob.kthSmallest(arr, 0, n-1, k)) # } Driver Code Ends ================================================ FILE: GFG/LCM Triplet/LCM Triplet.java ================================================ class Solution { long lcmTriplets(long N) { // code here if(N<=2)return N; if((N&1)==1)return N*(N-1)*(N-2); if(N%3==0)return (N-1)*(N-3)*(N-2); return N*(N-1)*(N-3); } } ================================================ FILE: GFG/Largest subtree sum in a tree/Largest subtree sum in a tree.cpp ================================================ class Solution { public: int subtree(Node* root, int& ans){ if(root==NULL){ return 0; } int lsum = subtree(root->left,ans); int rsum = subtree(root->right,ans); int tot = root->data + lsum + rsum; ans = max(ans,tot); return tot; } int findLargestSubtreeSum(Node* root){ int ans = INT_MIN; subtree(root,ans); return ans; } }; ================================================ FILE: GFG/Largest subtree sum in a tree/Largest subtree sum in a tree.java ================================================ class Solution { static int ans; public static int findLargestSubtreeSum(Node root) { // code here ans=Integer.MIN_VALUE; dfs(root); return ans; } static int dfs(Node root){ int sum=root.data; if(root.left!=null){ sum+=dfs(root.left); } if(root.right!=null){ sum+=dfs(root.right); } ans=Math.max(ans,sum); return sum; } } ================================================ FILE: GFG/Last modified ball/Last modified ball.java ================================================ class Solution { int solve(int N, int[] A) { // code here for(int i=N-1;i>=0;i--){ if(A[i]<9)return i+1; } return -1; } }; ================================================ FILE: GFG/Longest Bitonic subsequence/Longest Bitonic subsequence.java ================================================ class Solution { public int LongestBitonicSequence(int[] nums) { // Code here int n=nums.length; int[]inc=new int[n]; for(int i=0;i=0;j--){ if(nums[j]inc[i]){ inc[i]=inc[j]+1; } } } int[]dec=new int[n]; for(int i=n-1;i>=0;i--){ dec[i]=1; for(int j=i+1;jdec[i]){ dec[i]=dec[j]+1; } } } int ans=0; for(int i=0;i max=new PriorityQueue<>(Collections.reverseOrder()); PriorityQueue min=new PriorityQueue<>(); int ans=0; for(int i=0,j=0;i1){ min.remove(arr[j]); max.remove(arr[j]); j++; } ans=Math.max(ans,i-j+1); } return ans; } }; ================================================ FILE: GFG/Magic Triplets/Magic Triplets.java ================================================ class Solution{ public int countTriplets(int[] nums){ // code here int ans=0; int n=nums.length; for(int j=1;j=0;i--){ if(nums[i]nums[j])larger++; } ans+=smaller*larger; } return ans; } } ================================================ FILE: GFG/Majority Element/Majority Element.java ================================================ //Boyer-Moore Voting Algorithm class Solution { public int majorityElement(int[] nums) { int count = 0; Integer candidate = null; for (int num : nums) { if (count == 0) { candidate = num; } count += (num == candidate) ? 1 : -1; } return candidate; } } //================================================================= //recursive class Solution { public int majorityElement(int[] nums) { return recurse(nums, 0); } public int recurse(int[] nums, int start){ int n = nums.length; int tracker= 1; for(int i=start+1;i map=new HashMap<>(); for(int i=0;i n // 2): return majorityNum else: return -1 ================================================ FILE: GFG/Majority Element/README.md ================================================ # Majority Element ### Medium Given an array **A** of **N** elements. Find the majority element in the array. A majority element in an array A of size N is an **element that appears more than N/2 times in the array.** ### Example 1:
Input:
N = 3 
A[] = {1,2,3} 
Output:
-1
Explanation:
Since, each element in 
{1,2,3} appears only once so there 
is no majority element.
### Example 2:
Input:
N = 5 
A[] = {3,1,3,3,2} 
Output:
3
Explanation:
Since, 3 is present more
than N/2 times, so it is 
the majority element.
**Your Task:** The task is to complete the function **majorityElement()** which returns the majority element in the array. If no majority exists, return -1. **Expected Time Complexity:** O(N). **Expected Auxiliary Space:** O(1). **Constraints:** 1 ≤ N ≤ 107 0 ≤ Ai ≤ 106 ================================================ FILE: GFG/Make array elements unique/Make array elements unique.java ================================================ class Solution { public long minIncrements(int[] arr, int N) { // Code here Arrays.sort(arr); int ans=0; for(int i=1;i=arr[i]){ ans+=arr[i-1]-arr[i]+1; arr[i]=arr[i-1]+1; } } return ans; } } ================================================ FILE: GFG/Max Min/Max Min.cpp ================================================ class Solution { public: int findSum(int A[], int N) { //code here. int maxVal=INT_MIN; int minVal=INT_MAX; for(int i=0;iA[x]):min=A[x] if(max

Given an array A of size N of integers. Your task is to find the sum of minimum and maximum element in the array.

Example 1:

Input:
N = 5
A[] = {-2, 1, -4, 5, 3}
Output: 1
Explanation: min = -4, max =  5. Sum = -4 + 5 = 1

 

Example 2:

Input:
N = 4
A[]  = {1, 3, 4, 1}
Output: 5
Explanation: min = 1, max = 4. Sum = 1 + 4 = 5

 

Your Task:  
You don't need to read input or print anything. Your task is to complete the function findSum() which takes the array A[] and its size N as inputs and returns the summation of minimum and maximum element of the array.

 

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

 

Constraints:
1 <= N <= 105
-109 <= Ai <= 109

================================================ FILE: GFG/Maximize the sum of selected numbers from an array to make it empty/Maximize the sum of selected numbers from a sorted array to make it empty.cpp ================================================ class Solution{ public: int maximizeSum(int a[], int n) { // Complete the function unordered_map ans; int sum=0; bool arr[n]; for(int i=0;i=0;i--) { if(arr[i] == false) { arr[i]=true; sum+= a[i]; if(ans[a[i]-1] > 0) { arr[i-ans[a[i]]]=true; ans[a[i]-1]--; } } } return sum; } }; ================================================ FILE: GFG/Maximize the sum of selected numbers from an array to make it empty/Maximize the sum of selected numbers from an array to make it empty.java ================================================ class Complete{ // Function for finding maximum and value pair public static int maximizeSum (int arr[], int n) { //Complete the function int[] map=new int[100001]; for(int x:arr){ map[x]++; } int sum=0; for(int i=n-1;i>=0;i--){ int curr=arr[i]; if(map[curr]!=0){ sum+=curr; map[curr]--; if(map[curr-1]!=0){ map[curr-1]--; } } } return sum; } ================================================ FILE: GFG/Maximize the sum of selected numbers from an array to make it empty/README.md ================================================ ## Maximize the sum of selected numbers from a sorted array to make it empty Given a array of N numbers, we need to maximize the sum of selected numbers. At each step, you need to select a number Ai, delete one occurrence of Ai-1 (if exists), and Ai each from the array. Repeat these steps until the array gets empty. The problem is to maximize the sum of the selected numbers. **Note:** Numbers need to be selected from maximum to minimum. ``` Example 1: Input : arr[ ] = {1, 2, 2, 2, 3, 4} Output : 10 Explanation: We select 4, so 4 and 3 are deleted leaving us with {1,2,2,2}. Then we select 2, so 2 & 1 are deleted. We are left with{2,2}. We select 2 in next two steps, thus the sum is 4+2+2+2=10. ``` ``` Example 2: Input : arr[ ] = {1, 2, 3} Output : 4 Explanation: We select 3, so 3 and 2 are deleted leaving us with {1}. Then we select 1, 0 doesn't exist so we delete 1. thus the sum is 3+1=4. ``` **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 **maximizeSum()** that takes an array (arr), sizeOfArray (n), and return the maximum sum of the selected numbers. The driver code takes care of the printing. **Expected Time Complexity:** O(N). **Expected Auxiliary Space:** O(N). **Constraints:** 1 ≤ N ≤ 105 1 ≤ A[i] ≤ 105 ================================================ FILE: GFG/Maximum Number of Toys/Maximum Number of Toys.java ================================================ // Nlogn + Q(K + logN) class Pair{ private K cost; private V index; public Pair(K a,V b){ this.cost=a; this.index=b; } public K getCost(){ return this.cost; } public V getIndex(){ return this.index; } } class Solution { ArrayList maximumToys(int N, int A[], int Q, ArrayList Queries[]){ ArrayList> arr=new ArrayList<>(N); for(int i=0;i(A[i],i)); } Collections.sort(arr,(a,b)->a.getCost()-b.getCost());//Nlogn HashMap map=new HashMap<>(); for(int i=0;i res=new ArrayList<>(Q); for(int i=0;i damaged=new HashSet<>(); for(int j=0;j=arr.get(s).getCost()){ if(!damaged.contains(s)){ ans++; rem-=arr.get(s).getCost(); } s++; } res.add(ans); } return res; } } ================================================ FILE: GFG/Maximum Profit By Choosing A Subset Of Intervals/Maximum Profit By Choosing A Subset Of Intervals.java ================================================ class Solution { public static int maximum_profit(int n, int[][] arr) { // code here Arrays.sort(arr,(a,b)->{ if(a[0]!=b[0]) return a[0]-b[0]; return a[1]-b[1]; }); int[]dp=new int[n]; return rec(0,arr,n,dp); } static int rec(int index,int[][]arr,int n,int[]dp){ if(index>=n)return 0; if(dp[index]!=0)return dp[index]; int not_select=rec(index+1,arr,n,dp); int nextIndex = findNext(index+1,arr[index][1],arr,n); int select = arr[index][2] + rec(nextIndex,arr,n,dp); return dp[index]=Math.max(select,not_select); } static int findNext(int i,int prevEnd,int[][]arr,int n){ while(i=prevEnd){ break; }else{ i++; } } return i; } } ================================================ FILE: GFG/Maximum Sub Array/Maximum Sub Array.java ================================================ class Solution { ArrayList findSubarray(int a[], int n) { // code here int maxSum=0; int maxStart=0; int maxEnd=0; int currSum=0; int currStart=0; for(int i=0;imaxSum){ maxSum=currSum; maxStart=currStart; maxEnd=i+1; }else if(currSum==maxSum){ int currDis=i+1-currStart; int maxDis=maxEnd-maxStart; if(currDis>maxDis){ maxStart=currStart; maxEnd=i+1; } } } ArrayList ans=new ArrayList<>(); for(int i=maxStart;itemp(26); for(int i=0;ik){ temp[s[l]-'A']--; l++; } else ans = max(ans,i-l+1); } return ans; } }; ================================================ FILE: GFG/Maximum Sub-String after at most K changes/Maximum Sub-String after at most K changes.java ================================================ class Solution { public int characterReplacement(String s, int k) { // code here int[]arr=new int[26]; int prev=0; int ans=0; for(int i=0;isame){ diff+=same; same=i; }else{ diff+=i; } } return diff<=k? same+diff : -1; } } ================================================ FILE: GFG/Maximum Sub-String after at most K changes/README.md ================================================ ## Maximum Sub-String after at most K changes We have a string s of length n, which contains only UPPERCASE characters and we have a number k (always less than n). We can make at most k changes in our string. In one change, you can replace any s[i] (0<= i < n) with any uppercase character (from 'A' to 'Z'). After k changes, find the maximum possible length of the sub-string which have all same characters. **Example 1:** ``` Input: s = "ABAB", k = 2 Output: 4 Explanation: Change 2 'B' into 'A'. Now s = "AAAA" ``` Example:2 ``` Input: s = "ADBD", k = 1 Output: 3 Explanation: Change 'B' into 'D'. Now s = "ADDD" ``` *** **Your Task:** You don't need to read or print anything. Your task is to complete the function **characterReplacement()** which takes s and k as input parameters and returns the maximum length of sub-string after doing k changes. **Expected Time Complexity:** O(n) **Expected Space Complexity:** O(26) ================================================ FILE: GFG/Maximum Sum LCM/Maximum Sum LCM.java ================================================ //User function Template for Java class Solution { static long maxSumLCM(int n) { // code here long ans=0; for(int i=1;i<=(int)Math.sqrt(n);i++){ if(n%i==0){ ans+=i; if(n/i!=i)ans+=(n/i); } } return ans; } } ================================================ FILE: GFG/Maximum Value/Maximum Value.java ================================================ class Solution { ArrayList maximumValue(Node node) { //code here Queue q=new LinkedList<>(); ArrayList ans=new ArrayList<>(); q.add(node); while(!q.isEmpty()){ int currLevelSize = q.size(); int max=0; while(currLevelSize-->0){ Node curr=q.remove(); max=Math.max(max,curr.data); if(curr.left!=null)q.add(curr.left); if(curr.right!=null)q.add(curr.right); } ans.add(max); } return ans; } } ================================================ FILE: GFG/Maximum of all subarrays of size k/Maximum of all subarrays of size k.java ================================================ class Solution { //Function to find maximum of each subarray of size k. static ArrayList max_of_subarrays(int arr[], int n, int k) { // Your code here Deque q=new ArrayDeque<>(); for(int i=0;i0 && q.peekLast() ans =new ArrayList<>(); ans.add(q.peekFirst()); int x=0; for(int i=k;i0 && q.peekLast()max)max=matrix[i][C-1]; } int desired=(R*C +1)/2; while(min=r){ return; } int mid = l + (r-l)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,mid,r); } } ================================================ FILE: GFG/Merge two BST 's/Merge two BST.cpp ================================================ //This Approch uses Recursuion class Solution { public: //Function to return a list of integers denoting the node //values of both the BST in a sorted order. void inorder1(Node* root, vector &v1){ if(root){ inorder1(root->left,v1); v1.push_back(root->data); inorder1(root->right,v1); } } //calling Inorder void inorder2(Node* root, vector &v1){ if(root){ inorder2(root->left,v1); v1.push_back(root->data); inorder2(root->right,v1); } } vector merge(Node *root1, Node *root2) { vector v1; inorder1(root1,v1);//we are calling this inorder to add all the element in the main vector so that at the end we get a sorted array by merging both element in the main vector inorder2(root2,v1); sort(v1.begin(),v1.end()); return v1; } }; ================================================ FILE: GFG/Min operations/Min operations.java ================================================ class Solution { public static int solve(int a, int b) { // code here if(a==b)return 0; if((a & b) == a || (a & b) == b)return 1; return 2; } } ================================================ FILE: GFG/Minimize number of Students to be removed/Minimize number of Students to be removed.java ================================================ class Solution { public int removeStudents(int[] H, int n) { // code here ArrayList dp=new ArrayList<>(); for(int i=0;i arr){ int l=0; int h=arr.size()-1; while(l<=h){ int mid=(l+h)/2; if(arr.get(mid)>=ele){ h=mid-1; }else{ l=mid+1; } } return l; } }; ================================================ FILE: GFG/Minimize the sum/Minimize the sum.java ================================================ class Solution { long minimizeSum(int N, int arr[]) { // code here long ans=0; PriorityQueue pq=new PriorityQueue<>(); for(int i:arr){ pq.add(i); } while(pq.size()>1){ int curr=pq.remove()+pq.remove(); ans+=curr; pq.add(curr); } return ans; } } ================================================ FILE: GFG/Minimum Cost of ropes/Minimum Cost of ropes.java ================================================ class Solution { //Function to return the minimum cost of connecting the ropes. long minCost(long arr[], int n) { // your code here long cost = 0; if(n < 2){ return cost; } PriorityQueue pq = new PriorityQueue(); for(int i = 0; i < n; i++){ pq.add(arr[i]); } while(true){ long first = pq.peek(); pq.remove(); long second = pq.peek(); pq.remove(); long temp = first + second; cost = cost + temp; if(pq.isEmpty()){ break; } pq.add(temp); } return cost; } } ================================================ FILE: GFG/Minimum Costs of Ropes/Minimum Costs of Ropes.cpp ================================================ #include using namespace std; class Solution { public: //Function to return the minimum cost of connecting the ropes. long long minCost(long long arr[], long long n) { // Your code here if(n==1) return 0; // base case if 1 rope is only given then we don't have to add so return 0 priority_queue, greater> pq; // taking priority_queue in main_heap for(int i=0; i1){ // getting 1st elem mini from top and popping out from priority_queue long long x = pq.top(); pq.pop(); // getting 2nd elem mini from top and popping out from priority_queue long long y = pq.top(); pq.pop(); // adding 1st mini and 2nd mini res+=(x+y); // pushing to Priority queue to add with other numbers also pq.push(x+y); } return res; // TC: O(N log N) -> pq takes log n and loop is running for n times so it becomes nlogn // SC: O(N) - pq is taking N Space to store } }; int main() { long long t; cin >> t; while (t--) { long long n; cin >> n; long long i, a[n]; for (i = 0; i < n; i++) { cin >> a[i]; } Solution ob; cout << ob.minCost(a, n) << endl; } return 0; } ================================================ FILE: GFG/Minimum characters to be added at front to make string palindrome/Minimum characters to be added at front to make string palindrome oc2.cpp ================================================ #include using namespace std; class Solution { public: int minChar(string str){ //Write your code here int i =0, j = str.length()-1; int temp_j =j, res =0; while(i <=j){ // to check curr with reverse, if matches incr if(str[i]== str[j]){ i++; j--; }else{ // otherwise res++; i=0; j=--temp_j; } } return res; } }; int main() { int t; cin>>t; while(t--) { string str; cin >> str; Solution ob; int ans = ob.minChar(str); cout << ans< minPartition(int N) { vector v; if(N>=2000){ int cnt = N/2000; for(int i=0;i=500){ int cnt = N/500; for(int i=0;i=200){ int cnt = N/200; for(int i=0;i=100){ int cnt = N/100; for(int i=0;i=50){ int cnt = N/50; for(int i=0;i=20){ int cnt = N/20; for(int i=0;i=10){ int cnt = N/10; for(int i=0;i=5){ int cnt = N/5; for(int i=0;i=2){ int cnt = N/2; for(int i=0;i=1){ int cnt = N; for(int i=0;i minPartition(int N) { // code here int[]a=new int[]{1,2,5,10,20,50,100,200,500,2000}; List ans=new ArrayList<>(); int i=9; while(i>=0){ if(a[i]>N){ i--; }else{ while(N>=a[i]){ ans.add(a[i]); N-=a[i]; } } } return ans; } } ================================================ FILE: GFG/Minimum sum partition/Minimum sum partition.cpp ================================================ }; ================================================ FILE: GFG/Minimum sum partition/Minimum sum partition.java ================================================ class Solution { public int minDifference(int arr[], int n) { // Your code goes here Map map=new HashMap<>(); return dfs(arr,n-1,0,0,map); } public int dfs(int[]arr,int n,int s1,int s2,Map map){ if(n<0){ return Math.abs(s1-s2); } String key=n+","+s1; if(!map.containsKey(key)){ int first=dfs(arr,n-1,s1+arr[n],s2,map); int sec=dfs(arr,n-1,s1,s2+arr[n],map); map.put(key,Math.min(first,sec)); } return map.get(key); } } ================================================ FILE: GFG/Minimum sum partition/README.md ================================================ ## Minimum sum partition Given an array arr of size n containing non-negative integers, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum and find the minimum difference **Example 1:** ``` Input: N = 4, arr[] = {1, 6, 11, 5} Output: 1 Explanation: Subset1 = {1, 5, 6}, sum of Subset1 = 12 Subset2 = {11}, sum of Subset2 = 11 ``` **Example 2:** ``` Input: N = 2, arr[] = {1, 4} Output: 3 Explanation: Subset1 = {1}, sum of Subset1 = 1 Subset2 = {4}, sum of Subset2 = 4 ``` **Your Task:** You don't need to read input or print anything. Complete the function **minDifference()** which takes N and array arr as input parameters and returns the integer value **Expected Time Complexity:** O(N*|sum of array elements|) **Expected Auxiliary Space:** O(N*|sum of array elements|) **Constraints:** 1 ≤ N*|sum of array elements| ≤ 106 0 < arr[i] <= 105 ================================================ FILE: GFG/Missing number in matrix.java/Missing number in matrix.java ================================================ class Solution { public long MissingNo(int[][] mat) { // code here int n=mat.length; int x=-1; int y=-1; long rowSum[]=new long[n]; long colSum[]=new long[n]; long leftDia=0; long rightDia=0; for(int i=0;i=l) { if(f[i]==0) ans+=i; else ans+=f[i]; } } return ans; } } ================================================ FILE: GFG/Modified Numbers and Queries/Modified Numbers and Queries oc3.cpp ================================================ #include using namespace std; class Solution { private:void Sieve(vector &Primes, int n){ Primes[1]=1; for(int i =2; i<=n; i++) if(Primes[i] ==0) for(int j =i; j<=n; j+=i) Primes[j]+=i; }; public: int sumOfAll(int l, int r){ // code here vectorPrimes(r+1, 0); Sieve(Primes, r); int sum=0; for(int i =l; i<=r; i++) sum+=Primes[i]; return sum; } }; int main() { int t; cin >> t; while (t--) { int l, r; cin>>l>>r; Solution ob; cout<1, 2->2 and 1+2=3. ``` ## Example 2: ``` Input: l = 1, r = 6 Output: 18 Explanation:1->1, 2->2, 3->3, 4->2 5->5, 6->2+3=5, 1+2+3+2+5+5 = 18. ``` **Your Task:** You dont need to read input or print anything. Complete the function **sumOfAll()** which takes l and r as input parameter and returns sum all the numbers ( as represented ) in the given range both L and R included. **Expected Time Complexity:** O(nloglogn) **Expected Auxiliary Space:** O(N) **Constraints:** 1 <= l <= r <=104 ================================================ FILE: GFG/Move Last Element to Front of a Linked List/Move Last Element to Front of a Linked List 2 different approaches.java ================================================ First Approach: Time Complexity:O(N) Auxiliary Space:O(N) Code: class Solution { public static Node moveToFront(Node head) { if(head==null || head.next==null){ return head; } ArrayListaa=new ArrayList(); Node temp=head; while(temp!=null){ aa.add(temp.data); temp=temp.next; } int a=aa.get(aa.size()-1); aa.remove(aa.size()-1); aa.add(0,a); Node temp2=new Node(-1); Node temp3=temp2; for(int a1:aa){ temp2.next=new Node(a1); temp2=temp2.next; } return temp3.next; } } ======================================================================================================================================================================= Second Approach: Time Complexity:O(N) Auxiliary Space:O(1) Code: class Solution { public static Node moveToFront(Node head) { if(head==null){ return null; } else if(head.next==null){ return head; } Node temp=head; Node prev=null; Node current=head; while(current.next!=null){ prev=current; current=current.next; } current.next=head; prev.next=null; return current; } } ================================================ FILE: GFG/Move Last Element to Front of a Linked List/Move Last Element to Front of a Linked List.cpp ================================================ class Solution{ public: ListNode *moveToFront(ListNode *head){ if(head->next == NULL) return head; ListNode *temp = head; while(head->next->next!=NULL) head = head->next; head->next->next = temp; temp = head->next; head->next = NULL; return temp; } }; ================================================ FILE: GFG/Move Last Element to Front of a Linked List/Move Last Element to Front of a Linked List.java ================================================ class Solution { public static Node moveToFront(Node head) { // code here if(head.next==null)return head; Node temp=head; while(temp.next.next!=null){ temp=temp.next; } Node last=temp.next; temp.next=null; last.next=head; return last; } } ================================================ FILE: GFG/Move Last Element to Front of a Linked List/README.md ================================================ ## Move Last Element to Front of a Linked List You are given the head of a Linked List. You have to move the last element to the front of the Linked List and return the list. **Example 1:** ``` Input: N = 5 List = {2,5,6,2,1} Output: {1,2,5,6,2} Explanation: In the given linked list, the last element is 1, after moving the last element to the front the linked list will be {1,2,5,6,2}. ``` **Example 2:** ``` Input: N = 1 List = {2} Output: {2} Explanation: Here 2 is the only element so, the linked list will remain the same. ``` *** **Your Task:** You don't need to read input or print anything. Your task is to complete the function **moveToFront()** which takes the address of the head of the linked list and returns the modified linked list. **Expected Time Complexity:** O(N) **Expected Auxiliary Space:** O(1) **Constraints:** 1 <= N <= 105 0 <= Elements of List <= 109 Sum of N over all test cases doesn't exceeds 106 ================================================ FILE: GFG/Next Greater Element/Next Greater Element.java ================================================ class Solution{ public static long[] nextLargerElement(long[] arr, int n) { // Your code here long[]ans=new long[n]; Stack st=new Stack<>(); for(int i=n-1;i>=0;i--){ while(!st.isEmpty() && st.peek() ar=new ArrayList(); if(isHappyNumber(i, ar)) { return i; } } return -1; } public static boolean isHappyNumber(int n, ArrayList ar) { if(ar.contains(n)) { return false; } if(n==1) { return true; } ar.add(n); n=findSquareNumber(n); boolean res=isHappyNumber(n, ar); return res; } public static int findSquareNumber(int n) { int newNumber=0; while(n>0) { int rem=n%10; newNumber+=(rem*rem); n=n/10; } return newNumber; } } ================================================ FILE: GFG/Nine Divisors/Nine Divisors.cpp ================================================ class Solution{ public: long long int nineDivisors(long long int N){ //Code Here if(N < 36) return 0; long long size = sqrt(N); long long count = 0; vector sieve(size+1); for(int i = 1; i <= size; i++) { sieve[i] = i; } for(long long i = 2; i*i <= size; i++) { if(sieve[i] != i) continue; for(long long j = i*i; j <= size; j+=i) { if(sieve[j] == j) sieve[j] = i; } } for(long long i = 2; i <= size; i++) { long long p = sieve[i]; long long q = sieve[i/p]; if((p!=q && p*q == i && q !=1) || (sieve[i] == i && pow(i,8) <= N)) { count++; } } return count; } }; ================================================ FILE: GFG/Nine Divisors/Nine Divisors.java ================================================ class Solution{ static long nineDivisors(long N){ //Code Here long ans=0; int size=(int)Math.sqrt(N); int prime[]=new int[size+1]; for(int i=1;i<=size;i++){ prime[i]=i; } //fill sieve for(int i=2;i*i<=size;i++){ if(prime[i]==i){ for(int j=i*i;j<=size;j+=i){ if(prime[j]==j){ prime[j]=i; } } } } //check for root n for(int i=2;i<=size;i++){ int p=prime[i]; int q=prime[i/p]; if((p!= q && p*q==i && q!=1) || (prime[i]==i && Math.pow(i,8)<=N)){ ans+=1; } } return ans; } } ================================================ FILE: GFG/Number Formation/Number Formation.cpp ================================================ class Solution { public: const int mod=1e9+7; int getSum(int X, int Y, int Z) { // Your code goes here long long exactsum[X+1][Y+1][Z+1],exactnum[X+1][Y+1][Z+1]; for (int i = 0; i <=X; i++){ for (int j = 0; j <= Y; j++) { for (int k = 0; k <= Z; k++) { exactsum[i][j][k] = 0; exactnum[i][j][k] = 0; } } } long long ans=0; exactnum[0][0][0] = 1LL; for (int i = 0; i <= X; ++i){ for (int j = 0; j <= Y; ++j){ for (int k = 0; k <= Z; ++k) { if (i > 0){ exactsum[i][j][k] += (exactsum[i - 1][j][k] * 10 + 4 * exactnum[i - 1][j][k]) % mod; exactnum[i][j][k] += exactnum[i - 1][j][k] % mod; } if (j > 0) { exactsum[i][j][k] += (exactsum[i][j - 1][k] * 10 + 5 * exactnum[i][j - 1][k]) % mod; exactnum[i][j][k] += exactnum[i][j - 1][k] % mod; } if (k>0){ exactsum[i][j][k] += (exactsum[i][j][k-1] * 10 + 6 * exactnum[i][j][k-1]) % mod; exactnum[i][j][k] += exactnum[i][j][k-1] % mod; } ans+=exactsum[i][j][k]%mod; ans=ans%mod; } } } return ans; } }; ================================================ FILE: GFG/Number Formation/Number Formation.java ================================================ class Solution { public int getSum(int X, int Y, int Z) { // Your code goes here int mod=1000000007; long[][][] exactSum=new long[X+1][Y+1][Z+1]; long[][][] num=new long[X+1][Y+1][Z+1]; num[0][0][0]=1L; long ans=0L; for(int i=0;i<=X;i++){ for(int j=0;j<=Y;j++){ for(int k=0;k<=Z;k++){ if(i>0){ exactSum[i][j][k]+=(exactSum[i-1][j][k]*10 +4*num[i-1][j][k])%mod; num[i][j][k]+=num[i-1][j][k]%mod; } if(j>0){ exactSum[i][j][k]+=(exactSum[i][j-1][k]*10 +5*num[i][j-1][k])%mod; num[i][j][k]+=num[i][j-1][k]%mod; } if(k>0){ exactSum[i][j][k]+=(exactSum[i][j][k-1]*10 +6*num[i][j][k-1])%mod; num[i][j][k]+=num[i][j][k-1]%mod; } ans+=exactSum[i][j][k]%mod; ans%=mod; } } } return (int)ans; } } ================================================ FILE: GFG/Number Formation/README.md ================================================ ## Number Formation Given three integers x, y, and z, the task is to find the sum of all the numbers formed by having 4 at most x times, having 5 at most y times, and having 6 at most z times as a digit. **Note:** Output the sum modulo 109+7. **Example 1:** ``` Input: X = 1, Y = 1, Z = 1 Output: 3675 Explanation: 4 + 5 + 6 + 45 + 54 + 56 + 65 + 46 + 64 + 456 + 465 + 546 + 564 + 645 + 654 = 3675 ``` **Example 2:** ``` Input: X = 0, Y = 0, Z = 0 Output: 0 Explanation: No number can be formed ``` *** **Your Task:** You don't need to read input or print anything. Complete the function **getSum()** which takes X, Y and Z as input parameters and returns the integer value **Expected Time Complexity:** O(X*Y*Z) **Expected Auxiliary Space:** O(X*Y*Z) Constraints: 0 ≤ X, Y, Z ≤ 60 ================================================ FILE: GFG/Number Of Islands/Number Of Islands.cpp ================================================ class Solution { public: //dfs function for finding island void dfs(vector>&v,int l,int i,int j,int n,int m){ if(i>n-1||j>m-1||i<0||j<0){ return; } if(v[i][j]!=l){ return; } // update number v[i][j]+=1; dfs(v,l,i-1,j,n,m); // up dfs(v,l,i+1,j,n,m); // down dfs(v,l,i,j-1,n,m); // left dfs(v,l,i,j+1,n,m); // right } vector numOfIslands(int n, int m, vector> &operators) { int k=operators.size(); //flag int l=1; vector ans; vector> v(n,vector(m,0)); // iterate around the number of operations for(int i=0;i numOfIslands(int rows, int cols, int[][] operators) { //Your code here int[][] mat=new int[rows][cols]; List ans=new ArrayList<>(); UnionFind uf=new UnionFind(rows,cols); int[] dx=new int[]{1,0,-1,0}; int[] dy=new int[]{0,1,0,-1}; for(int[]operator:operators){ int x=operator[0]; int y=operator[1]; mat[x][y]=1; for(int i=0;i<4;i++){ int nx=x+dx[i]; int ny=y+dy[i]; if(nx>=0 && ny>=0 && nx using namespace std; class Solution { public: void dfs(vector>& grid, int i, int j, int xi, int xj, int n, int m, vector&ans){ if(i<0 || j<0 || i>=n || j>=m || grid[i][j]==0) return; ans.push_back(i-xi); ans.push_back(j-xj); grid[i][j] =0; dfs(grid, i-1, j, xi, xj, n,m, ans); dfs(grid, i+1, j, xi, xj, n,m, ans); dfs(grid, i, j-1, xi, xj, n,m, ans); dfs(grid, i, j+1, xi, xj, n,m, ans); } int countDistinctIslands(vector>& grid) { // code here set>st; int n = grid.size(), m= grid[0].size(); for(int i =0; ians; dfs(grid,i,j,i,j,n,m,ans); st.insert(ans); } } } return st.size(); } }; int main() { int t; cin >> t; while (t--) { 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; cout << obj.countDistinctIslands(grid) << endl; } } // Another Approach : /* Instead of changing the original content/values of grid vector, we can also use a different vector storing each visited indexes, while keeping grid vector intact, as in general it's not recommended to change values of original vector. Below is my Code class implementing my logic, I hope it will help, */ class Solution { public: void dfs(int i,int j,int r,int c,vector> &vis, vector> &v,vector>&a){ int n = v.size(), m = v[0].size(); if(r>=n || c>=m || r<0 || c<0 || v[r][c]==0 || vis[r][c]==1) return; a.push_back({i,j}); vis[r][c] = 1; dfs(i+1,j,r+1,c,vis,v,a); dfs(i,j+1,r,c+1,vis,v,a); dfs(i-1,j,r-1,c,vis,v,a); dfs(i,j-1,r,c-1,vis,v,a); } int countDistinctIslands(vector>& grid) { set>> st; vector> vis(grid.size(),vector(grid[0].size(),0)); for(int i=0;i> v; dfs(0,0,i,j,vis,grid,v); if(v.size()>0) st.insert(v); } } } return st.size(); } }; ================================================ FILE: GFG/Number of Distinct Islands/Number of Distinct Islands.py ================================================ import sys class Solution: sys.setrecursionlimit(10**8) def countDistinctIslands(self, grid : List[List[int]]) -> int: ans = set() n=len(grid) m=len(grid[0]) def dfs(r,c,ans): if r<0 or c<0 or r>=n or c>=m or grid[r][c]!=1: return grid[r][c] = 0 dfs(r, c-1, arr) arr.append('R') dfs(r, c+1, arr) arr.append('D') dfs(r+1, c, arr) arr.append('U') dfs(r-1, c, arr) arr.append('L') for i in range(n): for j in range(m): if grid[i][j] == 1: arr = [] dfs(i,j,arr) ans.add(tuple(arr)) return len(ans) ================================================ FILE: GFG/Number of turns in binary tree/Number of turns in binary tree.cpp ================================================ /* This code is contributed by--> - Abhishek Kumar (https://github.com/Abhi2061) - Adarsh Urmaliya (https://github.com/Satellite-system) */ class Solution{ public: // function should return the number of turns required to go from first node to second node int NumberOFTurns(struct Node* root, int first, int second) { // Your code goes here Node *head = lca(root, first, second); int F = countTurns(head, first, ' '); int S = countTurns(head, second, ' '); int ans = F + S; if(head->data != first and head->data != second) ans++; return ans; } //Function to return the lowest common ancestor in a Binary Tree. Node* lca(Node* root ,int n1 ,int n2 ) { //Your code here if(!root) return root; if(root->data == n1 or root->data == n2) return root; Node *Left = lca(root->left, n1, n2); Node *Right = lca(root->right, n1, n2); if(Left and !Right) return Left; else if(!Left and Right) return Right; else if(Left and Right) return root; else return nullptr; } // function should return the minimum number of turn to reach a node. int countTurns(Node* root, int n, char d) { if(!root) return 1e5; if(root->data == n) return 0; int Left = countTurns(root->left, n, 'L'); int Right = countTurns(root->right, n, 'R'); if(d == 'L') Right++; if(d == 'R') Left++; return min(Left, Right); } }; // Another Approach :: // We can use Vector, and store the char as 'L' when we move to left of node in 'R' when me move to right of node, in a common vector, // when we got to find first number, we then store all that data to vector named First, similarily for second number we save to vector named Second, // now in main function we would traverse through, First and Second vector so as to remove common char stored for common Nodes, then after the common // nodes have been filtered, we travese in both vectors separately so as to count number of points when char has been changed from the previous char, as that // would mean a turn from LEFT to RIGHT or from RIGHT to LEFT, also just after removing the common nodes we would check if we have traversed any vector completely, // that would mean that one of the node is ancestor to other, in that case we would not increment an extra for a turn at an ancestor node.. // MY code : class Solution{ public: void traverseHelper(Node* root, int first, int second, vector &FirstSeries, vector &SecondSeries, vector &cmn, int num){ if(!root || num ==2) return; if(root->data==first){ num++; FirstSeries = cmn; } if(root->data==second){ num++; SecondSeries = cmn; } cmn.push_back('L'); traverseHelper(root->left, first, second, FirstSeries, SecondSeries, cmn, num); cmn.pop_back(); if(num==2) return; cmn.push_back('R'); traverseHelper(root->right, first, second, FirstSeries, SecondSeries, cmn, num); cmn.pop_back(); } // function should return the number of turns required to go from first node to second node int NumberOFTurns(struct Node* root, int first, int second) { vector FirstSeries, SecondSeries, cmn; traverseHelper(root, first, second, FirstSeries, SecondSeries, cmn, 0); int i=0; for(; i< min(FirstSeries.size(), SecondSeries.size()); i++){ if(FirstSeries[i] != SecondSeries[i]) break; } int cnt = 0; if(i == FirstSeries.size() && i == SecondSeries.size()) return cnt; // For the case of Different Ancestors if(i> displayContacts(int n, string contact[], string s) { // code here //tried to make it as simple as possible sort(contact,contact+n); set st; for(int i=0;i> ans; for(int j=0;j temp; for(auto it:st){ if(s.substr(0,j+1)==it.substr(0,j+1)) temp.push_back(it); } if(temp.size()==0) temp.push_back("0"); ans.push_back(temp); } return ans; } }; ================================================ FILE: GFG/Phone directory/Phone directory.java ================================================ class Trie{ Map> map; Map next; Trie(){ map=new HashMap<>(); next=new HashMap<>(); } } class Solution{ static ArrayList> displayContacts(int n, String contact[], String s) { // code here ArrayList> ans=new ArrayList<>(); Trie head=new Trie(); //create trie for(String st:contact){ Trie curr=head; for(char c:st.toCharArray()){ curr.map.putIfAbsent(c,new TreeSet<>()); curr.map.get(c).add(st); curr.next.putIfAbsent(c,new Trie()); curr=curr.next.get(c); } } Trie curr=head; for(int i=0;i list=new ArrayList<>(); if(curr.map.containsKey(s.charAt(i))){ for(String str:curr.map.get(s.charAt(i))){ list.add(str); } } if(list.size()==0)list.add("0"); ans.add(list); if(curr.next.containsKey(s.charAt(i))){ curr=curr.next.get(s.charAt(i)); }else{ break; } } while(ans.size()!=s.length()){ ArrayList list=new ArrayList<>(); list.add("0"); ans.add(list); } return ans; } } //Method 2 class Solution{ static class Trie { Trie child[]=new Trie[26]; Boolean word[]=new Boolean[26]; } static ArrayList> displayContacts(int n, String contact[], String s) { // code here ArrayList> res=new ArrayList<>(); Trie head = new Trie(); for(int i=0;i curList=new ArrayList<>(); if(flag==1) { // No string found with prefix curList.add("0"); res.add(curList); continue; } if( cur.word[s.charAt(i)-'a']!=null && cur.word[s.charAt(i)-'a'] == true) { curList.add(new String(sb.toString())); } findAllPrefixes(cur, sb, curList); if(curList.size()>0) // Adding all words which start with prefix 0-i of String s. res.add(curList); else { curList.add("0"); res.add(curList); } } return res; } public static int findAllPrefixes(Trie cur, StringBuilder sb, ArrayList curList) { // Adding all words which start with the preficx from o-i of string s, storing in curList int childVis = -1; for(int i=0;i<26;i++) { if(cur.child[i]!=null && childVis!=i) { sb.append(""+(char)(i+'a')); if(cur.child[i].word[i]!=null && cur.child[i].word[i]==true) { curList.add(new String(sb.toString())); } childVis=findAllPrefixes(cur.child[i], sb, curList); sb.deleteCharAt(sb.length()-1); } } return -1; } } ================================================ FILE: GFG/Primes sum/Primes sum.cpp ================================================ class Solution { public: bool checkPrime(int n) { if(n<2) return false; for(int i=2; i<=sqrt(n); i++) { if(n%i==0) return false; } return true; } string isSumOfTwo(int N){ // code here for(int i=2; i downwardDigonal(int N, vector> A) { // Your code goes here vectorv; for(int i=0;i downwardDigonal(int N, int A[][]) { // code here ArrayList ans=new ArrayList<>(); int row=0; int col=0; while(col=0){ ans.add(A[r][c]); r++; c--; } col++; } col=N-1; row=1; while(row=0){ ans.add(A[r][c]); r++; c--; } row++; } return ans; } } ================================================ FILE: GFG/Print Diagonally/README.md ================================================ ## Print Diagonally Give a **N * N** square matrix **A**, return all the elements of its **anti-diagonals** from top to bottom. **Example 1:** ``` Input: N = 2 A = [[1, 2], [3, 4]] Output: 1 2 3 4 Explanation: ``` ![ScreenShot2022-10-17at9-1665980852](https://user-images.githubusercontent.com/76674591/196438008-83b2851a-b6b9-4a19-949b-06826956a58e.png) ``` Hence, elements will be returned in the order {1, 2, 3, 4}. ``` **Example 2:** ``` Input: N = 3 A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Output: 1 2 4 3 5 7 6 8 9 Explanation: ``` ![ScreenShot2022-10-17at9-1665980941](https://user-images.githubusercontent.com/76674591/196438089-a533157f-3d20-4be3-a631-dcb4fda61cff.png) ``` Hence, elements will be returned in the order {1, 2, 4, 3, 5, 7, 6, 8, 9}. ``` *** **Your Task:** You don't need to read input or print anything. Your task is to complete the function **downwardDigonal()** which takes an integer N and a 2D matrix A[ ][ ] as input parameters and returns the list of all elements of its anti-diagonals from top to bottom. **Expected Time Complexity:** O(N*N) **Expected Auxillary Space:** O(N*N) Constraints: 1 ≤ N, M ≤ 103 0 ≤ A[i][j] ≤ 106 ================================================ FILE: GFG/Print leaf nodes from preorder traversal of BST/Print leaf nodes from preorder traversal of BST.cpp ================================================ class Solution { public: vector leafNodes(int a[],int n) { // code here stack s; vector vec; s.push(a[0]); for(int i=1;i1){ vec.push_back(ln); } } s.push(a[i]); } if(!s.empty()){ vec.push_back(s.top()); } return vec; } }; ================================================ FILE: GFG/Print leaf nodes from preorder traversal of BST/Print leaf nodes from preorder traversal of BST.java ================================================ class Solution { public int[] leafNodes(int arr[], int N) { // code here ArrayList ans=new ArrayList<>(); Stack st=new Stack<>(); st.push(arr[0]); for(int i=1;i=2){ ans.add(temp); } } } ans.add(st.peek()); int[] res=new int[ans.size()]; int idx=0; for(int i:ans){ res[idx++]=i; } return res; } } ================================================ FILE: GFG/Print leaf nodes from preorder traversal of BST/README.md ================================================ ## Print leaf nodes from preorder traversal of BST Given a preorder traversal of a BST, find the leaf nodes of the tree without building the tree. **Example 1:** ``` Input: N = 2 arr = {2,1} Output: {1} Explaination: 1 is the only leaf node. ``` **Example 2:** ``` Input: N = 3 Arr = {3, 2, 4} Output: {2, 4} Explaination: 2, 4 are the leaf nodes. ``` *** **Your Task:** You don't need to read input or print anything. Your task is to complete the function **leafNodes()** which takes the array arr[] and its size N as input parameters and returns the leaf nodes of the tree. **Expected Time Complexity:** O(N) **Expected Auxiliary Space:** O(N) **Constraints:** 1 ≤ N ≤ 103 1 ≤ arr[i] ≤ 103 ================================================ FILE: GFG/Queries on a matrix/Queries on a matrix hard s25 gfg.cpp ================================================ #include using namespace std; class Solution { public: vector> solveQueries(int n, vector> Queries) { // Code here vector>mat(n, vector (n,0)); for(auto e: Queries){ int a,b,c,d; a = e[0]; b=e[1]; c=e[2]; d=e[3]; mat[a][b] +=1; if(c > tc; while (tc--) { int n, q; cin >> n >> q; vector> Queries; for (int i = 0; i < q; i++) { vector cur(4); for (int j = 0; j < 4; j++) cin >> cur[j]; Queries.push_back(cur); } Solution obj; vector> ans = obj.solveQueries(n, Queries); for (auto i : ans) { for (auto j : i) cout << j << " "; cout << "\n"; } } return 0; } // } Driver Code Ends ================================================ FILE: GFG/Rearrange Array Alternately/Rearrange Array Alternately.java ================================================ class Solution{ // temp: input array // n: size of array //Function to rearrange the array elements alternately. public static void rearrange(long arr[], int n){ // Your code here int l=0; int r=n-1; long mod=1000001; for(int i=0;i> &vis,int n,int m,vector> &grid) { vis[r][c]=1; for(int i=0;i<4;i++){ int nr=r+delrow[i]; int nc=c+delcol[i]; if(nr>=0 && nr=0 && nc> fill(int n, int m, vector> grid) { vector> vis(n,vector(m,0)); for(int j=0;j findLeastGreater(vector& arr, int n) { vector v; sets; for(int i=n-1;i>=0;i--) { auto up=s.upper_bound(arr[i]); //finds the nearest greater value if(up==s.end()) //if not find nearest grater value v.push_back(-1); else v.push_back(*up); s.insert(arr[i]); //insert ans in array } reverse(v.begin(),v.end()); //reverse it cause we itarate to last return v; } }; ================================================ FILE: GFG/Replace every element with the least greater element on its right/Replace every element with the least greater element on its right.java ================================================ class Solution { public static ArrayList findLeastGreater(int n, int[] arr) { // code here TreeSet set=new TreeSet<>(); ArrayList ans =new ArrayList<>(); for(int i=n-1;i>=0;i--){ set.add(arr[i]); if(set.higher(arr[i])==null)ans.add(-1); else ans.add(set.higher(arr[i])); } Collections.reverse(ans); return ans; } } // second Method using Binary Search Tree class Solution { static class Node { int val; Node left; Node right; Node(int val) { this.val=val; this.left=null; this.right=null; } } public static ArrayList findLeastGreater(int n, int[] arr) { Node head = null; ArrayList res=new ArrayList<>(); for(int i=arr.length-1;i>=0;i--) { if(head==null) { head=new Node(arr[i]); } else { Node prev=addNodeInBST(arr[i], head, head); if(prev.val>arr[i]) { prev.left=new Node(arr[i]); } else { prev.right=new Node(arr[i]); } } int max[]=new int[1]; max[0]=Integer.MAX_VALUE; leastGreater(head, max, arr[i]); if(max[0]==Integer.MAX_VALUE) { arr[i]=-1; } else { arr[i]= max[0]; } } for(int i=0;ival) { return addNodeInBST(val, cur.left, cur); } else { return addNodeInBST(val, cur.right, cur); } } public static void leastGreater(Node head, int []max, int value) { if(head==null) { return ; } if(head.val>value) { max[0]=Math.min(max[0], head.val); } if(head.val>value) { leastGreater(head.left, max, value); } else { leastGreater(head.right, max, value); } } } ================================================ FILE: GFG/Reverse Spiral Form of Matrix/Reverse Spiral Form of Matrix.cpp ================================================ class Solution { public: vector reverseSpiral(int R, int C, vector>&a) { // code here vectorans; int top=0,left=0,right=C-1,bottom=R-1; while(top<=bottom and left<=right) { // top row if(top<=bottom) { for(int i=left;i<=right;i++) ans.push_back(a[top][i]); top++; } // right column if(left<=right){ for(int i=top;i<=bottom;i++) { ans.push_back(a[i][right]); } right--; } //bottom row (reverse order) if(top<=bottom) { for(int i=right;i>=left;i--) { ans.push_back(a[bottom][i]); } bottom--; } //left column (reverse order) if(left<=right) { for(int i=bottom;i>=top;i--) { ans.push_back(a[i][left]); } left++; } } // reverse ans vector reverse(ans.begin(),ans.end()); return ans; } }; ================================================ FILE: GFG/Reverse Spiral Form of Matrix/Reverse Spiral Form of Matrix.java ================================================ class Solution { public int[] reverseSpiral(int R, int C, int[][] a) { // code here int[] ans=new int[R*C]; int idx=R*C-1; int up=0; int down=a.length-1; int left=0; int right=a[0].length-1; while(idx>=0){ //upper row for(int i=left;i<=right && idx>=0;i++){ ans[idx--]=a[up][i]; } up++; //last col for(int i=up;i<=down && idx>=0;i++){ ans[idx--]=a[i][right]; } right--; //lower row for(int i=right;i>=left && idx>=0;i--){ ans[idx--]=a[down][i]; } down--; for(int i=down;i>=up && idx>=0;i--){ ans[idx--]=a[i][left]; } left++; } return ans; } } ================================================ FILE: GFG/Satisfy the equation/Satisfy the equation.java ================================================ class Pair{ int x; int y; Pair(int a,int b){ x=a; y=b; } } // 1 2 4 5==curr // 0 3 4 5 ==ans class Solution { static int[] satisfyEqn(int[] A, int N) { // code here int ans[]=new int[4]; Arrays.fill(ans,Integer.MAX_VALUE); Map map=new HashMap<>();//key-> sum, values-> indices for(int i=0;icurr[idx]){ replace=true; break; }else if(ans[idx] map=new HashMap<>(); for(int i=0;imax){ max=curr; ans=new StringBuilder(temp); } if(curr<0){ curr=0; temp=new StringBuilder(); } } return ans.toString(); } } //Approach 2 class Solution{ static String maxSum(String w,char x[],int b[], int n){ int i= 0; int j=0; int max=Integer.MIN_VALUE; int res[]=new int[52]; for(int k=0;k<52;k++) { res[k]=2000; } for(int k=0;k='a' && x[k]<='z') res[x[k]-'a']=b[k]; else res[x[k]-'A'+26]=b[k]; } for(int k=0;k<26;k++) { if(res[k]==2000) { res[k]=97+k; } } for(int k=26;k<52;k++) { if(res[k]==2000) { res[k]=65+k-26; } } int count =0; int maxI=0; int maxJ=0; while(j='a' && w.charAt(j)<='z') count+=res[w.charAt(j)-'a']; else count+=res[w.charAt(j)-'A'+26]; if(count>max) { max=count; maxI=i; maxJ=j; } if(count<0) { count=0; i=j+1; } j+=1; } return w.substring(maxI, maxJ+1); } } ================================================ FILE: GFG/Search Pattern (KMP-Algorithm)/Search Pattern (KMP-Algorithm).java ================================================ class Solution { ArrayList search(String pat, String txt) { int pn=pat.length(), tn=txt.length(); int lps[]=new int[pn]; fill(lps,pat,pn); ArrayList list=new ArrayList<>(); int j=0; for(int i=0;i search(String pat, String S) { int total=26, mod=101; ArrayList list=new ArrayList<>(); int p=0, s=0, sn=S.length(), pn=pat.length(); // calculate most significant position // (we will need this when we have to remove most signicant position value) // The value of h would be "pow(d, M-1)%q" int h = 1; for (int i = 0; i < pn-1; i++) h = (h*total)%mod; // System.out.println(h); for(int i=0;i=n || j>=m) return false; return true; } int shortestPath(vector> &grid, pair source, pair destination){ if(source==destination){ return 0; } int n=grid.size(); int m =grid[0].size(); queue,int>>q; q.push({source,0}); grid[source.first][source.second]=0; while(!q.empty()){ int row = q.front().first.first; int col = q.front().first.second; int dis = q.front().second; q.pop(); if(row==destination.first && col==destination.second){ return dis; } if(isSafe(row+1,col,n,m) && grid[row+1][col]==1){ q.push({{row+1,col},dis+1}); grid[row+1][col]=0; } if(isSafe(row-1,col,n,m) && grid[row-1][col]==1){ q.push({{row-1,col},dis+1}); grid[row-1][col]=0; } if(isSafe(row,col+1,n,m) && grid[row][col+1]==1){ q.push({{row,col+1},dis+1}); grid[row][col+1]=0; } if(isSafe(row,col-1,n,m) && grid[row][col-1]==1){ q.push({{row,col-1},dis+1}); grid[row][col-1]=0; } } return -1; } }; ================================================ FILE: GFG/Shortest Distance in a Binary Maze/Shortest Distance in a Binary Maze.java ================================================ class Solution { class Pair{ int x; int y; Pair(int i,int j){ x=i; y=j; } } int shortestPath(int[][] grid, int[] src, int[] des) { Queue q=new LinkedList<>(); q.add(new Pair(src[0],src[1])); grid[src[0]][src[1]]=0; int dis=0; while(!q.isEmpty()){ int sz=q.size(); while(sz-->0){ Pair curr=q.remove(); int i=curr.x; int j=curr.y; if(i==des[0] && j==des[1])return dis; if(i>0 && grid[i-1][j]==1){ grid[i-1][j]=0; q.add(new Pair(i-1,j)); } if(j>0 && grid[i][j-1]==1){ grid[i][j-1]=0; q.add(new Pair(i,j-1)); } if(i q=new LinkedList<>(); visited[source[0]][source[1]]=1; if(grid[source[0]][source[1]] == 0) return -1; q.add(new Pair(source[0], source[1])); int ans=0; while(!q.isEmpty()) { int n=q.size(); while(n>0) { Pair p=q.poll(); if(p.i==destination[0] && p.j==destination[1]) return ans; Pair up=getPair(p.i, p.j+1, grid, visited); Pair down=getPair(p.i, p.j-1, grid, visited); Pair left=getPair(p.i-1, p.j, grid, visited); Pair right=getPair(p.i+1, p.j, grid, visited); if(up!=null) q.add(up); if(down!=null) q.add(down); if(left!=null) q.add(left); if(right!=null) q.add(right); n-=1; } ans+=1; } return -1; } public Pair getPair(int x, int y, int[][] grid, int [][]visited) { if(x<0 || y<0 || x>=grid.length || y>=grid[0].length) return null; if(grid[x][y]==0 || visited[x][y]==1) { return null; } visited[x][y]=1; return new Pair(x, y); } } ================================================ FILE: GFG/Shortest Path by Removing K walls/Shortest Path by Removing K walls.java ================================================ class Solution { static int shotestPath(int[][] mat, int n, int m, int k) { // code here int[][]dirs={{1,0},{0,1},{0,-1},{-1,0}}; Queue q=new LinkedList<>(); q.add(new int[]{0,0,k}); boolean[][][]vis=new boolean[n][m][k+1]; vis[0][0][k]=true; int dis=0; while(!q.isEmpty()){ int sz=q.size(); while(sz-->0){ int[]curr=q.remove(); if(curr[0]==n-1 && curr[1]==m-1)return dis; for(int[]d:dirs){ int i=curr[0]+d[0]; int j=curr[1]+d[1]; int obs=curr[2]; if(i=0 && j>=0){ if(mat[i][j]==0 && !vis[i][j][obs]){ q.add(new int[]{i,j,obs}); vis[i][j][obs]=true; }else if(mat[i][j]==1 && obs>0 && !vis[i][j][obs-1]){ q.add(new int[]{i,j,obs-1}); vis[i][j][obs-1]=true; } } } } dis++; } return -1; } }; ================================================ FILE: GFG/Shortest Prime Path/Shortest Prime Path.java ================================================ class Solution { boolean[] prime; Solution() { prime =new boolean[10000]; Arrays.fill(prime,true); prime[0]=prime[1]=false; for(int i=2;i<10000;i++){ if(!prime[i])continue; for(int j=2;i*j<10000;j++)prime[i*j]=false; } // Every index of prime stores zero or one // If prime[i] is zero means i is not a prime // If prime[i] is one means i is a prime } public int shortestPath(int Num1,int Num2){ // Complete this function using prime array boolean[]vis=new boolean[10000]; Queue q=new LinkedList<>(); q.add(new int[]{Num1,0}); vis[Num1]=true; while(!q.isEmpty()){ int[] curr=q.remove(); if(curr[0]==Num2)return curr[1]; char[] arr= Integer.toString(curr[0]).toCharArray(); for(int i=0;i<4;i++){ for(char ch='0';ch<='9';ch++){ char prevChar = arr[i]; arr[i]=ch; int newNum = Integer.parseInt(new String(arr)); if(!vis[newNum] && prime[newNum] && newNum>=1000){ vis[newNum]=true; q.add(new int[]{newNum,curr[1]+1}); } arr[i]=prevChar; } } } return -1; } } ================================================ FILE: GFG/Shreyansh and his bits/Shreyansh and his bits.java ================================================ class Solution{ long[][]dp; long count(long n) { dp=new long[64][64]; for(int i=0;i<64;i++){ Arrays.fill(dp[i],-1); } int ones=0; int positions=0; long ans=0; while(n>0){ if((n&1)==1){ ones++; ans+=nCr(positions,ones); } n=n>>1; positions++; } return ans; } long nCr(int n,int r){ if(r>n){ return 0; } if(r==0 || r==n)return 1; if(dp[n][r]!=-1)return dp[n][r]; return dp[n][r]=nCr(n-1,r-1)+nCr(n-1,r); } } ================================================ FILE: GFG/Single valued subtree/Single valued subtree.java ================================================ class Solution { int ans; public int singlevalued(Node root) { //code here ans=0; dfs(root); return ans; } Integer dfs(Node root){ if(root==null)return null; Integer lefty=dfs(root.left); Integer righty=dfs(root.right); if(lefty!=null && righty!=null && lefty==righty && lefty==root.data){ ans++; return righty; }else if(root.left==null && root.right==null){ ans++; return root.data; }else if(root.left==null && righty!=null && righty==root.data){ ans++; return root.data; }else if(root.right==null && lefty!=null && lefty==root.data){ ans++; return root.data; } return null; } } ================================================ FILE: GFG/Sort an array of 0s, 1s and 2s/Sort an array of 0s, 1s and 2s.java ================================================ class Solution { public static void sort012(int a[], int n) { // code here int zero=0; int one=0; int two=0; for(int i:a){ if(i==0){ zero++; }else if(i==1){ one++; }else{ two++; } } int idx=0; while(zero>0){ zero--; a[idx++]=0; } while(one-->0){ a[idx]=1; idx++; } while(two-->0){ a[idx++]=2; } } } ================================================ FILE: GFG/Sort an array of 0s, 1s and 2s/Sort an array of 0s,1s and 2s s29.cpp ================================================ #include using namespace std; class Solution { public: void sort012(int a[], int n) { // code here int zero =0, one =0, two =n-1; while(one<=two){ if(a[one]==0){ swap(a[one] ,a[zero]); zero++, one++; }else if(a[one]==2){ swap(a[one], a[two]); two--; }else one++; } } }; 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> &matrix, int m, int n, int k) { // Your code goes here vector v; int left = 0, right = n-1, top = 0, bottom = m-1; int direction = 1; while(left <= right and top <= bottom){ if(direction == 1){ // ---> for(int i=left;i<=right;i++) v.push_back(matrix[top][i]); direction = 2; top++; } else if(direction == 2){ // downwords for(int i=top;i<=bottom;i++) v.push_back(matrix[i][right]); direction = 3; right--; } else if(direction == 3){ // <---- for(int i=right;i>=left;--i) v.push_back(matrix[bottom][i]); direction = 4; bottom--; }else if(direction == 4){ // upwards for(int i=bottom;i>=top;--i) v.push_back(matrix[i][left]); direction = 1; left++; } } return v[k-1]; } }; ================================================ FILE: GFG/Split Array Largest Sum/Split Array Largest Sum.java ================================================ class Solution { static int splitArray(int[] arr , int N, int K) { // code here int l=0; int h=0; int ans=0; for(int i:arr){ l=Math.max(l,i); h+=i; } while(l<=h){ int mid=l+(h-l)/2; if(isPossible(mid,arr,K)){ ans=mid; h=mid-1; }else{ l=mid+1; } } return ans; } static boolean isPossible(int maxSum,int[]arr,int k){ int cnt=0; int currSum=0; for(int i:arr){ if(currSum+i>maxSum){ cnt++; currSum=i; }else{ currSum+=i; } } if(currSum<=maxSum)cnt++; return cnt<=k; } }; ================================================ FILE: GFG/Stepping Numbers/README.md ================================================ ## Stepping Numbers A number is called a stepping number if all adjacent digits have an absolute difference of 1, e.g. '321' is a Stepping Number while 421 is not. Given two integers **n** and **m**, find the count of all the stepping numbers in the range [n, m]. **Example 1:** ``` Input: n = 0, m = 21 Output: 13 Explanation: Stepping no's are 0 1 2 3 4 5 6 7 8 9 10 12 21 ``` **Example 2:** ``` Input: n = 10, m = 15 Output: 2 Explanation: Stepping no's are 10, 12 ``` *** **Your Task:** You don't need to read input or print anything. Your task is to complete the function **steppingNumbers()** which takes the integer n and integer m as input parameters and returns the number of stepping numbers in the range between n and m. **Expected Time Complexity:** O(log(M)) **Expected Auxiliary Space:** O(SN) where SN is the number of stepping numbers in the range **Constraints:** 0 ≤ N < M ≤ 10^7 ================================================ FILE: GFG/Stepping Numbers/Stepping Numbers.cpp ================================================ class Solution{ public: unordered_map mp; public: void dfs(int n, int m) { if (n > m) return; if (mp.find(n) != mp.end()) return; mp[n] = 1; if (n % 10 == 0) dfs(n * 10 + 1, m); else if (n % 10 == 9) dfs(n * 10 + 8, m); else { dfs(n * 10 + (n % 10) - 1, m); dfs(n * 10 + (n % 10) + 1, m); } } int steppingNumbers(int n, int m) { // Code Here mp.clear(); for (int i = 0; i <= 9; i++) dfs(i, m); int ans = 0; for (auto i : mp) ans += (i.first >= n and i.second <= m); return ans; } }; ================================================ FILE: GFG/Stepping Numbers/Stepping Numbers.java ================================================ class Solution{ int steppingNumbers(int n, int m){ // code here int ans=0; if(n==0)ans++; Queue q=new LinkedList<>(); for(int i=1;i<=9;i++){ q.add(i); } while(q.size()>0){ int sz=q.size(); while(sz-->0){ int ele=q.remove(); if(ele>=n && ele<=m)ans++; int lastDigit=ele%10; if(lastDigit==9){ int next=ele*10+8; if(next<=m)q.add(next); }else if(lastDigit==0){ int next=ele*10+1; if(next<=m)q.add(next); }else{ int smaller=ele*10+(lastDigit-1); if(smaller<=m)q.add(smaller); int greater=ele*10+(lastDigit+1); if(greater<=m)q.add(greater); } } } return ans; } } ================================================ FILE: GFG/Substrings of length k with k-1 distinct elements/README.md ================================================ ## Substrings of length k with k-1 distinct elements Given a String **S** and an integer **K**. Find the count of all substrings of length **K** which have exactly **K-1** distinct characters. ## Example 1: ``` Input: S = "abcc" K = 2 Output: 1 Explanation: Possible substrings of length K = 2 are ab : 2 distinct characters bc : 2 distinct characters cc : 1 distinct character Only one valid substring exists {"cc"}. ``` ## Example 2: ``` Input: S = "aabab" K = 3 Output : 3 Explanation: Possible substrings of length K = 3 are aab : 2 distinct characters aba : 2 distinct characters bab : 2 distinct characters. All of these Substrings are a possible answer, so the count is 3. ``` **Your Task:** You don't need to read input or print anything. Your task is to complete the function **countOfSubstrings()** which takes a String **S** and an integer **K** as input and returns the count of substrings of length **K** having **K-1** distinct characters. **Expected Time Complexity:** O(|S|) **Expected Auxiliary Space:** O(constant) **Constraints:** 1 ≤ K ≤ |S| ≤ 105 ================================================ FILE: GFG/Substrings of length k with k-1 distinct elements/Substrings of length k with k-1 distinct elements.cpp ================================================ }; ================================================ FILE: GFG/Substrings of length k with k-1 distinct elements/Substrings of length k with k-1 distinct elements.java ================================================ class Solution { static int countOfSubstrings(String s, int k) { // code here int ans=0; int[]freq=new int[26]; for(int i=0;i0)cnt++; } int i=0; int j=k; while(j<=s.length()){ if(cnt==k-1){ ans++; } if(j==s.length())break; freq[s.charAt(i)-'a']--; if(freq[s.charAt(i)-'a']==0)cnt--; freq[s.charAt(j)-'a']++; if(freq[s.charAt(j)-'a']==1)cnt++; i++; j++; } return ans; } }; ================================================ FILE: GFG/Sum of Beauty of All Substrings/Sum of Beauty of All Substrings.java ================================================ class Solution { public static int beautySum(String s) { // code here int ans=0; int n=s.length(); for(int size=3;size<=n;size++){ int i=0; int j=size; int[]freq=new int[26]; for(int k=i;kmp; for(int i = 0 ; i < n ; i++){ mp[arr[i]]++; } int cnt = 0; for(auto x : mp){ cnt+=x.second; } if(mp['R']%2==0 and mp['B']%2==0 and mp['G']%2==0){ return 2; } else if(mp['R']%2==1 and mp['B']%2==1 and mp['G']%2==1){ return 2; } else{ return 1; } } }; ================================================ FILE: GFG/The Smurfs/The Smurfs.java ================================================ class Solution{ static int minFind(int n, String a[]){ // code here int r=0; int g=0; int b=0; for(int i=0;i using namespace std; class Solution { public: int numsGame(int N) { // code here // as per example tom wins in every even number, if(N%2==0) return 1; else return 0; } }; int main() { int t; cin >> t; while (t--) { int N; cin>>N; Solution ob; cout << ob.numsGame(N) << endl; } return 0; } ================================================ FILE: GFG/Tom and jerry/Tom and Jerry.java ================================================ class Solution { static int numsGame(int N) { // code here if(N%2==0)return 1; return 0; } }; ================================================ FILE: GFG/Tom and jerry/Tom and Jerry.py ================================================ class Solution: def numsGame(self, N): # code here if(N%2==0): return 1 else: return 0 ================================================ FILE: GFG/Transform to Sum Tree/Transform to Sum Tree.java ================================================ class Solution{ public void toSumTree(Node root){ //add code here. dfs(root); } int dfs(Node root){ if(root==null)return 0; int val = root.data; int lefty=dfs(root.left); int righty=dfs(root.right); root.data=lefty+righty; return val + lefty + righty; } } ================================================ FILE: GFG/Two numbers with odd occurrences/README.md ================================================ ## Two numbers with odd occurrences Given an unsorted array, Arr[] of size N and that contains even number of occurrences for all numbers except two numbers. Find the two numbers in decreasing order which has odd occurrences. **Example 1:** ``` Input: N = 8 Arr = {4, 2, 4, 5, 2, 3, 3, 1} Output: {5, 1} Explaination: 5 and 1 have odd occurrences. ``` **Example 2:** ``` Input: N = 8 Arr = {1 7 5 7 5 4 7 4} Output: {7, 1} Explaination: 7 and 1 have odd occurrences. ``` *** **Your Task:** You don't need to read input or print anything. Your task is to complete the function **twoOddNum()** which takes the array Arr[] and its size N as input parameters and returns the two numbers in decreasing order which have odd occurrences. **Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 2 ≤ N ≤ 106 1 ≤ Arri ≤ 1012 ================================================ FILE: GFG/Two numbers with odd occurrences/Two numbers with odd occurrences.cpp ================================================ class Solution{ public: vector twoOddNum(long long int Arr[], long long int N) { // code here vector< long long int> v; long long int res=0,x=0,count=0,b=0; for(long long int i=0;i> UniquePartitions(int n) { // Code here ArrayList> ans=new ArrayList<>(); ArrayList curr=new ArrayList<>(); int idx=n-1; int[]arr=new int[n]; for(int i=0;i> ans,ArrayList curr, int idx,int n,int[]arr){ if(idx<0 || n<0)return; curr.add(arr[idx]); if(n-arr[idx]==0){ ans.add(new ArrayList<>(curr)); } dfs(ans,curr,idx,n-arr[idx],arr); curr.remove(curr.size()-1); dfs(ans,curr,idx-1,n,arr); } } ================================================ FILE: GFG/Wine Buying and Selling/Wine Buying and Selling.java ================================================ //{ Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; public class GFG { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T>0) { int N = sc.nextInt(); int arr[] = new int[N]; for(int i=0; i q=new LinkedList<>(); for(int i=0;i0)q.add(new int[]{i,arr[i]}); } int i=0; long ans=0l; while(!q.isEmpty()){ while(i0)i++; int sell=Math.abs(arr[i]); while(sell>0){ int buy=q.peek()[1]; int pos=q.peek()[0]; if(sell>=buy){ ans+=(Math.abs(i-pos)*buy); sell-=buy; q.remove(); }else{ ans+=(Math.abs(i-pos)*sell); q.peek()[1]=buy-sell; sell=0; } } i++; } return ans; //Method 2 ArrayList positive=new ArrayList<>(); ArrayList negative=new ArrayList<>(); for(int i=0;i=0) { positive.add(i); } else { negative.add(i); } } long ans=0; int neg=0; int i=0; while(i=Math.abs(Arr[negative.get(neg)])) { long diff=Math.abs(positive.get(i)-negative.get(neg)); long sum=-1*Arr[negative.get(neg)]; Arr[positive.get(i)]= Arr[positive.get(i)]+Arr[negative.get(neg)]; ans+=sum*diff; neg+=1; } else { long diff=Math.abs(positive.get(i)-negative.get(neg)); long sum=Arr[positive.get(i)]; Arr[negative.get(neg)]= Arr[negative.get(neg)]+Arr[positive.get(i)]; ans+=sum*diff; i+=1; } } return ans; } } //{ Driver Code Starts. // } Driver Code Ends //{ Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; public class GFG { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T>0) { int N = sc.nextInt(); int arr[] = new int[N]; for(int i=0; i map=new HashMap<>(); map.put(0L,1L); long sum=0; long ans=0; for(long i:arr){ sum+=i; if(map.containsKey(sum)){ ans+=map.get(sum); } map.put(sum,map.getOrDefault(sum,0L)+1); } return ans; } } ================================================ FILE: GFG/k-th smallest element in BST/k-th smallest element in BST.java ================================================ class Solution { // Return the Kth smallest element in the given BST public int KthSmallestElement(Node root, int k) { // Write your code here Node curr=root; int count=0; int ans=-1; while(curr!=null){ if(curr.left==null){ count++; if(count==k)return curr.data; curr=curr.right; }else{ Node leftSubtree=curr.left; while(leftSubtree.right!=null && leftSubtree.right!=curr){ leftSubtree=leftSubtree.right; } if(leftSubtree.right==null){ leftSubtree.right=curr; curr=curr.left; }else{ leftSubtree.right=null; count++; if(count==k)return curr.data; curr=curr.right; } } } return ans; } } ================================================ FILE: GFG_Find_all_distinct_subset_(or subsequence ================================================ class Solution{ public: vector DistinctSum(vectornums){ // tabulation - bottom up approach - used , it is faster than memoization vectorres; int sum =0, m= nums.size(); for(auto n : nums) sum+=n; vector>dp_tab(m+1, vector(sum+1)); for(int i=0; i<=m;i++){ for(int j =0; j<=sum; j++){ if(j==0) dp_tab[i][j] = true; else if(i==0) dp_tab[i][j] = false; else if(j>=nums[i-1]) dp_tab[i][j] = dp_tab[i-1][j-nums[i-1]] || dp_tab[i-1][j]; else dp_tab[i][j] = dp_tab[i-1][j]; } } for(int j =0; j<=sum; j++){ for(int i =0; i<=m; i++){ if(dp_tab[i][j]){ res.push_back(j); break; } } } return res; // TC: O(n*sum), SC: O(n*sum) } }; ================================================ FILE: Game with nos ================================================ int* game_with_number(int arr[], int n) { // Complete the function for(int i=1;i= 0 ? start : -1; } } ================================================ FILE: Geek and Number String s23 med.cpp ================================================ #include using namespace std; class Solution{ public: int minLength(string s, int n) { // code here vectorv={"12","21","34","43","56","65","78","87","09","90"}; int n1=n; stackst; for(int i=0;i1) { string temp=""; char a=st.top(); st.pop(); char b=st.top(); st.pop(); temp+=a; temp+=b; if(find(v.begin(),v.end(),temp)==v.end()) { st.push(b); st.push(a); } } } return st.size(); } }; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while(t--) { int n; cin >> n; string s; cin >> s; Solution obj; cout << obj.minLength(s, n) << "\n"; } return 0; } ================================================ FILE: Geek and Number String.cpp ================================================ class Solution{ public: int minLength(string s, int n) { // code here stack S; char arr[10] = {'9','2','1','4','3','6','5','8','7','0'}; for(char it : s) { if(!S.empty() and arr[S.top()-'0'] == it) S.pop(); else S.push(it); } return S.size(); } }; ================================================ FILE: Geek and Number String.java ================================================ ======= public int minLength(String s, int n) { // code here Stackst=new Stack<>(); int pair[]=new int[]{9,2,1,4,3,6,5,8,7,0}; for(char ch:s.toCharArray()){ int key=ch-'0'; if(st.size()==0){ st.push(key); }else{ if(st.peek()==pair[key]){ st.pop(); }else{ st.push(key); } } } return st.size(); } } Approach 2: class Solution { public int minLength(String s1, int n) { Stackstack=new Stack(); for(int i=0;i 255) return false; temp.clear(); count++; } else temp.push_back(op[i]); } if(temp[0] == '0') { for(int i=1; i &ans) { if(ip.size() == 0) { if(isValid(op)) ans.push_back(op); return; } if(op.size() == 0) { op.push_back(ip[0]); ip.erase(ip.begin()+0); } if(op[op.size()-1] == '.') { string opt = op + ip[0]; ip.erase(ip.begin()+0); solve(ip,opt,ans); } else { string op1 = op + '.'; solve(ip,op1,ans); string op2 = op + ip[0]; ip.erase(ip.begin()+0); solve(ip,op2,ans); } } vector genIp(string &s) { vector ans; if(s.size() < 4) ans.push_back("-1"); else { string op = ""; solve(s,op,ans); if(ans.size() == 0) ans.push_back("-1"); } return ans; } }; // Another approach // class Solution{ // public: // vector ans; // bool isValidIp(string &s) // { // string temp = ""; // for(int i=0; i 1 and temp[0] == '0')) // return false; // if(stoll(temp) > 255) // return false; // temp = ""; // } // } // if(temp.empty() or (temp.length() > 1 and temp[0] == '0')) // return false; // if(stoll(temp) > 255) // return false; // return true; // } // void solve(string &s, int i, int cnt) // { // if(cnt == 3) // { // if(isValidIp(s)) // ans.push_back(s); // return; // } // for(int p=i+1; p genIp(string &s) { // // Your code here // ans.clear(); // if(s.length() >= 4 and s.length() <= 12) // solve(s, 0, 0); // if(ans.empty()) // ans.push_back({"-1"}); // return ans; // } // }; ================================================ FILE: Generate IP Addresses.java ================================================ class Solution { public ArrayList genIp(String s) { // code here ArrayList ans=new ArrayList<>(); int n=s.length(); if(n>12){ ans.add("-1"); return ans; } for(int i=1;i3 || (s.charAt(0)=='0' && n>1) || Integer.parseInt(s)>255)return false; return true; } } ================================================ FILE: Generate IP Addresses.py ================================================ class Solution: def genIp(self, s): n = len(s) arr = set() if len(s)<4: return [] for i in range(1, n): if int(s[:i]) > 256 or str(int(s[:i])) != s[:i]: continue for j in range(i+1, n): if int(s[i:j]) > 256 or str(int(s[i:j])) != s[i:j]: continue for k in range(j+1, n): if int(s[j:k]) > 256 or str(int(s[j:k])) != s[j:k]: continue if int(s[k:]) > 256 or str(int(s[k:])) != s[k:]: continue ipAdd = s[:i] + "." + s[i:j] + "." + s[j:k]+ "." + s[k:] arr.add(ipAdd) return list(arr) ================================================ FILE: Generate all Parentheses II.java ================================================ public class Solution { private ArrayList res; public ArrayList generateParenthesis(int A) { res = new ArrayList<>(); StringBuilder str = new StringBuilder(); rec(0, 0, 0, str, A); return res; } public void rec(int leftCount, int rightCount, int index, StringBuilder str, int n) { if (leftCount > n || rightCount > n)return; if (rightCount > leftCount)return; if (index == 2 * n) { res.add(str.toString()); return; } str.append('('); rec(leftCount + 1, rightCount, index + 1, str, n); str.deleteCharAt(str.length() - 1); str.append(')'); rec(leftCount, rightCount + 1, index + 1, str, n); str.deleteCharAt(str.length() - 1); } } ================================================ FILE: Get min at pop.java ================================================ class GetMin { //Function to push all the elements into the stack. public static Stack _push(int arr[],int n) { // your code here Stack s=new Stack<>(); s.push(arr[0]); for(int i=1;is) { // your code here while(!s.isEmpty()){ System.out.print(s.pop()+" "); } } } ================================================ FILE: Greater of Lesser.java ================================================ public class Solution { public int solve(ArrayList A, ArrayList B, int C) { int i=0; int j=0; for(int num:A){ if(num>C)i++; } for(int num:B){ if(nummax){ ans++; max=A[i]; } } return ans; } } ================================================ FILE: Hamiltonian Path - GFG/README.md ================================================ # Hamiltonian Path ## Medium

A Hamiltonian path, is a path in an undirected graph that visits each vertex exactly once. Given an undirected graph, the task is to check if a Hamiltonian path is present in it or not.

Example 1:

Input:
N = 4, M = 4
Edges[][]= { {1,2}, {2,3}, {3,4}, {2,4} }
Output:
1 
Explanation: 
There is a hamiltonian path: 
1 -> 2 -> 3 -> 4 

Example 2:

Input:
N = 4, M = 3 
Edges[][] = { {1,2}, {2,3}, {2,4} } 
Output: 
0 
Explanation: 
It can be proved that there is no 
hamiltonian path in the given graph

Your task:
You don't need to read input or print anything. Your task is to complete the function check() which takes the (the number of vertices), M (Number of edges) and the list of Edges[][] (where Edges[i] denotes the undirected Edge between vertices Edge[i][0] and Edges[i][1] ) as input parameter and returns true (boolean value) if the graph contains Hamiltonian path,otherwise returns false


Expected Time Complexity: O(N!).
Expected Auxiliary Space: O(N+M).


Constraints:
1 ≤ N ≤ 10
1 ≤ M ≤ 15
Size of Edges[i] is 2
1 ≤ Edges[i][0],Edges[i][1] ≤ N

================================================ FILE: Hamiltonian Path - GFG/hamiltonian-path.java ================================================ //{ Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0){ String input_line[] = read.readLine().trim().split("\\s+"); int N = Integer.parseInt(input_line[0]); int M = Integer.parseInt(input_line[1]); input_line = read.readLine().trim().split("\\s+"); ArrayList> Edges = new ArrayList>(); for(int i = 0; i < M; i++){ ArrayList e = new ArrayList(); e.add(Integer.parseInt(input_line[2*i])); e.add(Integer.parseInt(input_line[2*i+1])); Edges.add(e); } Solution ob = new Solution(); if(ob.check(N, M, Edges)){ System.out.println(1); } else{ System.out.println(0); } } } } // } Driver Code Ends //User function Template for Java class Solution { int n; boolean check(int N, int M, ArrayList> Edges) { // code here n=N; Map> map=new HashMap<>(); for(ArrayList edge:Edges){ int src=edge.get(0); int des=edge.get(1); map.putIfAbsent(src,new ArrayList<>()); map.putIfAbsent(des,new ArrayList<>()); map.get(src).add(des); map.get(des).add(src); } Set set=new HashSet<>(); for(int node=1;node<=N;node++){ if(dfs(node,set,map)){ return true; } } return false; } boolean dfs(int curr,Set set,Map> map){ set.add(curr); if(set.size()==n){ return true; } for(int neb:map.get(curr)){ if(!set.contains(neb) && dfs(neb,set,map)){ return true; } } set.remove(curr);//back.. return false; } } ================================================ FILE: Height Using Parent Array.java ================================================ class Solution{ static int findHeight(int N, int arr[]){ int h=1; int k=arr[N-1]; while(arr[k]!=-1){ k=arr[k]; h++; } return h+1; } } ================================================ FILE: Highest Product.java ================================================ public class Solution { public int maxp3(int[] A) { int n=A.length; Arrays.sort(A); int ans=Math.max(A[0]*A[1]*A[n-1],A[n-3]*A[n-1]*A[n-2]); return ans; } } ================================================ FILE: Highest Score.java ================================================ public class Solution { public int highestScore(String[][] A) { HashMap totalMarks=new HashMap<>(); HashMap freqMarks=new HashMap<>(); for(String x[]:A){ long marks=Long.parseLong(x[1]); if(totalMarks.containsKey(x[0])){ Long val=totalMarks.get(x[0]); long freq=freqMarks.get(x[0]); totalMarks.put(x[0],(Long)val+marks); freqMarks.put(x[0],++freq); }else{ totalMarks.put(x[0],marks); freqMarks.put(x[0],1L); } } long max=Integer.MIN_VALUE; for(String x[]:A){ long sum=totalMarks.get(x[0]); long freq=freqMarks.get(x[0]); max=Math.max(max,(sum/freq)); } return (int)max; } } ================================================ FILE: Hit most Balloons.java ================================================ class Solution { public int mostBalloons(int N, int arr[][]) { int ans=0; for(int i=0;i hm=new HashMap<>(); int count=0; for(int j=0;j A) { ArrayListl=new ArrayList<>(); l.add(A.get(0)); int ans=0; for(int i=1;i max_of_subarrays(vector arr, int n, int k) { // your code here vector ans; priority_queue> pq; for(int i=0; i max_of_subarrays(vector arr, int n, int k) { // your code here vector ans; deque dq; for(int i=0; i max_of_subarrays(int arr[], int n, int k) { // Your code here ArrayListans=new ArrayList<>(); Dequeq=new LinkedList<>(); for(int i=0;i0 && i-q.peek()>=k){ q.removeFirst(); } while(q.size()>0 && arr[q.getLast()]<=arr[i]){ q.removeLast(); } q.addLast(i); if(i>=k-1)ans.add(arr[q.peek()]); } return ans; } } ================================================ FILE: IPL 2021 - Match Day 2.py ================================================ #User function Template for python3 class Solution: def max_of_subarrays(self,arr,n,k): ''' you can use collections module here. :param a: given array :param n: size of array :param k: value of k :return: A list of required values ''' #code here def arr_max_ind(array, start, end): m_ind, m_ele = start, array[start] for i in range(start, end): if array[i]>=m_ele: m_ele = array[i] m_ind = i return [m_ele, m_ind] strategy = [] max_ele, max_ind = arr_max_ind(arr, 0, k) for i in range(k, n+1): start, end = i-k, k if max_ind=i-k: if arr[i-1]>max_ele: max_ele = arr[i-1] max_ind = i-1 else: max_ele, max_ind = arr_max_ind(arr, i-k, i) strategy.append(max_ele) return strategy ================================================ FILE: Identical Binary Trees.java ================================================ public class Solution { public int isSameTree(TreeNode A, TreeNode B) { if(equal(A,B)){ return 1; }else{ return 0; } } public boolean equal(TreeNode a,TreeNode b){ if(a==null && b==null)return true; if((a==null && b!=null) || (a!=null && b==null))return false; if(a.val!=b.val)return false; return equal(a.left,b.left) && equal(a.right,b.right); } } ================================================ FILE: Immediate Smaller Element.java ================================================ class Solution { void immediateSmaller(int arr[], int n) { // code here for(int i=0;iarr[i+1]){ arr[i]=arr[i+1]; }else{ arr[i]=-1; } } arr[n-1]=-1; } } ================================================ FILE: Immediate Smaller Element.js ================================================ class Solution { immediateSmaller(arr,n){ //code here // loop iterates to last numbers for(let i=0; i0){ if((y&1)!=0)res=(res*x)%d; //if y is odd then result will be mul by "a" y=y>>1; // y=y/2 x=(x*x)%d; // x=x^2 : eg. x^8 = (x^2)^4 } return (int)((d+res)%d);// for -ve testcases d is added in res } } ================================================ FILE: Implement StrStr.java ================================================ public class Solution { // DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY public int strStr(final String A, final String B) { for(int i=0;i<=A.length()-B.length();i++){ if(A.charAt(i)==B.charAt(0)){ if(B.equals(A.substring(i,i+B.length()))){ return i; } } } return -1; } } ================================================ FILE: Implementing Dijkstra Algorithm.java ================================================ class Solution { //Function to find the shortest distance of all the vertices //from the source vertex S. static int[] dijkstra(int V, ArrayList>> adj, int S) { // distance of all numbers from source int[] distance=new int[V]; //currently we don't know so filling maximum distance for(int i=0;i> pq=new PriorityQueue<>( new Comparator>(){ @Override public int compare(ArrayList a1,ArrayList a2){ return a1.get(0)-a2.get(0); } } ); //adding first pair into our priority queue ArrayList a=new ArrayList<>(); a.add(0); a.add(S); pq.add(a); while(!pq.isEmpty()){ //getting the smallest distance in pq ArrayList arr=pq.remove(); int currDistance=arr.get(0); int number=arr.get(1); //if that number was not already traversed then do it if(!selected[number]){ //get all connected pairs for that particular number ArrayList> connecteds=adj.get(number); for(int i=0;i newList=new ArrayList<>(); newList.add(newDistance); newList.add(connectedNumber); pq.add(newList); } } //mark the number as selected selected[number]=true; } } return distance; } } ======================================================================================================================================= //without using arraylist and comparator :: class Solution { //Function to find the shortest distance of all the vertices //from the source vertex S. static int[] dijkstra(int V, ArrayList>> adj, int S) { // distance of all numbers from source int[] distance=new int[V]; //currently we don't know so filling maximum distance Arrays.fill(distance,Integer.MAX_VALUE); //ditance to source will be 0 distance[S]=0; //boolean array to check if already a number is selected or not and also to reduce time // boolean[] selected=new boolean[V]; //priority queue to always give smallest distance from one number PriorityQueue pq=new PriorityQueue<>(); pq.add(S); while(!pq.isEmpty()){ //getting the element from pq int number=pq.remove(); int currDistance=distance[number]; //get all connected pairs for that particular number ArrayList> connecteds=adj.get(number); for(int i=0;ij)return null; int temp=i; int max=Integer.MIN_VALUE; int idx=0; while(temp<=j){ if(a[temp]>max){ max=a[temp]; idx=temp; } temp++; } TreeNode node=new TreeNode(a[idx]); node.left=dfs(a,i,idx-1); node.right=dfs(a,idx+1,j); return node; } } ================================================ FILE: Inorder linear Traversal.java ================================================ public class Solution { public ArrayList inorderTraversal(TreeNode A) { ArrayList list=new ArrayList<>(); Map map=new HashMap<>(); Deque stack=new ArrayDeque<>(); stack.push(A); map.put(A,false); while(!stack.isEmpty()){ TreeNode node=stack.pop(); if(map.get(node)==false){ if(node.right!=null){ stack.push(node.right); map.put(node.right,false); } stack.push(node); if(node.left!=null){ stack.push(node.left); map.put(node.left,false); } map.put(node,true); }else{ list.add(node.val); } } return list; } } ================================================ FILE: Insert into a Binary Search Tree ================================================ class Solution { public TreeNode insertIntoBST(TreeNode root, int val) { if(root==null)return new TreeNode(val); return addNode(root,root,val); } public TreeNode addNode(TreeNode head,TreeNode root,int val){ if(root.val>val){ if(root.left==null){ root.left=new TreeNode(val); return head; }else{ return addNode(head,root.left,val); } }else if(root.val in.val) { //if there is some faulty node, 'en insert it b/w prev and temp prev.next = in ; in.next = temp; return; } prev = temp; temp = temp.next; } prev.next = in; //make sure to cut off some extra nodes in.next = null; return; } } ================================================ FILE: Insertion Sort for Singly Linked List.java ================================================ class Solution { public static Node insertionSort(Node head){ Node newHead=new Node(-1); Node temp=head; while(temp!=null){ Node newtemp=newHead; Node toAdd=temp; temp=temp.next; toAdd.next=null; if(newtemp.next==null){ newtemp.next=toAdd; }else{ while(newtemp!=null){ if(newtemp.next==null){ break; } if(newtemp.next.data=0;i--){ if(str.charAt(i)!='0'){ num=str.substring(i); break; } } String roman=getRoman(Integer.parseInt(num)); sb.insert(0,roman); A-=Integer.parseInt(num); } return sb.toString(); } public String getRoman(int a){ switch(a){ case 1: return "I"; case 2: return "II"; case 3: return "III"; case 4: return "IV"; case 5: return "V"; case 6: return "VI"; case 7: return "VII"; case 8: return "VIII"; case 9: return "IX"; case 10: return "X"; case 20: return "XX"; case 30: return "XXX"; case 40: return "XL"; case 50: return "L"; case 60: return "LX"; case 70: return "LXX"; case 80: return "LXXX"; case 90: return "XC"; case 100: return "C"; case 200: return "CC"; case 300: return "CCC"; case 400: return "CD"; case 500: return "D"; case 600: return "DC"; case 700: return "DCC"; case 800: return "DCCC"; case 900: return "CM"; case 1000: return "M"; case 2000: return "MM"; case 3000: return "MMM"; } return ""; } } ================================================ FILE: Integers in Strings.java ================================================ public class Solution { public ArrayList solve(String A) { ArrayList arr=new ArrayList<>(); String[] ar=A.split(","); for(int i=0;i intersect(final List a, final List b) { ArrayList ans=new ArrayList<>(); int i=0; int j=0; while(isizeA){ //move b diff times int diff=sizeB-sizeA; while(diff--!=0){ tempB=tempB.next; } }else if(sizeA>sizeB){ //move a diff times int diff=sizeA-sizeB; while(diff--!=0){ tempA=tempA.next; } } //move untill they meet or they become null while(tempA!=tempB && tempA!=null && tempB!=null){ tempA=tempA.next; tempB=tempB.next; } if(tempA==null || tempB==null)return null; return tempB; } } ================================================ FILE: Interviewbit/Colorful Number/Colorful Number.java ================================================ public class Solution { public int colorful(int num) { Set set=new HashSet<>(); String s=Integer.toString(num); for(int i=0;i8: return 0 digitset={ch for ch in A} if len(digitset)!=len(A): return 0 if ('1' in digitset) or ('0' in digitset): return 0 if '2' not in digitset: return 1 bigrams={A[i:i+2] for i in range(len(A)-1)} if ('23'in bigrams or '32' in bigrams) and '6' in digitset: return 0 if ('24'in bigrams or '42' in bigrams) and '8' in digitset: return 0 if ('26'in bigrams or '62' in bigrams) and ('43' in bigrams or '34' in bigrams): return 0 return 1 ================================================ FILE: Interviewbit/Copy List/Copy List.java ================================================ /** * Definition for singly-linked list with a random pointer. * class RandomListNode { * int label; * RandomListNode next, random; * RandomListNode(int x) { this.label = x; } * }; */ public class Solution { public RandomListNode copyRandomList(RandomListNode head) { Map map=new HashMap<>(); RandomListNode temp=head; while(temp!=null){ map.put(temp,new RandomListNode(temp.label)); temp=temp.next; } temp=head; RandomListNode newHead=map.get(head); while(temp!=null){ if(temp.next!=null){ map.get(temp).next=map.get(temp.next); } map.get(temp).random=map.get(temp.random); temp=temp.next; } return newHead; } } ================================================ FILE: Interviewbit/Valid Sudoku/Valid Sudoku.cpp ================================================ int Solution::isValidSudoku(const vector &A) { vector> row(9); vector> col(9); vector> box(9); for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ if(A[i][j] != '.'){ char curr = A[i][j]; if(row[i].find(curr) != row[i].end()) return 0; else row[i].insert(curr); if(col[j].find(curr) != col[j].end()) return 0; else col[j].insert(curr); int index = i - i%3 + j/3; if(box[index].find(curr) != box[index].end()) return 0; else box[index].insert(curr); } } } return 1; } ================================================ FILE: Interviewbit/Valid Sudoku/Valid Sudoku.java ================================================ public class Solution { // DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY public int isValidSudoku(final String[] A) { char[][] board=new char[9][9]; for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ board[i][j]=A[i].charAt(j); } } for(int i=0;i<9;i++){ Set row=new HashSet<>(); Set col=new HashSet<>(); Set cube=new HashSet<>(); int rowindex=(i/3)*3,colindex=(i%3)*3; for(int j=0;j<9;j++){ if(board[i][j]!='.'&&!(row.add(board[i][j]))) return 0; if(board[j][i]!='.'&&!(col.add(board[j][i]))) return 0; if(board[rowindex+j/3][colindex+j%3]!='.'&&!(cube.add(board[rowindex+j/3][colindex+j%3]))) return 0; } } return 1; } } ================================================ FILE: Invert the Binary Tree.java ================================================ public class Solution { public TreeNode invertTree(TreeNode A) { if(A==null)return null; TreeNode le=null; if(A.left!=null){ le=invertTree(A.left); } TreeNode ri=null; if(A.right!=null){ ri=invertTree(A.right); } A.left=ri; A.right=le; return A; } } ================================================ FILE: Is Subsequence.java ================================================ class Solution { public boolean isSubsequence(String s, String t) { int i = 0; for(int j = 0;j=0;i--) { step++; if(A[i]>=step)step=0; } if(step==0)return 1; return 0; } } ================================================ FILE: Jump Game IV ================================================ class Solution { public int minJumps(int[] arr) { if (arr.length == 1) return 0; if (arr[0] == arr[arr.length - 1] || arr.length == 2) return 1; if (arr[0] == arr[arr.length - 2]) return 2; Queue q = new LinkedList<>(); HashMap> ind = new HashMap<>(); for (int i = 0; i < arr.length; i++) { if (!ind.containsKey(arr[i])) { ind.put(arr[i], new ArrayList<>()); } ind.get(arr[i]).add(i); } q.add(arr.length - 1); boolean[] seen = new boolean[arr.length]; int level = 0; while (!q.isEmpty()) { int sz = q.size(); for (int s = 0; s < sz; s++) { int state = q.poll(); if (state == 0) return level; if (state + 1 < arr.length && !seen[state + 1]) { seen[state + 1] = true; if (state + 1 == 0) return level + 1; q.add(state + 1); } if (state - 1 >= 0 && !seen[state - 1]) { seen[state - 1] = true; if (state - 1 == 0) return level + 1; q.add(state - 1); } List same = ind.get(arr[state]); for (int i : same) { if (i == state || seen[i]) continue; seen[i] = true; if (i == 0) return level + 1; q.add(i); } } level++; } return -1; } } ================================================ FILE: K Largest Elements.java ================================================ public class Solution { public ArrayList solve(ArrayList A, int B) { Collections.sort(A); ArrayList ans=new ArrayList<>(); for(int i=A.size()-1;i>=A.size()-B;i--){ ans.add(A.get(i)); } return ans; } } ================================================ FILE: K-diff Pairs in an Array.java ================================================ class Solution { public int findPairs(int[] nums, int k) { Arrays.sort(nums); int i = 0; int n = nums.length; int j = 0; int count = 0; while(j < n) { j = i + 1; while(j < n && nums[j] - nums[i] < k) { j++; } if (j < n && nums[j] - nums[i] == k) { count++; } while(i + 1 < n && nums[i+1] == nums[i]) { i++; } i++; } return count; } } ================================================================================ class Solution { public int findPairs(int[] nums, int k) { Map map = new HashMap(); for (int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); int result = 0; for (int i : map.keySet()) if (k > 0 && map.containsKey(i + k) || k == 0 && map.get(i) > 1) result++; return result; } } ================================================ FILE: Kill Captain America - GFG/README.md ================================================ # Kill Captain America ## Hard

Captain America is hiding from Thanos in a maze full of N rooms connected by M gates.
The maze is designed in such a way that each room leads to another room via gates. All connecting gates are unidirectional. Captain America is hiding only in those rooms which are accessible directly/indirectly through every other room in the maze.
Help Thanos find the number of rooms in which Captain America can hide. 

 

Example 1:

Input:
N = 5 and M = 5
V = [[1, 2], [2, 3], [3, 4], [4, 3], [5, 4]]
Output: 2
Explanation:

We can look closesly after forming graph 
than captain america only can hide in a 
room 3 and 4 because they are the only room 
which have gates through them. So,
answer is 2.

Example 2:

Input:
N = 2, M = 1
V = [[1, 2]]
Output: 1


Your Task:  
You don't need to read input or print anything. Your task is to complete the function captainAmerica() which takes the integer N, an integer M and 2-d array V as input parameters and returns the Total no of rooms.

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

 

Constraints:
1 ≤ n ≤ 30000
1 ≤ m ≤ 200000
1 ≤ p,q ≤ n

================================================ FILE: Kill Captain America - GFG/kill-captain-america.java ================================================ // { Driver Code Starts //Initial Template for Java //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[])throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { String input_line[] = read.readLine().trim().split("\\s+"); int N = Integer.parseInt(input_line[0]); int M = Integer.parseInt(input_line[1]); int V[][] = new int[M+1][2]; for(int i=0;i> adj = new ArrayList<>(); for(int i=0; i<=N; i++) { adj.add(new ArrayList<>()); } for(int i=0; i q = new ArrayDeque<>(); boolean visited[] = new boolean[N+1]; visited[mainNd] = true; q.add(mainNd); int count = 1; while(!q.isEmpty()) { int nd = q.poll(); for(int nei : adj.get(nd)) { if(visited[nei]==false) { count++; visited[nei]=true; q.add(nei); } } } return count; } } ================================================ FILE: Killing Spree - GFG/README.md ================================================ # Killing Spree ## Medium

There are Infinite People Standing in a row, indexed from 1.
A person having index 'i' has strength of (i*i).
You have Strength 'P'. You need to tell what is the maximum number of People You can Kill With your Strength P.
You can only Kill a person with strength 'X' if P >= 'X'  and after killing him, Your Strength decreases by 'X'. 

 

Example 1:

Input:
N = 14
Output: 3
Explanation:
The strengths of people is 1, 4, 9, 16, .... 
and so on. WE can kill the first 3 person , 
after which our Power becomes 0 and we cant 
kill anyone else. So answer is 3

 

Example 2:

Input:
N = 10
Output: 2


Your Task:  
You don't need to read input or print anything. Your task is to complete the function killinSpree() which takes the integer N as input parameters and returns the maximum Number of People You can kill.

Expected Time Complexity: O(log(n))
Expected Auxiliary Space: O(1)

 

Constraints:
1 ≤ T ≤ 103
1 ≤ N ≤ 1012

================================================ FILE: Killing Spree - GFG/killing-spree.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[])throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { String input_line[] = read.readLine().trim().split("\\s+"); long N = Long.parseLong(input_line[0]); Solution ob = new Solution(); long ans = ob.killinSpree(N); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution{ long killinSpree(long n) { long low=1; long high=(long)Math.sqrt(n); long ans=0; while(low<=high){ long mid=low+(high-low)/2; long sum=(mid*(mid+1)*(2*mid + 1))/6; if(sum==n)return mid; else if(sum B) { Arrays.fill(fact, i, A, B + 1); break; } } List dig = new ArrayList<>(); for (int i = 1; i <= A; i++) dig.add(i); StringBuilder res = new StringBuilder(); for (; A > 0; A--) { int pos = (B / fact[A - 1]); res.append(dig.get(pos)); dig.remove(pos); B = (B % fact[A - 1]); } return res.toString(); } } ================================================ FILE: Kth Row of Pascal's Triangle.java ================================================ public class Solution { public int[] getRow(int a) { int[] res = new int[a+1]; res[0]=1; res[a]=1; for(int i=1; i=k); } } ================================================ FILE: Kth Smallest Element In Tree.java ================================================ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { static int count, result; public int kthsmallest(TreeNode root, int B) { count = 0; result = Integer.MIN_VALUE; inorder(root,B); return result; } public static void inorder(TreeNode root,int k){ if(root == null){ return; } inorder(root.left,k); count++; if(count == k){ result = root.val; return; } inorder(root.right,k); } } ================================================ FILE: Kth smallest element.cpp ================================================ 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) { //code here int n=r+1; sort(arr,arr+n); return arr[k-1]; } }; ================================================ FILE: LC 1000. Minimum Cost to Merge Stones.cpp ================================================ class Solution { public: // This problem comes under the category of partition dp. int mergeStones(vector &stones, int k) { int n = stones.size(); // Condition to check if it's possible to merge all piles of stones into a single pile if ((n - 1) % (k - 1) != 0) return -1; vector prefixSum(n + 1); prefixSum[0] = 0; prefixSum[1] = stones[0]; for (int i = 2; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + stones[i - 1]; } vector> dp(n, vector(n, 0)); for (int i = n - 1; i >= 0; i--) { for (int j = i+1; j <= n - 1; j++) { int mini = 1e9; for (int idx = i; idx < j; idx = idx + k - 1) { int cost = dp[i][idx] + dp[idx + 1][j]; mini = min(cost, mini); } if((j-i)%(k-1) == 0){ mini += prefixSum[j+1] - prefixSum[i]; } dp[i][j] = mini; } } return dp[0][n - 1]; } }; ================================================ FILE: LCP - GFG/README.md ================================================ # LCP ## 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 is at the geek summer carnival. He is given an array of N strings. To unlock exclusive course discounts he needs to find the longest common prefix among all strings present in the array. Can you help him ?


Example 1:

Input:
N = 4
ar[] = {geeksforgeeks, geeks, geek, geezer}

Output:
gee

Explanation: 
Longest common prefix in all the given string is gee. 

 

Example 2:

Input:
N = 3
ar[] = {apple, ape, april}

Output:
ap


Your Task:
You don't need to read input or print anything. Complete the function LCP() that takes integer n and ar[] as input parameters and return the LCP. 

 

Expected time complexity: O(NlogN)
Expected space complexity: O(string length)


Constraints:
1 <= N <= 10^3
1 <= String Length <= 100

================================================ FILE: LCP - GFG/lcp.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; import java.math.*; class GFG { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = Integer.parseInt(sc.next()); while(t-- > 0) { int n = Integer.parseInt(sc.next()); String s[] = new String[n]; for(int i=0;ia.length()-b.length()); String ans=s[0]; for(int i=1;i

Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.

Example 1:

Input:
        1
      /   \
     4     4
   /   \
  6     8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.

Example 2:

Input: 6 6 3 N 2 9 3 N 8 8 2
            6
        /       \
       6         3
        \      /   \
         2    9     3
          \  /  \
          8 8    2 
Output: 2
Explanation: The following sub-tree is a
BST of size 2: 
       2
    /    \ 
   N      8

Your Task:
You don't need to read input or print anything. Your task is to complete the function
largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree. 

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).

Constraints:
1 ≤ Number of nodes ≤ 105
1 ≤ Data of a node ≤ 106

================================================ FILE: Largest BST - GFG/largest-bst.java ================================================ // { Driver Code Starts //Initial Template for Java /*package whatever //do not write package name here */ import java.io.*; import java.util.*; import java.math.*; class Node { int data; Node left, right; public Node(int d) { data = d; left = right = null; } } class GFG { static Node buildTree(String str) { // Corner Case if(str.length() == 0 || str.equals('N')) return null; String[] s = str.split(" "); Node root = new Node(Integer.parseInt(s[0])); Queue q = new LinkedList(); q.add(root); // Starting from the second element int i = 1; while(!q.isEmpty() && i < s.length) { // Get and remove the front of the queue Node currNode = q.remove(); // Get the curr node's value from the string String currVal = s[i]; // If the left child is not null if(!currVal.equals("N")) { // Create the left child for the curr node currNode.left = new Node(Integer.parseInt(currVal)); // Push it to the queue q.add(currNode.left); } // For the right child i++; if(i >= s.length) break; currVal = s[i]; // If the right child is not null if(!currVal.equals("N")) { // Create the right child for the curr node currNode.right = new Node(Integer.parseInt(currVal)); // Push it to the queue q.add(currNode.right); } i++; } return root; } public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); while(t>0) { String s = br.readLine(); Node root = buildTree(s); Solution T = new Solution(); System.out.println(T.largestBst(root)); t--; } } } // } Driver Code Ends //User function Template for Java // class Node // { // int data; // Node left, right; // public Node(int d) // { // data = d; // left = right = null; // } // } class Solution{ static int ans; // Return the size of the largest sub-tree which is also a BST static int largestBst(Node root){ if(root==null)return 0; ans=0; checkBST(root); return ans; } static boolean checkBST(Node root){ if(root==null)return true; boolean isLeftBST=checkBST(root.left); boolean isRightBST=checkBST(root.right); boolean isLeftSmaller=true; boolean isRightLarger=true; if(root.left!=null && isLeftBST){ if(getMAX(root.left)>=root.data)isLeftSmaller=false; } if(root.right!=null && isRightBST){ if(getMIN(root.right)<=root.data)isRightLarger=false; } boolean isBST=isLeftSmaller && isRightLarger && isLeftBST && isRightBST; if(isBST){ ans=Math.max(ans,count(root)); } return isBST; } static int count(Node root){ if(root==null)return 0; return 1+count(root.left)+count(root.right); } static int getMIN(Node root){ if(root.left==null)return root.data; return getMIN(root.left); } static int getMAX(Node root){ if(root.right==null)return root.data; return getMAX(root.right); } } ================================================ FILE: Largest Number.java ================================================ public class Solution { // DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY public String largestNumber(final List A) { Collections.sort(A,(a,b)->{ String s1=Integer.toString(a); String s2=Integer.toString(b); return (s1+s2).compareTo(s2+s1)>0?-1:1; }); StringBuilder sb=new StringBuilder(); for(int i=0;i0; i++){ if (A[i]!=len-i){ A[position[len-i]] = A[i]; int temp = position[A[i]]; position[A[i]] = position[len-i]; A[i] = len-i; B--; } } return A; } } ================================================ FILE: Largest Rectangle in Histogram.java ================================================ class Solution { public int largestRectangleArea(int[] a) { int max=0; int ps[]=prevSmallest(a); int ns[]=nextSmallest(a); for(int i=0;i s=new ArrayDeque<>(); for(int i=0;i=a[i]){ s.pop(); } if(s.isEmpty()){ ps[i]=-1; }else{ ps[i]=s.peek(); } s.push(i); } return ps; } public int[] nextSmallest(int[]a){ int ns[]=new int[a.length]; Deque s=new ArrayDeque<>(); for(int i=a.length-1;i>=0;i--){ while(!s.isEmpty() && a[s.peek()]>=a[i]){ s.pop(); } if(s.isEmpty()){ ns[i]=a.length; }else{ ns[i]=s.peek(); } s.push(i); } return ns; } } ================================================ FILE: Largest number with given sum - GFG/README.md ================================================ # Largest number with given sum ## Easy

Geek lost the password of his super locker. He remembers the number of digits N as well as the sum S of all the digits of his password. He know that his password is the largest number of N digits that can be made with given sum S. As he is busy doing his homework, help him retrieving his password.

Example 1:

Input:
N = 5, S = 12
Output:
93000
Explanation:
Sum of elements is 12. Largest possible 
5 digit number is 93000 with sum 12.

Example 2:

Input:
N = 3, S = 29
Output:
-1
Explanation:
There is no such three digit number 
whose sum is 29.

Your Task : 
You don't need to read input or print anything. Your task is to complete the function largestNumber() which takes 2 integers N and S as input parameters and returns the password in the form of string, else return "-1" in the form of string.

Constraints:
1 ≤ N ≤ 104
0 ≤ S ≤ 9*104

Expected Time Complexity : O(N)
Expected Auxilliary Space : O(1)

================================================ FILE: Largest number with given sum - GFG/largest-number-with-given-sum.java ================================================ // { Driver Code Starts import java.io.*; import java.lang.*; import java.util.*; class Driverclass { public static void main(String args[])throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //testcases int t = Integer.parseInt(br.readLine().trim()); while(t-- >0) { String inputLine[] = br.readLine().trim().split(" "); //taking n and sum int n = Integer.parseInt(inputLine[0]); int sum = Integer.parseInt(inputLine[1]); //calling largestNumber() function System.out.println(new Solution().largestNumber(n, sum)); } } }// } Driver Code Ends class Solution { //Function to return the largest possible number of n digits //with sum equal to given sum. static String largestNumber(int n, int sum){ StringBuilder sb=new StringBuilder(); while(n-->0){ if(sum!=0){ int num=9; while(sum0){ num--; } sum-=num; sb.append(num); }else{ sb.append(0); } } if(sum!=0)return "-1"; return sb.toString(); } } ================================================ FILE: Largest prime factor.cpp ================================================ class Solution{ public: bool isPrime(int N){ for(int i=2;i<=sqrt(N); i++){ if(N % i==0) return false; } return true; } long long int largestPrimeFactor(int N){ if(isPrime(N)) return N; long long int ans = 0; for(long long int i=N-1;i>=2;i--){ if(N%i==0 && isPrime(i)) return i; // else cout< largestValues(Node root) { //code here Map map=new HashMap<>(); dfs(root,1,map); ArrayList ans=new ArrayList<>(); int level=1; while(map.containsKey(level)){ ans.add(map.get(level)); level++; } return ans; } public void dfs(Node root,int level,Map map){ if(root==null)return; if(!map.containsKey(level)){ map.put(level,root.data); }else{ int cur=root.data; int init=map.get(level); map.put(level,Math.max(cur,init)); } dfs(root.right,level+1,map); dfs(root.left,level+1,map); } } ================================================ FILE: Last Node in a Complete Binary Tree.java ================================================ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { public int lastNode(TreeNode A) { Queue q=new LinkedList<>(); q.add(A); int val=-1; while(q.size()>0){ int sz=q.size(); while(sz-->0){ TreeNode node=q.remove(); if(node.left!=null)q.add(node.left); if(node.right!=null)q.add(node.right); val=node.val; } } return val; } } ================================================ FILE: Last digit K count.java ================================================ public class Solution { public int solve(int A, int B, int C) { while((A%10)!=C && AA){ B--; } if(A==B && A%10!=C)return 0; return (B-A)/10+1; } } ================================================ FILE: Leaders in an array.java ================================================ public class Solution { public ArrayList solve(ArrayList A) { int high=-1; ArrayList ans=new ArrayList<>(); for(int i=A.size()-1;i>=0;i--){ if(A.get(i)>high){ high=A.get(i); ans.add(high); } } return ans; } } ================================================ FILE: Leaves to DLL.java ================================================ class Tree{ // return the head of the DLL and remove those node from the tree as well. public Node convertToDLL(Node root) { // Code here if(root==null) return null; ArrayList al=new ArrayList<>(); solve(root,al); Node head=al.get(0); Node prev=al.get(0); for(int i=1;i al) { if(root==null) return null; if(root.right==null && root.left==null) { al.add(root); return null; } root.left=solve(root.left,al); root.right=solve(root.right,al); return root; } } ================================================ FILE: Leetcode/104 maximum depth of binary tree/104 maximum depth of binary tree.cpp ================================================ /** * 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; } int h1=maxDepth(root->left); int h2=maxDepth(root->right); return 1+max(h1,h2); } }; ================================================ FILE: Leetcode/104 maximum depth of binary tree/104. Maximum Depth of Binary Tree.java ================================================ class Solution { public int maxDepth(TreeNode root) { // Base Condition if(root == null) return 0; // Hypothesis int left = maxDepth(root.left); int right = maxDepth(root.right); // Induction return Math.max(left, right) + 1; } } ================================================ FILE: Leetcode/104 maximum depth of binary tree/README.md ================================================

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
================================================ FILE: Leetcode/112 Path Sum/112 Path Sum oc4.cpp ================================================ #include using namespace std; 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) return false; if(!root->left && !root->right && root->val == targetSum) return true; return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val); } }; ================================================ FILE: Leetcode/112 Path Sum/Path Sum.java ================================================ Solution 1: Using ArrayList class Solution { public static void fun(TreeNode root, int sum , int val, ArrayListaa){ if(root==null){ return ; } else if(root.left==null && root.right==null){ val=val+root.val; aa.add(val); return ; } else{ fun(root.left,sum,val+root.val,aa); fun(root.right,sum,val+root.val,aa); } } public boolean hasPathSum(TreeNode root, int sum) { if(root==null){ return false; } else{ ArrayListaa=new ArrayList(); fun(root,sum,0,aa); // System.out.println(aa); if(aa.contains(sum)){ return true; } return false; } } } +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Solution 2: Without Using ArrayList class Solution { boolean status=false; public void fun(TreeNode root, int sum,int s, boolean status){ if(root==null){ return; } else if(root.left==null && root.right==null){ s=s+root.val; if(s==sum){ this.status=true; } } else{ fun(root.left,sum,s+root.val,status); fun(root.right,sum,s+root.val,status); } } public boolean hasPathSum(TreeNode root, int sum) { if(root==null){ return false; } else{ fun(root,sum,0,status); if(status==true){ return true; } return false; } } } ================================================ FILE: Leetcode/1155. Number of Dice Rolls With Target Sum/1155 Number of Dice Rolls With Target Sum.cpp ================================================ #include using namespace std; #define MOD 1000000007 class Solution { public: long long solve(int dice, int faces, int target, vector> &dp){ // top down appr if(target <0) return 0; if(dice ==0 and target != 0 || target==0 and dice !=0) return 0; if(target ==0 and dice ==0) return 1; if(dp[dice][target] != -1) return dp[dice][target]; long long res =0; for(int i =1; i<= faces; i++){ res = (res + solve(dice - 1, faces, target - i, dp))%MOD; } return dp[dice][target] = res; } int numRollsToTarget(int n, int k, int target) { vector> dp(n + 1, vector(target + 1, -1)); return solve(n, k, target, dp); } }; ================================================ FILE: Leetcode/1155. Number of Dice Rolls With Target Sum/1155. Number of Dice Rolls With Target Sum.java ================================================ class Solution { static int MOD = (int)1e9 + 7; int helper(int n,int t,int k,int dp[][]){ if(n < 0 || t < 0) return 0; if(n == 0 && t == 0) return 1; if(dp[n][t] != -1) return dp[n][t]; int c_ans = 0; for(int i = 1;i <= k;i++){ c_ans = (c_ans + helper(n - 1,t - i,k,dp)) % MOD; } return dp[n][t] = c_ans; } public int numRollsToTarget(int n, int k, int target) { int dp[][] = new int[n + 1][target + 1]; for(var a:dp) Arrays.fill(a,-1); return helper(n,target,k,dp); } } ================================================ FILE: Leetcode/1155. Number of Dice Rolls With Target Sum/1155. Number of Dice Rolls With Target Sum.py ================================================ class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: dicti={} m=(10**9)+7 def rec(i,res): if i in dicti: if res in dicti[i]: return dicti[i][res] if res>=target or res+n-i>target or res+(n-i)*k=target: return 1 temp=0 for j in range(1,k+1): temp+=rec(i+1,res+j) if i not in dicti: dicti[i]={} dicti[i][res]=temp return temp%m return rec(0,0) ================================================ FILE: Leetcode/1217. Minimum Cost to Move Chips to The Same Position/1217. Minimum Cost to Move Chips to The Same Position.java ================================================ class Solution { public int minCostToMoveChips(int[] position) { int even = 0; int odd = 0; for(int i=0; i> threeSum(int[] num) { List> result = new ArrayList>(); if (num.length < 3) { return result; } Arrays.sort(num); for (int i = 0; i < num.length - 2; i++) { if (i > 0 && num[i] == num[i - 1]) { continue; } int j = i + 1; int k = num.length - 1; while (j < k) { if (num[i] + num[j] + num[k] == 0) { List list = new ArrayList(); list.add(num[i]); list.add(num[j]); list.add(num[k]); result.add(list); j++; k--; while (j < k && num[j] == num[j - 1]) { j++; } while (j < k && num[k] == num[k + 1]) { k--; } } else if (num[i] + num[j] + num[k] < 0) { j++; } else { k--; } } } return result; } } ================================================ FILE: Leetcode/15. 3Sum/README.md ================================================

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.

Notice that the solution set must not contain duplicate triplets.

 

Example 1:

  Input: nums = [0,1,1]
  Output: []
  Explanation: The only possible triplet does not sum up to 0.
  

Example 2:

  Input: nums = [-1,0,1,2,-1,-4]
  Output: [[-1,-1,2],[-1,0,1]]
  Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
  nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
  nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
  The distinct triplets are [-1,0,1] and [-1,-1,2].
  Notice that the order of the output and the order of the triplets does not matter.
  
================================================ FILE: Leetcode/151.Reverse Words in a String/Reverse Words in a String.java ================================================ class Solution { public String reverseWords(String s) { String s1=s.trim(); StringBuilder sb=new StringBuilder(); ArrayListaa=new ArrayList(); int i=0; while(i-1;i1--){ sb.append(aa.get(i1)); sb.append(" "); } sb.setLength(sb.length()-1); return sb.toString(); } } ================================================ FILE: Leetcode/1531. String Compression II/1531. String Compression II.cpp ================================================ class Solution { public: int helper(int currIdx,int prevchar,int curFreq,int k, vector>>> &dp, string &s) { if(k < 0) return 100000000; if(currIdx >= s.size()) return 0; // if curCharFreqCount, consider it as 10, because, until 10 .. 99, string length will be 2, if(curFreq >= 10) curFreq = 10; if(dp[currIdx][prevchar][curFreq][k] != -1) return dp[currIdx][prevchar][curFreq][k]; // // exclude int res = 100000000; /* 3 cases: case 1: We will delete our current character if K is available, so our string length will be minimum. case 2: If cur char is not same as prev, our res will be increased by 1 and curCharFreqCount will be 1 case 3: If cur char is same as prev char, we need to merge it and increase our count case 3.1: If curCharFreqCount is either 1 or more than 9, our res will be increased by 1 case 3.2: Else, we just need to increase curCharFreqCount. */ res = min(res, helper(currIdx + 1, prevchar, curFreq, k - 1, dp, s)); // // include if(s[currIdx] - 'a' != prevchar) { res = min(res, 1 + helper(currIdx + 1, s[currIdx] - 'a', 1, k, dp, s)); } else { if(curFreq == 1 || curFreq == 9) { res = min(res, 1 + helper(currIdx + 1, prevchar, curFreq + 1, k, dp, s)); } else res = min(res, helper(currIdx + 1, prevchar, curFreq + 1, k, dp, s)); } return dp[currIdx][prevchar][curFreq][k] = res; } int getLengthOfOptimalCompression(string s, int k) { int n = s.size(); vector>>> dp(n+1, vector>>(28, vector>(11, vector(n+1, -1)))); string p = s; if(n == 100) { bool isSame = true; sort(s.begin(), s.end()); for(int i = 1; i < s.size(); i++) { if(s[i] != s[i-1]) { isSame = false; break; } } if(isSame) return 4; } s = p; return helper(0, 27, 0, k, dp, s); } }; ================================================ FILE: Leetcode/1578 Minimum Time to Make Rope Colorful/1578 Minimum Time to Make Rope Colorful.cpp ================================================ //There are two approch for this Problem both approch are optimal also both uses O(n) Time Complexity #include using namespace std; //===========================Approch 1====================== class Solution { public: int minCost(string s, vector& time) { int ans = 0; int n = s.length(); for(int i = 1; i < n; i++) { if(s[i] == s[i - 1]) { ans += min(time[i], time[i - 1]); time[i] = max(time[i], time[i - 1]); } } return ans; } }; //===========================Approch 2 ========================= class Solution { public: int minCost(string colors, vector& neededTime) { // initializing 2 pointers int totalTime =0, i =0, j =0; while(i int: lenC = len(colors) temp = [] count = 0 ans = 0 for x in range(0,lenC): if x == lenC-1: if colors[x] == colors[x-1]: temp.append(neededTime[x]) count+=1 temp = sorted(temp) if len(temp) > 1: for i in range(0,count-1): ans+=temp.pop(0) temp = [] count = 0 else: temp = [] count = 0 elif colors[x] == colors[x+1]: temp.append(neededTime[x]) count += 1 else: temp.append(neededTime[x]) count+=1 temp = sorted(temp) if len(temp) > 1: for i in range(0,count-1): ans+=temp.pop(0) temp = [] count=0 else: temp = [] count=0 return ans ================================================ FILE: Leetcode/1662. Check If Two String Arrays are Equivalent/Check If Two String Arrays are Equivalent.java ================================================ Using StringBuilder Objects: class Solution { public boolean arrayStringsAreEqual(String[] word1, String[] word2) { StringBuilder sb1=new StringBuilder(); StringBuilder sb2=new StringBuilder(); for(String a:word1){ sb1.append(a); } for(String a:word2){ sb2.append(a); } if(sb1.toString().equals(sb2.toString())){ return true; } return false; } } ======================================================================================================================================================================= Without Using StringBuilder objects: class Solution { public boolean arrayStringsAreEqual(String[] word1, String[] word2) { String sum=null; String sum2=null; for(int i=0;inext; } if(count==1){ return NULL; } int x = count-n; if(x==0){ return head->next; } p = head; for(int i =0;inext; } p->next = p->next->next; return head; } }; //=============================Approch 2 ======================================================== #include using namespace std; /** * 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 *prev = head, *NextNode = head; for(int i =0; inext; if(!prev) return head->next; while(prev->next){ NextNode = NextNode->next; prev = prev->next; } NextNode->next = NextNode->next->next; return head; } }; ================================================ FILE: Leetcode/19 Remove Nth Node From End of List/Remove Nth Node from End Of List.java ================================================ Solution 1: Using ArrayList as additional Space Time: 2ms Space: 42.3Mb ArrayListaa=new ArrayList(); ListNode temp=head; while(temp!=null){ aa.add(temp.val); temp=temp.next; } aa.remove(aa.size()-n); ListNode temp2=new ListNode(-1); ListNode temp3=temp2; for(int i=0;i &a,vector &b){ if(a[0]!=b[0]) return a[0]>b[0]; return a[1]>& p) { sort(p.begin(),p.end(),comp); int max = INT_MIN; int ans=0; for(auto it:p){ if(max>it[1]){ ans++; } else{ max = it[1]; } } return ans; } }; ///===============Approch 1========================= // int n = properties.size(); // int weakp=0; // for(int i =0;i> v; // int n = properties.size(); // for(int i =0;i m(v.size(),0); // int i =0; // for(auto it:v){ // int x = it.first; // int y = it.second; // for(auto it1:v){ // if(x2095. Delete the Middle Node of a Linked List

Medium


You are given the head of the Linked List. Delete the middle node and return the headof the modified linked list. The middle node of the list of size n is the [n/2]thnode from the start using 0-based indexing, where [x]denotes the largest integer less than or equal to x

 

Example 1:

Input: tops = [2,1,2,4,2,2]
Output: [1,3,4,1,2,6]
Explanation: 
The above figure represents the given linked list. The indices of the nodes are written below.
Since n = 7, node 3 with value 7 is the middle node, which is marked in red.
We return the new list after removing this node. 

 

Constraints:

  • The number of nodes in the list is in the range [1, 10]5
  • 1 <= Node.val <= 105
================================================ FILE: Leetcode/2124. Check if All A's Appears Before All B's/2124. Check if All A's Appears Before All B's.java ================================================ Code : class Solution { public boolean checkString(String s) { int indexb=s.indexOf("b"); int indexa=s.lastIndexOf("a"); if(indexa!=-1 && indexb!=-1 && indexa>indexb){ return false; } else if(indexa==-1 || indexb==-1){ return true; } return true; } } Time Complexity:O(String Length)[As indexOf() method will found out the index of a particular character after thraversing the whole string] Space Complexity:O(1) Auxiliary Space:O(1) Leetcode Time:1ms beats 86.26% Leetcode Space:42.2Mb beats 42.38% ================================================ FILE: Leetcode/218 The Skyline Problem/218 The Skyline Problem s30.cpp ================================================ #include using namespace std; class Solution { public: vector> getSkyline(vector>& buildings) { vector> res; multiset pq{0}; vector> points; for(auto b: buildings){ points.push_back({b[0], -b[2]}); points.push_back({b[1], b[2]}); } sort(points.begin(), points.end()); int ongoingHeight = 0; for(int i = 0; i < points.size(); i++){ int currentPoint = points[i].first; // x coordinate int heightAtCurrentPoint = points[i].second; // ht if(heightAtCurrentPoint < 0){ pq.insert(-heightAtCurrentPoint); } else { pq.erase(pq.find(heightAtCurrentPoint)); } auto pqTop = *pq.rbegin(); if(ongoingHeight != pqTop){ ongoingHeight = pqTop; res.push_back({currentPoint, ongoingHeight}); } } return res; } }; ================================================ FILE: Leetcode/221. Maximal Square/221. Maximal Square.java ================================================ class Solution { public int maximalSquare(char[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; int maxSquare = 0; int[][] maxSideLength = new int[rows+1][cols+1]; for(int i=rows-1;i>=0;i--){ for(int j=cols-1;j>=0;j--){ if(matrix[i][j] == '1'){ // maximum sideLength of square is minimum of length covered by either of row, column, diagonal maxSideLength[i][j] = Math.min(maxSideLength[i+1][j],Math.min(maxSideLength[i][j+1],maxSideLength[i+1][j+1]))+1; maxSquare = Math.max(maxSquare, maxSideLength[i][j]); }else{ maxSideLength[i][j] = 0; } } } return maxSquare*maxSquare; } } ================================================ FILE: Leetcode/222. Count Complete Tree Nodes/Count Complete Tree Nodes.java ================================================ class Solution { int count = 0; public int countNodes(TreeNode root) { if(root==null) return 0; countNodes(root.left); count++; System.out.print(root.val+" "); countNodes(root.right); return count; } } ================================================ FILE: Leetcode/2368. Reachable Nodes With Restrictions/Reachable Nodes With Restrictions.cpp ================================================ class Solution { public: void dfs(vector adj[],vector&vis,int node,int &no){ vis[node]=1; no++; for(auto it:adj[node]){ if(vis[it]==0){ dfs(adj,vis,it,no); } } } int reachableNodes(int n, vector>& edges, vector& res) { vector adj[n]; vector v(n,0); for(int i =0;inext); // ListNode* temp = node; int temp = node->next->val; node->next->val = node->val; node->val = temp; node->next = node->next->next; // ListNode *t = node->next; // free(node); // node = t; // free(t); // cout<val< using namespace std ; class Solution { public: int commonFactors(int a, int b) { int count = 1 ; for(int i = 2 ; i <= b ; i++ ) { if(a % i == 0 && b % i == 0) { count ++ ; } } return count ; } }; ================================================ FILE: Leetcode/2428. Maximum Sum of an Hour Glass/2428. Maximum Sum of an Hour Glass.cpp ================================================ #include using namespace std ; class Solution { public: int maxSum(vector>& grid) { int m = grid.size() ; // Gives the no. of rows in a matrix. int n = grid[0].size() ; // Gives the no. of columns in a matrix. int sum = 0 ; // Initialised a variable for calculating the sum. int maxi = 0 ; // Initialized a variable for comparing and finding the maximum sum. for(int i = 1 ; i < m - 1 ; i++) { for(int j = 1 ; j < n - 1 ; j++) { // Carefully, Access all the grid indices in the form of hour glass by sticking to one point. // Avoid accessing the wrong indices and indices out of bound. sum += grid[i][j] + grid[i + 1][j] + grid[i + 1][j - 1] + grid[i + 1][j + 1] + grid[i - 1][j] + grid[i - 1][j + 1] + grid[i - 1][j - 1] ; maxi = max(sum , maxi) ; // Used the inbuilt max function of C++ to comapare the previous and curreent values. sum = 0 ; // Again, initialised the sum to be zero so that for next iteration it will again start from zero. } } return maxi ; // Return the maximum sum after completing all the iterations. // Generalised, Time Complexity of the solution is - O(N^2) - As the nested loop is involved. } }; ================================================ FILE: Leetcode/263. Ugly Number/263. Ugly Number.cpp ================================================ class Solution { public: bool isUgly(int n) { if(n == 0) return false; if(n == 1) return true; while(n%2==0) { n = n/2; } while(n%3==0) { n = n/3; } while(n%5==0) { n = n/5; } return n == 1 ? true:false; } }; ================================================ FILE: Leetcode/279. Perfect Squares/279. Perfect Squares.cpp ================================================ class Solution { int solve(int ind, vector &nums, int tar, vector> &dp) { if(tar == 0) return 0; if(ind == 0) return tar; if(dp[ind][tar] != -1) return dp[ind][tar]; int excl = solve(ind-1, nums, tar, dp); int incl = 1e9; if(nums[ind] <= tar) incl = 1 + solve(ind, nums, tar-nums[ind], dp); return dp[ind][tar] = min(excl, incl); } public: int numSquares(int n) { if(n <= 3) return n; vector nums; for(int i = 1; i*i <= n; i++) { nums.push_back(i*i); } int m = nums.size(); vector> dp(m+1, vector(n+1, -1)); //n is target return solve(m-1, nums, n , dp); } }; ================================================ FILE: Leetcode/336. Palindrome Pairs/336. Palindrome Pairs.java ================================================ class Solution { static int palindromepair(int N, String arr[]) { for(int i = 0; i< N;i++){ for(int j =0; j< N;j++){ if(i!=j){ String newStr = arr[i]+arr[j]; if(isPalindrome(newStr)) return 1; } } } return 0; } static boolean isPalindrome(String input){ int i = 0; int j = input.length() - 1; while (i < j) { if (input.charAt(i) != input.charAt(j)) { return false; } i++; j--; } return true; } }; ================================================ FILE: Leetcode/336. Palindrome Pairs/336. Palindrome pairs.cpp ================================================ #include using namespace std; struct TrieNode { TrieNode *next[26] = {}; int index = -1; vector palindromeIndexes; }; class Solution { TrieNode root; // Suffix trie void add(string &s, int i) { auto node = &root; for (int j = s.size() - 1; j >= 0; --j) { if (isPalindrome(s, 0, j)) node->palindromeIndexes.push_back(i); // A[i]'s prefix forms a palindrome int c = s[j] - 'a'; if (!node->next[c]) node->next[c] = new TrieNode(); node = node->next[c]; } node->index = i; node->palindromeIndexes.push_back(i); // A[i]'s prefix is empty string here, which is a palindrome. } bool isPalindrome(string &s, int i, int j) { while (i < j && s[i] == s[j]) ++i, --j; return i >= j; } public: vector> palindromePairs(vector& words) { int N = words.size(); for (int i = 0; i < N; ++i) add(words[i], i); vector> ans; for (int i = 0; i < N; ++i) { auto s = words[i]; auto node = &root; for (int j = 0; j < s.size() && node; ++j) { if (node->index != -1 && node->index != i && isPalindrome(s, j, s.size() - 1)) ans.push_back({ i, node->index }); // A[i]'s prefix matches this word and A[i]'s suffix forms a palindrome node = node->next[s[j] - 'a']; } if (!node) continue; for (int j : node->palindromeIndexes) { // A[i] is exhausted in the matching above. // If a word whose prefix is palindrome after matching its suffix with A[i], // then this is also a valid pair if (i != j) ans.push_back({ i, j }); } } return ans; } }; ================================================ FILE: Leetcode/4. Median of Two Sorted Arrays/4. Median of Two Sorted Arrays.java ================================================ // as median we have to divide values in array // left side (some of nums1 and some of nums2) // right side (some of nums1 and some of nums2) class Solution { public double findMedianSortedArrays(int[] arr1, int[] arr2) { //taking nums2 bigger always (bcz we taking values from nums2) //so to not get index out of bound if(arr2.length "+l+" "+r+"\n"+ // "cut1 & cut2 => "+cut1+" "+cut2+"\n"+ // "left half=> "+Math.min(l1,l2)+" "+Math.max(l1,l2)+"\n"+ // "right half=> "+Math.min(r1,r2)+" "+Math.max(r1,r2)); if(l1<=r2 && l2<=r1){ // System.out.print(l1+" ") if((n+m)%2==0){ // System.out.println(l1+" "+l2+" "+r1+" "+r2); return ( Math.max(l1,l2) + Math.min(r1,r2) )/2.0; }else{ //odd length return Math.max(l1,l2); } } else if(l1>r2){ r=cut1-1; } else if(l2>r1){ l=cut1+1; } } return 1L; } } ================================================ FILE: Leetcode/4. Median of Two Sorted Arrays/Median of Two Sorted Arrays.cpp ================================================ class Solution { public: double findMedianSortedArrays(vector& v1, vector& v2) { for(int i =0;i readBinaryWatch(int turnedOn) { List ans=new ArrayList<>(); if(turnedOn>8){ return ans; } for(int h=0;h<12;h++){ for(int m=0;m<60;m++){ //bit count will count total set bit(1) in a numbmer if(Integer.bitCount(h*64+m)==turnedOn){ ans.add(String.format("%d:%02d",h,m)); } } } return ans; } } ================================================ FILE: Leetcode/401 binary watch/NOTES.md ================================================ ​ ================================================ FILE: Leetcode/401 binary watch/README.md ================================================

401. Binary Watch

Easy


A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to 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 (ignoring the PM), 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
================================================ FILE: Leetcode/437 Path Sum III/pathSum.cpp ================================================ class Solution { public: int cnt=0; void dfs(TreeNode* root,long long target) { if(!root) return; if(root->val==target) cnt++; dfs(root->left,target-root->val); dfs(root->right,target-root->val); } ///////// int pathSum(TreeNode* root, int targetSum) { if(root) { dfs(root,targetSum); pathSum(root->left,targetSum); pathSum(root->right,targetSum); } return cnt; } }; ================================================ FILE: Leetcode/450 Delete Node in a BST/deleteNode.java ================================================ ```java class Solution { public TreeNode deleteNode(TreeNode root, int key) { // if current node is null, return null // this can happen only if the tree is empty or if the key does not exist in the tree if (root == null) return null; // if current node's value is equal to key, then simply delete it if (root.val == key) { // straightforward case where node is leaf node, then just delete it if (root.left == null && root.right == null) { return null; } else if (root.left != null) { // if the left child exists, then the node to attach is the left child's rightmost descendant // and we should return the current node's left child as the new root for its parent to attach to TreeNode newRoot = root.left; TreeNode attach = newRoot; while (attach.right != null) { attach = attach.right; } // attach the deleted nodes' right child to the right of the node to attach attach.right = root.right; return newRoot; } else { // if the right child exists, then the node to attach is the right child's leftmost descendant // and we should return the current node's right child as the new root for its parent to attach to TreeNode newRoot = root.right; TreeNode attach = newRoot; while (attach.left != null) { attach = attach.left; } // attach the deleted nodes' left child to the left of the node to attach attach.left = root.left; return newRoot; } } // if the key is not equal to the current node's value, keep searching for the key using BST property // attach the current node to the result of the deletion (which will either return the original child or a new child if the child is deleted) if (key > root.val) { root.right = deleteNode(root.right, key); } else { root.left = deleteNode(root.left, key); } // return current node return root; } } ``` ================================================ FILE: Leetcode/4Sum II/4Sum II.java ================================================ class Solution { public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { Map map = new HashMap<>(); for(int k : nums3) for(int l : nums4) map.put(k + l, map.getOrDefault(k + l, 0) + 1); int count = 0; for(int i : nums1) for(int j : nums2) count += map.getOrDefault(-(i + j), 0); return count; } } ================================================ FILE: Leetcode/622 Design Circular Queue/622 Design Circular Queue med s25.cpp ================================================ #include using namespace std; class MyCircularQueue { public: MyCircularQueue(int k) { // queue holding the elems for circular queue q.resize(k); // no. of elems in the circular queue count =0; size =k; // queue size headIndex =0; // index of head element } bool enQueue(int value) { // handle full case if(isFull()) return false; q[(headIndex+count)% size] = value; count+=1; return true; } bool deQueue() { // handle empty case if(isEmpty()) return false; // update head idx headIndex= (headIndex+1)% size; count-=1; return true; } int Front() { // handle empty queue case if(isEmpty()) return -1; return q[headIndex]; // return head elem } int Rear() { // handle empty queue case if(isEmpty()) return -1; return q[(headIndex+count-1) %size]; } bool isEmpty() { // no elem in queue return count == 0; } bool isFull() { // return true if the count is equal to the queue size return count==size; // else return false } private: int count, size, headIndex; vector q; }; ================================================ FILE: Leetcode/623 Add One Row To Tree/Add one row to tree.java ================================================ class Solution { public TreeNode addOneRow(TreeNode root, int val, int depth) { if(depth==1) { // if depth is 1 we have to add for root TreeNode newH=new TreeNode(val); newH.left=root; return newH; } addRow(root, val, 1, depth-1); //starting with root starting from 1 to depth-1 return root; } public void addRow(TreeNode root, int val, int height, int expHeight) { if(root==null) { return ; } if(expHeight==height) { TreeNode left=new TreeNode(val, root.left, null); TreeNode right=new TreeNode(val, null, root.right); root.left=left; root.right=right; return ; } addRow(root.left, val, height+1, expHeight); addRow(root.right, val, height+1, expHeight); } } ================================================ FILE: Leetcode/623 Add One Row To Tree/ReadMe.md ================================================ # 623. Add One Row to Tree Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth. Note that the root node is at depth 1. The adding rule is: Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root. cur's original left subtree should be the left subtree of the new left subtree root. cur's original right subtree should be the right subtree of the new right subtree root. If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree. ### Example 1: ![addrow-tree](https://user-images.githubusercontent.com/75923481/193965191-3f95d1b4-9bf0-499d-ae01-5daee00b9110.jpg) Input: root = [4,2,6,3,1,5], val = 1, depth = 2
Output: [4,1,1,2,null,null,6,3,1,5]
## Example 2: ![add2-tree](https://user-images.githubusercontent.com/75923481/193965239-82dc673e-015a-46c3-8e0d-9d04907c0c32.jpg) Input: root = [4,2,null,3,1], val = 1, depth = 3
Output: [4,2,null,1,1,3,null,null,1]
Constraints: The number of nodes in the tree is in the range [1, 104].
The depth of the tree is in the range [1, 104].
-100 <= Node.val <= 100
-105 <= val <= 105
1 <= depth <= the depth of tree + 1
================================================ FILE: Leetcode/623 Add One Row to Tree/623 Add One Row to Tree.java ================================================ class Solution { public TreeNode add(TreeNode root, int val, int depth, int currdepth){ if(root==null) return root; if(depth==1){ TreeNode temp = new TreeNode(val); // if(side=='l') temp.left = root; return temp; } else if(currdepth==depth-1){ TreeNode temp1 = new TreeNode(val); TreeNode temp2 = new TreeNode(val); temp1.right = root.right; temp2.left = root.left; root.left = temp2; root.right = temp1; return root; }else{ root.left = add(root.left,val,depth,currdepth+1); root.right = add(root.right,val,depth,currdepth+1); return root; } } public TreeNode addOneRow(TreeNode root, int val, int depth) { if(depth==1){ TreeNode temp = new TreeNode(val); temp.left = root; return temp; } return add(root,val,depth,1); } } ================================================ FILE: Leetcode/658 Find K Closest Elements/658 Find K Closest Elements s29.cpp ================================================ #include using namespace std; class Solution { public: vector findClosestElements(vector& arr, int k, int x) { int L =0, R = arr.size()-1; while(R-L >= k) if(x- arr[L] <= arr[R]-x) R--; else L++; return vector(arr.begin() + L, arr.begin() + R+1); } }; ================================================ FILE: Leetcode/658 Find K Closest Elements/Find k Closest Elements.java ================================================ Approach 1: class Solution { public List findClosestElements(int[] arr, int k, int x) { TreeMap>map=new TreeMap>(); for(int i=0;iset=map.get(a); set.add(arr[i]); map.put(a,set); } else{ LinkedListset=new LinkedList(); set.add(arr[i]); map.put(a,set); } } //System.out.println(map); Listlist=new ArrayList(); boolean flag=false; for(int a:map.keySet()){ LinkedListset=map.get(a); for(int b:set){ list.add(b); if(list.size()==k){ flag=true; break; } } if(flag==true){ break; } } Collections.sort(list); return list; } } Time Taken:130ms +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Approach 2: class Solution { public static class Pair implements Comparable{ int ele; int diff; public Pair(int a, int b){ ele=a; diff=b; } public int compareTo(Pair p){ if((p.diff)==(this.diff)){ return this.ele-p.ele; } return this.diff-p.diff; } } public List findClosestElements(int[] arr, int k, int x) { Pair obj[]=new Pair[arr.length]; for(int i=0;iaa=new ArrayList(); for(int i=0;i x: high = mid - 1 # means x is present at mid else: return mid # If we reach here, then the element was not present return -1 ================================================ FILE: Leetcode/704 binary search/NOTES.md ================================================ ================================================ FILE: Leetcode/704 binary search/README.md ================================================

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.
================================================ FILE: Leetcode/72 Edit distance/minDistance.cpp ================================================ /*This code is contributed by mr-optimizer (https://github.com/mr-optimizer) */ class Solution { public: int memo[501][501]; int dp(string word1, string word2, int i, int j) { if (i == 0)return j; if (j == 0)return i; if (memo[i][j] != -1)return memo[i][j]; if (word1[i - 1] == word2[j - 1]) { return memo[i][j] = dp(word1, word2, i - 1, j - 1); } else { return memo[i][j] = 1 + min(dp(word1, word2, i - 1, j), min(dp(word1, word2, i, j - 1), dp(word1, word2, i - 1, j - 1))); } } int minDistance(string word1, string word2) { memset(memo, -1, sizeof(memo)); return dp(word1, word2, word1.size(), word2.size()); } }; ================================================ FILE: Leetcode/72 Edit distance/minDistance.java ================================================ public class Solution { public int minDistance(String A, String B) { int[][]list=new int[A.length()][B.length()]; return editDist(A,B,0,0,list); } int editDist(String A,String B,int x,int y,int[][]memory){ if(y==B.length())return A.length()-x; if(x==A.length())return B.length()-y; int ans=memory[x][y]; if(ans!=0)return ans; if(A.charAt(x)==B.charAt(y)){ ans=editDist(A,B,x+1,y+1,memory); }else{ ans=1+Math.min(editDist(A,B,x+1,y,memory),Math.min(editDist(A,B,x,y+1,memory),editDist(A,B,x+1,y+1,memory))); } memory[x][y]=ans; return ans; } } ================================================ FILE: Leetcode/75.Sort colors/75.Sort-colors.java ================================================ class Solution { public void sortColors(int[] nums) { int count0 = 0; int count1=0; for(int i=0 ; i 0){ nums[i] = 0 ; } else if(count1-- > 0){ nums[i]=1; } else{ nums[i]=2; } } } } ================================================ FILE: Leetcode/75.Sort colors/Notes.md ================================================ ================================================ FILE: Leetcode/75.Sort colors/README.md ================================================ # [75. Sort Colors](https://leetcode.com/problems/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. ================================================ FILE: Leetcode/75.Sort colors/Sort colors.cpp ================================================ class Solution { public: void sortColors(vector& v) { int n =v.size(); for(int i =0;iv[j+1]){ swap(v[j],v[j+1]); } } } } }; ================================================ FILE: Leetcode/766.Toeplitz Matrix/Toeplitz Matrix.java ================================================ Solution 1: Backward Comparison: Comparison with previous diagonal cee Time Complexity:O(N*M) Space Complexity:O(N*M) Auxiliary Space:O(1) LeetCode Time: 1 ms faster than 93.83% LeetCode Memory: 45.2MB less than 80.01% boolean flag=false; int n=arr.length; int m=arr[0].length; for(int i=01;i>& board, string word) { if (word.empty()) return true; if (board.empty() || board[0].empty()) return false; m = board.size(); n = board[0].size(); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) // traverse the board to find the first char if (dfsSearch(board, word, 0, i, j)) return true; return false; } private: int m; int n; bool dfsSearch(vector>& board, string& word, int k, int i, int j) { if (i < 0 || i >= m || j < 0 || j >= n || word[k] != board[i][j]) return false; if (k == word.length() - 1) return true; // found the last char char cur = board[i][j]; board[i][j] = '*'; // used bool search_next = dfsSearch(board, word, k+1, i-1 ,j) || dfsSearch(board, word, k+1, i+1, j) || dfsSearch(board, word, k+1, i, j-1) || dfsSearch(board, word, k+1, i, j+1); board[i][j] = cur; // reset return search_next; } }; ================================================ FILE: Leetcode/79.Word Search/NOTES.md ================================================ ================================================ FILE: Leetcode/79.Word Search/README.md ================================================

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 2:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false


================================================
FILE: Leetcode/838 Push Dominoes/838 Push Dominoes lc med s27.cpp
================================================
#include
using namespace std;

class Solution {
public:
// using 2-pointer
    string pushDominoes(string dominoes) {
        int l = 0, n = dominoes.size();
        for (int r = 0; r < n; r++) {
            if (dominoes[r] == '.') {
                continue;
            } else if ((dominoes[r] == dominoes[l]) || (dominoes[l] == '.' && dominoes[r] == 'L')) {
                for (int k = l; k < r; k++) dominoes[k] = dominoes[r];
            } else if (dominoes[l] == 'L' && dominoes[r] == 'R') {

            }  else if (dominoes[l] == 'R' && dominoes[r] == 'L') {

                int m = (r - l - 1) / 2;
                for (int k = 1; k <= m; k++) dominoes[r - k] = 'L', dominoes[l + k] = 'R';
            }
            l = r;
            dominoes[l] = dominoes[r];
        }
        if (dominoes[l] == 'R') for (int k = l; k < n; k++) dominoes[k] = 'R';
        return dominoes;
    }
};

================================================
FILE: Leetcode/91 Decode Ways/91 Decode Ways oc1.cpp
================================================
#include
using namespace std;

class Solution {
public:
    int numDecodings(string s) {
//         check for empty string or leading zero
        if(!s.size() || s.front() == '0') return 0;
        int d1=1, d2 =1;   
        for(int i =1; inext;
        }
        p = head;
        vector v;
        while(p!=NULL){
           v.push_back(p->val);
           p=p->next; 
        }
        reverse(v.begin()+left-1,v.begin()+right);
        p = head;
        int i=0;
        while(p!=NULL){
            p->val = v[i];
            p=p->next;
            i++;
        }
        return head;
    }
};


 // ListNode* p = head;
 //        int count =0;
 //        while(p!=NULL){
 //            count++;
 //            p=p->next;
 //        }
 //        p = head;
 //        int a[count];
 //        int i =0;
 //        while(p!=NULL){
 //            a[i]=p->val;
 //            p=p->next;
 //            i++;
 //        }
 //        p = head;
 //        reverse(a+(left-1),a+right);
 //        int j =0;
 //        while(p!=NULL){
 //            p->val = a[j];
 //            p=p->next;
 //            j++;
 //        }
 //        return head;


================================================
FILE: Leetcode/92 Reverse Linked List II/Reverse Linked List II.java
================================================
public class Solution {
    public ListNode reverseBetween(ListNode A, int B, int C) {

        ListNode temp = A;
        ListNode prevtemp = null;

        int count = 1;
        while(count
using namespace std;

class Solution {
public:
    int alphabet_size[26];
    int find(int x){
        return alphabet_size[x] == x ? x: find(alphabet_size[x]);
    }
    bool equationsPossible(vector& equations) {
        int n = (int) equations.size();
        
        for(int i =0; i<26; i++) alphabet_size[i]=i;
        
        for(auto x : equations){
            if(x[1]== '='){
                alphabet_size[find(x[0]-'a')] = find(x[3]-'a');
            }
        }
//         handle != case
        for(auto x : equations){
            if(x[1]== '!' && find(x[0]-'a') == find(x[3]-'a')){
                return false;
            }
        }
            return true;
    }
};

================================================
FILE: Leetcode/Break A Palindrome/Break A Palindrome.java
================================================
class Solution{
  public String breakPalindrome(String s) {
          if(s.length()<=1){
              return "";
          }
          else{
              int len=0;
              len=s.length()/2;
              int i=0;
              StringBuilder sb=new StringBuilder(s);
              while(i& nums, int k) {
        unordered_map mp;
            for(auto i: nums) {
                    mp[i]++;
            }
            int ans = 0;
            for(auto x: mp) {
                    if(k == 0) {
                            if(x.second > 1) {
                                    ans++;
                            }
                    }else if(mp.find(x.first+k) != mp.end()) {
                            ans++;
                    }
            }
            return ans;
    }
};

================================================
FILE: Leetcode/Merge Overlapping Intervals/Merge Overlapping Intervals.cpp
================================================
class Solution {
public:
    vector> merge(vector>& intervals) {
        vector> ans;
            sort(intervals.begin(), intervals.end());
            
         vector temp = intervals[0];
            for(int i= 1; i& neededTime) {
        if(colors.length() != neededTime.size()) return -1;
                int time = 0; int maxTime;
            for(int i=0; i0 && colors[i]!=colors[i-1])
                           maxTime =0;
                 
                  time += min(maxTime, neededTime[i]);
                  maxTime = max(maxTime, neededTime[i]);  
            }
            
            return time;
    }
};

================================================
FILE: Leetcode/Number of Dice rolls with target sum/Number of dice rolls.cpp
================================================
vector dp(target + 1);
  dp[0] = 1;
  for (int i = 1; i <= d; ++i) {
    vector dp1(target + 1);
    for (int j = 1; j <= f; ++j)
      for (auto k = j; k <= target; ++k)
        dp1[k] = (dp1[k] + dp[k - j]) % 1000000007;
    swap(dp, dp1);
  }
  return dp[target];

================================================
FILE: Leetcode/Remove Letter To Equalize Frequency/Remove Letter To Equalize Frequency.cpp
================================================
class Solution {
public:
    bool equalFrequency(string word) {
        vector v;
        unordered_map mp;
        for(char ch : word) mp[ch]++;
        for(auto x : mp){
            v.push_back(x.second);
        }
        sort(v.begin(), v.end());
        if(v.size() == 1) return 1;
        
        else if(v.size() == 2){
            if(v[0] == 1 and v[1] == 1) return 1;
            else if(v[1] - v[0] == 1) return 1;
            return 0;
        }
        
        else{
            if(v[0] == 1 and count(v.begin(), v.end(), v[0]) == v.size()) return 1;
            else if(v[0] == 1 and count(v.begin(), v.end(), v[0]) != v.size()){
                if(v.size() == 3 and v[v.size() - 1] == 2) return 1;
            }
            
            int sum = 0;
            for(int x : v) sum += x;
            
            if(sum == (v[0] * v.size() + 1)) return 1;
            else return 0;
        }
        return 0;
    }
};


================================================
FILE: Leetcode/Sort Colors/Sort Colors.cpp
================================================
class Solution {
public:
    void sortColors(vector& nums) {
        if(nums.size() == 0) return;
            int i=0, j=0, k = nums.size()-1;
            while(j<=k) {
                    if(nums[j] == 2) {
                            swap(nums[j], nums[k]);  k--;
                    }
                    if(nums[j] == 0) {
                            swap(nums[j], nums[i]);  i++; j++;
                    }else if(nums[j] == 1) {
                            j++;
                    }
            }
    }
};

================================================
FILE: Leetcode/Top K Frequent Words/Top K Frequent Words.cpp
================================================
class Solution {
public:
    #define ps pair
   class comp {
  public:
    bool operator() (const ps &p1, const ps &p2) {
      if(p1.first == p2.first) return p1.second < p2.second;
      
      return p1.first > p2.first;
    }
   }; 
    vector topKFrequent(vector& words, int k) {
        int n=words.size();
        
        unordered_mapmap;
        for(auto x:words){
            map[x]++;
        }
        
        priority_queue,comp>pq;
        
        for(auto x:map){
            pq.push({x.second,x.first});
            if(pq.size()>k) pq.pop();
        }
        vectorans(k);
        while(k--){
            ans[k]=pq.top().second;
            pq.pop();
        }
        return ans;
    }
};


================================================
FILE: Leetcode/Two Sum IV-Input is BST/Two Sum IV-Input is a BST.java
================================================
Solution 1:
Without using set:

Approach:
1.Doing Inorder Traversal 
2.Storing data values in an arraylist
3.Applying two pointer algorithm and if target is found return true else return false
  
Code:

class Solution {
    
    public void fun(TreeNode root,ArrayListaa){
        if(root==null){
            return ;
        }
        else{
            fun(root.left,aa);
            aa.add(root.val);
            fun(root.right,aa);
        }
    }
    public boolean findTarget(TreeNode root, int target) {
        ArrayListaa=new ArrayList();
        fun(root,aa);
        int start=0;
        int end=aa.size()-1;
        while(starttarget){
                end--;
            }
            else{
                start++;
            }
        }
        return false;
    }
    
  
  
  
Solution 2:
Using Set:
  
  
  Approach:
1.Doing Inorder Traversal 
2.While traversal if we get (target-root.val) in set we made flag as true else add the root.val in set.
3.return flag. If flag==true it means target is found else target sum is not present in the BST.
  
  class Solution {
   
    HashSetset=new HashSet();//global set
    boolean flag=false;//global variable
    
    
    public void fun(TreeNode root,int target){
        if(root==null){
            return;
        }
        if(set.contains(target-root.val)){
            flag=true;
        }
        else{
            set.add(root.val);
        }
        fun(root.left,target);
        fun(root.right,target);
    }
     public boolean findTarget(TreeNode root, int target) {
         fun(root,target);
         return flag;
     }
}



================================================
FILE: Length of Last Word.java
================================================
public class Solution {
    // DO NOT MODIFY THE LIST. IT IS READ ONLY
    public int lengthOfLastWord(final String s) {
        int ans=0;
        boolean started=false;
        for(int i=s.length()-1;i>=0;i--){
            if(s.charAt(i)==' '){
                if(started){
                    return ans;
                }
            }else{
                started=true;
                ans++;
            }
        }
        return ans;
    }
}


================================================
FILE: Length of longest palindrome in Linked List.java
================================================
class GfG
{
        public static int fun(LinkedListlist,int start, int end){
            //System.out.println("Hi");
            
            while(startlist=new LinkedList();
          Node temp=head;
          while(temp!=null){
              list.add(temp.data);
              temp=temp.next;
          }
          int max=01;
          int end=list.size()-1;
          int start=0;
          
         for(int i=0;ii;j--){
                 if(list.get(i)==list.get(j)){
                     //System.out.println("hi"+list.get(i));
                     int a=fun(list,i,j);
                     if(a!=-1){
                         max=Integer.max(max,j-i+1);
                         break;
                     }
                 }
                 
                 
                 
                
             }
         }
          
          return max;
          
        }
}


================================================
FILE: Length of longest palindrome in linked list.java
================================================
class GfG
{
   
        public static int maxPalindrome(Node head)
        {
          //add code here.
          ArrayList al = new ArrayList<>();
          while(head != null){
              al.add(head.data);
              head = head.next;
          }
          int[] arr = new int[2];
          int center = 0;
          while(center < al.size()){
              center = binary(al,center,arr);
              center++;
          }
          return(arr[1]-arr[0]-1);
        }
        public static int binary(ArrayList al , int i, int[] arr){
            int n = al.size();
            int new_center = i;
            int t = i;
            while(new_center < n-1 && al.get(new_center) == al.get(new_center+1) ){
                new_center++;
            }
            int center = new_center;
            while(t >= 0 && new_center < n && al.get(t) == al.get(new_center) ){
                t--;
                new_center++;
            }
            if(arr[1]-arr[0]-1 < new_center-t-1){
                arr[0] = t;
                arr[1] = new_center;
            }
            return center;
        }
}


================================================
FILE: Letter Phone.java
================================================
public class Solution {
    String[] map = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    public ArrayList letterCombinations(String digits) {
        ArrayList res = new ArrayList<>();
        if(digits == null || digits.length() == 0){
            return res;
        }
        dfs(digits, 0, new StringBuilder(), res);
        return res;
    }
    
    public void dfs(String digits, int index, StringBuilder sb, ArrayList res){
        if(index == digits.length()){
            res.add(sb.toString());
            return;
        }
        
        String str = map[digits.charAt(index) - '0'];
        for(int i = 0; i < str.length(); i++){
            sb.append(str.charAt(i));
            dfs(digits, index + 1, sb, res);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}


================================================
FILE: Level Order.java
================================================
public class Solution {
    public ArrayList> levelOrder(TreeNode A) {
        Queue q=new LinkedList<>();
        q.add(A);
        ArrayList> ans=new ArrayList<>();

        while(!q.isEmpty()){
            int size=q.size();
            ArrayList arr=new ArrayList<>();
            for(int i=0;i0 && m>0){
            if(selectOne){
                h+=3;
                m+=2;
                level++;
                selectOne=false;
            }else{
                selectOne=true;
                level++;
                if(h>5 && m>10){
                    h-=5;
                    m-=10;
                }else{
                    h-=20;
                    m+=5;
                }
            }
        }
        return level-1;
    }
}


================================================
FILE: Licence Key Formatting.java
================================================
class Solution{
    static String ReFormatString(String s, int k){
        StringBuilder sb=new StringBuilder(s);
        StringBuilder sb2=new StringBuilder();
        for(int i=0;i=0;i--){
           if(s.charAt(i)!='-'){
               if(count==k){
                   count=01;
                   sb1.append("-");
                   sb1.append(sb.charAt(i));
               }
               else{
                   count++;
                   sb1.append(sb.charAt(i));
               }
           }
           
        }
        sb1.reverse();
        return sb1.toString();
        
        
    }
}


================================================
FILE: License Key Formatting GFG/Licence.cpp
================================================
string ReFormatString(string S, int K){
    	  int len=0;
        string temp="";
        for(int i=0;i=0; i--){
    	    if(tmp.length()==K){
    	        if(str.length()==0) str = tmp;
    	        else str = tmp + "-" + str ;
    	        tmp = "";
    	    }
    	    if(S[i]!='-'){  
    	        char ch;
    	        if(islower(S[i])) ch = toupper(int(S[i]));
    	        else ch = S[i];
    	        tmp = ch + tmp;
    	    }
    	}

    	if(tmp.length()>0){
        	if(str.length()==0) str = tmp;
        	else str = tmp + "-" + str;
    	}

    	return str;
    }
};


================================================
FILE: License Key Formatting med s21.cpp
================================================
#include
using namespace std;
class Solution
{
   public:
    string ReFormatString(string S, int K){
    	int n = S.size()-1,size =0;
    	string res="", temp="";
    	
    	while(n>=0){
    	    while(size=0){
    	        if(S[n]!='-'){
    	           // to check alphabets
    	           int check = isalpha(S[n]);
    	           if(check){
    	               S[n] = toupper(S[n]);
    	           }
    	           temp+=S[n];
    	           size++;
    	        }
    	        n--;
    	    }
    	    size=0;
    	    res+=temp;
    	    temp.clear();
    	    if(n>=0) res+='-';
    	}
    	reverse(res.begin(), res.end());
    	if(res[0]=='-') return res.substr(1);
    	return res;
    	
    }
};

int main()
{
	int t;
	cin>>t;
	while(t--)
	{
	    string S;
	    cin>>S;
	    int K;
	    cin >> K;
	    Solution ob;  
	    string ans=ob.ReFormatString(S, K);
	    cout<
using namespace std;

// } Driver Code Ends
//Back-end complete function Template for C++
class Solution
{
   public:
    string ReFormatString(string S, int K){
    	
    	int n = S.size();
    	string ans, temp;
    	
    	/*we start fro the end of the string , 
    	because only the first group can have contain characters less than K*/
    	for(int i=n-1;i>=0;i--){           
    	    char ch = S[i];
    	    
    	    //if we encounter a dash, ignore and continue
    	    if(ch=='-')
    	        continue;
    	    else{
    	        
    	        //change to uppercase
    	        temp+=toupper(ch);
    	        
    	        //check temp size
    	        if(temp.size() == K){
    	            
    	            //add temp to ans
    	            ans+=temp;      
    	            
    	            //add dash b/w them
    	            ans+='-';
    	            
    	            //empty the temp to search for next K elements
    	            temp="";
    	        }
    	    }
    	}
    	
    	/*Adding the leftover elements(Since the size of temp never reached K, 
    	temp won't enter the if case nested inside the else ABOVE)*/
    	ans+=temp;
    	
    	//Since we stored the elements in temp in reverse order, we'll reverse
    	reverse(ans.begin(), ans.end());
    	
    	//Incase the first element is a dash, we would remove it
    	if(ans[0] == '-')
    	    ans.erase(ans.begin());
    	    
    	return ans;
    }
};

//{ Driver Code Starts.
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
	    string S;
	    cin>>S;
	    int K;
	    cin >> K;
	    Solution ob;  
	    string ans=ob.ReFormatString(S, K);
	    cout<=0;i--){
    	   if(s[i] == '-'){
    	       if(cnt== k){
    	           cnt=0;
    	           ans+= '-';
    	       }
    	   }else{
    	       if(cnt == k){
    	           ans+= '-';
    	           cnt=0;
    	       }
    	       cnt++;
    	       if(s[i] <= 'z' && s[i] >= 'a'){
    	           ans += char('A' + (s[i]-'a'));
    	       }else{
    	           ans+= s[i];
    	       }
    	   }
    	}
    	if(ans.back() == '-'){
    	    ans.pop_back();
    	}
    	reverse(ans.begin(), ans.end());
    	return ans;
    }
};


================================================
FILE: License Key Formatting.java
================================================
class Solution{
    static String ReFormatString(String S, int K){
        StringBuilder ans = new StringBuilder();
        int cnt = 0;
        for(int i = S.length() - 1; i >= 0; i--) {
                char ch = S.charAt(i);
                if(ch != '-' && cnt < K){
                    ans.append(Character.toUpperCase(ch));
                    cnt++;
                }
                if(cnt==K){
                    cnt = 0;
                    ans.append('-');
                }
        }
        ans.reverse();
        if(ans.length() > 0 && ans.charAt(0)=='-') ans.deleteCharAt(0);
        return ans.toString();
        
    }
}


================================================
FILE: Linked List Cycle II.java
================================================
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode meet=detect(head);
        if(meet==null)return meet;
        ListNode temp=head;
        while(temp!=meet){
            temp=temp.next;
            meet=meet.next;
        }
        return temp;
    }
    public ListNode detect(ListNode node){
        ListNode slow=node;
        ListNode fast=node;
        while(fast!=null && fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
            if(slow==fast)return fast;
        }
        return null;
    }
}


================================================
FILE: Linked List Cycle.java
================================================
public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode slow=head;
        ListNode fast=head;
        while(fast!=null && fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
            if(slow==fast)return true;
        }
        return false;
    }
}


================================================
FILE: Longest Bitonic subsequence.cpp
================================================
class Solution{
	public:
	int LongestBitonicSequence(vectornums)
	{
	    vector Incre(nums.size(), 0 ), Dec(nums.size(), 0);
	    
	    Incre[0] = 1;
	    for(int i=1; i=0; i--){
	        int mx = 0;
	        for(int j=i+1;j a) {
        String ans=a.get(0);
        int index=0;
        String s="";
        for(int i=1;isz){
                    sz=j-i+1;
                    asnI=i;
                    ansJ=j+1;
                }
            }
        }
        return s.substring(asnI,ansJ);
    }
}


================================================
FILE: Longest Path in a matrix - GFG/README.md
================================================
# Longest Path in a matrix
## Hard 

Given a n*m matrix, find the maximum length path (starting from any cell) such that all cells along the path are in strictly increasing order.

We can move in 4 directions from a given cell (i, j), i.e., we can move to (i+1, j) or (i, j+1) or (i-1, j) or (i, j-1).
 

Example 1:

Input: matrix = {{1,2,9},{5,3,8},{4,6,7}}
Output: 7
Explanation: The longest increasing path is
{1,2,3,6,7,8,9}.

Example 2:

Input: matrix = {{3,4,5},{3,2,6},{2,2,1}}
Output: 4
Explanation: The longest increasing path is
{3,4,5,6}.

 

Your Task:
You don't need to read or print anyhting. Your task is to complete the function longestIncreasingPath() which takes matrix as input parameter and returns the length of the lonest increasing path.

Expected Time Complexity: O(n*m)
Expected Space Comeplxity: O(n*m)

 

Constraints:
1 <= n, m <= 100
1 <= matrix[i][j] <= 104

================================================ FILE: Longest Path in a matrix - GFG/longest-path-in-a-matrix.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String[] S1 = br.readLine().trim().split(" "); int n = Integer.parseInt(S1[0]); int m = Integer.parseInt(S1[1]); int[][] matrix = new int[n][m]; for(int i = 0; i < n; i++){ String[] S2 = br.readLine().trim().split(" "); for(int j = 0; j < m; j++){ matrix[i][j] = Integer.parseInt(S2[j]); } } Solution obj = new Solution(); int ans = obj.longestIncreasingPath(matrix); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution{ int[][]dp; int [][]arr; public int longestIncreasingPath(int[][] matrix){ int n=matrix.length; int m=matrix[0].length; dp=new int[n][m]; arr=matrix; int ans=Integer.MIN_VALUE; for(int i=0;iarr[i][j]){ int curr=dfs(i+1,j); ans=Math.max(ans,curr); } if(valid(i-1,j) && arr[i-1][j]>arr[i][j]){ int curr=dfs(i-1,j); ans=Math.max(ans,curr); } if(valid(i,j+1) && arr[i][j+1]>arr[i][j]){ int curr=dfs(i,j+1); ans=Math.max(ans,curr); } if(valid(i,j-1) && arr[i][j-1]>arr[i][j]){ int curr=dfs(i,j-1); ans=Math.max(ans,curr); } dp[i][j]=ans+1; return dp[i][j]; }else{ return 0; } } public boolean valid(int i,int j){ int n=arr.length; int m=arr[0].length; if(i<0 || j<0 || i==n || j==m)return false; return true; } } ================================================ FILE: Longest Possible Route in a Matrix with Hurdles - GFG/README.md ================================================ # Longest Possible Route in a Matrix with Hurdles ## Medium

Given an N x M matrix, with a few hurdles(denoted by 0) arbitrarily placed, calculate the length of the longest possible route possible from source(xs,ys) to a destination(xd,yd) within the matrix. We are allowed to move to only adjacent cells which are not hurdles. The route cannot contain any diagonal moves and a location once visited in a particular path cannot be visited again.If it is impossible to reach the destination from the source return -1.

 

Example 1:

Input:
{xs,ys} = {0,0}
{xd,yd} = {1,8}
matrix = 1 1 1 1 1 1 1 1 1 1
         1 1 0 1 1 0 1 1 0 1
         1 1 1 1 1 1 1 1 1 1
Output: 24
Explanation:

 

Example 2:

Input: 
{xs,ys} = {0,3}
{xd,yd} = {2,2}
matrix = 1 0 0 1 0
         0 0 0 1 0
         0 1 1 0 0
Output: -1
Explanation:
We can see that it is impossible to
reach the cell (2,2) from (0,3).

Your Task:
You don't need to read input or print anything. Your task is to complete the function longestPath() which takes matrix ,source and destination as input parameters and returns an integer denoting the longest path.


Expected Time Complexity: O(2^(N*M))
Expected Auxiliary Space: O(N*M)


Constraints:
1 <= N,M <= 10

================================================ FILE: Longest Possible Route in a Matrix with Hurdles - GFG/longest-possible-route-in-a-matrix-with-hurdles.java ================================================ // { Driver Code Starts import java.io.*; import java.util.*; class IntArray { public static int[] input(BufferedReader br, int n) throws IOException { String[] s = br.readLine().trim().split(" "); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = Integer.parseInt(s[i]); return a; } public static void print(int[] a) { for(int e : a) System.out.print(e + " "); System.out.println(); } public static void print(ArrayList a) { for(int e : a) System.out.print(e + " "); System.out.println(); } } class IntMatrix { public static int[][] input(BufferedReader br, int n, int m) throws IOException { int[][] mat = new int[n][]; for(int i = 0; i < n; i++) { String[] s = br.readLine().trim().split(" "); mat[i] = new int[s.length]; for(int j = 0; j < s.length; j++) mat[i][j] = Integer.parseInt(s[j]); } return mat; } public static void print(int[][] m) { for(var a : m) { for(int e : a) System.out.print(e + " "); System.out.println(); } } public static void print(ArrayList> m) { for(var a : m) { for(int e : a) System.out.print(e + " "); System.out.println(); } } } class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t; t = Integer.parseInt(br.readLine()); while(t-- > 0){ int[] a = IntArray.input(br, 2); int[] b = IntArray.input(br, 4); int[][] mat = IntMatrix.input(br, a[0], a[1]); Solution obj = new Solution(); int res = obj.longestPath(mat,a[0],a[1],b[0],b[1],b[2],b[3]); System.out.println(res); } } } // } Driver Code Ends class Solution { static int xd; static int yd; public static int longestPath(int[][] mat,int n,int m,int xs,int ys,int x,int y) { xd=x; yd=y; boolean[][]vis=new boolean[n][m]; int ans=dfs(mat,xs,ys,vis); return ans<0?-1:ans; } public static int dfs(int[][]mat,int x,int y,boolean[][]vis){ if(!valid(mat,x,y,vis))return Integer.MIN_VALUE; if(x==xd && y==yd)return 0; vis[x][y]=true; int ans=Integer.MIN_VALUE; if(valid(mat,x+1,y,vis)) ans=Math.max(ans,1+dfs(mat,x+1,y,vis)); if(valid(mat,x,y+1,vis)) ans=Math.max(ans,1+dfs(mat,x,y+1,vis)); if(valid(mat,x-1,y,vis)) ans=Math.max(ans,1+dfs(mat,x-1,y,vis)); if(valid(mat,x,y-1,vis)) ans=Math.max(ans,1+dfs(mat,x,y-1,vis)); vis[x][y]=false; return ans; } public static boolean valid(int[][]mat,int x,int y,boolean[][]vis){ if(x<0 || y<0 || x==mat.length || y==mat[0].length)return false; if(mat[x][y]==0 || vis[x][y])return false; return true; } } ================================================ FILE: Longest Sub-Array with Sum K.cpp ================================================ class Solution{ public: int lenOfLongSubarr(int A[], int N, int K) { // Complete the function map mp; mp.insert({0,-1}); int ans = 0, sum = 0; for(int i=0; i map=new HashMap<>(); int sum=0; int length=0; for(int i=0;i

Given an array containing N integers and a positive integer K, find the length of the longest sub array with sum of the elements divisible by the given value K.

Example 1:

Input:
A[] = {2, 7, 6, 1, 4, 5}
K = 3
Output: 4
Explanation:The subarray is {7, 6, 1, 4}
with sum 18, which is divisible by 3.

Example 2:

Input:
A[] = {-2, 2, -5, 12, -11, -1, 7}
K = 3
Output: 5
Explanation:
The subarray is {2,-5,12,-11,-1} with
sum -3, which is divisible by 3.

 

Your Task:
The input is already taken care of by the driver code. You only need to complete the function longSubarrWthSumDivByK() that takes an array (arr), sizeOfArray (n), positive integer K, and return the length of the longest subarray which has sum divisible by K. The driver code takes care of the printing.

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).

Constraints:
1<=N,K<=106
-105<=A[i]<=105

 

================================================ FILE: Longest subarray with sum divisible by K - GFG/longest-subarray-with-sum-divisible-by-k.java ================================================ // { Driver Code Starts //Initial Template for Java //Initial Template for Java /*package whatever //do not write package name here */ import java.io.*; import java.util.*; // } Driver Code Ends //User function Template for Java class Solution{ int longSubarrWthSumDivByK(int a[], int n, int k){ int prefixSum = 0; int maxResult = 0; HashMap map = new HashMap<>(); for (int i = 0; i < a.length; i++) { prefixSum += a[i]; int rem = ((prefixSum%k) + k) % k; if(rem == 0)maxResult = i + 1; if(map.containsKey(rem)) maxResult = Math.max(maxResult,i-map.get(rem)); else map.put(rem,i); } return maxResult; } } // { Driver Code Starts. // Driver class class GFG { // Driver code public static void main (String[] args) throws IOException{ // Taking input using buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testcases = Integer.parseInt(br.readLine()); // looping through all testcases while(testcases-- > 0){ String line1 = br.readLine(); String[] element = line1.trim().split("\\s+"); int sizeOfArray = Integer.parseInt(element[0]); int K = Integer.parseInt(element[1]); int arr [] = new int[sizeOfArray]; String line = br.readLine(); String[] elements = line.trim().split("\\s+"); for(int i = 0;i

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

================================================ FILE: Longest substring to form a Palindrome - GFG/longest-substring-to-form-a-palindrome.java ================================================ // { Driver Code Starts import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { String S = read.readLine(); Solution ob = new Solution(); System.out.println(ob.longestSubstring(S)); } } }// } Driver Code Ends //User function Template for Java class Solution { static int longestSubstring(String S) { int n = S.length(); Map index = new HashMap<>(); // Initialize answer with 0 int answer = 0; int mask = 0; index.put(mask, -1); for(int i = 0; i < n; i++){ int temp = (int)S.charAt(i) - 97; // Turn the temp-th bit on if // character occurs odd number // of times and turn off the temp-th // bit off if the character occurs // ever number of times mask ^= (1 << temp); // If a mask is present in the index // Therefore a palindrome is // found from index[mask] to i if (index.containsKey(mask)){ answer = Math.max(answer, i - index.get(mask)); } // If x is not found then add its // position in the index dict. else index.put(mask,i); // Check for the palindrome of // odd length for (int j = 0;j < 26; j++){ // We cancel the occurrence // of a character if it occurs // odd number times int mask2 = mask ^ (1 << j); if (index.containsKey(mask2)) { answer = Math.max(answer, i - index.get(mask2)); } } } return answer; } }; ================================================ FILE: Longest valid Parentheses.java ================================================ public class Solution { public int longestValidParentheses(String s) { int ans=0; int n=s.length(); int open=0; int close=0; for(int i=0;iopen){ open=close=0; }else if(open==close) ans=Math.max(ans,open*2); } open=close=0; for(int i=n-1;i>=0;i--){ if(s.charAt(i)==')') close++; else open++; if(close> map=new HashMap<>(); for(int i=0;i()); for(int j=0;j> map,int currNode,int[]col,int n,int m){ if(currNode==n)return true; for(int currColor=1;currColor<=m;currColor++){ if(safe(currNode,currColor,map,col)){ col[currNode]=currColor; if(dfs(map,currNode+1,col,n,m))return true; col[currNode]=0;//backtracking } } return false; } boolean safe(int currNode,int currColor,Map> map,int[]col){ ArrayList arr=map.get(currNode); for(int neb:arr){ if(col[neb]==currColor)return false; } return true; } } ================================================ FILE: MInimum time to fulfil all orders.cpp ================================================ class Solution{ public: // Function to return number of donuts prepared by R rank in T time int countDonut(int R, int T) { int cnt = 1; while(T-R*cnt >= 0) { T -= R*cnt; cnt++; } return cnt-1; } int findMinTime(int N, vector&A, int L){ //write your code here int ans = INT_MAX; int low = 0, high = INT_MAX; while(low <= high) { int mid = low + (high-low)/2; int cnt = 0; for(auto it : A) cnt += countDonut(it, mid); if(cnt >= N) { ans = mid; high = mid-1; } else low = mid+1; } return ans; } }; ================================================ FILE: Magician and Chocolates.java ================================================ public class Solution { public int nchoc(int A, ArrayList B) { Queue pq=new PriorityQueue<>((a,b)->b-a); pq.addAll(B); int ans=0; int mod=1000000007; while(A-->0){ int ele=pq.remove(); ans=(ans%mod +ele%mod)%mod; pq.add(ele/2); } return ans; } } ================================================ FILE: Magnet Array Problem - GFG/README.md ================================================ # Magnet Array Problem ## Medium

Given N Magnets which are placed linearly, with each magnet to be considered as of point object. Each magnet suffers force from its left sided magnets such that they repel it to the right and vice versa. All forces are repulsive. The force being equal to the distance (1/d , d being the distance). Now given the positions of the magnets, the task to find all the points along the linear line where net force is ZERO

More Formally, Magnets are placed on X axis, the coordinates of which are given, you are asked to find out the X-co-ordinates of all the equilibrium points (i.e. the point where net force is zero). You notice the point each magnet repels each other, it means the polarity of the magnet is such that exerts +ve force in its right side and -ve force in left side, (here +ve is considered in +ve direction of x-axis). And that forces are inversely proportional to the distance, thus there lies an equilibrium point between every two magnetic points. Thus there will be total of N-1 equllibrium points. You have to find those N-1 points.
Note: Array M[] is sorted and distance have to be calculated with precision of 2 decimal places.

 

Example 1:

Input:
N = 2
M[] = {1, 2}
Output:
1.50
Explanation:
The mid point of two points will have 
net force zero, thus answer = 1.50

 

Example 2:

Input:
N = 4
M[] = {0, 10, 20, 30}
Output:
3.82, 15.00, 26.18

 

Your Task:  
You don't need to read input or print anything. Your task is to complete the function nullPoints() which takes the array M[], its size N as inputs and an answer array getAnswer[] to store the points having net force zero till precised two decimal places.


Expected Time Complexity: O(N2 * Log(N))
Expected Auxiliary Space: O(1)

 

Constraints:
2 ≤ N ≤ 105
0 ≤  M[1] < ....M[i] < M[i+1] < ....M[N] ≤ 106

 

 

 

 

================================================ FILE: Magnet Array Problem - GFG/magnet-array-problem.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); // Inputting the testcases while(t-->0) { int n = Integer.parseInt(br.readLine().trim()); double a[] = new double[(int)(n)]; double getAnswer[] = new double[(int)(n)]; String inputLine[] = br.readLine().trim().split(" "); for (int i = 0; i < n; i++) { a[i] = Double.parseDouble(inputLine[i]); } Solution obj = new Solution(); obj.nullPoints(n, a, getAnswer); StringBuilder output = new StringBuilder(); for(int i=0;i map=new HashMap<>(); for(int i=0;i set=new HashSet<>(); set.add(A[0]+B); set.add(A[0]-B); for(int i=1;i> &dp, int arr[] , int i , int j) { if(i == j) return dp[i][j] = 0; if(dp[i][j] != -1) return dp[i][j]; int mn = INT_MAX; for(int k = i;k> dp(N-1 , vector(N-1 , -1)); solve(dp , arr , 0 , N-2); return dp[0][N-2]; // code here } }; ================================================ FILE: Matrix Exponentiation - GFG/README.md ================================================ # Matrix Exponentiation ## Medium

Given an equation of the form f(n) = f(n-1) + f(n-2) where f(0) = 1, F(1) = 1 , the task is to find the nth term of this sequence.
 

Example 1:

Input: n = 3
Output: 3
Explanation: f(3) = f(2) + f(1) = 3

Example 2:

Input: n = 2
Output: 2
Explanation: f(2) = f(1) + f(0) = 2

 

Yout Task:
You don't need to read or print anything. Your task is to complete the function FindNthTerm() which takes n as input parameter and returns nth term mod 10^9+7 .


Expected Time Compelxity: O(log(n))
Expected Space Complexity: O(K) where K is constant.

 

Constraints:
1 <= n <= 109

================================================ FILE: Matrix Exponentiation - GFG/matrix-exponentiation.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { int n = Integer.parseInt(br.readLine().trim()); Solution ob = new Solution(); int ans = ob.FindNthTerm(n); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution { static long mod = 1000000007; long[][] multiply(long [][]m1, long[][]m2) { long ans[][] =new long[2][2]; for(int i=0;i<2;i++) for(int j=0;j<2;j++) for(int k=0;k<2;k++) ans[i][j] += (m1[i][k]*m2[k][j])%mod; return ans; } long[][] matPow(long [][]mat,long n){ if(n == 1)return mat; long[][] ans = matPow(mat,n/2); ans = multiply(ans,ans); if((n&1) == 1)ans = multiply(ans,mat); return ans; } public int FindNthTerm(int N){ long n = N; if(n==1 || n==0)return 1; long mat[][] = {{1,1},{1,0}}; mat = matPow(mat,n); return (int) (mat[0][0]%mod); } } ================================================ FILE: Matrix Operations.java ================================================ class Solution{ static int[]UP=new int[]{-1,0}; static int[]RIGHT=new int[]{0,1}; static int[]DOWN=new int[]{1,0}; static int[]LEFT=new int[]{0,-1}; static int [] endPoints(int [][]arr, int m, int n){ char dir='R'; int row=0; int col=0; while(true){ if(arr[row][col]==1){ arr[row][col]=0; dir=changeDir(dir); } int[]move=getDir(dir); if(outOfBounds(arr,row+move[0],col+move[1])){ return new int[]{row,col}; }else{ row+=move[0]; col+=move[1]; } } } static boolean outOfBounds(int[][] arr,int row,int col){ int a=arr.length; int b=arr[0].length; if(row>=a)return true; if(col>=b)return true; if(row<0 || col<0)return true; return false; } static int[] getDir(char c){ if(c=='U'){ return UP; }else if(c=='D'){ return DOWN; }else if(c=='R'){ return RIGHT; }else{ return LEFT; } } static char changeDir(char c){ if(c=='R'){ return 'D'; }else if(c=='D'){ return 'L'; }else if(c=='L'){ return 'U'; }else{ return 'R'; } } } ================================================ FILE: Matrix Search.java ================================================ public class Solution { public int searchMatrix(ArrayList> A, int B) { return dfs(A,B,0,A.size()-1); } public int dfs(ArrayList> A, int B,int l,int h){ if(l<=h){ int mid=l+(h-l)/2; if(A.get(mid).get(0)>B){ return dfs(A,B,l,mid-1); }else if(A.get(mid).get(A.get(mid).size()-1)=0;i--) rmax[i]=Math.max(rmax[i+1],arr[i]); int i=0,j=0; while(i maxset(ArrayList a) { long max=0; ArrayList ans=new ArrayList<>(); int i=0; while(i maybe=new ArrayList<>(); while(imax){ max=curr; ans.clear(); ans=maybe; }else if(curr==max){ if(maybe.size()>ans.size()){ ans.clear(); ans=maybe; } } i++; } return ans; } } ================================================ FILE: Max Product Subarray.java ================================================ public class Solution { // DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY public int maxProduct(final int[] nums) { int length = nums.length; int result = nums[0];; int curr_max = nums[0]; int curr_min = nums[0]; for(int i =1; i < length; i++){ int curr_max_prev= curr_max; curr_max = Math.max(nums[i], Math.max(curr_max*nums[i], curr_min*nums[i])); curr_min = Math.min(nums[i], Math.min(curr_max_prev*nums[i], curr_min*nums[i])); result = Math.max(result,curr_max); } return result; } } ================================================ FILE: Max Rectangle in Binary Matrix.java ================================================ public class Solution { public int maximalRectangle(int[][] a) { int max=Integer.MIN_VALUE; for(int i=0;i s=new ArrayDeque<>(); for(int i=0;i=a[i]){ s.pop(); } if(s.isEmpty()){ ps[i]=-1; }else{ ps[i]=s.peek(); } s.push(i); } return ps; } public int[] nextSmallest(int[]a){ int ns[]=new int[a.length]; Deque s=new ArrayDeque<>(); for(int i=a.length-1;i>=0;i--){ while(!s.isEmpty() && a[s.peek()]>=a[i]){ s.pop(); } if(s.isEmpty()){ ns[i]=a.length; }else{ ns[i]=s.peek(); } s.push(i); } return ns; } } ================================================ FILE: Max Sum Path in Binary Tree.java ================================================ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { Map map; public int maxPathSum(TreeNode A) { if(A==null)return 0; map=new HashMap<>(); return dfs(A); } int dfs(TreeNode A){ if(A==null) return Integer.MIN_VALUE; int s=A.val; if(A.left!=null && sum(A.left)>0) s=s+sum(A.left); if(A.right!=null && sum(A.right)>0) s=s+sum(A.right); return max(s,dfs(A.left),dfs(A.right)); } int max(int a,int b,int c){ return (a>b&&a>c?a:(b>c?b:c)); } int sum(TreeNode A){ if(A==null) return 0; if(map.containsKey(A))return map.get(A); int ans=A.val+Math.max(sum(A.left),sum(A.right)); map.put(A,ans); return ans; } } ================================================ FILE: Max length chain.cpp ================================================ class Solution{ public: /*You are required to complete this method*/ int maxChainLen(struct val p[],int n){ //Your code here vector>ans; for(int i=0;ix) { x = ans[i+1].first; count++; } } return count; } }; ================================================ FILE: Max length chain.java ================================================ class GfG { int maxChainLength(Pair arr[], int n) { Arrays.sort(arr,(a,b)->a.y-b.y); int ans=1; int prev=arr[0].y; for(int i=1;iprev){ prev=arr[i].y; ans++; } } return ans; } } ================================================ FILE: Maximize Distance to Closest Person ================================================ class Solution { public int maxDistToClosest(int[] seats) { int max=Integer.MIN_VALUE; for(int i=0;i=0){ leftClosest++; if(a[x]==1)break; x--; } int y=i+1; int rightClosest=0; while(y

Given two integer arrays Arr1 and Arr2 of size N. Use the greatest elements from the given arrays to create a new array of size N such that it consists of only unique elements and the sum of all its elements is maximum.
The created elements should contain the elements of Arr2 followed by elements of Arr1 in order of their appearance.


Example 1:

Input:
N = 5
Arr1 = {7, 4, 8, 0, 1}
Arr2 = {9, 7, 2, 3, 6}
Output: 9 7 6 4 8
Explanation: 9, 7, 6 are from 2nd array
and 4, 8 from 1st array.


Example 2:

Input: N = 4
Arr1 = {6, 7, 5, 3}
Arr2 = {5, 6, 2, 9} 
Output: 5 6 9 7 
Explanation: 5, 6, 9 are from 2nd array
and 7 from 1st array.


Your Task:
You don't need to read input or print anything. Your task is to complete the function maximizeArray() which takes the array arr1[], arr2[] and n as input parameters and returns the desired array of integers.


Expected Time Complexity: O(NlogN)
Expected Auxiliary Space: O(N)


Constraints:
1 <= N <= 105
0 <=| Arr1[i] |<= 109
0 <= |Arr2[i] |<= 109

================================================ FILE: Maximize The Array - GFG/maximize-the-array.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; import java.lang.*; public class GFG { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tc = Integer.parseInt(br.readLine().trim()); while (tc-- > 0) { String[] inputLine; int n = Integer.parseInt(br.readLine().trim()); int[] arr1 = new int[n], arr2 = new int[n]; inputLine = br.readLine().trim().split(" "); for (int i = 0; i < n; i++) { arr1[i] = Integer.parseInt(inputLine[i]); } inputLine = br.readLine().trim().split(" "); for (int i = 0; i < n; i++) { arr2[i] = Integer.parseInt(inputLine[i]); } ArrayList ans = new Solution().maximizeArray(arr1, arr2, n); for (Integer x : ans) { System.out.print(x + " "); } System.out.println(); } } } // } Driver Code Ends class Solution { ArrayList maximizeArray(int[] arr1, int[] arr2, int n) { ArrayList ans=new ArrayList<>(); PriorityQueue pq=new PriorityQueue<>((a,b)->b-a); for(int i:arr1)pq.add(i); for(int i:arr2)pq.add(i); Set set=new HashSet(); while(set.size()!=n && pq.size()>0){ set.add(pq.remove()); } for(int i:arr2){ if(set.contains(i)){ ans.add(i); set.remove(i); } } for(int i:arr1){ if(set.contains(i)){ ans.add(i); set.remove(i); } } return ans; } } ================================================ FILE: Maximize the sum of selected numbers from an array to make it empty - GFG/README.md ================================================ # Maximize the sum of selected numbers from an array to make it empty ## Medium

Given a array of N numbers, we need to maximize the sum of selected numbers. At each step, you need to select a number Ai, delete one occurrence of Ai-1 (if exists), and Ai each from the array. Repeat these steps until the array gets empty. The problem is to maximize the sum of the selected numbers.

Example 1:

Input : arr[ ] = {1, 2, 2, 2, 3, 4}
Output : 10
Explanation:
We select 4, so 4 and 3 are deleted leaving us with {1,2,2,2}.
Then we select 2, so 2 & 1 are deleted. We are left with{2,2}.
We select 2 in next two steps, thus the sum is 4+2+2+2=10.


Example 2:

Input : arr[ ] = {1, 2, 3} 
Output :  4
Explanation: We select 3, so 3 and 2 are deleted leaving us with {1}. Then we select 1, 0 doesn't exist so we delete 1. thus the sum is 3+1=4.

 

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 maximizeSum() that takes an array (arr), sizeOfArray (n), and return the maximum sum of the selected numbers. The driver code takes care of the printing.

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).


Constraints:
1 ≤ N ≤ 105
1 ≤ A[i] ≤ 105
Note: Numbers need to be selected from maximum to minimum.

================================================ FILE: Maximize the sum of selected numbers from an array to make it empty - GFG/maximize-the-sum-of-selected-numbers-from-an-array-to-make-it-empty.java ================================================ //{ Driver Code Starts //Initial Template for Java //Initial Template for Java /*package whatever //do not write package name here */ import java.io.*; import java.util.*; class Array { // Driver code public static void main (String[] args) throws IOException{ // Taking input using buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testcases = Integer.parseInt(br.readLine()); // looping through all testcases while(testcases-- > 0){ String line = br.readLine(); String[] element = line.trim().split("\\s+"); int sizeOfArray = Integer.parseInt(element[0]); int arr [] = new int[sizeOfArray]; line = br.readLine(); String[] elements = line.trim().split("\\s+"); for(int i = 0;i=0;i--){ int curr=arr[i]; if(map[curr]!=0){ sum+=curr; map[curr]--; if(map[curr-1]!=0){ map[curr-1]--; } } } return sum; } } ================================================ FILE: Maximum Depth of Binary Tree.java ================================================ class Solution { public int maxDepth(TreeNode root) { if(root==null){ return 0; } return Math.max(maxDepth(root.right),maxDepth(root.left))+1; } } ================================================ FILE: Maximum GCD of siblings of a binary tree - GFG/README.md ================================================ # Maximum GCD of siblings of a binary tree ## Easy

Given a 2d list that represents the nodes of a Binary tree with N nodes, the task is to find the maximum GCD of the siblings of this tree without actually constructing it.
Note: If there are no pairs of siblings in the given tree, print 0. Also, if given that there's an edge between a and b in the form of {a,b} in the list, then a is the parent node.


Example 1:

Input:
N = 7
arr = {{4, 5}, {4, 2}, {2, 3}, {2, 1}, {3, 6}, {3, 12}}
Output:
6
Explanation:

For the above tree, the maximum GCD
for the sibilings is 6, formed for the
nodes 6 and 12 for the children of node 3.
Example 2:
Input:
N = 3
arr[] = {{1,2}, {1,4}} 
Output :
2
Explanation:

For the above tree, the maximum GCD
for the sibilings is 2, formed for the
nodes 2 and 4 for the children of node 1.


Your Task:  
You don't need to read input or print anything. Your task is to complete the function maxBinTreeGCD() which takes an integer N and a 2-d list denoting the edges as input and returns the maximum GCD of sibilings of the tree.


Expected Time Complexity: O(E*logE), where E is the number of edges in the Tree.
Expected Auxiliary Space: O(1)


Constraints:
1 ≤ N ≤ 105
There might be edges with similar values

================================================ FILE: Maximum GCD of siblings of a binary tree - GFG/maximum-gcd-of-siblings-of-a-binary-tree.java ================================================ // { Driver Code Starts import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { int N = Integer.parseInt(read.readLine()); ArrayList> arr = new ArrayList<>(); for(int i=0; i temp = new ArrayList<>(); String S[] = read.readLine().split(" "); temp.add(Integer.parseInt(S[0])); temp.add(Integer.parseInt(S[1])); arr.add(temp); } Solution ob = new Solution(); System.out.println(ob.maxBinTreeGCD(arr,N)); } } }// } Driver Code Ends //User function Template for Java class Solution { static int getGCD(int a,int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return getGCD(a-b, b); return getGCD(a, b-a); } static int maxBinTreeGCD(ArrayList> arr, int N) { if(N==1)return 0; arr.sort((arr1,arr2)->arr1.get(0)-arr2.get(0)); int ans=0; int i=1; while(i arr1=arr.get(i); ArrayList arr2=arr.get(i-1); if(arr1.get(0)!=arr2.get(0)) i++; else{ ans=Math.max(ans,getGCD(arr1.get(1),arr2.get(1))); i+=2; } } return ans; } }; ================================================ FILE: Maximum Number of Words Found in Sentences.java ================================================ class Solution { public int mostWordsFound(String[] sentences) { int max=0; for(String s:sentences){ int cur=1; for(int i=0;ileft && !root->right) return root->data; int l = maxSum(root->left,sum); int r = maxSum(root->right,sum); // cout<data<<" "<left && root->right) sum = max(l+r+root->data,sum); return max(l,r) + root->data; } int maxPathSum(Node* root) { int out = 0; Node* tmp = root; int Sum = INT_MIN; out = maxSum(root,Sum); if(root->left== NULL || root->right==NULL) Sum = max(Sum,out); return Sum; } }; ================================================ FILE: Maximum Path in Triangle.java ================================================ public class Solution { int[][]dp; public int solve(int[][] A) { int n=A.length; dp=new int[n][n]; for(int i=0;i

Given a sequence of non-negative integers, find the subsequence of length 3 having maximum product, with the elements of the subsequence being in increasing order.

 

Example 1:

​Input:
n = 8
arr[ ] = {6, 7, 8, 1, 2, 3, 9, 10}
Output:
8 9 10
Explanation: 3 increasing elements of 
the given arrays are 8,9 and 10 which 
forms the subsequence of size 3 with 
maximum product.


​Example 2:

Input:
n = 4
arr[ ] = {3, 4, 2, 1} 
Output:
Not Present 

 

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 maxProductSubsequence() that takes an array arr, sizeOfArray n, and return the subsequence of size 3 having the maximum product, numbers of subsequence being in increasing order. If no such sequence exists, return "-1". The driver code takes care of the printing.


Expected Time Complexity: O(N*LOG(N)).
Expected Auxiliary Space: O(N).



Constraints:
1 <= N <= 105
1 <= Arr[i] <= 105

================================================ FILE: Maximum Product of Increasing Subsequence of Size 3 - GFG/maximum-product-of-increasing-subsequence-of-size-3.java ================================================ // { Driver Code Starts //Initial Template for Java //Initial Template for Java //Initial Template for Java /*package whatever //do not write package name here */ import java.io.*; import java.util.*; class Array { // Driver code public static void main (String[] args) throws IOException{ // Taking input using buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testcases = Integer.parseInt(br.readLine()); // looping through all testcases while(testcases-- > 0){ String line = br.readLine(); String[] element = line.trim().split("\\s+"); int N = Integer.parseInt(element[0]); int arr [] = new int[N]; line = br.readLine(); String[] elements = line.trim().split("\\s+"); for(int i = 0;i ans; ans = obj.maxProductSubsequence(arr, N); if(ans.get(0) == -1) System.out.println("Not Present"); else{ for(int i: ans) System.out.print(i + " "); System.out.println(); } } } } // } Driver Code Ends //User function Template for Java class Solution{ public static ArrayList maxProductSubsequence (int arr[], int n) { long ans = 0; ArrayList list = new ArrayList<>(); list.add(-1); TreeSet left = new TreeSet<>(); left.add(arr[0]); int max[] = new int[n]; max[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) { max[i] = Math.max(arr[i], max[i + 1]); } for (int i = 1; i < n - 1; i++) { Integer l = left.floor(arr[i] - 1); int r = max[i + 1]; if (l != null && r > arr[i] && ((long) arr[i]) * l * r > ans) { ans = ((long) arr[i]) * l * r; list.clear(); list.add(l); list.add(arr[i]); list.add(r); } left.add(arr[i]); } return list; } } ================================================ FILE: Maximum Split of Positive Even Integers.py ================================================ class Solution: def maximumEvenSplit(self, num: int) -> List[int]: if num&1==1: return [] even=2 a=[] while num>0: a.append(even) num-=even even+=2 if -num in a: a.remove(-num) return a ================================================ FILE: Maximum Twin Sum of a Linked List.java ================================================ class Solution { public int pairSum(ListNode head) { int length=1; ListNode temp=head; while(temp.next!=null){ temp=temp.next; length++; } int dp[]=new int[length/2]; temp=head; int index=0; while(temp!=null){ if(index q=new LinkedList<>(); root.val=0; q.add(root); return bfs(q); } public int bfs(Queue q){ int maxWidth = 1; while(!q.isEmpty()){ int sz=q.size(); int left = q.peek().val; int right = left; for(int i=0;i set=new HashSet(); int maxNum=0; for(int i:nums) maxNum=Math.max(maxNum,i); for(int i=31-Integer.numberOfLeadingZeros(maxNum);i>=0;i--){ set.clear(); int bit=1< children; Node() { this.children = new HashMap<>(); } } class Trie { Node root; Trie() { this.root = new Node(); } public void insert(int[] A) { for(int num : A) { Node curr = this.root; for(int i=31;i>=0;i--) { int currBit = (num >> i) & 1; if(!curr.children.containsKey(currBit)) curr.children.put(currBit, new Node()); curr = curr.children.get(currBit); } } } } class Solution { public int findMaximumXOR(int[] nums) { Trie trie = new Trie(); trie.insert(nums); int max = 0; for(int num : nums) { Node curr = trie.root; int currSum = 0; for(int i=31;i>=0;i--) { int requiredBit = 1-((num >> i) & 1); // if A[i] is 0, we need 1 and if A[i] is 1, we need 0. Thus, 1 - A[i] if(curr.children.containsKey(requiredBit)) { currSum |= (1<

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

================================================ FILE: Maximum average subarray - GFG/maximum-average-subarray.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; public class GFG { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tc = Integer.parseInt(br.readLine().trim()); while (tc-- > 0) { String[] inputLine; inputLine = br.readLine().trim().split(" "); int k = Integer.parseInt(inputLine[0]); inputLine = br.readLine().trim().split(" "); int n = Integer.parseInt(inputLine[0]); int[] arr = new int[n]; inputLine = br.readLine().trim().split(" "); for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(inputLine[i]); } int ans = new Solution().findMaxAverage(arr, n, k); for(int i=ans; ians){ index=i; ans=curr; } } return index; } } ================================================ FILE: Maximum level sum.java ================================================ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { public int solve(TreeNode A) { int sum=A.val; Queue q=new LinkedList<>(); q.add(A); while(!q.isEmpty()){ int sz=q.size(); int curr=0; for(int i=0;i using namespace std; // } Driver Code Ends //User function Template for C++ class Solution { public: long long int numberOfSquares(long long int base) { //code here base/=2; return (base*(base-1))/2; } }; //{ Driver Code Starts. int main() { int t; cin >> t; while (t--) { long long int base; cin >> base; Solution ob; cout << ob.numberOfSquares(base) << "\n"; } return 0; } // } Driver Code Ends ================================================ FILE: Maximum number of 2X2 squares.java ================================================ class Solution { public static long numberOfSquares(long n) { //code here if(n<=3)return 0; if(n%2==0){ n-=2; }else{ n-=3; } n/=2; return n*(n+1)/2; } } ================================================ FILE: Maximum number of events that can be attended.java ================================================ class Solution { static int maxEvents(int[] start, int[] end, int N) { // code here int[][] arr = new int[N][2]; for(int i=0; i Integer.compare(a[0], b[0])); PriorityQueue pq = new PriorityQueue(); int i = 0, res = 0, d = 0; while (!pq.isEmpty() || i < N) { if (pq.isEmpty()) d = arr[i][0]; while (i < N && arr[i][0] <= d) pq.offer(arr[i++][1]); pq.poll(); ++res; ++d; while (!pq.isEmpty() && pq.peek() < d) pq.poll(); } return res; } }; ================================================ FILE: Maximum selections - GFG/README.md ================================================ # 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

================================================ FILE: Maximum selections - GFG/maximum-selections.java ================================================ // { Driver Code Starts import java.io.*; import java.util.*; import java.lang.*; class GFG{ public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t > 0){ int n = sc.nextInt(); int arr[][] = new int[n][2]; for( int i=0 ; i{ if(a[1]!=b[1]) return a[1]-b[1]; else return b[0]-a[0]; }); int prevMax=Integer.MIN_VALUE; for(int a[]:ranges){ if(a[0]>=prevMax){ ans++; prevMax=a[1]; } } return ans; } } ================================================ FILE: Maximum sum Rectangle - GFG/README.md ================================================ # Maximum sum Rectangle ## Medium

Given a 2D matrix M of dimensions RxC. Find the maximum sum submatrix in it.

Example 1:

Input:
R=4
C=5
M=[[1,2,-1,-4,-20],
[-8,-3,4,2,1],
[3,8,10,1,3],
[-4,-1,1,7,-6]]
Output:
29
Explanation:
The matrix is as follows and the
blue rectangle denotes the maximum sum
rectangle.
Thumbnail

Example 2:

Input:
R=2
C=2
M=[[-1,-2],[-3,-4]]
Output:
-1
Explanation:
Taking only the first cell is the 
optimal choice.


Your Task:
You don't need to read input or print anything. Your task is to complete the function maximumSumRectangle() which takes the number R, C, and the 2D matrix M as input parameters and returns the maximum sum submatrix.


Expected Time Complexity:O(R*R*C)
Expected Auxillary Space:O(R*C)

 

Constraints:
1<=R,C<=500
-1000<=M[i][j]<=1000

================================================ FILE: Maximum sum Rectangle - GFG/maximum-sum-rectangle.java ================================================ // { Driver Code Starts // Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { int N, M, x, y; String S[] = read.readLine().split(" "); N = Integer.parseInt(S[0]); M = Integer.parseInt(S[1]); int a[][] = new int[N][M]; for (int i = 0; i < N; i++) { String s[] = read.readLine().split(" "); for (int j = 0; j < M; j++) a[i][j] = Integer.parseInt(s[j]); } Solution ob = new Solution(); System.out.println(ob.maximumSumRectangle(N, M, a)); } } }// } Driver Code Ends // User function Template for Java class Solution { int kade(int[]sum){ int max = Integer.MIN_VALUE; int cur=0; for(int i : sum){ cur += i; if(cur > max){ max = cur; } if(cur <0){ cur = 0; } } return max; } int maximumSumRectangle(int r, int c, int mat[][]) { int max = Integer.MIN_VALUE; for(int i=0; i dp){ if(root==null) return 0; if(canTake && dp.containsKey(path+'t')) return dp.get(path+'t'); else if(!canTake && dp.containsKey(path+'f')) return dp.get(path+'f'); if(canTake){ int ans1 = root.data + solve(root.left,false,path+'l',dp) + solve(root.right,false, path+'r',dp); int ans2 = solve(root.left,true,path+'l',dp) + solve(root.right,true,path+'r',dp); int ans = Math.max(ans1,ans2); dp.put(path+'t',ans); return ans; } int ans = solve(root.left,true,path+'l',dp) + solve(root.right,true,path+'r',dp); dp.put(path+'f',ans); return ans; } //Function to return the maximum sum of non-adjacent nodes. static int getMaxSum(Node root){ // add your code here Map dp = new HashMap<>(); return Math.max(solve(root,true,"",dp),solve(root,false,"",dp)); } } ================================================ FILE: Maximum sum of increasing order elements from n arrays.java ================================================ class Complete{ // Function for finding maximum and value pair public static int maximumSum (int n, int m, int arr[][]) { //Complete the function int sum=0; int lastMax=Integer.MAX_VALUE; for(int i=n-1;i>=0;i--){ int[]a=arr[i]; int val=limitMax(a,lastMax); if(val==0)return 0; sum+=val; lastMax=val; } return sum; } public static int limitMax(int[]a,int lastMax){ Arrays.sort(a); for(int i=a.length-1;i>=0;i--){ if(a[i]next){ fast = fast->next->next; slow = slow->next; } // reverse half of linkedlist ListNode* nextNode, *prev = NULL; while(slow){ nextNode = slow->next; slow->next = prev; prev = slow; slow = nextNode; } // get max sum of twins int ans = INT_MIN; while(prev){ ans = max(ans, head->val + prev->val); head = head->next; prev = prev->next; } return ans; // //2. // stack st; // ListNode* temp = head; // while(head){ // st.push(head); // head = head->next; // } // head = temp; // int n = st.size(); // int ans = INT_MIN; // while(st.size() > n/2){ // ans = max(ans, head->val + st.top()->val); // st.pop(); // head = head->next; // } // return ans; } }; ================================================ FILE: Maximum-number-of-2X2-squares.cpp ================================================ class Solution { public: long long int numberOfSquares(long long int base) { long long int h=(base/2)-1; long long int ans=h*(h+1)/2; return ans; } }; ================================================ FILE: Merge Intervals ================================================ class Solution { public int[][] merge(int[][] intervals) { Arrays.sort(intervals,(a,b) ->Integer.compare(a[0],b[0])); LinkedList ans = new LinkedList<>(); for(int[] tem:intervals){ if(ans.isEmpty() || ans.getLast()[1]=tem[0]) ans.getLast()[1] = Math.max(ans.getLast()[1],tem[1]); } return ans.toArray(new int[ans.size()][]); } } ================================================ FILE: Merge K sorted linked lists.java ================================================ class Solution { Node mergeKList(Node[]arr,int K){ PriorityQueue pq = new PriorityQueue<>((a,b) -> a.data - b.data); for(int i = 0 ; i < arr.length ; ++i){ if(arr[i] != null){ pq.add(arr[i]); } } Node head = null , curr = null ; while(!pq.isEmpty()){ Node temp = pq.poll(); if(head == null){ head = curr = temp; } else{ curr.next = temp; curr = curr.next; } if(temp.next != null){ pq.add(temp.next); } } return head; } } ================================================ FILE: Merge Nodes in Between Zeros.java ================================================ class Solution { public ListNode mergeNodes(ListNode head) { ListNode temp=head.next; ListNode start=head; ListNode end=new ListNode(-1); while(start.next!=null){ int sum=0; while(temp.val!=0){ sum+=temp.val; temp=temp.next; } end=temp; ListNode newNode=new ListNode(sum); start.next=newNode; newNode.next=end; start=end; temp=temp.next; } temp=head.next; while(temp!=null){ temp.next=temp.next.next; temp=temp.next; } return head.next; } } ================================================ FILE: Merge Overlapping Intervals.java ================================================ /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class Solution { public ArrayList merge(ArrayList arr) { ArrayList ans=new ArrayList<>(); Collections.sort(arr,(a,b)->a.start-b.start); ans.add(arr.get(0)); int idx=0; for(int i=1;i=arr.get(i).start){ ans.get(idx).end= Math.max(ans.get(idx).end,arr.get(i).end); } } return ans; } } ================================================ FILE: Merge Two Sorted Array.py ================================================ class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ # Replace the n 0's of "nums1" with all n elements of "nums2" j = 0 for i in range(m, m+n): nums1[i] = nums2[j] j+=1 # Sort the list "nums1" in ASCENDING order for i in range(len(nums1)): for j in range(i+1, len(nums1)): if nums1[i] > nums1[j]: nums1[i], nums1[j] = nums1[j], nums1[i] ================================================ FILE: Merge Two Sorted Lists ================================================ public class Solution { public ListNode mergeTwoLists(ListNode A, ListNode B) { ListNode head=new ListNode(-1); ListNode my=head; while(A!=null && B!=null){ if(B.val=0 && r pq=new PriorityQueue<>(); for(ListNode head:lists){ ListNode temp=head; while(temp!=null){ pq.offer(temp.val); temp=temp.next; } } ListNode ans=new ListNode(-1); ListNode temp=ans; while(!pq.isEmpty()){ temp.next=new ListNode(pq.poll()); temp=temp.next; } return ans.next; } } ================================================ FILE: Merge new Interval.java ================================================ class Solution: def insert(self, intervals, newInterval): if len(intervals) == 0: return [newInterval] result = [] result.append(newInterval) for i in range(0,len(intervals)): a = result.pop() b = intervals[i] if a.start > b.end: result.append(b) result.append(a) elif a.end < b.start: result.append(a) result.append(b) else: start = min(a.start, b.start) end = max(a.end, b.end) result.append(Interval(start, end)) return result ================================================ FILE: Merge two Binary Tree.java ================================================ public class Solution { public TreeNode solve(TreeNode A, TreeNode B) { if(A==null && B==null)return null; if(A==null){ return B; } if(B==null){ return A; } TreeNode node=new TreeNode(A.val+B.val); TreeNode lefty=solve(A.left,B.left); TreeNode righty=solve(A.right,B.right); node.left=lefty; node.right=righty; return node; } } ================================================ FILE: Merge two binary Max heaps ================================================ class Solution{ public int[] mergeHeaps(int[] a, int[] b, int n, int m) { // your code here int ans[]=new int[a.length+b.length]; Arrays.sort(a); Arrays.sort(b); int i=a.length-1,j=b.length-1,index=0; while(i>=0 && j>=0){ if(a[i]>b[j]){ ans[index]=a[i]; i--; index++; }else{ ans[index]=b[j]; j--; index++; } } if(i>=0){ while(i>=0){ ans[index]=a[i]; index++; i--; } } if(j>=0){ while(j>=0){ ans[index]=b[j]; j--; index++; } } return ans; } } ================================================ FILE: Merge two sorted linked lists - GFG/README.md ================================================ # Merge two sorted linked lists ## Medium

Given two sorted linked lists consisting of N and M nodes respectively. The task is to merge both of the list (in-place) and return head of the merged list.
 

Example 1:

Input:
N = 4, M = 3 
valueN[] = {5,10,15,40}
valueM[] = {2,3,20}
Output: 2 3 5 10 15 20 40
Explanation: After merging the two linked
lists, we have merged list as 2, 3, 5,
10, 15, 20, 40.

Example 2:

Input:
N = 2, M = 2
valueN[] = {1,1}
valueM[] = {2,4}
Output:1 1 2 4
Explanation: After merging the given two
linked list , we have 1, 1, 2, 4 as
output.

Your Task:
The task is to complete the function sortedMerge() which takes references to the heads of two linked lists as the arguments and returns the head of merged linked list.

Expected Time Complexity : O(n+m)
Expected Auxilliary Space : O(1)

Constraints:
1 <= N, M <= 104
1 <= Node's data <= 105

================================================ FILE: Merge two sorted linked lists - GFG/merge-two-sorted-linked-lists.java ================================================ // { Driver Code Starts import java.util.*; class Node { int data; Node next; Node(int d) { data = d; next = null; } } class MergeLists { Node head; /* Function to print linked list */ public static void printList(Node head) { while (head!= null) { System.out.print(head.data+" "); head = head.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { /* Constructed Linked List is 1->2->3->4->5->6-> 7->8->8->9->null */ Scanner sc = new Scanner(System.in); int t=sc.nextInt(); while(t>0) { int n1 = sc.nextInt(); int n2 = sc.nextInt(); Node head1 = new Node(sc.nextInt()); Node tail1 = head1; for(int i=0; ihead2.data){ ans.next=head2; ans=ans.next; sortedMerge(head1, head2.next); }else{ ans.next=head1; ans=ans.next; sortedMerge(head1.next, head2); } return node.next; } } ================================================ FILE: Merging Details - GFG/Merging Details.cpp ================================================ class Solution { public: vector> mergeDetails(vector>& details) { vector>vv; for(int i=0;is; vectorv; for(int j=1;j> mergeDetails(vector>& details) { vector>vv; for(int i=0;is; vectorv; for(int j=1;j> mergeDetails(List> details) { // Your code here List> ans=new ArrayList<>(); for(int i=0;i detail=details.get(i); if(detail.size()==0)continue; Set set=new TreeSet<>(); String name=detail.get(0); for(int j=1;j curr=details.get(j); if(curr.size()==0)continue; for(int k=1;k merged=new ArrayList<>(); merged.add(name); for(String s:set){ merged.add(s); } ans.add(merged); } return ans; } } ================================================ FILE: Min Coin - GFG/README.md ================================================ # 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

================================================ FILE: Min Coin - GFG/min-coin.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String S = br.readLine().trim(); String[] S1 = S.split(" "); int n = Integer.parseInt(S1[0]); int amount = Integer.parseInt(S1[1]); String s = br.readLine().trim(); String[] s1 = s.split(" "); int[] nums = new int[n]; for(int i = 0; i < s1.length; i++) nums[i] = Integer.parseInt(s1[i]); Solution ob = new Solution(); int ans = ob.MinCoin(nums, amount); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution{ public int MinCoin(int[] nums, int amount){ int n = nums.length; int dp[] = new int[amount+1]; for(int i=1; i<=amount; i++){ dp[i] = 100000; for(int j=0; j=nums[j] && dp[i-nums[j]]!=-1){ dp[i] = Math.min(dp[i], dp[i-nums[j]] + 1); } } if(dp[i]>=100000)dp[i]=-1; } return dp[amount]; } } ================================================ FILE: Min Depth of Binary Tree.java ================================================ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { public int minDepth(TreeNode A) { if(A==null)return Integer.MAX_VALUE; int x=Math.min(minDepth(A.left),minDepth(A.right)); if(x==Integer.MAX_VALUE)return 1; return 1+x; } } ================================================ FILE: Min Jumps Array.java ================================================ public class Solution { public int jump(int[] a) { if(a.length<=1) return 0; int farthest=0,current=0,jumps=0; for(int i=0;icurrent) return -1; } return jumps; } } ================================================ FILE: Min Stack.java ================================================ class Solution { Stack st=new Stack(); Stack mst=new Stack(); public void push(int x) { if (st.empty() && mst.empty()){ st.push(x); mst.push(x); }else{ st.push(x); if(x> list) { int sz=list.size(); if(sz==1) return list.get(0).get(0); int dp[]=new int[sz+1]; for(int row=sz-1;row>=0;row--){ int len=list.get(row).size(); for(int col=0;col

Given an array of digits (values are from 0 to 9), find the minimum possible sum of two numbers formed from digits of the array. All digits of given array must be used to form the two numbers.

 

Example 1:

Input:
N = 6
arr[] = {6, 8, 4, 5, 2, 3}
Output:
604
Explanation:
The minimum sum is formed by numbers 
358 and 246

 

Example 2:

Input:
N = 5
arr[] = {5, 3, 0, 7, 4}
Output:
82
Explanation:
The minimum sum is formed by numbers 
35 and 047



Your Task:
You don't have to print anything, printing is done by the driver code itself. Your task is to complete the function minSum() which takes the array A[] and its size N as inputs and returns the required sum.

 


Expected Time Complexity: O(N. log(N))
Expected Auxiliary Space: O(1)


Constraints:
1 ≤ N ≤ 35
0 ≤ A[] ≤ 9

================================================ FILE: Min sum formed by digits - GFG/min-sum-formed-by-digits.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); // Inputting the testcases while(t-->0) { int n = Integer.parseInt(br.readLine().trim()); int a[] = new int[(int)(n)]; String inputLine[] = br.readLine().trim().split(" "); for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(inputLine[i]); } Solution obj = new Solution(); System.out.println(obj.minSum(a, n)); } } } // } Driver Code Ends //User function Template for Java //2 3 4 5 6 //246 //35 class Solution { public static long minSum(int arr[], int n) { // Your code goes here Arrays.sort(arr); long a=0; long b=0; int i=0; while(i maxHeap = new PriorityQueue<>((o1,o2)->o2-o1); int min = Integer.MAX_VALUE; int diff=min; for(int i=0;i99) { min--; sec+=60; } while(min>=0&&sec<=99) { tar=min*100+sec; char arr[]=(""+tar).toCharArray(); int mul=0; for(int i=0;i X, vector Y, int M, int N){ //Write your code here int ans = 0; sort(X.begin(), X.end(), greater()); sort(Y.begin(), Y.end(), greater()); int i=0, j=0; while(i= Y[j]) ans += (j+1)*X[i++]; else ans += (i+1)*Y[j++]; } while(i=0 || j>=0){ int a=i>=0?X[i]:-1; int b=j>=0?Y[j]:-1; if(a>=b){ ans+=(a*row); col++; i--; }else{ ans+=(b*col); row++; j--; } } return ans; } } ================================================ FILE: Minimum Cost to cut a board into squares.py ================================================ from typing import List class Solution: def minimumCostOfBreaking(self, X, Y, M, N): X.sort() Y.sort() xCut = 1 yCut = 1 currPrice = 0 i = len(X)-1 j = len(Y)-1 while i>=0 and j>=0: if X[i] > Y[j]: currPrice += X[i]*xCut yCut +=1 i-=1 elif X[i] < Y[j]: currPrice += Y[j]*yCut xCut +=1 j -= 1 elif X[i] == Y[j]: if xCut > yCut: currPrice += X[i]*xCut yCut +=1 i-=1 else: currPrice += Y[j]*yCut xCut +=1 j-=1 while i>=0: currPrice += X[i]*xCut yCut +=1 i-=1 while j>=0: currPrice += Y[j]*yCut xCut +=1 j-=1 return currPrice ================================================ FILE: Minimum Exchange GFG/MinimumExchange.cpp ================================================ class Solution { public: int MinimumExchange(vector>matrix){ // Code here int ans1=0; int ans2=0; for(int i=0;i>matrix){ // // Code here // int m = matrix.size(), n = matrix[0].size(); // int cnt = 0; // for(int i=0; i using namespace std; class Solution { public: int MinimumExchange(vector>matrix){ // Code here int m = matrix.size(), n = matrix[0].size(); int case1=0, case2 = 0; for(int i =0; i> tc; while(tc--){ int n, m; cin >> n >> m; vector>matrix(n, vector(m,'x')); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++) cin >> matrix[i][j]; } Solution obj; int ans = obj.MinimumExchange(matrix); cout << ans <<"\n"; } return 0; } ================================================ FILE: Minimum Exchange.java ================================================ class Solution { public int MinimumExchange(char[][] matrix) { int a = 0, b = 0; int m = matrix.length, n = matrix[0].length; for(int i = 0; i < m; ++i){ for(int j = 0; j < n; ++j){ if(matrix[i][j] == 'A'){ a++; } else { b++; } } } if(a > b){ return Count('A', 'B', matrix); } else if(a < b){ return Count('B', 'A', matrix) ; } else { return Math.min(Count('A', 'B', matrix), Count('B', 'A', matrix)); } } private int Count(char x, char y, char[][] matrix) { int m = matrix.length, n = matrix[0].length; int cnt = 0; for(int i = 0; i < m; ++i){ char ch = x; if(i % 2 == 1){ ch = y; } for(int j = 0; j < n; ++j){ if(matrix[i][j] != ch){ cnt++; } if(ch == x){ ch = y; } else { ch = x; } } } return cnt / 2; } } ================================================ FILE: Minimum Lights to Activate.java ================================================ public class Solution { public int solve(int[] a, int b) { int n=a.length; int i=0,curr=-1; int cnt=0; while(i

Given an array of distinct elements which was initially sorted. This array is rotated at some unknown point. The task is to find the minimum element in the given sorted and rotated array. 

Example 1:

Input:
N = 10
arr[] = {2,3,4,5,6,7,8,9,10,1}
Output: 1
Explanation: The array is rotated 
once anti-clockwise. So minium 
element is at last index (n-1) 
which is 1.

Example 2:

Input:
N = 5
arr[] = {3,4,5,1,2}
Output: 1
Explanation: The array is rotated 
and the minimum element present is
at index (n-2) which is 1.

Your Task:
The task is to complete the function minNumber() which takes the array arr[] and its starting and ending indices (low and high) as inputs and returns the minimum element in the given sorted and rotated array.

Expected Time Complexity: O(LogN).
Expected Auxiliary Space: O(LogN).

Constraints:
1 <= N <= 107
1 <= arr[i] <= 107

================================================ FILE: Minimum Number in a sorted rotated array - GFG/minimum-number-in-a-sorted-rotated-array.java ================================================ // { Driver Code Starts import java.io.*; import java.lang.*; import java.util.*; class Array { public static void main(String args[])throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { int n = Integer.parseInt(read.readLine()); String st[] = read.readLine().trim().split("\\s+"); int arr[] = new int[n]; for(int i = 0; i < n; i++) arr[i] = Integer.parseInt(st[i]); System.out.println(new Solution().minNumber(arr,0,n-1)); } } }// } Driver Code Ends class Solution { //Function to find the minimum element in sorted and rotated array. static int minNumber(int arr[], int l, int h){ while(l<=h){ int m=(l+h)/2; if(m==0 || arr[m-1]>arr[m]) return arr[m]; if(arr[m]arr[h]) l=m+1; } return -1; } } ================================================ FILE: Minimum Number in a sorted rotated array - GFG/minimum-number-in-a-sorted-rotated-array.py ================================================ #User function Template for python3 class Solution: #Function to find the minimum element in sorted and rotated array. def minNumber(self, arr,low,high): return min(arr) #{ # Driver Code Starts #Initial Template for Python 3 import math def main(): T=int(input()) while(T>0): N=int(input()) A=[int(x) for x in input().strip().split()] obj = Solution() print(obj.minNumber(A,0,N-1)) T-=1 if __name__ == "__main__": main() # } Driver Code Ends ================================================ FILE: Minimum Number of Arrows to Burst Balloons(Non Overlapping intervals) ================================================ class Solution { public int findMinArrowShots(int[][] points) { // This Problem is similar to Non Overlapping Interval Problem of Greedy Approach // Link for detiled discussion : http://www.leetcode-solution.com/2019/06/01/0452-minimum-number-of-arrows-to-burst-balloons.html // Base case if(points.length == 0) return 0; // Sort the point accroding to their end points i.e., a[1] - b[1] Arrays.sort(points, (a,b) -> a[1] - b[1]); // Position arrow at end (Extreme Right) as it has maximum chance of hittng there int arrPos = points[0][1]; int count = 1; // Minimun 1 arrow is required to shoot any points for(int i = 1; i < points.length; i++ ) // start with 1 as 0th index end will be check for start of 1st { int left = points[i][0]; int right = points[i][1]; //check whether the arrowFired can burst other balloons. //if not fire arrow at the next point end value if (!(arrPos >= left && arrPos <= right)) { count++; // increase the arrowsFired by 1. arrPos = points[i][1]; // next point end value. } /* if(arrPos >= points[i][0]) // Since Current arrow position than start pos of array that means we can { // continue, but as soon as it not true we break as our current arrow pos continue; // cant handle beyond that point . so update its pos and count++ } count++ ; // As we are done with current pos arrPos = points[i][1]; // Update as we already exhausted our option with previous position */ } return count; } } ================================================ FILE: Minimum Number of Vertices to Reach All Nodes.java ================================================ class Solution { public List findSmallestSetOfVertices(int n, List> edges) { List> adj=new ArrayList<>(); List ansList=new ArrayList<>(); for(int i=0;i l=new ArrayList<>(); adj.add(l); } for(int i=0;i oddMap = new HashMap<>(); Map evenMap = new HashMap<>(); for(int i=0; i odd = new PriorityQueue<>((a, b) -> b.freq - a.freq); Queue even = new PriorityQueue<>((a, b) -> b.freq - a.freq); for(Map.Entry entry : oddMap.entrySet()){ odd.offer(new Node(entry.getKey(), entry.getValue())); } for(Map.Entry entry : evenMap.entrySet()){ even.offer(new Node(entry.getKey(), entry.getValue())); } while(!odd.isEmpty() && !even.isEmpty() && odd.peek().val == even.peek().val){ if(odd.peek().freq < even.peek().freq){ odd.poll(); }else{ even.poll(); } } int n = nums.length; if(n % 2 == 0){ return (odd.isEmpty() ? n / 2 : n / 2 - odd.poll().freq) + (even.isEmpty() ? n / 2 : n / 2 - even.poll().freq); }else{ return (odd.isEmpty() ? n / 2 + 1 : n / 2 + 1 - odd.poll().freq) + (even.isEmpty() ? n / 2 : n / 2 - even.poll().freq); } } class Node { int freq; int val; public Node(int val, int freq){ this.freq = freq; this.val = val; } public String toString(){ return val + ": " + freq; } } } ================================================ FILE: Minimum Parantheses!.java ================================================ public class Solution { public int solve(String A) { int ans=0; Deque st=new ArrayDeque<>(); for(int i=0;i0){ st.pop(); }else{ ans++; } } } ans+=st.size(); return ans; } } ================================================ FILE: Minimum Platforms.java ================================================ class Solution { //Function to find the minimum number of platforms required at the //railway station such that no train waits. static int findPlatform(int arr[], int dep[], int n) { // add your code here Arrays.sort(arr); Arrays.sort(dep); int plat=1; int max=1; int i=1; int j=0; while(i st; int i = 0; // we are removing open bracket if extra and marking them with # and finally not including the character # in the ans string while(i < n){ if(s[i] == '(') st.push(i); else if(s[i] == ')'){ if(st.empty()){ s[i] = '#'; }else{ st.pop(); // removing the relavent open bracket for closing bracket and finally we will be left with extra open brackets and we will mark them as # } } i++; } // here we are marking extra open brackets as # while(!st.empty()){ s[st.top()] = '#'; st.pop(); } i = 0; while(i stack=new ArrayDeque<>(); int[]dp=new int[s.length()]; for(int i=0;i using namespace std; class Solution{ public: long long findMinSum(vector &A,vector &B,int N){ long long res =0; sort(A.begin(), A.end()); sort(B.begin(), B.end()); for(int i =0; i using namespace std; // } Driver Code Ends //User function Template for C++ class Solution { public: int minimumSwaps(int c[],int v[],int n,int k,int b,int T) { // code here int good_sheep = 0; //to count how many sheeps can reach target int bad_sheep = 0; //to count how many sheeps can NOT reach target int swap = 0; //no. of sweeps for(int i=n-1;i>=0;i--){ //check if it is able to reach destination if(v[i]*T + c[i] >= b){ good_sheep++; //now check no of bad sheep infront of it and swap it with that swap+=bad_sheep; } else{ bad_sheep++; } //check whether atleast k sheep reach the barn //if YES then break if(good_sheep>=k) break; } if(good_sheep>=k) return swap; return -1; } }; //{ Driver Code Starts. int main(){ int t=1,testcases=1; cin>>t; while(t>=testcases) { int n,k,b,T; cin>>n>>k>>b>>T; int c[n]; int v[n]; for(auto &j:c) cin>>j; for(auto &j:v) cin>>j; Solution s; int ans=s.minimumSwaps(c,v,n,k,b,T); cout<& nums) { int n = nums.size(); int k = 0 , ans = n; for(int i = 0;i map=new HashMap<>(); for(int i=0;i=0;i--){ int pos=c[i]+(v[i]*t); if(pos>=b){ k--; totalSwaps+=slow; if(k==0)return totalSwaps; }else{ slow++; } } return -1; } } ================================================ FILE: Minimum Time To Fulfill All Orders Using BinarySearch And ApSeries Formula.java ================================================ class Solution { public static int findMinTime(int n, int l, int[] arr) { int start=1; int end=Integer.MAX_VALUE; int ans=0; while(start<=end) { int mid=start +(end-start)/2; if(isAnswer(arr, mid, n)) { ans=mid; end=mid-1; } else { start=mid+1; } } return ans; } public static boolean isAnswer(int arr[], int mid, int n) { int curAns=0; for(int i=0;iarr[i], Sn->mid found n using binary search if(curAns>=n) return true; } // System.out.println(curAns+" "+n+" "+mid); return curAns>=n; } public static int getNumber(int a, int sum) { int start=1; int end=sum; int n=0; if(sum=sum) { n=(int)mid; end=(int)mid-1; } else { start=(int)mid+1; } } if(n*(2*a+(n-1)*a)/2==sum) return n; else return n-1>=0?n-1:0; } } ================================================ FILE: Minimum Time to Remove All Cars Containing Illegal Goods.java ================================================ class Solution { public int minimumTime(String s) { int n = s.length(); int min = s.length(); int[] nums = new int[n]; for (int i = 0; i < n; i++) nums[i] = s.charAt(i) - '0'; // step1 int[] leftOptimized = new int[n + 2]; for (int i = 1; i <= n; i++) { leftOptimized[i] = Math.min(i, leftOptimized[i - 1] + (nums[i - 1] == 1? 2: 0)); } // step2 int[] rightOptimized = new int[n + 2]; for (int i = n; i > 0; i--) { rightOptimized[i] = Math.min(n - i + 1, rightOptimized[i + 1] + (nums[i - 1] == 1? 2: 0)); } // step3 for (int p = 0; p <= n; p++) { min = Math.min(min, leftOptimized[p] + rightOptimized[p + 1]); } return min; } } ================================================ FILE: Minimum X (xor) A - GFG/README.md ================================================ # Minimum X (xor) A ## Hard

Given two integers A and B, the task is to find an integer X such that (X XOR A) is minimum possible and the count of set bit in X is equal to the count of set bits in B.

Example 1:

Input: 
A = 3, B = 5
Output: 3
Explanation:
Binary(A) = Binary(3) = 011
Binary(B) = Binary(5) = 101
The XOR will be minimum when x = 3
i.e. (3 XOR 3) = 0 and the number
of set bits in 3 is equal
to the number of set bits in 5.

Example 2:

Input: 
A = 7, B = 12
Output: 6
Explanation:
(7)2= 111
(12)2= 1100
The XOR will be minimum when x = 6 
i.e. (6 XOR 7) = 1 and the number 
of set bits in 6 is equal to the 
number of set bits in 12.
Your task :
You don't need to read input or print anything. Your task is to complete the function minVal() that takes integer A and B as input and returns the value of X according to the question.
 
Expected Time Complexity : O(log N)
Expected Auxiliary Space : O(1)
 
Constraints :
1 <= A, B <= 109
 

================================================ FILE: Minimum X (xor) A - GFG/minimum-x-xor-a.java ================================================ // { Driver Code Starts // Initial Template for Java import java.util.*; import java.io.*; import java.lang.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); // Inputting the testcases while (t-- > 0) { int a = Integer.parseInt(br.readLine().trim()); int b = Integer.parseInt(br.readLine().trim()); Solution ob = new Solution(); System.out.println(ob.minVal(a, b)); } } }// } Driver Code Ends // User function Template for Java //1001 //1011 //bitsA=2 //bitsB=3 //1101 //1001 //0100 class Solution { public static int minVal(int a, int b) { int bitsA=Integer.bitCount(a); int bitsB=Integer.bitCount(b); int diff=Math.abs(bitsA-bitsB); if(diff==0)return a; else if(bitsA>bitsB){ while(diff>0){ a = a&(a-1); diff--; } }else{ while(diff>0){ a = a|(a+1); diff--; } } return a; } } ================================================ FILE: Minimum increment/decrement to make array non-Increasing - GFG/README.md ================================================ # Minimum increment/decrement to make array non-Increasing ## 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.


Given an array a of length n, find the minimum number of operations required to make it non-increasing. You can select any one of the following operations and preform it any number of times on an array element.

  • increment the array element by 1.
  • decrement the array element by 1. 

Example 1:

Input:
N = 4 
array = {3, 1, 2, 1}
Output: 1
Explanation: 
Decrement array[2] by 1. 
New array becomes {3,1,1,1} which is non-increasing. 
Therefore, only 1 step is required. 


Example 2:

Input:
N = 4 
array = {3, 1, 5, 1}
Output: 4


Your Task:
You don't need to read input or print anything. Complete the function minOperations() that takes n and array a as input parameters and returns the minimum number of operations required. 

Expected time complexity: O(nlogn)
Expected space complexity: O(n)


Constraints:
1 <= n <= 10^4
1 <= a[i] <= 10^4

================================================ FILE: Minimum increment/decrement to make array non-Increasing - GFG/minimum-incrementdecrement-to-make-array-non-increasing.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; import java.util.PriorityQueue; // } Driver Code Ends //User function Template for Java class Solution { public static int minOperations(int a[], int n){ int ans=0; PriorityQueue pq = new PriorityQueue<>(); for(int i=0;i 0) { int n; n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); Solution ob = new Solution(); System.out.println(ob.minOperations(a,n)); t--; } } } // } Driver Code Ends ================================================ FILE: Minimum sum of absolute difference of pairs.cpp ================================================ #include using namespace std; // } Driver Code Ends //User function Template for C++ class Solution{ public: long long findMinSum(vector &A,vector &B,int N){ sort(A.begin(),A.end()); sort(B.begin(),B.end()); long long res = 0; for(int i=0;i>t; while(t--){ int N; cin>>N; vector A(N),B(N); for(int i=0;i>A[i]; } for(int i=0;i>B[i]; } Solution ob; cout<= time) return true; return false; } } ================================================ FILE: Minimum time to fulfil all orders gfg hard.cpp ================================================ #include using namespace std; class Solution{ public: int getDonuts(int rank, int time){ int i =1, currSum =1, numDonuts =0; while((rank*currSum) <= time){ numDonuts++; i++; currSum+=i; } return numDonuts; } bool isPossible(vector&A, int time, int donuts){ int currSum =0; for(int i=0;i=donuts; } int findMinTime(int N, vector&A, int L){ //write your code here int start =0, maxi =0; for(int i =0; i=n; } } ================================================ FILE: Minimum time to fulfill all orders.java ================================================ class Solution { public static int donutCount(int min,int rank[]) { int dCount = 0; for(int i = 0;i < rank.length;i++) { int chefRank = rank[i]; if(chefRank > min) continue; int curDount = 1; int curTime = chefRank; while(curTime <= min) { dCount++; curDount++; curTime += curDount*chefRank; } } return dCount; } public static int findMinTime(int n, int arrLength, int[] arr) { int l = 1, h = 10000000; while(l <= h) { int mid = (l+h)/2; int midRes = donutCount(mid,arr); if(n <= midRes) h = mid-1; else l = mid+1; } return l; } } ================================================ FILE: Minimum times A has to be repeated such that B is a substring of it - GFG/README.md ================================================ # Minimum times A has to be repeated such that B is a substring of it ## Medium

Given two strings A and B. Find minimum number of times A has to be repeated such that B is a Substring of it. If B can never be a substring then return -1.

 

Example 1:

Input:
A = "abcd"
B = "cdabcdab"
Output:
3
Explanation:
Repeating A three times (“abcdabcdabcd”),
B is a substring of it. B is not a substring
of A when it is repeated less than 3 times.
Example 2:
Input:
A = "ab"
B = "cab"
Output :
-1
Explanation:
No matter how many times we repeat A, we can't
get a string such that B is a substring of it.


Your Task:  
You don't need to read input or print anything. Your task is to complete the function minRepeats() which takes 2 strings A, and B respectively and returns the minimum number of times A has to be repeated such that B is a substring of it. Return -1 if it's not possible.


Expected Time Complexity: O(|A| * |B|)
Expected Auxiliary Space: O(|B|)


Constraints:
1 ≤ |A|, |B| ≤ 103
String A and B consists of lower case alphabets

================================================ FILE: Minimum times A has to be repeated such that B is a substring of it - GFG/minimum-times-a-has-to-be-repeated-such-that-b-is-a-substring-of-it.py ================================================ #User function Template for python3 class Solution: def minRepeats(self, A, B): parent=str(A) ans=1 while(len(parent)= 0; i--){ if(v[i]*T+c[i] >= b){ //Distance = speed*time so a sheep can reach to barn if its postion*time+cost is greater than equal to barn position g++; // If yes then we will not swap that sheep s += bad; }else bad++; // If not than that sheep can exploit other sheeps also which have higher //cost and are on left side of bad sheep so we increase count of bad sheeps if(g >= k) break; // number of good sheeps is equal to k we will break and return no. of swap required } if(g >= k) return s; return -1; // else return -1; } }; ================================================ FILE: Minimum_Cost_to_cut_a_board_into_squares_gfg_greedy.cpp ================================================ #include using namespace std; class Solution { public: int minimumCostOfBreaking(vector X, vector Y, int M, int N){ //Write your code here sort(X.begin(), X.end(), greater()); sort(Y.begin(), Y.end(), greater()); int i =0,j =0, cost =0, hor=1, ver =1; while(i

You are given the head of a Linked List. You have to move the last element to the front of the Linked List and return the list.

 

Example 1:

Input:
N = 5
List = {2,5,6,2,1}
Output:
{1,2,5,6,2}
Explanation:
In the given linked list, the last element is 1,
after moving the last element to the front the
linked list will be {1,2,5,6,2}.

 

Example 2:

Input:
N = 1
List = {2}
Output:
{2}
Explanation:
Here 2 is the only element so, the linked list
will remain the same.

 

Your Task:

You don't need to read input or print anything. Your task is to complete the function moveToFront() which takes the address of the head of the linked list and returns the modified linked list.

 

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

 

Constraints:
1 <= N <= 105
0 <= Elements of List <= 109
Sum of N over all test cases doesn't exceeds 106

================================================ FILE: Move Last Element to Front of a Linked List - GFG/move-last-element-to-front-of-a-linked-list.java ================================================ //{ Driver Code Starts import java.io.*; import java.util.*; class Node { int data; Node next; Node(int x) { data = x; next = null; } public static Node inputList(BufferedReader br) throws IOException { int n = Integer.parseInt(br.readLine().trim()); // Length of Linked List String[] s = br.readLine().trim().split(" "); Node head = new Node(Integer.parseInt(s[0])), tail = head; for(int i = 1; i < s.length; i++) tail = tail.next = new Node(Integer.parseInt(s[i])); return head; } public static void printList(Node node) { while (true) { System.out.print(node.data); node = node.next; if(node == null) break; System.out.print(" "); } System.out.println(); } } class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t; t = Integer.parseInt(br.readLine()); while(t-- > 0){ Node head = Node.inputList(br); Solution obj = new Solution(); Node res = obj.moveToFront(head); Node.printList(res); } } } // } Driver Code Ends /* Definition for singly Link List Node class Node { int data; Node next; Node(int x){ data = x; next = null; } } You can also use the following for printing the link list. Node.printList(Node node); */ class Solution { public static Node moveToFront(Node head) { // code here if(head.next==null)return head; Node temp=head; while(temp.next.next!=null){ temp=temp.next; } Node last=temp.next; temp.next=null; last.next=head; return last; } } ================================================ FILE: Move Zeroes.java ================================================ public class Solution { public int[] solve(int[] A) { int cnt=0; for(int i:A){ if(i==0)cnt++; } int pos=0; int i=0; while(i0){ A[i--]=0; } return A; } } ================================================ FILE: Move all zeroes to end of the array.java ================================================ public class Solution { public ArrayList solve(ArrayList A) { ArrayList ans=new ArrayList<>(); for(int i:A){ if(i!=0){ ans.add(i); } } int diff=A.size()-ans.size(); while(diff!=0){ ans.add(0); diff--; } return ans; } } ================================================ FILE: Move all zeros to the front of the linked list - GFG/README.md ================================================ # 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


 

================================================ FILE: Move all zeros to the front of the linked list - GFG/move-all-zeros-to-the-front-of-the-linked-list.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; class Node{ int data; Node next; Node(int d){ data=d; next=null; } } class Zeroes{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); Node head=null; while(n-->0){ int a=sc.nextInt(); if(head==null){ head=new Node(a); } else{ Node temp=new Node(a); temp.next=head; head=temp; } } GfG g=new GfG(); head = g.moveZeroes(head); while(head!=null){ System.out.print(head.data+" "); head=head.next; } System.out.println(); } } } // } Driver Code Ends //User function Template for Java /* class Node{ int data; Node next; Node(int d){ data=d; next=null; } } */ class GfG{ public Node moveZeroes(Node head){ Node temp=head; while(temp.next!=null){ if(temp.next.data==0){ Node zero=temp.next; temp.next=temp.next.next; zero.next=head; head=zero; }else{ temp=temp.next; } } return head; } } ================================================ FILE: Moving on grid - GFG/README.md ================================================ # Moving on grid ## Easy

Given a grid with dimensions r x c, the two players (say JON and ARYA ) can move the coin over the grid satisfying the following rules:

  • There is a coin on (1,1) cell initially.
  • JON will move first.
  • Both will play on alternate moves.
  • In each move they can place coin on following positions if current position of coin is x,y
    (x+1,y), (x+2,y), (x+3,y), (x,y+1), (x,y+2), (x,y+3), (x,y+4), (x,y+5), (x,y+6)
  • They can't go outside the grid.
  • Player who cannot make any move will lose this game.
  • Both play optimally.


Example 1:

Input: r = 1, c = 2
Output: JON 
Explanation: ARYA lost the game because
he won't able to move after JON's move.  


Example 2:

Input: r = 2, c = 2
Output: ARYA
Explanation: After first move by JON(1,2 or 2,1)
and second move by ARYA(2,2) JON won't able to
move so ARYA wins.   


Your Task:  
You dont need to read input or print anything. Complete the function movOnGrid() which takes r and c as input parameter and returns the name of the winner ( either JON or ARYA)
.

Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)

Constraints:
1 <= r, c <=105

================================================ FILE: Moving on grid - GFG/moving-on-grid.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String[] input = new String[2]; input = br.readLine().split(" "); int r = Integer.parseInt(input[0]); int c = Integer.parseInt(input[1]); Solution ob = new Solution(); System.out.println(ob.movOnGrid(r,c)); } } } // } Driver Code Ends //User function Template for Java class Solution { public String movOnGrid(int r, int c){ r=(r-1)%7; c=(c-1)%4; return(r==c?"ARYA":"JON"); } } ================================================ FILE: Multiple left rotations of the array.java ================================================ public class Solution { Map map=new HashMap<>(); public int[][] solve(int[] A, int[] B) { int[][]ans=new int[B.length][A.length]; for(int i=0;i increasingNumbers(int n){ // code here ArrayList list=new ArrayList(); if(n==1){ for(int i=0;i<10;i++){ list.add(i); } return list; }else if(n==9){ list.add(123456789); return list; }else if(n==8){ list.add(12345678); list.add(12345679); list.add(12345689); list.add(12345789); list.add(12346789); list.add(12356789); list.add(12456789); list.add(13456789); list.add(23456789); return list; }else{ int start=(int)Math.pow(10,n-1); int end=(int)Math.pow(10,n); while(start a) { int n = a.size(); HashMap h = new HashMap(); for(int i = 0; i < n; i++){ int x = a.get(i), times = 0; if(h.containsKey(x)){ times = h.get(x); h.put(x, times + 1); times++; }else{ h.put(x, 1); times = 1; } if(times > n / 3){ return x; } } return -1; } } ================================================ FILE: N-th_Tribonacci_Number_leetcode1137.cpp ================================================ class Solution { public: int tribonacci(int n) { if (n < 2) return n; int a = 0, b = 1, c = 1, d = a + b + c; while (n-- > 2) { d = a + b + c, a = b, b = c, c = d; } return c; } }; ================================================ FILE: Nearest Smaller Element.java ================================================ public class Solution { public int[] prevSmaller(int[] A) { int n=A.length; int[]ans=new int[n]; for(int i=0;i=0){ if(a[i] prevSmaller(ArrayList A) { ArrayList result=new ArrayList<>(); result.add(-1); Stack stack=new Stack<>(); stack.push(A.get(0)); for(int i=1;i=A.get(i)) stack.pop(); result.add(stack.isEmpty()?-1:stack.peek()); stack.add(A.get(i)); } return result; } } ================================================ FILE: Nearly sorted - GFG/README.md ================================================ # Nearly sorted ## Medium

Given an array of n elements, where each element is at most k away from its target position, you need to sort the array optimally.

Example 1:

Input:
n = 7, k = 3
arr[] = {6,5,3,2,8,10,9}
Output: 2 3 5 6 8 9 10
Explanation: The sorted array will be
2 3 5 6 8 9 10

Example 2:

Input:
n = 5, k = 2
arr[] = {3,1,4,2,5}
Output: 1 2 3 4 5 

Note: DO NOT use STL sort() function for this question.

Your Task:
You are required to complete the method nearlySorted() which takes 3 arguments and returns the sorted array.

Expected Time Complexity : O(nlogk)
Expected Auxilliary Space : O(n)

Constraints:
1 ≤ n ≤ 106
1 ≤ k < n
1 ≤ arri ≤ 107

================================================ FILE: Nearly sorted - GFG/nearly-sorted.java ================================================ // { Driver Code Starts import java.util.*; import java.io.*; import java.lang.*; class gfg { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { int num = sc.nextInt(); int k = sc.nextInt(); int arr[] = new int[num]; for(int i = 0; i < num; i++) arr[i] = sc.nextInt(); ArrayList res = new Solution().nearlySorted(arr, num, k); for (int i = 0; i < res.size (); i++) System.out.print (res.get (i) + " "); System.out.println(); } } } // } Driver Code Ends class Solution { //Function to return the sorted array. ArrayList nearlySorted(int arr[], int num, int k) { ArrayList ans=new ArrayList<>(); PriorityQueue pq=new PriorityQueue<>(); int i=0; while(i<=k){ pq.add(arr[i]); i++; } while(!pq.isEmpty()){ int ele=pq.remove(); ans.add(ele); if(i

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.

================================================ FILE: Negative weight cycle - GFG/negative-weight-cycle.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String[] S1 = br.readLine().trim().split(" "); int n = Integer.parseInt(S1[0]); int m = Integer.parseInt(S1[1]); int[][] edges = new int[m][3]; for(int i = 0; i < m; i++){ String S2[] = br.readLine().trim().split(" "); for(int j = 0; j < 3; j++) edges[i][j] = Integer.parseInt(S2[j]); } Solution obj = new Solution(); int ans = obj.isNegativeWeightCycle(n, edges); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution{ public int isNegativeWeightCycle(int n, int[][] edges){ if (edges == null || n == 0) { return 0; } int [] distance = new int [n]; Arrays.fill(distance, Integer.MAX_VALUE); distance[0] = 0; // n - 1 number of relaxation steps for (int i = 1; i <= n - 1; i++) { for (int [] edge : edges) { int source = edge[0]; int destination = edge[1]; int weight = edge[2]; // condition if (distance[source] != Integer.MAX_VALUE) { distance[destination] =Math.min(distance[destination], distance[source] + weight); } } } // relaxation step once more to make sure about the negative cycle for (int [] edge : edges) { int source = edge[0]; int destination = edge[1]; int weight = edge[2]; if (distance[source] != Integer.MAX_VALUE && distance[source] + weight < distance[destination]) { // there is a negative cycle as distance will get updated return 1; } } return 0; } } ================================================ FILE: Next Permutation ================================================ class Solution{ static List nextPermutation(int N, int a[]){ // code here int k=-1; for(int i=0;i list=new ArrayList<>(); for(int i=N-1;i>=0;i--){ list.add(a[i]); } return list; } int l=k+1; for(int i=k+1;ia[k]){ l=i; } } int temp=a[k]; a[k]=a[l]; a[l]=temp; List list=new ArrayList<>(); for(int i=0;i<=k;i++){ list.add(a[i]); } for(int i=N-1;i>k;i--){ list.add(a[i]); } return list; } } //============================================================= public class Solution { public ArrayList nextPermutation(ArrayList a) { // code here int k=-1; int N=a.size(); for(int i=0;i list=new ArrayList<>(); for(int i=N-1;i>=0;i--){ list.add(a.get(i)); } return list; } int l=k+1; for(int i=k+1;ia.get(k)){ l=i; } } int temp=a.get(k); a.set(k,a.get(l)); a.set(l,temp); ArrayList list=new ArrayList<>(); for(int i=0;i<=k;i++){ list.add(a.get(i)); } for(int i=N-1;i>k;i--){ list.add(a.get(i)); } return list; } } ================================================ FILE: Next Pointer Binary Tree.java ================================================ public class Solution { public void connect(TreeLinkNode root) { TreeLinkNode prev=null; Queue q=new LinkedList<>(); q.add(root); while(q.size()>0){ int sz=q.size(); prev=null; for(int i=0;idata) return new Node(-1); queue q; q.push(root); while(!q.empty()){ int n = q.size(); vector v; for(int i=0;ileft) q.push(node->left); if(node->right) q.push(node->right); v.push_back(node); q.pop(); } for(int i=0;idata == key) return v[i+1]; } if(v[v.size()-1]->data == key) return new Node(-1); } return new Node(-1); } }; // Another approach // class Solution // { // public: // Node *nextRight(Node *root, int key) // { // //code here // queue Q; // Q.push(root); // while(!Q.empty()) // { // int sz = Q.size(); // while(sz--) // { // Node* cur = Q.front(); // Q.pop(); // if(cur->data == key) // { // if(sz == 0) // return new Node(-1); // else // return Q.front(); // } // if(cur->left) // Q.push(cur->left); // if(cur->right) // Q.push(cur->right); // } // } // return new Node(-1); // } // }; ================================================ FILE: Next Right Node.java ================================================ class Solution{ Node nextRight(Node root, int key) { //Write your code here Queue q=new LinkedList<>(); q.add(root); boolean found=false; while(q.size()>0){ int sz=q.size(); //level while(sz-->0){ Node node=q.remove(); if(found)return node; if(node.data==key)found=true; if(node.left!=null)q.add(node.left); if(node.right!=null)q.add(node.right); } if(found)return new Node(-1); } return null; } } ================================================ FILE: Next element with greater frequency - GFG/README.md ================================================ # Next element with greater frequency ## Medium

Given an array arr[ ] of n integers, for every element, find the closest element on it's right that has a greater frequency than its own frequency.

Frequency is the number of times the element appears in the array.

 

Example 1:

Input:
n = 6
arr[] = {2 1 1 3 2 1}
Output:
1 -1 -1 2 1 -1 
Explanation:
1 appears 3 times.
2 appears 2 times.
3 appears 1 time. 

For arr[0] ie, 2
arr[1] ie 1 is the closest element on its 
right which has greater frequency than the 
frequency of 2. For the arr[1] and arr[2] no element 
on the right has greater frequency than 1, 
so -1 will be printed. and so on. 

Example 2:

Input:
n = 10
arr[] = {5 1 2 3 2 5 5 4 5 2}
Output:
-1 2 5 2 5 -1 -1 5 -1 -1

 

Your task:
Your task is to complete the function print_next_greater_freq() which take two parameters arr and n.This function returns answer(as a list of integers) as explained above.


Expected time complexity: O(n)
Expected space complexity: O(n)


Constraints:
1 <= n <= 104
1 <= arr[i] <= 104

================================================ FILE: Next element with greater frequency - GFG/next-element-with-greater-frequency.java ================================================ // { Driver Code Starts import java.util.*; import java.io.*; class GFG { public static void main (String[] args) { Scanner sc = new Scanner(System.in); // int arr[] = new int[10000]; int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int arr[]=new int[n]; for(int i=0; ifreq[arr[i]]){ ans[i]=arr[j]; got=true; break; } } if(!got){ ans[i]=-1; } } return ans; } } ================================================ FILE: Noble Integer.java ================================================ public class Solution { public int solve(ArrayList A) { Collections.sort(A); for(int i=1;i& e) { int n = e.size(); vector v(n); for(int i =0;isum){ sum = v[i]; index = i; } } return index; } }; ================================================ FILE: Nodes at even distance - GFG/README.md ================================================ # Nodes at even distance ## Medium

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

================================================ FILE: Nodes at even distance - GFG/nodes-at-even-distance.java ================================================ // { Driver Code Starts import java.io.*; import java.lang.*; import java.util.*; class GFG{ public static void main(String [] args) throws IOException{ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); ArrayList> graph = new ArrayList<>(); for(int i = 0; i <= n; i++) { graph.add(new ArrayList<>()); } int temp = n; while(temp-- > 1){ int u = sc.nextInt(); int v = sc.nextInt(); graph.get(u).add(v); graph.get(v).add(u); } Solution ob = new Solution(); System.out.println(ob.countOfNodes(graph, n)); } } }// } Driver Code Ends //User function Template for Java class Solution { int countOfNodes(ArrayList> graph, int n) { // Write your code here Integer[] arr=new Integer[n+1]; dfs(1,graph,arr,0); int ev=0,od=0; for(Integer i:arr) { if(i!=null) if(i%2==0) ev++; else od++; } return ev*(ev-1)/2+od*(od-1)/2; } static void dfs(int src,ArrayList> adj,Integer[] arr,int di) { arr[src]=di; for(int i:adj.get(src)) if(arr[i]==null) dfs(i,adj,arr,di+1); } } ================================================ FILE: Nth item through sum - GFG/README.md ================================================ # Nth item through sum ## Easy

Given two sorted arrays A and B of length L1 and L2, we can get a set of sums(add one element from the first and one from second). Find the Nth element in the set considered in sorted order.
Note: Set of sums should have unique elements.

Example 1:

Input: L1 = 2, L2 = 2
A = {1, 2}
B = {3, 4}
N = 3
Output: 6
Explaination: The set of sums are in 
the order 4, 5, 6.

Example 2:

Input: L1 = 5, L2 = 4
A = {1, 3, 4, 8, 10}
B = {20, 22, 30, 40}
N = 4
Output: 25
Explaination: The numbers before it 
are 21, 23 and 24.

Your Task:
You do not need to read input or print anything. Your task is to complete the function nthItem() which takes L1, L2, A, B, and the value N as input parameters and returns the Nth value of the set. If N is greater than the size of the set then it returns -1.

Expected Time Complexity: O((L1*L2)*log(L1*L2))
Expected Auxiliary Space: O(L1*L2)

Constraints:
1 ≤ L1, L2 ≤ 500
1 ≤ A[i], B[i] ≤ 10000
1 ≤ N ≤ L1*L2

================================================ FILE: Nth item through sum - GFG/nth-item-through-sum.py ================================================ #User function Template for python3 class Solution: def nthItem(self, L1, L2, A, B, N): s = sorted({i+j for j in B for i in A}) if N > len(s) : return -1 else : return s[N-1] #{ # Driver Code Starts #Initial Template for Python 3 if __name__ == '__main__': t = int(input()) for _ in range(t): L1, L2 = [int(x) for x in input().split()] A = input().split() for itr in range(L1): A[itr] = int(A[itr]) B = input().split() for it in range(L2): B[it] = int(B[it]) N = int(input()) ob = Solution() print(ob.nthItem(L1, L2, A, B, N)) # } Driver Code Ends ================================================ FILE: Number Formation - GFG/README.md ================================================ # Number Formation ## Hard

Given three integers x, y, and z, the task is to find the sum of all the numbers formed by 
having 4 at most x times, having 5 at most y times, and having 6 at most z times as a digit.

Note: Output the sum modulo 109+7.

Example 1:

Input: X = 1, Y = 1, Z = 1 
Output: 3675
Explanation: 4 + 5 + 6 + 45 + 54 + 56 
+ 65 + 46 + 64 + 456 + 465 
+ 546 + 564 + 645 + 654 = 3675
Example 2:
Input: X = 0, Y = 0, Z = 0
Output: 0
Explanation: No number can be formed


Your Task:  
You don't need to read input or print anything. Complete the function getSum() which takes X, Y and Z as input parameters and returns the integer value

Expected Time Complexity: O(X*Y*Z)
Expected Auxiliary Space: O(X*Y*Z)

Constraints:
0 ≤ X, Y, Z ≤ 60

================================================ FILE: Number Formation - GFG/number-formation.java ================================================ //{ Driver Code Starts // Initial Template for Java import java.io.*; import java.util.*; class GfG { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int x = sc.nextInt(); int y = sc.nextInt(); int z = sc.nextInt(); Solution ob = new Solution(); System.out.println(ob.getSum(x, y, z)); } } } // } Driver Code Ends // User Function template for JAVA class Solution { public int getSum(int X, int Y, int Z) { // Your code goes here int mod=1000000007; long[][][] exactSum=new long[X+1][Y+1][Z+1]; long[][][] num=new long[X+1][Y+1][Z+1]; num[0][0][0]=1L; long ans=0L; for(int i=0;i<=X;i++){ for(int j=0;j<=Y;j++){ for(int k=0;k<=Z;k++){ if(i>0){ exactSum[i][j][k]+=(exactSum[i-1][j][k]*10 +4*num[i-1][j][k])%mod; num[i][j][k]+=num[i-1][j][k]%mod; } if(j>0){ exactSum[i][j][k]+=(exactSum[i][j-1][k]*10 +5*num[i][j-1][k])%mod; num[i][j][k]+=num[i][j-1][k]%mod; } if(k>0){ exactSum[i][j][k]+=(exactSum[i][j][k-1]*10 +6*num[i][j][k-1])%mod; num[i][j][k]+=num[i][j][k-1]%mod; } ans+=exactSum[i][j][k]%mod; ans%=mod; } } } return (int)ans; } } ================================================ FILE: Number of 1 Bits.java ================================================ public class Solution { public int numSetBits(long a) { int ans=0; while(a!=0){ ans+=(a&1); a=a>>1; } return ans; } } ================================================ FILE: Number of Provinces.java ================================================ class Solution { static int numProvinces(ArrayList> adj, int V) { // code here boolean[]vis=new boolean[V]; int count=0; for(int i=0;i> adj,int curr,int V){ vis[curr]=true; for(int i=0;iB)return 0; ans++; ans+=(B-num)/7; return ans; } } ================================================ FILE: Number of Ways to Arrive at Destination gfg med sep16.cpp ================================================ #include using namespace std; class Solution { public: int countPaths(int n, vector>& roads) { // code here vector>> adj(n); for(auto road : roads){ int u = road[0], v = road[1], t = road[2]; adj[u].push_back({v, t}); adj[v].push_back({u, t}); } priority_queue, vector>, greater>> pq; pq.push({0, 0}); vector dist(n, 1e18); dist[0] = 0; long long ans = 0, mod = 1000000007; while(!pq.empty()){ long long node = pq.top().second, d = pq.top().first; pq.pop(); if(node == n - 1 && d == dist[n - 1]){ ans = (ans + 1) % mod; continue; } for(auto child : adj[node]){ if(d + child.second <= dist[child.first]){ dist[child.first] = d + child.second; pq.push({dist[child.first], child.first}); } } } return ans; } }; int main() { int T; cin >> T; while (T--) { int n, m; cin >> n >> m; int u, v; vector> adj; for (int i = 0; i < m; ++i) { vector temp; for (int j = 0; j < 3; ++j) { int x; cin >> x; temp.push_back(x); } adj.push_back(temp); } Solution obj; cout << obj.countPaths(n, adj) << "\n"; } return 0; } ================================================ FILE: Number of Ways to Arrive at Destination.cpp ================================================ class Solution { public: int countPaths(int n, vector>& roads) { long long mod = 1e9+7; long long ans = 0; vector>> adj(n); vector dist(n,INT_MAX); priority_queue,vector>,greater>> pq; for(int i=0;i wtwithadj) { dist[u] = wtwithadj; ans = 0; } if(dist[u] == wtwithadj) ans =(ans+1)%mod; continue; } if(dist[u] >= wtwithadj) { dist[u] = wtwithadj; pq.push({dist[u], u}); } } } return ans; } }; ================================================ FILE: Number of Ways to Arrive at Destination.java ================================================ class Solution { static int minTime; static int noOfRoads; static int countPaths(int n, List> roads) { // Your code here minTime=Integer.MAX_VALUE; noOfRoads=0; Map> map=new HashMap<>();// node -> list({des,time}) for(List curr:roads){ int src=curr.get(0); int des=curr.get(1); int time=curr.get(2); map.putIfAbsent(src,new ArrayList<>()); map.putIfAbsent(des,new ArrayList<>()); map.get(src).add(new int[]{des,time}); map.get(des).add(new int[]{src,time}); } boolean[]vis=new boolean[n]; dfs(0,map,vis,0); return noOfRoads; } static void dfs(int node,Map> map,boolean[]vis,int currTime){ if(node==vis.length-1){ if(currTimeminTime)return; vis[node]=true; //find in nebs List nebList=map.get(node); if(nebList!=null){ for(int[] neb:nebList){ int des=neb[0]; int time=neb[1]; if(!vis[des]){ dfs(des,map,vis,currTime+time); } } } vis[node]=false; } } ================================================ FILE: Number of distict Words with k maximum contiguous vowels.java ================================================ class Solution{ private static final int mod = 1000000007; private static int reset; private static Integer[][] dp; private static int find(int N, int K){ if(N == 0){ return 1; } if(dp[N][K] != null) return dp[N][K]; int count = 0; for(char c = 'a'; c <= 'z'; c++){ if(c=='a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){ if(K > 0){ count = (count + find(N-1, K-1)) % mod; } } else{ count = (count + find(N-1, reset)) % mod; } } return dp[N][K] = count; } public int kvowelwords(int N,int K){ dp = new Integer[N+1][K+1]; reset = K; return find(N, K); } } ================================================ FILE: Number of distinct Words with k maximum contiguous vowels - GFG/README.md ================================================ # Number of distinct Words with k maximum contiguous vowels ## Hard

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

================================================ FILE: Number of distinct Words with k maximum contiguous vowels - GFG/number-of-distinct-words-with-k-maximum-contiguous-vowels.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[])throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { int N = sc.nextInt(); int K = sc.nextInt(); Solution ob = new Solution(); int ans = ob.kvowelwords(N,K); System.out.println(ans); } } }// } Driver Code Ends //User function Template for Java class Solution{ private static final int mod = 1000000007; private static int reset; private static Integer[][] dp; private static int find(int N, int K){ if(N == 0){ return 1; } if(dp[N][K] != null) return dp[N][K]; int count = 0; for(char c = 'a'; c <= 'z'; c++){ if(c=='a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){ if(K > 0){ count = (count + find(N-1, K-1)) % mod; } } else{ count = (count + find(N-1, reset)) % mod; } } return dp[N][K] = count; } public int kvowelwords(int N,int K){ dp = new Integer[N+1][K+1]; reset = K; return find(N, K); } } ================================================ FILE: Number of positive integral solutions - GFG/README.md ================================================ # Number of positive integral solutions ## Medium

You are given an equation of the form x1+x2+...+xN=K. You need to find the total number of positive integral solutions of this equation.
 

Example 1:

Input: s = a+b=5
Output: 4
Explanation: (4,1) , (1,4) , (2,3) , (3,2)


Example 2:

Input: s = a+b=1
Output: 0
Explanation: No solution exist.

 

Your Task:
You don't need to read input or print anything. Your task is to complete the function posIntSol() which takes a string as input and returns number of solutions.

 

Expected Time Complexity : O(Length of given string)
Expected Auxiliary Space : O(1)

 

Constraints:
1 <= K <= 25
2 <= N <= 10

 

================================================ FILE: Number of positive integral solutions - GFG/number-of-positive-integral-solutions.py ================================================ #User function Template for python3 from math import factorial as fact class Solution: def posIntSol(self,s): #code here r=1 n="" for i in range(len(s)): if(s[i]=="+"): r+=1 if(s[i]=="="): n=s[i+1:] break; n=int(n) if(n-1>=r-1): return fact(n-1)//(fact(n-r)*fact(r-1)) else: return 0 #{ # Driver Code Starts #Initial Template for Python 3 if __name__ == '__main__': t = int(input()) for _ in range(t): s = input() solObj = Solution() print(solObj.posIntSol(s)) # } Driver Code Ends ================================================ FILE: Number of ways - GFG/README.md ================================================ # Number of ways ## Medium

Given a value N. In how many ways you can construct a grid of size N x 4 using tiles of size 1 x 4.


Example 1:

Input: N = 1
Output: 1
Explaination: We can arrange the tiles horizontally 
and this is the only way.


Example 2:

Input: N = 4
Output: 2
Explaination: The first way can be when all 
the 1 x 4 tiles are arranged horizontally. 
Second way can be when all the 1 x 4 tiles 
are arranged vertically.


Your Task:
You do not need to read input or print anything. Your task is to complete the function arrangeTiles() which takes the value N as input parameter and returns the number of ways to make N x 4 grid using 1 x 4 tiles.


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


Constraints:
1 ≤ N ≤ 80

================================================ FILE: Number of ways - GFG/number-of-ways.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[])throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); while(t-- > 0){ int N = Integer.parseInt(in.readLine().trim()); Solution ob = new Solution(); System.out.println(ob.arrangeTiles(N)); } } }// } Driver Code Ends //User function Template for Java class Solution{ static long arrangeTiles(int n){ // code here if(n<4)return 1; int four=n/4; long sum=0; for(int i=1;i<=four;i++){ int rem=n-4*i; sum=sum+nCr(rem+i,i); } return sum+1; } static long nCr(int n,int r){ long sum=1; int max=Math.max(r,n-r); int min=Math.min(r,n-r); int st=1; for(int i=n;i>max;i--){ sum= sum*i; sum/=st; st++; } return sum; } } ================================================ FILE: Number-of-ways-to-arrive-destination/Solution.cpp ================================================ typedef pair ip; long long int M=1e9+7; class Solution { public: int countPaths(int n, vector>& roads) { int ans=0; vector dis(n,INT_MAX); vector adj[n]; for(auto it: roads) adj[it[0]].push_back({it[1],it[2]}),adj[it[1]].push_back({it[0],it[2]}); priority_queue,greater > pq; dis[0]=0; pq.push({dis[0],0}); while(!pq.empty()){ int src=pq.top().second,wt=pq.top().first; pq.pop(); for(auto it: adj[src]){ int v=it.first,nw=wt+it.second; if(v==n-1){ if(dis[v]==nw) ans=(ans+1ll)%M; else if(dis[v]>nw) dis[v]=nw,ans=1; } else{ if(dis[v]>=nw) dis[v]=nw,pq.push({dis[v],v}); } } } return ans; } }; ================================================ FILE: Number-of-ways-to-arrive-destination/question.md ================================================ ### Number of Ways to Arrive at Destination **Medium**Accuracy: **48.81%**Submissions: **127**Points: **4** You are in a city that consists of `n` intersections numbered from `0` to `n - 1` with **bi-directional** roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer `n` and a 2D integer array `roads` where `roads[i] = [ui, vi, timei]` means that there is a road between intersections `ui` and `vi` that takes `timei` minutes to travel. You want to know in how many ways you can travel from intersection `0` to intersection `n - 1` in the **shortest amount of time** . Return *the **number of ways** you can arrive at your destination in the **shortest amount of time*** . Since the answer may be large, return it **modulo** `109 + 7`. ``` Example: Input: n=7, m=10 edges= [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]] Output: 4 Explaination: The four ways to get there in 7 minutes are: - 0 6 - 0 4 6 - 0 1 2 5 6 - 0 1 3 5 6 ``` **Constraints:** `1 <= n <= 200
n - 1 <= roads.length <= n * (n - 1) / 2
roads[i].length == 3
0 <= ui, vi <= n - 1
1 <= timei <= 109
u!= vi` There is at most one road connecting any two intersections. You can reach any intersection from any other intersection. Expected Time Complexity: O(M * logN + N) Expected Space Complexity: O(M+N) ================================================ FILE: Numbers-With-Same-Consecutive-Differences.cpp ================================================ class Solution { public: vector ans; void solve(int idx, int n, int k, int num){ if(idx == n){ if(ans.empty() || ans.back() != num) ans.push_back(num); return; } int lastDigit = num % 10; if(lastDigit+k < 10){ solve(idx+1,n,k, num*10 + (lastDigit+k)); } if(lastDigit-k >= 0){ solve(idx+1,n,k, num*10 + (lastDigit-k)); } return; } vector numsSameConsecDiff(int n, int k) { for(int i = 1; i < 10; i++){ solve(1,n,k,i); } return ans; } }; ================================================ FILE: Occurence of Each Number.java ================================================ public class Solution { public ArrayList findOccurences(ArrayList A) { ArrayList ans=new ArrayList<>(); Collections.sort(A); int cnt=1; int prev=A.get(0); for(int i=1;i B){ low++; } else high++; } return 0; } } ================================================ FILE: Pairs With Given Xor.java ================================================ public class Solution { public int solve(int[] A, int B) { Set set = new HashSet<>(); int count = 0; for(int i : A){ if(set.contains(i)){ count++; }else{ set.add(i^B); } } return count; } } ================================================ FILE: Pairs of Non Coinciding Points - GFG/README.md ================================================ # Pairs of Non Coinciding Points ## Medium

In a given cartesian plane, there are N points. We need to find the Number of Pairs of  points(A, B) such that

  • Point A and Point B do not coincide.
  • Manhattan Distance and the Euclidean Distance between the points should be equal.

Note: Pair of 2 points(A,B) is considered same as Pair of 2 points(B ,A).
Manhattan Distance = |x2-x1|+|y2-y1|

Euclidean Distance   = ((x2-x1)^2 + (y2-y1)^2)^0.5, where points are (x1,y1) and (x2,y2).

 

Example 1:

Input:
N = 2
X = {1, 7}
Y = {1, 5}
Output:
0
Explanation:
None of the pairs of points have
equal Manhatten and Euclidean distance.

Example 2:

Input:
N = 3
X = {1, 2, 1}
Y = {2, 3, 3}
Output:
2
Explanation:
The pairs {(1,2), (1,3)}, and {(1,3), (2,3)}
have equal Manhatten and Euclidean distance.

 

Your Task:
You don't need to read input or print anything. Your task is to complete the function numOfPairs() which takes an Integer N and two arrays X, and Y of length N as input and returns the number of pairs with equal Manhattan and Euclidean Distance. (X[i], Y[i]) denotes a point.

 

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

 

Constraints:
1 <= N <= 105
 -10^9 <= X[i], Y[i] <= 10^9

================================================ FILE: Pairs of Non Coinciding Points - GFG/pairs-of-non-coinciding-points.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { int N = Integer.parseInt(read.readLine()); String S1[] = read.readLine().split(" "); String S2[] = read.readLine().split(" "); int[] X = new int[N]; int[] Y = new int[N]; for(int i=0; i xCount = new HashMap<>(); HashMap yCount = new HashMap<>(); HashMap, Integer> visited = new HashMap<>(); int ans = 0; int count1 = 0; int count2 = 0; int count3 = 0; for (int i = 0; i < n; ++i) { count1 += xCount.getOrDefault(x[i], 0); xCount.put(x[i], xCount.getOrDefault(x[i], 0) + 1); } for (int i = 0; i < n; ++i) { count2 += yCount.getOrDefault(y[i], 0); yCount.put(y[i], yCount.getOrDefault(y[i], 0) + 1); } for (int i = 0; i < n; ++i) { ArrayList current = new ArrayList<>(Arrays.asList(x[i], y[i])); count3 += visited.getOrDefault(current, 0); visited.put(current, visited.getOrDefault(current, 0) + 1); } ans = count1 + count2 - 2 * count3; return ans; } }; ================================================ FILE: Palindrome List.java ================================================ public class Solution { public int lPalin(ListNode A) { if(A==null || A.next==null)return 1; int sz=0; ListNode temp=A; while(temp!=null){ temp=temp.next; sz++; } ListNode prev=null; ListNode curr=A; for(int i=0;i pal=new ArrayList<>(); for(i=A;i<=B;i++) { if(check(Integer.toString(i)))pal.add(i); } // int ans=0;/ int l=0; int n=pal.size(); int ans=0; i=0; while(iC)l++; } return ans; } boolean check(String s) { int n=s.length(); int i; for(i=0;i=j) return dp[i][j] = 0; if(dp[i][j] != -1) return dp[i][j]; if(isPalindrome(str,i,j)) return 0; int min = Integer.MAX_VALUE; for(int k=i;k<=j-1;k++){ int left = 0,right = 0; if(dp[i][k] != -1) left = dp[i][k]; else{ left = solve(str,i,k); dp[i][k] = left; } if(dp[k+1][j] != -1) right = dp[k+1][j]; else{ right = solve(str,k+1,j); dp[k+1][j] = right; } int temp = right + left + 1; min = Math.min(min,temp); } return dp[i][j] = min; } static boolean isPalindrome(String str,int i,int j){ String x = str.substring(i,j+1); int k=0,l=x.length()-1; while(k> partition(String a) { ArrayList> ans=new ArrayList<>(); ArrayList path=new ArrayList<>(); helper(a,0,path,ans); return ans; } void helper(String s,int index,ArrayList path,ArrayList> ans){ if(index==s.length()){ ans.add(new ArrayList<>(path)); return; } for(int i=index;i=m && r<60) return r-m; else{ h=(h+1)%24; ans+=60-m; if(h>=10 && (h<16 || h>=20)){ r=(h%10)*10 + h/10; if(r==10) r=1; }else if(h>=16){ ans+=(20-h)*60; r=2; } else if(h<6) r=h*10; else { ans+=(10-h)*60; r=1; } } return ans+r; } } ================================================ FILE: Palindromic Words.java ================================================ public class Solution { public int solve(String A) { int ans=0; String[]arr=A.split(" "); for(String a:arr){ if(isPalindrome(a))ans++; } return ans; } boolean isPalindrome(String str){ // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters to compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } } ================================================ FILE: Partition Array According to Given Pivot.java ================================================ class Solution { public int[] pivotArray(int[] nums, int pivot) { List small=new ArrayList<>(); List large=new ArrayList<>(); int pivs=0; int n=nums.length; for(int i=0;ipivot){ large.add(nums[i]); }else{ pivs++; } } int index=0; for(int i=0;i partitionLabels(string s) { unordered_map mp; for(int i=0;i ans; int prev=-1,mx=0; for(int i=0;i

Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with value equal to x and finally nodes with value greater than or equal to x. The original relative order of the nodes in each of the three partitions should be preserved. The partition must work in-place.
 
Example 1:
Input:
1->4->3->2->5->2->3,
x = 3
Output:
1->2->2->3->3->4->5
Explanation: 
Nodes with value less than 3 come first, 
then equal to 3 and then greater than 3.
Example 2:
Input:
1->4->2->10 
x = 3
Output: 
1->2->4->10
Explanation:
Nodes with value less than 3 come first,
then equal to 3 and then greater than 3.
Your task:
You don't need to read input or print anything. Your task is to complete the function partition() which takes the head of the inked list and an integer x as input, and returns the head of the modified linked list after arranging the values according to x.
 
Expected time complexity : O(n)
Expected Auxiliary Space: O(n)
 
Constraints:
1 <= N <= 105
1 <= k <= 105

================================================ FILE: Partition a Linked List around a given value - GFG/partition-a-linked-list-around-a-given-value.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.io.*; import java.lang.*; class Node { int data; Node next; Node(int key) { data = key; next = null; } } class Partition { static Node head; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int a1 = sc.nextInt(); Node head = new Node(a1); Node tail = head; for (int i = 1; i < n; i++) { int a = sc.nextInt(); // addToTheLast(new Node(a)); tail.next = new Node(a); tail = tail.next; } int k = sc.nextInt(); Solution ob = new Solution(); Node res = ob.partition(head, k); printList(res); System.out.println(); } } public static void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } }// } Driver Code Ends // User function Template for Java /*class Node { int data; Node next; Node(int key) { data = key; next = null; } } */ class Solution { public static Node partition(Node node, int x) { Queue fis=new LinkedList<>(); Queue sec=new LinkedList<>(); Queue thir=new LinkedList<>(); Node temp=node; while(temp!=null){ if(temp.data0){ temp.next=fis.remove(); temp=temp.next; } while(sec.size()>0){ temp.next=sec.remove(); temp=temp.next; } while(thir.size()>0){ temp.next=thir.remove(); temp=temp.next; } return head.next; } } ================================================ FILE: Partition a number into two divisible parts - GFG/README.md ================================================ # Partition a number into two divisible parts ## Medium

Given a number (as string) and two integers a and b, divide the string in two non-empty parts such that the first part is divisible by a and the second part is divisible by b. In case multiple answers exist, return the string such that the first non-empty part has minimum length.

 

Example 1:

Input:
1200 4 3
Output:
12 00
Explanation:
12 is divisible by 4, and
00 is divisible by 3.

 

Example 2:

Input: 
125 12 5
Output: 
12 5
Explanation: 
12 is divisible by 12, and 
5 is divisible by 5.

 

Your Task:

You don't need to read input or print anything. Your task is to complete the function stringPartition() which takes the string S and returns a string which will be in the form of first sub-string + " " (Single Space) + second sub-string. If not found return -1 as a string.

 

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

 

Constraints:

1<=N<=106

1<=a,b<=N

================================================ FILE: Partition a number into two divisible parts - GFG/partition-a-number-into-two-divisible-parts.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[])throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { String str[] = read.readLine().split(" "); String S= str[0]; int a = Integer.parseInt(str[1]); int b = Integer.parseInt(str[2]); Solution ob = new Solution(); System.out.println(ob.stringPartition(S,a,b)); } } }// } Driver Code Ends //User function Template for Java class Solution{ static String stringPartition(String S, int a, int b){ int n=S.length(); String[]pre=new String[n-1]; String[]post=new String[n-1]; for(int i=0;i

Given an integer array a[ ] of N elements and an integer K, the task is to check if the array a[ ] could be divided into K non-empty subsets with equal sum of elements.
Note: All elements of this array should be part of exactly one partition.

Example 1:

Input: 
N = 5
a[] = {2,1,4,5,6}
K = 3
Output: 
1
Explanation: we can divide above array 
into 3 parts with equal sum as (2, 4), 
(1, 5), (6)

Example 2:

Input: 
N = 5 
a[] = {2,1,5,5,6}
K = 3
Output: 
0
Explanation: It is not possible to divide
above array into 3 parts with equal sum.

Your Task:
You don't need to read input or print anything. Your task is to complete the function isKPartitionPossible() which takes the array a[], the size of the array N, and the value of K as inputs and returns true(same as 1) if possible, otherwise false(same as 0).

Expected Time Complexity: O(N*2N).
Expected Auxiliary Space: O(2N).

Constraints:
1 ≤ K ≤ N ≤ 10
1 ≤ a[i] ≤ 100

================================================ FILE: Partition array to K subsets - GFG/partition-array-to-k-subsets.java ================================================ // { Driver Code Starts import java.util.*; class Partition_Arr_To_K_Subsets { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t>0) { int n = sc.nextInt(); int a[] = new int[n]; for(int i=0;itarget) || (i>0 && sum[i] == sum[i-1]))continue; sum[i]+=arr[ind]; if(dfs(ind-1,arr,sum,k,target))return true; sum[i]-= arr[ind]; } return false; } } ================================================ FILE: Partition array to K subsets - GFG/partition-array-to-k-subsets.py ================================================ #User function Template for python3 from functools import lru_cache class Solution: def isKPartitionPossible(self, nums, k): #code here if sum(nums)%k: return False visited=[False]*len(nums) nums.sort(reverse=True) target=sum(nums)/k @lru_cache(None) def solve(i,k,ans): if k==0: return True if ans==target: return solve(0,k-1,0) for j in range(i,len(nums)): if visited[j] or ans+nums[j]>target: continue visited[j]=True if solve(j+1,k,ans+nums[j]): return True visited[j]=False return False return solve(0,k,0) #{ # Driver Code Starts if __name__ == '__main__': tcs = int(input()) for _ in range(tcs): N=int(input()) arr=[int(x) for x in input().split()] k=int(input()) if Solution().isKPartitionPossible(arr, k): print(1) else: print(0) # } Driver Code Ends ================================================ FILE: Partition array to K subsets.java ================================================ class Solution { public boolean isKPartitionPossible(int a[], int n, int k) { // Your code here int sum=0; for(int i:a)sum+=i; if(sum%k != 0)return false; int target=sum/k; int[] subsets=new int[k]; Arrays.sort(a); return dfs(a,subsets,n-1,target); } boolean dfs(int[]a,int[]subsets,int ind,int target){ if(ind==-1)return true; for(int i=0;itarget)continue; subsets[i]+=a[ind]; if(dfs(a,subsets,ind-1,target)){ return true; } subsets[i]-=a[ind]; } return false; } } ================================================ FILE: Party in Town - GFG/README.md ================================================ # Party in Town ## Medium

Geek town has N Houses numbered from 1 to N. They are connected with each other via N-1 bidirectional roads and an adjacency list is used to represent the connections. Find the house from which the distance to the farthest house is the minimum to host the optimal party.


Example 1:

Input: 
N = 4
Roads = {{1,2},{2,3},{2,4}} 
adj = {{2},{1,3,4},{2},{2}} 

Output: 1

Explaination: Maximum distance from house number 2 is 1.


Your Task:
You do not need to read input or print anything. Your task is to complete the function partyHouse() which takes N and adj as input parameters and returns the minimum possible distance to the farthest house from the house where the party is happening.


Expected Time Complexity: O(N*N)
Expected Auxiliary Space: O(1)


Constraints:
1 ≤ N ≤ 1000

================================================ FILE: Party in Town - GFG/party-in-town.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[])throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); while(t-- > 0){ int N = Integer.parseInt(in.readLine()); ArrayList> adj = new ArrayList>(); for(int i = 0;i < N+1;i++){ ArrayList arr = new ArrayList(); adj.add(arr); } for(int i = 0;i < N-1;i++){ String a[] = in.readLine().trim().split("\\s+"); int x = Integer.parseInt(a[0]); int y = Integer.parseInt(a[1]); adj.get(x).add(y); adj.get(y).add(x); } Solution ob = new Solution(); System.out.println(ob.partyHouse(N, adj)); } } }// } Driver Code Ends //User function Template for Java class Solution{ static int dfs(ArrayList> adj, int start, boolean[]visited){ Queue q = new LinkedList<>(); q.add(start); int level = 0; while(!q.isEmpty()){ int size = q.size(); while(size-->0){ int val = q.remove(); visited[val] = true; for(int i : adj.get(val)){ if(visited[i]==false){ q.add(i); } } } level++; } return level-1; } static int partyHouse(int N, ArrayList> adj) { int ans = Integer.MAX_VALUE; for(int i=1; i<=N;i++){ boolean[]visited = new boolean[N+1]; ans = Math.min(ans, dfs(adj, i,visited)); } return ans; } } ================================================ FILE: Pascal's Triangle.java ================================================ class Solution { public List> generate(int numRows) { List> triangle=new ArrayList<>(); triangle.add(new ArrayList<>()); triangle.get(0).add(1); for(int i = 1; i < numRows; i++){ List row = new ArrayList<>(); List prevRow = triangle.get(i-1); row.add(1); for(int j = 1; j < i; j++){ row.add(prevRow.get(j-1) + prevRow.get(j)); } row.add(1); triangle.add(row); } return triangle; } } ================================================ FILE: Path in Directed Graph.java ================================================ public class Solution { public int solve(int A, int[][] B) { Map>map=new HashMap<>(); for(int i=0;i()); } for(int i=0;i arr=map.get(B[i][0]); arr.add(B[i][1]); map.put(B[i][0],arr); } Queue q=new LinkedList<>(); q.add(1); boolean[]vis=new boolean[A+1]; while(!q.isEmpty()){ int sz=q.size(); for(int i=0;i>map=new HashMap<>(); for(int i=0;i()); } for(int i=0;i arr=map.get(B[i][0]); arr.add(B[i][1]); map.put(B[i][0],arr); } Queue q=new LinkedList<>(); q.add(1); boolean[]vis=new boolean[A+1]; while(!q.isEmpty()){ int sz=q.size(); for(int i=0;i ans=new ArrayList<>(); public ArrayList solve(TreeNode A, int B) { target=B; solve(A,new ArrayList()); return ans; } public void solve(TreeNode curr,ArrayList arr){ if(curr==null)return; arr.add(curr.val); if(curr.val==target){ ans=arr; return; }else{ if(curr.left!=null){ solve(curr.left,(ArrayList)arr.clone()); } if(curr.right!=null){ solve(curr.right,(ArrayList)arr.clone()); } } } } ================================================ FILE: Path with good nodes!.java ================================================ public class Solution { public int solve(int[] type, int[][] B, int C) { int n = type.length; ArrayList> adj = new ArrayList<>(); for(int i = 0; i < n; i++) adj.add(new ArrayList<>()); for(int[] edge : B){ adj.get(edge[0] - 1).add(edge[1] - 1); adj.get(edge[1] - 1).add(edge[0] - 1); } return dfs(0, type, C - type[0], -1, adj); } private int dfs(int root,int[] type, int goodNodes, int par, ArrayList> adj){ if(goodNodes < 0) return 0; int cnt = 0; // we are at leaf node if(adj.get(root).size() == 1) { return 1; } for(int child :adj.get(root)){ if(child == par)continue; cnt += dfs(child, type, goodNodes - type[child], root, adj); } return cnt; } } ================================================ FILE: Perfect Peak of Array.java ================================================ public class Solution { public int perfectPeak(int[] A) { int n=A.length; int[] maxArr=new int[n]; int[] minArr=new int[n]; maxArr[0]=A[0]; for(int i=1;i=0;i--){ minArr[i]=Math.min(A[i],minArr[i+1]); } for(int i=1;imaxArr[i-1] && A[i] len_s2) return false; int[] count = new int[26]; for (int i = 0; i < len_s1; i++) { count[s1.charAt(i) - 'a']++; count[s2.charAt(i) - 'a']--; } if (zeroCount(count)) return true; for (int i = len_s1; i < len_s2; i++) { count[s2.charAt(i) - 'a']--; count[s2.charAt(i - len_s1) - 'a']++; if (zeroCount(count)) return true; } return false; } private boolean zeroCount(int[] count) { for (int i = 0; i < 26; i++) { if (count[i] != 0) return false; } return true; } } ================================================================================================== class Solution { public boolean checkInclusion(String s1, String s2) { int[] arr=new int[26]; for(char c:s1.toCharArray()){ arr[(int)c-97]++; } int[] a=new int[26]; for(int i=0;i<=s2.length()-s1.length();i++){ a=arr.clone(); boolean present=false; for(int j=i;j

Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. The output should be printed in sorted increasing order of strings

Example 1:

Input:
S = "ABC"
Output: (A B C)(A BC)(AB C)(ABC)
Explanation:
ABC
AB C
A BC
A B C
These are the possible combination of "ABC".

 

Example 2:

Input:
S = "AB"
Output: (A B)(AB)


Your Task:  
You don't need to read input or print anything. Your task is to complete the function permutation() which takes the string S as input parameters and returns the sorted array of the string denoting the different permutation (DON'T ADD '(' and ')' it will be handled by the driver code only).

Expected Time Complexity: O(2^n)
Expected Auxiliary Space: O(1)

 

CONSTRAINTS:
1 < |S| < 10
S only contains lowercase and Uppercase English letters.

================================================ FILE: Permutation with Spaces - GFG/permutation-with-spaces.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[])throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { String S = read.readLine().trim(); Solution ob = new Solution(); ArrayList ans = new ArrayList(); ans = ob.permutation(S); for(int i=0;i ans; ArrayList permutation(String S){ ans=new ArrayList<>(); helper("",S); return ans; } public void helper(String curr,String s){ if(s.length()==0){ ans.add(curr); return; } if(curr.length()==0){ helper(s.charAt(0)+"",s.substring(1)); return; } helper(curr+" "+s.charAt(0),s.substring(1)); helper(curr+s.charAt(0),s.substring(1)); } } ================================================ FILE: Permutations.java ================================================ public class Solution { ArrayList> ans; public ArrayList> permute(ArrayList A) { int n=A.size(); ans=new ArrayList<>(); boolean[] vis=new boolean[n]; dfs(new ArrayList<>(),A,vis); return ans; } public void dfs(ArrayList curr,ArrayList A,boolean[]vis){ if(curr.size()==A.size()){ if(!ans.contains(curr)){ ans.add(new ArrayList(curr)); } return; } for(int i=0;i

Given two polynomial numbers represented by a linked list. The task is to complete the function addPolynomial() that adds these lists meaning adds the coefficients who have the same variable powers.
Note: 
 Given polynomials are sorted in decreasing order of power.

Example 1:

Input:
LinkedList1:  (1,x2) 
LinkedList2:  (1,x3)
Output:
1x^3 + 1x^2
Explanation: Since, x2 and x3 both have
different powers as 2 and 3. So, their
coefficient can't be added up.

Example 2:

Input:
LinkedList1:  (1,x3) -> (2,x2)
LinkedList2:  (3,x3) -> (4,x2)
Output:
4x^3 + 6x^2
Explanation: Since, x3 has two different
coefficients as 3 and 1. Adding them up
will lead to 4x3. Also, x2 has two
coefficients as 4 and 2. So, adding them
up will give 6x2.

Your Task:
The task is to complete the function addPolynomial() which should add the polynomial with same powers return the required polynomial in decreasing order of the power in the form of a linked list.
Note: Try to solve the question without using any extra space.

Expected Time Complexity: O(N+M)
Expected Auxiliary Space: O(1)

Constraints:
1 <= N, M <= 105
1 <= x, y <= 106

================================================ FILE: Polynomial Addition - GFG/polynomial-addition.java ================================================ // { Driver Code Starts import java.util.Scanner; import java.io.*; class Node{ int coeff; int pow; Node next; Node(int a,int b) { coeff=a; pow=b; next=null; } } class GFG2 { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); Node start1=null,cur1=null,start2=null,cur2=null; while(n-->0) { int a=sc.nextInt(); int b=sc.nextInt(); Node ptr=new Node(a,b); if(start1==null) { start1=ptr; cur1=ptr; } else{ cur1.next=ptr; cur1=ptr; } } n=sc.nextInt(); while(n-->0) { int a=sc.nextInt(); int b=sc.nextInt(); Node ptr=new Node(a,b); if(start2==null) { start2=ptr; cur2=ptr; } else{ cur2.next=ptr; cur2=ptr; } } Solution obj=new Solution(); Node sum = obj.addPolynomial(start1,start2); for(Node ptr=sum ; ptr != null; ptr=ptr.next ) { // printing polynomial System.out.print(ptr.coeff + "x^" + ptr.pow); if(ptr.next != null) System.out.print(" + "); } System.out.println(); } } }// } Driver Code Ends /*class Node{ int coeff; int pow; Node next; Node(int a,int b) { coeff=a; pow=b; next=null; } }*/ //Print the polynomial formed by adding both LL in the function itself. class Solution { public static Node addPolynomial(Node p1,Node p2) { //Add your code here. Node ans =new Node(-1,-1); Node curr=ans; Node temp1=p1; Node temp2=p2; while(temp1!=null && temp2!=null){ if(temp1.pow==temp2.pow){ temp1.coeff=temp1.coeff+temp2.coeff; curr.next=temp1; curr=curr.next; temp1=temp1.next; temp2=temp2.next; }else if(temp2.powfindPairs(int arr[], int n) { ArrayList< Integer > results = new ArrayList<>(); Set< Integer > set = new HashSet<>(); for (int a : arr) { if (set.contains(-a)) { int x = Math.abs(a); results.add(-x); results.add(x); } set.add(a); } return results; } } ================================================ FILE: Postorder Traversal (Iterative).java ================================================ class Tree { ArrayList postOrder(Node node) { // code here Map map=new HashMap<>(); Deque s=new ArrayDeque<>(); ArrayList ans=new ArrayList<>(); if(node!=null){ s.push(node); map.put(node,true); } if(node.right!=null){ s.push(node.right); map.put(node.right,false); } if(node.left!=null){ s.push(node.left); map.put(node.left,false); } while(!s.isEmpty()){ Node cur=s.pop(); if(map.get(cur)){ ans.add(cur.data); }else{ s.push(cur); if(cur.right!=null){ s.push(cur.right); map.put(cur.right,false); } if(cur.left!=null){ s.push(cur.left); map.put(cur.left,false); } map.put(cur,true); } } return ans; } } ================================================ FILE: Postorder Traversal.py ================================================ class Solution: # @param A : root node of tree # @return a list of integers def postorderTraversal(self, A): ans=[] if A==None: return ans stack=[(A,0)] while len(stack)>0: (curr,vis)=stack.pop() if vis==1: ans.append(curr.val) else: stack.append((curr,1)) if curr.right!=None: stack.append((curr.right,0)) if curr.left!=None: stack.append((curr.left,0)) return ans ================================================ FILE: Pots of Gold Game.java ================================================ class GfG { public static int maxCoins(int A[],int n) { //add code here. int[][]dp=new int[n+1][n+1]; return dfs(A,0,n-1,dp); } static int dfs(int[]A,int i,int j,int[][]dp){ if(i==j)return A[i]; if(i+1==j)return Math.max(A[i],A[j]); if(dp[i][j]==0){ int start=A[i]+Math.min(dfs(A,i+2,j,dp),dfs(A,i+1,j-1,dp)); int end=A[j]+Math.min(dfs(A,i+1,j-1,dp),dfs(A,i,j-2,dp)); dp[i][j]=Math.max(start,end); } return dp[i][j]; } } ================================================ FILE: Power Of 2 and Subsequences GFG/powerOf2Sub.cpp ================================================ long long numberOfSubsequences(int N, long long A[]){ int mod=1e9+7; long long count=0; for(int i=0;i A){ // code here int cnt=0; long mod=1000000007l; for(Long i:A){ if((i&(i-1))==0){ cnt++; } } return (long)(Math.pow(2,cnt)%mod-1)%mod; } } ================================================ FILE: Power Of 2 and Subsequences.py ================================================ class Solution: def numberOfSubsequences (ob,N,A): import math A2 = [] for i in A: if math.ceil((math.log(i, 2) )) == math.floor((math.log(i, 2))): A2.append(i) n = len(A2) return (2**n - 1) % (10**9+7) ================================================ FILE: Power of 2 and Subsequences.cpp ================================================ class Solution{ public: long long numberOfSubsequences(int N, long long A[]){ // code here long long ans = 0, MOD = 1e9+7; for(int i=0; i 1) { if(temp%2) { f = false; break; } temp /= 2; } if(f) { ans *= 2; ans++; ans %= MOD; } } return ans; } }; ================================================ FILE: Power of 2 and Subsequences.java ================================================ class Solution{ static Long numberOfSubsequences(int N, ArrayList A){ // code here long m=(long)1e9+7; long count=0; for(int i=0;iInput: N = 3 A[] = {1, 6, 2} Output: 3 Explanation: The subsequence that can be chosen is {1}, {2} and {1,2}. **Example 2:**
Input:
N = 3
A[] = {3, 5, 7}
Output:
0
Explanation:
No subsequences exist.
**Your Task:** You don't need to read input or print anything. Your task is to complete the function numberOfSubsequences() which takes an integer N and an array A and returns the number of subsequences that exist. As this number can be very large return the result under modulo 10 ^9^ +7. **Expected Time Complexity:** O(N) **Expected Auxiliary Space:** O(1) **Constraints:** 1 <= N <= 10^5^ 1 <= A[i] <= 10^9^ ================================================ FILE: Preorder Traversal.java ================================================ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { ArrayList ans; public ArrayList preorderTraversal(TreeNode A) { ans=new ArrayList<>(); pre(A); return ans; } void pre(TreeNode root){ if(root==null)return; ans.add(root.val); pre(root.left); pre(root.right); } } ================================================ FILE: Preorder to BST.java ================================================ public static Node post_order(int pre[], int size) { //Your code here Node root=new Node(pre[0]); for(int i=1;i

Given a non-negative number N in the form of string. The task is to apply at most one swap operation on the number N so that the result is just a previous possible number.

Note:  Leading zeros are not allowed.

 

Example 1:

Input :
S = "12435"
Output: 
12345
Explanation:
Although the number 12354 
will be the largest smaller 
number from 12435. But it is 
not possible to make it using 
only one swap. So swap 
4 and 3 and get 12345.

 

Example 2:

Input: 
S = " 12345"
Output: 
-1
Explanation:
Digits are in increasing order. 
So it is not possible to 
make a smaller number from it.

 

Your Task:

You don't need to read input or print anything. Your task is to complete the function previousNumber() which takes the string S and returns the previous number of S. If no such number exists return -1;

 

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

 

Constraints:
2<=|Number length |<=105

 

================================================ FILE: Previous number in one swap - GFG/previous-number-in-one-swap.py ================================================ #User function Template for python3 class Solution: def previousNumber (ob,S): i=len(S)-2 while i>=0 and S[i]<=S[i+1]: i-=1 if i<0: return '-1' j=len(S)-1 while j>i and S[i]<=S[j]: j-=1 while j>0 and S[j-1]==S[j]: j-=1 S=list(S) S[i],S[j]=S[j],S[i] if S[0]=='0': return '-1'; return ''.join(S) #{ # Driver Code Starts #Initial Template for Python 3 if __name__ == '__main__': t = int (input ()) for _ in range (t): S=str(input()) ob = Solution() print(ob.previousNumber(S)) # } Driver Code Ends ================================================ FILE: Prim's_Algorithm.cpp ================================================ #include using namespace std; int main(){ int m,n; cin>>m>>n; vector> adj[m]; for(int i =0;i>x>>y>>w; adj[x].push_back({y,w}); adj[y].push_back({x,w}); } vector key(m,INT_MAX),parent(m,-1),mst(m,false); key[0]=0; parent[0]=-1; for(int i =0;i "< primesum(int A) { ArrayList al=new ArrayList<>(); boolean a[]=prime(A); for(int i=2;i<=A;i++){ if(a[i]==false && a[A-i]==false){ al.add(i); al.add(A-i); break; } } return al; } } ================================================ FILE: Print Diagonally - GFG/README.md ================================================ # Print Diagonally ## Easy

Give a N * N square matrix A, return all the elements of its anti-diagonals from top to bottom.

Example 1:

Input: 
N = 2
A = [[1, 2],
     [3, 4]]
Output:
1 2 3 4
Explanation: 

Hence, elements will be returned in the 
order {1, 2, 3, 4}.

Example 2:

Input: 
N = 3 
A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
Output: 
1 2 4 3 5 7 6 8 9
Explanation: 

Hence, elements will be returned in 
the order {1, 2, 4, 3, 5, 7, 6, 8, 9}.

Your Task:
You don't need to read input or print anything. Your task is to complete the function downwardDigonal() which takes an integer N and a 2D matrix A[ ][ ] as input parameters and returns the list of all elements of its anti-diagonals from top to bottom.

Expected Time Complexity: O(N*N)
Expected Auxillary Space: O(N*N)

Constraints:
1 ≤ N, M ≤ 103
0 ≤ A[i][j] ≤ 106

================================================ FILE: Print Diagonally - GFG/print-diagonally.java ================================================ //{ Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[])throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); int matrix[][] = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) matrix[i][j] = sc.nextInt(); } Solution ob = new Solution(); ArrayList ans = ob.downwardDigonal(n, matrix); for (Integer val: ans) System.out.print(val+" "); System.out.println(); } } } // } Driver Code Ends //User function Template for Java class Solution{ static ArrayList downwardDigonal(int N, int A[][]) { // code here ArrayList ans=new ArrayList<>(); int row=0; int col=0; while(col=0){ ans.add(A[r][c]); r++; c--; } col++; } col=N-1; row=1; while(row=0){ ans.add(A[r][c]); r++; c--; } row++; } return ans; } } ================================================ FILE: Print Pattern using String.java ================================================ class Solution{ static List pattern(int n){ // code here List r=new ArrayList<>(); int first=1; int end=n*(n+1); int spaces=0; for(int i=0;i using namespace std; class Solution{ public: vector pattern(int n){ // code here vector res; int cnt=1; for(int i=0;i=0;i--){ string t=""; for(int j=n-1;j>=i;j--){ t+= to_string(cnt++)+"*"; } t.pop_back(); res[i]+= t; } return res; } }; // 2. class Solution{ public: vector pattern(int n){ // code here vector v; int curr=n, next=n*n+1; for(int i=0;i pattern(int n){ // code here int num=1; List ans=new ArrayList<>(); for(int row=0;row=0;row--){ StringBuilder sb=new StringBuilder(ans.get(row)); for(int times=0;times

Given an NxN chessboard and a Knight at position (x, y). The Knight has to take exactly K steps, where at each step it chooses any of the 8 directions uniformly at random. Find the probability that the Knight remains in the chessboard after taking K steps, with the condition that it cant enter the board again once it leaves it.
 

Example 1:

Input : N = 8, x = 0, y = 0, K = 3
Output: 0.125000

Example 2:

Input: N = 4, x = 1, y = 2, k = 4
Output: 0.024414

 

Your Task: 
You don't need to read or print anything. Your task is to complete the function findProb() which takes N, x, y and K as input parameter and returns the probability.

 

Expected Time Complexity : O(N 3)
Expected Space Complexity: O(N3)

 

Constraints:
1 <= N <= 100
0 <= x, y <= N

0 <= K <= N

================================================ FILE: Probability of Knight - GFG/probability-of-knight.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String s = br.readLine().trim(); String []S = s.split(" "); int N = Integer.parseInt(S[0]); int start_x = Integer.parseInt(S[1]); int start_y = Integer.parseInt(S[2]); int step = Integer.parseInt(S[3]); Solution ob = new Solution(); double ans = ob.findProb(N, start_x, start_y, step); System.out.println(String.format("%.6f", ans)); } } } // } Driver Code Ends //User function Template for Java // code starts class Solution { public static boolean isValid(int ni, int nj, int n){ if(ni>=0 && nj>=0 && ni

Given two numbers L and R (inclusive) find the product of primes within this range. Print the product modulo 109+7. If there are no primes in that range you must print 1.

Example 1:

Input: L = 1, R = 10
Output: 210
Explaination: The prime numbers are 
2, 3, 5 and 7.

Example 2:

Input: L = 1, R = 20
Output: 9699690
Explaination: The primes are 2, 3, 
5, 7, 11, 13, 17 and 19.

Your Task:
You do not need to read input or print anything. Your task is to complete the function primeProduct() which takes L and R and returns the product of the primes within the range. If there are no primes in that range then return 1.

Expected Time Complexity: O((R-L)*(logR))
Expected Auxiliary Space: O(sqrt(R))

Constraints:
1 ≤ L ≤ R ≤ 109
0 ≤ L - R ≤ 106  

================================================ FILE: Product of Primes - GFG/product-of-primes.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[])throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); while(t-- > 0){ String a[] = in.readLine().trim().split("\\s+"); long L = Long.parseLong(a[0]); long R = Long.parseLong(a[1]); Solution ob = new Solution(); System.out.println(ob.primeProduct(L, R)); } } }// } Driver Code Ends //User function Template for Java class Solution{ static int mod=1000000007; static long primeProduct(long L, long R){ // code here long ans=1; for(long i=L;i<=R;i++){ if(isPrime(i)){ ans=(ans%mod*i)%mod; } } return ans; } static boolean isPrime(long n){ if(n<=1) return false; if(n==2) return true; for(long i=2;i<=Math.sqrt(n);i++){ if(n%i==0) return false; } return true; } } ================================================ FILE: Profit Maximisation.java ================================================ public class Solution { public int solve(int[] A, int B) { PriorityQueue pq=new PriorityQueue<>(Collections.reverseOrder()); for(int i:A){ pq.add(i); } int ans=0; while(B>0){ int val=pq.remove(); ans+=val; val--; pq.add(val); B--; } return ans; } } ================================================ FILE: Pythagorean Triplets.java ================================================ public class Solution { public int solve(int n) { int ans=0; for(int i=3;i<=n-2;i++){ for(int j=i+1;j<=n-1;j++){ for(int k=j+1;k<=n;k++){ if(isTriplet(i,j,k))ans++; } } } return ans; } public boolean isTriplet(int a,int b,int c){ return (a*a)+(b*b)==c*c; } } ================================================ FILE: Queries on Strings - GFG/README.md ================================================ # 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|

================================================ FILE: Queries on Strings - GFG/queries-on-strings.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String str = br.readLine().trim(); int q = Integer.parseInt(br.readLine().trim()); int[][] Query = new int[q][2]; for(int i = 0; i < q; i++){ String[] s = br.readLine().trim().split(" "); for(int j = 0; j < 2; j++){ Query[i][j] = Integer.parseInt(s[j]); } } Solution obj = new Solution(); int[] ans = obj.SolveQueris(str, Query); for(int i = 0; i < ans.length; i++) System.out.print(ans[i] + " "); System.out.println(); } } } // } Driver Code Ends //User function Template for Java class Solution { public int[] SolveQueris(String str, int[][] Query) { Set set = new HashSet<>(); int a[]= new int[Query.length]; for(int i=0;i s1 = new Stack(); Stack s2 = new Stack(); //Function to push an element in queue by using 2 stacks. void Push(int x) { // Your code here s1.push(x); } //Function to pop an element from queue by using 2 stacks. int Pop() { // Your code here while(s1.size()>0){ s2.push(s1.pop()); } int num=-1; if(s2.size()>0){ num=s2.pop(); } while(s2.size()>0){ s1.push(s2.pop()); } return num; } } ================================================ FILE: QuickSort on Doubly Linked List.java ================================================ class GfG { public static Node partition(Node l, Node h) { //code here. Node pivot=l; Node left=l; Node right=h; boolean flag=false; while(!flag){ while(left!=null && left.data<=pivot.data){ if(left==right)flag=true; left=left.next; } while(right!=null && right.data>pivot.data){ if(right==left)flag=true; right=right.prev; } if(!flag)swap(left,right); } swap(pivot,right); return right; } static void swap(Node a,Node b){ int temp=a.data; a.data=b.data; b.data=temp; } } ================================================ FILE: README.md ================================================ # DSA > Building the largest DSA solutions repository TOGETHER. # Note: > All DsA repositories are excluded from Hacktoberfest # Beginner's Guide --- # 🔥Find your solution - Press "T" in windows/mac/linux to open the file finder. - Enter your problem name. We support only following naming formats to find files! Note: We are slowly migrating to normal word spacing format for new files, see [Contributing.md](https://github.com/Sagar0-0/DsA/blob/main/CONTRIBUTING.md). - ### Old questions finding - PascalCase (ThisIsTheExampleOfPascalCaseWritingWriting) - Snake case (this_is_the_example_of_snake_case_writing) - Caterpillar case (this-is-the-example-of-catarpillar-case-writing) - Normal (A question name with proper words and spacings) - Most of Leetcode Questions also have question numbers. Eg. 1007-minimum-domino-rotations-f... - ### New questions finding - Normal (A question name with proper words and spacings) - Proper structure with folders/directories according to coding platforms. - If exists, select your solution file according to your programming language. - If your problem's solution doesn't exist - Either create an new [Issue](https://github.com/Sagar0-0/DsA/issues) and request public to solve it for you.(Coming soon...) - Or [Contribute](https://github.com/Sagar0-0/DsA/pulls) it by yourself🔥 --- # ✅Open To Contribute - Start your open source journey with us🚀 - Share your code with the world✨ - Become an active member🔥 - Contribute and get Appreciated🤝 - Must read [CONTRIBUTING.md](https://github.com/Sagar0-0/DsA/blob/main/CONTRIBUTING.md) before contributing. > *No more DSA contributions from my side.* --- # ➡️Platforms covered:








--- # ✅Contributors > Thanks to these amazing contributors who helps us in building the LARGEST DSA SOLUTIONS REPOSITORY --- ## Love my work? # ☕My Coding Profiles:



================================================ FILE: Rank The Permutations - GFG/README.md ================================================ # 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

================================================ FILE: Rank The Permutations - GFG/rank-the-permutations.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String str = br.readLine().trim(); Solution obj = new Solution(); long ans = obj.findRank(str); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution { public long findRank(String s){ // Code here if(s.length()==0){ return 0; } long res=1; for(int i=0; i s.charAt(j)){ cou++; } } res += cou * fact(s.length()-1-i); } return res; } long fact(int n){ if(n<=1){ return 1; } return n * fact(n-1); } } ================================================ FILE: Rat Maze With Multiple Jumps - GFG/README.md ================================================ # Rat Maze With Multiple Jumps ## Medium

A Maze is given as n*n matrix of blocks where source block is the upper left most block i.e., matrix[0][0] and destination block is lower rightmost block i.e., matrix[n-1][n-1]. A rat starts from source and has to reach the destination. The rat can move in only two directions: first forward if possible or down. If multiple solutions exist, the shortest earliest hop will be accepted. For the same hop distance at any point, forward will be preferred over downward. In the maze matrix, 0 means the block is the dead end and non-zero number means the block can be used in the path from source to destination. The non-zero value of mat[i][j] indicates number of maximum jumps rat can make from cell mat[i][j]. In this variation, Rat is allowed to jump multiple steps at a time instead of 1. Find a matrix which describes the position the rat to reach at the destination.
 

Example:

Input: {{2,1,0,0},{3,0,0,1},{0,1,0,1},
{0,0,0,1}}
Output: {{1,0,0,0},{1,0,0,1},{0,0,0,1},
{0,0,0,1}}
Explanation: Rat started with matrix[0][0] and 
can jump up to 2 steps right/down. First check 
matrix[0][1] as it is 1, next check 
matrix[0][2] ,this won't lead to the solution. 
Then check matrix[1][0], as this is 3(non-zero)
,so we can make 3 jumps to reach matrix[1][3]. 
From matrix[1][3] we can move downwards taking 
1 jump each time to reach destination at 
matrix[3][3].

Example 2:

Input: {{2,1,0,0},{2,0,0,1},{0,1,0,1},
{0,0,0,1}}
Output: {{-1}}
Explanation: As no path exists so, -1.

 

Your Task:
You don't need to read or print anyhting, Your task is to complete the function ShortestDistance() which takes the matrix as input parameter and returns a matrix of size n if path exists otherwise returns a matrix of 1x1 which contains -1. In output matrix, 1 at (i, j) represents the cell is taken into the path otherwise 0 if any path exists.

 

Expected Time Complexity: O(n*n*k) where k is max(matrix[i][j])
Expected Space Complexity: O(1)

 

Constraints:
1 <= n <= 50
1 <= matrix[i][j] <= 20

================================================ FILE: Rat Maze With Multiple Jumps - GFG/rat-maze-with-multiple-jumps.java ================================================ // { Driver Code Starts import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { int n = Integer.parseInt(br.readLine().trim()); int[][] matrix = new int[n][n]; for(int i = 0; i < n; i++){ String[] S = br.readLine().trim().split(" "); for(int j = 0; j < n; j++) matrix[i][j] = Integer.parseInt(S[j]); } Solution ob = new Solution(); int[][] ans = ob.ShortestDistance(matrix); for(int i = 0; i < ans.length; i++){ for(int j = 0; j < ans[i].length; j++){ System.out.print(ans[i][j] + " "); } System.out.println(); } } } } // } Driver Code Ends class Solution { public int[][] ShortestDistance(int[][] matrix){ // Code here int m= matrix.length; int n= matrix[0].length; if(matrix[0][0]==0 && n!=1){ int ans[][]={{-1}}; return ans; } int ans[][] = new int[m][n]; if(solver(matrix, ans,0,0)==false){ ans[0][0]=-1; return ans; } return ans; } public boolean solver(int[][] matrix,int[][] ans,int i,int j){ if(i==matrix.length-1 && j==matrix[0].length-1){ ans[i][j]=1; return true; } if(isValid(i,j,matrix)){ ans[i][j] = 1; for(int k=1;k<=matrix[i][j] && k=matrix.length || y>=matrix[0].length||matrix[x][y]==0){ return false; } return true; } } ================================================ FILE: Reaching the heights - GFG/README.md ================================================ # Reaching the heights ## Medium

The teacher gives a mental ability question to Raju. The question is as follows:-

Raju is in an elevator. Given by his teacher is an array of size N which denotes the number of floors and has a 1 based indexing. The elevator starts from the ground and moves up and down, X and Y floors respectively. There is a code used in the elevator according to which it moves up X floors given at odd indexes of the array and moves down Y floors given at even indexes of the array. He is asked to go to the highest floor possible. Help him to sort the array such that he reaches the highest floor after traversing the whole array from starting till the end, without skipping any index.

He always prefers to move more number of floors up and less number of floors down. Once he gets into the elevator, the elevator should not reach the ground again, if it does print Not Possible.

Example 1:

Input : arr[ ] = {2, 3, 4, 5}
Output : 5 2 4 3
Explanation:
Array can be arranged as {5,3,4,2} or 
{4,3,5,2} or {4,2,5,3} but it will get 
arranged as {5,2,4,3} because he always 
prefer to move more number of floors up 
and less number of floors down.


Example 2:

Input : arr[ ] = {1, 1} 
Output :  Not Possible 

 

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 game_with_number() that takes sizeOfArray (n), an array (arr), and return the sorted array or if it is Not Possible return -1. The driver code takes care of the printing.

Expected Time Complexity: O(N*LOG(N)).
Expected Auxiliary Space: O(1).

 


Constraints:

1 ≤ N ≤ 105
1 ≤ arr[i] ≤ 103

================================================ FILE: Reaching the heights - GFG/reaching-the-heights.java ================================================ // { Driver Code Starts //Initial Template for Java //Initial Template for Java /*package whatever //do not write package name here */ import java.io.*; import java.util.*; class Array { // Driver code public static void main (String[] args) throws IOException{ // Taking input using buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testcases = Integer.parseInt(br.readLine()); // looping through all testcases while(testcases-- > 0){ String line = br.readLine(); String[] element = line.trim().split("\\s+"); int N = Integer.parseInt(element[0]); int arr [] = new int[N]; line = br.readLine(); String[] elements = line.trim().split("\\s+"); for(int i = 0;i ans; ans = obj.reaching_height(N, arr); if(ans.size() == 1 && ans.get(0) == -1){ System.out.println("Not Possible"); continue; } for(int i: ans) System.out.print(i + " "); System.out.println(); } } } // } Driver Code Ends //User function Template for Java //2 4 10 //10 2 4 class Complete{ // Function for finding maximum and value pair public static ArrayList reaching_height (int n, int arr[]) { //Complete the function ArrayList ans=new ArrayList<>(); Arrays.sort(arr); int flag=0; int end=arr.length-1; int start=0; while(end>=start){ ans.add(arr[end]); flag+=arr[end]; if(end!=start){ ans.add(arr[start]); flag-=arr[start]; } end--; start++; } if(flag==0){ ans.clear(); ans.add(-1); } return ans; } } ================================================ FILE: Rearrange Geek and his Classmates.java ================================================ class Solution { void prank(long[] a, int n) { for(int i=0;i

Given a string s, remove all its adjacent duplicate characters recursively. 

Example 1:

Input:
S = "geeksforgeek"
Output: "gksforgk"
Explanation: 
g(ee)ksforg(ee)k -> gksforgk


Example 2:

Input: 
S = "abccbccba"
Output: ""
Explanation: 
ab(cc)b(cc)ba->abbba->a(bbb)a->aa->(aa)->""(empty string)


Your Task:
You don't need to read input or print anything. Your task is to complete the function remove() which takes the string S as input parameter and returns the resultant string.
Note: For some test cases, the resultant string would be an empty string. For that case, the function should return the empty string only.


Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(|S|)


Constraints:
1<=|S|<=105

================================================ FILE: Recursively remove all adjacent duplicates - GFG/recursively-remove-all-adjacent-duplicates.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases while(t-->0){ String S = br.readLine(); Solution ob = new Solution(); System.out.println(ob.remove(S)); } } }// } Driver Code Ends //User function Template for Java class Solution{ String remove(String s) { if(s.length()<=1) return s; StringBuilder str = new StringBuilder(); for(int i =0;i stack=new ArrayDeque<>(); int n=s.length(); for(int i=0;i0){ char ch=stack.pop(); if(ch=='(')break; if(ch=='+' || ch=='-' || ch=='*' || ch=='/'){ count++; } } if(count==0)return 1; } } return 0; } } ================================================ FILE: Region in BinaryMatrix.java ================================================ public class Solution { int[][]arr; boolean[][]vis; public int solve(int[][] A) { arr=A; int n=A.length; int m=A[0].length; vis=new boolean[n][m]; int ans=0; for(int i=0;iB) res += A.charAt(A.length()-1); return res; } } ================================================ FILE: Remove Covered Intervals.java ================================================ class Solution { public int removeCoveredIntervals(int[][] nums) { Arrays.sort(nums, new Comparator() { public int compare(int[] o1, int[] o2){ if(o1[0]==o2[0])return o2[1]-o1[1]; return o1[0]-o2[0]; }}); int count = 0, cur = 0; for(int interval[] : nums){ if(cur < interval[1]){ cur = interval[1]; count++; } } return count; } } ================================================ FILE: Remove Duplicates from Sorted Array II.java ================================================ class Solution { public int removeDuplicates(int[] nums) { int count=1; int i=0; int j=1; while(j a) { int extras=0; int i=0; int x=0; while(i1){ a.set(x,a.get(i)); x++; a.set(x,a.get(i)); x++; i=j; extras+=cnt-2; }else{ a.set(x,a.get(i)); x++; i=j; } } return a.size()-extras; } } ================================================ FILE: Remove Duplicates from Sorted List II.java ================================================ class Solution { public ListNode deleteDuplicates(ListNode head) { // sentinel ListNode sentinel = new ListNode(0, head); // predecessor = the last node // before the sublist of duplicates ListNode pred = sentinel; while (head != null) { if (head.next != null && head.val == head.next.val) { while (head.next != null && head.val == head.next.val) { head = head.next; } pred.next = head.next; } else { pred = pred.next; } head = head.next; } return sentinel.next; } } ================================================ FILE: Remove Duplicates from Sorted List.java ================================================ public class Solution { public ListNode deleteDuplicates(ListNode A) { ListNode temp=A; while(temp.next!=null){ if(temp.val==temp.next.val){ temp.next=temp.next.next; }else{ temp=temp.next; } } return A; } } ================================================ FILE: Remove Half Nodes.java ================================================ public class Solution { public TreeNode solve(TreeNode A) { if(A==null)return A; if(A.left!=null && A.right!=null){ A.left=solve(A.left); A.right=solve(A.right); }else if(A.left!=null){ A=solve(A.left); }else if(A.right!=null){ A=solve(A.right); } return A; } } ================================================ FILE: Remove K Digits.java ================================================ class Solution { public String removeKdigits(String num, int k) { Deque stack = new ArrayDeque<>(); for(char c : num.toCharArray()){ while(!stack.isEmpty() && k > 0 && stack.peek() > c) { stack.pop(); k--; } stack.push(c); } while(!stack.isEmpty() && k > 0){ stack.pop(); k--; } StringBuilder sb = new StringBuilder(); while(!stack.isEmpty()){ sb.append(stack.pop()); } sb.reverse(); while(sb.length() > 1 && sb.charAt(0) == '0'){ sb.deleteCharAt(0); } return sb.length() > 0 ? sb.toString() : "0"; } } ================================================ FILE: Remove Nth Node from List End.java ================================================ public class Solution { public ListNode removeNthFromEnd(ListNode A, int B) { int size=0; ListNode temp=A; while(temp!=null){ size++; temp=temp.next; } if(B>=size)return A.next; int toGo=size-B; temp=A; for(int i=1;i map=new HasMap<>(); for(char c:S.toCharArray())map.put(c,map.getOrDefault(c,0)+1); for(int i=0;i1)return c; } return '#'; } } //O(n) //O(1) class Solution { char firstRep(String S) { for(int i=0;i

Given an array arr[] of N integers and replace every element with the least greater element on its right side in the array. If there are no greater elements on the right side, replace it with -1. 

Example 1:

Input:
arr[] = {8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28}
Output: {18, 63, 80, 25, 32, 43, 80, 93, 80, 25, 93, -1, 28, -1, -1}
Explanation: 
The least next greater element of 8 is 18.
The least next greater element of 58 is 63 and so on.

Example 2:

Input:
arr[] = {2, 6, 9, 1, 3, 2}
Output: {3, 9, -1, 2, -1, -1}
Explanation: 
The least next greater element of 2 is 3. 
The least next greater element of 6 is 9.
least next greater element for 9 does not
exist and so on.

Your Task:  
You don't need to read input or print anything. Your task is to complete the function findLeastGreater() which takes an array arr[] of size N and returns a list as an output.

Expected Time Complexity: O(N* log N)
Expected Auxiliary Space: O(N)

Constraints:
1 <= N <= 105
1 <= A[i] <= 105

================================================ FILE: Replace every element with the least greater element on its right - GFG/replace-every-element-with-the-least-greater-element-on-its-right.java ================================================ //{ Driver Code Starts import java.io.*; import java.util.*; class IntArray { public static int[] input(BufferedReader br, int n) throws IOException { String[] s = br.readLine().trim().split(" "); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = Integer.parseInt(s[i]); return a; } public static void print(int[] a) { for(int e : a) System.out.print(e + " "); System.out.println(); } public static void print(ArrayList a) { for(int e : a) System.out.print(e + " "); System.out.println(); } } class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t; t = Integer.parseInt(br.readLine()); while(t-- > 0){ int n; n = Integer.parseInt(br.readLine()); int[] arr = IntArray.input(br, n); Solution obj = new Solution(); ArrayList res = obj.findLeastGreater(n, arr); IntArray.print(res); } } } // } Driver Code Ends class Solution { public static ArrayList findLeastGreater(int n, int[] arr) { // code here TreeSet set=new TreeSet<>(); ArrayList ans =new ArrayList<>(); for(int i=n-1;i>=0;i--){ set.add(arr[i]); if(set.higher(arr[i])==null)ans.add(-1); else ans.add(set.higher(arr[i])); } Collections.reverse(ans); return ans; } } ================================================ FILE: Return two prime numbers.java ================================================ class Solution{ static Set set=new HashSet<>(); static List primeDivision(int n){ // code here List ans=new ArrayList<>(); for(int i=2;i> 1 return ans ================================================ FILE: Reverse First K elements of Queue ================================================ public Queue modifyQueue(Queue q, int k) { // using a stack and another queue to reverse first k elements. Stack s = new Stack<>(); Queue qq = new LinkedList<>(); // we pop first k elements from queue and push it in the stack. while (k-- > 0) { int a = q.peek(); q.poll(); s.push(a); } // while stack is not empty, we push the elements into the new queue. while (!s.isEmpty()) { int a = s.peek(); s.pop(); qq.add(a); } // then we add rest of the elements of original queue to the new queue. while (!q.isEmpty()) { int a = q.peek(); q.poll(); qq.add(a); } // returning the new queue. return qq; } ================================================ FILE: Reverse Level Order.java ================================================ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ import java.util.*; public class Solution { public ArrayList solve(TreeNode node) { ArrayList list=new ArrayList<>(); Stack S = new Stack(); Queue Q = new LinkedList(); Q.add(node); // Do something like normal level order traversal order.Following // are the differences with normal level order traversal // 1) Instead of printing a node, we push the node to stack // 2) Right subtree is visited before left subtree while (Q.isEmpty() == false) { /* Dequeue node and make it root */ node = Q.peek(); Q.remove(); S.push(node); /* Enqueue right child */ if (node.right != null) // NOTE: RIGHT CHILD IS ENQUEUED BEFORE LEFT Q.add(node.right); /* Enqueue left child */ if (node.left != null) Q.add(node.left); } // Now pop all items from stack one by one and print them while (S.empty() == false) { node = S.peek(); System.out.print(node.val + " "); S.pop(); } return list; } } ================================================ FILE: Reverse Spiral Form of Matrix - GFG/README.md ================================================ # Reverse Spiral Form of Matrix ## Medium

Given a matrix as 2D array. Find the reverse spiral traversal of the matrix. 

Example 1:

Input: R = 3, C = 3
  a = {{9, 8, 7},
       {6, 5, 4},
       {3, 2, 1}}
Output: 5 6 3 2 1 4 7 8 9
Explanation: Spiral form of the matrix
in reverse order starts from the centre 
and goes outward.


Example 2:

Input: R = 4, C = 4 
  a = {{1, 2, 3, 4},
       {5, 6, 7, 8},
       {9, 10, 11, 12}, 
       {13, 14, 15, 16}}
Output: 10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1
Explanation: 


Your Task:  
You dont need to read input or print anything. Complete the function reverseSpiral() which takes R, C and a as input parameters and returns the matrix in reverse spiral form.


Expected Time Complexity: O(R*C)
Expected Auxiliary Space: O(R*C)

Constraints:
1 <= R,C <=100
1 <= a[R][C] <=100

================================================ FILE: Reverse Spiral Form of Matrix - GFG/reverse-spiral-form-of-matrix.java ================================================ //{ Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[])throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { String[] input = new String[2]; input = read.readLine().split(" "); int R = Integer.parseInt(input[0]); int C = Integer.parseInt(input[1]); String s1[] = read.readLine().trim().split("\\s+"); int a[][] = new int[R][C]; for(int i = 0;i < R*C;i++) a[i/C][i%C] = Integer.parseInt(s1[i]); Solution ob = new Solution(); int[] ans = ob.reverseSpiral(R,C,a); for(int i = 0; i < ans.length; i++) { System.out.print(ans[i] + " "); } System.out.println(); } } } // } Driver Code Ends //User function Template for Java class Solution { public int[] reverseSpiral(int R, int C, int[][] a) { // code here int[] ans=new int[R*C]; int idx=R*C-1; int up=0; int down=a.length-1; int left=0; int right=a[0].length-1; while(idx>=0){ //upper row for(int i=left;i<=right && idx>=0;i++){ ans[idx--]=a[up][i]; } up++; //last col for(int i=up;i<=down && idx>=0;i++){ ans[idx--]=a[i][right]; } right--; //lower row for(int i=right;i>=left && idx>=0;i--){ ans[idx--]=a[down][i]; } down--; for(int i=down;i>=up && idx>=0;i--){ ans[idx--]=a[i][left]; } left++; } return ans; } } ================================================ FILE: Reverse a Stack using Recursion.cpp ================================================ class Solution { void insertAtBottom(stack &s,int &x) { if(s.empty()) { s.push(x); return; } int num = s.top(); s.pop(); insertAtBottom(s,x); s.push(num); } void solve(stack &st) { if(st.empty()) return; int x = st.top(); st.pop(); solve(st); insertAtBottom(st,x); } public: stack Reverse(stack st) { solve(st); return st; } }; ================================================ FILE: Reverse a string using Stack.java ================================================ class Solution { public String reverse(String S){ //code here Deque s=new ArrayDeque<>(); for(char c:S.toCharArray()){ s.push(c); } S=""; while(!s.isEmpty()){ S+=s.pop()+""; } return S; } } ================================================ FILE: Reverse a sublist of a linked list - GFG/README.md ================================================ # Reverse a sublist of a linked list ## Hard

Given a linked list and positions m and n. Reverse the linked list from position m to n.

Example 1:

Input :
N = 10
Linked List = 1->7->5->3->9->8->10
                      ->2->2->5->NULL
m = 1, n = 8
Output : 2 10 8 9 3 5 7 1 2 5 
Explanation :
The nodes from position 1 to 8 
are reversed, resulting in 
2 10 8 9 3 5 7 1 2 5.

Example 2:

Input:
N = 6
Linked List = 1->2->3->4->5->6->NULL
m = 2, n = 4
Output: 1 4 3 2 5 6
Explanation:
Nodes from position 2 to 4 
are reversed resulting in
1 4 3 2 5 6.
Your task :
You don't need to read input or print anything. Your task is to complete the function reverseBetween() which takes the head of the linked list and two integers m and n as input and returns the head of the new linked list after reversing the nodes from position m to n.
 
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
 
Constraints:
1<=N<=10^5

================================================ FILE: Reverse a sublist of a linked list - GFG/reverse-a-sublist-of-a-linked-list.java ================================================ // { Driver Code Starts //Initial Template for Java //Initial Template for Java import java.io.*; import java.util.*; class Node { int data; Node next; Node(int d) {data = d; next = null; } } class insertion { Node head; Node tail; public void addToTheLast(Node node) { if (head == null) { head = node; tail = node; } else { tail.next = node; tail = node; } } void printList(Node head) { Node temp = head; while (temp != null) { System.out.print(temp.data+" "); temp = temp.next; } System.out.println(); } /* Drier program to test above functions */ public static void main(String args[])throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // Scanner sc = new Scanner(System.in); int t=Integer.parseInt(br.readLine()); while(t>0) { String S[] = br.readLine().split(" "); int N = Integer.parseInt(S[0]); int m = Integer.parseInt(S[1]); int n = Integer.parseInt(S[2]); String S1[] = br.readLine().split(" "); insertion llist = new insertion(); int a1=Integer.parseInt(S1[0]); Node head= new Node(a1); llist.addToTheLast(head); for (int i = 1; i < N; i++) { int a = Integer.parseInt(S1[i]); llist.addToTheLast(new Node(a)); } Solution ob = new Solution(); Node newhead=ob.reverseBetween(llist.head, m, n); llist.printList(newhead); t--; } }}// } Driver Code Ends //User function Template for Java /* class Node { int data; Node next; Node(int d) {data = d; next = null; } } */ class Solution { public static Node reverseBetween(Node head, int m, int n) { if(m > n) return head; Node prev = null; Node curr = head; for(int i=1; i arr, int n, int k) { for (int i = 0; i < n; i += k) { // Get the left element ========== int starting = i; // Get the right most element ==== int ending = Math.min(i + k - 1, n - 1); // Now swap reverse the small piece of sub-arry in the arraylist while(starting < ending){ int aux = arr.get(starting); arr.set(starting, arr.get(ending)); arr.set(ending, aux); starting++; ending--; } } } } ================================================ FILE: Reverse the String.cpp ================================================ #include using namespace std; int getLength(char ayu[]){ int count=0; for (int i=0; ayu[i]!='\0';i++){ count++; } return count; } void reverse(char ayu[], int n){ int s=0; int e=n-1; while(s>ayu; cout<<"My name is "<=0;i--){ if(s.charAt(i)==' '){ if(sb.length()!=0){ ans+=sb.reverse()+" "; sb.setLength(0); } }else{ sb.append(s.charAt(i)); } } ans+=sb.reverse(); return ans.trim(); } } ================================================ FILE: Reverse-Interger.java ================================================ class Solution { public int reverse(int x) { int result = 0; while ( x != 0){ int d = x % 10 ; int next = result * 10 + d; if((next - d)/10 != result){ return 0; } result = next; x = x / 10 ; } return result; } } ================================================ FILE: Richest Customer Wealth.java ================================================ class Solution { public int maximumWealth(int[][] a) { int max=0; for(int i=0;i solve(TreeNode A) { ArrayList ans=new ArrayList<>(); dfs(A,ans,0); return ans; } public void dfs(TreeNode a,ArrayList ans,int level){ if(a==null)return; if(ans.size()==level){ ans.add(a.val); } dfs(a.right,ans,level+1); dfs(a.left,ans,level+1); } } ================================================ FILE: Robot Bounded In Circle ================================================ class Solution { public boolean isRobotBounded(String instructions) { int dir[][] = {{0,1}, {-1, 0}, {0, -1}, {1,0}}; int i = 0; int x = 0; int y = 0; for(int s = 0; s < instructions.length(); s++){ if(instructions.charAt(s) == 'L'){ i = (i + 1) % 4; } else if(instructions.charAt(s) == 'R'){ i = (i + 3) % 4; } else{ x = x + dir[i][0]; y = y + dir[i][1]; } } return x == 0 && y == 0 || i != 0; } } ================================================ FILE: Robots.java ================================================ class Solution { public String moveRobots(String s1, String s2) { int i = 0, j = 0, n = s1.length(); while(i < n && j < n) { if(s1.charAt(i) == '#') { i++; } else if(s2.charAt(j) == '#') { j++; } else if(s1.charAt(i) != s2.charAt(j)) { return "No"; } else if(s1.charAt(i) == 'B' && i > j) { return "No"; } else if(s1.charAt(i) == 'A' && i < j) { return "No"; } else { i++; j++; } } return "Yes"; } } ================================================ FILE: Roman To Integer.java ================================================ public class Solution { public int romanToInt(String A) { int ans=0; int i=0; while(igetValue(A.charAt(i))){ ans+=getValue(A.charAt(i+1))-getValue(A.charAt(i)); i+=2; }else{ ans+=getValue(A.charAt(i)); i++; } }else{ ans+=getValue(A.charAt(i)); i++; } } return ans; } int getValue(char ch){ switch(ch){ case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return -1; } } } ================================================ FILE: Root to Leaf Paths With Sum.java ================================================ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { ArrayList> ans; public ArrayList> pathSum(TreeNode A, int B) { ans=new ArrayList<>(); ArrayList curr=new ArrayList<>(); curr.add(A.val); dfs(A,B,curr,A.val); return ans; } public void dfs(TreeNode a,int b,ArrayList list,int curr){ if(a.left==null && a.right==null){ if(curr==b){ ans.add(new ArrayList<>(list)); } return; } if(a.left!=null){ list.add(a.left.val); curr+=a.left.val; dfs(a.left,b,list,curr); curr-=a.left.val; list.remove(list.size()-1); } if(a.right!=null){ list.add(a.right.val); curr+=a.right.val; dfs(a.right,b,list,curr); curr-=a.right.val; list.remove(list.size()-1); } } } ================================================ FILE: Rotate Image.cpp ================================================ class Solution { public: void rotate(vector>& matrix) { transpose(matrix); reflect(matrix); } public: void transpose(vector>& matrix){ int n = matrix.size(); for(int i =0; i>& matrix){ int n = matrix.size(); for(int i =0; i0){ sz--; temp=temp.next; } ListNode Alast=temp; ListNode Bfist=Alast.next; if(Bfist==null)return A; Alast.next=null; temp=Bfist; while(temp.next!=null){ temp=temp.next; } temp.next=A; return Bfist; } } ================================================ FILE: Rotate Matrix.java ================================================ public class Solution { public void rotate(ArrayList> arr) { int n=arr.size(); int a=0; int b=n-1; while(a temp=arr.get(a); arr.set(a,arr.get(b)); arr.set(b,temp); a++; b--; } int num=0; while(num'){ ans+=left; }else{ left--; } } return ans; } } ================================================ FILE: Save Your Life - GFG/README.md ================================================ # Save Your Life ## Medium

Given a string w, integer array b,  character array and an integer n. n is the size of array b and array x. Find a substring which has the sum of the ASCII values of its every character, as maximum. ASCII values of some characters are redefined.
Note:
 Uppercase & lowercase both will be present in the string w. Array b and Array x contain corresponding redefined ASCII values. For each i, 0<=ib[i] contain redefined ASCII value of character x[i].

Example 1:

Input:
W = abcde
N = 1
X[] = { 'c' }
B[] = { -1000 }
Output:
de
Explanation:
Substring "de" has the
maximum sum of ascii value,
including c decreases the sum value

Example 2:

Input:
W = dbfbsdbf 
N = 2
X[] = { 'b','s' }
B[] = { -100, 45  }
Output:
dbfbsdbf
Explanation:
Substring "dbfbsdbf" has the maximum
sum of ascii value.


Your Task:
You don't need to read input or print anything. Your task is to complete the function maxSum() which takes string W, character array X, integer array B, integer N as length of array X and B as input parameters and returns the substring with the maximum sum of ascii value.

 

Expected Time Complexity: O(|W|)
Expected Auxiliary Space: O(1)


Constraints:

1<=|W|<=100000
1<=|X|<=52
-1000<=Bi<=1000

Each character of W and A will be from a-z, A-Z.

================================================ FILE: Save Your Life - GFG/save-your-life.java ================================================ //{ Driver Code Starts import java.io.*; import java.util.*; // } Driver Code Ends class Solution{ static String maxSum(String w,char x[],int b[], int n){ //code here Map map=new HashMap<>(); for(int i=0;imaxSum){ maxSum=currSum; ans=new StringBuilder(temp); } if(currSum<0){ currSum=0; temp=new StringBuilder(); } } return ans.toString(); } } //{ Driver Code Starts. class GFG { public static void main(String args[])throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { String w = read.readLine(); int n = Integer.parseInt(read.readLine()); String TE[] = read.readLine().trim().split(" "); char x[] = new char[n]; for(int i = 0;ib){ dfs(a,b,ans,i,mid-1); }else{ dfs(a,b,ans,mid+1,j); } } } } ================================================ FILE: Search in Bitonic Array!.java ================================================ public class Solution { public int solve(ArrayList A, int B) { int l=0; int h=A.size()-1; while(l<=h){ int mid=(l+h)/2; if(A.get(mid)==B){ return mid; }else if(A.get(mid)B){ if(A.get(l)

Given a sorted array Arr[](0-index based) consisting of distinct integers and an integer k, the task is to find the index of k, if its present in the array Arr[]. Otherwise, find the index where k must be inserted to keep the array sorted.


Example 1:

Input:
N = 4
Arr = {1, 3, 5, 6}
k = 5
Output: 2
Explaination: Since 5 is found at index 2 
as Arr[2] = 5, the output is 2.


Example 2:

Input:
N = 4
Arr = {1, 3, 5, 6}
k = 2
Output: 1
Explaination: Since 2 is not present in 
the array but can be inserted at index 1 
to make the array sorted.


Your Task:
You don't need to read input or print anything. Your task is to complete the function searchInsertK() which takes the array Arr[] and its size N and as input parameters and returns the index.


Expected Time Complexity: O(logN)
Expected Auxiliary Space: O(1)


Constraints:
1 ≤ N ≤ 104
-103 ≤ Arr[i] ≤ 103
-103 ≤ k ≤ 103

================================================ FILE: Search insert position of K in a sorted array - GFG/search-insert-position-of-k-in-a-sorted-array.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[])throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { int N = Integer.parseInt(read.readLine()); String input_line[] = read.readLine().trim().split("\\s+"); int Arr[]= new int[N]; for(int i = 0; i < N; i++) Arr[i] = Integer.parseInt(input_line[i]); int k = Integer.parseInt(read.readLine()); Solution ob = new Solution(); System.out.println(ob.searchInsertK(Arr, N, k)); } } }// } Driver Code Ends //User function Template for Java class Solution { static int searchInsertK(int a[], int N, int k){ int i=0; int j=a.length; while(i solve(ArrayList arr) { Collections.sort(arr); return arr; } } ================================================ FILE: Self Permutation.java ================================================ public class Solution { public int permuteStrings(String A, String B) { HashMap hm = new HashMap<>(); if(A.length()!=B.length()) return 0; for(int i=0; i sequentialDigits(int low, int high) { List list=new ArrayList<>(); this.high=high; this.low=low; for(int i=1;i<=9;i++){ dfs(i,list); } Collections.sort(list); return list; } public void dfs(int num,List list){ int add=(num%10)+1; if(add!=10){ num=(num*10)+add; if(num<=high){ if(num>=low){ list.add(num); } dfs(num,list); } } } } ================================================ FILE: Serialize.java ================================================ public class Solution { public String serialize(ArrayList A) { StringBuilder sb=new StringBuilder(); for(String s:A){ sb.append(s); sb.append(s.length()); sb.append("~"); } return sb.toString(); } } ================================================ FILE: Shop in Candy Store - GFG/README.md ================================================ # Shop in Candy Store ## Easy

In a candy store, there are N different types of candies available and the prices of all the N different types of candies are provided to you.
You are now provided with an attractive offer.
You can buy a single candy from the store and get at most K other candies ( all are different types ) for free.
Now you have to answer two questions. Firstly, you have to find what is the minimum amount of money you have to spend to buy all the N different candies. Secondly, you have to find what is the maximum amount of money you have to spend to buy all the N different candies.
In both the cases you must utilize the offer i.e. you buy one candy and get K other candies for free.

Example 1:

Input:
N = 4
K = 2
candies[] = {3 2 1 4}

Output:
3 7

Explanation:
As according to the offer if you buy 
one candy you can take at most two 
more for free. So in the first case, 
you buy the candy which costs 1 and 
takes candies worth 3 and 4 for free, 
also you buy candy worth 2 as well.
So min cost : 1+2 =3.
In the second case, you can buy the 
candy which costs 4 and takes candies 
worth 1 and 2 for free, also you need 
to buy candy worth 3 as well. 
So max cost : 3+4 =7.

Example 2:

Input: 
N = 5
K = 4
candies[] = {3 2 1 4 5}

Output: 
1 5

Explanation:
For minimimum cost buy the candy with
the cost 1 and get all the other candies
for free.
For maximum cost buy the candy with
the cost 5 and get all other candies
for free.

Your Task:  
You don't need to read input or print anything. Your task is to complete the function candyStore() which takes the array candies[], its size N and an integer K as input parameters and returns the minimum amount and maximum amount of money to buy all candies according to the offer.

Expected Time Complexity: O(NLogN)
Expected Auxiliary Space: O(1)


Constraints:
1 <= <= 100000
 0 <= K <= N-1
1 <= candies[i] <= 10000

================================================ FILE: Shop in Candy Store - GFG/shop-in-candy-store.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[])throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { String input_line[] = read.readLine().trim().split("\\s+"); int N = Integer.parseInt(input_line[0]); int K = Integer.parseInt(input_line[1]); input_line = read.readLine().trim().split("\\s+"); int candies[]= new int[N]; for(int i = 0; i < N; i++) candies[i] = Integer.parseInt(input_line[i]); Solution ob = new Solution(); ArrayList cost = ob.candyStore(candies,N,K); System.out.println(cost.get(0)+" "+cost.get(1)); } } } // } Driver Code Ends //User function Template for Java class Solution{ static ArrayList candyStore(int arr[],int N,int k){ // code here ArrayList ans=new ArrayList<>(); Arrays.sort(arr); int i=0; int j=N-1; int minCost=0; while(i<=j){ minCost+=arr[i]; j-=k; i++; } ans.add(minCost); i=0; j=N-1; int maxCost=0; while(i<=j){ maxCost+=arr[j]; j--; i+=k; } ans.add(maxCost); return ans; } } ================================================ FILE: Shortest Distance in a Binary Maze - GFG/README.md ================================================ # Shortest Distance in a Binary Maze ## Medium

Given a n * m matrix grid where each element can either be 0 or 1. You need to find the shortest distance between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1. 

If the path is not possible between source cell and destination cell, then return -1.

Note : You can move into an adjacent cell if that adjacent cell is filled with element 1. Two cells are adjacent if they share a side. In other words, you can move in one of the four directions, Up, Down, Left and Right.

Example 1:

Input:
grid[][] = {{1, 1, 1, 1},
            {1, 1, 0, 1},
            {1, 1, 1, 1},
            {1, 1, 0, 0},
            {1, 0, 0, 1}}
source = {0, 1}
destination = {2, 2}
Output:
3
Explanation:
1 1 1 1
1 1 0 1
1 1 1 1
1 1 0 0
1 0 0 1
The highlighted part in the matrix denotes the 
shortest path from source to destination cell.

Example 2:

Input:
grid[][] = {{1, 1, 1, 1, 1},
            {1, 1, 1, 1, 1},
            {1, 1, 1, 1, 0},
            {1, 0, 1, 0, 1}}
source = {0, 0}
destination = {3, 4}
Output:
-1
Explanation:
The path is not possible between source and 
destination, hence return -1.

Your Task:

You don't need to read or print anything. Your task is to complete the function shortestPath() which takes the a 2D integer array grid, source cell and destination cell as an input parameters and returns the shortest distance between source and destination cell.

Expected Time Complexity: O(n * m)
Expected Space Complexity: O(n * m)

Constraints:

  • 1 ≤ n, m ≤ 500
  • grid[i][j] == 0 or grid[i][j] == 1
  • The source and destination cells are always inside the given matrix.
  • The source and destination cells always contain 1.
================================================ FILE: Shortest Distance in a Binary Maze - GFG/shortest-distance-in-a-binary-maze.java ================================================ //{ Driver Code Starts // Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; // Position this line where user code will be pasted. class GFG { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while (T-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { grid[i][j] = sc.nextInt(); } } int[] source = new int[2]; for (int i = 0; i < 2; i++) { int x = sc.nextInt(); source[i] = x; } int[] dest = new int[2]; for (int i = 0; i < 2; i++) { int x = sc.nextInt(); dest[i] = x; } Solution ob = new Solution(); int ans = ob.shortestPath(grid, source, dest); System.out.println(ans); } } } // } Driver Code Ends // User function Template for Java class Solution { class Pair{ int x; int y; Pair(int i,int j){ x=i; y=j; } } int shortestPath(int[][] grid, int[] src, int[] des) { Queue q=new LinkedList<>(); q.add(new Pair(src[0],src[1])); grid[src[0]][src[1]]=0; int dis=0; while(!q.isEmpty()){ int sz=q.size(); while(sz-->0){ Pair curr=q.remove(); int i=curr.x; int j=curr.y; if(i==des[0] && j==des[1])return dis; if(i>0 && grid[i-1][j]==1){ grid[i-1][j]=0; q.add(new Pair(i-1,j)); } if(j>0 && grid[i][j-1]==1){ grid[i][j-1]=0; q.add(new Pair(i,j-1)); } if(i q = new LinkedList<>(); for (int i = 0; i < n; i++) { int source = 1 << i; q.add(new int[] {i,source}); seen[i][source] = true; } int level = 0; while (!q.isEmpty()) { int size = q.size(); for (int i = 0; i < size; i++) { int[] currentPair = q.remove(); int node = currentPair[0]; int mask = currentPair[1]; for (int nei : graph[node]) { int nextMask = mask | (1 << nei); if (nextMask == target) return level + 1; if (!seen[nei][nextMask]) { seen[nei][nextMask] = true; q.add(new int[] {nei, nextMask}); } } } level++; } return -1; } } ================================================ FILE: Shortest Path between Cities - GFG/README.md ================================================ # 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

================================================ FILE: Shortest Path between Cities - GFG/shortest-path-between-cities.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0){ String input_line[] = read.readLine().trim().split("\\s+"); int x = Integer.parseInt(input_line[0]); int y = Integer.parseInt(input_line[1]); Solution ob = new Solution(); System.out.println(ob.shortestPath(x,y)); } } } // } Driver Code Ends //User function Template for Java class Solution { Map map; int shortestPath( int x, int y){ int max=Math.max(x,y); int min=Math.min(x,y); int ans=0; while(max!=min){ max/=2; ans++; if(max

Given two strings S and T, find length of the shortest subsequence in S which is not a subsequence in T. If no such subsequence is possible, return -1. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. A string of length n has 2^n different possible subsequences.

 

Example 1:

Input:
S = "babab"
T = "babba"
Output:
3
Explanation:
There are no subsequences of S with
length less than 3 which is not a
subsequence of T. "aab" is an example of
a subsequence of length 3 which isn't a
subsequence of T.

Example 2:

Input:
S = "babhi"
T = "babij"
Output:
1
Explanation:
"h" is a subsequence of S that is
not a subsequence of T.

 

Your Task:
You don't need to read input or print anything. Your task is to complete the function shortestUnSub() which takes two Strings S, and T as input and returns the shortest Uncommon Subsequence.

 

Expected Time Complexity: O(|S|2*|T|)
Expected Auxiliary Space: O(|S|*|T|)

 

Constraints:
1 <= |S|, |T| <= 500

================================================ FILE: Shortest Uncommon Subsequence - GFG/shortest-uncommon-subsequence.cpp ================================================ // { Driver Code Starts #include using namespace std; // } Driver Code Ends class Solution { public: int findShortest(vector> &dp, string &S, string &T, int n, int m, int i, int j){ if(i >= n){ return 501; } if(j >= m){ return 1; } if(dp[i][j] != -1){ return dp[i][j]; } int k = j; for(; k < m; k++){ if(S[i] == T[k]){ break; } } if(k == m){ return 1; } return dp[i][j] = min(findShortest(dp, S, T, n, m, i + 1, j), 1 + findShortest(dp, S, T, n, m, i + 1, k + 1)); } int shortestUnSub(string S, string T) { int n = S.size(); int m = T.size(); vector> dp (n + 1, vector (m + 1, -1)); int ans = findShortest(dp, S, T, n, m, 0, 0); return ans >= 501 ? -1 : ans; } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { string S,T; cin>>S>>T; Solution ob; cout << ob.shortestUnSub(S,T) << endl; } return 0; } // } Driver Code Ends ================================================ FILE: Shortest Uncommon Subsequence - GFG/shortest-uncommon-subsequence.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { String A[] = read.readLine().split(" "); String S = A[0]; String T = A[1]; Solution ob = new Solution(); System.out.println(ob.shortestUnSub(S,T)); } } }// } Driver Code Ends //bcda //bcd //dp[i][j]=Math.min(dp[i-1][j],dp[i-1][k]+ 1) //User function Template for Java class Solution { static int shortestUnSub(String S, String T) { // code here int n=S.length(); int m=T.length(); int[][]dp=new int[n+1][m+1]; for(int i=0;i<=n;i++){ dp[i][0]=1; } int MAX=501; for(int j=0;j<=m;j++){ dp[0][j]=MAX; } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ int k; for(k=j-1;k>=0;k--){ if(S.charAt(i-1)==T.charAt(k))break; } if(k==-1){ dp[i][j]=1; }else{ dp[i][j]=Math.min(dp[i-1][j],dp[i-1][k]+ 1); } } } if(dp[n][m]>=MAX)return -1; return dp[n][m]; } }; ================================================ FILE: Shortest Unique prefix for every word.java ================================================ class Trie{ Trie[] children; int count; Trie(){ children = new Trie[26]; count = 0; } static void insert(Trie root, String s){ Trie temp = root; for(char ch : s.toCharArray()){ int index = ch-'a'; if(temp.children[index] == null){ temp.children[index] = new Trie(); } temp.children[index].count++; temp = temp.children[index]; } } static String searchPrefix(Trie root, String s){ StringBuilder ans = new StringBuilder(); Trie temp = root; for(char ch : s.toCharArray()){ int index = ch-'a'; ans.append(ch); if(temp.children[index].count == 1){ break; } temp = temp.children[index]; } return ans.toString(); } } class Solution { static String[] findPrefixes(String[] arr, int n) { // code here String[]ans=new String[n]; Trie root=new Trie(); for(String s:arr){ Trie.insert(root,s); } for(int i=0;i using namespace std; void toposort(vector> adj[], vector &vis, stack &st, int node) { vis[node] = 1; for (auto it : adj[node]) { if (!vis[it.first]) { toposort(adj, vis, st, it.first); } } st.push(node); } void sdd(vector> adj[], int n, int src) { vector vis(n, 0); stack st; for (int i = 0; i < n; i++) { if (!vis[i]) { toposort(adj, vis, st, i); } } vector dist(n, INT_MAX); dist[src] = 0; while (!st.empty()) { int node = st.top(); st.pop(); if(dist[node]!=INT_MAX){ for(auto it: adj[node]){ if(dist[node]+it.second> m >> n; vector> adj[m]; for (int i = 0; i < n; i++) { int x, y, w; cin >> x >> y >> w; adj[x].push_back({y, w}); } int src; cin >> src; sdd(adj, m, src); return 0; } ================================================ FILE: Simplify Path.java ================================================ class Solution { public String simplifyPath(String path) { Deque dq = new LinkedList<>(); int i = 0; while (i < path.length()) { i++; int l = i; while (i < path.length() && path.charAt(i) != '/') i++; String segment = path.substring(l, i); if (segment.equals(".") || segment.isEmpty()) continue; if (segment.equals("..")) { if (!dq.isEmpty()) dq.pollLast(); } else { dq.offerLast(segment); } } if (dq.isEmpty()) return "/"; StringBuilder result = new StringBuilder(); while (!dq.isEmpty()) { result.append("/").append(dq.pollFirst()); } return result.toString(); } } ================================================ FILE: Single Element in Sorted Array.py ================================================ """LEETCODE""" #QUESTION LINK:-https://leetcode.com/problems/single-element-in-a-sorted-array/ #SOLUTION:- class Solution(object): def singleNonDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ l,r=0,len(nums)-1 if r==0: return nums[-1] while l<=r: mid=(l+r)//2 if (mid==0 and nums[mid]!=nums[mid+1]) or (mid==r and nums[mid]!=nums[mid-1]) or nums[mid]!=nums[mid-1] and nums[mid]!=nums[mid+1]: return nums[mid] elif (mid%2==0 and nums[mid]==nums[mid-1]) or (mid%2!=0 and nums[mid]==nums[mid+1]): r=mid-1 else: l=mid+1 return -1 #EXPLANATION:- #This question is tricky. From examples we can observe that among the repeated elements, the first occur at even index and second at odd index (until the single element is found.) We will use that trick. #We will initialize a left and right (l and r) variable as 0 and len(nums)-1. #If r==0(only one element of the array), we will return the only element of the array. #After that we will start a while loop till l is less than r, and we will initialize a mid variable as l+r//2. # Now here the tricky part comes, as first condition, we will check if the mid is at index 0 and it is not equal to next index element, OR if mid is the last index and mid is not equal to the previous index element OR if the element is neither equal to the previous nor to the next element, if it fulfills any condition, we will return the mid index. # If the first condition is not fulfilled, we will check if the mid is at even index and the element before the mid is equal to current element OR if the index is odd and the next element is equal to to the current element, we will increment the r index. #If none of the conditions meet, we will increment the l index. #If none element found in loop, we will return -1 as element not found. #SUBMISSION REPORT:- # Runtime: 147 ms, faster than 92.46% of Python online submissions for Single Element in a Sorted Array. # Memory Usage: 20.6 MB, less than 20.29% of Python online submissions for Single Element in a Sorted Array. ================================================ FILE: Single Number II.java ================================================ public class Solution { // DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY public int singleNumber(final int[] A) { int num=0,n=A.length; for(int i=0;i<32;i++) { int count=0; for(int j=0;j A) { int ans=0; for(int i:A){ ans=ans^i; } return ans; } } ================================================ FILE: Sliding Window Maximum.java ================================================ public class Solution { // DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY public int[] slidingMaximum(final int[] arr, int B) { int ans[]=new int[arr.length-B+1]; int idx=0; if(arr.length==1){ ans[0]=arr[0]; return ans; } Deque q=new ArrayDeque<>(); int i; for(i=0;i=arr[q.peekLast()]){ q.removeLast(); } q.addLast(i); } for(i=B;i=arr[q.peekLast()])q.removeLast(); q.addLast(i); } ans[idx]=arr[q.peekFirst()]; return ans; } } ================================================ FILE: Smaller on Left - GFG/README.md ================================================ # Smaller on Left ## Medium

Given an array arr[ ] of N positive integers, the task is to find the greatest element on the left of every element in the array which is strictly smaller than itself, if this element does not exist for an index print "-1".

Example 1:

Input:
N = 5
arr[] = {2, 3, 4, 5, 1}
Output: 
-1 2 3 4 -1
Explanation:
Greatest element on the left of 3 smaller 
than itself is 2, for 4 it is 3 and for 5 
it is 1. Since 2 is the first element and 
no element on its left is present, so it's 
greatest smaller element will be -1 and for 
1 no element smaller than itself is present 
on its left, so it's greatest smaller element 
is -1.

Example 2:

Input:
N = 3
arr[] = {1, 2, 3} 
Output:
-1 1 2 

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 Smallestonleft() that takes an array arr[ ] and sizeOfArray N, and return the required answer. The driver code takes care of the printing.

Expected Time Complexity: O(N*Log(N)).
Expected Auxiliary Space: O(N).

Constraints:
1 ≤ N ≤ 106
1 ≤ arr[i] ≤ 108

================================================ FILE: Smaller on Left - GFG/smaller-on-left.java ================================================ // { Driver Code Starts //Initial Template for Java //Initial Template for Java //Initial Template for Java /*package whatever //do not write package name here */ import java.io.*; import java.util.*; class Array { // Driver code public static void main (String[] args) throws IOException{ // Taking input using buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testcases = Integer.parseInt(br.readLine()); // looping through all testcases while(testcases-- > 0){ int sizeOfArray = Integer.parseInt(br.readLine()); int arr [] = new int[sizeOfArray]; String line = br.readLine(); String[] elements = line.trim().split("\\s+"); for(int i = 0;i set = new TreeSet<>(); int ans[] = new int[n]; for(int i=0; i sumOf(Arr,0,N-i-2)){ return count; } count++; } return 0; } long sumOf(int[] Arr ,int beg, int end){ long sum=0; for(int i=beg;i<=end;i++){ sum+=Arr[i]; } return sum; } } ================================================ FILE: Smallest Subset With Greater Sum.java ================================================ class Solution { int minSubset(int[] arr,int n) { Arrays.sort(arr); long sum=0; for(int i=0;i &Arr,int N){ sort(Arr.begin(),Arr.end()); int count=0; long long sum=0; for(int i=0;i=0){ sum-=Arr[j]; rev+=Arr[j]; if(rev>sum) return N-j; else{ j--; } } return N; } ================================================ FILE: Smallest Subset with Greater Sum gfg s15.cpp ================================================ #include using namespace std; class Solution{ public: int minSubset(vector &Arr,int N){ sort(Arr.begin(), Arr.end()); long long sum =0; for(int i =0; i=1; i--){ s+=Arr[i]; sum-=Arr[i]; if(s >sum) return N-i; } return 1; } }; int main(){ int t; cin>>t; while(t--){ int N; cin>>N; vector Arr(N); for(int i=0;i>Arr[i]; } Solution ob; cout< &Arr,int N){ sort(Arr.begin(),Arr.end()); long long int sum=0; for(int i=0;i=1;j--) { x+=Arr[j]; if(x>sum-x) break; count++; } return count; } ================================================ FILE: Smallest Subset with Greater Sum.java ================================================ class Solution { int minSubset(int[] Arr,int N) { if(N == 1) return 1; Arrays.sort(Arr); int start = 0; int end = N-1; int count = 1; int sum = Arr[end]; while(start < end) { if(Arr[start] < sum) { sum -= Arr[start++]; } else { sum += Arr[--end]; count++; } } return count; } } ================================================ FILE: Smallest Subset with Max Sum.py ================================================ class Solution: def minSubset(self, A,N): A.sort() totalSum = sum(A) currSum = 0 for i in range(N-1, -1, -1): currSum += A[i] totalSum -= A[i] if totalSum=0;i--){ if(digits[i]!=0){ while(digits[i]!=0){ sb.append((char)(i+48)); digits[i]--; } } } return -Long.parseLong(sb.toString()); } } } ================================================ FILE: Smallest distinct window - GFG/README.md ================================================ # Smallest distinct window ## Medium

Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.

 

Example 1:

Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
 
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"

 


Your Task:  
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string  S as input and returns the length of the smallest such window of the string.


Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)

 

Constraints:
1 ≤ |S| ≤ 105
String may contain both type of English Alphabets.

================================================ FILE: Smallest factorial number - GFG/README.md ================================================ # Smallest factorial number ## Easy

Given a number n. The task is to find the smallest number whose factorial contains at least n trailing zeroes.

Example 1:

Input:
n = 1
Output: 5
Explanation : 5! = 120 which has at
least 1 trailing 0.

Example 2:

Input:
n = 6
Output: 25
Explanation : 25! has at least
6 trailing 0.


User Task:
Complete the function findNum() which takes an integer N as input parameters, and returns the answer.

Expected Time Complexity: O(log2 N * log5 N).
Expected Auxiliary Space: O(1).

Constraints:
1 <= n <= 104

================================================ FILE: Smallest factorial number - GFG/smallest-factorial-number.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; public class GFG { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); System.out.println(new Solution().findNum(n)); } } }// } Driver Code Ends //User function Template for Java class Solution { int findNum(int n) { int ans = 0; int low = 5; int high = 5*n; while(low <= high){ int mid = low + (high-low)/2; int count = 0; for(int i=5; mid/i >= 1; i *= 5){ count += mid/i; } if(count >= n){ ans = mid; high = mid-1; }else{ low = mid+1; } } return ans; } } ================================================ FILE: Smallest greater elements in whole array - GFG/README.md ================================================ # Smallest greater elements in whole array ## Easy

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

 

================================================ FILE: Smallest greater elements in whole array - GFG/smallest-greater-elements-in-whole-array.java ================================================ // { Driver Code Starts //Initial Template for Java //Initial Template for Java //Initial Template for Java /*package whatever //do not write package name here */ import java.io.*; import java.util.*; class Array { // Driver code public static void main (String[] args) throws IOException{ // Taking input using buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testcases = Integer.parseInt(br.readLine()); // looping through all testcases while(testcases-- > 0){ int sizeOfArray = Integer.parseInt(br.readLine()); int arr [] = new int[sizeOfArray]; String line = br.readLine(); String[] elements = line.trim().split("\\s+"); for(int i = 0;i set = new HashSet<>(); for(int i=0;i using namespace std; // } Driver Code Ends // User function Template for C++ class Solution{ public: vector leftSmaller(int n, int a[]){ // code here stacks; vectorv; s.push(-1); for(int i =0; i>t; while(t--){ int n; cin>>n; int a[n]; for(int i = 0;i < n;i++) cin>>a[i]; Solution ob; vector ans = ob.leftSmaller(n, a); for(int i = 0;i < n;i++) cout< using namespace std; // } Driver Code Ends // User function Template for C++ class Solution{ public: vector leftSmaller(int n, int a[]){ // code here stacks; vectorans; //to store the answer for(int i=0;i=a[i]){ //Remove elements from stack which are greater than current element while(!s.empty() && s.top()>=a[i]) s.pop(); // poping till we find smaller element if(s.empty()) ans.push_back(-1); else ans.push_back(s.top()); } s.push(a[i]); //push the element } return ans; } }; //{ Driver Code Starts. int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i = 0;i < n;i++) cin>>a[i]; Solution ob; vector ans = ob.leftSmaller(n, a); for(int i = 0;i < n;i++) cout< leftSmaller(int n, int a[]) { //code here List ans=new ArrayList<>(); ans.add(-1); Stack s=new Stack<>(); s.push(a[0]); for(int i=1;i=a[i]){ s.pop(); } if(s.isEmpty()){ ans.add(-1); }else{ ans.add(s.peek()); } s.push(a[i]); } return ans; } } class Solution{ static List leftSmaller(int n, int a[]) { List res=new ArrayList<>(); Stack st=new Stack<>(); for(int i=0;i=a[i]) { st.pop(); } if(st.isEmpty()) { res.add(-1); } else { res.add(st.peek()); } } st.push(a[i]); } return res; } } ================================================ FILE: Smallest number with sum of digits as N and divisible by 10^N.cpp ================================================ class Solution{ public: string digitsNum(int N) { // Code here. string ans = ""; int n = N; while(n >= 9) { n -= 9; ans.push_back('9'); } if(n) ans.push_back('0'+n); reverse(ans.begin(), ans.end()); for(int i=0; i9){ sb.insert(0,9); N-=9; }else{ sb.insert(0,N); N-=N; } } return sb.toString(); } } ================================================ FILE: Smallest number with sum of digits as N and divisible by 10^N.py ================================================ class Solution: def digitsNum(self, N): # Code here ans = "" if N == 0: ans += "0" return ans if (N%9 != 0): ans += chr(N%9 + ord("0")) for i in range(1, (N//9) + 1): ans += "9" for i in range(1, N+1): ans += "0" return ans ================================================ FILE: Smallest number with sum of digits as N and divisible by 10powerN.cpp ================================================ #include using namespace std; // } Driver Code Ends class Solution{ public: string digitsNum(int N) { // Code here. int n = N; string ans =""; int i=9; while(i>=1){ if(n>=i){ ans = to_string(i)+ans; n -= i; }else{ i--; } if(n==0){ break; } } for(int i=1;i<=N;i++){ ans += '0'; } return ans; } }; //{ Driver Code Starts. int main(){ int tc; cin >> tc; while(tc--){ int n; cin >> n; Solution ob; string ans = ob.digitsNum(n); cout << ans <<"\n"; } return 0; } ================================================ FILE: Smallest sum contiguous subarray.cpp ================================================ class Solution{ public: int smallestSumSubarray(vector& a){ //Code here int n = a.size(); int sum = a[0], ans = a[0]; for(int i=1; i 0) { if(sum > a[i]) sum = a[i]; } else sum += a[i]; ans = min(ans, sum); } return ans; } }; // Another Approach - 2 class Solution{ public: int smallestSumSubarray(vector& a){ int ans = INT_MAX,sum=0; for(int i=0;i0)curSum=0; } return ans; } } //Approach 2 class Solution { static int smallestSumSubarray(int a[], int size) { int ans=Integer.MAX_VALUE; int i=0, j=0, sum=0; while(j0) { //In the question , they asked smallest sum contiguous sub array, hence we reduce the sum if sum>0 using sliding window sum-=a[i]; i+=1; } j+=1; } return ans; } } ================================================ FILE: Smallest sum contiguous subarray.py ================================================ def smallestSumSubarray(A): currSum, minSum = 0, float('inf') for i in A: currSum += i minSum = min(currSum, minSum) if currSum>0: currSum = 0 return minSum ================================================ FILE: Smallest window containing 0, 1 and 2.java ================================================ class Solution { public int smallestSubstring(String S) { // Code here int i=0,j=0,n=S.length(); int count0=0,count1=0,count2=0,size=Integer.MAX_VALUE; while(j=1 && count1>=1 && count2>=1){ while(count0>=1 && count1>=1 && count2>=1){ if(S.charAt(i)=='0'){ i++; count0--; } else if(S.charAt(i)=='1'){ i++; count1--; } else if(S.charAt(i)=='2') { i++; count2--; } } size=Math.min(size,j-i+2); } j++; } if(size==Integer.MAX_VALUE) return -1; return size; } }; ================================================ FILE: SmallestNumberWithSumOfDigitsAsNAndDivisbileBy10ToThePowerN.java ================================================ /* * Find the smallest number such that the sum of its digits is N and it is divisible by 10N. Example 1: Input: N = 5 Outptut: 500000 Explanation: Sum of digits of 500000 is 5 and divisible by 105. Example 2: Input: N = 20 Output: 29900000000000000000000 Explanation: Sum of digits of 29900000000000000000000 is 20 and divisible by 1020. Your Task: You don't need to read or print anything. Your task is to complete the function digitsNum() which takes the input parameter N and returns the smallest number such that sum of its digits is N and divisible by 10N. Expected Time Complexity: O(N) Expected Space Complexity: O(N) Constraints: 1 <= N <= 10000 * */ public class SmallestNumberWithSumOfDigitsAsNAndDivisbileBy10ToThePowerN { public static void main(String[] args) { SmallestNumberWithSumOfDigitsAsNAndDivisbileBy10ToThePowerN obj = new SmallestNumberWithSumOfDigitsAsNAndDivisbileBy10ToThePowerN(); System.out.println(obj.digitsNum(5)); System.out.println(obj.digitsNum(20)); } public String digitsNum(int N) { // Code here StringBuilder sb = new StringBuilder(); for(int i = 0; i < N; i++) { sb.append("0"); } while(N > 9) { N = N-9; sb.append("9"); } sb.append(N); sb.reverse(); return sb.toString(); } } ================================================ FILE: Solve-the-Sudoku - GFG/Solve-the-Sudoku.java ================================================ import java.util.*; import java.io.*; import java.lang.*; class Driver_class { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { int grid[][] = new int[9][9]; for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) grid[i][j] = sc.nextInt(); } Solution ob = new Solution(); if(ob.SolveSudoku(grid) == true) ob.printGrid(grid); else System.out.print("NO solution exists"); System.out.println(); } } } class Solution { static boolean isValid(int grid[][],int i, int j, int k){ for(int row = 0;row<9;row++){ if(grid[row][j]==k) return false; } for(int col = 0;col<9;col++){ if(grid[i][col]==k) return false; } int col = (j/3)*3; int row = (i/3)*3; for(int l = 0;l<3;l++){ for(int m = 0;m<3;m++){ if(grid[row+l][col+m]==k) return false; } } return true; } static boolean solve(int grid[][],int i,int j){ int ni = 0,nj = 0; if(i==9){ return true; } if(j==8){ ni=i+1; nj=0; }else{ ni = i; nj = j+1; } if(grid[i][j]!=0) return solve(grid,ni,nj); for(int k = 1;k<=9;k++){ if(isValid(grid,i,j,k)){ grid[i][j] = k; if(solve(grid,ni,nj)){ return true; } grid[i][j] = 0; } } return false; } static boolean SolveSudoku(int grid[][]){return solve(grid,0,0);} static void printGrid (int grid[][]) { for(int i = 0;i<9;i++){ for(int j = 0;j<9;j++){ System.out.print(grid[i][j]+" ");} } } } ================================================ FILE: Sort Binary Linked List.java ================================================ public class Solution { public ListNode solve(ListNode A) { ListNode head = A; ListNode curr = A; ListNode prev = null; ListNode next = null; while (curr != null){ next = curr.next; if(curr.val == 0){ if(prev != null){ prev.next = next; curr.next = head; head = curr; }else { prev = curr; } }else { prev = curr; } curr = next; } return head; } } ================================================ FILE: Sort Even and Odd Indices Independently.java ================================================ class Solution { public int[] sortEvenOdd(int[] nums) { List even=new ArrayList<>();; List odd=new ArrayList<>();; for(int i=0;i() { @Override public int compare(Integer o1, Integer o2) { return countSetBits(o2)-countSetBits(o1); } }); } static int countSetBits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } ========================================================================== class Compute { static void sortBySetBitCount(Integer arr[], int n) { // Your code goes here Arrays.sort(arr,(o1,o2)-> Integer.bitCount(o2)-Integer.bitCount(o1)); } } ================================================ FILE: Sorted Array To Balanced BST.java ================================================ public class Solution { // DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY public TreeNode sortedArrayToBST(final int[] A) { return makeTree(A,0,A.length-1); } public TreeNode makeTree(int[]a,int start,int end){ if(start>end)return null; int mid=start+(end-start)/2; TreeNode root=new TreeNode(a[mid]); if(start==end)return root; else{ root.left=makeTree(a,start,mid-1); root.right=makeTree(a,mid+1,end); } return root; } } ================================================ FILE: Sorted Insert Position.java ================================================ public class Solution { public int searchInsert(ArrayList a, int b) { int i=0; int j=a.size(); while(i

Given a Singly Linked List which has data members sorted in ascending order. Construct a Balanced Binary Search Tree which has same data members as the given Linked List.
Note: There might be nodes with same value.

Example 1:

Input:
Linked List: 1->2->3->4->5->6->7
Output:
4 2 1 3 6 5 7
Explanation :
The BST formed using elements of the 
linked list is,
        4
      /   \
     2     6
   /  \   / \
  1   3  5   7  
Hence, preorder traversal of this 
tree is 4 2 1 3 6 5 7

Example 2:

Input:
Linked List : 1->2->3->4
Ouput:
3 2 1 4
Exaplanation:
The BST formed using elements of the 
linked list is,
      3   
    /  \  
   2    4 
 / 
1
Hence, the preorder traversal of this 
tree is 3 2 1 4
Your task :
You don't have to read input or print anything. Your task is to complete the function sortedListToBST(), which takes head of the linked list as an input parameter and returns the root of the BST created.
 
Expected Time Complexity: O(N), N = number of Nodes
Expected Auxiliary Space: O(N), N = number of Nodes
 
Constraints:
1 ≤ Number of Nodes ≤ 106
1 ≤ Value of each node ≤ 106

================================================ FILE: Special Matrix.java ================================================ class Solution{ int mod=1000000007; public int FindWays(int n, int m, int[][] bl){ int[][]arr=new int[n+1][m+1]; for(int i=0;i q){ int n = mat.length; int m = mat[0].length; if(i<0 || i>=n || j<0 || j>=m || visited[i][j] || mat[i][j]=='W') return; visited[i][j] = true; q.offer(new int[]{i,j}); } public static int bfs(char mat[][], int i, int j){ int n = mat.length; int m = mat[0].length; boolean visited[][] = new boolean[n][m]; visited[i][j] = true; Queue q = new LinkedList<>(); q.offer(new int[]{i,j}); int min = 0; while(!q.isEmpty()){ int len = q.size(); min++; for(int k=0;k=left;i--) res[bottom][i]=A[k++]; bottom--; direction=4; } else if(direction == 4){ for(int i=bottom;i>=top;i--) res[i][left]=A[k++]; left++; direction = 1; } } return res; } } ================================================ FILE: Spiral Order Matrix II.java ================================================ public class Solution { public int[][] generateMatrix(int n) { int[][] arr=new int[n][n]; for(int i=0;irowBottom || colBack=colFront;i--){ arr[rowBottom][i]=arr[rowBottom][i+1]+1; } dir='U'; rowBottom--; }else if(dir=='U'){ for(int i=rowBottom;i>=rowTop;i--){ arr[i][colFront]=arr[i+1][colFront]+1; } dir='R'; colFront++; }else if(dir=='R'){ for(int i=colFront;i<=colBack;i++){ arr[rowTop][i]=arr[rowTop][i-1]+1; } dir='D'; rowTop++; } } return arr; } } ================================================ FILE: Split_Array_Into_Consecutive_subsequence.java ================================================ class Solution { public boolean isPossible(int[] nums) { HashMap available = new HashMap<>(); for(int i:nums) available.put(i,available.getOrDefault(i,0)+1); HashMap vacancyFor = new HashMap<>(); for(int i:nums) { int freq = available.get(i); if(freq > 0) { if(vacancyFor.containsKey(i) && vacancyFor.get(i)>0) { vacancyFor.put(i,vacancyFor.getOrDefault(i,0)-1); vacancyFor.put(i+1,vacancyFor.getOrDefault(i+1,0)+1); available.put(i,available.getOrDefault(i,0)-1); } else { if(available.containsKey(i+1) && available.containsKey(i+2) && available.get(i+1)>0 && available.get(i+2)>0) { vacancyFor.put(i+3,vacancyFor.getOrDefault(i+3,0)+1); available.put(i,available.getOrDefault(i,0)-1); available.put(i+1,available.getOrDefault(i+1,0)-1); available.put(i+2,available.getOrDefault(i+2,0)-1); } else return false; } } } return true; } } ================================================ FILE: Square Root of Integer.java ================================================ public class Solution { public int sqrt(int A) { if (A == 0 || A == 1) return A; if (A == 2 || A == 3) return 1; int i=1; int j=A/2; int expect=0; while(i<=j){ int m=i+(j-i)/2; if(m<=A/m){ i=m+1; expect=m; }else{ j=m-1; } } return expect; } } ================================================ FILE: Stack Permutation med gfg sep7.cpp ================================================ #include using namespace std; class Solution{ public: int isStackPermutation(int N,vector &A,vector &B){ // creating stack and a variable to traverse through 'B' variable stackst; int j=0; for(int i =0; i>t; while(t--){ int n; cin>>n; vector a(n),b(n); for(int i=0;i>a[i]; } for(int i=0;i>b[i]; } Solution ob; cout< s= new Stack<>(); int j=0,i=0; for(int k=0;k=n){ return 0; } else{ s.push(ip[i]); i++; } } if(Arrays.equals(ans,op)){ return 1; } return 0; } } ================================================ FILE: Stack Permutations.java ================================================ class Solution { public static int isStackPermutation(int n, int[] ip, int[] op) { // code here Stack s=new Stack<>(); int i=0; int j=0; while(j=len(B): break arr.pop() j+=1 else: if i>=len(A): break arr.append(A[i]) i+=1 return 1 if len(arr) == 0 else 0 ================================================ FILE: Step by Step.java ================================================ public class Solution { public int solve(int A) { A=Math.abs(A); int i=0; int sum=0; while(sum

A number is called a stepping number if all adjacent digits have an absolute difference of 1, e.g. '321' is a Stepping Number while 421 is not. Given two integersand m, find the count of all the stepping numbers in the range [n, m].

Example 1:

Input: n = 0, m = 21
Output: 13
Explanation: Stepping no's are 0 1 2 3 4 5
6 7 8 9 10 12 21

Example 2:

Input: n = 10, m = 15
Output: 2
Explanation: Stepping no's are 10, 12


Your Task:  
You don't need to read input or print anything. Your task is to complete the function steppingNumbers() which takes the integer n and integer m as input parameters and returns the number of stepping numbers in the range between n and m.

Expected Time Complexity: O(log(M))
Expected Auxiliary Space: O(SN) where SN is the number of stepping numbers in the range


Constraints:
0 ≤ N < M ≤ 10
7

================================================ FILE: Stepping Numbers - GFG/stepping-numbers.java ================================================ //{ Driver Code Starts //Initial Template for Java //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[])throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { String input_line[] = read.readLine().trim().split("\\s+"); int N = Integer.parseInt(input_line[0]); int M = Integer.parseInt(input_line[1]); Solution ob = new Solution(); int ans = ob.steppingNumbers(N, M); System.out.println(ans); } } } // } Driver Code Ends //User function Template for Java class Solution{ int steppingNumbers(int n, int m){ // code here int ans=0; if(n==0)ans++; Queue q=new LinkedList<>(); for(int i=1;i<=9;i++){ q.add(i); } while(q.size()>0){ int sz=q.size(); while(sz-->0){ int ele=q.remove(); if(ele>=n && ele<=m)ans++; int lastDigit=ele%10; if(lastDigit==9){ int next=ele*10+8; if(next<=m)q.add(next); }else if(lastDigit==0){ int next=ele*10+1; if(next<=m)q.add(next); }else{ int smaller=ele*10+(lastDigit-1); if(smaller<=m)q.add(smaller); int greater=ele*10+(lastDigit+1); if(greater<=m)q.add(greater); } } } return ans; } } ================================================ FILE: Steps by Knight ================================================ class Solution { public int minStepToReachTarget(int KnightPos[], int TargetPos[], int N) { boolean [][]vis = new boolean[N+1][N+1]; Queue q = new ArrayDeque<>(); q.add(KnightPos); vis[KnightPos[0]][KnightPos[1]] =true; int step =0; int [][]dir ={{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}}; while(q.size() > 0){ int sz = q.size(); while(sz-- >0 ){ int []pos = q.poll(); if( pos[0] == TargetPos[0] && pos[1] == TargetPos[1] ){ return step; } for(int i=0 ; i < 8 ;i++){ int r = pos[0] + dir[i][0]; int c = pos[1] + dir[i][1]; if( r > 0 && r <= N && c > 0 && c <= N && !vis[r][c] ){ vis[r][c] =true; q.offer( new int[]{r ,c } ); } } } step++; } return -1; } } ================================================ FILE: Stock buy and sell - GFG/Stock buy and sell.cpp ================================================ // N = 7 // A[] = { 100, 180, 260, 310, 40, 535, 695 } // This function finds the buy sell schedule for maximum profit void stockBuySell(int price[], int n) { // code here vector> v; // int profit = 0; for(int i=1;i= price[i-1]){ int j = i; while(j < n and price[j] >= price[j-1]){ j++; } // profit = max(profit, (price[j-1] - price[i-1])); v.push_back({i-1, j-1}); i = j; }else i++; } // cout<0){ sb.append(ch); sb.append(freq[ch-'a']); freq[ch-'a']=0; } } return sb.toString(); } } ================================================ FILE: String formation from substring - GFG/README.md ================================================ # String formation from substring ## Medium

Given a string s, the task is to check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. 

Example 1:

Input: s = "ababab"
Output: 1
Explanation: It is contructed by 
appending "ab" 3 times

Example 2:

Input: s = "ababac"
Output: 0
Explanation: Not possible to construct

User Task:
Your task is to complete the function isRepeat() which takes a single string as input and returns 1 if possible to construct, otherwise 0. You do not need to take any input or print anything.

Expected Time Complexity: O(|s|)
Expected Auxiliary Space: O(|s|)

Constraints:
1 <= |s| <= 105

================================================ FILE: String formation from substring - GFG/string-formation-from-substring.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { String input = read.readLine(); Solution ob = new Solution(); int result = ob.isRepeat(input); System.out.println(result); } } }// } Driver Code Ends //User function Template for Java class Solution { int isRepeat(String s) { if(s.length()==1)return 0; if(s.length()==2){ if(s.charAt(0)==s.charAt(1)) return 1; return 0; } String t = s+s; String ns = t.substring(2,t.length()-1); if(ns.indexOf(s)!=-1)return 1; return 0; } } ================================================ FILE: String to Integer (atoi).java ================================================ class Solution { public int myAtoi(String s) { int sign=1,flagSign=0,n=s.length(); long ans=0; for(int i=0;i='0'&&s.charAt(i)<='9') { ans=ans*10+(s.charAt(i)-'0'); if(ans*sign>=Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else if(ans*sign<=Integer.MIN_VALUE) { return Integer.MIN_VALUE; } flagSign=1; } else break; } ans=ans*sign; return (int)ans; } } ================================================ FILE: Subarray Sum Equals K.java ================================================ public class Solution { public int subarraySum(int[] nums, int k) { int count = 0, sum = 0; Map < Integer, Integer > map = new HashMap<>(); map.put(0, 1); for (int i = 0; i < nums.length; i++) { sum += nums[i]; if (map.containsKey(sum - k)){ count += map.get(sum - k); } map.put(sum, map.getOrDefault(sum, 0) + 1); } return count; } } ================================================ FILE: Subarray with equal occurences!.java ================================================ public class Solution { public int solve(int[] A, int B, int C) { int ans=0; for(int i=0;i using namespace std; // } Driver Code Ends class Solution { public: vector subarraySum(int arr[], int n, long long s) { vector ans; if(s==0) { ans.push_back(-1); return ans; } int start=0; int end=0; long long sum=0; while(ends) { sum=sum-arr[start]; start++; if(sum==s) { ans.push_back(start+1); ans.push_back(end); return ans; } } while(ends) { sum=sum-arr[start]; start++; if(sum==s) { ans.push_back(start+1); ans.push_back(end); return ans; } } ans.push_back(-1); return ans; } }; //{ Driver Code Starts. int main() { int t; cin>>t; while(t--) { int n; long long s; cin>>n>>s; int arr[n]; const int mx = 1e9; for(int i=0;i>arr[i]; } Solution ob; vectorres; res = ob.subarraySum(arr, n, s); for(int i = 0;i> res; ArrayList A; int N; public ArrayList> subsets(ArrayList A) { ArrayList temp; res = new ArrayList<>(); temp = new ArrayList<>(); this.A = A; N = A.size(); Collections.sort(A); subset(0, temp); Collections.sort(res, new Comparator>() { @Override public int compare(ArrayList a, ArrayList b) { int an = a.size(); int bn = b.size(); for (int i = 0; i < Math.min(an, bn); i++) { int cmp = Integer.compare(a.get(i), b.get(i)); if (cmp != 0) return cmp; } return Integer.compare(a.size(), b.size()); } }); return res; } private void subset(int index, ArrayList arr) { if (index == N) { res.add(new ArrayList<>(arr)); return; } subset(index + 1, arr); arr.add(A.get(index)); subset(index + 1, arr); arr.remove(arr.size() - 1); } } ================================================ FILE: Subsets II.java ================================================ public class Solution { ArrayList> ans; public ArrayList> subsetsWithDup(ArrayList A) { ans=new ArrayList<>(); ans.add(new ArrayList<>()); Collections.sort(A); dfs(0,A,new ArrayList<>()); return ans; } public void dfs(int idx,ArrayList a,ArrayList curr){ if(idx==a.size())return; for(int i=idx;i(curr)); dfs(i+1,a,curr); curr.remove(curr.size()-1); } } } ================================================ FILE: Subsets with XOR value - GFG/README.md ================================================ # Subsets with XOR value ## Medium

Given an array arr of N integers and an integer K, find the number of subsets of arr having XOR of elements as K.
 

Example 1:

Input:
N = 4
k = 6
arr: 6 9 4 2
Output:
2
Explanation:
The subsets are 
{4,2} and {6}

Example 2:

Input:
N = 5
K = 4
arr: 1 2 3 4 5
Output:
4
Explanation:
The subsets are {1, 5},
{4}, {1, 2, 3, 4},
and {2, 3, 5}


Your Task:
You don't need to read input or print anything. Your task is to complete the function subsetXOR​() which takes the array arr[], its size N and an integer K as input parameters and returns the number of subsets having xor as K

 

Expected Time Complexity: O(N*M)
Expected Space Complexity: O(N*M)
Note: M = maximum value any XOR subset will acquire

 

Constraints:
1<=N<=20
1<=K<=100
0<=arr[i]<=100

================================================ FILE: Subsets with XOR value - GFG/subsets-with-xor-value.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; // } Driver Code Ends //User function Template for Java class Solution{ static int subsetXOR(int arr[], int N, int K) { int max_ele = arr[0]; for (int i=1; i max_ele) max_ele = arr[i]; int m = 10*max_ele; int[][] dp = new int[N+1][m+1]; dp[0][0] = 1; for(int i=1;i<=N;i++){ for(int j=0;j<=m;j++){ dp[i][j] += dp[i-1][j]; if((j^arr[i-1])<=m){ dp[i][j] += dp[i-1][j^arr[i-1]]; } } } return dp[N][K]; } } // { Driver Code Starts. class GFG { public static void main(String args[])throws IOException { Scanner s = new Scanner(System.in); int t = s.nextInt(); while(t-- > 0) { int N = s.nextInt(); int K = s.nextInt(); int arr[] = new int[N]; for(int i =0;i> subsets(int[] nums) { List> list = new ArrayList<>(); backtrack(list, new ArrayList<>(), nums, 0); return list; } private void backtrack(List> list , List tempList, int [] nums, int start){ list.add(new ArrayList<>(tempList)); for(int i = start; i < nums.length; i++){ tempList.add(nums[i]); backtrack(list, tempList, nums, i + 1); tempList.remove(tempList.size() - 1); } } } ================================================ FILE: Sum Of k smallest elements in BST.java ================================================ class Tree { public static void fun(Node root,ArrayListaa){ if(root==null){ return ; } else{ fun(root.left,aa); aa.add(root.data); fun(root.right,aa); } } int sum(Node root, int k) { ArrayListaa=new ArrayList(); fun(root,aa); int sum=0; for(int i=0;ileft,k,sum); if(k==0) return; sum+=node->data; k--; inorder(node->right,k,sum); } int sum(Node* root, int k) { // Your code here int sum=0; inorder(root,k,sum); return sum; } ================================================ FILE: Sum of Root To Leaf Binary Numbers.java ================================================ Approach 1: Iterative Time: O(H) Space: O(H) class Solution { public int sumRootToLeaf(TreeNode root) { int rootToLeaf = 0, currNumber = 0; Deque> stack = new ArrayDeque(); stack.push(new Pair(root, 0)); while (!stack.isEmpty()) { Pair p = stack.pop(); root = p.getKey(); currNumber = p.getValue(); if (root != null) { currNumber = (currNumber << 1) | root.val; // if it's a leaf, update root-to-leaf sum if (root.left == null && root.right == null) { rootToLeaf += currNumber; } else { stack.push(new Pair(root.right, currNumber)); stack.push(new Pair(root.left, currNumber)); } } } return rootToLeaf; } } --------------------------------------------------------------------------------------- Approach 2: Recursive Time: O(H) Space: O(H) class Solution { public int sumRootToLeaf(TreeNode root) { return pathSumRootToLeaf(root, 0); } private int pathSumRootToLeaf(TreeNode root, int parentNodeSum){ if(root == null) return 0; parentNodeSum = 2 * parentNodeSum + root.val; if(root.left == null && root.right == null){ return parentNodeSum; } return pathSumRootToLeaf(root.left, parentNodeSum) + pathSumRootToLeaf(root.right, parentNodeSum); } } --------------------------------------------------------------------------------------- Approach 3: Morris approach(using predessesors) Time: O(n) Space: O(1) class Solution { public int sumRootToLeaf(TreeNode root) { int rootToLeaf = 0, currNumber = 0; int steps; TreeNode predecessor; while (root != null) { // If there is a left child, // then compute the predecessor. // If there is no link predecessor.right = root --> set it. // If there is a link predecessor.right = root --> break it. if (root.left != null) { // Predecessor node is one step to the left // and then to the right till you can. predecessor = root.left; steps = 1; while (predecessor.right != null && predecessor.right != root) { predecessor = predecessor.right; ++steps; } // Set link predecessor.right = root // and go to explore the left subtree if (predecessor.right == null) { currNumber = (currNumber << 1) | root.val; predecessor.right = root; root = root.left; } // Break the link predecessor.right = root // Once the link is broken, // it's time to change subtree and go to the right else { // If you're on the leaf, update the sum if (predecessor.left == null) { rootToLeaf += currNumber; } // This part of tree is explored, backtrack for(int i = 0; i < steps; ++i) { currNumber >>= 1; } predecessor.right = null; root = root.right; } } // If there is no left child // then just go right. else { currNumber = (currNumber << 1) | root.val; // if you're on the leaf, update the sum if (root.right == null) { rootToLeaf += currNumber; } root = root.right; } } return rootToLeaf; } } ================================================ FILE: Sum of elements between k1'th and k2'th smallest elements - GFG/README.md ================================================ # Sum of elements between k1'th and k2'th smallest elements ## Easy

Given an array A[] of N positive integers and two positive integers K1 and K2. Find the sum of all elements between K1th and K2th smallest elements of the array. It may be assumed that (1 <= k1 < k2 <= n).

 

Example 1:

Input:
N  = 7
A[] = {20, 8, 22, 4, 12, 10, 14}
K1 = 3, K2 = 6
Output:
26
Explanation:
3rd smallest element is 10
6th smallest element is 20
Sum of all element between
K1 & K2 is 12 + 14 = 26

 

Example 2:

Input
N = 6
A[] = {10, 2, 50, 12, 48, 13}
K1= 2, K2 = 6
Output:
73

 

Your Task:  
You don't need to read input or print anything. Your task is to complete the function sumBetweenTwoKth() which takes the array A[], its size N and two integers K1 and K2 as inputs and returns the sum of all the elements between K1th and K2th smallest elements.

 

Expected Time Complexity: O(N. log(N))
Expected Auxiliary Space: O(N)

 

Constraints:
1 ≤ N ≤ 105
1 ≤ K1, K2 ≤ 109

================================================ FILE: Sum of elements between k1'th and k2'th smallest elements - GFG/sum-of-elements-between-k1th-and-k2th-smallest-elements.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); while(t-->0) { long n = Long.parseLong(br.readLine().trim()); long a[] = new long[(int)n]; String inputLine[] = br.readLine().trim().split(" "); for (int i = 0; i < n; i++) { a[i] = Long.parseLong(inputLine[i]); } StringTokenizer stt = new StringTokenizer(br.readLine()); long k1 = Long.parseLong(stt.nextToken()); long k2 = Long.parseLong(stt.nextToken()); Solution obj = new Solution(); System.out.println( obj.sumBetweenTwoKth(a, n, k1, k2) ); } } }// } Driver Code Ends //User function Template for Java class Solution { public static long sumBetweenTwoKth(long A[], long N, long K1, long K2) { // Your code goes here Arrays.sort(A); long ans = 0; for(long i=K1;i S; while((!S.empty() or cur) and k--) { while(cur) { S.push(cur); cur = cur->left; } cur = S.top(); S.pop(); ans += cur->data; cur = cur->right; } return ans; } ================================================ FILE: Sum of k smallest elements in BST.java ================================================ class Tree { int sum; int cnt; int sum(Node root, int k) { sum=0; cnt=0; dfs(root,k); return sum; // Code here } void dfs(Node root,int k){ if(root==null)return; dfs(root.left,k); if(cnt

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 is at the geek summer carnival. To unlock discounts on exclusive courses he is given a card with a binary tree, a target node and a positive integer k on it. 
He needs to find the sum of all nodes within a max distance k from target node such that the target node is included in sum.

Example 1:

Input:
target = 9 
k = 1
Binary Tree = 
            1
           /  \
          2    9
        /     /  \
       4     5    7
      /  \       /  \
     8    19    20   11
    /   /   \
  30   40   50

Output: 22

Explanation: 
Nodes within distance 1 from 9 
9 + 5 + 7 + 1 = 22


Example 2:

Input:
target = 40 
k = 2
Binary Tree = 
            1
           /  \
          2    9
        /     /  \
       4     5    7
      /  \       /  \
     8    19    20   11
    /   /   \
  30   40   50

Output: 113

Explanation:
Nodes within distance 2 from 40,
40 + 19 + 50 + 4 = 113

Your Task:
You don't need to read input or print anything. Complete the function sum_at_distK() that takes the root of the given binary tree, target and k as input parameters and return the required sum. 

Expected time complexity: O(n)
Expected space complexity: O(n)


Constraints:
1 <= number of nodes <= 1000
1 <= data in nodes,target <= 10000
1 <= k <= 20

================================================ FILE: Sum of nodes within k distance from target - GFG/sum-of-nodes-within-k-distance-from-target.java ================================================ // { Driver Code Starts import java.util.LinkedList; import java.util.Queue; import java.io.*; import java.util.*; class Node{ int data; Node left; Node right; Node(int data){ this.data = data; left=null; right=null; } } class GfG { static Node buildTree(String str){ if(str.length()==0 || str.charAt(0)=='N'){ return null; } String ip[] = str.split(" "); // Create the root of the tree Node root = new Node(Integer.parseInt(ip[0])); // Push the root to the queue Queue queue = new LinkedList<>(); queue.add(root); // Starting from the second element int i = 1; while(queue.size()>0 && i < ip.length) { // Get and remove the front of the queue Node currNode = queue.peek(); queue.remove(); // Get the current node's value from the string String currVal = ip[i]; // If the left child is not null if(!currVal.equals("N")) { // Create the left child for the current node currNode.left = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.left); } // For the right child i++; if(i >= ip.length) break; currVal = ip[i]; // If the right child is not null if(!currVal.equals("N")) { // Create the right child for the current node currNode.right = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.right); } i++; } return root; } public static void main (String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t > 0){ String line = br.readLine().trim(); Node root = buildTree(line); line = br.readLine().trim(); String target_k[] = line.split(" "); int target = Integer.parseInt(target_k[0]); int k = Integer.parseInt(target_k[1]); solver x = new solver(); System.out.println( x.sum_at_distK(root, target, k) ); t--; } } } // } Driver Code Ends /* // node structure: class Node{ int data; Node left; Node right; Node(int data){ this.data = data; left=null; right=null; } } */ class solver{ static Map map=new HashMap<>(); static Node tar; static int n; static int sum_at_distK(Node root, int target, int k){ n=target; Node copy=root; addAll(copy); Set set=new HashSet<>(); bfs(tar,set,0,k); int sum=0; for(int i:set){ sum+=i; } return sum; } static void bfs(Node curr,Setset,int dis,int k){ if(curr==null)return; if(dis>k)return; if(set.contains(curr.data))return; set.add(curr.data); bfs(curr.left,set,dis+1,k); bfs(curr.right,set,dis+1,k); bfs(map.get(curr),set,dis+1,k); } static void addAll(Node root){ if(root==null)return; if(root.data==n)tar=root; if(root.left!=null){ map.put(root.left,root); addAll(root.left); } if(root.right!=null){ map.put(root.right,root); addAll(root.right); } } } ================================================ FILE: Sum of two large numbers.cpp ================================================ class Solution { public: string findSum(string X, string Y) { // Your code goes here string ans = ""; int n = X.length()-1, m = Y.length()-1, rem = 0; while(n >= 0 and m >= 0) { int cur = (X[n--]-'0') + (Y[m--]-'0') + rem; rem = cur/10; cur = cur%10; ans.push_back('0'+cur); } while(n >= 0) { int cur = (X[n--]-'0') + rem; rem = cur/10; cur = cur%10; ans.push_back('0'+cur); } while(m >= 0) { int cur = (Y[m--]-'0') + rem; rem = cur/10; cur = cur%10; ans.push_back('0'+cur); } if(rem) ans.push_back('0'+rem); while(ans.back() == '0') ans.pop_back(); if(ans.empty()) return "0"; reverse(ans.begin(), ans.end()); return ans; } }; // Used almost same approach // class Solution { // public: // string findSum(string X, string Y) { // int i = X.length()-1, j = Y.length()-1; // string ans = ""; // int c = 0; // while(i >= 0 || j >= 0 || c != 0){ // int val1 = 0, val2 = 0; // if(i >= 0) val1 = X[i] - 48; // if(j >= 0) val2 = Y[j] - 48; // int sum = val1+val2+c; // int rem = sum % 10; // ans.push_back(char(rem+48)); // c = sum / 10; // if(i>=0) i--; // if(j>=0) j--; // } // reverse(ans.begin(), ans.end()); // int idx = 0; // while(idx < ans.size()-1){ // if(ans[idx] != '0') // break; // idx++; // } // ans.erase(0,idx); // return ans; // } // }; ================================================ FILE: Sum of two large numbers.java ================================================ class Solution { String findSum(String X, String Y) { // code here StringBuilder a=new StringBuilder(X); StringBuilder b=new StringBuilder(Y); StringBuilder ans=new StringBuilder(); int carry=0; while(a.length()>0 || b.length()>0){ int first=a.length()>0?a.charAt(a.length()-1)-'0':0; int second=b.length()>0?b.charAt(b.length()-1)-'0':0; int sum=first+second+carry; if(sum>9){ sum-=10; carry=1; }else{ carry=0; } ans.insert(0,sum); if(a.length()>0)a.setLength(a.length()-1); if(b.length()>0)b.setLength(b.length()-1); } if(carry==1){ ans.insert(0,1); } //000000 for(int i=0;i'0'){ return ans.substring(i); } } return "0"; } } ================================================ FILE: Sum of two numbers without using arithmetic operators - GFG/README.md ================================================ # Sum of two numbers without using arithmetic operators ## Easy

Given two integers a and b. Find the sum of two numbers without using arithmetic operators.

Example 1:

Input:
a = 5, b = 3
Output: 8
Explanation :
5 + 3 = 8

Example 2:

Input:
a = 10, b = 30
Output: 40
Explanation:
10 + 30 = 40
Your task:
You don't need to read input or print anything. Your task is to complete the function sum() which takes two integers a and b as input and returns the sum of a and b, which is calculated without using any arithmetic operator.
 
Expected Time Complexity : O(max(number of bits in 'a', number of bits in 'b'))
Expected Auxiliary Space : O(1)
 
Constraints:
1<=a, b<=10^8

================================================ FILE: Sum of two numbers without using arithmetic operators - GFG/sum-of-two-numbers-without-using-arithmetic-operators.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; import java.math.BigInteger; class GFG { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t>0) { String S[] = br.readLine().split(" "); int a = Integer.parseInt(S[0]); int b = Integer.parseInt(S[1]); Solution obj = new Solution(); System.out.println(obj.sum(a,b)); t--; } } }// } Driver Code Ends //User function Template for Java class Solution{ int sum(int a , int b){ while(b!=0){ int ans=(a^b); int carry=(a&b)<<1; a=ans; b=carry; } return a; } } ================================================ FILE: Summary Ranges.java ================================================ class Solution { public List summaryRanges(int[] nums) { List res = new ArrayList<>(); StringBuilder buf = new StringBuilder(); for(int i = 0; i < nums.length; i++) { buf.setLength(0); int index = i; while(index < nums.length-1 && nums[index]+1 == nums[index+1]){ index++; } if(index == i){ buf.append(""); buf.append(nums[i]); }else{ buf.append(nums[i]); buf.append("->"); buf.append(nums[index]); } res.add(buf.toString()); i = index; } return res; } } ================================================ FILE: Super Primes - GFG/README.md ================================================ # Super Primes ## Medium

A prime number is Super Prime if it is a sum of two primes. Find all the Super Primes upto N

Example 1:

Input:
N = 5
Output: 1
Explanation: 5 = 2 + 3, 5 is the
only super prime

Example 2:

Input:
N = 10 
Output: 2
Explanation: 5 and 7 are super primes


Your Task:  
You don't need to read input or print anything. Your task is to complete the function superPrimes() which takes the N as input and returns the count of super primes.


Expected Time Complexity: O(Nlog(logN))
Expected Auxiliary Space: O(N)


Constraints:
1 ≤ N ≤ 105

================================================ FILE: Super Primes - GFG/super-primes.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[]) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { int n = Integer.parseInt(read.readLine()); Solution ob = new Solution(); System.out.println(ob.superPrimes(n)); } } }// } Driver Code Ends //User function Template for Java class Solution { int superPrimes(int n) { boolean [] primes=new boolean[n+1]; Arrays.fill(primes,true); //performing sieve for(int i=2;i<=Math.sqrt(n);i++){ if(primes[i]==true){ for(int j=i*i;j<=n;j+=i){ primes[j]=false; } } } int count=0; for(int i=5;i<=n;i++){ if(primes[i] && primes[i-2]){ count++; } } return count; } } ================================================ FILE: Swap Bits.java ================================================ public class Solution { public int solve(int n, int p, int q) { if ((((n & (1 << p-1)) >> p-1) ^ ((n & (1 << q-1)) >> q-1))!=0){ n ^= (1 << p-1); n ^= (1 << q-1); } return n ; } } ================================================ FILE: Swap Kth nodes from ends - GFG/README.md ================================================ # 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

 

================================================ FILE: Swap Kth nodes from ends - GFG/swap-kth-nodes-from-ends.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.io.*; import java.lang.*; class Node { int data; Node next; Node(int data) { this.data = data; next = null; } } class LinkedList { static Node head; static Node lastNode; public static void addToTheLast(Node node) { if (head == null) { head = node; lastNode = node; } else { Node temp = head; lastNode.next = node; lastNode = node; } } public static void main(String args[]) { Scanner sc= new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { int n, K; n = sc.nextInt(); K = sc.nextInt(); Node head = null; int val = sc.nextInt(); head = new Node(val); addToTheLast(head); for(int i = 1; i< n; i++) { val = sc.nextInt(); addToTheLast(new Node(val)); } Node before[] = new Node[n]; addressstore(before, head); GFG obj = new GFG(); head = obj.swapkthnode(head, n, K); Node after[] = new Node[n]; addressstore(after, head); if(check(before, after, n, K) == true) System.out.println("1"); else System.out.println("0"); } } static boolean check(Node before[], Node after[], int num, int K) { if(K > num) return true; return (before[K-1] == after[num - K]) && (before[num-K] == after[K-1]); } static void addressstore(Node arr[], Node head) { Node temp = head; int i = 0; while(temp != null){ arr[i] = temp; i++; temp = temp.next; } } }// } Driver Code Ends //User function Template for Java /* Linked List Node class class Node { int data; Node next; Node(int data) { this.data = data; next = null; } } */ class GFG{ //Function to swap Kth node from beginning and end in a linked list. Node swapkthnode(Node head, int num, int k){ // your code here if (head == null)return head; if (k > num)return head; // begining node will be at k // end node will be at n - k + 1 Node x = head; Node prevX = null; Node y = head; Node prevY = null; for (int i = 1; i < k; i++) { prevX = x; x = x.next; } for (int i = 1; i < num - k + 1; i++) { prevY = y; y = y.next; } if (prevX != null) { prevX.next = y; } if (prevY != null) { prevY.next = x; } Node temp = x.next; x.next = y.next; y.next = temp; if (k == 1) { head = y; } if (k == num) { head = x; } return head; } } ================================================ FILE: Swap Nodes in Pairs.java ================================================ class Solution { public ListNode swapPairs(ListNode head) { if(head==null)return null; if(head.next==null)return head; ListNode rec=swapPairs(head.next.next); ListNode sec=head.next; sec.next=head; head.next=rec; return sec; } } ================================================ FILE: Swap bits - GFG/README.md ================================================ # Swap bits ## Easy

Given a number X and two positions (from right side) in binary representation of x, write a program that swaps N bits at given two positions and returns the result.

 

Example 1:

Input:
X = 47
P1 = 1
P2 = 5
N = 3
Output: 227
Explanation:
The 3 bits starting from the second bit 
(from the right side) are swapped with 3 bits
starting from 6th position (from the right side) 
X = 47 (00101111)
[001]0[111]1
ANS = [111]0[001]1
ANS = 227 (11100011)
Hence, the result is 227.  

 

Example 2:

Input:
X = 28
P1 = 0
P2 = 3
N = 2
Output: 7


Your Task:  
You don't need to read input or print anything. Your task is to complete the function swapBits() which takes the integer X, integer P1, integer P2, and integer N as input parameters and returns the new integer after swapping. 

Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)

 


Constraints:
1 ≤ X ≤ 200
0 ≤ P1 < P2 ≤ 11
1 ≤ N ≤ 5


 

================================================ FILE: Swap bits - GFG/swap-bits.java ================================================ // { Driver Code Starts //Initial Template for Java //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[])throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while(t-- > 0) { String input_line[] = read.readLine().trim().split("\\s+"); int X = Integer.parseInt(input_line[0]); int P1 = Integer.parseInt(input_line[1]); int P2 = Integer.parseInt(input_line[2]); int N = Integer.parseInt(input_line[3]); Solution ob = new Solution(); System.out.println(ob.swapBits(X, P1, P2, N)); } } } // } Driver Code Ends //User function Template for Java class Solution{ int swapBits(int x, int p1, int p2, int n){ int mask1= (x >> p1) & ((1 << n) - 1); int mask2 = (x >> p2) & ((1 << n) - 1); int xor = ( mask1^ mask2); xor = (xor << p1) | (xor << p2); int res = x ^ xor; return res; } } ================================================ FILE: Symmetric Binary Tree.java ================================================ public class Solution { public int isSymmetric(TreeNode A) { if( isMirrorUtil(A, A)){ return 1; } return 0; } public static boolean isMirrorUtil(TreeNode root1, TreeNode root2){ if(root1 == null && root2 == null){ return true; } if(root1 != null && root2!= null && root1.val == root2.val){ return (isMirrorUtil(root1.left, root2.right) && isMirrorUtil(root1.right, root2.left)); } return false; } } ================================================ FILE: The Bit Game easy s24.cpp ================================================ #include using namespace std; class Solution{ public: int swapBitGame(long long N){ // code here int win=0, swap=0; while(N>0){ if((N&1)==1 && swap>0) win^=swap; if((N&1)==0) swap++; N>>=1; } return win>0? 1: 2; } }; int main() { int t; cin>>t; while(t--) { long long N; cin >> N; Solution ob; cout << ob.swapBitGame(N) << endl; } return 0; } ================================================ FILE: The bit Game.cpp ================================================ class Solution{ public: int swapBitGame(long long N){ int cnt=0; while(N>0){ if((N&1)==1){ cnt++; } N>>=1; } return cnt%2==0?2:1; } }; ================================================ FILE: Theft at World Bank - GFG/README.md ================================================ # Theft at World Bank ## Easy

The worlds most successful thief Albert Spaggiari was planning for his next heist on the world bank. He decides to carry a sack with him, which can carry a maximum weight of C kgs. Inside the world bank there were N large blocks of gold. All the blocks have some profit value associated with them i.e. if he steals ith block of weight w[i] then he will have p[i] profit. As blocks were heavy he decided to steal some part of them by cutting them with his cutter.
The thief does not like symmetry, hence, he wishes to not take blocks or parts of them whose weight is a perfect square. Now, you need to find out the maximum profit that he can earn given that he can only carry blocks of gold in his sack. 
Note: The answer should be precise upto 3 decimal places.

Example 1 :

N = 3, C = 10
w[] = {4, 5, 7}
p[] = {8, 5, 4)
Output: 
7.857
Explanation: As first blocks weight is 4
which is a perfect square, he will not use 
this block. Now with the remaining blocks 
the most optimal way is to use 2nd block 
completely and cut 5kg piece from the 3rd 
block to get a total profit of 5 + 2.857 
= 7.857

Your Task:
You don't need to read or print anything. Your task is to complete the function maximumProfit() which takes N, C, w[ ] and p[ ] as input parameters and returns the maximum profit thief can achieve with precision upto 3 decimal places.

Expected Time Complexity: O(N * LogN)
Expected Space Complexity : O(N)

Constraints:
1 ≤ N ≤ 103
1 ≤ C ≤ 1018
1 ≤ W≤ 109
1 ≤ P≤ 109

================================================ FILE: Theft at World Bank - GFG/theft-at-world-bank.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String s1 = br.readLine().trim(); String []S1 = s1.split(" "); int n = Integer.parseInt(S1[0]); long C = Long.parseLong(S1[1]); String s2 = br.readLine().trim(); String []S2 = s2.split(" "); long [] w = new long[n]; long [] p = new long[n]; for(int i = 0; i < n; i++){ w[i] = Long.parseLong(S2[2*i]); p[i] = Long.parseLong(S2[(2*i)+1]); } Solution ob = new Solution(); double ans = ob.maximumProfit(n, C, w, p); String a1 = String.format("%.3f",ans); System.out.println(a1); } } } // } Driver Code Ends //User function Template for Java class Pair{ long weight; long profit; double ratio; Pair(long weight, long profit, double ratio){ this.weight=weight; this.profit=profit; this.ratio=ratio; } } class Solution { public boolean isPerfect(long num){ long sq=(long)Math.sqrt(num); return sq*sq==num; } public double maximumProfit(int n, long c, long w[], long p[]) { Pair[] item=new Pair[n]; for(int i=0;iDouble.compare(b.ratio, a.ratio)); double total=0; int i=0; while(c>0){ if(!isPerfect(item[i].weight)){ long wgt=Math.min(c, item[i].weight); total+=(double)(wgt)*item[i].ratio; c-=wgt; } i++; } return total; } } ================================================ FILE: Topo_sort.cpp ================================================ #include using namespace std; void funct(vector adj[],vector &vis,stack&st,int node){ vis[node]=1; for(auto it:adj[node]){ if(!vis[it]){ funct(adj,vis,st,it); } } st.push(node); } void topo(int n, vector adj[]){ stack st; vector vis(n,0); for(int i =0;i v; while(!st.empty()){ v.push_back(st.top()); st.pop(); } for(int i =0;i< v.size();i++){ cout<>m>>n; vector adj[m]; for(int i =0;i>x>>y; adj[x].push_back(y); } topo(m,adj); return 0; } ================================================ FILE: Total Moves For Bishop!.java ================================================ public class Solution { public int solve(int A, int B) { int topLeft=Math.min(A-1,B-1); int topRight=Math.min(A-1,8-B); int botLeft=Math.min(8-A,B-1); int botRight=Math.min(8-A,8-B); return topLeft+topRight+botLeft+botRight; } } ================================================ FILE: Towers_CSES.cpp ================================================ #include using namespace std; #define ll long long void solve(){ int n; cin>>n; multisetset; for(int i = 0; i>x; auto it = set.upper_bound(x); if(it == set.end()){ set.insert(x); } else{ set.erase(it); set.insert(x); } } cout<=0 && n2>=0){ if(A.charAt(n1)==B.charAt(n2)){ n1--; n2--; }else{ n1--; res++; } } return res; } } ================================================ FILE: Transform String - GFG/README.md ================================================ # Transform String ## Medium

Given two strings A and B. Find the minimum number of steps required to transform string A into string B. The only allowed operation for the transformation is selecting a character from string A and inserting it in the beginning of string A.

Example 1:

Input:
A = "abd"
B = "bad"
Output: 1
Explanation: The conversion can take place in
1 operation: Pick 'b' and place it at the front.

Example 2:

Input:
A = "GeeksForGeeks"
B = "ForGeeksGeeks"
Output: 3
Explanation: The conversion can take
place in 3 operations:
Pick 'r' and place it at the front.
A = "rGeeksFoGeeks"
Pick 'o' and place it at the front.
A = "orGeeksFGeeks"
Pick 'F' and place it at the front.
A = "ForGeeksGeeks"

Your Task: 
You dont need to read input or print anything. Complete the function transform() which takes two strings A and B as input parameters and returns the minimum number of steps required to transform A into B. If transformation is not possible return -1.


Expected Time Complexity: O(N) where N is max(length of A, length of B) 
Expected Auxiliary Space: O(1)  


Constraints:
1<= A.length(), B.length() <= 104

 

================================================ FILE: Tree Path Sum.java ================================================ public class Solution { public int hasPathSum(TreeNode A, int B) { if(A==null) return 0; if(A.val==B && A.left==null && A.right==null) return 1; if(hasPathSum(A.left,B-A.val)==1) return 1; return hasPathSum(A.right,B-A.val); } } ================================================ FILE: Triangle and Square - GFG/README.md ================================================ # 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

================================================ FILE: Triangle and Square - GFG/triangle-and-square.java ================================================ // { Driver Code Starts //Initial Template for Java import java.util.*; import java.io.*; import java.lang.*; class GFG{ public static void main(String [] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int test = Integer.parseInt(br.readLine()); while(test-- > 0) { int B = Integer.parseInt(br.readLine()); Solution obj = new Solution(); int count = obj.countSquare(B); System.out.println(count); } } }// } Driver Code Ends //User function Template for Java class Solution{ int countSquare(int B){ //Write your code here B-=2; B/=2; return B*(B+1)/2; } } ================================================ FILE: Tricky Subset Problem - GFG/README.md ================================================ # Tricky Subset Problem ## Medium

N children are made to stand in a queue. Each of them is given a number A[i]. The teacher writes a number S on a page and passes it to the first child. Each child must add all the numbers they see on the page along with their own number, write the sum on the paper and pass it to the next person. 
In the end, the teacher must determine if X can be formed by adding some of the numbers from the series of numbers written on the paper.

Example 1:

Input: 
S = 1, N = 4, X = 7
A = {1, 2, 4, 2}
Output: yes
Explaination: The final sequence of 
numbers on the paper is 1, 2, 5, 12, 22. 
Using 2 and 5 we can form 7. 


Example 2:

Input: 
S = 100, N = 2, X = 500
A = {51, 88}
Output: no
Explaination: The final sequence of 
numbers on the paper is 100, 151, 339. 
Using these numbers we cannot form 500.


Your Task:
You do not need to read input or print anything. Your task is to complete the function isPossible() which takes S, N, X and array A as input parameters and returns 1 if there is a subset which adds to this sum. Otherwise returns 0.


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

 

Constraints
1 ≤ N ≤ 105
1 ≤ S, Ai , X ≤ 1018  

================================================ FILE: Tricky Subset Problem - GFG/tricky-subset-problem.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[])throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); while(t-- > 0){ String a[] = in.readLine().trim().split("\\s+"); long S = Long.parseLong(a[0]); int N = Integer.parseInt(a[1]); long X = Long.parseLong(a[2]); String a1[] = in.readLine().trim().split("\\s+"); long A[] = new long[N]; for(int i = 0;i < N;i++) A[i] = Long.parseLong(a1[i]); Solution ob = new Solution(); if(ob.isPossible(S, N, X, A) == 1) System.out.println("yes"); else System.out.println("no"); } } }// } Driver Code Ends //User function Template for Java class Solution{ static int isPossible(long S, int N, long X, long A[]) { int i=0; long s=S; for(i=0;iX){ break; } } if(s==X)return 1; while(X>=0 && i>=0){ if(X>=A[i])X-=A[i]; if(X==0 || X-S==0)return 1; i--; } return 0; } } ================================================ FILE: Two Sum.java ================================================ class Solution { public int[] twoSum(int[] nums, int target) { int i; int j; for (i=1;i List[int]: lookup_dict = {} for position, number in enumerate(nums): if target - number in lookup_dict: return lookup_dict[target-number], position else: lookup_dict[number] = position ================================================ FILE: UTF-8-Validation med lc.cpp ================================================ #include using namespace std; // TC : O(N) where N is the number of elements in data // SC: O(1) class Solution { public: bool validUtf8(vector& data) { int remaining = 0; for (auto& x : data) { if (remaining == 0) { if ((x >> 5) == 0b110) { remaining = 1; } else if ((x >> 4) == 0b1110) { remaining = 2; } else if ((x >> 3) == 0b11110) { remaining = 3; } else if ((x >> 7) != 0) { return false; } } else { if ((x >> 6) != 0b10) return false; else remaining--; } } return remaining == 0; } }; ================================================ FILE: Union-Find - GFG/README.md ================================================ # Union-Find ## Easy

This problem is to implement disjoint set union. There will be 2 incomplete functions namely union and find. You have to complete these functions. 

Union: Join two subsets into a single set.
isConnected: Determine which subset a particular element is in. This can be used for determining if two elements are in same subset.

Example 1:

Input:
N = 5
q = 4
Queries = 
Union(1,3)
isConnected(1,2)
Union(1,5)
isConnected(3,5)
Output:
0
1
Explanation: Initially all nodes 1 2 3 4 5
are not connected. 
After Union(1,3), node 1 and 3 will be
connected.
When we do isConnected(1,2),  as node 1
and 2 are not connected it will return 0.
After Union(1,5), node 1 and 5 will be
connected.
When we do isConnected(3,5),  as node
1 and 3 are connected, and node 1 and 5
are connected, hence 3 and 5 are
connected. Thus it will return 1.

Example 2:

Input:
N = 5
q = 4
Queries = 
Union(1,4)
Union(1,5)
isConnected(2,3)
Union(3,4)
Output: 0

Your Task:

You have to complete the function union_() which merges the node1 and node2. You will also have to complete the function isConnected() which will return whether the two nodes are connected.

Note: Both function will contain two arrays par[] and ranks1[] along with two nodes. Initially par[i] = i and rank1[i] = 1 

Expected Time Complexity: O(N + Q).
Expected Auxiliary Space: O(1).

Constraints: 
1 <= N <= 105
1<= Q <= 105
1 <= node1, node2 <= N

================================================ FILE: Union-Find - GFG/union-find.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; public class GFG { public static void main(String[] args) throws IOException { //using BufferedReader to take input BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //taking total testcases int t = Integer.parseInt(br.readLine()); while(t-- > 0){ //taking total number of elements int n = Integer.parseInt(br.readLine()); int par[] = new int[n+1]; int rank[] = new int[n+1]; //initializing the parent and //the rank array for(int i = 1; i<=n; ++i){ par[i] = i; rank[i] = 1; } int a = 0, b = 0; char c = '0'; //taking number of queries int query = Integer.parseInt(br.readLine()); Boolean output = false; while(query-- >0){ String str[] = br.readLine().trim().split(" "); c = str[0].charAt(0); a = Integer.parseInt(str[1]); b = Integer.parseInt(str[2]); //if query type is 'U' //then calling union_ method if(c == 'U'){ new Solution().union_(a, b, par, rank); } else{//else calling isConnected() method output = new Solution().isConnected(a, b, par, rank); if(output == true) System.out.println("1"); else System.out.println("0"); } } } } }// } Driver Code Ends //User function Template for Java class Solution { public int findPar(int node,int par[]){ if(node==par[node])return node; return par[node]=findPar(par[node],par); } //Function to merge two nodes a and b. public void union_(int a, int b, int par[], int rank[]) { a=findPar(a,par); b=findPar(b,par); if(rank[a]

Given an array arr[] of integers of size N that might contain duplicates, the task is to find all possible unique subsets.

Note: Each subset should be sorted.

Example 1:

Input: N = 3, arr[] = {2,1,2}
Output:(),(1),(1 2),(1 2 2),(2),(2 2)
Explanation: 
All possible subsets = (),(2),(1),(1,2),(2),(2,2),(2,1),(2,1,2)
After Sorting each subset = (),(2),(1),(1,2),(2),(2,2),(1,2),(1,2,2) 
Unique Susbsets in Lexicographical order = (),(1),(1,2),(1,2,2),(2),(2,2)

Example 2:

Input: N = 4, arr[] = {1,2,3,3}
Output: (),(1),(1 2),(1 2 3)
(1 2 3 3),(1 3),(1 3 3),(2),(2 3)
(2 3 3),(3),(3 3)

Your Task:
Your task is to complete the function AllSubsets() which takes the array arr[] and N as input parameters and returns list of all possible unique subsets in lexicographical order. 

Expected Time Complexity: O(2N).
Expected Auxiliary Space: O(2N * X), X = Length of each subset.

Constraints:
1 ≤ N ≤ 12

1 ≤ arr[i] ≤ 9

================================================ FILE: Unique Subsets - GFG/unique-subsets.java ================================================ // { Driver Code Starts import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int testCases = sc.nextInt(); for(int t=0;t> res = new solve().AllSubsets(arr,n); for (int i = 0; i < res.size (); i++) { System.out.print ("("); for (int j = 0; j < res.get(i).size (); j++) { if (j != res.get(i).size()-1) System.out.print ((res.get(i)).get(j) + " "); else System.out.print ((res.get(i)).get(j)); } System.out.print (")"); } System.out.println(); } } }// } Driver Code Ends class solve{ public static ArrayList > AllSubsets(int arr[], int n){ Arrays.sort(arr); ArrayList> ans= new ArrayList<>(); ArrayList al=new ArrayList<>(); check(arr,n,0,ans,al); ans.remove(0); return ans; } public static void check(int arr[], int n,int index,ArrayList> ans,ArrayList al){ if(!ans.contains(al))ans.add(al); if(index==n) return; ArrayList temp=new ArrayList<>(al); temp.add(arr[index]); check(arr,n,index+1,ans,temp); check(arr,n,index+1,ans,al); } } ================================================ FILE: Unit Area of largest region of 1's.cpp ================================================ class Solution { public: //Function to find unit area of the largest region of 1s. void solve(vector> &grid , int i , int j , int n , int m , int &cnt) { if(i < 0 || j < 0 || i >= n || j >= m || grid[i][j] == 0) return; cnt+=1; grid[i][j] = 0; // 8 directions solve(grid,i-1,j,n,m ,cnt); solve(grid,i+1,j,n,m ,cnt); solve(grid,i,j-1,n,m ,cnt); solve(grid,i,j+1,n,m ,cnt); solve(grid,i-1,j-1,n,m ,cnt); solve(grid,i-1,j+1,n,m ,cnt); solve(grid,i+1,j-1,n,m ,cnt); solve(grid,i+1,j+1,n,m ,cnt); } int findMaxArea(vector>& grid) { int ans = 0; int n = grid.size() , m = grid[0].size(); for(int i = 0;i>& grid, int i, int j) // { // if(i < 0 or i >= n or j < 0 or j >= m or grid[i][j] == 0) // return 0; // int ans = 1; // grid[i][j] = 0; // for(int d=0; d<8; d++) // ans += countArea(grid, i+dx[d], j+dy[d]); // return ans; // } // //Function to find unit area of the largest region of 1s. // int findMaxArea(vector>& grid) { // // Code here // n = grid.size(); // m = grid[0].size(); // int ans = 0; // for(int i=0; i=ROW || col>=COL || visited[row][col] || grid[row][col]==0) return false; return true; } void DFS(int[][] grid,int row,int col,boolean[][] visited,int ROW,int COL) { int[] x = { -1, -1, -1, 0, 0, 1, 1, 1 }; int[] y = { -1, 0, 1, -1, 1, -1, 0, 1 }; visited[row][col] = true; for (int k = 0; k < 8; k++) { if (isSafe(grid, row + x[k], col + y[k],visited, ROW, COL)) { count++; DFS(grid, row + x[k], col + y[k],visited, ROW, COL); } } } public int findMaxArea(int[][] grid) { int ROW = grid.length; int COL = grid[0].length; boolean[][] visited = new boolean[ROW][COL]; int result = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (grid[i][j] == 1 && !visited[i][j]) { count = 1; DFS(grid, i, j, visited, ROW, COL); result = Math.max(result, count); } } } return result; } } ================================================ FILE: Valid Binary Search Tree.java ================================================ public class Solution { int check(TreeNode a,int min,int max){ if(a==null)return 1; if(a.valmax)return 0; return check(a.left,min,a.val-1)& check(a.right,a.val+1,max); } public int isValidBST(TreeNode root) { return check(root,Integer.MIN_VALUE,Integer.MAX_VALUE); } } ================================================ FILE: Valid Mountain Array.java ================================================ class Solution { public boolean validMountainArray(int[] A) { int N = A.length; int i = 0; // walk up while (i+1 < N && A[i] < A[i+1]) i++; // peak can't be first or last if (i == 0 || i == N-1) return false; // walk down while (i+1 < N && A[i] > A[i+1]) i++; return i == N-1; } } ================================================ FILE: Valid Parentheses.java ================================================ class Solution { public boolean isValid(String s) { char[] stack = new char[s.length()]; int head = 0; for(char c : s.toCharArray()) { switch(c) { case '{': case '[': case '(': stack[head++] = c; break; case '}': if(head == 0 || stack[--head] != '{') return false; break; case ')': if(head == 0 || stack[--head] != '(') return false; break; case ']': if(head == 0 || stack[--head] != '[') return false; break; } } return head == 0; } } ================================================ FILE: Valid Password.java ================================================ public class Solution { public int solve(String A) { if(A.length()<8 || A.length()>15)return 0; boolean num=false; boolean lower=false; boolean upper=false; boolean spcl=false; for(int i=0;i='0' && ch<='9')num=true; if(ch>='a' && ch<='z')lower=true; if(ch>='A' && ch<='Z')upper=true; if(ch=='@' || ch=='#' || ch=='%'||ch=='&'||ch=='!'||ch=='$'||ch=='*')spcl=true; } return num && lower && upper && spcl?1:0; } } ================================================ FILE: Validate Stack Sequences.java ================================================ class Solution { public boolean validateStackSequences(int[] a, int[] b) { Deque st=new ArrayDeque<>(); int i=0; int j=0; st.push(a[i]); i++; while(i=0&&arr[i]==pop[j]) { i--; j++; } } if(i==-1&&j==n) return true; return false; } } ================================================ FILE: Verify Prime.java ================================================ static boolean prime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i += 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } ================================================ FILE: Vertical Sum of a Binary Tree.java ================================================ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { int min; int max; public ArrayList verticalSum(TreeNode A) { min=Integer.MAX_VALUE; max=Integer.MIN_VALUE; ArrayList arr=new ArrayList<>(); Map map=new HashMap<>(); dfs(A,map,0); while(min<=max){ arr.add(map.get(min)); min++; } return arr; } public void dfs(TreeNode a,Map map,int curr){ if(a==null)return; map.put(curr,map.getOrDefault(curr,0)+a.val); min=Math.min(min,curr); max=Math.max(max,curr); dfs(a.left,map,curr-1); dfs(a.right,map,curr+1); } } ================================================ FILE: Villain Con - GFG/README.md ================================================ # Villain Con ## Medium

The minions are very elitist in nature. If minion x admires minion y, then y thinks too highly of himself and does not admire x back. Also, if x admires y, x also admires everyone that y admires.
All the minions are going to be present at the Villain Con. They want to make sure that they do not dress in the same color as someone who admires them. 
There are N minions and M relations between them. The relations are given in a 2D array mat. Each relation is given in xi , yi format where yi admires xi. Find the minimum number of different colours that the minions will be dressing in. 

 

Example 1:

Input: 
N = 5, M = 6
mat = {{1, 3}, 
       {2, 3}, 
       {3, 4}, 
       {1, 4}, 
       {2, 5}, 
       {3, 5}}
Output: 3
Explaination:
If we assign red colour to 1 and 2,
green colour to 3, and blue colour to 4 and 5, then
every minion will have different coloured dresses
from the one who admires them.

Example 2:

Input:
N = 3, M = 2
mat = {{1,3},{2,3}}
Output:
2
Explanation:
If we assign red colour to 1 and 2, and green colour to 3, then the condition is satisfied.

Your Task:
You do not need to read input or print anything. Your task is to complete the function minColour() which takes N, M and mat[][] as input parameters and returns the minimum number of colours required.

 

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

 

Constraints:
1 ≤ N ≤ 105
1 ≤ M ≤ 2*105  
1 ≤ xi , yi ≤ N

================================================ FILE: Villain Con - GFG/villain-con.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG{ public static void main(String args[])throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); while(t-- > 0) { String a[] = in.readLine().trim().split("\\s+"); int N = Integer.parseInt(a[0]); int M = Integer.parseInt(a[1]); int mat[][] = new int[M][2]; for(int i = 0;i < M;i++){ String a1[] = in.readLine().trim().split("\\s+"); mat[i][0] = Integer.parseInt(a1[0]); mat[i][1] = Integer.parseInt(a1[1]); } Solution ob = new Solution(); System.out.println(ob.minColour(N, M, mat)); } } }// } Driver Code Ends //User function Template for Java class Solution{ static int minColour(int N, int M, int mat[][]) { Queue q = new LinkedList<>(); int[] indegree = new int[N+1]; ArrayList> adj = new ArrayList<>(); for(int i=0;i<=N;i++){ adj.add(new ArrayList<>()); } for(int[] row : mat){ indegree[row[0]]++; adj.get(row[1]).add(row[0]); } for(int i=0;i<=N;i++){ if(indegree[i] == 0){ q.offer(i); } } int count = 0; while(!q.isEmpty()){ count++; int size = q.size(); while(size-->0){ int currVertex = q.poll(); for(int neighbor : adj.get(currVertex)){ if(indegree[neighbor] == 1){ q.offer(neighbor); } indegree[neighbor]--; } } } return count; } } ================================================ FILE: Vowel and Consonant Substrings!.java ================================================ public class Solution { int mod=1000000007; public int solve(String A) { int ans=0; int con=0; int vow=0; for(int i=A.length()-1;i>=0;i--){ char c=A.charAt(i); if(vowel(c)){ vow++; ans+=con; }else{ con++; ans+=vow; } ans%=mod; } return ans; } public boolean vowel(char c){ if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u'){ return true; } return false; } } ================================================ FILE: Wave Array.java ================================================ public class Solution { public ArrayList wave(ArrayList arr) { Collections.sort(arr); int i=0; while(i+1 0) { ways += dp[i-1]; ways %= mod; } dig = s.substring(i-2, i); if(Integer.parseInt(dig) >= 10 && Integer.parseInt(dig) <= 26) { ways += dp[i-2]; ways %= mod; } dp[i] = ways; } return dp[n]; } } ================================================ FILE: Window String.java ================================================ public class Solution { public String minWindow(String A, String B) { int want=B.length(); int count=0; StringBuilder sb=new StringBuilder(); String ans=null; Map map=new HashMap<>(); Map curr=new HashMap<>(); for(char c:B.toCharArray()){ map.put(c,map.getOrDefault(c,0)+1); } int i=0; int j=0; while(jsb.length()){ ans=sb.toString(); } char c=A.charAt(j); sb.deleteCharAt(0); curr.put(c,curr.get(c)-1); if(!map.containsKey(c)){ j++; continue; } if(curr.get(c)

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 

================================================ FILE: Word Break - Part 2 - GFG/word-break-part-2.java ================================================ // { Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; import java.util.stream.*; class GFG{ public static void main(String args[])throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); while(t-- > 0){ int n = Integer.parseInt(in.readLine()); String arr[] = in.readLine().trim().split("\\s+"); List dict = new ArrayList(); for(int i = 0;i < n;i++) dict.add(arr[i]); String s = in.readLine(); Solution ob = new Solution(); List ans = new ArrayList(); ans = ob.wordBreak(n, dict, s); if(ans.size() == 0) System.out.println("Empty"); else{ List sol = ans.stream().sorted().collect(Collectors.toList()); for(int i = 0;i < sol.size();i++) System.out.print("("+sol.get(i)+")"); System.out.println(); } } } }// } Driver Code Ends //User function Template for Java class Solution{ static List wordBreak(int n, List dict, String s) { // code here List ans=new ArrayList<>(); dfs(dict,s,"",ans); return ans; } static void dfs(List dict,String s,String sentence,List ans){ if(s.length()==0){ ans.add(sentence.substring(0,sentence.length()-1)); } for(int i=0;ians; void backTrack(int i, string &s, string t, vector& wordDict){ if(i == s.size()){ t.pop_back(); ans.push_back(t); return; } for(auto &w : wordDict){ int n = w.size(); string str = s.substr(i, n); if(w == str){ backTrack(i + n, s, t + str + " ", wordDict); } } } vector wordBreak(string s, vector& wordDict) { backTrack(0, s, "", wordDict); return ans; } }; ================================================ FILE: Word Break II.java ================================================ public class Solution { ArrayList> dp; public ArrayList wordBreak(String A, ArrayList B) { dp = new ArrayList<>(); for(int i = 0;i()); } Set set = new HashSet<>(); for(String str:B){ set.add(str); } return wordBreak(A,set,0); } public ArrayList wordBreak(String A, Set set, int i) { if(i==A.length()){ return new ArrayList(); } if(dp.get(i).size()!=0) return dp.get(i); ArrayList ans = new ArrayList<>(); for(int j = i+1;j<=A.length();j++){ if(set.contains(A.substring(i,j))){ ArrayList buf = wordBreak(A,set,j); for(String a: buf){ ans.add(A.substring(i,j)+" "+a); } if(j==A.length()){ ans.add(A.substring(i)); } } } dp.set(i,ans); return ans; } } ================================================ FILE: Word Break.java ================================================ public class Solution { public int wordBreak(String A, String[] B) { Set set = new HashSet<>(); for (String s : B) { set.add(s); } Boolean[] dp = new Boolean[A.length()]; return wordBreak(A, set, 0, dp); } private int wordBreak(String s, Set set, int start, Boolean[] dp) { if (start == s.length()) { return 1; } if (dp[start] != null) return dp[start] ? 1 : 0; int ans = 0; for (int end = start + 1; end <= s.length(); end++) { if (set.contains(s.substring(start, end)) && wordBreak(s, set, end, dp) == 1) { ans = 1; break; } } dp[start] = ans == 1; return ans; } } ================================================ FILE: Word Count.py ================================================ class Solution: # @param A : string # @return an integer def solve(self, A): list1=A.split(' ') i=0 k=len(list1) while i& wordList) { if(startWord==targetWord){ for(int i=0;i> st; st.push({startWord, 1}); set sr; while(!st.empty()){ auto tp = st.front(); sr.insert(tp.first); if(tp.first==targetWord) return tp.second; st.pop(); for(int i=0; i List[List[str]]: #generate Nei = defaultdict(list) for word in wordList: for i in range(len(word)): pattern = word[:i]+'*'+word[i+1:] Nei[pattern].append(word) #breadth first search + generate parent dictionary with path length limit seen = {beginWord:0} q = deque([(beginWord,0)]) minDist = float("inf") Parent = defaultdict(set) while q: for _ in range(len(q)): pre,dis = q.popleft() for i in range(len(pre)): pattern = pre[:i] + "*" + pre[i+1:] for neighbor in Nei[pattern]: if neighbor not in seen or (seen[neighbor] == dis + 1 and seen[neighbor] <= minDist): if neighbor == endWord: minDist = dis + 1 Parent[neighbor].add(pre) if neighbor not in seen: q.append((neighbor,dis+1)) seen[neighbor] = dis + 1 #generate path from parent dictionary def makeList(cur,Path): if cur == beginWord: res.append(Path) else: for parent in Parent[cur]: makeList(parent,[parent] + Path) res = [] makeList(endWord,[endWord]) #return results return res ================================================ FILE: Word Ladder.java ================================================ class Solution { public int ladderLength(String beginWord, String endWord, List wordList) { if (wordList == null || wordList.size() == 0) return 0; //Hashset benefits: deduplication is also completed //start end HashSet start = new HashSet<>(); //end HashSet end = new HashSet<>(); //dictionary of all strings HashSet dic = new HashSet<>(wordList); start.add(beginWord); end.add(endWord); if (!dic.contains(endWord)) return 0; //After going through the above series of judgments, when you get here, if there is a path, the minimum is 2, so start with 2 return bfs(start, end, dic, 2); } public int bfs(HashSet st, HashSet ed, HashSet dic, int l) { //When searching with two ends, if any segment is "broken", that is to say, there is no path that can be connected, it will return 0 directly. if (st.size() == 0) return 0; if (st.size() > ed.size()) {//Double-ended search, in order to optimize the time, always use less to find more. For example, if 1000 are inserted at the beginning, but only 3 at the end, it is definitely better to start from the less end. return bfs(ed, st, dic, l); } //Marking behavior of BFS, i.e. used not reused dic.removeAll(st); //Collect next level proximity points HashSet next = new HashSet<>(); for (String s : st) { char[] arr = s.toCharArray(); for (int i = 0; i < arr.length; i++) { char tmp = arr[i]; //Variety for (char c = 'a'; c <= 'z'; c++) { if (tmp == c) continue; arr[i] = c; String nstr = new String(arr); if (dic.contains(nstr)) { if (ed.contains(nstr)) return l; else next.add(nstr); } } //Variety arr[i] = tmp; } } return bfs(next, ed, dic, l + 1); } } ================================================ FILE: Word Pattern.java ================================================ class Solution { public boolean wordPattern(String pattern, String s) { String[] words = s.split(" "); Map wordMap = new HashMap<>(); Map charMap = new HashMap<>(); if(pattern.length()!=words.length){ return false; } for(int i= 0;i

Given an array nums[] of size n, where nums[i] denotes the number of characters in one word. Let K be the limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly.
Assume that the length of each word is smaller than the line width. When line breaks are inserted there is a possibility that extra spaces are present in each line. The extra spaces include spaces put at the end of every line except the last one

You have to minimize the following total cost where total cost = Sum of cost of all lines, where cost of line is = (Number of extra spaces in the line)2.

Example 1:

Input: nums = {3,2,2,5}, k = 6
Output: 10
Explanation: Given a line can have 6
characters,
Line number 1: From word no. 1 to 1
Line number 2: From word no. 2 to 3
Line number 3: From word no. 4 to 4
So total cost = (6-3)2 + (6-2-2-1)2 = 32+12 = 10.
As in the first line word length = 3 thus
extra spaces = 6 - 3 = 3 and in the second line
there are two word of length 2 and there already
1 space between two word thus extra spaces
= 6 - 2 -2 -1 = 1. As mentioned in the problem
description there will be no extra spaces in
the last line. Placing first and second word
in first line and third word on second line
would take a cost of 02 + 42 = 16 (zero spaces
on first line and 6-2 = 4 spaces on second),
which isn't the minimum possible cost.

Example 2:

Input: nums = {3,2,2}, k = 4
Output: 5
Explanation: Given a line can have 4 
characters,
Line number 1: From word no. 1 to 1
Line number 2: From word no. 2 to 2
Line number 3: From word no. 3 to 3
Same explaination as above total cost
= (4 - 3)2 + (4 - 2)2 = 5.


Your Task:
You don't need to read or print anyhting. Your task is to complete the function solveWordWrap() which takes nums and k as input paramater and returns the minimized total cost.

 

Expected Time Complexity: O(n2)
Expected Space Complexity: O(n)

 

Constraints:
1 ≤ n ≤ 500
1 ≤ nums[i] ≤ 1000
max(nums[i]) ≤ k ≤ 2000

================================================ FILE: Word Wrap - GFG/word-wrap.java ================================================ // { Driver Code Starts import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { int n = Integer.parseInt(br.readLine().trim()); int[] nums = new int[n]; String[] S = br.readLine().trim().split(" "); for(int i = 0; i < n; i++) nums[i] =Integer.parseInt(S[i]); int k = Integer.parseInt(br.readLine().trim()); Solution obj = new Solution(); System.out.println(obj.solveWordWrap(nums, k)); } } } // } Driver Code Ends class Solution{ public int solveWordWrap (int[] nums, int k){ return solveWordWrapRec(nums, k, 0, new HashMap<>()); } public int solveWordWrapRec (int[] nums, int k, int idx, Map cache){ if(idx >= (nums.length-1)){ return 0; } Integer value = cache.get(idx); if(value != null) return value; int cost = Integer.MAX_VALUE; int used = 0; for(int i=idx; i k) break; if(i+1 < nums.length){ cost = Math.min(cost, solveWordWrapRec(nums, k, i+1, cache) + getCost(nums, idx, i, k)); }else{ cost = Math.min(cost, getCost(nums, idx, i, k)); } used += nums[i] + 1; } value = cost; cache.put(idx, value); return value; } private int getCost(int[] nums, int from, int to, int k){ if(to == nums.length-1) return 0; int used = 0; for(int i=from; i<=to; i++){ if(used > 0) used++; used += nums[i]; } return (k-used)*(k-used); } } ================================================ FILE: X Total Shapes.java ================================================ class Solution { //Function to find the number of 'X' total shapes. public int xShape(char[][] grid) { // code here int ans=0; int n=grid.length; int m=grid[0].length; boolean[][] vis=new boolean[n][m]; for(int i=0;i0){ dfs(grid,i-1,j,vis); } if(i0){ dfs(grid,i,j-1,vis); } if(j> 1; // int b = a ^ k; // return Math.abs(a - b) == 1? Math.min(a,b): -1; if (k % 2 == 0) return -1; if ((k & (k+1)) != 0) return -1; if (k == 1) return 2; return k>>1; } } ================================================ FILE: XOR-ing the Subarrays!.java ================================================ public class Solution { public int solve(int[] A) { int ans=0; if(A.length%2==0)return ans; for(int i=0;i> zigzagLevelOrder(TreeNode root) { ArrayList> res = new ArrayList<>(); if(root==null) return res; Queue q = new LinkedList<>(); q.offer(root); int p=0; while(!q.isEmpty()) { int l = q.size(); List level = new ArrayList<>(); for(int i=0;i(level)); p++; } return res; } } ================================================ FILE: Zigzag String.java ================================================ public class Solution { public String convert(String input, int num) { if(num<=1){ return input; } StringBuilder result = new StringBuilder(); List list = new ArrayList<>(); for (int i = 0; i < num; i++) { list.add(new StringBuilder()); } boolean l2r = true; int i = 0; int size = input.length(); int ptr = 0; while (i < size) { if (l2r) { while (ptr < num && i < size) { list.get(ptr).append(input.charAt(i)); i++; ptr++; } ptr -= 2; l2r = false; } else { while (ptr >= 0 && i < size) { list.get(ptr).append(input.charAt(i)); i++; ptr--; } ptr = 1; l2r = true; } } for (StringBuilder temp : list) { result.append(temp); } return result.toString(); } } ================================================ FILE: alternate positive and negative.cpp ================================================ void rearrange(int arr[], int n) { // code here vector A; vector B; for (int i=0; i& nums) { int size = nums.size(); int count = 0; for(int x=0; x nums[(x+1)%size]) count ++; } return (count <= 1); // in case of sorted and rotated array the count is 1 and in case of only sorted array the count is 0 // in case of non-sorted and non-rotated array the count is greater than 1 so false. } }; ================================================ FILE: depth first search.cpp ================================================ #include #include using namespace std; void dfs(vector* adj,int node,vector& visited) { visited[node]=1; cout<>n>>e; // n is number of vertix // e is number of edges vector adj[n]; while(e--) { int u,v; cin>>u>>v; adj[u].push_back(v); adj[v].push_back(u); } vector visited(n,0); for(int i=0;i& nums, int k) { // eg 1 2 3 4 5 6 7 k %= nums.size(); reverse(nums.begin(), nums.end()); // reverse full 7 6 5 4 3 2 1 reverse(nums.begin(), nums.begin()+k); // reverse till first k 5 6 7 4 3 2 1 reverse(nums.begin()+k, nums.end()); // reverse till end from k 5 6 7 1 2 3 4 } }; ================================================ FILE: sorting-characters-by-frequency/sorting-characters-by-frequency.cpp ================================================ bool compare(const string& a, const string &b){ return a.length() > b.length(); } class Solution { public: string frequencySort(string s) { // 1. // unordered_map mp; // for(int i=0;i 0){ // int maxFre = -1; // char ch; // for(auto it : mp){ // if(maxFre < it.second){ // maxFre = it.second; // ch = it.first; // } // } // mp.erase(ch); // for(int i=0;i freq(100,""); for (char a : s) freq[a-'0'] += a; sort(freq.begin(), freq.end(), compare); s = ""; for (string str : freq) s += str; return s; // what it does is it is appending the string at the position of characters based on their indexes in alphabet order // like for tree it storing like for position 4(0-based indexing) ee, 19 - t and 17 - r // and then sorting based on length of strings. } }; ================================================ FILE: split array into consecutive subsequences/split-array-into-consecutive-subsequences.cpp ================================================ class Solution { public: bool isPossible(vector& nums) { int n = nums.size(); unordered_mapm, m1; // to store the frequency of each element for(int i=0;i0){// step 3. earlier explained m1[it-1]--; m1[it]++; }else if(m[it+1] != 0 and m[it+2] != 0){ // step 4. --> if(next 2 consecutive elements present in the map) like if it == 1 then if 2 and 3 is present in the map or not if not then false else reduce their freq and store the last element's freq in second map m[it+1]--; m[it+2]--; m1[it+2]++; } // if for test case 1 2 3 3 4 4 5 5 answer is true but our algo return false when reached to 4 so to overcome it we are using m1 and doing step 3, like if for 4 if 3 is present in m1 then add 4 also to one of the subsequence. // https://youtu.be/Gmc-4Dpzw2g -- video for reference else{ return false; } } return true; } }; ================================================ FILE: string-to-integer(atoi)/string-to-integer(atoi).cpp ================================================ #include class Solution { public: int myAtoi(string str) { long long res = 0; int i=0, len = str.length(); bool neg = false; while(str[i]==' ') i++; // skip all the spaces in starting if(str[i]=='+') i++; // skip + in starting else if(str[i]=='-') {i++; neg=true;} // skip - in starting while(str[i]>='0' && str[i]<='9'){ res = res*10 + (str[i]-'0'); if(res>=INT_MAX && !neg) {res = INT_MAX; break;} else if(res>INT_MAX && neg) {res = INT_MIN; break;} i++; } if (neg) res *= -1; return (int)res; } }; ================================================ FILE: sum of k smallest elements in BST.cpp ================================================ void inorder(Node* node,vector &ans) { if(node==NULL) return ; inorder(node->left,ans); ans.push_back(node->data); inorder(node->right,ans); } int sum(Node* root, int k) { // Your code here int sum=0; vector ans; inorder(root,ans); int cnt=0; for(int i=0;i stack = new Stack(); for(char c: s.toCharArray()){ if(c == '(' || c == '[' || c == '{'){ stack.push(c); } else if(c == ')' && !stack.isEmpty() && stack.peek() == '(' ){ stack.pop(); } else if(c == ']' && !stack.isEmpty() && stack.peek() == '[') { stack.pop(); } else if(c == '}' && !stack.isEmpty() && stack.peek() == '{') { stack.pop(); } else{ return false; } } return stack.isEmpty(); } }