├── 231-power-of-two └── power-of-two.cpp ├── 2645-pass-the-pillow └── pass-the-pillow.cpp ├── 1013-fibonacci-number └── fibonacci-number.cpp ├── 2649-count-total-number-of-colored-cells └── count-total-number-of-colored-cells.cpp ├── 3676-smallest-number-with-all-set-bits └── smallest-number-with-all-set-bits.cpp ├── 136-single-number └── single-number.cpp ├── 1916-find-center-of-star-graph └── find-center-of-star-graph.cpp ├── 287-find-the-duplicate-number └── find-the-duplicate-number.cpp ├── 2308-divide-array-into-equal-pairs └── divide-array-into-equal-pairs.cpp ├── 2792-neighboring-bitwise-xor └── neighboring-bitwise-xor.cpp ├── 2128-reverse-prefix-of-word └── reverse-prefix-of-word.cpp ├── 1556-make-two-arrays-equal-by-reversing-subarrays └── make-two-arrays-equal-by-reversing-subarrays.cpp ├── 3447-clear-digits └── clear-digits.cpp ├── 283-move-zeroes ├── move-zeroes.cpp └── README.md ├── 2323-minimum-bit-flips-to-convert-number └── minimum-bit-flips-to-convert-number.cpp ├── 268-missing-number └── missing-number.cpp ├── 1849-maximum-absolute-sum-of-any-subarray └── maximum-absolute-sum-of-any-subarray.cpp ├── 2614-maximum-count-of-positive-integer-and-negative-integer └── maximum-count-of-positive-integer-and-negative-integer.cpp ├── 1137-height-checker └── height-checker.cpp ├── 53-maximum-subarray └── maximum-subarray.cpp ├── 2021-remove-all-occurrences-of-a-substring └── remove-all-occurrences-of-a-substring.cpp ├── 3483-alternating-groups-ii └── alternating-groups-ii.cpp ├── 1927-maximum-ascending-subarray-sum └── maximum-ascending-subarray-sum.cpp ├── 2478-longest-nice-subarray └── longest-nice-subarray.cpp ├── 3429-special-array-i └── special-array-i.cpp ├── 792-binary-search └── binary-search.cpp ├── 344-reverse-string ├── reverse-string.cpp └── README.md ├── 476-number-complement └── number-complement.cpp ├── 121-best-time-to-buy-and-sell-stock └── best-time-to-buy-and-sell-stock.cpp ├── 1642-water-bottles └── water-bottles.cpp ├── 26-remove-duplicates-from-sorted-array └── remove-duplicates-from-sorted-array.cpp ├── 768-partition-labels └── partition-labels.cpp ├── 2463-minimum-recolors-to-get-k-consecutive-black-blocks └── minimum-recolors-to-get-k-consecutive-black-blocks.cpp ├── 3379-score-of-a-string └── score-of-a-string.cpp ├── 2107-find-unique-binary-string └── find-unique-binary-string.cpp ├── 242-valid-anagram ├── valid-anagram.cpp └── README.md ├── 2681-put-marbles-in-bags └── put-marbles-in-bags.cpp ├── 69-sqrtx ├── sqrtx.cpp └── README.md ├── 237-delete-node-in-a-linked-list └── delete-node-in-a-linked-list.cpp ├── 3154-maximum-value-of-an-ordered-triplet-i └── maximum-value-of-an-ordered-triplet-i.cpp ├── 3430-count-days-without-meetings └── count-days-without-meetings.cpp ├── 3621-minimum-operations-to-make-array-values-equal-to-k └── minimum-operations-to-make-array-values-equal-to-k.cpp ├── 185-department-top-three-salaries └── department-top-three-salaries.sql ├── 2148-minimum-number-of-moves-to-seat-everyone └── minimum-number-of-moves-to-seat-everyone.cpp ├── 560-subarray-sum-equals-k ├── subarray-sum-equals-k.cpp └── README.md ├── 78-subsets ├── subsets.cpp └── README.md ├── 1878-check-if-array-is-sorted-and-rotated └── check-if-array-is-sorted-and-rotated.cpp ├── 442-find-all-duplicates-in-an-array └── find-all-duplicates-in-an-array.cpp ├── 152-maximum-product-subarray └── maximum-product-subarray.cpp ├── 982-minimum-increment-to-make-array-unique └── minimum-increment-to-make-array-unique.cpp ├── 240-search-a-2d-matrix-ii └── search-a-2d-matrix-ii.cpp ├── 2448-count-number-of-bad-pairs └── count-number-of-bad-pairs.cpp ├── 2195-time-needed-to-buy-tickets └── time-needed-to-buy-tickets.cpp ├── 35-search-insert-position └── search-insert-position.cpp ├── 1631-number-of-sub-arrays-with-odd-sum └── number-of-sub-arrays-with-odd-sum.cpp ├── 125-valid-palindrome └── valid-palindrome.cpp ├── 1460-number-of-substrings-containing-all-three-characters └── number-of-substrings-containing-all-three-characters.cpp ├── 3475-minimum-operations-to-make-binary-array-elements-equal-to-one-i └── minimum-operations-to-make-binary-array-elements-equal-to-one-i.cpp ├── 1370-count-number-of-nice-subarrays └── count-number-of-nice-subarrays.cpp ├── 1737-maximum-nesting-depth-of-the-parentheses └── maximum-nesting-depth-of-the-parentheses.cpp ├── 455-assign-cookies └── assign-cookies.cpp ├── 1889-check-if-number-is-a-sum-of-powers-of-three └── check-if-number-is-a-sum-of-powers-of-three.cpp ├── 1236-n-th-tribonacci-number ├── n-th-tribonacci-number.cpp └── README.md ├── 330-patching-array └── patching-array.cpp ├── 485-max-consecutive-ones ├── max-consecutive-ones.cpp └── README.md ├── 1520-number-of-steps-to-reduce-a-number-in-binary-representation-to-one └── number-of-steps-to-reduce-a-number-in-binary-representation-to-one.cpp ├── 169-majority-element ├── majority-element.cpp └── README.md ├── 189-rotate-array └── rotate-array.cpp ├── 2524-largest-positive-integer-that-exists-with-its-negative └── largest-positive-integer-that-exists-with-its-negative.cpp ├── 1-two-sum └── two-sum.cpp ├── 1741-sort-array-by-increasing-frequency └── sort-array-by-increasing-frequency.cpp ├── 2502-sort-the-people └── sort-the-people.cpp ├── 2572-append-characters-to-string-to-make-subsequence └── append-characters-to-string-to-make-subsequence.cpp ├── 260-single-number-iii └── single-number-iii.cpp ├── 1756-minimum-deletions-to-make-string-balanced └── minimum-deletions-to-make-string-balanced.cpp ├── 1335-maximum-candies-allocated-to-k-children └── maximum-candies-allocated-to-k-children.cpp ├── 2665-minimum-time-to-repair-cars └── minimum-time-to-repair-cars.cpp ├── 2509-minimize-xor └── minimize-xor.cpp ├── 75-sort-colors ├── sort-colors.cpp └── sort-colors.java ├── 2533-bitwise-xor-of-all-pairings └── bitwise-xor-of-all-pairings.cpp ├── 953-reverse-only-letters └── reverse-only-letters.cpp ├── 1620-check-if-array-pairs-are-divisible-by-k └── check-if-array-pairs-are-divisible-by-k.cpp ├── 1951-find-the-winner-of-the-circular-game └── find-the-winner-of-the-circular-game.cpp ├── 1720-crawler-log-folder └── crawler-log-folder.cpp ├── 1114-binary-search-tree-to-greater-sum-tree └── binary-search-tree-to-greater-sum-tree.cpp ├── 1477-product-of-the-last-k-numbers └── product-of-the-last-k-numbers.cpp ├── 905-length-of-longest-fibonacci-subsequence └── length-of-longest-fibonacci-subsequence.cpp ├── 153-find-minimum-in-rotated-sorted-array └── find-minimum-in-rotated-sorted-array.cpp ├── 2132-convert-1d-array-into-2d-array └── convert-1d-array-into-2d-array.cpp ├── 2690-house-robber-iv └── house-robber-iv.cpp ├── 22-generate-parentheses ├── generate-parentheses.cpp └── README.md ├── 3384-minimum-number-of-operations-to-make-word-k-periodic └── minimum-number-of-operations-to-make-word-k-periodic.cpp ├── 2271-rearrange-array-elements-by-sign └── rearrange-array-elements-by-sign.cpp ├── 2456-construct-smallest-number-from-di-string └── construct-smallest-number-from-di-string.cpp ├── 3-longest-substring-without-repeating-characters └── longest-substring-without-repeating-characters.cpp ├── 1616-minimum-difference-between-largest-and-smallest-value-in-three-moves └── minimum-difference-between-largest-and-smallest-value-in-three-moves.cpp ├── 165-compare-version-numbers └── compare-version-numbers.cpp ├── 2707-merge-two-2d-arrays-by-summing-values └── merge-two-2d-arrays-by-summing-values.cpp ├── 678-valid-parenthesis-string └── valid-parenthesis-string.cpp ├── 1993-sum-of-all-subset-xor-totals └── sum-of-all-subset-xor-totals.cpp ├── 908-middle-of-the-linked-list └── middle-of-the-linked-list.cpp ├── 42-trapping-rain-water ├── trapping-rain-water.cpp └── README.md ├── 118-pascals-triangle ├── pascals-triangle.cpp └── README.md ├── 1321-get-equal-substrings-within-budget └── get-equal-substrings-within-budget.cpp ├── 1046-max-consecutive-ones-iii └── max-consecutive-ones-iii.cpp ├── 128-longest-consecutive-sequence ├── longest-consecutive-sequence.cpp └── README.md ├── 2145-grid-game └── grid-game.cpp ├── 3434-find-the-number-of-distinct-colors-among-the-balls └── find-the-number-of-distinct-colors-among-the-balls.cpp ├── 1802-number-of-students-unable-to-eat-lunch └── number-of-students-unable-to-eat-lunch.cpp ├── 206-reverse-linked-list └── reverse-linked-list.cpp ├── 3643-zero-array-transformation-ii └── zero-array-transformation-ii.cpp ├── 890-lemonade-change └── lemonade-change.cpp ├── 1128-remove-all-adjacent-duplicates-in-string └── remove-all-adjacent-duplicates-in-string.cpp ├── 3332-minimum-operations-to-exceed-threshold-value-ii └── minimum-operations-to-exceed-threshold-value-ii.cpp ├── 1553-count-triplets-that-can-form-two-arrays-of-equal-xor └── count-triplets-that-can-form-two-arrays-of-equal-xor.cpp ├── 1537-maximum-score-after-splitting-a-string └── maximum-score-after-splitting-a-string.cpp ├── 1037-minimum-number-of-k-consecutive-bit-flips └── minimum-number-of-k-consecutive-bit-flips.cpp ├── 350-intersection-of-two-arrays-ii └── intersection-of-two-arrays-ii.cpp ├── 2527-count-subarrays-with-fixed-bounds └── count-subarrays-with-fixed-bounds.cpp ├── 1516-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n └── the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.cpp ├── 31-next-permutation └── next-permutation.cpp ├── 463-island-perimeter └── island-perimeter.cpp ├── 680-valid-palindrome-ii ├── valid-palindrome-ii.cpp └── README.md ├── 2160-minimum-operations-to-make-a-uni-value-grid └── minimum-operations-to-make-a-uni-value-grid.cpp ├── 2573-remove-nodes-from-linked-list └── remove-nodes-from-linked-list.cpp ├── 14-longest-common-prefix ├── longest-common-prefix.cpp └── README.md ├── 2888-minimum-index-of-a-valid-split └── minimum-index-of-a-valid-split.cpp ├── 33-search-in-rotated-sorted-array └── search-in-rotated-sorted-array.cpp ├── 3657-check-if-grid-can-be-cut-into-sections └── check-if-grid-can-be-cut-into-sections.cpp ├── 74-search-a-2d-matrix └── search-a-2d-matrix.cpp ├── 1907-count-pairs-with-xor-in-a-range └── count-pairs-with-xor-in-a-range.cpp ├── 3372-longest-strictly-increasing-or-strictly-decreasing-subarray └── longest-strictly-increasing-or-strictly-decreasing-subarray.cpp ├── 264-ugly-number-ii ├── ugly-number-ii.cpp └── README.md ├── 2265-partition-array-according-to-given-pivot └── partition-array-according-to-given-pivot.cpp ├── 39-combination-sum └── combination-sum.cpp ├── 853-most-profit-assigning-work └── most-profit-assigning-work.cpp ├── 1217-relative-sort-array └── relative-sort-array.cpp ├── 205-isomorphic-strings ├── isomorphic-strings.py └── isomorphic-strings.cpp ├── 57-insert-interval └── insert-interval.cpp ├── 1450-delete-leaves-with-a-given-value └── delete-leaves-with-a-given-value.cpp ├── 2473-max-sum-of-a-pair-with-equal-sum-of-digits └── max-sum-of-a-pair-with-equal-sum-of-digits.cpp ├── 647-palindromic-substrings └── palindromic-substrings.cpp ├── 776-n-ary-tree-postorder-traversal └── n-ary-tree-postorder-traversal.cpp ├── 345-reverse-vowels-of-a-string ├── reverse-vowels-of-a-string.cpp └── README.md ├── 328-odd-even-linked-list └── odd-even-linked-list.cpp ├── 1333-sort-the-jumbled-numbers └── sort-the-jumbled-numbers.cpp ├── 145-binary-tree-postorder-traversal └── binary-tree-postorder-traversal.cpp ├── 8-string-to-integer-atoi └── string-to-integer-atoi.cpp ├── 3348-minimum-cost-walk-in-weighted-graph └── minimum-cost-walk-in-weighted-graph.cpp ├── 2793-count-the-number-of-complete-components └── count-the-number-of-complete-components.cpp ├── 1765-merge-in-between-linked-lists └── merge-in-between-linked-lists.cpp ├── 90-subsets-ii ├── subsets-ii.cpp └── README.md ├── 131-palindrome-partitioning ├── palindrome-partitioning.cpp └── README.md ├── 40-combination-sum-ii └── combination-sum-ii.cpp ├── 19-remove-nth-node-from-end-of-list └── remove-nth-node-from-end-of-list.cpp ├── 179-largest-number ├── largest-number.cpp └── README.md ├── 61-rotate-list ├── rotate-list.cpp └── README.md ├── 1034-subarrays-with-k-different-integers └── subarrays-with-k-different-integers.cpp ├── 1240-stone-game-ii └── stone-game-ii.cpp ├── 917-boats-to-save-people └── boats-to-save-people.cpp ├── 162-find-peak-element └── find-peak-element.cpp ├── 135-candy └── candy.cpp ├── 2454-largest-local-values-in-a-matrix └── largest-local-values-in-a-matrix.cpp ├── 2255-minimum-swaps-to-group-all-1s-together-ii └── minimum-swaps-to-group-all-1s-together-ii.cpp ├── 891-score-after-flipping-matrix └── score-after-flipping-matrix.cpp ├── 203-remove-linked-list-elements └── remove-linked-list-elements.cpp ├── 2696-the-number-of-beautiful-subsets └── the-number-of-beautiful-subsets.cpp ├── 670-maximum-swap ├── README.md └── maximum-swap.cpp ├── 1675-magnetic-force-between-two-balls └── magnetic-force-between-two-balls.cpp ├── 3351-maximize-happiness-of-selected-children └── maximize-happiness-of-selected-children.cpp ├── 539-minimum-time-difference ├── README.md └── minimum-time-difference.cpp ├── 719-find-k-th-smallest-pair-distance └── find-k-th-smallest-pair-distance.cpp ├── 2416-evaluate-boolean-binary-tree └── evaluate-boolean-binary-tree.cpp ├── 15-3sum └── 3sum.cpp ├── 404-sum-of-left-leaves ├── sum-of-left-leaves.cpp └── README.md ├── 907-koko-eating-bananas └── koko-eating-bananas.cpp ├── 50-powx-n └── powx-n.cpp ├── 1170-shortest-common-supersequence └── shortest-common-supersequence.cpp ├── 1256-rank-transform-of-an-array └── rank-transform-of-an-array.cpp ├── 5-longest-palindromic-substring ├── longest-palindromic-substring.cpp └── README.md ├── 623-add-one-row-to-tree └── add-one-row-to-tree.cpp ├── 1325-path-with-maximum-probability └── path-with-maximum-probability.cpp ├── 200-number-of-islands └── number-of-islands.cpp ├── 506-relative-ranks └── relative-ranks.cpp ├── 1030-smallest-string-starting-from-leaf └── smallest-string-starting-from-leaf.cpp ├── 1818-maximum-score-from-removing-substrings └── maximum-score-from-removing-substrings.cpp ├── 2581-divide-players-into-teams-of-equal-skill └── divide-players-into-teams-of-equal-skill.cpp ├── 2090-number-of-ways-to-arrive-at-destination └── number-of-ways-to-arrive-at-destination.cpp ├── 2379-maximum-total-importance-of-roads └── maximum-total-importance-of-roads.cpp ├── 1044-find-common-characters ├── README.md └── find-common-characters.cpp ├── 802-k-th-smallest-prime-fraction └── k-th-smallest-prime-fraction.cpp ├── 1138-grumpy-bookstore-owner └── grumpy-bookstore-owner.cpp ├── 2121-find-if-path-exists-in-graph └── find-if-path-exists-in-graph.cpp ├── 789-kth-largest-element-in-a-stream └── kth-largest-element-in-a-stream.cpp ├── 1915-check-if-one-string-swap-can-make-strings-equal └── check-if-one-string-swap-can-make-strings-equal.cpp ├── 664-strange-printer └── strange-printer.cpp ├── 1558-course-schedule-iv └── course-schedule-iv.cpp ├── 2-add-two-numbers └── add-two-numbers.cpp ├── 273-integer-to-english-words └── README.md ├── 1408-find-the-smallest-divisor-given-a-threshold └── find-the-smallest-divisor-given-a-threshold.cpp ├── LICENSE ├── 1431-all-ancestors-of-a-node-in-a-directed-acyclic-graph └── all-ancestors-of-a-node-in-a-directed-acyclic-graph.cpp ├── 820-find-eventual-safe-states └── find-eventual-safe-states.cpp ├── 409-longest-palindrome └── longest-palindrome.cpp ├── 921-spiral-matrix-iii └── spiral-matrix-iii.cpp ├── 79-word-search └── word-search.cpp ├── 523-continuous-subarray-sum └── continuous-subarray-sum.cpp ├── 1331-path-with-maximum-gold └── path-with-maximum-gold.cpp ├── 85-maximal-rectangle └── maximal-rectangle.cpp ├── 1093-recover-a-tree-from-preorder-traversal └── recover-a-tree-from-preorder-traversal.cpp ├── 2212-removing-minimum-and-maximum-from-array └── removing-minimum-and-maximum-from-array.cpp ├── 88-merge-sorted-array └── merge-sorted-array.cpp ├── 1876-map-of-highest-peak └── map-of-highest-peak.cpp ├── 1285-balance-a-binary-search-tree └── balance-a-binary-search-tree.cpp ├── 2163-kth-distinct-string-in-an-array └── kth-distinct-string-in-an-array.cpp ├── 1605-minimum-number-of-days-to-make-m-bouquets └── minimum-number-of-days-to-make-m-bouquets.cpp ├── 1549-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit └── longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp ├── 143-reorder-list └── reorder-list.cpp ├── 3227-find-missing-and-repeated-values └── find-missing-and-repeated-values.cpp ├── 2299-merge-nodes-in-between-zeros └── merge-nodes-in-between-zeros.cpp ├── 2764-maximum-number-of-fish-in-a-grid └── maximum-number-of-fish-in-a-grid.cpp ├── 863-sum-of-distances-in-tree └── sum-of-distances-in-tree.cpp └── 2802-find-the-punishment-number-of-an-integer └── find-the-punishment-number-of-an-integer.cpp /231-power-of-two/power-of-two.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | return n > 0 && not (n & n - 1); 5 | } 6 | }; -------------------------------------------------------------------------------- /2645-pass-the-pillow/pass-the-pillow.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int passThePillow(int n, int time) { 4 | return n - abs(n - 1 - time % (n * 2 - 2)); 5 | } 6 | }; -------------------------------------------------------------------------------- /1013-fibonacci-number/fibonacci-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int fib(int n) { 4 | if(n<=1) return n; 5 | return fib(n-1)+fib(n-2); 6 | 7 | 8 | } 9 | }; -------------------------------------------------------------------------------- /2649-count-total-number-of-colored-cells/count-total-number-of-colored-cells.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long coloredCells(int n) { 4 | return 1l * n * n + 1l * (n - 1) * (n - 1); 5 | } 6 | }; -------------------------------------------------------------------------------- /3676-smallest-number-with-all-set-bits/smallest-number-with-all-set-bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | 5 | int smallestNumber(int n) { 6 | return INT_MAX >> __builtin_clz(n) - 1; 7 | } 8 | }; -------------------------------------------------------------------------------- /136-single-number/single-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int ans=0; 5 | for(auto it:nums){ 6 | ans^=it; 7 | } 8 | return ans; 9 | } 10 | }; -------------------------------------------------------------------------------- /1916-find-center-of-star-graph/find-center-of-star-graph.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static int findCenter(vector>& edges) { 4 | return edges[0][0]==edges[1][0]?edges[0][0]:(edges[0][0]==edges[1][1]?edges[0][0]:edges[0][1]); 5 | } 6 | }; -------------------------------------------------------------------------------- /287-find-the-duplicate-number/find-the-duplicate-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | while(nums[0] != nums[nums[0]]){ 5 | swap(nums[0],nums[nums[0]]); 6 | } 7 | return nums[0]; 8 | 9 | } 10 | }; -------------------------------------------------------------------------------- /2308-divide-array-into-equal-pairs/divide-array-into-equal-pairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool divideArray(vector& nums) { 4 | int cnt[501] = {}; 5 | for (int n : nums) 6 | ++cnt[n]; 7 | return all_of(begin(cnt), end(cnt), [](int cnt){ return cnt % 2 == 0; }); 8 | } 9 | }; -------------------------------------------------------------------------------- /2792-neighboring-bitwise-xor/neighboring-bitwise-xor.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool doesValidArrayExist(vector& derived) { 4 | int xorSum = 0; 5 | for (int num : derived) { 6 | xorSum ^= num; 7 | } 8 | return xorSum == 0; 9 | } 10 | }; -------------------------------------------------------------------------------- /2128-reverse-prefix-of-word/reverse-prefix-of-word.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reversePrefix(string word, char ch) { 4 | int j = word.find(ch); 5 | if (j != -1) { 6 | reverse(word.begin(), word.begin() + j + 1); 7 | } 8 | return word; 9 | } 10 | }; -------------------------------------------------------------------------------- /1556-make-two-arrays-equal-by-reversing-subarrays/make-two-arrays-equal-by-reversing-subarrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canBeEqual(vector& target, vector& arr) { 4 | return unordered_multiset(arr.begin(), arr.end())==unordered_multiset(target.begin(), target.end()); 5 | } 6 | }; -------------------------------------------------------------------------------- /3447-clear-digits/clear-digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static string clearDigits(string& s) { 4 | int n=s.size(), j=0; 5 | for(int i=0; i0) j--; 7 | else s[j++]=s[i]; 8 | } 9 | s.resize(j); 10 | return s; 11 | } 12 | }; -------------------------------------------------------------------------------- /283-move-zeroes/move-zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void moveZeroes(vector& nums) { 4 | int i =0; 5 | for(int j =0 ; j>1; 9 | } 10 | return count; 11 | } 12 | }; -------------------------------------------------------------------------------- /268-missing-number/missing-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | int xor1 =0; 5 | int xor2 =0; 6 | 7 | int n = nums.size(); 8 | for(int i =0; i& A) { 4 | int s = 0, mi = 0, ma = 0; 5 | for (int& a : A) { 6 | s += a; 7 | mi = min(mi, s); 8 | ma = max(ma, s); 9 | } 10 | return ma - mi; 11 | } 12 | }; -------------------------------------------------------------------------------- /2614-maximum-count-of-positive-integer-and-negative-integer/maximum-count-of-positive-integer-and-negative-integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumCount(vector& nums) { 4 | int neg = lower_bound(nums.begin(), nums.end(), 0) - nums.begin(), pos = nums.end() - upper_bound(nums.begin(), nums.end(), 0); 5 | return max(neg, pos); 6 | } 7 | }; -------------------------------------------------------------------------------- /1137-height-checker/height-checker.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int heightChecker(vector& heights) { 4 | vector v(heights); 5 | sort(v.begin(),v.end()); 6 | int count = 0; 7 | for(int i=0;i& nums) { 5 | 6 | int maxS=INT_MIN; 7 | int sum=0; 8 | 9 | for(int i =0;i& colors, int k) { 4 | int n = colors.size(), res = 0, cnt = 1; 5 | for (int i = 0; i < n + k - 2; ++i) { 6 | cnt = colors[i % n] != colors[(i + 1) % n] ? cnt + 1 : 1; 7 | res += cnt >= k; 8 | } 9 | return res; 10 | } 11 | }; -------------------------------------------------------------------------------- /1927-maximum-ascending-subarray-sum/maximum-ascending-subarray-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxAscendingSum(vector& nums) { 4 | int curr = nums[0], ans = nums[0]; 5 | for (int i = 1; i < nums.size(); ++i) { 6 | curr = nums[i] > nums[i - 1] ? curr + nums[i] : nums[i]; 7 | ans = max(ans, curr); 8 | } 9 | return ans; 10 | } 11 | }; -------------------------------------------------------------------------------- /2478-longest-nice-subarray/longest-nice-subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestNiceSubarray(vector& nums) { 4 | int used = 0, j = 0, res = 0; 5 | for (int i = 0; i < nums.size(); ++i) { 6 | while ((used & nums[i]) != 0) 7 | used ^= nums[j++]; 8 | used |= nums[i]; 9 | res = max(res, i - j + 1); 10 | } 11 | return res; 12 | } 13 | }; -------------------------------------------------------------------------------- /3429-special-array-i/special-array-i.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static bool isArraySpecial(vector& nums) { 4 | int n=nums.size(); 5 | if (n==1) return 1; 6 | bool prev=nums[0]&1; 7 | for (int i=1; i& nums, int target) { 4 | int low=0; 5 | int high=nums.size()-1; 6 | 7 | while(low<=high){ 8 | int mid=low+(high-low)/2; 9 | if(nums[mid]==target) return mid; 10 | else if(nums[mid]>target) high=mid-1; 11 | else low=mid+1; 12 | } 13 | return -1; 14 | } 15 | }; -------------------------------------------------------------------------------- /344-reverse-string/reverse-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reverseString(vector& s) { 4 | reverseHelper(s, 0, s.size() - 1); 5 | } 6 | 7 | private: 8 | void reverseHelper(vector& s, int left, int right) { 9 | if (left >= right) return; 10 | 11 | swap(s[left], s[right]); 12 | reverseHelper(s, left + 1, right - 1); 13 | } 14 | }; -------------------------------------------------------------------------------- /476-number-complement/number-complement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int findComplement(int num) { 5 | int m=num; 6 | int mask=0; 7 | if(num==0){ 8 | return 1; 9 | } 10 | while(m!=0){ 11 | mask=(mask<<1) | 1; 12 | m=m >> 1; 13 | } 14 | int ans= (~num) & mask; 15 | return ans; 16 | 17 | } 18 | }; -------------------------------------------------------------------------------- /121-best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int mini = prices[0], profit =0; 5 | for(int i=0; i= numExchange) { 7 | totalBottles += numBottles / numExchange; 8 | numBottles = (numBottles / numExchange) + (numBottles % numExchange); 9 | } 10 | 11 | return totalBottles; 12 | } 13 | }; -------------------------------------------------------------------------------- /26-remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int i =0; 5 | int n = nums.size(); 6 | for(int j =1;j partitionLabels(string S) { 4 | vector res, pos(26, 0); 5 | for (auto i = 0; i < S.size(); ++i) pos[S[i] - 'a'] = i; 6 | for (auto i = 0, idx = INT_MIN, last_i = 0; i < S.size(); ++i) { 7 | idx = max(idx, pos[S[i] - 'a']); 8 | if (idx == i) res.push_back(i - exchange(last_i, i + 1) + 1); 9 | } 10 | return res; 11 | } 12 | }; -------------------------------------------------------------------------------- /2463-minimum-recolors-to-get-k-consecutive-black-blocks/minimum-recolors-to-get-k-consecutive-black-blocks.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumRecolors(string blocks, int k) { 4 | int b = 0, mb = 0; 5 | for (int i = 0; i < blocks.size(); ++i) { 6 | b += blocks[i] == 'B'; 7 | if (i >= k) 8 | b -= blocks[i - k] == 'B'; 9 | mb = max(b, mb); 10 | } 11 | return k - mb; 12 | } 13 | }; -------------------------------------------------------------------------------- /3379-score-of-a-string/score-of-a-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int scoreOfString(string& s) { 4 | int n=s.size(); 5 | int ans=0; 6 | for(int i=1; i& nums) { 4 | string ans=""; 5 | for(int i=0; i A, int k) { 4 | long long res = 0, n = A.size() - 1; 5 | for (int i = 0; i < n; ++i) 6 | A[i] += A[i + 1]; 7 | A.pop_back(); 8 | sort(A.begin(), A.end()); 9 | for (int i = 0; i < k - 1; ++i) 10 | res += A[n - 1 - i] - A[i]; 11 | return res; 12 | } 13 | }; -------------------------------------------------------------------------------- /69-sqrtx/sqrtx.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int mySqrt(int x) { 4 | int low =0 , high = x; 5 | long long ans = 0; 6 | while(low<=high){ 7 | long long mid = low + (high - low)/2; 8 | long long val = mid*mid; 9 | if(val<=x){ 10 | ans = mid; 11 | low=mid+1; 12 | } 13 | else{ 14 | high = mid-1; } 15 | } 16 | return ans; 17 | } 18 | }; -------------------------------------------------------------------------------- /237-delete-node-in-a-linked-list/delete-node-in-a-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | void deleteNode(ListNode* node) { 12 | 13 | node->val = node->next->val; 14 | node->next = node->next->next; 15 | 16 | } 17 | }; -------------------------------------------------------------------------------- /3154-maximum-value-of-an-ordered-triplet-i/maximum-value-of-an-ordered-triplet-i.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long maximumTripletValue(vector& A) { 4 | long long res = 0; 5 | int maxa = 0, maxab = 0; 6 | for (int&a : A) { 7 | res = max(res, 1LL * maxab * a); 8 | maxab = max(maxab, maxa - a); 9 | maxa = max(maxa, a); 10 | } 11 | return res; 12 | } 13 | }; -------------------------------------------------------------------------------- /3430-count-days-without-meetings/count-days-without-meetings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countDays(int days, vector>& meets) { 4 | int res = 0, cur = 1; 5 | sort(begin(meets), end(meets)); 6 | for (const auto &m : meets) { 7 | res += max(0, m[0] - cur); 8 | cur = max(cur, m[1] + 1); 9 | if (cur > days) 10 | break; 11 | } 12 | return res + max(0, days - cur + 1); 13 | } 14 | }; -------------------------------------------------------------------------------- /3621-minimum-operations-to-make-array-values-equal-to-k/minimum-operations-to-make-array-values-equal-to-k.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector& nums, int k) { 4 | unordered_set st; 5 | for (int x : nums) { 6 | if (x < k) { 7 | return -1; 8 | } else if (x > k) { 9 | st.insert(x); 10 | } 11 | } 12 | return st.size(); 13 | } 14 | }; -------------------------------------------------------------------------------- /185-department-top-three-salaries/department-top-three-salaries.sql: -------------------------------------------------------------------------------- 1 | -- Write your MySQL query statement below 2 | SELECT Department, Employee, Salary 3 | FROM ( 4 | SELECT 5 | d.name AS Department, 6 | e.name AS Employee, 7 | e.salary AS Salary, 8 | DENSE_RANK() OVER (PARTITION BY d.name ORDER BY Salary DESC) AS rnk 9 | FROM Employee e 10 | JOIN Department d 11 | ON e.departmentId = d.id 12 | ) AS rnk_tbl 13 | WHERE rnk <= 3; -------------------------------------------------------------------------------- /2148-minimum-number-of-moves-to-seat-everyone/minimum-number-of-moves-to-seat-everyone.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minMovesToSeat(vector& seats, vector& students) { 4 | sort(seats.begin(), seats.end()); 5 | sort(students.begin(), students.end()); 6 | int moves = 0; 7 | for( int i=0; i& nums, int k) { 4 | unordered_mapmpp; 5 | mpp[0]=1; 6 | int preSum =0 , cnt =0; 7 | 8 | for(int i=0; i> subsets(vector& nums) { 4 | int n = nums.size(), p = 1 << n; 5 | vector> subs(p); 6 | for (int i = 0; i < p; i++) { 7 | for (int j = 0; j < n; j++) { 8 | if ((i >> j) & 1) { 9 | subs[i].push_back(nums[j]); 10 | } 11 | } 12 | } 13 | return subs; 14 | } 15 | }; -------------------------------------------------------------------------------- /1878-check-if-array-is-sorted-and-rotated/check-if-array-is-sorted-and-rotated.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool check(vector& nums) { 4 | int count = 0 ; 5 | if (nums[0] < nums[nums.size()-1]) count++ ; 6 | for (int i=1; i 1) return false ; 10 | } 11 | } 12 | return true ; 13 | } 14 | }; -------------------------------------------------------------------------------- /442-find-all-duplicates-in-an-array/find-all-duplicates-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findDuplicates(vector& nums) { 4 | vectorans; 5 | int n=size(nums); 6 | for(int i=0;i& nums) { 4 | int maxi = INT_MIN; 5 | int pre =1, suff =1; 6 | for(int i =0; i& nums) { 5 | sort(nums.begin(),nums.end()); 6 | int ans = 0; 7 | for(int i=1;i>& matrix, int target) { 4 | int n = matrix.size(); 5 | int m = matrix[0].size(); 6 | 7 | int row=0; 8 | int col=m-1; 9 | while(row=0){ 10 | if(matrix[row][col]==target)return true; 11 | else if(matrix[row][col]& nums) { 4 | unordered_map freq; 5 | long long goodPairs = 0, n = nums.size(); 6 | 7 | for (int i = 0; i < n; i++) { 8 | int key = nums[i] - i; 9 | goodPairs += freq[key]; 10 | freq[key]++; 11 | } 12 | 13 | return (n * (n - 1)) / 2 - goodPairs; 14 | } 15 | }; -------------------------------------------------------------------------------- /2195-time-needed-to-buy-tickets/time-needed-to-buy-tickets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int timeRequiredToBuy(vector& tickets, int k) { 4 | int total = 0; 5 | 6 | for (int i = 0; i < tickets.size(); ++i) { 7 | if (i <= k) { 8 | total += min(tickets[i], tickets[k]); 9 | } else { 10 | total += min(tickets[i], tickets[k] - 1); 11 | } 12 | } 13 | 14 | return total; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /35-search-insert-position/search-insert-position.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | int low =0, high = nums.size()-1; 5 | int ans = nums.size(); 6 | while(low<=high){ 7 | 8 | int mid = low + (high-low)/2; 9 | if(nums[mid]>= target){ 10 | ans = mid; 11 | high = mid-1; 12 | } 13 | else low = mid+1; 14 | } 15 | return ans; 16 | } 17 | 18 | }; -------------------------------------------------------------------------------- /1631-number-of-sub-arrays-with-odd-sum/number-of-sub-arrays-with-odd-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numOfSubarrays(vector& arr) { 4 | int odd=0,even=0,answer=0,modulus=(int)1e9+7; 5 | for(auto number:arr){ 6 | if(number%2==0)even++; 7 | else{ 8 | swap(odd,even); 9 | odd++; 10 | } 11 | answer=(answer%modulus+odd%modulus)%modulus; 12 | } 13 | return answer; 14 | } 15 | }; -------------------------------------------------------------------------------- /125-valid-palindrome/valid-palindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(string s) { 4 | int start=0; 5 | int end=s.size()-1; 6 | while(start<=end){ 7 | if(!isalnum(s[start])){start++; continue;} 8 | if(!isalnum(s[end])){end--;continue;} 9 | if(tolower(s[start])!=tolower(s[end]))return false; 10 | else{ 11 | start++; 12 | end--; 13 | } 14 | } 15 | return true; 16 | } 17 | }; -------------------------------------------------------------------------------- /1460-number-of-substrings-containing-all-three-characters/number-of-substrings-containing-all-three-characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfSubstrings(string s) { 4 | int count[3] = {0, 0, 0},res = 0 , i = 0, n = s.length(); 5 | for (int j = 0; j < n; ++j) { 6 | ++count[s[j] - 'a']; 7 | while (count[0] && count[1] && count[2]) 8 | --count[s[i++] - 'a']; 9 | res += i; 10 | } 11 | return res; 12 | } 13 | }; -------------------------------------------------------------------------------- /3475-minimum-operations-to-make-binary-array-elements-equal-to-one-i/minimum-operations-to-make-binary-array-elements-equal-to-one-i.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector& nums) { 4 | int sz = nums.size(), res = 0; 5 | for (int i = 0; i + 2 < sz; ++i) 6 | if (nums[i] == 0) { 7 | ++res; 8 | nums[i + 1] = !nums[i + 1]; 9 | nums[i + 2] = !nums[i + 2]; 10 | } 11 | return nums[sz - 1] && nums[sz - 2] ? res : -1; 12 | } 13 | }; -------------------------------------------------------------------------------- /1370-count-number-of-nice-subarrays/count-number-of-nice-subarrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfSubarrays(vector& nums, int k) { 4 | int n = nums.size(); 5 | vector cnt(n + 1, 0); 6 | cnt[0] = 1; 7 | int ans = 0, t = 0; 8 | for (int v : nums) { 9 | t += v & 1; 10 | if (t - k >= 0) { 11 | ans += cnt[t - k]; 12 | } 13 | cnt[t]++; 14 | } 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /1737-maximum-nesting-depth-of-the-parentheses/maximum-nesting-depth-of-the-parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDepth(string s) { 4 | int count = 0; 5 | int max_num = 0; 6 | for (char c : s) { 7 | if (c == '(') { 8 | count++; 9 | if (max_num < count) 10 | max_num = count; 11 | } else if (c == ')') { 12 | count--; 13 | } 14 | } 15 | return max_num; 16 | } 17 | }; -------------------------------------------------------------------------------- /455-assign-cookies/assign-cookies.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findContentChildren(vector& students, vector& cookies) { 4 | int n = students.size(); 5 | int m = cookies.size(); 6 | 7 | sort(students.begin(), students.end()); 8 | sort(cookies.begin(), cookies.end()); 9 | 10 | int l = 0, r = 0; 11 | while (l < n && r < m) { 12 | if (cookies[r] >= students[l]) l++; 13 | r++; 14 | } 15 | return l; 16 | } 17 | }; -------------------------------------------------------------------------------- /1889-check-if-number-is-a-sum-of-powers-of-three/check-if-number-is-a-sum-of-powers-of-three.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkPowersOfThree(int n) { 4 | while (n > 0) { 5 | // Check if this power should be used twice 6 | if (n % 3 == 2) return false; 7 | 8 | // Divide n by 3 to move to the next greater power 9 | n /= 3; 10 | } 11 | 12 | // The ternary representation of n consists only of 0s and 1s 13 | return true; 14 | } 15 | }; -------------------------------------------------------------------------------- /1236-n-th-tribonacci-number/n-th-tribonacci-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int tribonacci(int n) { 4 | if (n == 0) { 5 | return 0; 6 | } else if (n == 1 || n == 2) { 7 | return 1; 8 | } 9 | 10 | std::vector dp(n + 1); 11 | dp[1] = 1; 12 | dp[2] = 1; 13 | 14 | for (int i = 3; i <= n; i++) { 15 | dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]; 16 | } 17 | 18 | return dp[n]; 19 | } 20 | }; -------------------------------------------------------------------------------- /330-patching-array/patching-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minPatches(vector& nums, int n) { 4 | long long miss = 1; 5 | int result = 0; 6 | size_t i = 0; 7 | 8 | while (miss <= n) { 9 | if (i < nums.size() && nums[i] <= miss) { 10 | miss += nums[i]; 11 | i++; 12 | } else { 13 | miss += miss; 14 | result++; 15 | } 16 | } 17 | 18 | return result; 19 | } 20 | }; -------------------------------------------------------------------------------- /485-max-consecutive-ones/max-consecutive-ones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxConsecutiveOnes(vector& nums) { 4 | int max_count = 0; 5 | int current_count = 0; 6 | 7 | for (int num : nums) { 8 | if (num == 1) { 9 | current_count++; 10 | max_count = max(max_count, current_count); 11 | } else { 12 | current_count = 0; 13 | } 14 | } 15 | 16 | return max_count; 17 | } 18 | }; -------------------------------------------------------------------------------- /1520-number-of-steps-to-reduce-a-number-in-binary-representation-to-one/number-of-steps-to-reduce-a-number-in-binary-representation-to-one.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numSteps(string s) { 4 | int carry = 0, steps = 0; 5 | for(int i = s.length() - 1; i > 0; i--) { 6 | if((s[i] - '0') + carry == 1) { 7 | steps += 2; 8 | carry = 1; 9 | } else { 10 | steps++; 11 | } 12 | } 13 | return steps + carry; 14 | } 15 | }; -------------------------------------------------------------------------------- /169-majority-element/majority-element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | int ele; 5 | int count =0; 6 | for(int i=0; i& nums, int k) { 4 | int n = nums.size(); 5 | k = k % n; // Ensure k is within the range [0, n) 6 | 7 | // Reverse the entire array 8 | 9 | reverse(nums.begin(), nums.end()); 10 | // Reverse the first k elements 11 | reverse(nums.begin(), nums.begin() + k); 12 | 13 | // Reverse the rest of the elements after k 14 | reverse(nums.begin() + k, nums.end()); 15 | } 16 | }; -------------------------------------------------------------------------------- /2524-largest-positive-integer-that-exists-with-its-negative/largest-positive-integer-that-exists-with-its-negative.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxK(std::vector& nums) { 4 | std::sort(nums.begin(), nums.end()); 5 | int n = nums.size(); 6 | for (int i = n-1; i >= 0; i--) { 7 | if (nums[i] > 0 && std::binary_search(nums.begin(), nums.end(), -nums[i])) { 8 | return nums[i]; 9 | } 10 | } 11 | return -1; // If no such pair found 12 | } 13 | }; -------------------------------------------------------------------------------- /1-two-sum/two-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | int n = nums.size(); 5 | unordered_map hash; 6 | 7 | 8 | for(int i=0;i frequencySort(vector& nums) { 4 | vector count(201, 0); 5 | for (int num : nums) { 6 | count[num + 100]++; 7 | } 8 | sort(nums.begin(), nums.end(), [&](int a, int b) { 9 | if (count[a + 100] == count[b + 100]) 10 | return a > b; 11 | return count[a + 100] < count[b + 100]; 12 | }); 13 | return nums; 14 | } 15 | }; -------------------------------------------------------------------------------- /2502-sort-the-people/sort-the-people.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortPeople(vector& names, vector& heights) { 4 | int n = names.size(); 5 | unordered_map mapping; 6 | 7 | for (int i = 0; i < n; ++i) { 8 | mapping[heights[i]] = names[i]; 9 | } 10 | 11 | sort(heights.rbegin(), heights.rend()); 12 | 13 | for (int i = 0; i < n; ++i) { 14 | names[i] = mapping[heights[i]]; 15 | } 16 | 17 | return names; 18 | } 19 | }; -------------------------------------------------------------------------------- /2572-append-characters-to-string-to-make-subsequence/append-characters-to-string-to-make-subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int appendCharacters(string s, string t) { 4 | int s_index = 0, t_index = 0; 5 | int s_length = s.length(), t_length = t.length(); 6 | 7 | while (s_index < s_length && t_index < t_length) { 8 | if (s[s_index] == t[t_index]) { 9 | t_index++; 10 | } 11 | s_index++; 12 | } 13 | 14 | return t_length - t_index; 15 | } 16 | }; -------------------------------------------------------------------------------- /260-single-number-iii/single-number-iii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector singleNumber(vector& nums) { 4 | long xorr=0; 5 | for(int i =0; ib2) return{b2,b1}; 15 | return {b1,b2}; 16 | } 17 | }; -------------------------------------------------------------------------------- /1756-minimum-deletions-to-make-string-balanced/minimum-deletions-to-make-string-balanced.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumDeletions(string s) { 4 | int n = s.size(); 5 | int f[n + 1]; 6 | memset(f, 0, sizeof(f)); 7 | int b = 0; 8 | for (int i = 1; i <= n; ++i) { 9 | if (s[i - 1] == 'b') { 10 | f[i] = f[i - 1]; 11 | ++b; 12 | } else { 13 | f[i] = min(f[i - 1] + 1, b); 14 | } 15 | } 16 | return f[n]; 17 | } 18 | }; -------------------------------------------------------------------------------- /1335-maximum-candies-allocated-to-k-children/maximum-candies-allocated-to-k-children.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumCandies(vector& A, long long k) { 4 | int left = 0, right = 1e7; 5 | while (left < right) { 6 | long sum = 0, mid = (left + right + 1) / 2; 7 | for (int& a : A) { 8 | sum += a / mid; 9 | } 10 | if (k > sum) 11 | right = mid - 1; 12 | else 13 | left = mid; 14 | } 15 | return left; 16 | } 17 | }; -------------------------------------------------------------------------------- /2665-minimum-time-to-repair-cars/minimum-time-to-repair-cars.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long repairCars(vector& A, int cars) { 4 | long long left = 1, right = 1L * A[0] * cars * cars; 5 | while (left < right) { 6 | long long mid = (left + right) / 2, cur = 0; 7 | for (int a : A) 8 | cur += int(sqrt(1.0 * mid / a)); 9 | if (cur < cars) 10 | left = mid + 1; 11 | else 12 | right = mid; 13 | } 14 | return left; 15 | } 16 | }; -------------------------------------------------------------------------------- /2509-minimize-xor/minimize-xor.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimizeXor(int num1, int num2) { 4 | int a = __builtin_popcount(num1); 5 | int b = __builtin_popcount(num2); 6 | int res = num1; 7 | for (int i = 0; i < 32; ++i) { 8 | if (a > b && (1 << i) & num1) { 9 | res ^= 1 << i; 10 | --a; 11 | } 12 | if (a < b && !((1 << i) & num1)) { 13 | res ^= 1 << i; 14 | ++a; 15 | } 16 | } 17 | return res; 18 | } 19 | }; -------------------------------------------------------------------------------- /75-sort-colors/sort-colors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(vector& nums) { 4 | int low = 0, mid =0, high = nums.size()-1; 5 | 6 | while(mid<=high){ 7 | if(nums[mid]==0){ 8 | swap(nums[mid], nums[low]); 9 | mid++, low++; 10 | } 11 | else if(nums[mid]==1){ 12 | 13 | mid++; 14 | } 15 | else{ 16 | swap(nums[mid], nums[high]); 17 | high--; 18 | } 19 | } 20 | } 21 | }; -------------------------------------------------------------------------------- /2533-bitwise-xor-of-all-pairings/bitwise-xor-of-all-pairings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int xorAllNums(vector& nums1, vector& nums2) { 4 | int c1 = nums1.size(); 5 | int c2 = nums2.size(); 6 | int x1 = 0, x2 = 0; 7 | 8 | if (c1 % 2 != 0) { 9 | for (int num : nums2) { 10 | x2 ^= num; 11 | } 12 | } 13 | if (c2 % 2 != 0) { 14 | for (int num : nums1) { 15 | x1 ^= num; 16 | } 17 | } 18 | return x1 ^ x2; 19 | } 20 | }; -------------------------------------------------------------------------------- /953-reverse-only-letters/reverse-only-letters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseOnlyLetters(string s) { 4 | 5 | int i=0, j= s.size()-1; 6 | 7 | while(i& arr, int k) { 4 | vector freq(k, 0); 5 | 6 | for (int num : arr) { 7 | int remainder = ((num % k) + k) % k; 8 | freq[remainder]++; 9 | } 10 | 11 | if (freq[0] % 2 != 0) return false; 12 | 13 | for (int i = 1; i <= k / 2; i++) { 14 | if (freq[i] != freq[k - i]) return false; 15 | } 16 | 17 | return true; 18 | } 19 | }; -------------------------------------------------------------------------------- /1951-find-the-winner-of-the-circular-game/find-the-winner-of-the-circular-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findTheWinner(int n, int k) { 4 | std::vector circle; 5 | for (int i = 1; i <= n; ++i) { 6 | circle.push_back(i); 7 | } 8 | int cur_ind = 0; 9 | 10 | while (circle.size() > 1) { 11 | int next_to_remove = (cur_ind + k - 1) % circle.size(); 12 | circle.erase(circle.begin() + next_to_remove); 13 | cur_ind = next_to_remove; 14 | } 15 | 16 | return circle[0]; 17 | } 18 | }; -------------------------------------------------------------------------------- /1720-crawler-log-folder/crawler-log-folder.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static int minOperations(vector& logs) { 4 | int level=0; 5 | for(auto& dir: logs){ 6 | if (dir=="../") 7 | level-=(level>0); 8 | else if (dir!="./") 9 | level++; 10 | // cout<right); // Traverse the right subtree 8 | sum += root->val; // Update the sum 9 | root->val = sum; // Update the current node's value 10 | traverse(root->left); // Traverse the left subtree 11 | } 12 | } 13 | 14 | public: 15 | TreeNode* bstToGst(TreeNode* root) { 16 | traverse(root); 17 | return root; 18 | } 19 | }; -------------------------------------------------------------------------------- /1477-product-of-the-last-k-numbers/product-of-the-last-k-numbers.cpp: -------------------------------------------------------------------------------- 1 | class ProductOfNumbers { 2 | public: 3 | vector A = {1}; 4 | void add(int a) { 5 | if (a) 6 | A.push_back(A.back() * a); 7 | else 8 | A = {1}; 9 | } 10 | 11 | int getProduct(int k) { 12 | return k < A.size() ? A.back() / A[A.size() - k - 1] : 0; 13 | } 14 | }; 15 | 16 | /** 17 | * Your ProductOfNumbers object will be instantiated and called as such: 18 | * ProductOfNumbers* obj = new ProductOfNumbers(); 19 | * obj->add(num); 20 | * int param_2 = obj->getProduct(k); 21 | */ -------------------------------------------------------------------------------- /905-length-of-longest-fibonacci-subsequence/length-of-longest-fibonacci-subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lenLongestFibSubseq(vector& A) { 4 | unordered_set s(A.begin(), A.end()); 5 | int res = 0; 6 | for (int i = 0; i < A.size(); ++i) { 7 | for (int j = i + 1; j < A.size(); ++j) { 8 | int a = A[i], b = A[j], l = 2; 9 | while (s.count(a + b)) 10 | b = a + b, a = b - a, l++; 11 | res = max(res, l); 12 | } 13 | } 14 | return res > 2 ? res : 0; 15 | } 16 | }; -------------------------------------------------------------------------------- /153-find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int low =0, high = nums.size()-1; 5 | int ans = INT_MAX; 6 | 7 | while(low<=high){ 8 | int mid = low + (high-low)/2; 9 | 10 | if(nums[low]<=nums[mid]){ 11 | ans = min(ans,nums[low]); 12 | low = mid+1; 13 | } 14 | else{ 15 | ans = min(nums[mid],ans); 16 | high = mid-1; 17 | } 18 | } 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /2132-convert-1d-array-into-2d-array/convert-1d-array-into-2d-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static vector> construct2DArray(vector& original, int m, int n) { 4 | const int sz=original.size(); 5 | if (sz!=m*n) return {}; 6 | vector> ans(m); 7 | for(int i=0; i& A, int k) { 4 | int left = 1, right = 1e9, n = A.size(); 5 | while (left < right) { 6 | int mid = (left + right) / 2, take = 0; 7 | for (int i = 0; i < n; ++i) 8 | if (A[i] <= mid) { 9 | take += 1; 10 | i++; 11 | } 12 | if (take >= k) 13 | right = mid; 14 | else 15 | left = mid + 1; 16 | } 17 | return left; //left == right 18 | } 19 | }; -------------------------------------------------------------------------------- /22-generate-parentheses/generate-parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void func(int open, int close, int n, string s , vector&ans){ 4 | if(open==close && (open+close)==2*n){ 5 | ans.push_back(s); 6 | return; 7 | } 8 | if(open generateParenthesis(int n) { 17 | vectorans; 18 | func(0,0,n,"",ans); 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /3384-minimum-number-of-operations-to-make-word-k-periodic/minimum-number-of-operations-to-make-word-k-periodic.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumOperationsToMakeKPeriodic(string word, int k) { 4 | int n = word.size(); 5 | unordered_map freq; 6 | 7 | for (int i = 0; i < n; i += k) { 8 | string segment = word.substr(i, k); 9 | freq[segment]++; 10 | } 11 | 12 | int maxFreq = 0; 13 | for (const auto& p : freq) { 14 | maxFreq = max(maxFreq, p.second); 15 | } 16 | 17 | return (n / k) - maxFreq; 18 | } 19 | }; -------------------------------------------------------------------------------- /2271-rearrange-array-elements-by-sign/rearrange-array-elements-by-sign.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector rearrangeArray(vector& nums) { 4 | int n = nums.size(); 5 | vectorans(n, 0); 6 | int positiveIndex = 0, negativeIndex = 1; 7 | 8 | for(int i = 0; i < n; i++) { 9 | if(nums[i] < 0) { 10 | ans[negativeIndex] = nums[i]; 11 | negativeIndex += 2; 12 | } else { 13 | ans[positiveIndex] = nums[i]; 14 | positiveIndex += 2; 15 | } 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /2456-construct-smallest-number-from-di-string/construct-smallest-number-from-di-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string smallestNumber(string pattern) { 4 | int n = pattern.length(); 5 | string result = ""; 6 | int stack[n + 1]; 7 | int index = 0; 8 | 9 | for (int i = 0; i <= n; i++) { 10 | stack[index++] = i + 1; 11 | 12 | if (i == n || pattern[i] == 'I') { 13 | while (index > 0) { 14 | result += to_string(stack[--index]); 15 | } 16 | } 17 | } 18 | 19 | return result; 20 | } 21 | }; -------------------------------------------------------------------------------- /3-longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int lengthOfLongestSubstring(string& s){ 4 | int n = s.size(); 5 | 6 | int hash[256]; 7 | for(int i =0; i<256; i++){ 8 | hash[i]=-1; 9 | } 10 | int l =0, r=0, maxLen=0; 11 | while (r& nums) { 4 | 5 | sort(nums.begin(),nums.end()); 6 | 7 | int minVal = INT_MAX; 8 | 9 | int n = nums.size(); 10 | 11 | if(n <= 4) return 0; 12 | 13 | minVal = min(minVal, nums[n-4] - nums[0]); 14 | minVal = min(minVal, nums[n-1] - nums[3]); 15 | minVal = min(minVal, nums[n-2] - nums[2]); 16 | minVal = min(minVal, nums[n-3] - nums[1]); 17 | 18 | return minVal; 19 | 20 | } 21 | }; -------------------------------------------------------------------------------- /165-compare-version-numbers/compare-version-numbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static int compareVersion(string& v1, string& v2) { 4 | const int n1=v1.size(), n2=v2.size(); 5 | int x1=0, x2=0; 6 | for(int i=0, j=0; ix2) return 1; 15 | x1=0; 16 | x2=0; 17 | } 18 | return 0; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /2707-merge-two-2d-arrays-by-summing-values/merge-two-2d-arrays-by-summing-values.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> mergeArrays(vector>& n1, vector>& n2) { 4 | int i = 0, j = 0, sz1 = n1.size(), sz2 = n2.size(); 5 | vector> res; 6 | while (i < sz1 || j < sz2) { 7 | int id = min(i < sz1 ? n1[i][0] : INT_MAX, j < sz2 ? n2[j][0] : INT_MAX); 8 | res.push_back({id, 0}); 9 | if (i < sz1 && n1[i][0] == id) 10 | res.back()[1] += n1[i++][1]; 11 | if (j < sz2 && n2[j][0] == id) 12 | res.back()[1] += n2[j++][1]; 13 | } 14 | return res; 15 | } 16 | }; -------------------------------------------------------------------------------- /678-valid-parenthesis-string/valid-parenthesis-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkValidString(string s) { 4 | int leftMin = 0, leftMax = 0; 5 | 6 | for (char c : s) { 7 | if (c == '(') { 8 | leftMin++; 9 | leftMax++; 10 | } else if (c == ')') { 11 | leftMin--; 12 | leftMax--; 13 | } else { 14 | leftMin--; 15 | leftMax++; 16 | } 17 | if (leftMax < 0) return false; 18 | if (leftMin < 0) leftMin = 0; 19 | } 20 | 21 | return leftMin == 0; 22 | } 23 | }; -------------------------------------------------------------------------------- /1993-sum-of-all-subset-xor-totals/sum-of-all-subset-xor-totals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subsetXORSum(vector& nums) { 4 | int n = nums.size(); 5 | int totalSum = 0; 6 | // Iterate through all possible subsets 7 | for (int i = 0; i < (1 << n); i++) { 8 | int subsetXor = 0; 9 | for (int j = 0; j < n; j++) { 10 | // Check if the j-th element is in the i-th subset 11 | if (i & (1 << j)) { 12 | subsetXor ^= nums[j]; 13 | } 14 | } 15 | totalSum += subsetXor; 16 | } 17 | return totalSum; 18 | } 19 | }; -------------------------------------------------------------------------------- /908-middle-of-the-linked-list/middle-of-the-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* middleNode(ListNode* head) { 14 | ListNode* fast = head; 15 | ListNode* slow=head; 16 | while(fast && fast->next){ 17 | fast=fast->next->next; 18 | slow=slow->next; 19 | } 20 | return slow; 21 | } 22 | }; -------------------------------------------------------------------------------- /42-trapping-rain-water/trapping-rain-water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trap(std::vector& height) { 4 | int i = 0, left_max = height[0], sum = 0; 5 | int j = height.size() - 1, right_max = height[j]; 6 | while (i < j) { 7 | if (left_max <= right_max) { 8 | sum += (left_max - height[i]); 9 | i++; 10 | left_max = std::max(left_max, height[i]); 11 | } else { 12 | sum += (right_max - height[j]); 13 | j--; 14 | right_max = std::max(right_max, height[j]); 15 | } 16 | } 17 | return sum; 18 | } 19 | }; -------------------------------------------------------------------------------- /118-pascals-triangle/pascals-triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | private: 4 | vectorgenerateRow(int row){ 5 | vectoransRow; 6 | ansRow.push_back(1); 7 | long long ans =1; 8 | for(int col =1; col> generate(int numRows) { 17 | vector>pascalTriangle; 18 | for(int row=1; row<=numRows; row++){ 19 | pascalTriangle.push_back(generateRow(row)); 20 | } 21 | return pascalTriangle; 22 | } 23 | }; -------------------------------------------------------------------------------- /1321-get-equal-substrings-within-budget/get-equal-substrings-within-budget.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int equalSubstring(string s, string t, int maxCost) { 4 | int n = s.size(); 5 | int start = 0; 6 | int current_cost = 0; 7 | int max_length = 0; 8 | 9 | for (int end = 0; end < n; ++end) { 10 | current_cost += abs(s[end] - t[end]); 11 | 12 | while (current_cost > maxCost) { 13 | current_cost -= abs(s[start] - t[start]); 14 | ++start; 15 | } 16 | 17 | max_length = max(max_length, end - start + 1); 18 | } 19 | 20 | return max_length; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /75-sort-colors/sort-colors.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void sortColors(int[] nums) { 3 | int low = 0, mid = 0, high = nums.length - 1; 4 | while (mid <= high) { 5 | if (nums[mid] == 0) { 6 | swap(nums, low, mid); 7 | low++; 8 | mid++; 9 | } else if (nums[mid] == 1) { 10 | mid++; 11 | } else { 12 | swap(nums, mid, high); 13 | high--; 14 | } 15 | } 16 | } 17 | 18 | private void swap(int[] nums, int i, int j) { 19 | int temp = nums[i]; 20 | nums[i] = nums[j]; 21 | nums[j] = temp; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /1046-max-consecutive-ones-iii/max-consecutive-ones-iii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestOnes(vector& nums, int k) { 4 | int n = nums.size(); 5 | int l = 0, r = 0; 6 | int zeros = 0, maxLen = 0; 7 | 8 | while (r < n) { 9 | if (nums[r] == 0) zeros++; 10 | if (zeros > k) { 11 | if (nums[l] == 0) { 12 | zeros--; 13 | } 14 | l++; 15 | } 16 | if (zeros <= k) { 17 | int len = r - l + 1; 18 | maxLen = max(len, maxLen); 19 | } 20 | r++; 21 | } 22 | return maxLen; 23 | } 24 | }; -------------------------------------------------------------------------------- /128-longest-consecutive-sequence/longest-consecutive-sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestConsecutive(vector& nums) { 4 | if(nums.size()==0)return 0; 5 | 6 | 7 | unordered_set st(nums.begin(), nums.end()); 8 | int longest = 0; 9 | 10 | 11 | for(auto it :st){ 12 | if(st.find(it-1)== st.end()){ 13 | int cnt = 1; 14 | int x = it; 15 | while(st.find(x+1)!=st.end()){ 16 | x++; 17 | cnt++; 18 | } 19 | longest = max(cnt,longest); 20 | } 21 | } 22 | return longest; 23 | } 24 | }; -------------------------------------------------------------------------------- /2145-grid-game/grid-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long gridGame(vector>& grid) { 4 | long long firstRowSum = accumulate(begin(grid[0]), end(grid[0]), 0LL), 5 | secondRowSum = 0; 6 | long long minimumSum = LONG_LONG_MAX; 7 | for (int turnIndex = 0; turnIndex < grid[0].size(); ++turnIndex) { 8 | firstRowSum -= grid[0][turnIndex]; 9 | // Find the minimum maximum value out of firstRowSum and 10 | // secondRowSum. 11 | minimumSum = min(minimumSum, max(firstRowSum, secondRowSum)); 12 | secondRowSum += grid[1][turnIndex]; 13 | } 14 | return minimumSum; 15 | } 16 | }; -------------------------------------------------------------------------------- /3434-find-the-number-of-distinct-colors-among-the-balls/find-the-number-of-distinct-colors-among-the-balls.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector queryResults(int limit, vector>& queries) { 4 | unordered_map ball, color; 5 | vector ans; 6 | ans.reserve(queries.size()); 7 | int distinct = 0; 8 | for(auto &q : queries) { 9 | int pos = q[0], c = q[1]; 10 | if(ball.count(pos)) 11 | if(--color[ball[pos]] == 0) distinct--; 12 | ball[pos] = c; 13 | if(++color[c] == 1) distinct++; 14 | ans.push_back(distinct); 15 | } 16 | return ans; 17 | } 18 | }; -------------------------------------------------------------------------------- /1802-number-of-students-unable-to-eat-lunch/number-of-students-unable-to-eat-lunch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int countStudents(vector& students, vector& sandwiches) { 7 | vector counts(2, 0); 8 | for (int student : students) 9 | counts[student]++; 10 | 11 | int remaining = sandwiches.size(); 12 | for (int sandwich : sandwiches) { 13 | if (counts[sandwich] == 0) 14 | break; 15 | if (remaining == 0) 16 | break; 17 | counts[sandwich]--; 18 | remaining--; 19 | } 20 | 21 | return remaining; 22 | } 23 | }; -------------------------------------------------------------------------------- /206-reverse-linked-list/reverse-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | ListNode*temp=head; 15 | ListNode*prev=NULL; 16 | 17 | while(temp){ 18 | ListNode* front = temp->next; 19 | temp->next=prev; 20 | prev=temp; 21 | temp=front; 22 | } 23 | return prev; 24 | } 25 | }; -------------------------------------------------------------------------------- /3643-zero-array-transformation-ii/zero-array-transformation-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minZeroArray(vector& nums, vector>& q) { 4 | int i = 0, j = 0; 5 | vector line(nums.size() + 1); 6 | for (int cur = 0; i < nums.size(); cur += line[++i]) { 7 | for (; j < q.size() && cur < nums[i]; ++j) 8 | if (q[j][1] >= i) { 9 | if (q[j][0] <= i) 10 | cur += q[j][2]; 11 | else 12 | line[q[j][0]] += q[j][2]; 13 | line[q[j][1] + 1] -= q[j][2]; 14 | } 15 | if (cur < nums[i]) 16 | break; 17 | } 18 | return i == nums.size() ? j : -1; 19 | } 20 | }; -------------------------------------------------------------------------------- /890-lemonade-change/lemonade-change.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool lemonadeChange(vector& bills) { 4 | int five =0; 5 | int ten =0; 6 | for(int i=0;i=3){ 21 | five-=3; 22 | } 23 | else return false; 24 | } 25 | } 26 | return true; 27 | } 28 | }; -------------------------------------------------------------------------------- /1128-remove-all-adjacent-duplicates-in-string/remove-all-adjacent-duplicates-in-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeDuplicates(string s) { 4 | 5 | int i =0; 6 | string ans =""; 7 | 8 | while(i0){ 10 | if(ans[ans.length()-1]==s[i]){ 11 | ans.pop_back(); 12 | } 13 | else{ 14 | ans.push_back(s[i]); 15 | } 16 | 17 | } 18 | 19 | 20 | else 21 | { 22 | ans.push_back(s[i]); 23 | } 24 | i++; 25 | 26 | } 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /3332-minimum-operations-to-exceed-threshold-value-ii/minimum-operations-to-exceed-threshold-value-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector& nums, int k) { 4 | priority_queue, greater> min_heap(nums.begin(), 5 | nums.end()); 6 | int num_operations = 0; 7 | 8 | while (min_heap.top() < k) { 9 | long x = min_heap.top(); 10 | min_heap.pop(); 11 | long y = min_heap.top(); 12 | min_heap.pop(); 13 | min_heap.push(min(x, y) * 2 + max(x, y)); 14 | 15 | num_operations++; 16 | } 17 | return num_operations; 18 | } 19 | }; -------------------------------------------------------------------------------- /1553-count-triplets-that-can-form-two-arrays-of-equal-xor/count-triplets-that-can-form-two-arrays-of-equal-xor.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countTriplets(vector& arr) { 4 | int n = arr.size() + 1; 5 | vector prefix_xor(n, 0); 6 | for (int i = 1; i < n; i++) { 7 | prefix_xor[i] = prefix_xor[i - 1] ^ arr[i - 1]; 8 | } 9 | 10 | int res = 0; 11 | 12 | for (int start = 0; start < n; start++) { 13 | for (int end = start + 1; end < n; end++) { 14 | if (prefix_xor[start] == prefix_xor[end]) { 15 | res += end - start - 1; 16 | } 17 | } 18 | } 19 | 20 | return res; 21 | } 22 | }; -------------------------------------------------------------------------------- /1537-maximum-score-after-splitting-a-string/maximum-score-after-splitting-a-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxScore(string inputStr) { 4 | int onesCount = 0; 5 | int zerosCount = 0; 6 | int bestScore = INT_MIN; 7 | 8 | for (int i = 0; i < inputStr.size() - 1; i++) { 9 | if (inputStr[i] == '1') { 10 | onesCount++; 11 | } else { 12 | zerosCount++; 13 | } 14 | 15 | bestScore = max(bestScore, zerosCount - onesCount); 16 | } 17 | 18 | if (inputStr[inputStr.size() - 1] == '1') { 19 | onesCount++; 20 | } 21 | 22 | return bestScore + onesCount; 23 | } 24 | }; -------------------------------------------------------------------------------- /1037-minimum-number-of-k-consecutive-bit-flips/minimum-number-of-k-consecutive-bit-flips.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minKBitFlips(vector& nums, int k) { 4 | int n = nums.size(); 5 | int flipped = 0; 6 | int res = 0; 7 | vector isFlipped(n, 0); 8 | 9 | for (int i = 0; i < n; ++i) { 10 | if (i >= k) { 11 | flipped ^= isFlipped[i - k]; 12 | } 13 | if (flipped == nums[i]) { 14 | if (i + k > n) { 15 | return -1; 16 | } 17 | isFlipped[i] = 1; 18 | flipped ^= 1; 19 | res++; 20 | } 21 | } 22 | 23 | return res; 24 | } 25 | }; -------------------------------------------------------------------------------- /350-intersection-of-two-arrays-ii/intersection-of-two-arrays-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector intersect(vector& nums1, vector& nums2) { 4 | sort(nums1.begin(), nums1.end()); 5 | sort(nums2.begin(), nums2.end()); 6 | 7 | int i = 0, j = 0; 8 | vector result; 9 | 10 | while (i < nums1.size() && j < nums2.size()) { 11 | if (nums1[i] < nums2[j]) { 12 | i++; 13 | } else if (nums1[i] > nums2[j]) { 14 | j++; 15 | } else { 16 | result.push_back(nums1[i]); 17 | i++; 18 | j++; 19 | } 20 | } 21 | 22 | return result; 23 | } 24 | }; -------------------------------------------------------------------------------- /2527-count-subarrays-with-fixed-bounds/count-subarrays-with-fixed-bounds.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long countSubarrays(vector& nums, int minK, int maxK) { 4 | long long res = 0; 5 | int bad_idx = -1, left_idx = -1, right_idx = -1; 6 | 7 | for (int i = 0; i < nums.size(); ++i) { 8 | if (!(minK <= nums[i] && nums[i] <= maxK)) { 9 | bad_idx = i; 10 | } 11 | 12 | if (nums[i] == minK) { 13 | left_idx = i; 14 | } 15 | 16 | if (nums[i] == maxK) { 17 | right_idx = i; 18 | } 19 | 20 | res += max(0, min(left_idx, right_idx) - bad_idx); 21 | } 22 | 23 | return res; 24 | } 25 | }; -------------------------------------------------------------------------------- /1516-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int n2; 3 | string dfs(string prefix, int n, int k) { 4 | if (n == 0) 5 | return prefix; 6 | for (char c = 'a'; c <= 'c'; c++) { 7 | if (!prefix.empty() && c == prefix.back()) 8 | continue; 9 | int cnt = (1 << (n2 - prefix.length() - 1)); 10 | if (cnt >= k) 11 | return dfs(prefix + c, n - 1, k); 12 | else 13 | k -= cnt; 14 | } 15 | return ""; 16 | } 17 | public: 18 | string getHappyString(int n, int k) { 19 | n2 = n; 20 | return dfs("", n, k); 21 | } 22 | }; -------------------------------------------------------------------------------- /31-next-permutation/next-permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void nextPermutation(vector& nums) { 4 | int n = nums.size(); 5 | int indx =-1; 6 | 7 | for(int i = n-2; i>=0 ; i--){ 8 | if(nums[i]indx;i--){ 20 | if(nums[i]>nums[indx]){ 21 | swap(nums[i],nums[indx]); 22 | break; 23 | } 24 | } 25 | reverse(nums.begin()+ indx +1, nums.end() ); 26 | } 27 | 28 | 29 | 30 | } 31 | }; -------------------------------------------------------------------------------- /463-island-perimeter/island-perimeter.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int islandPerimeter(vector>& grid) { 4 | int perimeter = 0; 5 | int rows = grid.size(); 6 | int cols = grid[0].size(); 7 | 8 | for (int r = 0; r < rows; r++) { 9 | for (int c = 0; c < cols; c++) { 10 | if (grid[r][c] == 1) { 11 | perimeter += 4; 12 | if (r > 0 && grid[r-1][c] == 1) { 13 | perimeter -= 2; 14 | } 15 | if (c > 0 && grid[r][c-1] == 1) { 16 | perimeter -= 2; 17 | } 18 | } 19 | } 20 | } 21 | 22 | return perimeter; 23 | } 24 | }; -------------------------------------------------------------------------------- /680-valid-palindrome-ii/valid-palindrome-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool checkPalindrome (string s, int i, int j){ 5 | while(i<=j){ 6 | if(s[i]!= s[j]){ 7 | return false; 8 | } 9 | else{ 10 | i++; 11 | j--; 12 | } 13 | } 14 | return true; 15 | } 16 | bool validPalindrome(string s) { 17 | int i=0; 18 | int j=s.length()-1; 19 | 20 | while(i<=j){ 21 | if(s[i]!=s[j]){ 22 | 23 | return checkPalindrome(s,i+1,j) || checkPalindrome(s,i,j-1); 24 | 25 | } 26 | 27 | else{ 28 | i++; 29 | j--; 30 | } 31 | } 32 | return true; 33 | } 34 | }; -------------------------------------------------------------------------------- /2160-minimum-operations-to-make-a-uni-value-grid/minimum-operations-to-make-a-uni-value-grid.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector>& grid, int x) { 4 | int res = INT_MAX, ops = 0; 5 | vector v, dp(grid.size() * grid[0].size()); 6 | for (auto &row : grid) 7 | v.insert(end(v), begin(row), end(row)); 8 | sort(begin(v), end(v)); 9 | for (int i = 0; i < v.size() - 1; ++i) { 10 | if ((v[i + 1] - v[i]) % x) 11 | return -1; 12 | dp[i + 1] = dp[i] + (i + 1) * (v[i + 1] - v[i]) / x; 13 | } 14 | for (int i = v.size() - 1; i > 0; --i) { 15 | ops += (v.size() - i) * (v[i] - v[i - 1]) / x; 16 | res = min(res, ops + dp[i - 1]); 17 | } 18 | return res == INT_MAX ? 0 : res; 19 | } 20 | }; -------------------------------------------------------------------------------- /2573-remove-nodes-from-linked-list/remove-nodes-from-linked-list.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* removeNodes(ListNode* head) { 4 | ListNode* cur = head; 5 | stack stack; 6 | 7 | while (cur != nullptr) { 8 | while (!stack.empty() && stack.top()->val < cur->val) { 9 | ListNode* a = stack.top(); 10 | stack.pop(); 11 | } 12 | stack.push(cur); 13 | cur = cur->next; 14 | } 15 | 16 | ListNode* nxt = nullptr; 17 | while (!stack.empty()) { 18 | cur = stack.top(); 19 | stack.pop(); 20 | cur->next = nxt; 21 | nxt = cur; 22 | } 23 | 24 | return cur; 25 | } 26 | }; -------------------------------------------------------------------------------- /14-longest-common-prefix/longest-common-prefix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestCommonPrefix(vector& strs) { 4 | string ans; 5 | if (strs.empty()) return ans; 6 | 7 | int i = 0; 8 | while (true) { 9 | char curr_ch = 0; 10 | for (auto& str : strs) { 11 | if (i >= str.size()) return ans; // No common prefix if index exceeds string size 12 | 13 | if (curr_ch == 0) { 14 | curr_ch = str[i]; 15 | } else if (str[i] != curr_ch) { 16 | return ans; // No common prefix if characters do not match 17 | } 18 | } 19 | ans.push_back(curr_ch); 20 | i++; 21 | } 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /2888-minimum-index-of-a-valid-split/minimum-index-of-a-valid-split.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumIndex(vector& nums) { 4 | //find the majority element 5 | int majority = nums[0], count = 0; 6 | for(auto n: nums){ 7 | if(n == majority) count++; 8 | else count--; 9 | if(count == 0) { majority = n; count = 1; } 10 | } 11 | 12 | //count majority elements occurance 13 | int majCout = 0; 14 | for(auto n: nums) if(n == majority) majCout++; 15 | 16 | //check if split is possible or not 17 | count = 0; 18 | for(int i = 0; i < nums.size(); ++i){ 19 | if(nums[i] == majority) count++; 20 | if(count*2 > (i+1) && (majCout - count)*2 > (nums.size() - i - 1)) return i; 21 | } 22 | return -1; 23 | } 24 | }; -------------------------------------------------------------------------------- /22-generate-parentheses/README.md: -------------------------------------------------------------------------------- 1 |

Generate Parentheses

Difficulty: Medium

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

2 | 3 |

 

4 |

Example 1:

5 |
Input: n = 3
 6 | Output: ["((()))","(()())","(())()","()(())","()()()"]
 7 | 

Example 2:

8 |
Input: n = 1
 9 | Output: ["()"]
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • 1 <= n <= 8
  • 16 |
17 | -------------------------------------------------------------------------------- /33-search-in-rotated-sorted-array/search-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) { 4 | int low =0, high = nums.size()-1; 5 | while(low<=high){ 6 | int mid = low + (high-low)/2; 7 | 8 | if(nums[mid]==target) 9 | return mid; 10 | // check left is sorted 11 | if(nums[low]<=nums[mid]){ 12 | if(nums[low]<=target && target<=nums[mid]){ 13 | high = mid -1; 14 | } 15 | else low = mid +1; 16 | } 17 | else{ 18 | if(nums[mid]<=target && target <= nums[high]){ 19 | low = mid+1; 20 | } 21 | else 22 | high = mid-1; 23 | } 24 | } 25 | return -1; 26 | } 27 | }; -------------------------------------------------------------------------------- /3657-check-if-grid-can-be-cut-into-sections/check-if-grid-can-be-cut-into-sections.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkValidCuts(int n, vector>& rectangles) { 4 | auto check = [](vector> A) -> bool { 5 | int res = 0; 6 | sort(A.begin(), A.end()); 7 | int pre = A[0][1]; 8 | for (auto& ab : A) { 9 | int a = ab[0], b = ab[1]; 10 | res += pre <= a; 11 | pre = max(pre, b); 12 | } 13 | return res > 1; 14 | }; 15 | 16 | vector> X, Y; 17 | for (auto& r : rectangles) { 18 | X.push_back({r[0], r[2]}); 19 | Y.push_back({r[1], r[3]}); 20 | } 21 | return check(X) || check(Y); 22 | } 23 | }; -------------------------------------------------------------------------------- /74-search-a-2d-matrix/search-a-2d-matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool searchMatrix(vector>& mat, int target) { 4 | int n = mat.size(); 5 | int m = mat[0].size(); 6 | 7 | int low = 0, high = n * m - 1; 8 | //Perform binary search 9 | while (low <= high) { 10 | int mid = (low + high) / 2; 11 | 12 | //Calculate the row and column 13 | int row = mid / m, col = mid % m; 14 | 15 | //If target is found return true 16 | if (mat[row][col] == target) return true; 17 | else if (mat[row][col] < target) low = mid + 1; 18 | else high = mid - 1; 19 | } 20 | // Return false if target is not found 21 | return false; 22 | } 23 | }; -------------------------------------------------------------------------------- /1907-count-pairs-with-xor-in-a-range/count-pairs-with-xor-in-a-range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPairs(vector& A, int low, int high) { 4 | return test(A, high + 1) - test(A, low); 5 | } 6 | 7 | int test(vector& A, int x) { 8 | unordered_map count, count2; 9 | for (int a : A) count[a]--; 10 | int res = 0; 11 | while (x) { 12 | for (auto const& [k, v] : count) { 13 | count2[k >> 1] += v; 14 | if (x & 1) 15 | if (count.find((x - 1) ^ k) != count.end()) 16 | res += v * count[(x - 1) ^ k]; 17 | } 18 | swap(count, count2); 19 | count2.clear(); 20 | x >>= 1; 21 | } 22 | return res / 2; 23 | } 24 | }; -------------------------------------------------------------------------------- /3372-longest-strictly-increasing-or-strictly-decreasing-subarray/longest-strictly-increasing-or-strictly-decreasing-subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestMonotonicSubarray(std::vector& nums) { 4 | int incLength = 1, decLength = 1, maxLength = 1; 5 | 6 | for (size_t i = 0; i < nums.size() - 1; i++) { 7 | if (nums[i + 1] > nums[i]) { 8 | incLength++; 9 | decLength = 1; 10 | } else if (nums[i + 1] < nums[i]) { 11 | decLength++; 12 | incLength = 1; 13 | } else { 14 | incLength = 1; 15 | decLength = 1; 16 | } 17 | maxLength = std::max(maxLength, std::max(incLength, decLength)); 18 | } 19 | 20 | return maxLength; 21 | } 22 | }; -------------------------------------------------------------------------------- /264-ugly-number-ii/ugly-number-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nthUglyNumber(int n) { 4 | vector primes = {2, 3, 5}; 5 | priority_queue, greater> uglyHeap; 6 | unordered_set visited; 7 | 8 | uglyHeap.push(1); 9 | visited.insert(1); 10 | 11 | long curr; 12 | for (int i = 0; i < n; ++i) { 13 | curr = uglyHeap.top(); 14 | uglyHeap.pop(); 15 | for (int prime : primes) { 16 | long new_ugly = curr * prime; 17 | if (visited.find(new_ugly) == visited.end()) { 18 | uglyHeap.push(new_ugly); 19 | visited.insert(new_ugly); 20 | } 21 | } 22 | } 23 | return (int)curr; 24 | } 25 | }; -------------------------------------------------------------------------------- /2265-partition-array-according-to-given-pivot/partition-array-according-to-given-pivot.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector pivotArray(vector& nums, int pivot) { 4 | vector result(nums.size(), 0); 5 | int left = 0, right = nums.size() - 1; 6 | 7 | for (int i = 0, j = nums.size() - 1; i < nums.size(); ++i, --j) { 8 | if (nums[i] < pivot) { 9 | result[left] = nums[i]; 10 | left++; 11 | } 12 | 13 | if (nums[j] > pivot) { 14 | result[right] = nums[j]; 15 | right--; 16 | } 17 | } 18 | 19 | while (left <= right) { 20 | result[left] = pivot; 21 | left++; 22 | } 23 | 24 | return result; 25 | } 26 | }; -------------------------------------------------------------------------------- /39-combination-sum/combination-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void func(vector& nums, int n, int sum, vector& list, 4 | vector>& ans) { 5 | if (sum == 0) { 6 | ans.push_back(list); 7 | return; 8 | } 9 | if (sum < 0) return; 10 | if (n < 0) return; 11 | 12 | func(nums, n - 1, sum, list, ans); 13 | 14 | list.push_back(nums[n]); 15 | func(nums, n, sum - nums[n], list, ans); 16 | list.pop_back(); 17 | } 18 | 19 | public: 20 | vector> combinationSum(vector& candidates, int target) { 21 | vector> ans; 22 | vector list; 23 | int n = candidates.size() - 1; 24 | func(candidates, n, target, list, ans); 25 | 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /853-most-profit-assigning-work/most-profit-assigning-work.cpp: -------------------------------------------------------------------------------- 1 | #define sort(a) sort(begin(a), end(a)) 2 | #define opt() ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); 3 | class Solution { 4 | public: 5 | int maxProfitAssignment(vector& difficulty, vector& profit, vector& worker) { 6 | opt(); 7 | int res = 0, j = 0, best = 0; 8 | vector> temp; 9 | for(int i = 0; i < worker.size(); ++i) { 10 | temp.push_back({difficulty[i], profit[i]}); 11 | } 12 | 13 | sort(temp); sort(worker); 14 | for(int work : worker) { 15 | while(work >= temp[j].first && j < worker.size()) { 16 | best = max(best, temp[j++].second); 17 | } 18 | 19 | res += best; 20 | } 21 | 22 | return res; 23 | } 24 | }; -------------------------------------------------------------------------------- /1217-relative-sort-array/relative-sort-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector relativeSortArray(vector& arr1, vector& arr2) { 4 | int n1=arr1.size(), n2=arr2.size(); 5 | int a2i[1001]; 6 | 7 | // Initialize a2i with n2 (indicating elements not in arr2) 8 | fill(a2i, end(a2i), n2); 9 | for(int i=0; ii 11 | 12 | sort(arr1.begin(), arr1.end(), [&](int x, int y){ 13 | // ordered by {a2i[x], x} 14 | if (a2i[x]==a2i[y]) return x bool: 3 | # Check if the lengths of the strings are equal 4 | if len(s) != len(t): 5 | return False 6 | 7 | # Initialize mappings from s to t and t to s 8 | mapST, mapTS = {}, {} 9 | 10 | # Iterate through each character in the strings 11 | for i in range(len(s)): 12 | c1, c2 = s[i], t[i] 13 | 14 | # Check if current characters have been mapped differently 15 | if (c1 in mapST and mapST[c1] != c2) or (c2 in mapTS and mapTS[c2] != c1): 16 | return False 17 | 18 | # Update mappings from s to t and t to s 19 | mapST[c1] = c2 20 | mapTS[c2] = c1 21 | 22 | return True 23 | 24 | -------------------------------------------------------------------------------- /57-insert-interval/insert-interval.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> insert(vector>& Intervals, 4 | vector& newInterval) { 5 | vector> res; 6 | int i = 0; 7 | int n = Intervals.size(); 8 | while (i < n && Intervals[i][1] < newInterval[0]) { 9 | res.push_back(Intervals[i]); 10 | i++; 11 | } 12 | while (i < n && Intervals[i][0] <= newInterval[1]) { 13 | newInterval[0] = min(newInterval[0], Intervals[i][0]); 14 | newInterval[1] = max(newInterval[1], Intervals[i][1]); 15 | i++; 16 | } 17 | res.push_back(newInterval); 18 | while (i < n) { 19 | res.push_back(Intervals[i]); 20 | i++; 21 | } 22 | return res; 23 | } 24 | }; -------------------------------------------------------------------------------- /1450-delete-leaves-with-a-given-value/delete-leaves-with-a-given-value.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* removeLeafNodes(TreeNode* root, int target) { 15 | if (!root) return nullptr; 16 | root->left = removeLeafNodes(root->left, target); 17 | root->right = removeLeafNodes(root->right, target); 18 | if (!root->left && !root->right && root->val == target) 19 | return nullptr; 20 | return root; 21 | } 22 | }; -------------------------------------------------------------------------------- /2473-max-sum-of-a-pair-with-equal-sum-of-digits/max-sum-of-a-pair-with-equal-sum-of-digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumSum(vector& nums) { 4 | int n = nums.size(); 5 | vector v; 6 | int ans=-1; 7 | vector> p; 8 | for( int i=0;i= 0 && right < n && s[left] == s[right]) { 11 | ++count; // Count the palindrome 12 | --left; 13 | ++right; 14 | } 15 | 16 | // Expand around the center for even-length palindromes 17 | left = i; 18 | right = i + 1; 19 | while (left >= 0 && right < n && s[left] == s[right]) { 20 | ++count; // Count the palindrome 21 | --left; 22 | ++right; 23 | } 24 | } 25 | 26 | return count; 27 | } 28 | }; -------------------------------------------------------------------------------- /776-n-ary-tree-postorder-traversal/n-ary-tree-postorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector postorder(Node* root) { 4 | // If the root is null, return an empty vector 5 | if (!root) return {}; 6 | 7 | vector res; 8 | 9 | // Define the DFS function 10 | function dfs = [&](Node* node) { 11 | // Recursively call dfs for each child of the current node 12 | for (Node* child : node->children) { 13 | dfs(child); 14 | } 15 | // Append the value of the current node to the result vector 16 | res.push_back(node->val); 17 | }; 18 | 19 | // Start DFS from the root 20 | dfs(root); 21 | 22 | // Return the result vector containing node values in post-order 23 | return res; 24 | } 25 | }; -------------------------------------------------------------------------------- /345-reverse-vowels-of-a-string/reverse-vowels-of-a-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool isVowel(char c){ 5 | c = tolower(c); 6 | // char arr[5] = {'a','e','i','o','u'}; 7 | // for(int i =0; i<5; i++){ 8 | // if(arr[i]==ch)return true; 9 | // } 10 | // return false; 11 | return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; 12 | 13 | } 14 | string reverseVowels(string s) { 15 | 16 | int i =0, j=s.size()-1; 17 | while(inext)return head; 15 | ListNode* odd = head; 16 | ListNode* even = head->next; 17 | ListNode* evenHead = head->next; 18 | 19 | while(even && even->next){ 20 | odd->next=odd->next->next; 21 | even->next=even->next->next; 22 | 23 | odd=odd->next; 24 | even=even->next; 25 | } 26 | odd->next=evenHead; 27 | return head; 28 | } 29 | }; -------------------------------------------------------------------------------- /1333-sort-the-jumbled-numbers/sort-the-jumbled-numbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortJumbled(vector& mapping, vector& nums) { 4 | auto translate_integer = [&](int num) -> int { 5 | string digits = to_string(num); 6 | for (char& digit : digits) { 7 | digit = '0' + mapping[digit - '0']; 8 | } 9 | return stoi(digits); 10 | }; 11 | 12 | unordered_map number_mapping; 13 | for (int num : nums) { 14 | if (number_mapping.find(num) == number_mapping.end()) { 15 | number_mapping[num] = translate_integer(num); 16 | } 17 | } 18 | 19 | sort(nums.begin(), nums.end(), [&](int a, int b) { 20 | return number_mapping[a] < number_mapping[b]; 21 | }); 22 | 23 | return nums; 24 | } 25 | }; -------------------------------------------------------------------------------- /145-binary-tree-postorder-traversal/binary-tree-postorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector postorderTraversal(TreeNode* root) { 15 | vector list; 16 | help(list,root); 17 | return list; 18 | } 19 | void help(vector& list,TreeNode* root){ 20 | if(root==NULL){ 21 | return; 22 | } 23 | help(list,root->left); 24 | help(list,root->right); 25 | list.push_back(root->val); 26 | } 27 | }; -------------------------------------------------------------------------------- /8-string-to-integer-atoi/string-to-integer-atoi.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int myAtoi(string s) 4 | { 5 | int i=0; 6 | int sign=1; 7 | long ans=0; 8 | while(i='0' && s[i]<='9') 20 | { 21 | ans=ans*10+(s[i]-'0'); 22 | if(ans>INT_MAX && sign==-1) 23 | return INT_MIN; 24 | else if(ans>INT_MAX && sign==1) 25 | return INT_MAX; 26 | i++; 27 | } 28 | else 29 | return ans*sign; 30 | } 31 | return (ans*sign); 32 | } 33 | }; -------------------------------------------------------------------------------- /3348-minimum-cost-walk-in-weighted-graph/minimum-cost-walk-in-weighted-graph.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector ds, cost; 4 | int find(int i) { 5 | return ds[i] < 0 ? i : ds[i] = find(ds[i]); 6 | } 7 | vector minimumCost(int n, vector>& edges, vector>& query) { 8 | ds = cost = vector(n, -1); 9 | for (auto &e : edges) { 10 | int p1 = find(e[0]), p2 = find(e[1]); 11 | if (p1 != p2) { 12 | cost[p1] &= cost[p2]; 13 | ds[p2] = p1; 14 | } 15 | cost[p1] &= e[2]; 16 | } 17 | vector res; 18 | for (auto q : query) { 19 | if (q[0] == q[1]) 20 | res.push_back(0); 21 | else if (int p1 = find(q[0]), p2 = find(q[1]); p1 != p2) 22 | res.push_back(-1); 23 | else 24 | res.push_back(cost[p1]); 25 | } 26 | return res; 27 | } 28 | }; -------------------------------------------------------------------------------- /2793-count-the-number-of-complete-components/count-the-number-of-complete-components.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(int i, vector> &al, unordered_set &s) { 4 | if (s.insert(i).second) 5 | for (int j : al[i]) 6 | dfs(j, al, s); 7 | } 8 | int countCompleteComponents(int n, vector>& edges) { 9 | vector> al(n); 10 | int res = 0; 11 | for (const auto &e : edges) { 12 | al[e[0]].push_back(e[1]); 13 | al[e[1]].push_back(e[0]); 14 | } 15 | unordered_set ms; 16 | for (int i = 0; i < n; ++i) { 17 | if (ms.count(i) == 0) { 18 | unordered_set s; 19 | dfs(i, al, s); 20 | res += all_of(begin(s), end(s), [&](int i){ return al[i].size() == s.size() - 1; }); 21 | ms.insert(begin(s), end(s)); 22 | } 23 | } 24 | return res; 25 | } 26 | }; -------------------------------------------------------------------------------- /1765-merge-in-between-linked-lists/merge-in-between-linked-lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) { 14 | ListNode* ptr = list1; 15 | for (int i = 0; i < a - 1; ++i) 16 | ptr = ptr->next; 17 | 18 | ListNode* qtr = ptr->next; 19 | for (int i = 0; i < b - a + 1; ++i) 20 | qtr = qtr->next; 21 | 22 | ptr->next = list2; 23 | while (list2->next) 24 | list2 = list2->next; 25 | list2->next = qtr; 26 | 27 | return list1; 28 | } 29 | }; -------------------------------------------------------------------------------- /90-subsets-ii/subsets-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void func(int ind, vector& arr, vector& nums, 4 | vector>& ans) { 5 | if (ind == nums.size()) { 6 | ans.push_back(arr); 7 | return; 8 | } 9 | arr.push_back(nums[ind]); 10 | func(ind + 1, arr, nums, ans); 11 | arr.pop_back(); 12 | 13 | for (int i = ind + 1; i < nums.size(); i++) { 14 | if (nums[i] != nums[ind]) { 15 | func(i, arr, nums, ans); 16 | return; 17 | } 18 | } 19 | func(nums.size(), arr, nums, ans); 20 | } 21 | 22 | public: 23 | vector> subsetsWithDup(vector& nums) { 24 | vector> ans; 25 | vector arr; 26 | sort(nums.begin(), nums.end()); 27 | func(0, arr, nums, ans); 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /131-palindrome-partitioning/palindrome-partitioning.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > partition(string s) { 4 | vector>res; 5 | vectorpath; 6 | dfs(0,s,path,res); 7 | return res; 8 | } 9 | void dfs(int ind, string s, vector&path, vector>&res){ 10 | if(ind == s.size()){ 11 | res.push_back(path); 12 | return; 13 | } 14 | for(int i=ind;i> combinationSum2(vector& candidates, int target) { 4 | sort(candidates.begin(), candidates.end()); 5 | vector < vector < int >> ans; 6 | vector < int > ds; 7 | findCombination(0, target, candidates, ans, ds); 8 | return ans; 9 | } 10 | void findCombination(int ind, int target, vector < int > & arr, vector < vector < int >> & ans, vector < int > & ds) { 11 | if (target == 0) { 12 | ans.push_back(ds); 13 | return; 14 | } 15 | for (int i = ind; i < arr.size(); i++) { 16 | if (i > ind && arr[i] == arr[i - 1]) continue; 17 | if (arr[i] > target) break; 18 | ds.push_back(arr[i]); 19 | findCombination(i + 1, target - arr[i], arr, ans, ds); 20 | ds.pop_back(); 21 | } 22 | } 23 | }; -------------------------------------------------------------------------------- /19-remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* removeNthFromEnd(ListNode* head, int n) { 14 | ListNode* fast = head; 15 | ListNode* slow = head; 16 | 17 | for (int i = 0; i < n; i++) fast = fast->next; 18 | 19 | if (fast == NULL) return head->next; 20 | 21 | while (fast->next != NULL) { 22 | slow = slow->next; 23 | fast = fast->next; 24 | } 25 | ListNode* delNode = slow->next; 26 | slow->next = slow->next->next; 27 | delete delNode; 28 | return head; 29 | } 30 | }; -------------------------------------------------------------------------------- /179-largest-number/largest-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string largestNumber(vector& nums) { 4 | // An array to store the converted numbers 5 | vector v; 6 | 7 | // Converting all the numbers into string format and storing in the array 8 | for(int i: nums){ 9 | v.push_back(to_string(i)); 10 | } 11 | 12 | // Custom Sorting based on the biggest of 2 when concatenated. 13 | sort(v.begin(), v.end(), [&](string a, string b) { 14 | return a+b > b+a; 15 | }); 16 | 17 | // result string to store the results 18 | string result = ""; 19 | for(string c: v){ 20 | result+=c; 21 | } 22 | 23 | // Checking if the result is 0 24 | if(result[0] == '0') return "0"; 25 | 26 | // returning the result. 27 | return result; 28 | } 29 | }; -------------------------------------------------------------------------------- /61-rotate-list/rotate-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* rotateRight(ListNode* head, int k) { 14 | if(!head ||!head->next||k==0)return head; 15 | 16 | ListNode* temp = head; 17 | int len =1; 18 | while(temp->next){ 19 | temp=temp->next; 20 | len++; 21 | } 22 | 23 | if(k%len==0)return head; 24 | k=k%len; 25 | temp->next =head; 26 | int end = len-k; 27 | while(end-->0){ 28 | temp=temp->next; 29 | } 30 | head=temp->next; 31 | temp->next=NULL; 32 | return head; 33 | } 34 | }; -------------------------------------------------------------------------------- /1034-subarrays-with-k-different-integers/subarrays-with-k-different-integers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subarraysWithKDistinct(vector& nums, int k) { 4 | int sub_with_max_element_k = subarray_with_atmost_k(nums,k); 5 | int reduced_sub_with_max_k = subarray_with_atmost_k(nums,k-1); 6 | return (sub_with_max_element_k - reduced_sub_with_max_k); 7 | } 8 | int subarray_with_atmost_k(vector& nums,int k){ 9 | unordered_map map; 10 | int left = 0 , right = 0,ans = 0; 11 | while(rightk){ 14 | map[nums[left]]--; 15 | if(map[nums[left]]==0)map.erase(nums[left]); 16 | left++; 17 | } 18 | ans += right-left+1; // basically the size of subarray; 19 | right++; 20 | } 21 | return ans; 22 | } 23 | }; -------------------------------------------------------------------------------- /1240-stone-game-ii/stone-game-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int stoneGameII(vector& piles) { 4 | int n = piles.size(); 5 | 6 | vector> dp(n, vector(n + 1, 0)); 7 | vector suffixSum(n, 0); 8 | suffixSum[n - 1] = piles[n - 1]; 9 | 10 | for (int i = n - 2; i >= 0; i--) { 11 | suffixSum[i] = suffixSum[i + 1] + piles[i]; 12 | } 13 | 14 | for (int i = n - 1; i >= 0; i--) { 15 | for (int m = 1; m <= n; m++) { 16 | if (i + 2 * m >= n) { 17 | dp[i][m] = suffixSum[i]; 18 | } else { 19 | for (int x = 1; x <= 2 * m; x++) { 20 | dp[i][m] = max(dp[i][m], suffixSum[i] - dp[i + x][max(m, x)]); 21 | } 22 | } 23 | } 24 | } 25 | 26 | return dp[0][1]; 27 | } 28 | }; -------------------------------------------------------------------------------- /917-boats-to-save-people/boats-to-save-people.cpp: -------------------------------------------------------------------------------- 1 | #pragma GCC optimize("O3", "unroll-loops") 2 | class Solution { 3 | public: 4 | int numRescueBoats(vector& people, int limit) { 5 | unsigned freq[30001]={0}; 6 | int maxW=0, minW=30001; 7 | for(int x: people){ 8 | freq[x]++; 9 | maxW=max(maxW, x); 10 | minW=min(minW, x); 11 | } 12 | for (int i=minW, j=0; i<=maxW; i++){ 13 | int f=freq[i]; 14 | fill(people.begin()+j, people.begin()+j+f, i); 15 | j+=f; 16 | } 17 | int x=0; 18 | for(int l=0, r=people.size()-1;l<=r; r--){ 19 | x++; 20 | if (people[l]+people[r]<=limit) 21 | l++; 22 | } 23 | return x; 24 | } 25 | }; 26 | 27 | 28 | auto init = []() { 29 | ios::sync_with_stdio(0); 30 | cin.tie(0); 31 | cout.tie(0); 32 | return 'c'; 33 | }(); -------------------------------------------------------------------------------- /162-find-peak-element/find-peak-element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findPeakElement(vector& arr) { 4 | int n = arr.size(); 5 | 6 | // Edge cases: 7 | if (n == 1) return 0; 8 | if (arr[0] > arr[1]) return 0; 9 | if (arr[n - 1] > arr[n - 2]) return n - 1; 10 | 11 | int low = 1, high = n - 2; 12 | while (low <= high) { 13 | int mid = (low + high) / 2; 14 | 15 | //If arr[mid] is the peak 16 | if (arr[mid - 1] < arr[mid] && arr[mid] > arr[mid + 1]) 17 | return mid; 18 | 19 | // If we are in the left 20 | if (arr[mid] > arr[mid - 1]) low = mid + 1; 21 | 22 | /* If we are in the right 23 | Or, arr[mid] is a common point*/ 24 | else high = mid - 1; 25 | } 26 | /* Return -1 if no peak element 27 | found (dummy return) */ 28 | return -1; 29 | } 30 | }; -------------------------------------------------------------------------------- /135-candy/candy.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int candy(vector& ratings) { 4 | int n = ratings.size(); 5 | if (n == 0) return 0; 6 | 7 | int sum = 1, up = 0, down = 0, peak = 0; 8 | 9 | for (int i = 1; i < n; i++) { 10 | if (ratings[i] > ratings[i - 1]) { // Increasing sequence 11 | up++; 12 | peak = up; 13 | down = 0; 14 | sum += up + 1; 15 | } 16 | else if (ratings[i] < ratings[i - 1]) { // Decreasing sequence 17 | down++; 18 | up = 0; 19 | sum += down; 20 | if (down > peak) sum++; // Extra candy needed if decreasing part is longer 21 | } 22 | else { // Equal ratings 23 | up = down = peak = 0; 24 | sum += 1; 25 | } 26 | } 27 | 28 | return sum; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /2454-largest-local-values-in-a-matrix/largest-local-values-in-a-matrix.cpp: -------------------------------------------------------------------------------- 1 | #pragma GCC optimize ("Ofast") 2 | #pragma GCC target ("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx") 3 | #pragma GCC optimize ("-ffloat-store") 4 | 5 | class Solution { 6 | public: 7 | vector> largestLocal(vector>& grid) { 8 | ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); 9 | int n = grid.size(); 10 | vector> res(n - 2, vector(n - 2)); 11 | 12 | for(int i = 1; i < n - 1; ++i) { 13 | for(int j = 1; j < n - 1; ++j) { 14 | int temp = 0; 15 | 16 | for(int k = i - 1; k <= i + 1; ++k) { 17 | for(int l = j - 1; l <= j + 1; ++l) { 18 | temp = max(temp, grid[k][l]); 19 | } 20 | } 21 | 22 | res[i - 1][j - 1] = temp; 23 | } 24 | } 25 | 26 | return res; 27 | } 28 | }; -------------------------------------------------------------------------------- /2255-minimum-swaps-to-group-all-1s-together-ii/minimum-swaps-to-group-all-1s-together-ii.cpp: -------------------------------------------------------------------------------- 1 | static const int fast = []{ 2 | std::ios_base::sync_with_stdio(false); 3 | std::cin.tie(0); 4 | std::cout.tie(0); 5 | 6 | return 0; 7 | }(); 8 | 9 | class Solution { 10 | public: 11 | int minSwaps(vector& nums) { 12 | int n = nums.size(); 13 | 14 | int cnt = 0; 15 | for(int& x : nums) cnt += x; 16 | 17 | if(cnt == n) return 0; 18 | 19 | int swaps = n; 20 | 21 | int l = 0; 22 | int r = 0; 23 | int curr = 0; 24 | 25 | while(l < n) 26 | { 27 | while(r >= l ? r - l < cnt : n - l + r < cnt) 28 | { 29 | curr += nums[r]; 30 | r = (r + 1) % n; 31 | } 32 | 33 | swaps = min(swaps, cnt - curr); 34 | curr -= nums[l]; 35 | l++; 36 | } 37 | 38 | return swaps; 39 | } 40 | }; -------------------------------------------------------------------------------- /891-score-after-flipping-matrix/score-after-flipping-matrix.cpp: -------------------------------------------------------------------------------- 1 | #pragma GCC optimize("O3", "unroll-loops") 2 | class Solution { 3 | public: 4 | int matrixScore(vector>& grid) { 5 | const int n = grid.size(), m = grid[0].size(); 6 | vector col1(m, 0); 7 | int sum = 0; 8 | for (auto& row : grid) { 9 | int x = 0; 10 | bool one = 0; 11 | for (int i = 0; i < m; i++) { 12 | one = (row[0] == 0) ^ (row[i] == 1); 13 | x = (x << 1) + one; 14 | col1[i] += one; 15 | } 16 | sum += x; 17 | } 18 | for (int i = 0; i < m; i++) { 19 | if (col1[i] <= n / 2) 20 | sum += (1 << (m - 1 - i)) * (n - 2 * col1[i]); 21 | } 22 | return sum; 23 | } 24 | }; 25 | 26 | auto init = []() { 27 | ios::sync_with_stdio(0); 28 | cin.tie(0); 29 | cout.tie(0); 30 | return 'c'; 31 | }(); -------------------------------------------------------------------------------- /203-remove-linked-list-elements/remove-linked-list-elements.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* removeElements(ListNode* head, int val) { 14 | while(head != nullptr && head -> val == val){ 15 | head = head -> next; 16 | } 17 | if(head == nullptr) 18 | return head; 19 | ListNode * p{head}, *q{head -> next}; 20 | while(q!=nullptr){ 21 | if(q->val == val){ 22 | p->next = q ->next; 23 | q = p->next; 24 | } 25 | else{ 26 | p = p->next; 27 | q = p -> next; 28 | } 29 | } 30 | return head; 31 | } 32 | }; -------------------------------------------------------------------------------- /2696-the-number-of-beautiful-subsets/the-number-of-beautiful-subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int beautifulSubsets(vector& nums, int k) { 4 | count = 0; 5 | explore(nums, k, 0); 6 | return count - 1; // Subtract 1 to exclude the empty subset 7 | } 8 | 9 | private: 10 | int count; 11 | unordered_map visited; 12 | 13 | void explore(vector& nums, int k, int index) { 14 | if (index == nums.size()) { 15 | count++; 16 | return; 17 | } 18 | 19 | int num = nums[index]; 20 | 21 | if (visited.find(num - k) == visited.end() && 22 | visited.find(num + k) == visited.end()) { 23 | visited[num]++; 24 | explore(nums, k, index + 1); 25 | visited[num]--; 26 | if (visited[num] == 0) { 27 | visited.erase(num); 28 | } 29 | } 30 | 31 | explore(nums, k, index + 1); 32 | } 33 | }; -------------------------------------------------------------------------------- /670-maximum-swap/README.md: -------------------------------------------------------------------------------- 1 |

Maximum Swap

Difficulty: Medium

You are given an integer num. You can swap two digits at most once to get the maximum valued number.

2 | 3 |

Return the maximum valued number you can get.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: num = 2736
10 | Output: 7236
11 | Explanation: Swap the number 2 and the number 7.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: num = 9973
18 | Output: 9973
19 | Explanation: No swap.
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 0 <= num <= 108
  • 27 |
28 | -------------------------------------------------------------------------------- /1675-magnetic-force-between-two-balls/magnetic-force-between-two-balls.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | bool canWePlace(vector& nums, int dist, int minCnt) { 4 | int cnt = 1, last = nums[0]; 5 | for (int i = 0; i < nums.size(); i++) { 6 | if (nums[i] - last >= dist) { 7 | cnt++; 8 | last = nums[i]; 9 | } 10 | if (cnt >= minCnt) 11 | return true; 12 | } 13 | return false; 14 | } 15 | 16 | public: 17 | int maxDistance(vector& nums, int k) { 18 | sort(nums.begin(), nums.end()); 19 | int n = nums.size(); 20 | int low = 1, high = nums[n - 1] - nums[0]; 21 | 22 | while (low <= high) { 23 | int mid = low + (high - low) / 2; 24 | if (canWePlace(nums, mid, k) == true) { 25 | low = mid + 1; 26 | } else 27 | high = mid - 1; 28 | } 29 | return high; 30 | } 31 | }; -------------------------------------------------------------------------------- /3351-maximize-happiness-of-selected-children/maximize-happiness-of-selected-children.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long maximumHappinessSum(vector& happiness, int k) { 4 | // Sort the vector in ascending order 5 | std::sort(happiness.begin(), happiness.end()); 6 | 7 | // Reverse the vector to get descending order 8 | std::reverse(happiness.begin(), happiness.end()); 9 | 10 | int selected = 0; 11 | long long happinessScore = 0; // Use long long to handle larger sums 12 | 13 | // Iterate over the sorted happiness values 14 | for (int score : happiness) { 15 | if (selected == k) { 16 | break; // Stop if 'k' elements have been selected 17 | } 18 | // Calculate and add the adjusted happiness value if it's positive 19 | happinessScore += std::max(0, score - selected); 20 | selected++; 21 | } 22 | 23 | return happinessScore; 24 | } 25 | }; -------------------------------------------------------------------------------- /539-minimum-time-difference/README.md: -------------------------------------------------------------------------------- 1 |

Minimum Time Difference

Difficulty: Medium
Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list. 2 |

 

3 |

Example 1:

4 |
Input: timePoints = ["23:59","00:00"]
 5 | Output: 1
 6 | 

Example 2:

7 |
Input: timePoints = ["00:00","23:59","00:00"]
 8 | Output: 0
 9 | 
10 |

 

11 |

Constraints:

12 | 13 |
    14 |
  • 2 <= timePoints.length <= 2 * 104
  • 15 |
  • timePoints[i] is in the format "HH:MM".
  • 16 |
17 | -------------------------------------------------------------------------------- /719-find-k-th-smallest-pair-distance/find-k-th-smallest-pair-distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static int cntPairs(int x, vector& nums){//sliding window 4 | const int n=nums.size(); 5 | int cnt=0; 6 | for(int l=0, r=1; rl && nums[r]-nums[l]>x) 8 | l++; 9 | cnt+=r-l; 10 | } 11 | return cnt; 12 | } 13 | 14 | static int smallestDistancePair(vector& nums, int k) { 15 | sort(nums.begin(), nums.end()); 16 | const int M=nums.back(); 17 | 18 | //Binary search 19 | int l=0, r=M, m; 20 | while(l val == 0 || root -> val == 1) { 16 | return root -> val == 1; 17 | } else if(root -> val == 2) { 18 | return helper(root -> left) || helper(root -> right); 19 | } else if(root -> val == 3) { 20 | return helper(root -> left) && helper(root -> right); 21 | } 22 | 23 | return false; 24 | } 25 | 26 | bool evaluateTree(TreeNode* root) { 27 | return helper(root); 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /15-3sum/3sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> threeSum(vector& nums) { 4 | vector>ans; 5 | sort(nums.begin(),nums.end()); 6 | 7 | for(int i=0; i0&&nums[i]==nums[i-1])continue; 9 | 10 | int j = i+1; 11 | int k = nums.size()-1; 12 | 13 | while(j0) k--; 19 | else{ 20 | vectortemp ={nums[i],nums[j],nums[k]}; 21 | ans.push_back(temp); 22 | j++; 23 | k--; 24 | while(jleft && !node->right) { // Leaf node 23 | return isLeft ? node->val : 0; 24 | } 25 | int leftSum = dfs(node->left, true); // Traverse left child 26 | int rightSum = dfs(node->right, false); // Traverse right child 27 | return leftSum + rightSum; 28 | } 29 | }; -------------------------------------------------------------------------------- /907-koko-eating-bananas/koko-eating-bananas.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | 4 | public: 5 | long long reqHours(vectornums, int hours){ 6 | long long sum=0; 7 | 8 | for(int i=0;i& nums) { 15 | int maxi = INT_MIN; 16 | int n = nums.size(); 17 | 18 | // Find the maximum element 19 | for (int i = 0; i < n; i++) { 20 | maxi = max(maxi, nums[i]); 21 | } 22 | return maxi; 23 | } 24 | 25 | int minEatingSpeed(vector&nums, int h) { 26 | int low =1; 27 | int high = findMax(nums); 28 | while(low<=high){ 29 | long long mid = (low+high)/2; 30 | long long reqTime = reqHours(nums,mid); 31 | if(reqTime<=h){ 32 | high = mid-1; 33 | } 34 | else low = mid+1; 35 | } 36 | return low; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /50-powx-n/powx-n.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private : 3 | 4 | double power(double x, long n) { 5 | // Base case: anything raised to 0 is 1 6 | if (n == 0) return 1.0; 7 | 8 | // Base case: anything raised to 1 is itself 9 | if (n == 1) return x; 10 | 11 | // If 'n' is even 12 | if (n % 2 == 0) { 13 | // Recursive call: x * x, n / 2 14 | return power(x * x, n / 2); 15 | } 16 | // If 'n' is odd 17 | // Recursive call: x * power(x, n-1) 18 | return x * power(x, n - 1); 19 | } 20 | 21 | public: 22 | 23 | double myPow(double x, int n) { 24 | // Store the value of n in a separate variable 25 | long long num = n; 26 | 27 | // If n is negative 28 | if (num < 0) { 29 | // Calculate the power of -n and take reciprocal 30 | return (1.0 / power(x, -1 * num)); 31 | } 32 | // If n is non-negative 33 | return power(x, num); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /179-largest-number/README.md: -------------------------------------------------------------------------------- 1 |

Largest Number

Difficulty: Medium

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

2 | 3 |

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

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums = [10,2]
10 | Output: "210"
11 | 
12 | 13 |

Example 2:

14 | 15 |
16 | Input: nums = [3,30,34,5,9]
17 | Output: "9534330"
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= nums.length <= 100
  • 25 |
  • 0 <= nums[i] <= 109
  • 26 |
27 | -------------------------------------------------------------------------------- /1170-shortest-common-supersequence/shortest-common-supersequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string shortestCommonSupersequence(string X, string Y) { 4 | int n=X.size(), m=Y.size(); 5 | int t[n+1][m+1]; 6 | for(int i=0;i<=n;i++) 7 | for(int j=0;j<=m;j++){ 8 | if(i==0||j==0) 9 | t[i][j]=0; 10 | } 11 | 12 | for(int i=1;i<=n;i++) 13 | for(int j=1;j<=m;j++){ 14 | if(X[i-1]==Y[j-1]) 15 | t[i][j]= 1+t[i-1][j-1]; 16 | else 17 | t[i][j]= max(t[i-1][j],t[i][j-1]); 18 | } 19 | 20 | int i=n,j=m; 21 | string s; 22 | while(i>0&&j>0){ 23 | if(X[i-1]==Y[j-1]){ 24 | s += X[i - 1]; 25 | i--, j--; 26 | } 27 | else 28 | { 29 | if(t[i][j-1]>t[i-1][j]){ 30 | s += Y[j - 1]; 31 | j--; 32 | } 33 | else{ 34 | s += X[i - 1]; 35 | i--; 36 | } 37 | } 38 | } 39 | 40 | while(i>0){ 41 | s.push_back(X[i-1]); 42 | i--; 43 | } 44 | 45 | while(j>0){ 46 | s.push_back(Y[j-1]); 47 | j--; 48 | } 49 | reverse(s.begin(), s.end()); 50 | return s; 51 | } 52 | }; -------------------------------------------------------------------------------- /1256-rank-transform-of-an-array/rank-transform-of-an-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | std::vector arrayRankTransform(std::vector& arr) { 4 | std::unordered_map valueToRank; // Map to store value-to-rank mapping 5 | std::vector sortedUniqueNumbers = arr; 6 | 7 | // Remove duplicates and sort 8 | std::sort(sortedUniqueNumbers.begin(), sortedUniqueNumbers.end()); 9 | sortedUniqueNumbers.erase(std::unique(sortedUniqueNumbers.begin(), sortedUniqueNumbers.end()), sortedUniqueNumbers.end()); 10 | 11 | // Assign ranks to sorted unique elements 12 | for (int i = 0; i < sortedUniqueNumbers.size(); i++) { 13 | valueToRank[sortedUniqueNumbers[i]] = i + 1; 14 | } 15 | 16 | // Replace each element in the original array with its rank 17 | for (int i = 0; i < arr.size(); i++) { 18 | arr[i] = valueToRank[arr[i]]; 19 | } 20 | 21 | return arr; // Return the updated array 22 | } 23 | }; -------------------------------------------------------------------------------- /90-subsets-ii/README.md: -------------------------------------------------------------------------------- 1 |

Subsets II

Difficulty: Medium

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

2 | 3 |

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

4 | 5 |

 

6 |

Example 1:

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

Example 2:

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

 

14 |

Constraints:

15 | 16 |
    17 |
  • 1 <= nums.length <= 10
  • 18 |
  • -10 <= nums[i] <= 10
  • 19 |
20 | -------------------------------------------------------------------------------- /5-longest-palindromic-substring/longest-palindromic-substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestPalindrome(const std::string& s) { 4 | int n = s.length(); 5 | if (n == 0) return ""; 6 | 7 | int longest_palindrome_start = 0; 8 | int longest_palindrome_len = 1; 9 | 10 | for (int i = 0; i < n; ++i) { 11 | int right = i; 12 | while (right < n && s[i] == s[right]) { 13 | right++; 14 | } 15 | 16 | int left = i - 1; 17 | while (left >= 0 && right < n && s[left] == s[right]) { 18 | left--; 19 | right++; 20 | } 21 | 22 | int palindrome_len = right - left - 1; 23 | if (palindrome_len > longest_palindrome_len) { 24 | longest_palindrome_len = palindrome_len; 25 | longest_palindrome_start = left + 1; 26 | } 27 | } 28 | 29 | return s.substr(longest_palindrome_start, longest_palindrome_len); 30 | } 31 | }; -------------------------------------------------------------------------------- /623-add-one-row-to-tree/add-one-row-to-tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* add(TreeNode* root, int val, int depth, int curr) { 4 | if (!root) 5 | return nullptr; 6 | 7 | if (curr == depth - 1) { 8 | TreeNode* lTemp = root->left; 9 | TreeNode* rTemp = root->right; 10 | 11 | root->left = new TreeNode(val); 12 | root->right = new TreeNode(val); 13 | root->left->left = lTemp; 14 | root->right->right = rTemp; 15 | 16 | return root; 17 | } 18 | 19 | root->left = add(root->left, val, depth, curr + 1); 20 | root->right = add(root->right, val, depth, curr + 1); 21 | 22 | return root; 23 | } 24 | 25 | TreeNode* addOneRow(TreeNode* root, int val, int depth) { 26 | if (depth == 1) { 27 | TreeNode* newRoot = new TreeNode(val); 28 | newRoot->left = root; 29 | return newRoot; 30 | } 31 | 32 | return add(root, val, depth, 1); 33 | } 34 | }; -------------------------------------------------------------------------------- /1325-path-with-maximum-probability/path-with-maximum-probability.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double maxProbability(int n, vector>& edges, vector& succProb, int start_node, int end_node) { 4 | vector maxProb(n, 0.0); 5 | maxProb[start_node] = 1.0; 6 | 7 | for (int i = 0; i < n - 1; ++i) { 8 | bool updated = false; 9 | for (int j = 0; j < edges.size(); ++j) { 10 | int u = edges[j][0]; 11 | int v = edges[j][1]; 12 | double prob = succProb[j]; 13 | 14 | if (maxProb[u] * prob > maxProb[v]) { 15 | maxProb[v] = maxProb[u] * prob; 16 | updated = true; 17 | } 18 | if (maxProb[v] * prob > maxProb[u]) { 19 | maxProb[u] = maxProb[v] * prob; 20 | updated = true; 21 | } 22 | } 23 | if (!updated) break; 24 | } 25 | 26 | return maxProb[end_node]; 27 | } 28 | }; -------------------------------------------------------------------------------- /118-pascals-triangle/README.md: -------------------------------------------------------------------------------- 1 |

Pascal's Triangle

Difficulty: Easy

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

2 | 3 |

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

4 | 5 |

 

6 |

Example 1:

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

Example 2:

10 |
Input: numRows = 1
11 | Output: [[1]]
12 | 
13 |

 

14 |

Constraints:

15 | 16 |
    17 |
  • 1 <= numRows <= 30
  • 18 |
19 | -------------------------------------------------------------------------------- /131-palindrome-partitioning/README.md: -------------------------------------------------------------------------------- 1 |

Palindrome Partitioning

Difficulty: Medium

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

2 | 3 |

 

4 |

Example 1:

5 |
Input: s = "aab"
 6 | Output: [["a","a","b"],["aa","b"]]
 7 | 

Example 2:

8 |
Input: s = "a"
 9 | Output: [["a"]]
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • 1 <= s.length <= 16
  • 16 |
  • s contains only lowercase English letters.
  • 17 |
18 | -------------------------------------------------------------------------------- /200-number-of-islands/number-of-islands.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numIslands(vector>& grid) { 4 | if (grid.empty() || grid[0].empty()) { 5 | return 0; 6 | } 7 | 8 | int numIslands = 0; 9 | for (int i = 0; i < grid.size(); i++) { 10 | for (int j = 0; j < grid[0].size(); j++) { 11 | if (grid[i][j] == '1') { 12 | numIslands++; 13 | dfs(grid, i, j); 14 | } 15 | } 16 | } 17 | 18 | return numIslands; 19 | } 20 | 21 | private: 22 | void dfs(vector>& grid, int i, int j) { 23 | if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j] != '1') { 24 | return; 25 | } 26 | 27 | grid[i][j] = '0'; // mark as visited 28 | dfs(grid, i + 1, j); // down 29 | dfs(grid, i - 1, j); // up 30 | dfs(grid, i, j + 1); // right 31 | dfs(grid, i, j - 1); // left 32 | } 33 | }; -------------------------------------------------------------------------------- /506-relative-ranks/relative-ranks.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findRelativeRanks(vector& score) { 4 | int N = score.size(); 5 | 6 | // Create a max heap of pairs (score, index) 7 | priority_queue> heap; 8 | for (int i = 0; i < N; i++) { 9 | heap.push({score[i], i}); 10 | } 11 | 12 | // Assign ranks to athletes 13 | vector rank(N); 14 | int place = 1; 15 | while (!heap.empty()) { 16 | int originalIndex = heap.top().second; 17 | heap.pop(); 18 | if (place == 1) { 19 | rank[originalIndex] = "Gold Medal"; 20 | } else if (place == 2) { 21 | rank[originalIndex] = "Silver Medal"; 22 | } else if (place == 3) { 23 | rank[originalIndex] = "Bronze Medal"; 24 | } else { 25 | rank[originalIndex] = to_string(place); 26 | } 27 | place++; 28 | } 29 | return rank; 30 | } 31 | }; -------------------------------------------------------------------------------- /1030-smallest-string-starting-from-leaf/smallest-string-starting-from-leaf.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string smallestFromLeaf(TreeNode* root) { 4 | string smallest; 5 | dfs(root, "", smallest); 6 | return smallest; 7 | } 8 | 9 | void dfs(TreeNode* node, string path, string& smallest) { 10 | if (node == nullptr) return; 11 | 12 | // Append current node's character to the path 13 | path += char('a' + node->val); 14 | 15 | // If it's a leaf node, compare and update smallest 16 | if (node->left == nullptr && node->right == nullptr) { 17 | reverse(path.begin(), path.end()); 18 | if (smallest.empty() || path < smallest) { 19 | smallest = path; 20 | } 21 | reverse(path.begin(), path.end()); // backtrack by reversing again 22 | } 23 | 24 | // Recursively traverse left and right subtrees 25 | dfs(node->left, path, smallest); 26 | dfs(node->right, path, smallest); 27 | } 28 | }; -------------------------------------------------------------------------------- /1818-maximum-score-from-removing-substrings/maximum-score-from-removing-substrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumGain(string s, int x, int y) { 4 | int aCount = 0; 5 | int bCount = 0; 6 | int lesser = min(x, y); 7 | int result = 0; 8 | 9 | for (char c : s) { 10 | if (c > 'b') { 11 | result += min(aCount, bCount) * lesser; 12 | aCount = 0; 13 | bCount = 0; 14 | } else if (c == 'a') { 15 | if (x < y && bCount > 0) { 16 | bCount--; 17 | result += y; 18 | } else { 19 | aCount++; 20 | } 21 | } else { 22 | if (x > y && aCount > 0) { 23 | aCount--; 24 | result += x; 25 | } else { 26 | bCount++; 27 | } 28 | } 29 | } 30 | 31 | result += min(aCount, bCount) * lesser; 32 | return result; 33 | } 34 | }; -------------------------------------------------------------------------------- /2581-divide-players-into-teams-of-equal-skill/divide-players-into-teams-of-equal-skill.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static long long dividePlayers(vector& skill) { 4 | const int n=skill.size(), n_2=n/2; 5 | long long sum=0; 6 | int freq[1001]={0}, xMax=1, xMin=1000; 7 | for(int x: skill){ 8 | sum+=x; 9 | freq[x]++; 10 | xMax=max(x, xMax); 11 | xMin=min(x, xMin); 12 | } 13 | if (sum%n_2!=0) return -1; 14 | int team_skill=sum/n_2; 15 | 16 | long long chemi=0; 17 | int l, r; 18 | for(l=xMin, r=xMax; l& timePoints) { 4 | vectorminutes; 5 | 6 | //step 1 : convert hours strings to minutes integer 7 | for(int i=0; i>& roads) { 4 | vector>> al(n); 5 | vector time(n, 0), cnt(n, 1); 6 | for (auto &r : roads) { 7 | al[r[0]].push_back({r[1], r[2]}); 8 | al[r[1]].push_back({r[0], r[2]}); 9 | } 10 | priority_queue, vector>, greater<>> pq; 11 | pq.push({0, 0}); 12 | while (!pq.empty()) { 13 | auto[dist, i] = pq.top(); pq.pop(); 14 | for (auto [j, t] : al[i]) { 15 | if (time[j] == 0 || time[j] >= dist + t) { 16 | if (time[j] == dist + t) 17 | cnt[j] = (cnt[j] + cnt[i]) % 1000000007; 18 | else { 19 | time[j] = dist + t; 20 | cnt[j] = cnt[i]; 21 | pq.push({time[j], j}); 22 | } 23 | } 24 | } 25 | } 26 | return cnt[n - 1]; 27 | } 28 | }; -------------------------------------------------------------------------------- /2379-maximum-total-importance-of-roads/maximum-total-importance-of-roads.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long maximumImportance(int n, vector>& roads) { 4 | vector degree(n, 0); // Array to store the degree of each city 5 | 6 | // Calculate the degree of each city 7 | for (const auto& road : roads) { 8 | degree[road[0]]++; 9 | degree[road[1]]++; 10 | } 11 | 12 | // Create a list of cities and sort by degree 13 | vector cities(n); 14 | for (int i = 0; i < n; i++) { 15 | cities[i] = i; 16 | } 17 | sort(cities.begin(), cities.end(), [&](int a, int b) { 18 | return degree[a] > degree[b]; 19 | }); 20 | 21 | // Assign values to cities starting from the highest degree 22 | long long totalImportance = 0; 23 | for (int i = 0; i < n; i++) { 24 | totalImportance += (long long)(n - i) * degree[cities[i]]; 25 | } 26 | 27 | return totalImportance; 28 | } 29 | }; -------------------------------------------------------------------------------- /485-max-consecutive-ones/README.md: -------------------------------------------------------------------------------- 1 |

Max Consecutive Ones

Difficulty: Easy

Given a binary array nums, return the maximum number of consecutive 1's in the array.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: nums = [1,1,0,1,1,1]
 8 | Output: 3
 9 | Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
10 | 
11 | 12 |

Example 2:

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

 

20 |

Constraints:

21 | 22 |
    23 |
  • 1 <= nums.length <= 105
  • 24 |
  • nums[i] is either 0 or 1.
  • 25 |
26 | -------------------------------------------------------------------------------- /560-subarray-sum-equals-k/README.md: -------------------------------------------------------------------------------- 1 |

Subarray Sum Equals K

Difficulty: Medium

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

2 | 3 |

A subarray is a contiguous non-empty sequence of elements within an array.

4 | 5 |

 

6 |

Example 1:

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

Example 2:

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

 

14 |

Constraints:

15 | 16 |
    17 |
  • 1 <= nums.length <= 2 * 104
  • 18 |
  • -1000 <= nums[i] <= 1000
  • 19 |
  • -107 <= k <= 107
  • 20 |
21 | -------------------------------------------------------------------------------- /1044-find-common-characters/README.md: -------------------------------------------------------------------------------- 1 |

Find Common Characters

Difficulty: Easy

Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.

2 | 3 |

 

4 |

Example 1:

5 |
Input: words = ["bella","label","roller"]
 6 | Output: ["e","l","l"]
 7 | 

Example 2:

8 |
Input: words = ["cool","lock","cook"]
 9 | Output: ["c","o"]
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • 1 <= words.length <= 100
  • 16 |
  • 1 <= words[i].length <= 100
  • 17 |
  • words[i] consists of lowercase English letters.
  • 18 |
19 | -------------------------------------------------------------------------------- /802-k-th-smallest-prime-fraction/k-th-smallest-prime-fraction.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector kthSmallestPrimeFraction(vector& arr, int k) { 4 | const int n = arr.size(); 5 | double l = 0.0; 6 | double r = 1.0; 7 | 8 | while (l < r) { 9 | const double m = (l + r) / 2.0; 10 | int fractionsNoGreaterThanM = 0; 11 | int p = 0; 12 | int q = 1; 13 | 14 | // For each index i, find the first index j s.t. arr[i] / arr[j] <= m, 15 | // so fractionsNoGreaterThanM for index i will be n - j. 16 | for (int i = 0, j = 1; i < n; ++i) { 17 | while (j < n && arr[i] > m * arr[j]) 18 | ++j; 19 | if (j == n) 20 | break; 21 | fractionsNoGreaterThanM += n - j; 22 | if (p * arr[j] < q * arr[i]) { 23 | p = arr[i]; 24 | q = arr[j]; 25 | } 26 | } 27 | 28 | if (fractionsNoGreaterThanM == k) 29 | return {p, q}; 30 | if (fractionsNoGreaterThanM > k) 31 | r = m; 32 | else 33 | l = m; 34 | } 35 | 36 | throw; 37 | } 38 | }; -------------------------------------------------------------------------------- /1138-grumpy-bookstore-owner/grumpy-bookstore-owner.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSatisfied(vector& customers, vector& grumpy, int minutes) { 4 | int initialSatisfaction = 0; 5 | int maxExtraSatisfaction = 0; 6 | int currentWindowSatisfaction = 0; 7 | 8 | for (int i = 0; i < customers.size(); ++i) { 9 | if (grumpy[i] == 0) { 10 | initialSatisfaction += customers[i]; 11 | } else if (i < minutes) { 12 | currentWindowSatisfaction += customers[i]; 13 | } 14 | } 15 | 16 | maxExtraSatisfaction = currentWindowSatisfaction; 17 | 18 | for (int i = minutes; i < customers.size(); ++i) { 19 | currentWindowSatisfaction += customers[i] * grumpy[i]; 20 | currentWindowSatisfaction -= customers[i - minutes] * grumpy[i - minutes]; 21 | maxExtraSatisfaction = max(maxExtraSatisfaction, currentWindowSatisfaction); 22 | } 23 | 24 | return initialSatisfaction + maxExtraSatisfaction; 25 | } 26 | }; -------------------------------------------------------------------------------- /1044-find-common-characters/find-common-characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector commonChars(vector& words) { 4 | vector last = count(words[0]); 5 | for (int i = 1; i < words.size(); i++) { 6 | last = intersection(last, count(words[i])); 7 | } 8 | 9 | vector result; 10 | for (int i = 0; i < 26; i++) { 11 | while (last[i] > 0) { 12 | result.push_back(string(1, 'a' + i)); 13 | last[i]--; 14 | } 15 | } 16 | 17 | return result; 18 | } 19 | 20 | private: 21 | vector count(const string& str) { 22 | vector frequency(26, 0); 23 | for (char c : str) { 24 | frequency[c - 'a']++; 25 | } 26 | return frequency; 27 | } 28 | 29 | vector intersection(const vector& a, const vector& b) { 30 | vector t(26, 0); 31 | for (int i = 0; i < 26; i++) { 32 | t[i] = min(a[i], b[i]); 33 | } 34 | return t; 35 | } 36 | }; -------------------------------------------------------------------------------- /2121-find-if-path-exists-in-graph/find-if-path-exists-in-graph.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validPath(int n, vector>& edges, int source, int destination) { 4 | unordered_map> graph; 5 | for (const auto& edge : edges) { 6 | int u = edge[0]; 7 | int v = edge[1]; 8 | graph[u].push_back(v); 9 | graph[v].push_back(u); 10 | } 11 | 12 | unordered_set visited; 13 | return dfs(source, destination, graph, visited); 14 | } 15 | 16 | bool dfs(int node, int destination, unordered_map>& graph, unordered_set& visited) { 17 | if (node == destination) { 18 | return true; 19 | } 20 | visited.insert(node); 21 | for (int neighbor : graph[node]) { 22 | if (visited.find(neighbor) == visited.end()) { 23 | if (dfs(neighbor, destination, graph, visited)) { 24 | return true; 25 | } 26 | } 27 | } 28 | return false; 29 | } 30 | }; -------------------------------------------------------------------------------- /670-maximum-swap/maximum-swap.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumSwap(int num) { 4 | // Convert the number to a string for easier digit manipulation 5 | string numStr = to_string(num); 6 | int n = numStr.size(); 7 | 8 | // Store the last occurrence of each digit (0-9) 9 | vector last(10, -1); 10 | for (int i = 0; i < n; ++i) { 11 | last[numStr[i] - '0'] = i; 12 | } 13 | 14 | // Traverse each digit from left to right 15 | for (int i = 0; i < n; ++i) { 16 | // Check if there's a larger digit appearing later 17 | for (int d = 9; d > numStr[i] - '0'; --d) { 18 | if (last[d] > i) { 19 | // Swap the current digit with the larger one 20 | swap(numStr[i], numStr[last[d]]); 21 | return stoi(numStr); // Convert back to integer and return 22 | } 23 | } 24 | } 25 | 26 | // If no swap was made, return the original number 27 | return num; 28 | } 29 | }; -------------------------------------------------------------------------------- /283-move-zeroes/README.md: -------------------------------------------------------------------------------- 1 |

Move Zeroes

Difficulty: Easy

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

2 | 3 |

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

4 | 5 |

 

6 |

Example 1:

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

Example 2:

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

 

14 |

Constraints:

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

 

22 | Follow up: Could you minimize the total number of operations done? -------------------------------------------------------------------------------- /345-reverse-vowels-of-a-string/README.md: -------------------------------------------------------------------------------- 1 |

Reverse Vowels of a String

Difficulty: Easy

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

2 | 3 |

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.

4 | 5 |

 

6 |

Example 1:

7 |
Input: s = "hello"
 8 | Output: "holle"
 9 | 

Example 2:

10 |
Input: s = "leetcode"
11 | Output: "leotcede"
12 | 
13 |

 

14 |

Constraints:

15 | 16 |
    17 |
  • 1 <= s.length <= 3 * 105
  • 18 |
  • s consist of printable ASCII characters.
  • 19 |
20 | -------------------------------------------------------------------------------- /789-kth-largest-element-in-a-stream/kth-largest-element-in-a-stream.cpp: -------------------------------------------------------------------------------- 1 | class KthLargest { 2 | public: 3 | KthLargest(int k, vector& nums) : k(k) { 4 | for (int num : nums) { 5 | if (minHeap.size() < k) { 6 | minHeap.push(num); 7 | } else if (num > minHeap.top()) { 8 | minHeap.push(num); 9 | if (minHeap.size() > k) { 10 | minHeap.pop(); 11 | } 12 | } 13 | } 14 | } 15 | 16 | int add(int val) { 17 | if (minHeap.size() < k) { 18 | minHeap.push(val); 19 | } else if (val > minHeap.top()) { 20 | minHeap.push(val); 21 | minHeap.pop(); 22 | } 23 | return minHeap.top(); 24 | } 25 | 26 | private: 27 | int k; 28 | priority_queue, greater> minHeap; // Min-heap to store the k largest elements 29 | }; 30 | 31 | 32 | /** 33 | * Your KthLargest object will be instantiated and called as such: 34 | * KthLargest* obj = new KthLargest(k, nums); 35 | * int param_1 = obj->add(val); 36 | */ -------------------------------------------------------------------------------- /1915-check-if-one-string-swap-can-make-strings-equal/check-if-one-string-swap-can-make-strings-equal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool areAlmostEqual(string s1, string s2) { 4 | int firstIndexDiff = 0; 5 | int secondIndexDiff = 0; 6 | int numDiffs = 0; 7 | for (int i = 0; i < s1.size(); i++) { 8 | if (s1[i] != s2[i]) { 9 | numDiffs++; 10 | // numDiffs is more than 2, one string swap will not make two 11 | // strings equal 12 | if (numDiffs > 2) 13 | return false; 14 | else if (numDiffs == 1) { 15 | // store the index of first difference 16 | firstIndexDiff = i; 17 | } else { 18 | // store the index of second difference 19 | secondIndexDiff = i; 20 | } 21 | } 22 | } 23 | // check if swap is possible 24 | return s1[firstIndexDiff] == s2[secondIndexDiff] && 25 | s1[secondIndexDiff] == s2[firstIndexDiff]; 26 | } 27 | }; -------------------------------------------------------------------------------- /664-strange-printer/strange-printer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int strangePrinter(string s) { 4 | int n = s.length(); 5 | vector> dp(n, vector(n, -1)); 6 | return Util(0, n - 1, s, dp); 7 | } 8 | 9 | int Util(int i, int j, const string& s, vector>& dp) { 10 | if (i > j) { 11 | return 0; 12 | } 13 | 14 | if (dp[i][j] != -1) return dp[i][j]; 15 | 16 | char firstLetter = s[i]; 17 | // If the current character is not repeated in the rest of the string 18 | int answer = 1 + Util(i + 1, j, s, dp); 19 | for (int k = i + 1; k <= j; k++) { 20 | // If repeated then update the answer 21 | if (s[k] == firstLetter) { 22 | // Splitting from i -> k - 1 (remove the last character) 23 | // and from k + 1 -> j 24 | int betterAnswer = Util(i, k - 1, s, dp) + Util(k + 1, j, s, dp); 25 | answer = min(answer, betterAnswer); 26 | } 27 | } 28 | return dp[i][j] = answer; 29 | } 30 | }; -------------------------------------------------------------------------------- /1558-course-schedule-iv/course-schedule-iv.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector checkIfPrerequisite(int numCourses, vector>& prerequisites, vector>& queries) { 4 | // Step 1: Initialize the reachability map 5 | unordered_map> reachable; 6 | 7 | // Step 2: Build direct reachability chains 8 | for (auto& prereq : prerequisites) { 9 | reachable[prereq[1]].insert(prereq[0]); 10 | } 11 | 12 | // Step 3: Propagate reachability to account for indirect prerequisites 13 | for (int i = 0; i < numCourses; ++i) { 14 | for (int j = 0; j < numCourses; ++j) { 15 | if (reachable[j].count(i)) { 16 | reachable[j].insert(reachable[i].begin(), reachable[i].end()); 17 | } 18 | } 19 | } 20 | 21 | // Step 4: Answer the queries 22 | vector result; 23 | for (auto& query : queries) { 24 | result.push_back(reachable[query[1]].count(query[0]) > 0); 25 | } 26 | return result; 27 | } 28 | }; -------------------------------------------------------------------------------- /2-add-two-numbers/add-two-numbers.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 14 | ListNode *dummy =new ListNode(); 15 | ListNode *temp = dummy; 16 | int carry =0; 17 | while((l1 != NULL || l2 != NULL)||carry){ 18 | int sum=0; 19 | if(l1!=NULL){ 20 | sum += l1->val; 21 | l1 = l1->next; 22 | } 23 | if(l2!=NULL){ 24 | sum += l2->val; 25 | l2 = l2->next; 26 | } 27 | 28 | sum+=carry; 29 | carry=sum/10; 30 | 31 | ListNode* newNode = new ListNode(sum%10); 32 | temp->next=newNode; 33 | 34 | temp = temp->next; 35 | } 36 | return dummy->next; 37 | } 38 | }; -------------------------------------------------------------------------------- /273-integer-to-english-words/README.md: -------------------------------------------------------------------------------- 1 |

Integer to English Words

Difficulty: Hard

Convert a non-negative integer num to its English words representation.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: num = 123
 8 | Output: "One Hundred Twenty Three"
 9 | 
10 | 11 |

Example 2:

12 | 13 |
14 | Input: num = 12345
15 | Output: "Twelve Thousand Three Hundred Forty Five"
16 | 
17 | 18 |

Example 3:

19 | 20 |
21 | Input: num = 1234567
22 | Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • 0 <= num <= 231 - 1
  • 30 |
31 | -------------------------------------------------------------------------------- /5-longest-palindromic-substring/README.md: -------------------------------------------------------------------------------- 1 |

Longest Palindromic Substring

Difficulty: Medium

Given a string s, return the longest palindromic substring in s.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: s = "babad"
 8 | Output: "bab"
 9 | Explanation: "aba" is also a valid answer.
10 | 
11 | 12 |

Example 2:

13 | 14 |
15 | Input: s = "cbbd"
16 | Output: "bb"
17 | 
18 | 19 |

 

20 |

Constraints:

21 | 22 |
    23 |
  • 1 <= s.length <= 1000
  • 24 |
  • s consist of only digits and English letters.
  • 25 |
26 | -------------------------------------------------------------------------------- /1408-find-the-smallest-divisor-given-a-threshold/find-the-smallest-divisor-given-a-threshold.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | int sumByD(vector &nums, int div) { 4 | int sum = 0; 5 | for (int i = 0; i < nums.size(); ++i) { 6 | sum += ceil((double)nums[i] / (double)div); 7 | } 8 | return sum; 9 | } 10 | int findMax(vector& nums) { 11 | int maxi = INT_MIN; 12 | int n = nums.size(); 13 | 14 | // Find the maximum element 15 | for (int i = 0; i < n; i++) { 16 | maxi = max(maxi, nums[i]); 17 | } 18 | return maxi; 19 | } 20 | 21 | public: 22 | int smallestDivisor(vector &nums, int limit) { 23 | int n = nums.size(); 24 | if (n > limit) return -1; 25 | 26 | int low = 1, high = findMax(nums); 27 | 28 | while (low <= high) { 29 | int mid = low + (high - low) / 2; 30 | if (sumByD(nums, mid) <= limit) { 31 | high = mid - 1; 32 | } else 33 | low = mid + 1; 34 | } 35 | return low; 36 | } 37 | }; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Harsh Gautam 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /1431-all-ancestors-of-a-node-in-a-directed-acyclic-graph/all-ancestors-of-a-node-in-a-directed-acyclic-graph.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> getAncestors(int n, vector>& edges) { 4 | vector> res(n); 5 | vector> graph(n); 6 | 7 | for (const auto& edge : edges) { 8 | graph[edge[0]].push_back(edge[1]); 9 | } 10 | 11 | for (int i = 0; i < n; ++i) { 12 | vector visit(n, false); 13 | dfs(graph, i, i, res, visit); 14 | } 15 | 16 | for (int i = 0; i < n; ++i) { 17 | sort(res[i].begin(), res[i].end()); 18 | } 19 | 20 | return res; 21 | } 22 | 23 | private: 24 | void dfs(vector>& graph, int parent, int curr, vector>& res, vector& visit) { 25 | visit[curr] = true; 26 | for (int dest : graph[curr]) { 27 | if (!visit[dest]) { 28 | res[dest].push_back(parent); 29 | dfs(graph, parent, dest, res, visit); 30 | } 31 | } 32 | } 33 | }; -------------------------------------------------------------------------------- /820-find-eventual-safe-states/find-eventual-safe-states.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int n; 4 | vector degreein; 5 | vector< vector > rGraph; 6 | vector ans; 7 | 8 | void init(vector>& G){ 9 | n = G.size(); 10 | degreein = vector(n,0); 11 | rGraph.resize(n, vector(0) ); 12 | 13 | for (int u=0; u eventualSafeNodes(vector>& graph) { 22 | init(graph); 23 | queue que; 24 | for (int i=0; i charSet; 6 | // Initialize the length of the longest palindrome 7 | int length = 0; 8 | 9 | // Iterate over each character in the string 10 | for (char c : s) { 11 | // If the character is already in the set, remove it and increase the length by 2 12 | if (charSet.find(c) != charSet.end()) { 13 | charSet.erase(c); 14 | length += 2; 15 | } else { 16 | // If the character is not in the set, add it to the set 17 | charSet.insert(c); 18 | } 19 | } 20 | 21 | // If there are any characters left in the set, add 1 to the length for the middle character 22 | if (!charSet.empty()) { 23 | length += 1; 24 | } 25 | 26 | // Return the total length of the longest palindrome 27 | return length; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /921-spiral-matrix-iii/spiral-matrix-iii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> spiralMatrixIII(int rows, int cols, int rStart, int cStart) { 4 | int i = rStart, j = cStart; 5 | int diri = 0, dirj = 1; // directions to move 6 | int twice = 2; 7 | vector> res; 8 | int moves = 1; 9 | int next_moves = 2; 10 | 11 | while (res.size() < rows * cols) { 12 | if (i >= 0 && i < rows && j >= 0 && j < cols) { 13 | res.push_back({i, j}); 14 | } 15 | 16 | i += diri; 17 | j += dirj; 18 | moves -= 1; 19 | if (moves == 0) { 20 | int temp = diri; 21 | diri = dirj; 22 | dirj = -temp; // right direction 23 | twice -= 1; 24 | if (twice == 0) { 25 | twice = 2; 26 | moves = next_moves; 27 | next_moves += 1; 28 | } else { 29 | moves = next_moves - 1; 30 | } 31 | } 32 | } 33 | return res; 34 | } 35 | }; -------------------------------------------------------------------------------- /344-reverse-string/README.md: -------------------------------------------------------------------------------- 1 |

Reverse String

Difficulty: Easy

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

2 | 3 |

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

4 | 5 |

 

6 |

Example 1:

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

Example 2:

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

 

14 |

Constraints:

15 | 16 | 20 | -------------------------------------------------------------------------------- /78-subsets/README.md: -------------------------------------------------------------------------------- 1 |

Subsets

Difficulty: Medium

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

2 | 3 |

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

4 | 5 |

 

6 |

Example 1:

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

Example 2:

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

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= nums.length <= 10
  • 25 |
  • -10 <= nums[i] <= 10
  • 26 |
  • All the numbers of nums are unique.
  • 27 |
28 | -------------------------------------------------------------------------------- /79-word-search/word-search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | bool func(vector >& v, int i, int j, string& s, int k) { 4 | if (k == s.length()) { 5 | return true; 6 | } 7 | if (i < 0 || j < 0 || i >= v.size() || j >= v[0].size() || 8 | s[k] != v[i][j]) { 9 | return false; 10 | } 11 | bool ans = false; 12 | char x = v[i][j]; 13 | v[i][j] = ' '; 14 | ans |= func(v, i + 1, j, s, k + 1); 15 | ans |= func(v, i - 1, j, s, k + 1); 16 | ans |= func(v, i, j + 1, s, k + 1); 17 | ans |= func(v, i, j - 1, s, k + 1); 18 | v[i][j] = x; 19 | return ans; 20 | } 21 | 22 | public: 23 | bool exist(vector >& board, string word) { 24 | for (int i = 0; i < board.size(); i++) { 25 | for (int j = 0; j < board[0].size(); j++) { 26 | if (board[i][j] == word[0]) { 27 | if (func(board, i, j, word, 0)) { 28 | return true; 29 | } 30 | } 31 | } 32 | } 33 | return false; 34 | } 35 | }; -------------------------------------------------------------------------------- /264-ugly-number-ii/README.md: -------------------------------------------------------------------------------- 1 |

Ugly Number II

Difficulty: Medium

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

2 | 3 |

Given an integer n, return the nth ugly number.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: n = 10
10 | Output: 12
11 | Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: n = 1
18 | Output: 1
19 | Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 1 <= n <= 1690
  • 27 |
28 | -------------------------------------------------------------------------------- /205-isomorphic-strings/isomorphic-strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isIsomorphic(string s, string t) { 4 | vector indexS(200, 0); // Stores index of characters in string s 5 | vector indexT(200, 0); // Stores index of characters in string t 6 | 7 | int len = s.length(); // Get the length of both strings 8 | 9 | if(len != t.length()) { // If the lengths of the two strings are different, they can't be isomorphic 10 | return false; 11 | } 12 | 13 | for(int i = 0; i < len; i++) { // Iterate through each character of the strings 14 | if(indexS[s[i]] != indexT[t[i]]) { // Check if the index of the current character in string s is different from the index of the corresponding character in string t 15 | return false; // If different, strings are not isomorphic 16 | } 17 | 18 | indexS[s[i]] = i + 1; // updating position of current character 19 | indexT[t[i]] = i + 1; 20 | } 21 | 22 | return true; // If the loop completes without returning false, strings are isomorphic 23 | } 24 | }; -------------------------------------------------------------------------------- /523-continuous-subarray-sum/continuous-subarray-sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Solution { 4 | public: 5 | bool checkSubarraySum(std::vector& numbers, int divisor) { 6 | ios::sync_with_stdio(false); 7 | cin.tie(0); 8 | cout.tie(0); 9 | 10 | int currentSum = numbers[0]; 11 | int length = numbers.size(); 12 | int index, tempSum; 13 | 14 | for (int i = 1; i < length; i++) { 15 | if (numbers[i] == numbers[i - 1] && numbers[i] == 0) { 16 | return true; 17 | } 18 | 19 | currentSum += numbers[i]; 20 | 21 | if (currentSum % divisor == 0) { 22 | return true; 23 | } 24 | 25 | index = 0; 26 | tempSum = currentSum; 27 | 28 | while ((i - index) > 1 && tempSum >= divisor) { 29 | tempSum -= numbers[index++]; 30 | 31 | if (tempSum % divisor == 0) { 32 | return true; 33 | } 34 | } 35 | } 36 | 37 | return false; 38 | } 39 | }; -------------------------------------------------------------------------------- /1331-path-with-maximum-gold/path-with-maximum-gold.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector roww = {1, -1, 0, 0}; 4 | vector coll = {0, 0, -1, 1}; 5 | int maxGold = 0; 6 | 7 | int dfs(vector>& grid, int x, int y, int n, int m) { 8 | if (x < 0 || x >= n || y < 0 || y >= m || grid[x][y] == 0) return 0; 9 | 10 | int curr = grid[x][y]; 11 | grid[x][y] = 0; 12 | int localMaxGold = curr; 13 | 14 | for (int i = 0; i < 4; i++) { 15 | int newX = x + roww[i]; 16 | int newY = y + coll[i]; 17 | localMaxGold = max(localMaxGold, curr + dfs(grid, newX, newY, n, m)); 18 | } 19 | 20 | grid[x][y] = curr; 21 | return localMaxGold; 22 | } 23 | 24 | int getMaximumGold(vector>& grid) { 25 | int n = grid.size(), m = grid[0].size(); 26 | 27 | for (int i = 0; i < n; i++) { 28 | for (int j = 0; j < m; j++) { 29 | if (grid[i][j] != 0) { 30 | maxGold = max(maxGold, dfs(grid, i, j, n, m)); 31 | } 32 | } 33 | } 34 | 35 | return maxGold; 36 | } 37 | }; -------------------------------------------------------------------------------- /85-maximal-rectangle/maximal-rectangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximalRectangle(vector>& matrix) { 4 | if (matrix.empty() || matrix[0].empty()) 5 | return 0; 6 | 7 | int rows = matrix.size(); 8 | int cols = matrix[0].size(); 9 | vector heights(cols + 1, 0); // Include an extra element for easier calculation 10 | int maxArea = 0; 11 | 12 | for (const auto& row : matrix) { 13 | for (int i = 0; i < cols; i++) { 14 | heights[i] = (row[i] == '1') ? heights[i] + 1 : 0; 15 | } 16 | 17 | // Calculate max area using histogram method 18 | int n = heights.size(); // Number of bars in the histogram 19 | 20 | for (int i = 0; i < n; i++) { 21 | for (int j = i, minHeight = INT_MAX; j < n; j++) { 22 | minHeight = min(minHeight, heights[j]); 23 | int area = minHeight * (j - i + 1); 24 | maxArea = max(maxArea, area); 25 | } 26 | } 27 | } 28 | 29 | return maxArea; 30 | } 31 | }; -------------------------------------------------------------------------------- /128-longest-consecutive-sequence/README.md: -------------------------------------------------------------------------------- 1 |

Longest Consecutive Sequence

Difficulty: Medium

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

2 | 3 |

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

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums = [100,4,200,1,3,2]
10 | Output: 4
11 | Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: nums = [0,3,7,2,5,8,4,6,0,1]
18 | Output: 9
19 | 
20 | 21 |

 

22 |

Constraints:

23 | 24 |
    25 |
  • 0 <= nums.length <= 105
  • 26 |
  • -109 <= nums[i] <= 109
  • 27 |
28 | -------------------------------------------------------------------------------- /169-majority-element/README.md: -------------------------------------------------------------------------------- 1 |

Majority Element

Difficulty: Easy

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

2 | 3 |

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

4 | 5 |

 

6 |

Example 1:

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

Example 2:

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

 

14 |

Constraints:

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

 

23 | Follow-up: Could you solve the problem in linear time and in O(1) space? -------------------------------------------------------------------------------- /61-rotate-list/README.md: -------------------------------------------------------------------------------- 1 |

Rotate List

Difficulty: Medium

Given the head of a linked list, rotate the list to the right by k places.

2 | 3 |

 

4 |

Example 1:

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

Example 2:

12 | 13 |
14 | Input: head = [0,1,2], k = 4
15 | Output: [2,0,1]
16 | 
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • The number of nodes in the list is in the range [0, 500].
  • 23 |
  • -100 <= Node.val <= 100
  • 24 |
  • 0 <= k <= 2 * 109
  • 25 |
26 | -------------------------------------------------------------------------------- /1236-n-th-tribonacci-number/README.md: -------------------------------------------------------------------------------- 1 |

N-th Tribonacci Number

Difficulty: Easy

The Tribonacci sequence Tn is defined as follows: 

2 | 3 |

T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.

4 | 5 |

Given n, return the value of Tn.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: n = 4
12 | Output: 4
13 | Explanation:
14 | T_3 = 0 + 1 + 1 = 2
15 | T_4 = 1 + 1 + 2 = 4
16 | 
17 | 18 |

Example 2:

19 | 20 |
21 | Input: n = 25
22 | Output: 1389537
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • 0 <= n <= 37
  • 30 |
  • The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.
  • 31 |
-------------------------------------------------------------------------------- /1093-recover-a-tree-from-preorder-traversal/recover-a-tree-from-preorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* recoverFromPreorder(string S) { 15 | vector stack; 16 | for (int i = 0, level, val; i < S.length();) { 17 | for (level = 0; S[i] == '-'; i++) 18 | level++; 19 | for (val = 0; i < S.length() && S[i] != '-'; i++) 20 | val = val * 10 + S[i] - '0'; 21 | TreeNode* node = new TreeNode(val); 22 | while (stack.size() > level) stack.pop_back(); 23 | if (!stack.empty()) 24 | if (!stack.back()->left) stack.back()->left = node; 25 | else stack.back()->right = node; 26 | stack.push_back(node); 27 | } 28 | return stack[0]; 29 | } 30 | }; -------------------------------------------------------------------------------- /2212-removing-minimum-and-maximum-from-array/removing-minimum-and-maximum-from-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumDeletions(vector& nums) { 4 | // storing no with their index so that we can get min index and max index 5 | unordered_mapmpp; 6 | 7 | for(int i = 0; iValid Palindrome II Difficulty: Easy

Given a string s, return true if the s can be palindrome after deleting at most one character from it.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: s = "aba"
 8 | Output: true
 9 | 
10 | 11 |

Example 2:

12 | 13 |
14 | Input: s = "abca"
15 | Output: true
16 | Explanation: You could delete the character 'c'.
17 | 
18 | 19 |

Example 3:

20 | 21 |
22 | Input: s = "abc"
23 | Output: false
24 | 
25 | 26 |

 

27 |

Constraints:

28 | 29 |
    30 |
  • 1 <= s.length <= 105
  • 31 |
  • s consists of lowercase English letters.
  • 32 |
33 | -------------------------------------------------------------------------------- /88-merge-sorted-array/merge-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | 4 | 5 | public: 6 | void merge(vector& nums1, int m, vector& nums2, int n) { 7 | int len = m+n; 8 | int gap = (len/2)+(len%2); 9 | 10 | while(gap>0){ 11 | int left =0; 12 | int right = left+gap; 13 | 14 | while(right=m){ 16 | swapIfgreater(nums1, nums2, left, right-m); 17 | } 18 | else if(left>=m){ 19 | swapIfgreater(nums2, nums2, left-m, right-m); 20 | } 21 | else { 22 | swapIfgreater(nums1, nums1, left, right); 23 | } 24 | left++, right++; 25 | } 26 | if(gap==1)break; 27 | gap = (gap/2) + (gap%2); 28 | } 29 | for (int i = m; i < m + n; i++) { 30 | nums1[i] = nums2[i - m]; 31 | } 32 | } 33 | 34 | private: 35 | void swapIfgreater(vector& nums1,vector& nums2, int idx1, int idx2){ 36 | if(nums1[idx1]>nums2[idx2]){ 37 | swap(nums1[idx1],nums2[idx2]); 38 | } 39 | }; 40 | }; -------------------------------------------------------------------------------- /1876-map-of-highest-peak/map-of-highest-peak.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> highestPeak(vector>& isWater) { 4 | int m = isWater.size(), n = isWater[0].size(); 5 | vector> height(m, vector(n, -1)); 6 | queue> q; 7 | 8 | // Initialize water cells 9 | for(int i = 0; i < m; i++) { 10 | for(int j = 0; j < n; j++) { 11 | if(isWater[i][j]) { 12 | height[i][j] = 0; 13 | q.push({i, j}); 14 | } 15 | } 16 | } 17 | 18 | // BFS directions 19 | int dirs[4][2] = {{1,0}, {-1,0}, {0,1}, {0,-1}}; 20 | 21 | // BFS from water to land 22 | while(!q.empty()) { 23 | auto [x, y] = q.front(); q.pop(); 24 | for(auto [dx, dy] : dirs) { 25 | int nx = x + dx, ny = y + dy; 26 | if(nx >= 0 && nx < m && ny >= 0 && ny < n && height[nx][ny] == -1) { 27 | height[nx][ny] = height[x][y] + 1; 28 | q.push({nx, ny}); 29 | } 30 | } 31 | } 32 | return height; 33 | } 34 | }; -------------------------------------------------------------------------------- /14-longest-common-prefix/README.md: -------------------------------------------------------------------------------- 1 |

Longest Common Prefix

Difficulty: Easy

Write a function to find the longest common prefix string amongst an array of strings.

2 | 3 |

If there is no common prefix, return an empty string "".

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: strs = ["flower","flow","flight"]
10 | Output: "fl"
11 | 
12 | 13 |

Example 2:

14 | 15 |
16 | Input: strs = ["dog","racecar","car"]
17 | Output: ""
18 | Explanation: There is no common prefix among the input strings.
19 | 
20 | 21 |

 

22 |

Constraints:

23 | 24 |
    25 |
  • 1 <= strs.length <= 200
  • 26 |
  • 0 <= strs[i].length <= 200
  • 27 |
  • strs[i] consists of only lowercase English letters.
  • 28 |
29 | -------------------------------------------------------------------------------- /1285-balance-a-binary-search-tree/balance-a-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector sortedArr; 15 | TreeNode* balanceBST(TreeNode* root) { 16 | inorderTraverse(root); 17 | return sortedArrayToBST(0, sortedArr.size() - 1); 18 | } 19 | void inorderTraverse(TreeNode* root) { 20 | if (root == NULL) return; 21 | inorderTraverse(root->left); 22 | sortedArr.push_back(root); 23 | inorderTraverse(root->right); 24 | } 25 | TreeNode* sortedArrayToBST(int start, int end) { 26 | if (start > end) return NULL; 27 | int mid = (start + end) / 2; 28 | TreeNode* root = sortedArr[mid]; 29 | root->left = sortedArrayToBST(start, mid - 1); 30 | root->right = sortedArrayToBST(mid + 1, end); 31 | return root; 32 | } 33 | }; -------------------------------------------------------------------------------- /2163-kth-distinct-string-in-an-array/kth-distinct-string-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | // struct Trie for N alphabets 2 | const int N=26; 3 | struct Trie { 4 | Trie* next[N]; 5 | int count=0; 6 | 7 | Trie() { 8 | // cout<<"Create a trie object!\n"; 9 | memset(next, 0, sizeof(next)); 10 | } 11 | 12 | void insert(string& s) { 13 | Trie* Node=this; 14 | for(char c: s){ 15 | int i=c-'a'; 16 | if (Node->next[i]==NULL) Node->next[i]=new Trie(); 17 | Node=Node->next[i]; 18 | } 19 | Node->count++; 20 | } 21 | bool findcnt1(string& s) { 22 | Trie* Node=this; 23 | for(char c: s){ 24 | int i=c-'a'; 25 | if (Node->next[i]==NULL) return 0; 26 | Node=Node->next[i]; 27 | } 28 | return Node->count==1; 29 | } 30 | }; 31 | 32 | 33 | class Solution { 34 | public: 35 | static string kthDistinct(vector& arr, int k) { 36 | Trie trie; 37 | for(string& s: arr) 38 | trie.insert(s); 39 | 40 | for(string& s: arr){ 41 | if (trie.findcnt1(s)==1) k--; 42 | if (k==0) return s; 43 | } 44 | return ""; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /1605-minimum-number-of-days-to-make-m-bouquets/minimum-number-of-days-to-make-m-bouquets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool possible(int n, vector nums, int day, int k, int m) { 4 | int cnt = 0; 5 | int noOfB = 0; 6 | for (int i = 0; i < n; i++) { 7 | if (nums[i] <= day) 8 | cnt++; 9 | else { 10 | noOfB += cnt / k; 11 | cnt = 0; 12 | } 13 | } 14 | noOfB += cnt / k; 15 | return noOfB >= m; 16 | } 17 | int minDays(vector& nums, int m, int k) { 18 | long long val = k * 1ll * m * 1ll; 19 | int n =nums.size(); 20 | if (n < val) 21 | return -1; 22 | 23 | int mini = INT_MAX, maxi = INT_MIN; 24 | for (int i = 0; i < n; ++i) { 25 | maxi = max(nums[i], maxi); 26 | mini = min(nums[i], mini); 27 | } 28 | int left = mini, right = maxi; 29 | while (left <= right) { 30 | int mid = left + (right - left) / 2; 31 | if (possible(n, nums, mid, k, m)) { 32 | right = mid - 1; 33 | } else 34 | left = mid + 1; 35 | } 36 | return left; 37 | } 38 | }; -------------------------------------------------------------------------------- /1549-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestSubarray(std::vector& nums, int limit) { 4 | std::deque decQ; 5 | std::deque incQ; 6 | int ans = 0; 7 | int left = 0; 8 | 9 | for (int right = 0; right < nums.size(); ++right) { 10 | int num = nums[right]; 11 | 12 | while (!decQ.empty() && num > decQ.back()) { 13 | decQ.pop_back(); 14 | } 15 | decQ.push_back(num); 16 | 17 | while (!incQ.empty() && num < incQ.back()) { 18 | incQ.pop_back(); 19 | } 20 | incQ.push_back(num); 21 | 22 | while (decQ.front() - incQ.front() > limit) { 23 | if (decQ.front() == nums[left]) { 24 | decQ.pop_front(); 25 | } 26 | if (incQ.front() == nums[left]) { 27 | incQ.pop_front(); 28 | } 29 | ++left; 30 | } 31 | 32 | ans = std::max(ans, right - left + 1); 33 | } 34 | 35 | return ans; 36 | } 37 | }; -------------------------------------------------------------------------------- /143-reorder-list/reorder-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | void reorderList(ListNode* head) { 14 | stack s; 15 | ListNode* curr = head; 16 | while(curr){ 17 | s.push(curr); 18 | curr = curr->next; 19 | } 20 | curr = head; 21 | unordered_map vis; 22 | while(true){ 23 | ListNode* last = s.top(); 24 | s.pop(); 25 | ListNode* next = curr->next; 26 | vis[curr] = true; 27 | if(vis[last]){ 28 | curr->next = NULL; 29 | break; 30 | } 31 | curr->next = last; 32 | vis[last] = true; 33 | curr = curr->next; 34 | if(vis[next]){ 35 | curr->next = NULL; 36 | break; 37 | } 38 | curr->next = next; 39 | curr = curr->next; 40 | } 41 | } 42 | }; -------------------------------------------------------------------------------- /404-sum-of-left-leaves/README.md: -------------------------------------------------------------------------------- 1 |

Sum of Left Leaves

Difficulty: Easy

Given the root of a binary tree, return the sum of all left leaves.

2 | 3 |

A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: root = [3,9,20,null,null,15,7]
10 | Output: 24
11 | Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: root = [1]
18 | Output: 0
19 | 
20 | 21 |

 

22 |

Constraints:

23 | 24 |
    25 |
  • The number of nodes in the tree is in the range [1, 1000].
  • 26 |
  • -1000 <= Node.val <= 1000
  • 27 |
28 | -------------------------------------------------------------------------------- /3227-find-missing-and-repeated-values/find-missing-and-repeated-values.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findMissingAndRepeatedValues(vector>& grid) { 4 | int n = grid.size(); 5 | int n_squared = n * n; 6 | 7 | long long expected_sum = 1LL * n_squared * (n_squared + 1) / 2; 8 | long long expected_sum_squares = 1LL * n_squared * (n_squared + 1) * (2 * n_squared + 1) / 6; 9 | 10 | long long actual_sum = 0, actual_sum_squares = 0; 11 | 12 | for (int i = 0; i < n; i++) { 13 | for (int j = 0; j < n; j++) { 14 | actual_sum += grid[i][j]; 15 | actual_sum_squares += (long long)grid[i][j] * grid[i][j]; 16 | } 17 | } 18 | 19 | // a - b 20 | long long diff_sum = actual_sum - expected_sum; 21 | 22 | // a² - b² 23 | long long diff_sum_squares = actual_sum_squares - expected_sum_squares; 24 | 25 | // a + b = (a² - b²) / (a - b) 26 | long long sum_a_b = diff_sum_squares / diff_sum; 27 | 28 | // Now we can find a and b 29 | int a = (sum_a_b + diff_sum) / 2; 30 | int b = (sum_a_b - diff_sum) / 2; 31 | 32 | return {a, b}; 33 | } 34 | }; -------------------------------------------------------------------------------- /69-sqrtx/README.md: -------------------------------------------------------------------------------- 1 |

Sqrt(x)

Difficulty: Easy

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

2 | 3 |

You must not use any built-in exponent function or operator.

4 | 5 |
    6 |
  • For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.
  • 7 |
8 | 9 |

 

10 |

Example 1:

11 | 12 |
13 | Input: x = 4
14 | Output: 2
15 | Explanation: The square root of 4 is 2, so we return 2.
16 | 
17 | 18 |

Example 2:

19 | 20 |
21 | Input: x = 8
22 | Output: 2
23 | Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
24 | 
25 | 26 |

 

27 |

Constraints:

28 | 29 |
    30 |
  • 0 <= x <= 231 - 1
  • 31 |
32 | -------------------------------------------------------------------------------- /2299-merge-nodes-in-between-zeros/merge-nodes-in-between-zeros.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* mergeNodes(ListNode* head) { 14 | ListNode* modify = head->next; // Start from the node after the initial 0 15 | ListNode* nextSum = modify; 16 | 17 | while (nextSum != nullptr) { 18 | int sum = 0; 19 | // Find the sum of all nodes until you encounter a 0. 20 | while (nextSum->val != 0) { 21 | sum += nextSum->val; 22 | nextSum = nextSum->next; 23 | } 24 | 25 | // Assign the sum to the current node's value. 26 | modify->val = sum; 27 | // Move nextSum to the first non-zero value of the next block. 28 | nextSum = nextSum->next; 29 | // Move modify also to this node. 30 | modify->next = nextSum; 31 | modify = modify->next; 32 | } 33 | return head->next; // Skip the initial 0 node. 34 | } 35 | }; -------------------------------------------------------------------------------- /2764-maximum-number-of-fish-in-a-grid/maximum-number-of-fish-in-a-grid.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxFish(vector>& grid) { 4 | int Max = 0; 5 | for (int i = 0; i < grid.size(); i++) { 6 | for (int j = 0; j < grid[0].size(); j++) { 7 | if (grid[i][j] > 0) { 8 | int C = 0; 9 | queue> T; 10 | T.push({i, j}); 11 | while (!T.empty()) { 12 | auto [x, y] = T.front(); 13 | T.pop(); 14 | if (grid[x][y] > 0) { 15 | C += grid[x][y]; 16 | grid[x][y] = 0; // Mark as visited 17 | if (x > 0 && grid[x - 1][y] > 0) T.push({x - 1, y}); 18 | if (x + 1 < grid.size() && grid[x + 1][y] > 0) T.push({x + 1, y}); 19 | if (y > 0 && grid[x][y - 1] > 0) T.push({x, y - 1}); 20 | if (y + 1 < grid[0].size() && grid[x][y + 1] > 0) T.push({x, y + 1}); 21 | } 22 | } 23 | Max = max(Max, C); 24 | } 25 | } 26 | } 27 | return Max; 28 | } 29 | }; -------------------------------------------------------------------------------- /863-sum-of-distances-in-tree/sum-of-distances-in-tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | unordered_map> graph; 4 | vector count; 5 | vector res; 6 | 7 | void dfs(int node, int parent) { 8 | for (int child : graph[node]) { 9 | if (child != parent) { 10 | dfs(child, node); 11 | count[node] += count[child]; 12 | res[node] += res[child] + count[child]; 13 | } 14 | } 15 | } 16 | 17 | void dfs2(int node, int parent) { 18 | for (int child : graph[node]) { 19 | if (child != parent) { 20 | res[child] = res[node] - count[child] + (count.size() - count[child]); 21 | dfs2(child, node); 22 | } 23 | } 24 | } 25 | 26 | public: 27 | vector sumOfDistancesInTree(int n, vector>& edges) { 28 | graph.clear(); 29 | count = vector(n, 1); 30 | res = vector(n, 0); 31 | 32 | for (auto& edge : edges) { 33 | int u = edge[0]; 34 | int v = edge[1]; 35 | graph[u].push_back(v); 36 | graph[v].push_back(u); 37 | } 38 | 39 | dfs(0, -1); 40 | dfs2(0, -1); 41 | 42 | return res; 43 | } 44 | }; -------------------------------------------------------------------------------- /2802-find-the-punishment-number-of-an-integer/find-the-punishment-number-of-an-integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canPartition(string s, int target) 4 | { 5 | if (s == "" && target == 0) return true; 6 | if (target < 0) return false; 7 | 8 | bool ans = false; 9 | //======================================================================== 10 | for (int i = 0; i < s.size(); i++) //try all possible pivot points 11 | { 12 | string left = s.substr(0, i + 1); //keep the left part 13 | string right = s.substr(i + 1); //recurse for right part 14 | int leftNum = stoi(left); 15 | 16 | bool isPossible = canPartition(right, target - leftNum); 17 | if (isPossible) { ans = true; break; } 18 | } 19 | //============================================================================= 20 | return ans; 21 | } 22 | int punishmentNumber(int n) 23 | { 24 | int sum = 0; 25 | for (int num = 1; num <= n; num++) 26 | { 27 | int sqr = num * num; 28 | if (canPartition(to_string(sqr), num)) 29 | { 30 | sum += sqr; 31 | } 32 | } 33 | return sum; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /42-trapping-rain-water/README.md: -------------------------------------------------------------------------------- 1 |

Trapping Rain Water

Difficulty: 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.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
 8 | Output: 6
 9 | 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.
10 | 
11 | 12 |

Example 2:

13 | 14 |
15 | Input: height = [4,2,0,3,2,5]
16 | Output: 9
17 | 
18 | 19 |

 

20 |

Constraints:

21 | 22 |
    23 |
  • n == height.length
  • 24 |
  • 1 <= n <= 2 * 104
  • 25 |
  • 0 <= height[i] <= 105
  • 26 |
27 | -------------------------------------------------------------------------------- /242-valid-anagram/README.md: -------------------------------------------------------------------------------- 1 |

Valid Anagram

Difficulty: Easy

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

2 | 3 |

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.

4 | 5 |

 

6 |

Example 1:

7 |
Input: s = "anagram", t = "nagaram"
 8 | Output: true
 9 | 

Example 2:

10 |
Input: s = "rat", t = "car"
11 | Output: false
12 | 
13 |

 

14 |

Constraints:

15 | 16 |
    17 |
  • 1 <= s.length, t.length <= 5 * 104
  • 18 |
  • s and t consist of lowercase English letters.
  • 19 |
20 | 21 |

 

22 |

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

23 | --------------------------------------------------------------------------------