├── 2023 ├── README.md ├── sept01.py ├── sept10.py ├── aug30.py ├── aug31.py ├── aug22.py ├── aug27.py ├── aug26.py └── oct1.py ├── 2024 ├── may25.txt ├── jan-4.py ├── jan-17.py ├── jan-29.py ├── jan-27.py ├── jan-12.py └── jan-22.py ├── string ├── repeated-substring-pattern.py ├── multiply-strings.py ├── score-of-a-string.java ├── number-of-senior-citizens.java ├── reverse-string.java ├── separate-black-and-white-balls.java ├── minimum-number-of-swaps-to-make-the-string-balanced.java ├── find-first-palindromic-string-in-the-array.py ├── minimum-add-to-make-parentheses-valid.java ├── first-unique-character-in-a-string.py ├── minimum-number-of-pushes-to-type-word-ii.java ├── append-characters-to-string-to-make-subsequence.java ├── minimum-string-length-after-removing-substrings.py ├── minimum-deletions-to-make-string-balanced.java ├── reverse-prefix-of-word.java ├── remove-sub-folders-from-the-filesystem.js ├── excel-sheet-column-title.py ├── generate-parentheses.py ├── find-the-index-of-the-first-occurrence-in-a-string.py ├── largest-number.java ├── determine-if-string-halves-are-alike.py ├── sum-of-digits-of-string-after-convert.java ├── reverse-words-in-a-string-iii.py ├── minimum-penalty-for-a-shop.py ├── sort-characters-by-frequency.py ├── count-the-number-of-consistent-strings.java └── get-equal-substrings-within-budget.java ├── string-matching ├── repeated-substring-pattern.py └── find-the-index-of-the-first-occurrence-in-a-string.py ├── graph ├── find-center-of-star-graph.java ├── reconstruct-itinerary.py └── maximum-total-importance-of-roads.java ├── 1916-find-center-of-star-graph └── find-center-of-star-graph.java ├── bit-manipulation ├── counting-bits.py ├── minimum-bit-flips-to-convert-number.java ├── count-number-of-maximum-bitwise-or-subsets.java ├── number-complement.java ├── sum-of-all-subset-xor-totals.java ├── single-number-iii.java ├── longest-subarray-with-maximum-bitwise-and.java ├── score-after-flipping-matrix.java ├── count-triplets-that-can-form-two-arrays-of-equal-xor.java ├── subsets.java ├── set-mismatch.py └── count-the-number-of-consistent-strings.java ├── array ├── rotate-image.py ├── two-sum.py ├── find-polygon-with-the-largest-perimeter.py ├── number-of-senior-citizens.java ├── three-consecutive-odds.java ├── time-needed-to-buy-tickets.py ├── find-the-student-that-will-replace-the-chalk.java ├── find-first-palindromic-string-in-the-array.py ├── minimum-increment-to-make-array-unique.java ├── count-number-of-maximum-bitwise-or-subsets.java ├── count-number-of-nice-subarrays.java ├── maximize-happiness-of-selected-children.java ├── sum-of-all-subset-xor-totals.java ├── minimum-replacements-to-sort-the-array.py ├── frog-jump.py ├── patching-array.java ├── minimum-number-of-taps-to-open-to-water-a-garden.py ├── points-that-intersect-with-cars.py ├── single-number-iii.java ├── minimum-number-of-moves-to-seat-everyone.java ├── remove-sub-folders-from-the-filesystem.js ├── minimum-swaps-to-group-all-1s-together-ii.java ├── my-calendar-i.java ├── unique-number-of-occurrences.py ├── maximum-length-of-pair-chain.py ├── minimum-number-of-operations-to-make-array-empty.py ├── majority-element.py ├── largest-positive-integer-that-exists-with-its-negative.java ├── convert-1d-array-into-2d-array.java ├── sort-colors.java ├── divide-array-into-arrays-with-max-difference.py ├── partition-array-for-maximum-sum.py ├── find-players-with-zero-or-one-losses.py ├── make-two-arrays-equal-by-reversing-subarrays.java ├── boats-to-save-people.java ├── largest-number.java ├── longest-subarray-with-maximum-bitwise-and.java ├── score-after-flipping-matrix.java ├── check-if-array-pairs-are-divisible-by-k.java ├── container-with-most-water.py ├── range-sum-of-sorted-subarray-sums.java ├── remove-element.py ├── reveal-cards-in-increasing-order.java ├── count-triplets-that-can-form-two-arrays-of-equal-xor.java ├── set-mismatch.py ├── subsets.java ├── maximum-width-ramp.java ├── count-the-number-of-consistent-strings.java ├── minimum-difference-between-largest-and-smallest-value-in-three-moves.cpp └── continuous-subarray-sum.java ├── dynamic-programming ├── counting-bits.py ├── count-all-valid-pickup-and-delivery-options.py ├── n-th-tribonacci-number.java ├── 2-keys-keyboard.java ├── frog-jump.py ├── minimum-number-of-taps-to-open-to-water-a-garden.py ├── minimum-deletions-to-make-string-balanced.java ├── maximum-length-of-pair-chain.py ├── generate-parentheses.py ├── partition-array-for-maximum-sum.py ├── k-inverse-pairs-array.py ├── unique-paths.py └── perfect-squares.py ├── math ├── rotate-image.py ├── count-all-valid-pickup-and-delivery-options.py ├── multiply-strings.py ├── palindrome-number.py ├── n-th-tribonacci-number.java ├── 2-keys-keyboard.java ├── count-number-of-nice-subarrays.java ├── sum-of-all-subset-xor-totals.java ├── insert-greatest-common-divisors-in-linked-list.java ├── minimum-replacements-to-sort-the-array.py ├── reverse-integer.py ├── excel-sheet-column-title.py ├── water-bottles.java ├── sum-of-square-numbers.java ├── unique-paths.py ├── count-triplets-that-can-form-two-arrays-of-equal-xor.java ├── perfect-squares.py └── continuous-subarray-sum.java ├── matrix ├── rotate-image.py ├── convert-1d-array-into-2d-array.java └── score-after-flipping-matrix.java ├── 205-isomorphic-strings └── isomorphic-strings.py ├── 1-two-sum └── two-sum.py ├── hash-table ├── two-sum.py ├── count-number-of-nice-subarrays.java ├── first-unique-character-in-a-string.py ├── minimum-number-of-pushes-to-type-word-ii.java ├── points-that-intersect-with-cars.py ├── unique-number-of-occurrences.py ├── minimum-number-of-operations-to-make-array-empty.py ├── majority-element.py ├── largest-positive-integer-that-exists-with-its-negative.java ├── find-players-with-zero-or-one-losses.py ├── make-two-arrays-equal-by-reversing-subarrays.java ├── check-if-array-pairs-are-divisible-by-k.java ├── sort-characters-by-frequency.py ├── count-triplets-that-can-form-two-arrays-of-equal-xor.java ├── set-mismatch.py └── count-the-number-of-consistent-strings.java ├── combinatorics ├── count-all-valid-pickup-and-delivery-options.py ├── sum-of-all-subset-xor-totals.java └── unique-paths.py ├── simulation ├── multiply-strings.py ├── time-needed-to-buy-tickets.py ├── find-the-student-that-will-replace-the-chalk.java ├── minimum-string-length-after-removing-substrings.py ├── convert-1d-array-into-2d-array.java ├── water-bottles.java ├── sum-of-digits-of-string-after-convert.java └── reveal-cards-in-increasing-order.java ├── 3379-score-of-a-string └── score-of-a-string.java ├── 268-missing-number └── missing-number.py ├── 1666-make-the-string-great └── make-the-string-great.py ├── greedy ├── find-polygon-with-the-largest-perimeter.py ├── separate-black-and-white-balls.java ├── minimum-number-of-swaps-to-make-the-string-balanced.java ├── minimum-add-to-make-parentheses-valid.java ├── minimum-increment-to-make-array-unique.java ├── maximize-happiness-of-selected-children.java ├── minimum-number-of-pushes-to-type-word-ii.java ├── append-characters-to-string-to-make-subsequence.java ├── minimum-replacements-to-sort-the-array.py ├── patching-array.java ├── minimum-number-of-taps-to-open-to-water-a-garden.py ├── minimum-number-of-moves-to-seat-everyone.java ├── maximum-length-of-pair-chain.py ├── minimum-number-of-operations-to-make-array-empty.py ├── divide-array-into-arrays-with-max-difference.py ├── boats-to-save-people.java ├── largest-number.java ├── score-after-flipping-matrix.java ├── maximum-total-importance-of-roads.java ├── container-with-most-water.py └── minimum-difference-between-largest-and-smallest-value-in-three-moves.cpp ├── prefix-sum ├── find-polygon-with-the-largest-perimeter.py ├── find-the-student-that-will-replace-the-chalk.java ├── count-number-of-nice-subarrays.java ├── points-that-intersect-with-cars.py ├── minimum-penalty-for-a-shop.py └── count-triplets-that-can-form-two-arrays-of-equal-xor.java ├── sorting ├── find-polygon-with-the-largest-perimeter.py ├── minimum-increment-to-make-array-unique.java ├── maximize-happiness-of-selected-children.java ├── minimum-number-of-pushes-to-type-word-ii.java ├── minimum-number-of-moves-to-seat-everyone.java ├── maximum-length-of-pair-chain.py ├── majority-element.py ├── largest-positive-integer-that-exists-with-its-negative.java ├── sort-colors.java ├── divide-array-into-arrays-with-max-difference.py ├── make-two-arrays-equal-by-reversing-subarrays.java ├── find-players-with-zero-or-one-losses.py ├── largest-number.java ├── boats-to-save-people.java ├── maximum-total-importance-of-roads.java ├── range-sum-of-sorted-subarray-sums.java ├── sort-characters-by-frequency.py ├── reveal-cards-in-increasing-order.java ├── set-mismatch.py └── minimum-difference-between-largest-and-smallest-value-in-three-moves.cpp ├── two-pointers ├── reverse-string.java ├── separate-black-and-white-balls.java ├── minimum-number-of-swaps-to-make-the-string-balanced.java ├── find-first-palindromic-string-in-the-array.py ├── append-characters-to-string-to-make-subsequence.java ├── reverse-prefix-of-word.java ├── largest-positive-integer-that-exists-with-its-negative.java ├── find-the-index-of-the-first-occurrence-in-a-string.py ├── sort-colors.java ├── sum-of-square-numbers.java ├── boats-to-save-people.java ├── reverse-words-in-a-string-iii.py ├── container-with-most-water.py ├── range-sum-of-sorted-subarray-sums.java └── remove-element.py ├── 344-reverse-string └── reverse-string.java ├── queue ├── time-needed-to-buy-tickets.py ├── first-unique-character-in-a-string.py ├── implement-queue-using-stacks.py └── reveal-cards-in-increasing-order.java ├── 1293-three-consecutive-odds └── three-consecutive-odds.java ├── linked-list ├── delete-node-in-a-linked-list.java ├── insert-greatest-common-divisors-in-linked-list.java └── merge-two-sorted-lists.py ├── memoization └── n-th-tribonacci-number.java ├── 3262-find-polygon-with-the-largest-perimeter └── find-polygon-with-the-largest-perimeter.py ├── 231-power-of-two └── power-of-two.py ├── 2571-find-the-pivot-integer └── find-the-pivot-integer.py ├── 1236-n-th-tribonacci-number └── n-th-tribonacci-number.java ├── 2195-time-needed-to-buy-tickets └── time-needed-to-buy-tickets.py ├── 237-delete-node-in-a-linked-list └── delete-node-in-a-linked-list.java ├── 1019-squares-of-a-sorted-array └── squares-of-a-sorted-array.py ├── stack ├── minimum-number-of-swaps-to-make-the-string-balanced.java ├── minimum-add-to-make-parentheses-valid.java ├── minimum-deletions-to-make-string-balanced.java ├── minimum-string-length-after-removing-substrings.py ├── reverse-prefix-of-word.java ├── implement-queue-using-stacks.py └── maximum-width-ramp.java ├── 201-bitwise-and-of-numbers-range └── bitwise-and-of-numbers-range.py ├── binary-search ├── find-the-student-that-will-replace-the-chalk.java ├── my-calendar-i.java ├── sum-of-square-numbers.java └── range-sum-of-sorted-subarray-sums.java ├── counting ├── minimum-increment-to-make-array-unique.java ├── first-unique-character-in-a-string.py ├── minimum-number-of-pushes-to-type-word-ii.java ├── majority-element.py ├── minimum-number-of-operations-to-make-array-empty.py ├── find-players-with-zero-or-one-losses.py ├── determine-if-string-halves-are-alike.py ├── check-if-array-pairs-are-divisible-by-k.java ├── sort-characters-by-frequency.py └── count-the-number-of-consistent-strings.java ├── backtracking ├── count-number-of-maximum-bitwise-or-subsets.java ├── sum-of-all-subset-xor-totals.java ├── generate-parentheses.py └── subsets.java ├── enumeration ├── count-number-of-maximum-bitwise-or-subsets.java ├── sum-of-all-subset-xor-totals.java └── sequential-digits.py ├── 2231-find-first-palindromic-string-in-the-array └── find-first-palindromic-string-in-the-array.py ├── sliding-window ├── count-number-of-nice-subarrays.java └── minimum-swaps-to-group-all-1s-together-ii.java ├── 3242-count-elements-with-maximum-frequency └── count-elements-with-maximum-frequency.py ├── tree └── sum-of-left-leaves.java ├── 982-minimum-increment-to-make-array-unique └── minimum-increment-to-make-array-unique.java ├── binary-tree └── sum-of-left-leaves.java ├── 1370-count-number-of-nice-subarrays └── count-number-of-nice-subarrays.java ├── 387-first-unique-character-in-a-string └── first-unique-character-in-a-string.py ├── 404-sum-of-left-leaves └── sum-of-left-leaves.java ├── breadth-first-search ├── sum-of-left-leaves.java └── perfect-squares.py ├── depth-first-search ├── sum-of-left-leaves.java ├── remove-sub-folders-from-the-filesystem.js └── reconstruct-itinerary.py ├── number-theory └── insert-greatest-common-divisors-in-linked-list.java ├── 3351-maximize-happiness-of-selected-children └── maximize-happiness-of-selected-children.java ├── 1993-sum-of-all-subset-xor-totals └── sum-of-all-subset-xor-totals.java ├── 966-binary-subarrays-with-sum └── binary-subarrays-with-sum.py ├── 330-patching-array └── patching-array.java ├── 1212-sequential-digits └── sequential-digits.py ├── 1765-merge-in-between-linked-lists └── merge-in-between-linked-lists.py ├── 807-custom-sort-string └── custom-sort-string.py ├── trie └── remove-sub-folders-from-the-filesystem.js ├── design ├── my-calendar-i.java └── implement-queue-using-stacks.py ├── 2572-append-characters-to-string-to-make-subsequence └── append-characters-to-string-to-make-subsequence.java ├── counting-sort └── minimum-number-of-moves-to-seat-everyone.java ├── ordered-set └── my-calendar-i.java ├── segment-tree └── my-calendar-i.java ├── 2128-reverse-prefix-of-word └── reverse-prefix-of-word.java ├── 260-single-number-iii └── single-number-iii.java ├── 2634-minimum-common-value └── minimum-common-value.py ├── 442-find-all-duplicates-in-an-array └── find-all-duplicates-in-an-array.py ├── 1756-minimum-deletions-to-make-string-balanced └── minimum-deletions-to-make-string-balanced.java ├── 1737-maximum-nesting-depth-of-the-parentheses └── maximum-nesting-depth-of-the-parentheses.py ├── 2148-minimum-number-of-moves-to-seat-everyone └── minimum-number-of-moves-to-seat-everyone.java ├── divide-and-conquer └── majority-element.py ├── 169-majority-element └── majority-element.py ├── 58-length-of-last-word └── length-of-last-word.py ├── 75-sort-colors └── sort-colors.java ├── 1642-water-bottles └── water-bottles.java ├── 349-intersection-of-two-arrays └── intersection-of-two-arrays.py ├── 678-valid-parenthesis-string └── valid-parenthesis-string.py ├── 2524-largest-positive-integer-that-exists-with-its-negative └── largest-positive-integer-that-exists-with-its-negative.java ├── brainteaser └── longest-subarray-with-maximum-bitwise-and.java ├── eulerian-circuit └── reconstruct-itinerary.py ├── 1121-partition-array-for-maximum-sum └── partition-array-for-maximum-sum.py ├── 633-sum-of-square-numbers └── sum-of-square-numbers.java ├── 3241-divide-array-into-arrays-with-max-difference └── divide-array-into-arrays-with-max-difference.py ├── 917-boats-to-save-people └── boats-to-save-people.java ├── 206-reverse-linked-list └── reverse-linked-list.py ├── 891-score-after-flipping-matrix └── score-after-flipping-matrix.java ├── heap-priority-queue ├── maximum-total-importance-of-roads.java └── sort-characters-by-frequency.py ├── 3213-count-subarrays-where-max-element-appears-at-least-k-times └── count-subarrays-where-max-element-appears-at-least-k-times.py ├── 2379-maximum-total-importance-of-roads └── maximum-total-importance-of-roads.java ├── 3225-length-of-longest-subarray-with-at-most-k-frequency └── length-of-longest-subarray-with-at-most-k-frequency.py ├── bucket-sort └── sort-characters-by-frequency.py ├── 78-subsets └── subsets.java ├── recursion └── merge-two-sorted-lists.py ├── 713-subarray-product-less-than-k └── subarray-product-less-than-k.py ├── monotonic-stack └── maximum-width-ramp.java ├── 279-perfect-squares └── perfect-squares.py └── 451-sort-characters-by-frequency └── sort-characters-by-frequency.py /2023/README.md: -------------------------------------------------------------------------------- 1 | # Leetcode -------------------------------------------------------------------------------- /2024/may25.txt: -------------------------------------------------------------------------------- 1 | FOrgot this day too -------------------------------------------------------------------------------- /string/repeated-substring-pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def repeatedSubstringPattern(self, s: str) -> bool: 3 | return s in s[1:]+s[:len(s)-1] 4 | -------------------------------------------------------------------------------- /string-matching/repeated-substring-pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def repeatedSubstringPattern(self, s: str) -> bool: 3 | return s in s[1:]+s[:len(s)-1] 4 | -------------------------------------------------------------------------------- /graph/find-center-of-star-graph.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findCenter(int[][] e) { 3 | return e[0][0] == e[1][0] || e[0][0] == e[1][1] ? e[0][0] : e[0][1]; 4 | } 5 | } -------------------------------------------------------------------------------- /1916-find-center-of-star-graph/find-center-of-star-graph.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findCenter(int[][] e) { 3 | return e[0][0] == e[1][0] || e[0][0] == e[1][1] ? e[0][0] : e[0][1]; 4 | } 5 | } -------------------------------------------------------------------------------- /bit-manipulation/counting-bits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countBits(self,n): 3 | ans = [0] * (n + 1) 4 | for i in range(1, n + 1): 5 | ans[i] = ans[i >> 1] + (i & 1) 6 | return ans 7 | -------------------------------------------------------------------------------- /array/rotate-image.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, matrix: List[List[int]]) -> None: 3 | """ 4 | Do not return anything, modify matrix in-place instead. 5 | """ 6 | matrix[:] = zip(*matrix[::-1]) -------------------------------------------------------------------------------- /dynamic-programming/counting-bits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countBits(self,n): 3 | ans = [0] * (n + 1) 4 | for i in range(1, n + 1): 5 | ans[i] = ans[i >> 1] + (i & 1) 6 | return ans 7 | -------------------------------------------------------------------------------- /math/rotate-image.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, matrix: List[List[int]]) -> None: 3 | """ 4 | Do not return anything, modify matrix in-place instead. 5 | """ 6 | matrix[:] = zip(*matrix[::-1]) -------------------------------------------------------------------------------- /matrix/rotate-image.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, matrix: List[List[int]]) -> None: 3 | """ 4 | Do not return anything, modify matrix in-place instead. 5 | """ 6 | matrix[:] = zip(*matrix[::-1]) -------------------------------------------------------------------------------- /205-isomorphic-strings/isomorphic-strings.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isIsomorphic(self, s, t): 3 | """ 4 | :type s: str 5 | :type t: str 6 | :rtype: bool 7 | """ 8 | return len(set(zip(s,t))) == len(set(s)) == len(set(t)) -------------------------------------------------------------------------------- /array/two-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums, target): 3 | n = len(nums) 4 | for i in range(n - 1): 5 | for j in range(i + 1, n): 6 | if nums[i] + nums[j] == target: 7 | return [i, j] 8 | return [] # No solution found -------------------------------------------------------------------------------- /math/count-all-valid-pickup-and-delivery-options.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countOrders(self, n): 3 | ans = 1 4 | MOD = 10 ** 9 + 7 5 | for n in range(2, n + 1): 6 | ans *= n*(2*n-1) 7 | ans %= MOD 8 | return ans 9 | 10 | -------------------------------------------------------------------------------- /1-two-sum/two-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums, target): 3 | n = len(nums) 4 | for i in range(n - 1): 5 | for j in range(i + 1, n): 6 | if nums[i] + nums[j] == target: 7 | return [i, j] 8 | return [] # No solution found -------------------------------------------------------------------------------- /hash-table/two-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums, target): 3 | n = len(nums) 4 | for i in range(n - 1): 5 | for j in range(i + 1, n): 6 | if nums[i] + nums[j] == target: 7 | return [i, j] 8 | return [] # No solution found -------------------------------------------------------------------------------- /math/multiply-strings.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def multiply(self, num1, num2): 3 | """ 4 | :type num1: str 5 | :type num2: str 6 | :rtype: str 7 | """ 8 | a=int(num1) 9 | b=int(num2) 10 | c= str(a*b) 11 | return c 12 | -------------------------------------------------------------------------------- /combinatorics/count-all-valid-pickup-and-delivery-options.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countOrders(self, n): 3 | ans = 1 4 | MOD = 10 ** 9 + 7 5 | for n in range(2, n + 1): 6 | ans *= n*(2*n-1) 7 | ans %= MOD 8 | return ans 9 | 10 | -------------------------------------------------------------------------------- /string/multiply-strings.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def multiply(self, num1, num2): 3 | """ 4 | :type num1: str 5 | :type num2: str 6 | :rtype: str 7 | """ 8 | a=int(num1) 9 | b=int(num2) 10 | c= str(a*b) 11 | return c 12 | -------------------------------------------------------------------------------- /string/score-of-a-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int scoreOfString(String s) { 3 | int score = 0; 4 | int l = s.length()-1; 5 | for(int i=0; i> 1] + (i & 1) 6 | return ans 7 | 8 | 9 | sol=Solution() 10 | n=int(input("Enter a number:-")) 11 | res=sol.countBits(n) 12 | print(res) 13 | -------------------------------------------------------------------------------- /3379-score-of-a-string/score-of-a-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int scoreOfString(String s) { 3 | int score = 0; 4 | int l = s.length()-1; 5 | for(int i=0; i>=1; 9 | } 10 | return ans; 11 | } 12 | } -------------------------------------------------------------------------------- /268-missing-number/missing-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def missingNumber(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | n = len(nums) 8 | expected_sum = n * (n + 1) // 2 9 | actual_sum = sum(nums) 10 | return expected_sum - actual_sum 11 | -------------------------------------------------------------------------------- /1666-make-the-string-great/make-the-string-great.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def makeGood(self, s): 3 | stack = [] 4 | for char in s: 5 | if stack and abs(ord(char) - ord(stack[-1])) == 32: 6 | stack.pop() 7 | else: 8 | stack.append(char) 9 | 10 | return ''.join(stack) -------------------------------------------------------------------------------- /array/find-polygon-with-the-largest-perimeter.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestPerimeter(self, nums): 3 | nums.sort() 4 | _sum = sum(nums) 5 | n = len(nums) 6 | for i in range(n - 1, 1, -1): 7 | _sum -= nums[i] 8 | if _sum > nums[i]: 9 | return _sum + nums[i] 10 | return -1 -------------------------------------------------------------------------------- /greedy/find-polygon-with-the-largest-perimeter.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestPerimeter(self, nums): 3 | nums.sort() 4 | _sum = sum(nums) 5 | n = len(nums) 6 | for i in range(n - 1, 1, -1): 7 | _sum -= nums[i] 8 | if _sum > nums[i]: 9 | return _sum + nums[i] 10 | return -1 -------------------------------------------------------------------------------- /array/number-of-senior-citizens.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countSeniors(String[] details) { 3 | int ans = 0; 4 | for (var x : details) { 5 | int age = Integer.parseInt(x.substring(11, 13)); 6 | if (age > 60) { 7 | ++ans; 8 | } 9 | } 10 | return ans; 11 | } 12 | } -------------------------------------------------------------------------------- /math/palindrome-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPalindrome(self, x): 3 | """ 4 | :type x: int 5 | :rtype: bool 6 | """ 7 | # Convert the integer to a string 8 | x_str = str(x) 9 | 10 | # Check if the string is equal to its reverse 11 | return x_str == x_str[::-1] 12 | 13 | -------------------------------------------------------------------------------- /prefix-sum/find-polygon-with-the-largest-perimeter.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestPerimeter(self, nums): 3 | nums.sort() 4 | _sum = sum(nums) 5 | n = len(nums) 6 | for i in range(n - 1, 1, -1): 7 | _sum -= nums[i] 8 | if _sum > nums[i]: 9 | return _sum + nums[i] 10 | return -1 -------------------------------------------------------------------------------- /sorting/find-polygon-with-the-largest-perimeter.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestPerimeter(self, nums): 3 | nums.sort() 4 | _sum = sum(nums) 5 | n = len(nums) 6 | for i in range(n - 1, 1, -1): 7 | _sum -= nums[i] 8 | if _sum > nums[i]: 9 | return _sum + nums[i] 10 | return -1 -------------------------------------------------------------------------------- /array/three-consecutive-odds.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean threeConsecutiveOdds(int[] arr) { 4 | for (int i = 0; i < arr.length - 2; i++) { 5 | if (arr[i] % 2 == 1 && arr[i + 1] % 2 == 1 && arr[i + 2] % 2 == 1) { 6 | return true; 7 | } 8 | } 9 | 10 | return false; 11 | } 12 | } -------------------------------------------------------------------------------- /string/number-of-senior-citizens.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countSeniors(String[] details) { 3 | int ans = 0; 4 | for (var x : details) { 5 | int age = Integer.parseInt(x.substring(11, 13)); 6 | if (age > 60) { 7 | ++ans; 8 | } 9 | } 10 | return ans; 11 | } 12 | } -------------------------------------------------------------------------------- /string/reverse-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void reverseString(char[] s) { 3 | 4 | int left = 0, right = s.length - 1; 5 | while(left < right) { 6 | char temp = s[left]; 7 | s[left] = s[right]; 8 | s[right] = temp; 9 | left++; 10 | right--; 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /two-pointers/reverse-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void reverseString(char[] s) { 3 | 4 | int left = 0, right = s.length - 1; 5 | while(left < right) { 6 | char temp = s[left]; 7 | s[left] = s[right]; 8 | s[right] = temp; 9 | left++; 10 | right--; 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /344-reverse-string/reverse-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void reverseString(char[] s) { 3 | 4 | int left = 0, right = s.length - 1; 5 | while(left < right) { 6 | char temp = s[left]; 7 | s[left] = s[right]; 8 | s[right] = temp; 9 | left++; 10 | right--; 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /array/time-needed-to-buy-tickets.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def timeRequiredToBuy(self, tickets, k): 3 | total = 0 4 | 5 | for i, x in enumerate(tickets): 6 | if i <= k: 7 | total += min(tickets[i], tickets[k]) 8 | else: 9 | total += min(tickets[i], tickets[k] - 1) 10 | 11 | return total 12 | -------------------------------------------------------------------------------- /queue/time-needed-to-buy-tickets.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def timeRequiredToBuy(self, tickets, k): 3 | total = 0 4 | 5 | for i, x in enumerate(tickets): 6 | if i <= k: 7 | total += min(tickets[i], tickets[k]) 8 | else: 9 | total += min(tickets[i], tickets[k] - 1) 10 | 11 | return total 12 | -------------------------------------------------------------------------------- /1293-three-consecutive-odds/three-consecutive-odds.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean threeConsecutiveOdds(int[] arr) { 4 | for (int i = 0; i < arr.length - 2; i++) { 5 | if (arr[i] % 2 == 1 && arr[i + 1] % 2 == 1 && arr[i + 2] % 2 == 1) { 6 | return true; 7 | } 8 | } 9 | 10 | return false; 11 | } 12 | } -------------------------------------------------------------------------------- /linked-list/delete-node-in-a-linked-list.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public void deleteNode(ListNode node) { 11 | node.val = node.next.val; 12 | node.next = node.next.next; 13 | } 14 | } -------------------------------------------------------------------------------- /math/n-th-tribonacci-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int tribonacci(int n) { 3 | if (n < 2) 4 | return n; 5 | 6 | int[] dp = {0, 1, 1}; 7 | 8 | for (int i = 3; i <= n; ++i) { 9 | final int next = dp[0] + dp[1] + dp[2]; 10 | dp[0] = dp[1]; 11 | dp[1] = dp[2]; 12 | dp[2] = next; 13 | } 14 | 15 | return dp[2]; 16 | } 17 | } -------------------------------------------------------------------------------- /simulation/time-needed-to-buy-tickets.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def timeRequiredToBuy(self, tickets, k): 3 | total = 0 4 | 5 | for i, x in enumerate(tickets): 6 | if i <= k: 7 | total += min(tickets[i], tickets[k]) 8 | else: 9 | total += min(tickets[i], tickets[k] - 1) 10 | 11 | return total 12 | -------------------------------------------------------------------------------- /memoization/n-th-tribonacci-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int tribonacci(int n) { 3 | if (n < 2) 4 | return n; 5 | 6 | int[] dp = {0, 1, 1}; 7 | 8 | for (int i = 3; i <= n; ++i) { 9 | final int next = dp[0] + dp[1] + dp[2]; 10 | dp[0] = dp[1]; 11 | dp[1] = dp[2]; 12 | dp[2] = next; 13 | } 14 | 15 | return dp[2]; 16 | } 17 | } -------------------------------------------------------------------------------- /3262-find-polygon-with-the-largest-perimeter/find-polygon-with-the-largest-perimeter.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestPerimeter(self, nums): 3 | nums.sort() 4 | _sum = sum(nums) 5 | n = len(nums) 6 | for i in range(n - 1, 1, -1): 7 | _sum -= nums[i] 8 | if _sum > nums[i]: 9 | return _sum + nums[i] 10 | return -1 -------------------------------------------------------------------------------- /231-power-of-two/power-of-two.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPowerOfTwo(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | # Check if n is positive 8 | if n <= 0: 9 | return False 10 | 11 | # Check if there is only one set bit in the binary representation of n 12 | return n & (n - 1) == 0 13 | -------------------------------------------------------------------------------- /2571-find-the-pivot-integer/find-the-pivot-integer.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def pivotInteger(self, n): 3 | _sum = n * (n + 1) // 2 4 | 5 | root = int(math.sqrt(_sum)) 6 | if root * root == _sum: 7 | return root 8 | return -1 9 | solution = Solution() 10 | n = 8 11 | result = solution.pivotInteger(n) 12 | print(result) # Output: 6 13 | -------------------------------------------------------------------------------- /dynamic-programming/n-th-tribonacci-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int tribonacci(int n) { 3 | if (n < 2) 4 | return n; 5 | 6 | int[] dp = {0, 1, 1}; 7 | 8 | for (int i = 3; i <= n; ++i) { 9 | final int next = dp[0] + dp[1] + dp[2]; 10 | dp[0] = dp[1]; 11 | dp[1] = dp[2]; 12 | dp[2] = next; 13 | } 14 | 15 | return dp[2]; 16 | } 17 | } -------------------------------------------------------------------------------- /greedy/separate-black-and-white-balls.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long minimumSteps(String s) { 3 | long swap = 0; 4 | int black = 0; 5 | for (int i = 0; i < s.length(); i++) { 6 | if (s.charAt(i) == '0') 7 | swap += (long) black; 8 | else 9 | black++; 10 | } 11 | return swap; 12 | } 13 | } -------------------------------------------------------------------------------- /string/separate-black-and-white-balls.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long minimumSteps(String s) { 3 | long swap = 0; 4 | int black = 0; 5 | for (int i = 0; i < s.length(); i++) { 6 | if (s.charAt(i) == '0') 7 | swap += (long) black; 8 | else 9 | black++; 10 | } 11 | return swap; 12 | } 13 | } -------------------------------------------------------------------------------- /1236-n-th-tribonacci-number/n-th-tribonacci-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int tribonacci(int n) { 3 | if (n < 2) 4 | return n; 5 | 6 | int[] dp = {0, 1, 1}; 7 | 8 | for (int i = 3; i <= n; ++i) { 9 | final int next = dp[0] + dp[1] + dp[2]; 10 | dp[0] = dp[1]; 11 | dp[1] = dp[2]; 12 | dp[2] = next; 13 | } 14 | 15 | return dp[2]; 16 | } 17 | } -------------------------------------------------------------------------------- /2195-time-needed-to-buy-tickets/time-needed-to-buy-tickets.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def timeRequiredToBuy(self, tickets, k): 3 | total = 0 4 | 5 | for i, x in enumerate(tickets): 6 | if i <= k: 7 | total += min(tickets[i], tickets[k]) 8 | else: 9 | total += min(tickets[i], tickets[k] - 1) 10 | 11 | return total 12 | -------------------------------------------------------------------------------- /237-delete-node-in-a-linked-list/delete-node-in-a-linked-list.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public void deleteNode(ListNode node) { 11 | node.val = node.next.val; 12 | node.next = node.next.next; 13 | } 14 | } -------------------------------------------------------------------------------- /two-pointers/separate-black-and-white-balls.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long minimumSteps(String s) { 3 | long swap = 0; 4 | int black = 0; 5 | for (int i = 0; i < s.length(); i++) { 6 | if (s.charAt(i) == '0') 7 | swap += (long) black; 8 | else 9 | black++; 10 | } 11 | return swap; 12 | } 13 | } -------------------------------------------------------------------------------- /array/find-the-student-that-will-replace-the-chalk.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int chalkReplacer(int[] chalk, int k) { 3 | long accSum = 0; 4 | for (int c : chalk) accSum += c; 5 | 6 | k %= accSum; 7 | 8 | for (int i = 0; i < chalk.length; i++) { 9 | if (chalk[i] > k) return i; 10 | k -= chalk[i]; 11 | } 12 | return -1; 13 | } 14 | } -------------------------------------------------------------------------------- /1019-squares-of-a-sorted-array/squares-of-a-sorted-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sortedSquares(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | # Create a new array to store squares 8 | squares = [num ** 2 for num in nums] 9 | 10 | # Sort the array of squares 11 | squares.sort() 12 | return squares -------------------------------------------------------------------------------- /greedy/minimum-number-of-swaps-to-make-the-string-balanced.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSwaps(String s) { 3 | int size = 0; 4 | for (int i = 0; i < s.length(); i++) { 5 | char ch = s.charAt(i); 6 | if (ch == '[') 7 | size++; 8 | else if (size > 0) 9 | size--; 10 | } 11 | return (size + 1) / 2; 12 | } 13 | } -------------------------------------------------------------------------------- /prefix-sum/find-the-student-that-will-replace-the-chalk.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int chalkReplacer(int[] chalk, int k) { 3 | long accSum = 0; 4 | for (int c : chalk) accSum += c; 5 | 6 | k %= accSum; 7 | 8 | for (int i = 0; i < chalk.length; i++) { 9 | if (chalk[i] > k) return i; 10 | k -= chalk[i]; 11 | } 12 | return -1; 13 | } 14 | } -------------------------------------------------------------------------------- /simulation/find-the-student-that-will-replace-the-chalk.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int chalkReplacer(int[] chalk, int k) { 3 | long accSum = 0; 4 | for (int c : chalk) accSum += c; 5 | 6 | k %= accSum; 7 | 8 | for (int i = 0; i < chalk.length; i++) { 9 | if (chalk[i] > k) return i; 10 | k -= chalk[i]; 11 | } 12 | return -1; 13 | } 14 | } -------------------------------------------------------------------------------- /stack/minimum-number-of-swaps-to-make-the-string-balanced.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSwaps(String s) { 3 | int size = 0; 4 | for (int i = 0; i < s.length(); i++) { 5 | char ch = s.charAt(i); 6 | if (ch == '[') 7 | size++; 8 | else if (size > 0) 9 | size--; 10 | } 11 | return (size + 1) / 2; 12 | } 13 | } -------------------------------------------------------------------------------- /string/minimum-number-of-swaps-to-make-the-string-balanced.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSwaps(String s) { 3 | int size = 0; 4 | for (int i = 0; i < s.length(); i++) { 5 | char ch = s.charAt(i); 6 | if (ch == '[') 7 | size++; 8 | else if (size > 0) 9 | size--; 10 | } 11 | return (size + 1) / 2; 12 | } 13 | } -------------------------------------------------------------------------------- /201-bitwise-and-of-numbers-range/bitwise-and-of-numbers-range.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def rangeBitwiseAnd(self, left, right): 3 | """ 4 | :type left: int 5 | :type right: int 6 | :rtype: int 7 | """ 8 | shift = 0 9 | while left < right: 10 | left >>= 1 11 | right >>= 1 12 | shift += 1 13 | 14 | return left << shift 15 | -------------------------------------------------------------------------------- /array/find-first-palindromic-string-in-the-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstPalindrome(self, words): 3 | """ 4 | :type words: List[str] 5 | :rtype: str 6 | """ 7 | def is_palindrome(word): 8 | return word == word[::-1] 9 | 10 | for word in words: 11 | if is_palindrome(word): 12 | return word 13 | 14 | return "" 15 | -------------------------------------------------------------------------------- /binary-search/find-the-student-that-will-replace-the-chalk.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int chalkReplacer(int[] chalk, int k) { 3 | long accSum = 0; 4 | for (int c : chalk) accSum += c; 5 | 6 | k %= accSum; 7 | 8 | for (int i = 0; i < chalk.length; i++) { 9 | if (chalk[i] > k) return i; 10 | k -= chalk[i]; 11 | } 12 | return -1; 13 | } 14 | } -------------------------------------------------------------------------------- /greedy/minimum-add-to-make-parentheses-valid.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minAddToMakeValid(String s) { 3 | int open =0, mismatch=0; 4 | for(int i=0; i0) 11 | open--; 12 | else 13 | mismatch++; 14 | } 15 | } 16 | return open+mismatch; 17 | } 18 | } -------------------------------------------------------------------------------- /stack/minimum-add-to-make-parentheses-valid.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minAddToMakeValid(String s) { 3 | int open =0, mismatch=0; 4 | for(int i=0; i0) 11 | open--; 12 | else 13 | mismatch++; 14 | } 15 | } 16 | return open+mismatch; 17 | } 18 | } -------------------------------------------------------------------------------- /string/find-first-palindromic-string-in-the-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstPalindrome(self, words): 3 | """ 4 | :type words: List[str] 5 | :rtype: str 6 | """ 7 | def is_palindrome(word): 8 | return word == word[::-1] 9 | 10 | for word in words: 11 | if is_palindrome(word): 12 | return word 13 | 14 | return "" 15 | -------------------------------------------------------------------------------- /string/minimum-add-to-make-parentheses-valid.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minAddToMakeValid(String s) { 3 | int open =0, mismatch=0; 4 | for(int i=0; i0) 11 | open--; 12 | else 13 | mismatch++; 14 | } 15 | } 16 | return open+mismatch; 17 | } 18 | } -------------------------------------------------------------------------------- /two-pointers/minimum-number-of-swaps-to-make-the-string-balanced.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSwaps(String s) { 3 | int size = 0; 4 | for (int i = 0; i < s.length(); i++) { 5 | char ch = s.charAt(i); 6 | if (ch == '[') 7 | size++; 8 | else if (size > 0) 9 | size--; 10 | } 11 | return (size + 1) / 2; 12 | } 13 | } -------------------------------------------------------------------------------- /two-pointers/find-first-palindromic-string-in-the-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstPalindrome(self, words): 3 | """ 4 | :type words: List[str] 5 | :rtype: str 6 | """ 7 | def is_palindrome(word): 8 | return word == word[::-1] 9 | 10 | for word in words: 11 | if is_palindrome(word): 12 | return word 13 | 14 | return "" 15 | -------------------------------------------------------------------------------- /2023/sept10.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countOrders(self, n): 3 | ans = 1 4 | mod=10**9+7 5 | for n in range(2, n + 1): 6 | ans *= n*(2*n-1) 7 | ans %= mod 8 | return ans 9 | 10 | # Example usage: 11 | solution = Solution() 12 | print(solution.countOrders(1)) # Output: 1 13 | print(solution.countOrders(2)) # Output: 6 14 | print(solution.countOrders(3)) # Output: 90 15 | -------------------------------------------------------------------------------- /array/minimum-increment-to-make-array-unique.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minIncrementForUnique(int[] nums) { 3 | Arrays.sort(nums); 4 | int ans = 0; 5 | for (int i = 1; i < nums.length; i++) { 6 | if (nums[i] <= nums[i - 1]) { 7 | ans += nums[i - 1] - nums[i] + 1; 8 | nums[i] = nums[i - 1] + 1; 9 | } 10 | } 11 | return ans; 12 | } 13 | } -------------------------------------------------------------------------------- /counting/minimum-increment-to-make-array-unique.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minIncrementForUnique(int[] nums) { 3 | Arrays.sort(nums); 4 | int ans = 0; 5 | for (int i = 1; i < nums.length; i++) { 6 | if (nums[i] <= nums[i - 1]) { 7 | ans += nums[i - 1] - nums[i] + 1; 8 | nums[i] = nums[i - 1] + 1; 9 | } 10 | } 11 | return ans; 12 | } 13 | } -------------------------------------------------------------------------------- /greedy/minimum-increment-to-make-array-unique.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minIncrementForUnique(int[] nums) { 3 | Arrays.sort(nums); 4 | int ans = 0; 5 | for (int i = 1; i < nums.length; i++) { 6 | if (nums[i] <= nums[i - 1]) { 7 | ans += nums[i - 1] - nums[i] + 1; 8 | nums[i] = nums[i - 1] + 1; 9 | } 10 | } 11 | return ans; 12 | } 13 | } -------------------------------------------------------------------------------- /sorting/minimum-increment-to-make-array-unique.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minIncrementForUnique(int[] nums) { 3 | Arrays.sort(nums); 4 | int ans = 0; 5 | for (int i = 1; i < nums.length; i++) { 6 | if (nums[i] <= nums[i - 1]) { 7 | ans += nums[i - 1] - nums[i] + 1; 8 | nums[i] = nums[i - 1] + 1; 9 | } 10 | } 11 | return ans; 12 | } 13 | } -------------------------------------------------------------------------------- /math/2-keys-keyboard.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSteps(int n) { 3 | if (n == 1) return 0; 4 | 5 | int steps = 0; 6 | int factor = 2; 7 | 8 | while (n > 1) { 9 | while (n % factor == 0) { 10 | steps += factor; 11 | n /= factor; 12 | } 13 | factor++; 14 | } 15 | 16 | return steps; 17 | } 18 | } -------------------------------------------------------------------------------- /2023/aug30.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumReplacement(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | ops = 0 5 | 6 | prev = nums[n - 1] 7 | 8 | for i in range(n - 2, -1, -1): 9 | if nums[i] > prev: 10 | k = math.ceil(nums[i] / prev) 11 | ops += k - 1 12 | prev = nums[i] // k 13 | else: 14 | prev = nums[i] 15 | return ops -------------------------------------------------------------------------------- /array/count-number-of-maximum-bitwise-or-subsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countMaxOrSubsets(int[] nums) { 3 | int max = 0; 4 | for (int n : nums) max |= n; 5 | return dfs(nums, 0, 0, max); 6 | } 7 | private int dfs(int[] nums, int i, int or, int max) { 8 | if (i == nums.length) return or == max ? 1 : 0; 9 | return dfs(nums, i + 1, or | nums[i], max) + dfs(nums, i + 1, or, max); 10 | } 11 | } -------------------------------------------------------------------------------- /array/count-number-of-nice-subarrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfSubarrays(int[] nums, int k) { 3 | int n=nums.length; 4 | int ans=0, t=0; 5 | int cnt[] = new int[n+1]; 6 | cnt[0]=1; 7 | for(int v : nums){ 8 | t += v&1; 9 | if(t-k>=0){ 10 | ans += cnt[t-k]; 11 | } 12 | cnt[t]++; 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /math/count-number-of-nice-subarrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfSubarrays(int[] nums, int k) { 3 | int n=nums.length; 4 | int ans=0, t=0; 5 | int cnt[] = new int[n+1]; 6 | cnt[0]=1; 7 | for(int v : nums){ 8 | t += v&1; 9 | if(t-k>=0){ 10 | ans += cnt[t-k]; 11 | } 12 | cnt[t]++; 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /queue/first-unique-character-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstUniqChar(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | char_count={} 8 | 9 | for char in s: 10 | char_count[char] = char_count.get(char, 0)+1 11 | 12 | for i in range(len(s)): 13 | if char_count[s[i]] == 1: 14 | return i 15 | 16 | return -1 17 | -------------------------------------------------------------------------------- /string/first-unique-character-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstUniqChar(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | char_count={} 8 | 9 | for char in s: 10 | char_count[char] = char_count.get(char, 0)+1 11 | 12 | for i in range(len(s)): 13 | if char_count[s[i]] == 1: 14 | return i 15 | 16 | return -1 17 | -------------------------------------------------------------------------------- /array/maximize-happiness-of-selected-children.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public long maximumHappinessSum(int[] happiness, int k) { 3 | Arrays.sort(happiness); 4 | long res = 0; 5 | int n = happiness.length, j = 0; 6 | 7 | for (int i = n - 1; i >= n - k; --i) { 8 | happiness[i] = Math.max(happiness[i] - j++, 0); 9 | res += happiness[i]; 10 | } 11 | 12 | return res; 13 | } 14 | } -------------------------------------------------------------------------------- /backtracking/count-number-of-maximum-bitwise-or-subsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countMaxOrSubsets(int[] nums) { 3 | int max = 0; 4 | for (int n : nums) max |= n; 5 | return dfs(nums, 0, 0, max); 6 | } 7 | private int dfs(int[] nums, int i, int or, int max) { 8 | if (i == nums.length) return or == max ? 1 : 0; 9 | return dfs(nums, i + 1, or | nums[i], max) + dfs(nums, i + 1, or, max); 10 | } 11 | } -------------------------------------------------------------------------------- /counting/first-unique-character-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstUniqChar(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | char_count={} 8 | 9 | for char in s: 10 | char_count[char] = char_count.get(char, 0)+1 11 | 12 | for i in range(len(s)): 13 | if char_count[s[i]] == 1: 14 | return i 15 | 16 | return -1 17 | -------------------------------------------------------------------------------- /enumeration/count-number-of-maximum-bitwise-or-subsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countMaxOrSubsets(int[] nums) { 3 | int max = 0; 4 | for (int n : nums) max |= n; 5 | return dfs(nums, 0, 0, max); 6 | } 7 | private int dfs(int[] nums, int i, int or, int max) { 8 | if (i == nums.length) return or == max ? 1 : 0; 9 | return dfs(nums, i + 1, or | nums[i], max) + dfs(nums, i + 1, or, max); 10 | } 11 | } -------------------------------------------------------------------------------- /greedy/maximize-happiness-of-selected-children.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public long maximumHappinessSum(int[] happiness, int k) { 3 | Arrays.sort(happiness); 4 | long res = 0; 5 | int n = happiness.length, j = 0; 6 | 7 | for (int i = n - 1; i >= n - k; --i) { 8 | happiness[i] = Math.max(happiness[i] - j++, 0); 9 | res += happiness[i]; 10 | } 11 | 12 | return res; 13 | } 14 | } -------------------------------------------------------------------------------- /hash-table/count-number-of-nice-subarrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfSubarrays(int[] nums, int k) { 3 | int n=nums.length; 4 | int ans=0, t=0; 5 | int cnt[] = new int[n+1]; 6 | cnt[0]=1; 7 | for(int v : nums){ 8 | t += v&1; 9 | if(t-k>=0){ 10 | ans += cnt[t-k]; 11 | } 12 | cnt[t]++; 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /hash-table/first-unique-character-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstUniqChar(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | char_count={} 8 | 9 | for char in s: 10 | char_count[char] = char_count.get(char, 0)+1 11 | 12 | for i in range(len(s)): 13 | if char_count[s[i]] == 1: 14 | return i 15 | 16 | return -1 17 | -------------------------------------------------------------------------------- /prefix-sum/count-number-of-nice-subarrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfSubarrays(int[] nums, int k) { 3 | int n=nums.length; 4 | int ans=0, t=0; 5 | int cnt[] = new int[n+1]; 6 | cnt[0]=1; 7 | for(int v : nums){ 8 | t += v&1; 9 | if(t-k>=0){ 10 | ans += cnt[t-k]; 11 | } 12 | cnt[t]++; 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /sorting/maximize-happiness-of-selected-children.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public long maximumHappinessSum(int[] happiness, int k) { 3 | Arrays.sort(happiness); 4 | long res = 0; 5 | int n = happiness.length, j = 0; 6 | 7 | for (int i = n - 1; i >= n - k; --i) { 8 | happiness[i] = Math.max(happiness[i] - j++, 0); 9 | res += happiness[i]; 10 | } 11 | 12 | return res; 13 | } 14 | } -------------------------------------------------------------------------------- /2023/aug31.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minTaps(self, n, ranges): 3 | dp = [float('inf')] * (n + 1) 4 | 5 | dp[0] = 0 6 | 7 | for i, tap_range in enumerate(ranges): 8 | left = max(0, i - tap_range) 9 | right = min(n, i + tap_range) 10 | 11 | for j in range(left, right + 1): 12 | dp[j] = min(dp[j], dp[left] + 1) 13 | 14 | return dp[n] if dp[n] < float('inf') else -1 15 | -------------------------------------------------------------------------------- /2231-find-first-palindromic-string-in-the-array/find-first-palindromic-string-in-the-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstPalindrome(self, words): 3 | """ 4 | :type words: List[str] 5 | :rtype: str 6 | """ 7 | def is_palindrome(word): 8 | return word == word[::-1] 9 | 10 | for word in words: 11 | if is_palindrome(word): 12 | return word 13 | 14 | return "" 15 | -------------------------------------------------------------------------------- /bit-manipulation/count-number-of-maximum-bitwise-or-subsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countMaxOrSubsets(int[] nums) { 3 | int max = 0; 4 | for (int n : nums) max |= n; 5 | return dfs(nums, 0, 0, max); 6 | } 7 | private int dfs(int[] nums, int i, int or, int max) { 8 | if (i == nums.length) return or == max ? 1 : 0; 9 | return dfs(nums, i + 1, or | nums[i], max) + dfs(nums, i + 1, or, max); 10 | } 11 | } -------------------------------------------------------------------------------- /bit-manipulation/number-complement.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findComplement(int num) { 3 | String str = Integer.toBinaryString(num); 4 | String res = ""; 5 | for(int i=0;i 1) { 9 | while (n % factor == 0) { 10 | steps += factor; 11 | n /= factor; 12 | } 13 | factor++; 14 | } 15 | 16 | return steps; 17 | } 18 | } -------------------------------------------------------------------------------- /sliding-window/count-number-of-nice-subarrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfSubarrays(int[] nums, int k) { 3 | int n=nums.length; 4 | int ans=0, t=0; 5 | int cnt[] = new int[n+1]; 6 | cnt[0]=1; 7 | for(int v : nums){ 8 | t += v&1; 9 | if(t-k>=0){ 10 | ans += cnt[t-k]; 11 | } 12 | cnt[t]++; 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /counting/minimum-number-of-pushes-to-type-word-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumPushes(String word) { 3 | int[] cnt = new int[26]; 4 | for (int i = 0; i < word.length(); ++i) { 5 | ++cnt[word.charAt(i) - 'a']; 6 | } 7 | Arrays.sort(cnt); 8 | int ans = 0; 9 | for (int i = 0; i < 26; ++i) { 10 | ans += (i / 8 + 1) * cnt[26 - i - 1]; 11 | } 12 | return ans; 13 | } 14 | } -------------------------------------------------------------------------------- /greedy/minimum-number-of-pushes-to-type-word-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumPushes(String word) { 3 | int[] cnt = new int[26]; 4 | for (int i = 0; i < word.length(); ++i) { 5 | ++cnt[word.charAt(i) - 'a']; 6 | } 7 | Arrays.sort(cnt); 8 | int ans = 0; 9 | for (int i = 0; i < 26; ++i) { 10 | ans += (i / 8 + 1) * cnt[26 - i - 1]; 11 | } 12 | return ans; 13 | } 14 | } -------------------------------------------------------------------------------- /sorting/minimum-number-of-pushes-to-type-word-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumPushes(String word) { 3 | int[] cnt = new int[26]; 4 | for (int i = 0; i < word.length(); ++i) { 5 | ++cnt[word.charAt(i) - 'a']; 6 | } 7 | Arrays.sort(cnt); 8 | int ans = 0; 9 | for (int i = 0; i < 26; ++i) { 10 | ans += (i / 8 + 1) * cnt[26 - i - 1]; 11 | } 12 | return ans; 13 | } 14 | } -------------------------------------------------------------------------------- /string/minimum-number-of-pushes-to-type-word-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumPushes(String word) { 3 | int[] cnt = new int[26]; 4 | for (int i = 0; i < word.length(); ++i) { 5 | ++cnt[word.charAt(i) - 'a']; 6 | } 7 | Arrays.sort(cnt); 8 | int ans = 0; 9 | for (int i = 0; i < 26; ++i) { 10 | ans += (i / 8 + 1) * cnt[26 - i - 1]; 11 | } 12 | return ans; 13 | } 14 | } -------------------------------------------------------------------------------- /3242-count-elements-with-maximum-frequency/count-elements-with-maximum-frequency.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxFrequencyElements(self, nums): 3 | freq_counter = Counter(nums) 4 | 5 | max_frequency = max(freq_counter.values()) 6 | 7 | max_freq_elements = [num for num, freq in freq_counter.items() if freq == max_frequency] 8 | 9 | total_frequency = max_frequency * len(max_freq_elements) 10 | 11 | return total_frequency -------------------------------------------------------------------------------- /hash-table/minimum-number-of-pushes-to-type-word-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumPushes(String word) { 3 | int[] cnt = new int[26]; 4 | for (int i = 0; i < word.length(); ++i) { 5 | ++cnt[word.charAt(i) - 'a']; 6 | } 7 | Arrays.sort(cnt); 8 | int ans = 0; 9 | for (int i = 0; i < 26; ++i) { 10 | ans += (i / 8 + 1) * cnt[26 - i - 1]; 11 | } 12 | return ans; 13 | } 14 | } -------------------------------------------------------------------------------- /tree/sum-of-left-leaves.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int sumOfLeftLeaves(TreeNode root) { 3 | if (root == null) { 4 | return 0; 5 | } 6 | int sum = 0; 7 | if (root.left != null && root.left.left == null && root.left.right == null) { 8 | sum += root.left.val; 9 | } 10 | sum += sumOfLeftLeaves(root.left); 11 | sum += sumOfLeftLeaves(root.right); 12 | return sum; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /982-minimum-increment-to-make-array-unique/minimum-increment-to-make-array-unique.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minIncrementForUnique(int[] nums) { 3 | Arrays.sort(nums); 4 | int ans = 0; 5 | for (int i = 1; i < nums.length; i++) { 6 | if (nums[i] <= nums[i - 1]) { 7 | ans += nums[i - 1] - nums[i] + 1; 8 | nums[i] = nums[i - 1] + 1; 9 | } 10 | } 11 | return ans; 12 | } 13 | } -------------------------------------------------------------------------------- /array/sum-of-all-subset-xor-totals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subsetXORSum(int[] nums) { 3 | return helper(nums, 0, 0); 4 | } 5 | 6 | public int helper(int[] nums, int level, int currentXOR) { 7 | if (level == nums.length) return currentXOR; 8 | int include = helper(nums, level + 1, currentXOR ^ nums[level]); 9 | int exclude = helper(nums, level + 1, currentXOR); 10 | return include + exclude; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /binary-tree/sum-of-left-leaves.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int sumOfLeftLeaves(TreeNode root) { 3 | if (root == null) { 4 | return 0; 5 | } 6 | int sum = 0; 7 | if (root.left != null && root.left.left == null && root.left.right == null) { 8 | sum += root.left.val; 9 | } 10 | sum += sumOfLeftLeaves(root.left); 11 | sum += sumOfLeftLeaves(root.right); 12 | return sum; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /math/sum-of-all-subset-xor-totals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subsetXORSum(int[] nums) { 3 | return helper(nums, 0, 0); 4 | } 5 | 6 | public int helper(int[] nums, int level, int currentXOR) { 7 | if (level == nums.length) return currentXOR; 8 | int include = helper(nums, level + 1, currentXOR ^ nums[level]); 9 | int exclude = helper(nums, level + 1, currentXOR); 10 | return include + exclude; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /1370-count-number-of-nice-subarrays/count-number-of-nice-subarrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfSubarrays(int[] nums, int k) { 3 | int n=nums.length; 4 | int ans=0, t=0; 5 | int cnt[] = new int[n+1]; 6 | cnt[0]=1; 7 | for(int v : nums){ 8 | t += v&1; 9 | if(t-k>=0){ 10 | ans += cnt[t-k]; 11 | } 12 | cnt[t]++; 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /2023/aug22.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def convertToTitle(self, columnNumber): 3 | result = [] 4 | 5 | while columnNumber > 0: 6 | columnNumber -= 1 # Adjust to 0-based index 7 | remainder = columnNumber % 26 8 | result.append(chr(remainder + ord('A'))) 9 | columnNumber //= 26 10 | 11 | result.reverse() # Reverse the list to get the correct order 12 | return ''.join(result) 13 | 14 | -------------------------------------------------------------------------------- /2024/jan-4.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def minOperations(self, nums): 5 | mp = Counter(nums) 6 | 7 | count = 0 8 | for t in mp.values(): 9 | if t == 1: 10 | return -1 11 | count += t // 3 12 | if t % 3: 13 | count += 1 14 | 15 | return count 16 | 17 | solution = Solution() 18 | nums = [1, 2, 2, 1, 1, 3] 19 | print(solution.minOperations(nums)) 20 | -------------------------------------------------------------------------------- /backtracking/sum-of-all-subset-xor-totals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subsetXORSum(int[] nums) { 3 | return helper(nums, 0, 0); 4 | } 5 | 6 | public int helper(int[] nums, int level, int currentXOR) { 7 | if (level == nums.length) return currentXOR; 8 | int include = helper(nums, level + 1, currentXOR ^ nums[level]); 9 | int exclude = helper(nums, level + 1, currentXOR); 10 | return include + exclude; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /combinatorics/sum-of-all-subset-xor-totals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subsetXORSum(int[] nums) { 3 | return helper(nums, 0, 0); 4 | } 5 | 6 | public int helper(int[] nums, int level, int currentXOR) { 7 | if (level == nums.length) return currentXOR; 8 | int include = helper(nums, level + 1, currentXOR ^ nums[level]); 9 | int exclude = helper(nums, level + 1, currentXOR); 10 | return include + exclude; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /enumeration/sum-of-all-subset-xor-totals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subsetXORSum(int[] nums) { 3 | return helper(nums, 0, 0); 4 | } 5 | 6 | public int helper(int[] nums, int level, int currentXOR) { 7 | if (level == nums.length) return currentXOR; 8 | int include = helper(nums, level + 1, currentXOR ^ nums[level]); 9 | int exclude = helper(nums, level + 1, currentXOR); 10 | return include + exclude; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /greedy/append-characters-to-string-to-make-subsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int appendCharacters(String s, String t) { 4 | int first = 0, longestPrefix = 0; 5 | 6 | while (first < s.length() && longestPrefix < t.length()) { 7 | if (s.charAt(first) == t.charAt(longestPrefix)) { 8 | longestPrefix++; 9 | } 10 | first++; 11 | } 12 | 13 | return t.length() - longestPrefix; 14 | } 15 | } -------------------------------------------------------------------------------- /math/insert-greatest-common-divisors-in-linked-list.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private int gcd(int a, int b) { 3 | if (b == 0) return a; 4 | return gcd(b, a % b); 5 | } 6 | 7 | public ListNode insertGreatestCommonDivisors(ListNode head) { 8 | var p = head; 9 | 10 | while (p.next != null) { 11 | var newNode = new ListNode(gcd(p.val, p.next.val), p.next); 12 | p.next = newNode; 13 | p = newNode.next; 14 | } 15 | return head; 16 | } 17 | } -------------------------------------------------------------------------------- /string/append-characters-to-string-to-make-subsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int appendCharacters(String s, String t) { 4 | int first = 0, longestPrefix = 0; 5 | 6 | while (first < s.length() && longestPrefix < t.length()) { 7 | if (s.charAt(first) == t.charAt(longestPrefix)) { 8 | longestPrefix++; 9 | } 10 | first++; 11 | } 12 | 13 | return t.length() - longestPrefix; 14 | } 15 | } -------------------------------------------------------------------------------- /387-first-unique-character-in-a-string/first-unique-character-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstUniqChar(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | char_count={} 8 | 9 | for char in s: 10 | char_count[char] = char_count.get(char, 0)+1 11 | 12 | for i in range(len(s)): 13 | if char_count[s[i]] == 1: 14 | return i 15 | 16 | return -1 17 | -------------------------------------------------------------------------------- /404-sum-of-left-leaves/sum-of-left-leaves.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int sumOfLeftLeaves(TreeNode root) { 3 | if (root == null) { 4 | return 0; 5 | } 6 | int sum = 0; 7 | if (root.left != null && root.left.left == null && root.left.right == null) { 8 | sum += root.left.val; 9 | } 10 | sum += sumOfLeftLeaves(root.left); 11 | sum += sumOfLeftLeaves(root.right); 12 | return sum; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /array/minimum-replacements-to-sort-the-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumReplacement(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | ops = 0 5 | 6 | prev = nums[n - 1] 7 | 8 | for i in range(n - 2, -1, -1): 9 | if nums[i] > prev: 10 | k = math.ceil(nums[i] / prev) 11 | ops += k - 1 12 | prev = nums[i] // k 13 | else: 14 | prev = nums[i] 15 | return ops -------------------------------------------------------------------------------- /bit-manipulation/sum-of-all-subset-xor-totals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subsetXORSum(int[] nums) { 3 | return helper(nums, 0, 0); 4 | } 5 | 6 | public int helper(int[] nums, int level, int currentXOR) { 7 | if (level == nums.length) return currentXOR; 8 | int include = helper(nums, level + 1, currentXOR ^ nums[level]); 9 | int exclude = helper(nums, level + 1, currentXOR); 10 | return include + exclude; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /breadth-first-search/sum-of-left-leaves.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int sumOfLeftLeaves(TreeNode root) { 3 | if (root == null) { 4 | return 0; 5 | } 6 | int sum = 0; 7 | if (root.left != null && root.left.left == null && root.left.right == null) { 8 | sum += root.left.val; 9 | } 10 | sum += sumOfLeftLeaves(root.left); 11 | sum += sumOfLeftLeaves(root.right); 12 | return sum; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /depth-first-search/sum-of-left-leaves.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int sumOfLeftLeaves(TreeNode root) { 3 | if (root == null) { 4 | return 0; 5 | } 6 | int sum = 0; 7 | if (root.left != null && root.left.left == null && root.left.right == null) { 8 | sum += root.left.val; 9 | } 10 | sum += sumOfLeftLeaves(root.left); 11 | sum += sumOfLeftLeaves(root.right); 12 | return sum; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /greedy/minimum-replacements-to-sort-the-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumReplacement(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | ops = 0 5 | 6 | prev = nums[n - 1] 7 | 8 | for i in range(n - 2, -1, -1): 9 | if nums[i] > prev: 10 | k = math.ceil(nums[i] / prev) 11 | ops += k - 1 12 | prev = nums[i] // k 13 | else: 14 | prev = nums[i] 15 | return ops -------------------------------------------------------------------------------- /linked-list/insert-greatest-common-divisors-in-linked-list.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private int gcd(int a, int b) { 3 | if (b == 0) return a; 4 | return gcd(b, a % b); 5 | } 6 | 7 | public ListNode insertGreatestCommonDivisors(ListNode head) { 8 | var p = head; 9 | 10 | while (p.next != null) { 11 | var newNode = new ListNode(gcd(p.val, p.next.val), p.next); 12 | p.next = newNode; 13 | p = newNode.next; 14 | } 15 | return head; 16 | } 17 | } -------------------------------------------------------------------------------- /math/minimum-replacements-to-sort-the-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumReplacement(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | ops = 0 5 | 6 | prev = nums[n - 1] 7 | 8 | for i in range(n - 2, -1, -1): 9 | if nums[i] > prev: 10 | k = math.ceil(nums[i] / prev) 11 | ops += k - 1 12 | prev = nums[i] // k 13 | else: 14 | prev = nums[i] 15 | return ops -------------------------------------------------------------------------------- /number-theory/insert-greatest-common-divisors-in-linked-list.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private int gcd(int a, int b) { 3 | if (b == 0) return a; 4 | return gcd(b, a % b); 5 | } 6 | 7 | public ListNode insertGreatestCommonDivisors(ListNode head) { 8 | var p = head; 9 | 10 | while (p.next != null) { 11 | var newNode = new ListNode(gcd(p.val, p.next.val), p.next); 12 | p.next = newNode; 13 | p = newNode.next; 14 | } 15 | return head; 16 | } 17 | } -------------------------------------------------------------------------------- /two-pointers/append-characters-to-string-to-make-subsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int appendCharacters(String s, String t) { 4 | int first = 0, longestPrefix = 0; 5 | 6 | while (first < s.length() && longestPrefix < t.length()) { 7 | if (s.charAt(first) == t.charAt(longestPrefix)) { 8 | longestPrefix++; 9 | } 10 | first++; 11 | } 12 | 13 | return t.length() - longestPrefix; 14 | } 15 | } -------------------------------------------------------------------------------- /3351-maximize-happiness-of-selected-children/maximize-happiness-of-selected-children.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public long maximumHappinessSum(int[] happiness, int k) { 3 | Arrays.sort(happiness); 4 | long res = 0; 5 | int n = happiness.length, j = 0; 6 | 7 | for (int i = n - 1; i >= n - k; --i) { 8 | happiness[i] = Math.max(happiness[i] - j++, 0); 9 | res += happiness[i]; 10 | } 11 | 12 | return res; 13 | } 14 | } -------------------------------------------------------------------------------- /array/frog-jump.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCross(self, stones: List[int]) -> bool: 3 | n = len(stones) 4 | 5 | dp = {stone:set() for stone in stones} 6 | dp[0].add(0) 7 | 8 | 9 | for i in range(n): 10 | for k in dp[stones[i]]: 11 | for step in range(k-1, k+2): 12 | if step and stones[i] + step in dp: 13 | dp[stones[i] + step].add(step) 14 | 15 | return len(dp[stones[-1]]) > 0 -------------------------------------------------------------------------------- /array/patching-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minPatches(int[] nums, int n) { 3 | long miss = 1; 4 | int result = 0; 5 | int i = 0; 6 | 7 | while (miss <= n) { 8 | if (i < nums.length && nums[i] <= miss) { 9 | miss += nums[i]; 10 | i++; 11 | } else { 12 | miss += miss; 13 | result++; 14 | } 15 | } 16 | 17 | return result; 18 | } 19 | } -------------------------------------------------------------------------------- /greedy/patching-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minPatches(int[] nums, int n) { 3 | long miss = 1; 4 | int result = 0; 5 | int i = 0; 6 | 7 | while (miss <= n) { 8 | if (i < nums.length && nums[i] <= miss) { 9 | miss += nums[i]; 10 | i++; 11 | } else { 12 | miss += miss; 13 | result++; 14 | } 15 | } 16 | 17 | return result; 18 | } 19 | } -------------------------------------------------------------------------------- /1993-sum-of-all-subset-xor-totals/sum-of-all-subset-xor-totals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subsetXORSum(int[] nums) { 3 | return helper(nums, 0, 0); 4 | } 5 | 6 | public int helper(int[] nums, int level, int currentXOR) { 7 | if (level == nums.length) return currentXOR; 8 | int include = helper(nums, level + 1, currentXOR ^ nums[level]); 9 | int exclude = helper(nums, level + 1, currentXOR); 10 | return include + exclude; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /966-binary-subarrays-with-sum/binary-subarrays-with-sum.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numSubarraysWithSum(self, nums, goal): 3 | count = {0: 1} 4 | curr_sum = 0 5 | total_subarrays = 0 6 | 7 | for num in nums: 8 | curr_sum += num 9 | if curr_sum - goal in count: 10 | total_subarrays += count[curr_sum - goal] 11 | count[curr_sum] = count.get(curr_sum, 0) + 1 12 | 13 | return total_subarrays -------------------------------------------------------------------------------- /array/minimum-number-of-taps-to-open-to-water-a-garden.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minTaps(self, n, ranges): 3 | dp = [float('inf')] * (n + 1) 4 | 5 | dp[0] = 0 6 | 7 | for i, tap_range in enumerate(ranges): 8 | left = max(0, i - tap_range) 9 | right = min(n, i + tap_range) 10 | 11 | for j in range(left, right + 1): 12 | dp[j] = min(dp[j], dp[left] + 1) 13 | 14 | return dp[n] if dp[n] < float('inf') else -1 15 | -------------------------------------------------------------------------------- /2023/aug27.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCross(self, stones: list[int]) -> bool: 3 | n = len(stones) 4 | 5 | dp = {stone:set() for stone in stones} 6 | dp[0].add(0) 7 | 8 | 9 | for i in range(n): 10 | for k in dp[stones[i]]: 11 | for step in range(k-1, k+2): 12 | if step and stones[i] + step in dp: 13 | dp[stones[i] + step].add(step) 14 | 15 | return len(dp[stones[-1]]) > 0 16 | 17 | -------------------------------------------------------------------------------- /2024/jan-17.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution(object): 4 | def uniqueOccurrences(self, arr): 5 | """ 6 | :type arr: List[int] 7 | :rtype: bool 8 | """ 9 | # Count occurrences of each value using Counter 10 | occurrences = Counter(arr) 11 | 12 | # Check if the number of occurrences is unique 13 | unique_counts = set(occurrences.values()) 14 | 15 | return len(unique_counts) == len(occurrences) 16 | 17 | -------------------------------------------------------------------------------- /2024/jan-29.py: -------------------------------------------------------------------------------- 1 | class MyQueue: 2 | def __init__(self): 3 | self.s1 = [] 4 | self.s2 = [] 5 | 6 | def push(self, x): 7 | while self.s1: 8 | self.s2.append(self.s1.pop()) 9 | self.s1.append(x) 10 | while self.s2: 11 | self.s1.append(self.s2.pop()) 12 | 13 | def pop(self): 14 | return self.s1.pop() 15 | 16 | def peek(self): 17 | return self.s1[-1] 18 | 19 | def empty(self): 20 | return not self.s1 21 | 22 | -------------------------------------------------------------------------------- /330-patching-array/patching-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minPatches(int[] nums, int n) { 3 | long miss = 1; 4 | int result = 0; 5 | int i = 0; 6 | 7 | while (miss <= n) { 8 | if (i < nums.length && nums[i] <= miss) { 9 | miss += nums[i]; 10 | i++; 11 | } else { 12 | miss += miss; 13 | result++; 14 | } 15 | } 16 | 17 | return result; 18 | } 19 | } -------------------------------------------------------------------------------- /enumeration/sequential-digits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sequentialDigits(self, low, high): 3 | """ 4 | :type low: int 5 | :type high: int 6 | :rtype: List[int] 7 | """ 8 | result = [] 9 | for i in range(1, 10): 10 | num = i 11 | for j in range(i + 1, 10): 12 | num = num * 10 + j 13 | if low <= num <= high: 14 | result.append(num) 15 | return sorted(result) 16 | -------------------------------------------------------------------------------- /greedy/minimum-number-of-taps-to-open-to-water-a-garden.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minTaps(self, n, ranges): 3 | dp = [float('inf')] * (n + 1) 4 | 5 | dp[0] = 0 6 | 7 | for i, tap_range in enumerate(ranges): 8 | left = max(0, i - tap_range) 9 | right = min(n, i + tap_range) 10 | 11 | for j in range(left, right + 1): 12 | dp[j] = min(dp[j], dp[left] + 1) 13 | 14 | return dp[n] if dp[n] < float('inf') else -1 15 | -------------------------------------------------------------------------------- /stack/minimum-deletions-to-make-string-balanced.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumDeletions(String s) { 3 | int n = s.length(); 4 | int[] f = new int[n + 1]; 5 | int b = 0; 6 | for (int i = 1; i <= n; ++i) { 7 | if (s.charAt(i - 1) == 'b') { 8 | f[i] = f[i - 1]; 9 | ++b; 10 | } else { 11 | f[i] = Math.min(f[i - 1] + 1, b); 12 | } 13 | } 14 | return f[n]; 15 | } 16 | } -------------------------------------------------------------------------------- /stack/minimum-string-length-after-removing-substrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minLength(self, s: str) -> int: 3 | stack = [] 4 | for c in s: 5 | if not stack: 6 | stack.append(c) 7 | continue 8 | if c == "B" and stack[-1] == "A": 9 | stack.pop() 10 | elif c == "D" and stack[-1] == "C": 11 | stack.pop() 12 | else: 13 | stack.append(c) 14 | return len(stack) -------------------------------------------------------------------------------- /string/minimum-string-length-after-removing-substrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minLength(self, s: str) -> int: 3 | stack = [] 4 | for c in s: 5 | if not stack: 6 | stack.append(c) 7 | continue 8 | if c == "B" and stack[-1] == "A": 9 | stack.pop() 10 | elif c == "D" and stack[-1] == "C": 11 | stack.pop() 12 | else: 13 | stack.append(c) 14 | return len(stack) -------------------------------------------------------------------------------- /array/points-that-intersect-with-cars.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numberOfPoints(self, nums): 3 | """ 4 | :type nums: List[List[int]] 5 | :rtype: int 6 | """ 7 | points = set() # Use a set to store unique points 8 | 9 | for start, end in nums: 10 | for i in range(start, end + 1): 11 | points.add(i) # Add all points between start and end to the set 12 | 13 | return len(points) # Return the number of unique points 14 | -------------------------------------------------------------------------------- /dynamic-programming/frog-jump.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCross(self, stones: List[int]) -> bool: 3 | n = len(stones) 4 | 5 | dp = {stone:set() for stone in stones} 6 | dp[0].add(0) 7 | 8 | 9 | for i in range(n): 10 | for k in dp[stones[i]]: 11 | for step in range(k-1, k+2): 12 | if step and stones[i] + step in dp: 13 | dp[stones[i] + step].add(step) 14 | 15 | return len(dp[stones[-1]]) > 0 -------------------------------------------------------------------------------- /simulation/minimum-string-length-after-removing-substrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minLength(self, s: str) -> int: 3 | stack = [] 4 | for c in s: 5 | if not stack: 6 | stack.append(c) 7 | continue 8 | if c == "B" and stack[-1] == "A": 9 | stack.pop() 10 | elif c == "D" and stack[-1] == "C": 11 | stack.pop() 12 | else: 13 | stack.append(c) 14 | return len(stack) -------------------------------------------------------------------------------- /stack/reverse-prefix-of-word.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reversePrefix(String word, char ch) { 3 | int firstOccurence = word.indexOf(ch); 4 | if (firstOccurence == -1) { 5 | return word; 6 | } 7 | StringBuilder sb = new StringBuilder(word.substring(0, firstOccurence + 1)).reverse(); 8 | if (firstOccurence < word.length()) { 9 | sb.append(word.substring(firstOccurence + 1)); 10 | } 11 | return sb.toString(); 12 | } 13 | } -------------------------------------------------------------------------------- /string/minimum-deletions-to-make-string-balanced.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumDeletions(String s) { 3 | int n = s.length(); 4 | int[] f = new int[n + 1]; 5 | int b = 0; 6 | for (int i = 1; i <= n; ++i) { 7 | if (s.charAt(i - 1) == 'b') { 8 | f[i] = f[i - 1]; 9 | ++b; 10 | } else { 11 | f[i] = Math.min(f[i - 1] + 1, b); 12 | } 13 | } 14 | return f[n]; 15 | } 16 | } -------------------------------------------------------------------------------- /string/reverse-prefix-of-word.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reversePrefix(String word, char ch) { 3 | int firstOccurence = word.indexOf(ch); 4 | if (firstOccurence == -1) { 5 | return word; 6 | } 7 | StringBuilder sb = new StringBuilder(word.substring(0, firstOccurence + 1)).reverse(); 8 | if (firstOccurence < word.length()) { 9 | sb.append(word.substring(firstOccurence + 1)); 10 | } 11 | return sb.toString(); 12 | } 13 | } -------------------------------------------------------------------------------- /1212-sequential-digits/sequential-digits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sequentialDigits(self, low, high): 3 | """ 4 | :type low: int 5 | :type high: int 6 | :rtype: List[int] 7 | """ 8 | result = [] 9 | for i in range(1, 10): 10 | num = i 11 | for j in range(i + 1, 10): 12 | num = num * 10 + j 13 | if low <= num <= high: 14 | result.append(num) 15 | return sorted(result) 16 | -------------------------------------------------------------------------------- /1765-merge-in-between-linked-lists/merge-in-between-linked-lists.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def mergeInBetween(self, list1, a, b, list2): 3 | ptr = list1 4 | for _ in range(a - 1): 5 | ptr = ptr.next 6 | 7 | qtr = ptr.next 8 | for _ in range(b - a + 1): 9 | qtr = qtr.next 10 | 11 | ptr.next = list2 12 | while list2.next: 13 | list2 = list2.next 14 | list2.next = qtr 15 | 16 | return list1 -------------------------------------------------------------------------------- /807-custom-sort-string/custom-sort-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def customSortString(self, order, s): 3 | """ 4 | :type order: str 5 | :type s: str 6 | :rtype: str 7 | """ 8 | # Define a custom sorting key 9 | key = lambda x: order.index(x) if x in order else float('inf') 10 | 11 | # Sort the characters in string s based on the custom key 12 | sorted_s = ''.join(sorted(s, key=key)) 13 | 14 | return sorted_s 15 | -------------------------------------------------------------------------------- /array/single-number-iii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] singleNumber(int[] nums) { 3 | int xorAll = 0; 4 | for (int num : nums) { 5 | xorAll ^= num; 6 | } 7 | int setBit = xorAll & -xorAll; 8 | int a = 0, b = 0; 9 | for (int num : nums) { 10 | if ((num & setBit) != 0) { 11 | a ^= num; 12 | } else { 13 | b ^= num; 14 | } 15 | } 16 | return new int[]{a, b}; 17 | } 18 | } -------------------------------------------------------------------------------- /dynamic-programming/minimum-number-of-taps-to-open-to-water-a-garden.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minTaps(self, n, ranges): 3 | dp = [float('inf')] * (n + 1) 4 | 5 | dp[0] = 0 6 | 7 | for i, tap_range in enumerate(ranges): 8 | left = max(0, i - tap_range) 9 | right = min(n, i + tap_range) 10 | 11 | for j in range(left, right + 1): 12 | dp[j] = min(dp[j], dp[left] + 1) 13 | 14 | return dp[n] if dp[n] < float('inf') else -1 15 | -------------------------------------------------------------------------------- /hash-table/points-that-intersect-with-cars.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numberOfPoints(self, nums): 3 | """ 4 | :type nums: List[List[int]] 5 | :rtype: int 6 | """ 7 | points = set() # Use a set to store unique points 8 | 9 | for start, end in nums: 10 | for i in range(start, end + 1): 11 | points.add(i) # Add all points between start and end to the set 12 | 13 | return len(points) # Return the number of unique points 14 | -------------------------------------------------------------------------------- /prefix-sum/points-that-intersect-with-cars.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numberOfPoints(self, nums): 3 | """ 4 | :type nums: List[List[int]] 5 | :rtype: int 6 | """ 7 | points = set() # Use a set to store unique points 8 | 9 | for start, end in nums: 10 | for i in range(start, end + 1): 11 | points.add(i) # Add all points between start and end to the set 12 | 13 | return len(points) # Return the number of unique points 14 | -------------------------------------------------------------------------------- /trie/remove-sub-folders-from-the-filesystem.js: -------------------------------------------------------------------------------- 1 | 2 | var removeSubfolders = function (folder) { 3 | folder.sort((a, b) => a.length - b.length) 4 | let set = new Set() 5 | primary: for (let dir of folder) { 6 | let dirArr = dir.split('/') 7 | let parDir = '' 8 | for (let i = 1; i < dirArr.length; i++) { 9 | parDir += `/${dirArr[i]}` 10 | if (set.has(parDir)) continue primary 11 | } 12 | set.add(parDir) 13 | } 14 | return Array.from(set) 15 | }; -------------------------------------------------------------------------------- /array/minimum-number-of-moves-to-seat-everyone.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int minMovesToSeat(int[] seats, int[] students) { 4 | Arrays.sort(seats); 5 | Arrays.sort(students); 6 | int moves = 0; 7 | for (int i = 0; i < seats.length; i++) { 8 | // Add the absolute value of the difference 9 | // between the position of the seat and the student 10 | moves += Math.abs(seats[i] - students[i]); 11 | } 12 | return moves; 13 | } 14 | } -------------------------------------------------------------------------------- /array/remove-sub-folders-from-the-filesystem.js: -------------------------------------------------------------------------------- 1 | 2 | var removeSubfolders = function (folder) { 3 | folder.sort((a, b) => a.length - b.length) 4 | let set = new Set() 5 | primary: for (let dir of folder) { 6 | let dirArr = dir.split('/') 7 | let parDir = '' 8 | for (let i = 1; i < dirArr.length; i++) { 9 | parDir += `/${dirArr[i]}` 10 | if (set.has(parDir)) continue primary 11 | } 12 | set.add(parDir) 13 | } 14 | return Array.from(set) 15 | }; -------------------------------------------------------------------------------- /dynamic-programming/minimum-deletions-to-make-string-balanced.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumDeletions(String s) { 3 | int n = s.length(); 4 | int[] f = new int[n + 1]; 5 | int b = 0; 6 | for (int i = 1; i <= n; ++i) { 7 | if (s.charAt(i - 1) == 'b') { 8 | f[i] = f[i - 1]; 9 | ++b; 10 | } else { 11 | f[i] = Math.min(f[i - 1] + 1, b); 12 | } 13 | } 14 | return f[n]; 15 | } 16 | } -------------------------------------------------------------------------------- /greedy/minimum-number-of-moves-to-seat-everyone.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int minMovesToSeat(int[] seats, int[] students) { 4 | Arrays.sort(seats); 5 | Arrays.sort(students); 6 | int moves = 0; 7 | for (int i = 0; i < seats.length; i++) { 8 | // Add the absolute value of the difference 9 | // between the position of the seat and the student 10 | moves += Math.abs(seats[i] - students[i]); 11 | } 12 | return moves; 13 | } 14 | } -------------------------------------------------------------------------------- /sorting/minimum-number-of-moves-to-seat-everyone.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int minMovesToSeat(int[] seats, int[] students) { 4 | Arrays.sort(seats); 5 | Arrays.sort(students); 6 | int moves = 0; 7 | for (int i = 0; i < seats.length; i++) { 8 | // Add the absolute value of the difference 9 | // between the position of the seat and the student 10 | moves += Math.abs(seats[i] - students[i]); 11 | } 12 | return moves; 13 | } 14 | } -------------------------------------------------------------------------------- /string/remove-sub-folders-from-the-filesystem.js: -------------------------------------------------------------------------------- 1 | 2 | var removeSubfolders = function (folder) { 3 | folder.sort((a, b) => a.length - b.length) 4 | let set = new Set() 5 | primary: for (let dir of folder) { 6 | let dirArr = dir.split('/') 7 | let parDir = '' 8 | for (let i = 1; i < dirArr.length; i++) { 9 | parDir += `/${dirArr[i]}` 10 | if (set.has(parDir)) continue primary 11 | } 12 | set.add(parDir) 13 | } 14 | return Array.from(set) 15 | }; -------------------------------------------------------------------------------- /two-pointers/reverse-prefix-of-word.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reversePrefix(String word, char ch) { 3 | int firstOccurence = word.indexOf(ch); 4 | if (firstOccurence == -1) { 5 | return word; 6 | } 7 | StringBuilder sb = new StringBuilder(word.substring(0, firstOccurence + 1)).reverse(); 8 | if (firstOccurence < word.length()) { 9 | sb.append(word.substring(firstOccurence + 1)); 10 | } 11 | return sb.toString(); 12 | } 13 | } -------------------------------------------------------------------------------- /array/minimum-swaps-to-group-all-1s-together-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSwaps(int[] nums) { 3 | int k = Arrays.stream(nums).sum(); 4 | int n = nums.length; 5 | int cnt = 0; 6 | for (int i = 0; i < k; ++i) { 7 | cnt += nums[i]; 8 | } 9 | int mx = cnt; 10 | for (int i = k; i < n + k; ++i) { 11 | cnt += nums[i % n] - nums[(i - k + n) % n]; 12 | mx = Math.max(mx, cnt); 13 | } 14 | return k - mx; 15 | } 16 | } -------------------------------------------------------------------------------- /array/my-calendar-i.java: -------------------------------------------------------------------------------- 1 | class MyCalendar { 2 | TreeMap calcy; 3 | public MyCalendar() { 4 | calcy = new TreeMap(); 5 | 6 | } 7 | 8 | public boolean book(int start, int end) { 9 | Integer prevBook = calcy.floorKey(start); 10 | Integer nextBook = calcy.ceilingKey(start); 11 | if((prevBook==null || calcy.get(prevBook)<=start) && (nextBook==null || end<=nextBook)) 12 | { 13 | calcy.put(start, end); 14 | return true; 15 | } 16 | return false; 17 | } 18 | } -------------------------------------------------------------------------------- /array/unique-number-of-occurrences.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution(object): 4 | def uniqueOccurrences(self, arr): 5 | """ 6 | :type arr: List[int] 7 | :rtype: bool 8 | """ 9 | # Count occurrences of each value using Counter 10 | occurrences = Counter(arr) 11 | 12 | # Check if the number of occurrences is unique 13 | unique_counts = set(occurrences.values()) 14 | 15 | return len(unique_counts) == len(occurrences) 16 | 17 | -------------------------------------------------------------------------------- /design/my-calendar-i.java: -------------------------------------------------------------------------------- 1 | class MyCalendar { 2 | TreeMap calcy; 3 | public MyCalendar() { 4 | calcy = new TreeMap(); 5 | 6 | } 7 | 8 | public boolean book(int start, int end) { 9 | Integer prevBook = calcy.floorKey(start); 10 | Integer nextBook = calcy.ceilingKey(start); 11 | if((prevBook==null || calcy.get(prevBook)<=start) && (nextBook==null || end<=nextBook)) 12 | { 13 | calcy.put(start, end); 14 | return true; 15 | } 16 | return false; 17 | } 18 | } -------------------------------------------------------------------------------- /2023/aug26.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLongestChain(self,pairs): 3 | # Sort the pairs based on the right end in ascending order. 4 | pairs.sort(key=lambda x: x[1]) 5 | 6 | n = len(pairs) 7 | dp = [1] * n # Initialize the dp array with all 1s. 8 | 9 | for i in range(1, n): 10 | for j in range(i): 11 | if pairs[i][0] > pairs[j][1]: 12 | dp[i] = max(dp[i], dp[j] + 1) 13 | 14 | return max(dp) 15 | 16 | -------------------------------------------------------------------------------- /2572-append-characters-to-string-to-make-subsequence/append-characters-to-string-to-make-subsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int appendCharacters(String s, String t) { 4 | int first = 0, longestPrefix = 0; 5 | 6 | while (first < s.length() && longestPrefix < t.length()) { 7 | if (s.charAt(first) == t.charAt(longestPrefix)) { 8 | longestPrefix++; 9 | } 10 | first++; 11 | } 12 | 13 | return t.length() - longestPrefix; 14 | } 15 | } -------------------------------------------------------------------------------- /bit-manipulation/single-number-iii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] singleNumber(int[] nums) { 3 | int xorAll = 0; 4 | for (int num : nums) { 5 | xorAll ^= num; 6 | } 7 | int setBit = xorAll & -xorAll; 8 | int a = 0, b = 0; 9 | for (int num : nums) { 10 | if ((num & setBit) != 0) { 11 | a ^= num; 12 | } else { 13 | b ^= num; 14 | } 15 | } 16 | return new int[]{a, b}; 17 | } 18 | } -------------------------------------------------------------------------------- /counting-sort/minimum-number-of-moves-to-seat-everyone.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int minMovesToSeat(int[] seats, int[] students) { 4 | Arrays.sort(seats); 5 | Arrays.sort(students); 6 | int moves = 0; 7 | for (int i = 0; i < seats.length; i++) { 8 | // Add the absolute value of the difference 9 | // between the position of the seat and the student 10 | moves += Math.abs(seats[i] - students[i]); 11 | } 12 | return moves; 13 | } 14 | } -------------------------------------------------------------------------------- /depth-first-search/remove-sub-folders-from-the-filesystem.js: -------------------------------------------------------------------------------- 1 | 2 | var removeSubfolders = function (folder) { 3 | folder.sort((a, b) => a.length - b.length) 4 | let set = new Set() 5 | primary: for (let dir of folder) { 6 | let dirArr = dir.split('/') 7 | let parDir = '' 8 | for (let i = 1; i < dirArr.length; i++) { 9 | parDir += `/${dirArr[i]}` 10 | if (set.has(parDir)) continue primary 11 | } 12 | set.add(parDir) 13 | } 14 | return Array.from(set) 15 | }; -------------------------------------------------------------------------------- /design/implement-queue-using-stacks.py: -------------------------------------------------------------------------------- 1 | class MyQueue: 2 | def __init__(self): 3 | self.s1 = [] 4 | self.s2 = [] 5 | 6 | def push(self, x): 7 | while self.s1: 8 | self.s2.append(self.s1.pop()) 9 | self.s1.append(x) 10 | while self.s2: 11 | self.s1.append(self.s2.pop()) 12 | 13 | def pop(self): 14 | return self.s1.pop() 15 | 16 | def peek(self): 17 | return self.s1[-1] 18 | 19 | def empty(self): 20 | return not self.s1 21 | 22 | -------------------------------------------------------------------------------- /hash-table/unique-number-of-occurrences.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution(object): 4 | def uniqueOccurrences(self, arr): 5 | """ 6 | :type arr: List[int] 7 | :rtype: bool 8 | """ 9 | # Count occurrences of each value using Counter 10 | occurrences = Counter(arr) 11 | 12 | # Check if the number of occurrences is unique 13 | unique_counts = set(occurrences.values()) 14 | 15 | return len(unique_counts) == len(occurrences) 16 | 17 | -------------------------------------------------------------------------------- /math/reverse-integer.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverse(self, x): 3 | if x < 0: 4 | sign = -1 5 | x = abs(x) 6 | else: 7 | sign = 1 8 | 9 | reversed_x = 0 10 | while x != 0: 11 | digit = x % 10 12 | reversed_x = reversed_x * 10 + digit 13 | x //= 10 14 | 15 | # Check for overflow 16 | if reversed_x > 2**31 - 1 or reversed_x < -2**31: 17 | return 0 18 | 19 | return sign * reversed_x 20 | -------------------------------------------------------------------------------- /ordered-set/my-calendar-i.java: -------------------------------------------------------------------------------- 1 | class MyCalendar { 2 | TreeMap calcy; 3 | public MyCalendar() { 4 | calcy = new TreeMap(); 5 | 6 | } 7 | 8 | public boolean book(int start, int end) { 9 | Integer prevBook = calcy.floorKey(start); 10 | Integer nextBook = calcy.ceilingKey(start); 11 | if((prevBook==null || calcy.get(prevBook)<=start) && (nextBook==null || end<=nextBook)) 12 | { 13 | calcy.put(start, end); 14 | return true; 15 | } 16 | return false; 17 | } 18 | } -------------------------------------------------------------------------------- /queue/implement-queue-using-stacks.py: -------------------------------------------------------------------------------- 1 | class MyQueue: 2 | def __init__(self): 3 | self.s1 = [] 4 | self.s2 = [] 5 | 6 | def push(self, x): 7 | while self.s1: 8 | self.s2.append(self.s1.pop()) 9 | self.s1.append(x) 10 | while self.s2: 11 | self.s1.append(self.s2.pop()) 12 | 13 | def pop(self): 14 | return self.s1.pop() 15 | 16 | def peek(self): 17 | return self.s1[-1] 18 | 19 | def empty(self): 20 | return not self.s1 21 | 22 | -------------------------------------------------------------------------------- /segment-tree/my-calendar-i.java: -------------------------------------------------------------------------------- 1 | class MyCalendar { 2 | TreeMap calcy; 3 | public MyCalendar() { 4 | calcy = new TreeMap(); 5 | 6 | } 7 | 8 | public boolean book(int start, int end) { 9 | Integer prevBook = calcy.floorKey(start); 10 | Integer nextBook = calcy.ceilingKey(start); 11 | if((prevBook==null || calcy.get(prevBook)<=start) && (nextBook==null || end<=nextBook)) 12 | { 13 | calcy.put(start, end); 14 | return true; 15 | } 16 | return false; 17 | } 18 | } -------------------------------------------------------------------------------- /stack/implement-queue-using-stacks.py: -------------------------------------------------------------------------------- 1 | class MyQueue: 2 | def __init__(self): 3 | self.s1 = [] 4 | self.s2 = [] 5 | 6 | def push(self, x): 7 | while self.s1: 8 | self.s2.append(self.s1.pop()) 9 | self.s1.append(x) 10 | while self.s2: 11 | self.s1.append(self.s2.pop()) 12 | 13 | def pop(self): 14 | return self.s1.pop() 15 | 16 | def peek(self): 17 | return self.s1[-1] 18 | 19 | def empty(self): 20 | return not self.s1 21 | 22 | -------------------------------------------------------------------------------- /2128-reverse-prefix-of-word/reverse-prefix-of-word.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reversePrefix(String word, char ch) { 3 | int firstOccurence = word.indexOf(ch); 4 | if (firstOccurence == -1) { 5 | return word; 6 | } 7 | StringBuilder sb = new StringBuilder(word.substring(0, firstOccurence + 1)).reverse(); 8 | if (firstOccurence < word.length()) { 9 | sb.append(word.substring(firstOccurence + 1)); 10 | } 11 | return sb.toString(); 12 | } 13 | } -------------------------------------------------------------------------------- /260-single-number-iii/single-number-iii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] singleNumber(int[] nums) { 3 | int xorAll = 0; 4 | for (int num : nums) { 5 | xorAll ^= num; 6 | } 7 | int setBit = xorAll & -xorAll; 8 | int a = 0, b = 0; 9 | for (int num : nums) { 10 | if ((num & setBit) != 0) { 11 | a ^= num; 12 | } else { 13 | b ^= num; 14 | } 15 | } 16 | return new int[]{a, b}; 17 | } 18 | } -------------------------------------------------------------------------------- /2634-minimum-common-value/minimum-common-value.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getCommon(self, nums1, nums2): 3 | """ 4 | :type nums1: List[int] 5 | :type nums2: List[int] 6 | :rtype: int 7 | """ 8 | i, j = 0, 0 9 | while i < len(nums1) and j < len(nums2): 10 | if nums1[i] == nums2[j]: 11 | return nums1[i] 12 | elif nums1[i] < nums2[j]: 13 | i += 1 14 | else: 15 | j += 1 16 | return -1 17 | -------------------------------------------------------------------------------- /binary-search/my-calendar-i.java: -------------------------------------------------------------------------------- 1 | class MyCalendar { 2 | TreeMap calcy; 3 | public MyCalendar() { 4 | calcy = new TreeMap(); 5 | 6 | } 7 | 8 | public boolean book(int start, int end) { 9 | Integer prevBook = calcy.floorKey(start); 10 | Integer nextBook = calcy.ceilingKey(start); 11 | if((prevBook==null || calcy.get(prevBook)<=start) && (nextBook==null || end<=nextBook)) 12 | { 13 | calcy.put(start, end); 14 | return true; 15 | } 16 | return false; 17 | } 18 | } -------------------------------------------------------------------------------- /sliding-window/minimum-swaps-to-group-all-1s-together-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSwaps(int[] nums) { 3 | int k = Arrays.stream(nums).sum(); 4 | int n = nums.length; 5 | int cnt = 0; 6 | for (int i = 0; i < k; ++i) { 7 | cnt += nums[i]; 8 | } 9 | int mx = cnt; 10 | for (int i = k; i < n + k; ++i) { 11 | cnt += nums[i % n] - nums[(i - k + n) % n]; 12 | mx = Math.max(mx, cnt); 13 | } 14 | return k - mx; 15 | } 16 | } -------------------------------------------------------------------------------- /array/maximum-length-of-pair-chain.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLongestChain(self,pairs): 3 | # Sort the pairs based on the right end in ascending order. 4 | pairs.sort(key=lambda x: x[1]) 5 | 6 | n = len(pairs) 7 | dp = [1] * n # Initialize the dp array with all 1s. 8 | 9 | for i in range(1, n): 10 | for j in range(i): 11 | if pairs[i][0] > pairs[j][1]: 12 | dp[i] = max(dp[i], dp[j] + 1) 13 | 14 | return max(dp) -------------------------------------------------------------------------------- /greedy/maximum-length-of-pair-chain.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLongestChain(self,pairs): 3 | # Sort the pairs based on the right end in ascending order. 4 | pairs.sort(key=lambda x: x[1]) 5 | 6 | n = len(pairs) 7 | dp = [1] * n # Initialize the dp array with all 1s. 8 | 9 | for i in range(1, n): 10 | for j in range(i): 11 | if pairs[i][0] > pairs[j][1]: 12 | dp[i] = max(dp[i], dp[j] + 1) 13 | 14 | return max(dp) -------------------------------------------------------------------------------- /442-find-all-duplicates-in-an-array/find-all-duplicates-in-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findDuplicates(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | duplicates = [] 8 | 9 | for num in nums: 10 | index = abs(num) 11 | if nums[index - 1] < 0: 12 | duplicates.append(index) 13 | else: 14 | 15 | nums[index - 1] *= -1 16 | 17 | return duplicates 18 | -------------------------------------------------------------------------------- /array/minimum-number-of-operations-to-make-array-empty.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def minOperations(self, nums): 5 | mp = Counter(nums) 6 | 7 | count = 0 8 | for t in mp.values(): 9 | if t == 1: 10 | return -1 11 | count += t // 3 12 | if t % 3: 13 | count += 1 14 | 15 | return count 16 | 17 | # Example usage: 18 | solution = Solution() 19 | nums = [1, 2, 2, 1, 1, 3] 20 | print(solution.minOperations(nums)) 21 | -------------------------------------------------------------------------------- /math/excel-sheet-column-title.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def convertToTitle(self, columnNumber): 3 | result = [] 4 | 5 | while columnNumber > 0: 6 | columnNumber -= 1 # Adjust to 0-based index 7 | remainder = columnNumber % 26 8 | result.append(chr(remainder + ord('A'))) 9 | columnNumber //= 26 10 | 11 | result.reverse() # Reverse the list to get the correct order 12 | return ''.join(result) 13 | 14 | # Test cases 15 | solution = Solution() 16 | -------------------------------------------------------------------------------- /sorting/maximum-length-of-pair-chain.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLongestChain(self,pairs): 3 | # Sort the pairs based on the right end in ascending order. 4 | pairs.sort(key=lambda x: x[1]) 5 | 6 | n = len(pairs) 7 | dp = [1] * n # Initialize the dp array with all 1s. 8 | 9 | for i in range(1, n): 10 | for j in range(i): 11 | if pairs[i][0] > pairs[j][1]: 12 | dp[i] = max(dp[i], dp[j] + 1) 13 | 14 | return max(dp) -------------------------------------------------------------------------------- /1756-minimum-deletions-to-make-string-balanced/minimum-deletions-to-make-string-balanced.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumDeletions(String s) { 3 | int n = s.length(); 4 | int[] f = new int[n + 1]; 5 | int b = 0; 6 | for (int i = 1; i <= n; ++i) { 7 | if (s.charAt(i - 1) == 'b') { 8 | f[i] = f[i - 1]; 9 | ++b; 10 | } else { 11 | f[i] = Math.min(f[i - 1] + 1, b); 12 | } 13 | } 14 | return f[n]; 15 | } 16 | } -------------------------------------------------------------------------------- /array/majority-element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def majorityElement(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | l = len(nums) 8 | 9 | candidate = nums[0] 10 | count=1 11 | for num in nums[1:]: 12 | if count == 0: 13 | candidate = num 14 | count = 1 15 | elif num == candidate: 16 | count += 1 17 | else: 18 | count -= 1 19 | 20 | return candidate -------------------------------------------------------------------------------- /counting/majority-element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def majorityElement(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | l = len(nums) 8 | 9 | candidate = nums[0] 10 | count=1 11 | for num in nums[1:]: 12 | if count == 0: 13 | candidate = num 14 | count = 1 15 | elif num == candidate: 16 | count += 1 17 | else: 18 | count -= 1 19 | 20 | return candidate -------------------------------------------------------------------------------- /counting/minimum-number-of-operations-to-make-array-empty.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def minOperations(self, nums): 5 | mp = Counter(nums) 6 | 7 | count = 0 8 | for t in mp.values(): 9 | if t == 1: 10 | return -1 11 | count += t // 3 12 | if t % 3: 13 | count += 1 14 | 15 | return count 16 | 17 | # Example usage: 18 | solution = Solution() 19 | nums = [1, 2, 2, 1, 1, 3] 20 | print(solution.minOperations(nums)) 21 | -------------------------------------------------------------------------------- /greedy/minimum-number-of-operations-to-make-array-empty.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def minOperations(self, nums): 5 | mp = Counter(nums) 6 | 7 | count = 0 8 | for t in mp.values(): 9 | if t == 1: 10 | return -1 11 | count += t // 3 12 | if t % 3: 13 | count += 1 14 | 15 | return count 16 | 17 | # Example usage: 18 | solution = Solution() 19 | nums = [1, 2, 2, 1, 1, 3] 20 | print(solution.minOperations(nums)) 21 | -------------------------------------------------------------------------------- /hash-table/minimum-number-of-operations-to-make-array-empty.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def minOperations(self, nums): 5 | mp = Counter(nums) 6 | 7 | count = 0 8 | for t in mp.values(): 9 | if t == 1: 10 | return -1 11 | count += t // 3 12 | if t % 3: 13 | count += 1 14 | 15 | return count 16 | 17 | # Example usage: 18 | solution = Solution() 19 | nums = [1, 2, 2, 1, 1, 3] 20 | print(solution.minOperations(nums)) 21 | -------------------------------------------------------------------------------- /sorting/majority-element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def majorityElement(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | l = len(nums) 8 | 9 | candidate = nums[0] 10 | count=1 11 | for num in nums[1:]: 12 | if count == 0: 13 | candidate = num 14 | count = 1 15 | elif num == candidate: 16 | count += 1 17 | else: 18 | count -= 1 19 | 20 | return candidate -------------------------------------------------------------------------------- /string/excel-sheet-column-title.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def convertToTitle(self, columnNumber): 3 | result = [] 4 | 5 | while columnNumber > 0: 6 | columnNumber -= 1 # Adjust to 0-based index 7 | remainder = columnNumber % 26 8 | result.append(chr(remainder + ord('A'))) 9 | columnNumber //= 26 10 | 11 | result.reverse() # Reverse the list to get the correct order 12 | return ''.join(result) 13 | 14 | # Test cases 15 | solution = Solution() 16 | -------------------------------------------------------------------------------- /1737-maximum-nesting-depth-of-the-parentheses/maximum-nesting-depth-of-the-parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxDepth(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | max_depth = 0 8 | current_depth = 0 9 | 10 | for char in s: 11 | if char == '(': 12 | current_depth += 1 13 | max_depth = max(max_depth, current_depth) 14 | elif char == ')': 15 | current_depth -= 1 16 | 17 | return max_depth 18 | -------------------------------------------------------------------------------- /array/largest-positive-integer-that-exists-with-its-negative.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | class Solution { 5 | public int findMaxK(int[] nums) { 6 | Set set = new HashSet<>(); 7 | int maxK = -1; 8 | 9 | for (int num : nums) { 10 | if (set.contains(-num)) { 11 | maxK = Math.max(maxK, Math.abs(num)); 12 | } else { 13 | set.add(num); 14 | } 15 | } 16 | 17 | return maxK; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /dynamic-programming/maximum-length-of-pair-chain.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLongestChain(self,pairs): 3 | # Sort the pairs based on the right end in ascending order. 4 | pairs.sort(key=lambda x: x[1]) 5 | 6 | n = len(pairs) 7 | dp = [1] * n # Initialize the dp array with all 1s. 8 | 9 | for i in range(1, n): 10 | for j in range(i): 11 | if pairs[i][0] > pairs[j][1]: 12 | dp[i] = max(dp[i], dp[j] + 1) 13 | 14 | return max(dp) -------------------------------------------------------------------------------- /hash-table/majority-element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def majorityElement(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | l = len(nums) 8 | 9 | candidate = nums[0] 10 | count=1 11 | for num in nums[1:]: 12 | if count == 0: 13 | candidate = num 14 | count = 1 15 | elif num == candidate: 16 | count += 1 17 | else: 18 | count -= 1 19 | 20 | return candidate -------------------------------------------------------------------------------- /2148-minimum-number-of-moves-to-seat-everyone/minimum-number-of-moves-to-seat-everyone.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int minMovesToSeat(int[] seats, int[] students) { 4 | Arrays.sort(seats); 5 | Arrays.sort(students); 6 | int moves = 0; 7 | for (int i = 0; i < seats.length; i++) { 8 | // Add the absolute value of the difference 9 | // between the position of the seat and the student 10 | moves += Math.abs(seats[i] - students[i]); 11 | } 12 | return moves; 13 | } 14 | } -------------------------------------------------------------------------------- /array/convert-1d-array-into-2d-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] construct2DArray(int[] original, int m, int n) { 3 | int len=original.length; 4 | if(len!=m*n) 5 | { 6 | return new int[0][0]; 7 | } 8 | 9 | int[][] twoD=new int[m][n]; 10 | int k=0; 11 | 12 | for(int i=0;i set = new HashSet<>(); 7 | int maxK = -1; 8 | 9 | for (int num : nums) { 10 | if (set.contains(-num)) { 11 | maxK = Math.max(maxK, Math.abs(num)); 12 | } else { 13 | set.add(num); 14 | } 15 | } 16 | 17 | return maxK; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /matrix/convert-1d-array-into-2d-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] construct2DArray(int[] original, int m, int n) { 3 | int len=original.length; 4 | if(len!=m*n) 5 | { 6 | return new int[0][0]; 7 | } 8 | 9 | int[][] twoD=new int[m][n]; 10 | int k=0; 11 | 12 | for(int i=0;i set = new HashSet<>(); 7 | int maxK = -1; 8 | 9 | for (int num : nums) { 10 | if (set.contains(-num)) { 11 | maxK = Math.max(maxK, Math.abs(num)); 12 | } else { 13 | set.add(num); 14 | } 15 | } 16 | 17 | return maxK; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /169-majority-element/majority-element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def majorityElement(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | l = len(nums) 8 | 9 | candidate = nums[0] 10 | count=1 11 | for num in nums[1:]: 12 | if count == 0: 13 | candidate = num 14 | count = 1 15 | elif num == candidate: 16 | count += 1 17 | else: 18 | count -= 1 19 | 20 | return candidate -------------------------------------------------------------------------------- /58-length-of-last-word/length-of-last-word.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lengthOfLastWord(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | # Remove trailing spaces from the string 8 | s = s.rstrip() 9 | # Split the string into words using spaces as delimiter 10 | words = s.split() 11 | # Check if there are any words in the string 12 | if len(words) == 0: 13 | return 0 14 | # Return the length of the last word 15 | return len(words[-1]) 16 | -------------------------------------------------------------------------------- /simulation/convert-1d-array-into-2d-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] construct2DArray(int[] original, int m, int n) { 3 | int len=original.length; 4 | if(len!=m*n) 5 | { 6 | return new int[0][0]; 7 | } 8 | 9 | int[][] twoD=new int[m][n]; 10 | int k=0; 11 | 12 | for(int i=0;i set = new HashSet<>(); 7 | int maxK = -1; 8 | 9 | for (int num : nums) { 10 | if (set.contains(-num)) { 11 | maxK = Math.max(maxK, Math.abs(num)); 12 | } else { 13 | set.add(num); 14 | } 15 | } 16 | 17 | return maxK; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /string/find-the-index-of-the-first-occurrence-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def strStr(self, haystack, needle): 3 | """ 4 | :type haystack: str 5 | :type needle: str 6 | :rtype: int 7 | """ 8 | if not needle: 9 | return 0 # If needle is an empty string, return 0. 10 | 11 | for i in range(len(haystack) - len(needle) + 1): 12 | if haystack[i:i + len(needle)] == needle: 13 | return i 14 | 15 | return -1 # If needle is not found in haystack, return -1. 16 | -------------------------------------------------------------------------------- /backtracking/generate-parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateParenthesis(self, n): 3 | def backtrack(s, left, right): 4 | if len(s) == 2 * n: 5 | result.append(s) 6 | return 7 | 8 | if left < n: 9 | backtrack(s + "(", left + 1, right) 10 | if right < left: 11 | backtrack(s + ")", left, right + 1) 12 | 13 | result = [] 14 | backtrack("", 0, 0) 15 | return result 16 | 17 | # Test cases 18 | solution = Solution() 19 | -------------------------------------------------------------------------------- /two-pointers/find-the-index-of-the-first-occurrence-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def strStr(self, haystack, needle): 3 | """ 4 | :type haystack: str 5 | :type needle: str 6 | :rtype: int 7 | """ 8 | if not needle: 9 | return 0 # If needle is an empty string, return 0. 10 | 11 | for i in range(len(haystack) - len(needle) + 1): 12 | if haystack[i:i + len(needle)] == needle: 13 | return i 14 | 15 | return -1 # If needle is not found in haystack, return -1. 16 | -------------------------------------------------------------------------------- /2024/jan-27.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kInversePairs(self, n: int, k: int) -> int: 3 | MOD = 10**9 + 7 4 | dp = [[0] * (k + 1) for _ in range(n + 1)] 5 | 6 | for i in range(1, n + 1): 7 | for j in range(k + 1): 8 | if j == 0: 9 | dp[i][j] = 1 10 | else: 11 | val = (dp[i - 1][j] + MOD - (dp[i - 1][j - i] if j - i >= 0 else 0)) % MOD 12 | dp[i][j] = (dp[i][j - 1] + val) % MOD 13 | 14 | return (dp[n][k] + MOD - (dp[n][k - 1] if k > 0 else 0)) % MOD -------------------------------------------------------------------------------- /array/sort-colors.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void sortColors(int[] nums) { 3 | int zeros = 0, ones = 0, n = nums.length; 4 | for(int num : nums) { 5 | if(num == 0) zeros++; 6 | else if(num == 1) ones++; 7 | } 8 | 9 | for(int i = 0; i < zeros; ++i) { 10 | nums[i] = 0; 11 | } 12 | 13 | for(int i = zeros; i < zeros + ones; ++i) { 14 | nums[i] = 1; 15 | } 16 | 17 | for(int i = zeros + ones; i < n; ++i) { 18 | nums[i] = 2; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /dynamic-programming/generate-parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateParenthesis(self, n): 3 | def backtrack(s, left, right): 4 | if len(s) == 2 * n: 5 | result.append(s) 6 | return 7 | 8 | if left < n: 9 | backtrack(s + "(", left + 1, right) 10 | if right < left: 11 | backtrack(s + ")", left, right + 1) 12 | 13 | result = [] 14 | backtrack("", 0, 0) 15 | return result 16 | 17 | # Test cases 18 | solution = Solution() 19 | -------------------------------------------------------------------------------- /math/water-bottles.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int numWaterBottles(int numBottles, int numExchange) { 4 | int consumedBottles = 0; 5 | 6 | while (numBottles >= numExchange) { 7 | // Consume numExchange full bottles. 8 | consumedBottles += numExchange; 9 | numBottles -= numExchange; 10 | 11 | // Exchange them for one full bottle. 12 | numBottles++; 13 | } 14 | 15 | // Consume the remaining numBottles (= 0 else 0) + current_max * j) 16 | 17 | return dp[-1] 18 | -------------------------------------------------------------------------------- /simulation/water-bottles.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int numWaterBottles(int numBottles, int numExchange) { 4 | int consumedBottles = 0; 5 | 6 | while (numBottles >= numExchange) { 7 | // Consume numExchange full bottles. 8 | consumedBottles += numExchange; 9 | numBottles -= numExchange; 10 | 11 | // Exchange them for one full bottle. 12 | numBottles++; 13 | } 14 | 15 | // Consume the remaining numBottles (= numExchange) { 7 | // Consume numExchange full bottles. 8 | consumedBottles += numExchange; 9 | numBottles -= numExchange; 10 | 11 | // Exchange them for one full bottle. 12 | numBottles++; 13 | } 14 | 15 | // Consume the remaining numBottles (= 0 else 0) + current_max * j) 16 | 17 | return dp[-1] 18 | -------------------------------------------------------------------------------- /graph/reconstruct-itinerary.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import heapq 3 | 4 | class Solution: 5 | def findItinerary(self, tickets: List[List[str]]) -> List[str]: 6 | ans = [] 7 | graph = collections.defaultdict(list) 8 | 9 | for a, b in tickets: 10 | graph[a].append(b) 11 | 12 | for u in graph: 13 | heapq.heapify(graph[u]) 14 | 15 | def dfs(u: str) -> None: 16 | while u in graph and graph[u]: 17 | dfs(heapq.heappop(graph[u])) 18 | ans.append(u) 19 | 20 | dfs('JFK') 21 | return ans[::-1] -------------------------------------------------------------------------------- /2524-largest-positive-integer-that-exists-with-its-negative/largest-positive-integer-that-exists-with-its-negative.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | class Solution { 5 | public int findMaxK(int[] nums) { 6 | Set set = new HashSet<>(); 7 | int maxK = -1; 8 | 9 | for (int num : nums) { 10 | if (set.contains(-num)) { 11 | maxK = Math.max(maxK, Math.abs(num)); 12 | } else { 13 | set.add(num); 14 | } 15 | } 16 | 17 | return maxK; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /array/boats-to-save-people.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int numRescueBoats(int[] people, int limit) { 5 | Arrays.sort(people); 6 | int boats = 0; 7 | int left = 0; 8 | int right = people.length - 1; 9 | 10 | while (left <= right) { 11 | if (people[left] + people[right] <= limit) { 12 | left++; 13 | right--; 14 | } else { 15 | right--; 16 | } 17 | boats++; 18 | } 19 | 20 | return boats; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /array/largest-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String largestNumber(int[] nums) { 3 | String[] array = new String[nums.length]; 4 | for(int i=0; i (b+a).compareTo(a+b)); 8 | if(array[0].equals("0")){ 9 | return "0"; 10 | } 11 | StringBuilder largest = new StringBuilder(); 12 | for(int i=0; i int: 3 | MOD = 10**9 + 7 4 | dp = [[0] * (k + 1) for _ in range(n + 1)] 5 | 6 | for i in range(1, n + 1): 7 | for j in range(k + 1): 8 | if j == 0: 9 | dp[i][j] = 1 10 | else: 11 | val = (dp[i - 1][j] + MOD - (dp[i - 1][j - i] if j - i >= 0 else 0)) % MOD 12 | dp[i][j] = (dp[i][j - 1] + val) % MOD 13 | 14 | return (dp[n][k] + MOD - (dp[n][k - 1] if k > 0 else 0)) % MOD -------------------------------------------------------------------------------- /greedy/boats-to-save-people.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int numRescueBoats(int[] people, int limit) { 5 | Arrays.sort(people); 6 | int boats = 0; 7 | int left = 0; 8 | int right = people.length - 1; 9 | 10 | while (left <= right) { 11 | if (people[left] + people[right] <= limit) { 12 | left++; 13 | right--; 14 | } else { 15 | right--; 16 | } 17 | boats++; 18 | } 19 | 20 | return boats; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /greedy/largest-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String largestNumber(int[] nums) { 3 | String[] array = new String[nums.length]; 4 | for(int i=0; i (b+a).compareTo(a+b)); 8 | if(array[0].equals("0")){ 9 | return "0"; 10 | } 11 | StringBuilder largest = new StringBuilder(); 12 | for(int i=0; i (b+a).compareTo(a+b)); 8 | if(array[0].equals("0")){ 9 | return "0"; 10 | } 11 | StringBuilder largest = new StringBuilder(); 12 | for(int i=0; i (b+a).compareTo(a+b)); 8 | if(array[0].equals("0")){ 9 | return "0"; 10 | } 11 | StringBuilder largest = new StringBuilder(); 12 | for(int i=0; i List[str]: 6 | ans = [] 7 | graph = collections.defaultdict(list) 8 | 9 | for a, b in tickets: 10 | graph[a].append(b) 11 | 12 | for u in graph: 13 | heapq.heapify(graph[u]) 14 | 15 | def dfs(u: str) -> None: 16 | while u in graph and graph[u]: 17 | dfs(heapq.heappop(graph[u])) 18 | ans.append(u) 19 | 20 | dfs('JFK') 21 | return ans[::-1] -------------------------------------------------------------------------------- /eulerian-circuit/reconstruct-itinerary.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import heapq 3 | 4 | class Solution: 5 | def findItinerary(self, tickets: List[List[str]]) -> List[str]: 6 | ans = [] 7 | graph = collections.defaultdict(list) 8 | 9 | for a, b in tickets: 10 | graph[a].append(b) 11 | 12 | for u in graph: 13 | heapq.heapify(graph[u]) 14 | 15 | def dfs(u: str) -> None: 16 | while u in graph and graph[u]: 17 | dfs(heapq.heappop(graph[u])) 18 | ans.append(u) 19 | 20 | dfs('JFK') 21 | return ans[::-1] -------------------------------------------------------------------------------- /sorting/boats-to-save-people.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int numRescueBoats(int[] people, int limit) { 5 | Arrays.sort(people); 6 | int boats = 0; 7 | int left = 0; 8 | int right = people.length - 1; 9 | 10 | while (left <= right) { 11 | if (people[left] + people[right] <= limit) { 12 | left++; 13 | right--; 14 | } else { 15 | right--; 16 | } 17 | boats++; 18 | } 19 | 20 | return boats; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /1121-partition-array-for-maximum-sum/partition-array-for-maximum-sum.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxSumAfterPartitioning(self, arr, k): 3 | """ 4 | :type arr: List[int] 5 | :type k: int 6 | :rtype: int 7 | """ 8 | n = len(arr) 9 | dp = [0] * n 10 | 11 | for i in range(n): 12 | current_max = 0 13 | for j in range(1, min(k, i + 1) + 1): 14 | current_max = max(current_max, arr[i - j + 1]) 15 | dp[i] = max(dp[i], (dp[i - j] if i - j >= 0 else 0) + current_max * j) 16 | 17 | return dp[-1] 18 | -------------------------------------------------------------------------------- /633-sum-of-square-numbers/sum-of-square-numbers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean judgeSquareSum(int c) { 3 | for (int divisor = 2; divisor * divisor <= c; divisor++) { 4 | if (c % divisor == 0) { 5 | int exponentCount = 0; 6 | while (c % divisor == 0) { 7 | exponentCount++; 8 | c /= divisor; 9 | } 10 | if (divisor % 4 == 3 && exponentCount % 2 != 0) { 11 | return false; 12 | } 13 | } 14 | } 15 | return c % 4 != 3; 16 | } 17 | } -------------------------------------------------------------------------------- /bit-manipulation/longest-subarray-with-maximum-bitwise-and.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestSubarray(int[] nums) { 3 | int maxVal = 0, ans = 0, currentStreak = 0; 4 | 5 | for (int num : nums) { 6 | if(maxVal < num) { 7 | maxVal = num; 8 | ans = currentStreak = 0; 9 | } 10 | if(maxVal == num){ 11 | currentStreak++; 12 | } else { 13 | currentStreak = 0; 14 | } 15 | ans = Math.max(ans, currentStreak); 16 | } 17 | return ans; 18 | } 19 | } -------------------------------------------------------------------------------- /bit-manipulation/score-after-flipping-matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int matrixScore(int[][] grid) { 3 | int n = grid.length, m = grid[0].length; 4 | int res = (1 << (m - 1)) * n; 5 | 6 | for (int j = 1; j < m; ++j) { 7 | int val = 1 << (m - 1 - j); 8 | int set = 0; 9 | 10 | for (int i = 0; i < n; ++i) { 11 | if (grid[i][j] == grid[i][0]) { 12 | set++; 13 | } 14 | } 15 | 16 | res += Math.max(set, n - set) * val; 17 | } 18 | 19 | return res; 20 | } 21 | } -------------------------------------------------------------------------------- /graph/maximum-total-importance-of-roads.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long maximumImportance(int n, int[][] roads) { 3 | int[] br = new int[n]; 4 | for(int[] r : roads){ 5 | br[r[0]]++; 6 | br[r[1]]++; 7 | } 8 | int[] cnt = new int[n]; 9 | for(int b : br){ 10 | cnt[b]++; 11 | } 12 | long sum = 0; 13 | long val = 1; 14 | for(long i = 0; i < n; i++){ 15 | for(int j = 0; j < cnt[(int)i]; j++){ 16 | sum += i*val++; 17 | } 18 | } 19 | return sum; 20 | } 21 | } -------------------------------------------------------------------------------- /greedy/maximum-total-importance-of-roads.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long maximumImportance(int n, int[][] roads) { 3 | int[] br = new int[n]; 4 | for(int[] r : roads){ 5 | br[r[0]]++; 6 | br[r[1]]++; 7 | } 8 | int[] cnt = new int[n]; 9 | for(int b : br){ 10 | cnt[b]++; 11 | } 12 | long sum = 0; 13 | long val = 1; 14 | for(long i = 0; i < n; i++){ 15 | for(int j = 0; j < cnt[(int)i]; j++){ 16 | sum += i*val++; 17 | } 18 | } 19 | return sum; 20 | } 21 | } -------------------------------------------------------------------------------- /string/determine-if-string-halves-are-alike.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def halvesAreAlike(self, s): 3 | def count_vowels(string): 4 | vowels = set('aeiouAEIOU') 5 | return sum(1 for char in string if char in vowels) 6 | 7 | n = len(s) 8 | mid = n // 2 9 | first_half = s[:mid] 10 | second_half = s[mid:] 11 | 12 | return count_vowels(first_half) == count_vowels(second_half) 13 | 14 | # Example usage: 15 | solution = Solution() 16 | print(solution.halvesAreAlike("book")) # Output: True 17 | print(solution.halvesAreAlike("textbook")) # Output: False 18 | -------------------------------------------------------------------------------- /two-pointers/boats-to-save-people.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int numRescueBoats(int[] people, int limit) { 5 | Arrays.sort(people); 6 | int boats = 0; 7 | int left = 0; 8 | int right = people.length - 1; 9 | 10 | while (left <= right) { 11 | if (people[left] + people[right] <= limit) { 12 | left++; 13 | right--; 14 | } else { 15 | right--; 16 | } 17 | boats++; 18 | } 19 | 20 | return boats; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /3241-divide-array-into-arrays-with-max-difference/divide-array-into-arrays-with-max-difference.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def divideArray(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: List[List[int]] 7 | """ 8 | n = len(nums) 9 | nums.sort() 10 | 11 | result = [] 12 | 13 | for i in range(0, n, 3): 14 | if i + 2 < n and nums[i + 2] - nums[i] <= k: 15 | result.append([nums[i], nums[i + 1], nums[i + 2]]) 16 | else: 17 | return [] 18 | 19 | return result 20 | -------------------------------------------------------------------------------- /counting/determine-if-string-halves-are-alike.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def halvesAreAlike(self, s): 3 | def count_vowels(string): 4 | vowels = set('aeiouAEIOU') 5 | return sum(1 for char in string if char in vowels) 6 | 7 | n = len(s) 8 | mid = n // 2 9 | first_half = s[:mid] 10 | second_half = s[mid:] 11 | 12 | return count_vowels(first_half) == count_vowels(second_half) 13 | 14 | # Example usage: 15 | solution = Solution() 16 | print(solution.halvesAreAlike("book")) # Output: True 17 | print(solution.halvesAreAlike("textbook")) # Output: False 18 | -------------------------------------------------------------------------------- /sorting/maximum-total-importance-of-roads.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long maximumImportance(int n, int[][] roads) { 3 | int[] br = new int[n]; 4 | for(int[] r : roads){ 5 | br[r[0]]++; 6 | br[r[1]]++; 7 | } 8 | int[] cnt = new int[n]; 9 | for(int b : br){ 10 | cnt[b]++; 11 | } 12 | long sum = 0; 13 | long val = 1; 14 | for(long i = 0; i < n; i++){ 15 | for(int j = 0; j < cnt[(int)i]; j++){ 16 | sum += i*val++; 17 | } 18 | } 19 | return sum; 20 | } 21 | } -------------------------------------------------------------------------------- /string/sum-of-digits-of-string-after-convert.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int getLucky(String s, int k) { 3 | StringBuilder number = new StringBuilder(); 4 | for (char x : s.toCharArray()) { 5 | number.append(x - 'a' + 1); 6 | } 7 | 8 | while (k > 0) { 9 | int temp = 0; 10 | for (char x : number.toString().toCharArray()) { 11 | temp += x - '0'; 12 | } 13 | number = new StringBuilder(String.valueOf(temp)); 14 | k--; 15 | } 16 | return Integer.parseInt(number.toString()); 17 | } 18 | } -------------------------------------------------------------------------------- /917-boats-to-save-people/boats-to-save-people.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int numRescueBoats(int[] people, int limit) { 5 | Arrays.sort(people); 6 | int boats = 0; 7 | int left = 0; 8 | int right = people.length - 1; 9 | 10 | while (left <= right) { 11 | if (people[left] + people[right] <= limit) { 12 | left++; 13 | right--; 14 | } else { 15 | right--; 16 | } 17 | boats++; 18 | } 19 | 20 | return boats; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /simulation/sum-of-digits-of-string-after-convert.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int getLucky(String s, int k) { 3 | StringBuilder number = new StringBuilder(); 4 | for (char x : s.toCharArray()) { 5 | number.append(x - 'a' + 1); 6 | } 7 | 8 | while (k > 0) { 9 | int temp = 0; 10 | for (char x : number.toString().toCharArray()) { 11 | temp += x - '0'; 12 | } 13 | number = new StringBuilder(String.valueOf(temp)); 14 | k--; 15 | } 16 | return Integer.parseInt(number.toString()); 17 | } 18 | } -------------------------------------------------------------------------------- /string/reverse-words-in-a-string-iii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseWords(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | words = s.split() # Split the sentence into words 8 | reversed_words = [word[::-1] for word in words] # Reverse each word 9 | return ' '.join(reversed_words) # Join the reversed words with whitespace 10 | 11 | # Test cases 12 | solution = Solution() 13 | print(solution.reverseWords("Let's take LeetCode contest")) # Output: "s'teL ekat edoCteeL tsetnoc" 14 | print(solution.reverseWords("God Ding")) # Output: "doG gniD" 15 | -------------------------------------------------------------------------------- /206-reverse-linked-list/reverse-linked-list.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseList(self, head): 3 | """ 4 | :type head: ListNode 5 | :rtype: ListNode 6 | """ 7 | # Initialize prev and current pointers 8 | prev = None 9 | current = head 10 | 11 | # Traverse the list and reverse pointers 12 | while current: 13 | next_node = current.next 14 | current.next = prev 15 | prev = current 16 | current = next_node 17 | 18 | # Return the new head of the reversed list 19 | return prev 20 | -------------------------------------------------------------------------------- /891-score-after-flipping-matrix/score-after-flipping-matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int matrixScore(int[][] grid) { 3 | int n = grid.length, m = grid[0].length; 4 | int res = (1 << (m - 1)) * n; 5 | 6 | for (int j = 1; j < m; ++j) { 7 | int val = 1 << (m - 1 - j); 8 | int set = 0; 9 | 10 | for (int i = 0; i < n; ++i) { 11 | if (grid[i][j] == grid[i][0]) { 12 | set++; 13 | } 14 | } 15 | 16 | res += Math.max(set, n - set) * val; 17 | } 18 | 19 | return res; 20 | } 21 | } -------------------------------------------------------------------------------- /heap-priority-queue/maximum-total-importance-of-roads.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long maximumImportance(int n, int[][] roads) { 3 | int[] br = new int[n]; 4 | for(int[] r : roads){ 5 | br[r[0]]++; 6 | br[r[1]]++; 7 | } 8 | int[] cnt = new int[n]; 9 | for(int b : br){ 10 | cnt[b]++; 11 | } 12 | long sum = 0; 13 | long val = 1; 14 | for(long i = 0; i < n; i++){ 15 | for(int j = 0; j < cnt[(int)i]; j++){ 16 | sum += i*val++; 17 | } 18 | } 19 | return sum; 20 | } 21 | } -------------------------------------------------------------------------------- /two-pointers/reverse-words-in-a-string-iii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseWords(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | words = s.split() # Split the sentence into words 8 | reversed_words = [word[::-1] for word in words] # Reverse each word 9 | return ' '.join(reversed_words) # Join the reversed words with whitespace 10 | 11 | # Test cases 12 | solution = Solution() 13 | print(solution.reverseWords("Let's take LeetCode contest")) # Output: "s'teL ekat edoCteeL tsetnoc" 14 | print(solution.reverseWords("God Ding")) # Output: "doG gniD" 15 | -------------------------------------------------------------------------------- /array/check-if-array-pairs-are-divisible-by-k.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canArrange(int[] arr, int k) { 3 | int[] mp = new int[k]; 4 | 5 | for (int num : arr) { 6 | int rem = (num % k + k) % k; 7 | mp[rem]++; 8 | } 9 | 10 | if (mp[0] % 2 != 0) { 11 | return false; 12 | } 13 | 14 | for (int rem = 1; rem <= k / 2; rem++) { 15 | int counterHalf = k - rem; 16 | if (mp[counterHalf] != mp[rem]) { 17 | return false; 18 | } 19 | } 20 | 21 | return true; 22 | } 23 | } -------------------------------------------------------------------------------- /array/container-with-most-water.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxArea(self, height): 3 | """ 4 | :type height: List[int] 5 | :rtype: int 6 | """ 7 | max_area = 0 8 | left = 0 9 | right = len(height) - 1 10 | 11 | while left < right: 12 | h = min(height[left], height[right]) 13 | w = right - left 14 | area = h * w 15 | max_area = max(max_area, area) 16 | 17 | if height[left] < height[right]: 18 | left += 1 19 | else: 20 | right -= 1 21 | 22 | return max_area 23 | -------------------------------------------------------------------------------- /counting/check-if-array-pairs-are-divisible-by-k.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canArrange(int[] arr, int k) { 3 | int[] mp = new int[k]; 4 | 5 | for (int num : arr) { 6 | int rem = (num % k + k) % k; 7 | mp[rem]++; 8 | } 9 | 10 | if (mp[0] % 2 != 0) { 11 | return false; 12 | } 13 | 14 | for (int rem = 1; rem <= k / 2; rem++) { 15 | int counterHalf = k - rem; 16 | if (mp[counterHalf] != mp[rem]) { 17 | return false; 18 | } 19 | } 20 | 21 | return true; 22 | } 23 | } -------------------------------------------------------------------------------- /math/unique-paths.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def uniquePaths(self, m, n): 3 | """ 4 | :type m: int 5 | :type n: int 6 | :rtype: int 7 | """ 8 | # Create a 2D array dp to store the number of unique paths 9 | dp = [[1] * n for _ in range(m)] 10 | 11 | # Fill in the dp array using dynamic programming 12 | for i in range(1, m): 13 | for j in range(1, n): 14 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1] 15 | 16 | # The value at dp[m-1][n-1] will be the number of unique paths 17 | return dp[m - 1][n - 1] 18 | 19 | -------------------------------------------------------------------------------- /string/minimum-penalty-for-a-shop.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bestClosingTime(self, customers: str) -> int: 3 | n, cntN, cntY = len(customers), 0, 0 4 | prefixN, suffixY = [0], [0] 5 | 6 | for c in customers: 7 | cntN += (c == 'N') 8 | prefixN.append(cntN) 9 | 10 | for c in reversed(customers): 11 | cntY += (c == 'Y') 12 | suffixY.append(cntY) 13 | 14 | suffixY.reverse() 15 | 16 | best_hour, _ = min(enumerate(a + b for a, b in zip(prefixN, suffixY)), key=lambda x: x[1]) 17 | 18 | return best_hour -------------------------------------------------------------------------------- /3213-count-subarrays-where-max-element-appears-at-least-k-times/count-subarrays-where-max-element-appears-at-least-k-times.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countSubarrays(self, nums, k): 3 | count = 0 4 | left = 0 5 | max_freq = 0 6 | max_element = max(nums) 7 | for right in range(len(nums)): 8 | if nums[right] == max_element: 9 | max_freq += 1 10 | while max_freq >= k: 11 | count += len(nums) - right 12 | if nums[left] == max_element: 13 | max_freq -= 1 14 | left += 1 15 | return count 16 | -------------------------------------------------------------------------------- /greedy/container-with-most-water.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxArea(self, height): 3 | """ 4 | :type height: List[int] 5 | :rtype: int 6 | """ 7 | max_area = 0 8 | left = 0 9 | right = len(height) - 1 10 | 11 | while left < right: 12 | h = min(height[left], height[right]) 13 | w = right - left 14 | area = h * w 15 | max_area = max(max_area, area) 16 | 17 | if height[left] < height[right]: 18 | left += 1 19 | else: 20 | right -= 1 21 | 22 | return max_area 23 | -------------------------------------------------------------------------------- /hash-table/check-if-array-pairs-are-divisible-by-k.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canArrange(int[] arr, int k) { 3 | int[] mp = new int[k]; 4 | 5 | for (int num : arr) { 6 | int rem = (num % k + k) % k; 7 | mp[rem]++; 8 | } 9 | 10 | if (mp[0] % 2 != 0) { 11 | return false; 12 | } 13 | 14 | for (int rem = 1; rem <= k / 2; rem++) { 15 | int counterHalf = k - rem; 16 | if (mp[counterHalf] != mp[rem]) { 17 | return false; 18 | } 19 | } 20 | 21 | return true; 22 | } 23 | } -------------------------------------------------------------------------------- /prefix-sum/minimum-penalty-for-a-shop.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bestClosingTime(self, customers: str) -> int: 3 | n, cntN, cntY = len(customers), 0, 0 4 | prefixN, suffixY = [0], [0] 5 | 6 | for c in customers: 7 | cntN += (c == 'N') 8 | prefixN.append(cntN) 9 | 10 | for c in reversed(customers): 11 | cntY += (c == 'Y') 12 | suffixY.append(cntY) 13 | 14 | suffixY.reverse() 15 | 16 | best_hour, _ = min(enumerate(a + b for a, b in zip(prefixN, suffixY)), key=lambda x: x[1]) 17 | 18 | return best_hour -------------------------------------------------------------------------------- /array/range-sum-of-sorted-subarray-sums.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rangeSum(int[] nums, int n, int left, int right) { 3 | int[] arr = new int[n * (n + 1) / 2]; 4 | for (int i = 0, k = 0; i < n; ++i) { 5 | int s = 0; 6 | for (int j = i; j < n; ++j) { 7 | s += nums[j]; 8 | arr[k++] = s; 9 | } 10 | } 11 | Arrays.sort(arr); 12 | int ans = 0; 13 | final int mod = (int) 1e9 + 7; 14 | for (int i = left - 1; i < right; ++i) { 15 | ans = (ans + arr[i]) % mod; 16 | } 17 | return ans; 18 | } 19 | } -------------------------------------------------------------------------------- /array/remove-element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeElement(self, nums, val): 3 | """ 4 | :type nums: List[int] 5 | :type val: int 6 | :rtype: int 7 | """ 8 | k = 0 # Initialize the pointer for the new length of the modified array 9 | 10 | for i in range(len(nums)): 11 | if nums[i] != val: 12 | nums[k] = nums[i] # Replace the element to be removed with the new element 13 | k += 1 14 | 15 | return k # k represents the new length of the modified array 16 | 17 | # Example usage 18 | solution = Solution() 19 | 20 | -------------------------------------------------------------------------------- /combinatorics/unique-paths.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def uniquePaths(self, m, n): 3 | """ 4 | :type m: int 5 | :type n: int 6 | :rtype: int 7 | """ 8 | # Create a 2D array dp to store the number of unique paths 9 | dp = [[1] * n for _ in range(m)] 10 | 11 | # Fill in the dp array using dynamic programming 12 | for i in range(1, m): 13 | for j in range(1, n): 14 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1] 15 | 16 | # The value at dp[m-1][n-1] will be the number of unique paths 17 | return dp[m - 1][n - 1] 18 | 19 | -------------------------------------------------------------------------------- /sorting/range-sum-of-sorted-subarray-sums.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rangeSum(int[] nums, int n, int left, int right) { 3 | int[] arr = new int[n * (n + 1) / 2]; 4 | for (int i = 0, k = 0; i < n; ++i) { 5 | int s = 0; 6 | for (int j = i; j < n; ++j) { 7 | s += nums[j]; 8 | arr[k++] = s; 9 | } 10 | } 11 | Arrays.sort(arr); 12 | int ans = 0; 13 | final int mod = (int) 1e9 + 7; 14 | for (int i = left - 1; i < right; ++i) { 15 | ans = (ans + arr[i]) % mod; 16 | } 17 | return ans; 18 | } 19 | } -------------------------------------------------------------------------------- /two-pointers/container-with-most-water.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxArea(self, height): 3 | """ 4 | :type height: List[int] 5 | :rtype: int 6 | """ 7 | max_area = 0 8 | left = 0 9 | right = len(height) - 1 10 | 11 | while left < right: 12 | h = min(height[left], height[right]) 13 | w = right - left 14 | area = h * w 15 | max_area = max(max_area, area) 16 | 17 | if height[left] < height[right]: 18 | left += 1 19 | else: 20 | right -= 1 21 | 22 | return max_area 23 | -------------------------------------------------------------------------------- /2024/jan-22.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findErrorNums(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | n = len(nums) 8 | expected_sum = n * (n + 1) // 2 9 | actual_sum = sum(set(nums)) 10 | 11 | duplicated_number = sum(nums) - actual_sum 12 | missing_number = expected_sum - actual_sum 13 | 14 | return [duplicated_number, missing_number] 15 | 16 | # Example usage: 17 | solution = Solution() 18 | print(solution.findErrorNums([1, 2, 2, 4])) # Output: [2, 3] 19 | print(solution.findErrorNums([1, 1])) # Output: [1, 2] 20 | -------------------------------------------------------------------------------- /2379-maximum-total-importance-of-roads/maximum-total-importance-of-roads.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long maximumImportance(int n, int[][] roads) { 3 | int[] br = new int[n]; 4 | for(int[] r : roads){ 5 | br[r[0]]++; 6 | br[r[1]]++; 7 | } 8 | int[] cnt = new int[n]; 9 | for(int b : br){ 10 | cnt[b]++; 11 | } 12 | long sum = 0; 13 | long val = 1; 14 | for(long i = 0; i < n; i++){ 15 | for(int j = 0; j < cnt[(int)i]; j++){ 16 | sum += i*val++; 17 | } 18 | } 19 | return sum; 20 | } 21 | } -------------------------------------------------------------------------------- /array/reveal-cards-in-increasing-order.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int[] deckRevealedIncreasing(int[] deck) { 4 | Arrays.sort(deck); 5 | Deque dq = new LinkedList<>(); 6 | int n = deck.length; 7 | dq.offerFirst(deck[n - 1]); 8 | for (int i = n - 2; i >= 0; i--) { 9 | int x = dq.pollLast(); 10 | dq.offerFirst(x); 11 | dq.offerFirst(deck[i]); 12 | } 13 | 14 | int[] ans = new int[n]; 15 | int index = 0; 16 | while (!dq.isEmpty()) { 17 | ans[index++] = dq.pollFirst(); 18 | } 19 | return ans; 20 | } 21 | } -------------------------------------------------------------------------------- /binary-search/range-sum-of-sorted-subarray-sums.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rangeSum(int[] nums, int n, int left, int right) { 3 | int[] arr = new int[n * (n + 1) / 2]; 4 | for (int i = 0, k = 0; i < n; ++i) { 5 | int s = 0; 6 | for (int j = i; j < n; ++j) { 7 | s += nums[j]; 8 | arr[k++] = s; 9 | } 10 | } 11 | Arrays.sort(arr); 12 | int ans = 0; 13 | final int mod = (int) 1e9 + 7; 14 | for (int i = left - 1; i < right; ++i) { 15 | ans = (ans + arr[i]) % mod; 16 | } 17 | return ans; 18 | } 19 | } -------------------------------------------------------------------------------- /dynamic-programming/unique-paths.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def uniquePaths(self, m, n): 3 | """ 4 | :type m: int 5 | :type n: int 6 | :rtype: int 7 | """ 8 | # Create a 2D array dp to store the number of unique paths 9 | dp = [[1] * n for _ in range(m)] 10 | 11 | # Fill in the dp array using dynamic programming 12 | for i in range(1, m): 13 | for j in range(1, n): 14 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1] 15 | 16 | # The value at dp[m-1][n-1] will be the number of unique paths 17 | return dp[m - 1][n - 1] 18 | 19 | -------------------------------------------------------------------------------- /queue/reveal-cards-in-increasing-order.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int[] deckRevealedIncreasing(int[] deck) { 4 | Arrays.sort(deck); 5 | Deque dq = new LinkedList<>(); 6 | int n = deck.length; 7 | dq.offerFirst(deck[n - 1]); 8 | for (int i = n - 2; i >= 0; i--) { 9 | int x = dq.pollLast(); 10 | dq.offerFirst(x); 11 | dq.offerFirst(deck[i]); 12 | } 13 | 14 | int[] ans = new int[n]; 15 | int index = 0; 16 | while (!dq.isEmpty()) { 17 | ans[index++] = dq.pollFirst(); 18 | } 19 | return ans; 20 | } 21 | } -------------------------------------------------------------------------------- /sorting/sort-characters-by-frequency.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution(object): 4 | def frequencySort(self, s): 5 | """ 6 | :type s: str 7 | :rtype: str 8 | """ 9 | # Count the frequency of each character 10 | char_freq = Counter(s) 11 | 12 | # Sort the characters based on their frequency in descending order 13 | sorted_chars = sorted(char_freq, key=lambda x: char_freq[x], reverse=True) 14 | 15 | # Build the sorted string 16 | result = ''.join(char * char_freq[char] for char in sorted_chars) 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /string/sort-characters-by-frequency.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution(object): 4 | def frequencySort(self, s): 5 | """ 6 | :type s: str 7 | :rtype: str 8 | """ 9 | # Count the frequency of each character 10 | char_freq = Counter(s) 11 | 12 | # Sort the characters based on their frequency in descending order 13 | sorted_chars = sorted(char_freq, key=lambda x: char_freq[x], reverse=True) 14 | 15 | # Build the sorted string 16 | result = ''.join(char * char_freq[char] for char in sorted_chars) 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /two-pointers/range-sum-of-sorted-subarray-sums.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rangeSum(int[] nums, int n, int left, int right) { 3 | int[] arr = new int[n * (n + 1) / 2]; 4 | for (int i = 0, k = 0; i < n; ++i) { 5 | int s = 0; 6 | for (int j = i; j < n; ++j) { 7 | s += nums[j]; 8 | arr[k++] = s; 9 | } 10 | } 11 | Arrays.sort(arr); 12 | int ans = 0; 13 | final int mod = (int) 1e9 + 7; 14 | for (int i = left - 1; i < right; ++i) { 15 | ans = (ans + arr[i]) % mod; 16 | } 17 | return ans; 18 | } 19 | } -------------------------------------------------------------------------------- /two-pointers/remove-element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeElement(self, nums, val): 3 | """ 4 | :type nums: List[int] 5 | :type val: int 6 | :rtype: int 7 | """ 8 | k = 0 # Initialize the pointer for the new length of the modified array 9 | 10 | for i in range(len(nums)): 11 | if nums[i] != val: 12 | nums[k] = nums[i] # Replace the element to be removed with the new element 13 | k += 1 14 | 15 | return k # k represents the new length of the modified array 16 | 17 | # Example usage 18 | solution = Solution() 19 | 20 | -------------------------------------------------------------------------------- /3225-length-of-longest-subarray-with-at-most-k-frequency/length-of-longest-subarray-with-at-most-k-frequency.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxSubarrayLength(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: int 7 | """ 8 | n, left, result = len(nums), 0, 0 9 | freq = defaultdict(int) 10 | 11 | for right in range(n): 12 | freq[nums[right]] += 1 13 | while freq[nums[right]] > k: 14 | freq[nums[left]] -= 1 15 | left += 1 16 | result = max(result, right - left + 1) 17 | return result -------------------------------------------------------------------------------- /array/count-triplets-that-can-form-two-arrays-of-equal-xor.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countTriplets(int[] arr) { 3 | int n = arr.length; 4 | int[] prefixXor = new int[n + 1]; 5 | 6 | for (int i = 0; i < n; i++) { 7 | prefixXor[i + 1] = prefixXor[i] ^ arr[i]; 8 | } 9 | 10 | int count = 0; 11 | for (int k = 0; k < n; k++) { 12 | for (int i = 0; i < k; i++) { 13 | if (prefixXor[i] == prefixXor[k + 1]) { 14 | count += (k - i); 15 | } 16 | } 17 | } 18 | return count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /array/set-mismatch.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findErrorNums(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | n = len(nums) 8 | expected_sum = n * (n + 1) // 2 9 | actual_sum = sum(set(nums)) 10 | 11 | duplicated_number = sum(nums) - actual_sum 12 | missing_number = expected_sum - actual_sum 13 | 14 | return [duplicated_number, missing_number] 15 | 16 | # Example usage: 17 | solution = Solution() 18 | print(solution.findErrorNums([1, 2, 2, 4])) # Output: [2, 3] 19 | print(solution.findErrorNums([1, 1])) # Output: [1, 2] 20 | -------------------------------------------------------------------------------- /array/subsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> subsets(int[] nums) { 3 | List> res = new ArrayList<>(); 4 | List op = new ArrayList<>(); 5 | solve(nums, 0, op, res); 6 | return res; 7 | } 8 | public void solve(int nums[], int start, List op, List> res){ 9 | if(nums.length == start){ 10 | res.add(new ArrayList<>(op)); 11 | return; 12 | } 13 | solve(nums, start + 1, op, res); 14 | op.add(nums[start]); 15 | solve(nums, start + 1, op, res); 16 | op.remove(op.size() - 1); 17 | } 18 | } -------------------------------------------------------------------------------- /bucket-sort/sort-characters-by-frequency.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution(object): 4 | def frequencySort(self, s): 5 | """ 6 | :type s: str 7 | :rtype: str 8 | """ 9 | # Count the frequency of each character 10 | char_freq = Counter(s) 11 | 12 | # Sort the characters based on their frequency in descending order 13 | sorted_chars = sorted(char_freq, key=lambda x: char_freq[x], reverse=True) 14 | 15 | # Build the sorted string 16 | result = ''.join(char * char_freq[char] for char in sorted_chars) 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /counting/sort-characters-by-frequency.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution(object): 4 | def frequencySort(self, s): 5 | """ 6 | :type s: str 7 | :rtype: str 8 | """ 9 | # Count the frequency of each character 10 | char_freq = Counter(s) 11 | 12 | # Sort the characters based on their frequency in descending order 13 | sorted_chars = sorted(char_freq, key=lambda x: char_freq[x], reverse=True) 14 | 15 | # Build the sorted string 16 | result = ''.join(char * char_freq[char] for char in sorted_chars) 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /hash-table/sort-characters-by-frequency.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution(object): 4 | def frequencySort(self, s): 5 | """ 6 | :type s: str 7 | :rtype: str 8 | """ 9 | # Count the frequency of each character 10 | char_freq = Counter(s) 11 | 12 | # Sort the characters based on their frequency in descending order 13 | sorted_chars = sorted(char_freq, key=lambda x: char_freq[x], reverse=True) 14 | 15 | # Build the sorted string 16 | result = ''.join(char * char_freq[char] for char in sorted_chars) 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /math/count-triplets-that-can-form-two-arrays-of-equal-xor.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countTriplets(int[] arr) { 3 | int n = arr.length; 4 | int[] prefixXor = new int[n + 1]; 5 | 6 | for (int i = 0; i < n; i++) { 7 | prefixXor[i + 1] = prefixXor[i] ^ arr[i]; 8 | } 9 | 10 | int count = 0; 11 | for (int k = 0; k < n; k++) { 12 | for (int i = 0; i < k; i++) { 13 | if (prefixXor[i] == prefixXor[k + 1]) { 14 | count += (k - i); 15 | } 16 | } 17 | } 18 | return count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /simulation/reveal-cards-in-increasing-order.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int[] deckRevealedIncreasing(int[] deck) { 4 | Arrays.sort(deck); 5 | Deque dq = new LinkedList<>(); 6 | int n = deck.length; 7 | dq.offerFirst(deck[n - 1]); 8 | for (int i = n - 2; i >= 0; i--) { 9 | int x = dq.pollLast(); 10 | dq.offerFirst(x); 11 | dq.offerFirst(deck[i]); 12 | } 13 | 14 | int[] ans = new int[n]; 15 | int index = 0; 16 | while (!dq.isEmpty()) { 17 | ans[index++] = dq.pollFirst(); 18 | } 19 | return ans; 20 | } 21 | } -------------------------------------------------------------------------------- /sorting/reveal-cards-in-increasing-order.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int[] deckRevealedIncreasing(int[] deck) { 4 | Arrays.sort(deck); 5 | Deque dq = new LinkedList<>(); 6 | int n = deck.length; 7 | dq.offerFirst(deck[n - 1]); 8 | for (int i = n - 2; i >= 0; i--) { 9 | int x = dq.pollLast(); 10 | dq.offerFirst(x); 11 | dq.offerFirst(deck[i]); 12 | } 13 | 14 | int[] ans = new int[n]; 15 | int index = 0; 16 | while (!dq.isEmpty()) { 17 | ans[index++] = dq.pollFirst(); 18 | } 19 | return ans; 20 | } 21 | } -------------------------------------------------------------------------------- /78-subsets/subsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> subsets(int[] nums) { 3 | List> res = new ArrayList<>(); 4 | List op = new ArrayList<>(); 5 | solve(nums, 0, op, res); 6 | return res; 7 | } 8 | public void solve(int nums[], int start, List op, List> res){ 9 | if(nums.length == start){ 10 | res.add(new ArrayList<>(op)); 11 | return; 12 | } 13 | solve(nums, start + 1, op, res); 14 | op.add(nums[start]); 15 | solve(nums, start + 1, op, res); 16 | op.remove(op.size() - 1); 17 | } 18 | } -------------------------------------------------------------------------------- /array/maximum-width-ramp.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxWidthRamp(int[] nums) { 3 | int n = nums.length; 4 | Stack stack = new Stack<>(); 5 | for (int i = 0; i < n; ++i) { 6 | if (stack.isEmpty() || nums[stack.peek()] > nums[i]) { 7 | stack.push(i); 8 | } 9 | } 10 | 11 | int maxWidth = 0; 12 | for (int j = n - 1; j >= 0; --j) { 13 | while (!stack.isEmpty() && nums[stack.peek()] <= nums[j]) { 14 | maxWidth = Math.max(maxWidth, j - stack.pop()); 15 | } 16 | } 17 | return maxWidth; 18 | } 19 | } -------------------------------------------------------------------------------- /backtracking/subsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> subsets(int[] nums) { 3 | List> res = new ArrayList<>(); 4 | List op = new ArrayList<>(); 5 | solve(nums, 0, op, res); 6 | return res; 7 | } 8 | public void solve(int nums[], int start, List op, List> res){ 9 | if(nums.length == start){ 10 | res.add(new ArrayList<>(op)); 11 | return; 12 | } 13 | solve(nums, start + 1, op, res); 14 | op.add(nums[start]); 15 | solve(nums, start + 1, op, res); 16 | op.remove(op.size() - 1); 17 | } 18 | } -------------------------------------------------------------------------------- /hash-table/count-triplets-that-can-form-two-arrays-of-equal-xor.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countTriplets(int[] arr) { 3 | int n = arr.length; 4 | int[] prefixXor = new int[n + 1]; 5 | 6 | for (int i = 0; i < n; i++) { 7 | prefixXor[i + 1] = prefixXor[i] ^ arr[i]; 8 | } 9 | 10 | int count = 0; 11 | for (int k = 0; k < n; k++) { 12 | for (int i = 0; i < k; i++) { 13 | if (prefixXor[i] == prefixXor[k + 1]) { 14 | count += (k - i); 15 | } 16 | } 17 | } 18 | return count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /hash-table/set-mismatch.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findErrorNums(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | n = len(nums) 8 | expected_sum = n * (n + 1) // 2 9 | actual_sum = sum(set(nums)) 10 | 11 | duplicated_number = sum(nums) - actual_sum 12 | missing_number = expected_sum - actual_sum 13 | 14 | return [duplicated_number, missing_number] 15 | 16 | # Example usage: 17 | solution = Solution() 18 | print(solution.findErrorNums([1, 2, 2, 4])) # Output: [2, 3] 19 | print(solution.findErrorNums([1, 1])) # Output: [1, 2] 20 | -------------------------------------------------------------------------------- /math/perfect-squares.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numSquares(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | # Create an array to store the least number of perfect squares that sum to each number 8 | dp = [float('inf')] * (n + 1) 9 | dp[0] = 0 10 | 11 | # Iterate through each number from 1 to n 12 | for i in range(1, n + 1): 13 | # Check all perfect squares less than or equal to i 14 | j = 1 15 | while j * j <= i: 16 | dp[i] = min(dp[i], dp[i - j * j] + 1) 17 | j += 1 18 | 19 | return dp[n] 20 | -------------------------------------------------------------------------------- /prefix-sum/count-triplets-that-can-form-two-arrays-of-equal-xor.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countTriplets(int[] arr) { 3 | int n = arr.length; 4 | int[] prefixXor = new int[n + 1]; 5 | 6 | for (int i = 0; i < n; i++) { 7 | prefixXor[i + 1] = prefixXor[i] ^ arr[i]; 8 | } 9 | 10 | int count = 0; 11 | for (int k = 0; k < n; k++) { 12 | for (int i = 0; i < k; i++) { 13 | if (prefixXor[i] == prefixXor[k + 1]) { 14 | count += (k - i); 15 | } 16 | } 17 | } 18 | return count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /recursion/merge-two-sorted-lists.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | class Solution: 7 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 8 | dummy = ListNode(0) 9 | curr = dummy 10 | 11 | while l1 and l2: 12 | if l1.val <= l2.val: 13 | curr.next = l1 14 | l1 = l1.next 15 | else: 16 | curr.next = l2 17 | l2 = l2.next 18 | curr = curr.next 19 | 20 | curr.next = l1 if l1 else l2 21 | return dummy.next 22 | -------------------------------------------------------------------------------- /sorting/set-mismatch.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findErrorNums(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | n = len(nums) 8 | expected_sum = n * (n + 1) // 2 9 | actual_sum = sum(set(nums)) 10 | 11 | duplicated_number = sum(nums) - actual_sum 12 | missing_number = expected_sum - actual_sum 13 | 14 | return [duplicated_number, missing_number] 15 | 16 | # Example usage: 17 | solution = Solution() 18 | print(solution.findErrorNums([1, 2, 2, 4])) # Output: [2, 3] 19 | print(solution.findErrorNums([1, 1])) # Output: [1, 2] 20 | -------------------------------------------------------------------------------- /stack/maximum-width-ramp.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxWidthRamp(int[] nums) { 3 | int n = nums.length; 4 | Stack stack = new Stack<>(); 5 | for (int i = 0; i < n; ++i) { 6 | if (stack.isEmpty() || nums[stack.peek()] > nums[i]) { 7 | stack.push(i); 8 | } 9 | } 10 | 11 | int maxWidth = 0; 12 | for (int j = n - 1; j >= 0; --j) { 13 | while (!stack.isEmpty() && nums[stack.peek()] <= nums[j]) { 14 | maxWidth = Math.max(maxWidth, j - stack.pop()); 15 | } 16 | } 17 | return maxWidth; 18 | } 19 | } -------------------------------------------------------------------------------- /array/count-the-number-of-consistent-strings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countConsistentStrings(String allowed, String[] words) { 3 | Set set=new HashSet<>(); 4 | for(int i=0;i& nums) { 4 | int numsSize = nums.size(); 5 | 6 | // If the array has 4 or fewer elements, return 0 7 | if (numsSize <= 4) return 0; 8 | 9 | sort(nums.begin(), nums.end()); 10 | 11 | int minDiff = INT_MAX; 12 | 13 | // Four scenarios to compute the minimum difference 14 | for (int left = 0, right = numsSize - 4; left < 4; left++, right++) { 15 | minDiff = min(minDiff, nums[right] - nums[left]); 16 | } 17 | 18 | return minDiff; 19 | } 20 | }; -------------------------------------------------------------------------------- /bit-manipulation/count-triplets-that-can-form-two-arrays-of-equal-xor.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countTriplets(int[] arr) { 3 | int n = arr.length; 4 | int[] prefixXor = new int[n + 1]; 5 | 6 | for (int i = 0; i < n; i++) { 7 | prefixXor[i + 1] = prefixXor[i] ^ arr[i]; 8 | } 9 | 10 | int count = 0; 11 | for (int k = 0; k < n; k++) { 12 | for (int i = 0; i < k; i++) { 13 | if (prefixXor[i] == prefixXor[k + 1]) { 14 | count += (k - i); 15 | } 16 | } 17 | } 18 | return count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /bit-manipulation/subsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> subsets(int[] nums) { 3 | List> res = new ArrayList<>(); 4 | List op = new ArrayList<>(); 5 | solve(nums, 0, op, res); 6 | return res; 7 | } 8 | public void solve(int nums[], int start, List op, List> res){ 9 | if(nums.length == start){ 10 | res.add(new ArrayList<>(op)); 11 | return; 12 | } 13 | solve(nums, start + 1, op, res); 14 | op.add(nums[start]); 15 | solve(nums, start + 1, op, res); 16 | op.remove(op.size() - 1); 17 | } 18 | } -------------------------------------------------------------------------------- /counting/count-the-number-of-consistent-strings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countConsistentStrings(String allowed, String[] words) { 3 | Set set=new HashSet<>(); 4 | for(int i=0;i& nums) { 4 | int numsSize = nums.size(); 5 | 6 | // If the array has 4 or fewer elements, return 0 7 | if (numsSize <= 4) return 0; 8 | 9 | sort(nums.begin(), nums.end()); 10 | 11 | int minDiff = INT_MAX; 12 | 13 | // Four scenarios to compute the minimum difference 14 | for (int left = 0, right = numsSize - 4; left < 4; left++, right++) { 15 | minDiff = min(minDiff, nums[right] - nums[left]); 16 | } 17 | 18 | return minDiff; 19 | } 20 | }; -------------------------------------------------------------------------------- /heap-priority-queue/sort-characters-by-frequency.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution(object): 4 | def frequencySort(self, s): 5 | """ 6 | :type s: str 7 | :rtype: str 8 | """ 9 | # Count the frequency of each character 10 | char_freq = Counter(s) 11 | 12 | # Sort the characters based on their frequency in descending order 13 | sorted_chars = sorted(char_freq, key=lambda x: char_freq[x], reverse=True) 14 | 15 | # Build the sorted string 16 | result = ''.join(char * char_freq[char] for char in sorted_chars) 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /linked-list/merge-two-sorted-lists.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | class Solution: 7 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 8 | dummy = ListNode(0) 9 | curr = dummy 10 | 11 | while l1 and l2: 12 | if l1.val <= l2.val: 13 | curr.next = l1 14 | l1 = l1.next 15 | else: 16 | curr.next = l2 17 | l2 = l2.next 18 | curr = curr.next 19 | 20 | curr.next = l1 if l1 else l2 21 | return dummy.next 22 | -------------------------------------------------------------------------------- /sorting/minimum-difference-between-largest-and-smallest-value-in-three-moves.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDifference(vector& nums) { 4 | int numsSize = nums.size(); 5 | 6 | // If the array has 4 or fewer elements, return 0 7 | if (numsSize <= 4) return 0; 8 | 9 | sort(nums.begin(), nums.end()); 10 | 11 | int minDiff = INT_MAX; 12 | 13 | // Four scenarios to compute the minimum difference 14 | for (int left = 0, right = numsSize - 4; left < 4; left++, right++) { 15 | minDiff = min(minDiff, nums[right] - nums[left]); 16 | } 17 | 18 | return minDiff; 19 | } 20 | }; -------------------------------------------------------------------------------- /string/count-the-number-of-consistent-strings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countConsistentStrings(String allowed, String[] words) { 3 | Set set=new HashSet<>(); 4 | for(int i=0;i= k: 18 | product /= nums[left] 19 | left += 1 20 | count += right - left + 1 21 | 22 | return count 23 | -------------------------------------------------------------------------------- /array/continuous-subarray-sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean checkSubarraySum(int[] nums, int k) { 3 | int n = nums.length, prefSum = 0; 4 | Map firstOcc = new HashMap<>(); 5 | firstOcc.put(0, 0); 6 | 7 | for (int i = 0; i < n; i++) { 8 | prefSum = (prefSum + nums[i]) % k; 9 | if (firstOcc.containsKey(prefSum)) { 10 | if (i + 1 - firstOcc.get(prefSum) >= 2) { 11 | return true; 12 | } 13 | } else { 14 | firstOcc.put(prefSum, i + 1); 15 | } 16 | } 17 | 18 | return false; 19 | } 20 | } -------------------------------------------------------------------------------- /bit-manipulation/set-mismatch.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findErrorNums(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | n = len(nums) 8 | expected_sum = n * (n + 1) // 2 9 | actual_sum = sum(set(nums)) 10 | 11 | duplicated_number = sum(nums) - actual_sum 12 | missing_number = expected_sum - actual_sum 13 | 14 | return [duplicated_number, missing_number] 15 | 16 | # Example usage: 17 | solution = Solution() 18 | print(solution.findErrorNums([1, 2, 2, 4])) # Output: [2, 3] 19 | print(solution.findErrorNums([1, 1])) # Output: [1, 2] 20 | -------------------------------------------------------------------------------- /hash-table/count-the-number-of-consistent-strings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countConsistentStrings(String allowed, String[] words) { 3 | Set set=new HashSet<>(); 4 | for(int i=0;i firstOcc = new HashMap<>(); 5 | firstOcc.put(0, 0); 6 | 7 | for (int i = 0; i < n; i++) { 8 | prefSum = (prefSum + nums[i]) % k; 9 | if (firstOcc.containsKey(prefSum)) { 10 | if (i + 1 - firstOcc.get(prefSum) >= 2) { 11 | return true; 12 | } 13 | } else { 14 | firstOcc.put(prefSum, i + 1); 15 | } 16 | } 17 | 18 | return false; 19 | } 20 | } -------------------------------------------------------------------------------- /monotonic-stack/maximum-width-ramp.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxWidthRamp(int[] nums) { 3 | int n = nums.length; 4 | Stack stack = new Stack<>(); 5 | for (int i = 0; i < n; ++i) { 6 | if (stack.isEmpty() || nums[stack.peek()] > nums[i]) { 7 | stack.push(i); 8 | } 9 | } 10 | 11 | int maxWidth = 0; 12 | for (int j = n - 1; j >= 0; --j) { 13 | while (!stack.isEmpty() && nums[stack.peek()] <= nums[j]) { 14 | maxWidth = Math.max(maxWidth, j - stack.pop()); 15 | } 16 | } 17 | return maxWidth; 18 | } 19 | } -------------------------------------------------------------------------------- /string/get-equal-substrings-within-budget.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int equalSubstring(String s, String t, int maxCost) { 3 | int start = 0; 4 | int currentCost = 0; 5 | int maxLength = 0; 6 | 7 | for (int end = 0; end < s.length(); end++) { 8 | currentCost += Math.abs(s.charAt(end) - t.charAt(end)); 9 | 10 | while (currentCost > maxCost) { 11 | currentCost -= Math.abs(s.charAt(start) - t.charAt(start)); 12 | start++; 13 | } 14 | 15 | maxLength = Math.max(maxLength, end - start + 1); 16 | } 17 | 18 | return maxLength; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /279-perfect-squares/perfect-squares.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numSquares(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | # Create an array to store the least number of perfect squares that sum to each number 8 | dp = [float('inf')] * (n + 1) 9 | dp[0] = 0 10 | 11 | # Iterate through each number from 1 to n 12 | for i in range(1, n + 1): 13 | # Check all perfect squares less than or equal to i 14 | j = 1 15 | while j * j <= i: 16 | dp[i] = min(dp[i], dp[i - j * j] + 1) 17 | j += 1 18 | 19 | return dp[n] 20 | -------------------------------------------------------------------------------- /451-sort-characters-by-frequency/sort-characters-by-frequency.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution(object): 4 | def frequencySort(self, s): 5 | """ 6 | :type s: str 7 | :rtype: str 8 | """ 9 | # Count the frequency of each character 10 | char_freq = Counter(s) 11 | 12 | # Sort the characters based on their frequency in descending order 13 | sorted_chars = sorted(char_freq, key=lambda x: char_freq[x], reverse=True) 14 | 15 | # Build the sorted string 16 | result = ''.join(char * char_freq[char] for char in sorted_chars) 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /bit-manipulation/count-the-number-of-consistent-strings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countConsistentStrings(String allowed, String[] words) { 3 | Set set=new HashSet<>(); 4 | for(int i=0;i