├── .gitignore ├── ruby ├── 0136-single-number.rb ├── 1929-concatenation-of-array.rb ├── 0179-largest-number.rb ├── 0217-contains-duplicate.rb ├── 0190-reverse-bits.rb ├── 0001-two-sum.rb ├── 0100-same-tree.rb ├── 0104-maximum-depth-of-binary-tree.rb ├── 0049-group-anagrams.rb ├── 0226-invert-binary-tree.rb ├── 0053-maximum-subarray.rb ├── 1299-replace-elements-with-greatest-element-on-right-side.rb ├── 0198-house-robber.rb ├── 0121-best-time-to-buy-and-sell-stock.rb ├── 0338-counting-bits.rb ├── 0134-gas-station.rb ├── 0045-jump-game-ii.rb ├── 0191-number-of-1-bits.rb ├── 0046-permutations.rb ├── 0703-kth-largest-element-in-a-stream.rb ├── 0020-valid-parentheses.rb ├── 0133-clone-graph.rb ├── 0235-lowest-common-ancestor-of-a-binary-search-tree.rb ├── 0268-missing-number.rb ├── 0167-two-sum-ii-input-array-is-sorted.rb ├── 1046-Last-Stone-Weight.rb ├── 1046-last-stone-weight.rb ├── 0110-balanced-binary-tree.rb ├── 0007-reverse-integer.rb ├── 0202-happy-number.rb ├── 0242-valid-anagram.rb ├── 1899-merge-triplets-to-form-target-triplet.rb ├── 0128-longest-consecutive-sequence.rb ├── 0543-diameter-of-binary-tree.rb └── 0050-powx-n.rb ├── go ├── 0912-sort-an-array.go ├── 0215-kth-largest-element-in-an-array.go ├── 0136-single-number.go ├── 0191-number-of-1-bits.go ├── 0344-reverse-string.go ├── 0283-move-zeroes.go ├── 0371-sum-of-two-integers.go ├── 0268-missing-number.go ├── 0070-climbing-stairs.go ├── 0190-reverse-bits.go ├── 0062-unique-paths.go ├── 0263-ugly-number.go ├── 0009-palindrome-number.go ├── 0055-jump-game.go ├── 0058-Length-of-Last-Word.go ├── 0058-length-of-last-word.go ├── 0169-majority-element.go ├── 0001-two-sum.go ├── 0219-contains-duplicate-ii.go ├── 0100-same-tree.go ├── 0104-maximum-depth-of-binary-tree.go ├── 0122-best-time-to-buy-and-sell-stock-ii.go ├── 1220-count-vowels-permutation.go ├── 0338-counting-bits.go ├── 0658-find-k-closest-elements.go ├── 0027-remove-element.go ├── 0026-remove-duplicates-from-sorted-array.go ├── 0367-valid-perfect-square.go ├── 0392-is-subsequence.go ├── 0121-best-time-to-buy-and-sell-stock.go ├── 0066-plus-one.go ├── 0217-contains-duplicate.go ├── 0560-subarray-sum-equals-k.go ├── 0187-repeated-dna-sequences.go ├── 1512-number-of-good-pairs.go ├── 1929-concatenation-of-array.go ├── 1963-minimum-number-of-swaps-to-make-the-string-balanced.go ├── 0179-largest-number.go ├── 0881-boats-to-save-people.go ├── 0007-reverse-integer.go ├── 0035-search-insert-position.go ├── 0198-house-robber.go ├── 0605-can-place-flowers.go ├── 0852-peak-index-in-a-mountain-array.go ├── 0189-rotate-array.go ├── 0075-sort-colors.go ├── 0045-jump-game-ii.go ├── 0238-product-of-array-except-self.go ├── 0926-flip-string-to-monotone-increasing.go ├── 1968-array-with-elements-not-equal-to-average-of-neighbors.go ├── 0287-find-the-duplicate-number.go ├── 0647-palindromic-substrings.go ├── 0014-longest-common-prefix.go ├── 0141-linked-list-cycle.go ├── 0203-remove-linked-list-elements.go ├── 0704-binary-search.go ├── 1822-sign-of-the-product-of-an-array.go ├── 0128-longest-consecutive-sequence.go ├── 0724-find-pivot-index.go ├── 0226-invert-binary-tree.go ├── 0013-roman-to-integer.go ├── 1029-two-city-scheduling.go ├── 0665-non-decreasing-array.go ├── 0374-guess-number-higher-or-lower.go └── 0300-longest-increasing-subsequence.go ├── python ├── 2235-add-two-integers.py ├── 0459-repeated-substring-pattern.py ├── 0136-single-number.py ├── 0191-number-of-1-bits.py ├── 1461-check-if-a-string-contains-all-binary-codes-of-size-k.py ├── 0268-missing-number.py ├── 1523-count-odd-numbers-in-an-interval-range.py ├── 0190-reverse-bits.py ├── 1929-concatenation-of-array.py ├── 0125-valid-palindrome.py ├── 0746-min-cost-climbing-stairs.py ├── 0055-jump-game.py ├── 0263-ugly-number.py ├── 0198-house-robber.py ├── 0392-is-subsequence.py ├── 0217-contains-duplicate.py ├── 0274-H-index.py ├── 0280-wiggle-sort.py ├── 0014-longest-common-prefix.py ├── 2405-optimal-partition-of-string.py ├── 0070-climbing-stairs.py ├── 0122-best-time-to-buy-and-sell-stock-ii.py ├── 0169-majority-element.py ├── 0278-first-bad-version.py ├── 0026-remove-duplicates-from-sorted-array.py ├── 0053-maximum-subarray.py ├── 1930-unique-length-3-palindromic-subsequences.py ├── 1985-find-the-kth-largest-integer-in-the-array.py ├── 1822-sign-of-the-product-of-an-array.py ├── 0001-two-sum.py ├── 0083-remove-duplicates-from-sorted-list.py ├── 0120-triangle.py ├── 0344-reverse-string.py ├── 0349-intersection-of-two-arrays.py ├── 1299-replace-elements-with-greatest-element-on-right-side.py ├── 0121-best-time-to-buy-and-sell-stock.py ├── 0442-find-all-duplicates-in-an-array.py ├── 0509-fibonacci-number.py ├── 0876-middle-of-the-linked-list.py ├── 1845-seat-reservation-manager.py ├── 0069-sqrtx.py ├── 0058-length-of-last-word.py ├── 0300-longest-increasing-subsequence.py ├── 2017-grid-game.py ├── 0062-unique-paths.py ├── 0724-find-pivot-index.py ├── 0205-isomorphic-strings.py ├── 0997-find-the-town-judge.py ├── 2390-removing-stars-from-a-string.py ├── 1800-maximum-ascending-subarray-sum.py ├── 1984-minimum-difference-between-highest-and-lowest-of-k-scores.py ├── 0213-house-robber-ii.py ├── 0448-find-all-numbers-disappeared-in-an-array.py ├── 0045-jump-game-ii.py ├── 0901-online-stock-span.py ├── 0946-validate-stack-sequences.py ├── 1189-maximum-number-of-balloons.py ├── 1464-maximum-product-of-two-elements-in-an-array.py ├── 0322-coin-change.py ├── 0441-arranging-coins.py ├── 0881-boats-to-save-people.py ├── 1750-minimum-length-of-string-after-deleting-similar-ends.py ├── 0050-powx-n.py ├── 0238-product-of-array-except-self.py ├── 0896-monotonic-array.py ├── 1423-maximum-points-you-can-obtain-from-cards.py ├── 0013-roman-to-integer.py ├── 0168-excel-sheet-column-title.py ├── 0383-ransom-note.py └── 0187-repeated-dna-sequences.py ├── cpp ├── 0231-power-of-two.cpp ├── 2235-add-two-integers.cpp ├── 0263-ugly-number.cpp ├── 1213-maximum-product-difference-between-two-pairs.cpp ├── 0026-remove-duplicates-from-sorted-array.cpp ├── 0344-Reverse-String.cpp ├── 0344-reverse-string.cpp ├── 1470-shuffle-the-array.cpp ├── 0280-wiggle-sort.cpp ├── 1920-build-array-from-permutation.cpp ├── 0283-move-zeroes.cpp ├── 0027-remove-element.cpp ├── 1985-Find-The-Kth-Largest-Integer-In-The-Array.cpp └── 1985-find-the-kth-largest-integer-in-the-array.cpp ├── scala ├── 0485-max-consecutive-ones.scala ├── 0179-largest-number.scala ├── 0070-climbing-stairs.scala ├── 0217-contains-duplicate.scala ├── 0058-length-of-last-word.scala ├── 1929-concatenation-of-array.scala ├── 0125-valid-palindrome.scala ├── 0167-two-sum-ii-input-array-is-sorted.scala └── 0198-house-robber.scala ├── .idea ├── codeStyles │ └── codeStyleConfig.xml ├── vcs.xml ├── .gitignore ├── misc.xml └── modules.xml ├── dart ├── 0058-length-of-last-word.dart ├── 0028-find-the-index-of-the-first-occurrence-in-a-string.dart ├── 0746-min-cost-climbing-stairs.dart ├── 0070-climbing-stairs.dart ├── 0392-is-subsequence.dart ├── 0344-reverse-string.dart ├── 0226-invert-binary-tree.dart ├── 1299-replace-elements-with-greatest-element-on-right-side.dart ├── 0217-contains-duplicate.dart ├── 0169-majority-element.dart ├── 0001-two-sum.dart └── 0014-longest-common-prefix.dart ├── javascript ├── 0263-ugly-number.js ├── 2235-add-two-integers.js ├── 1822-sign-of-the-product-of-an-array.js ├── 2769-find-the-maximum-achievable-number.js ├── 2667-create-hello-world-function.js ├── 2626-array-reduce-transformation.js ├── 2634-filter-elements-from-array.js ├── 0136-single-number.js ├── 1863-sum-of-all-subset-xor-totals.js ├── 0179-largest-number.js ├── 2620-counter.js ├── 2635-apply-transform-over-each-element-in-array.js ├── 2621-sleep.js ├── 2390-removing-stars-from-a-string.js ├── 0374-guess-number-higher-or-lower.js ├── 1929-concatenation-of-array.js ├── 1588-sum-of-all-odd-length-subarrays.js ├── 2629-function-composition.js ├── 0926-flip-string-to-monotone-increasing.js ├── 1029-two-city-scheduling.js ├── 0371-sum-of-two-integers.js ├── 1512-number-of-good-pairs.js ├── 0338-counting-bits.js ├── 1768-merge-strings-alternately.js ├── 0268-missing-number.js ├── 1137-n-th-tribonacci-number.js └── 2439-minimize-maximum-of-array.js ├── package.json ├── c ├── 0136-single-number.c ├── 0371-sum-of-two-integers.c ├── 0268-missing-number.c ├── 0190-reverse-bits.c ├── 1822-sign-of-the-product-of-an-array.c ├── 0055-jump-game.c ├── 0191-number-of-1-bits.c ├── 0026-remove-duplicates-from-sorted-array.c ├── 0070-climbing-stairs.c ├── 0746-min-cost-climbing-stairs.c ├── 0027-remove-element.c ├── 0058-length-of-last-word.c ├── 0242-valid-anagram.c ├── 0283-move-zeroes.c ├── 0069-sqrtx.c ├── 0344-reverse-string.c ├── 1470-shuffle-the-array.c ├── 0162-find-peak-element.c ├── 0287-find-the-duplicate-number.c ├── 1137-n-th-tribonacci-number.c ├── 0367-valid-perfect-square.c └── 0080-remove-duplicates-from-sorted-array-ii.c ├── java ├── 0342-power-of-four.java ├── 2220-minimum-bit-flips-to-convert-number.java ├── 0104-maximum-depth-of-binary-tree.java ├── 1464-maximum-product-of-two-elements-in-an-array.java ├── 0338-counting-bits.java ├── 0371-sum-of-two-integers.java ├── 1822-sign-of-the-product-of-an-array.java ├── 0263-ugly-number.java ├── 0343-integer-break.java ├── 1929-concatenation-of-array.java ├── 0201-bitwise-and-of-numbers-range.java ├── 0268-missing-number.java ├── 1846-maximum-element-after-decreasing-and-rearranging.java ├── 0055-jump-game.java ├── 0226-invert-binary-tree.java ├── 0700-search-in-a-binary-search-tree.java ├── 0169-majority-element.java ├── 1461-check-if-a-string-contains-all-binary-codes-of-size-k.java ├── 2348-number-of-zero-filled-subarrays.java ├── 2433-find-the-original-array-of-prefix-xor.java ├── 0190-reverse-bits.java ├── 0344-reverse-string.java ├── 1572-matrix-diagonal-sum.java ├── 0058-length-of-last-word.java ├── 0026-remove-duplicates-from-sorted-array.java ├── 1903-largest-odd-number-in-string.java ├── 2971-find-polygon-with-the-largest-perimeter.java ├── 0876-middle-of-the-linked-list.java ├── 0901-online-stock-span.java ├── 1299-Replace-Elements-With-Greatest-Element-On-Right-Side.java ├── 1299-replace-elements-with-greatest-element-on-right-side.java ├── 2486-append-characters-to-string-to-make-subsequence.java ├── 0136-single-number.java ├── 0217-contains-duplicate.java ├── 0746-min-cost-climbing-stairs.java ├── 0896-monotonic-array.java ├── 1611-minimum-one-bit-operations-to-make-integers-zero.java ├── 0045-jump-game-ii.java ├── 0442-find-all-duplicates-in-an-array.java ├── 0705-design-hashset.java ├── 2544-alternating-digit-sum ├── 1029-two-city-scheduling.java ├── 2405-optimal-partition-of-string.java ├── 0283-move-zeroes.java ├── 1359-count-all-valid-pickup-and-delivery-options.java └── 1603-design-parking-system.java ├── typescript ├── 0066-plus-one.ts ├── 2469-convert-the-temperature.ts ├── 0136-single-number.ts ├── 2667-create-hello-world-function.ts ├── 1929-concatenation-of-array.ts ├── 1822-sign-of-the-product-of-an-array.ts ├── 0070-climbing-stairs.ts ├── 2620-counter.ts ├── 0055-jump-game.ts ├── 0268-missing-number.ts ├── 0344-reverse-string.ts ├── 0190-reverse-bits.ts ├── 0198-house-robber.ts ├── 0263-ugly-number.ts ├── 0058-length-of-last-word.ts ├── 0217-contains-duplicate.ts ├── 0746-min-cost-climbing-stairs.ts ├── 0876-middle-of-the-linked-list.ts ├── 0191-number-of-1-bits.ts ├── 0027-remove-element.ts ├── 0371-sum-of-two-integers.ts ├── 0392-is-subsequence.ts ├── 0026-remove-duplicates-from-sorted-array.ts ├── 1029-two-city-scheduling.ts ├── 0053-maximum-subarray.ts ├── 0001-two-sum.ts ├── 0926-flip-string-to-monotone-increasing.ts ├── 2390-removing-stars-from-a-string.ts ├── 0724-find-pivot-index.ts ├── 1137-n-th-tribonacci-number.ts ├── 1299-Replace-Elements-With-Greatest-Element-On-Right-Side.ts ├── 1299-replace-elements-with-greatest-element-on-right-side.ts ├── 0050-powx-n.ts ├── 0929-unique-email-addresses.ts ├── 0009-palindrome-number.ts ├── 0014-longest-common-prefix.ts ├── 0518-coin-change-ii.ts ├── 0062-unique-paths.ts ├── 0230-kth-smallest-element-in-a-bst.ts ├── 0118-pascals-triangle.ts ├── 0283-move-zeroes.ts └── 0187-repeated-dna-sequences.ts ├── rust ├── 0136-single-number.rs ├── 0190-reverse-bits.rs ├── 0035-search-insert-position.rs ├── 0055-jump-game.rs ├── 0191-number-of-1-bits.rs ├── 0198-house-robber.rs ├── 0070-climbing-stairs.rs ├── 0268-missing-number.rs ├── 0344-reverse-string.rs ├── 0283-move-zeroes.rs ├── 1480-running-sum-of-1d-array.rs ├── 0371-sum-of-two-integers.rs ├── 1929-concatenation-of-array.rs ├── 0206-reverse-linked-list.rs ├── 0053-maximum-subarray.rs ├── 0202-happy-number.rs ├── 1299-Replace-Elements-With-Greatest-Element-On-Right-Side.rs ├── 1299-replace-elements-with-greatest-element-on-right-side.rs ├── 0179-largest-number.rs ├── 0746-min-cost-climbing-stairs.rs ├── 2114-maximum-number-of-words-found-in-sentences.rs ├── 0263-ugly-number.rs ├── 0926-flip-string-to-monotone-increasing.rs ├── 1137-n-th-tribonacci-number.rs ├── 0026-remove-duplicates-from-sorted-array.rs └── 0048-rotate-image.rs ├── swift ├── 0104-maximum-depth-of-binary-tree.swift ├── 0179-largest-number.swift ├── 0268-missing-number.swift ├── 0191-number-of-1-bits.swift ├── 0190-reverse-bits.swift ├── 0100-same-tree.swift ├── 0198-house-robber.swift ├── 1929-concatenation-of-array.swift ├── 0027-Remove-Element.swift ├── 0027-remove-element.swift ├── 0509-fibonacci-number.swift ├── 0055-jump-game.swift ├── 0263-ugly-number.swift ├── 0283-Move-Zeroes.Swift ├── 0283-move-zeroes.swift ├── 0746-min-cost-climbing-stairs.swift ├── 0070-climbing-stairs.swift ├── 0371-sum-of-two-integers.swift ├── 0053-maximum-subarray.swift ├── 0058-Length-of-Last-Word.swift ├── 0058-length-of-last-word.swift ├── 0026-Remove-Duplicates-from-Sorted-Array.swift ├── 0026-remove-duplicates-from-sorted-array.swift ├── 0094-binary-tree-inorder-traversal.swift └── 0344-reverse-string.swift ├── kotlin ├── 0217-contains-duplicate.kt ├── 0136-single-number.kt ├── 0746-min-cost-climbing-stairs.kt ├── 0268-missing-number.kt ├── 0263-ugly-number.kt ├── 0122-best-time-to-buy-and-sell-stock-ii.kt ├── 0179-largest-number.kt ├── 0053-maximum-subarray.kt ├── 0168-excel-sheet-column-title.kt ├── 1845-seat-reservation-manager.kt ├── 0027-remove-element.kt ├── 0058-length-of-last-word.kt ├── 1822-sign-of-the-product-of-an-array.kt ├── 0242-valid-anagram.kt ├── 1984-minimum-difference-between-highest-and-lowest-of-k-scores.kt ├── 0371-sum-of-two-integers.kt ├── 0392-is-subsequence.kt ├── 1637-widest-vertical-area-between-two-points-containing-no-points.kt ├── 0066-plus-one.kt ├── 0070-climbing-stairs.kt ├── 0120-triangle.kt ├── 1603-design-parking-system.kt ├── 0009-palindrome-number.kt ├── 0338-counting-bits.kt ├── 0349-intersection-of-two-arrays.kt ├── 1572-matrix-diagonal-sum.kt ├── 0121-best-time-to-buy-and-sell-stock.kt ├── 0387-first-unique-character-in-a-string.kt ├── 0896-monotonic-array.kt ├── 0724-find-pivot-index.kt ├── 0191-number-of-1-bits.kt ├── 0442-find-all-duplicates-in-an-array.kt ├── 1071-greatest-common-divisor-of-strings.kt ├── 0901-online-stock-span.kt ├── 1299-replace-elements-with-greatest-element-on-right-side.kt ├── 0026-remove-duplicates-from-sorted-array.kt ├── 0283-move-zeroes.kt ├── 0342-power-of-four.kt ├── 0926-flip-string-to-monotone-increasing.kt ├── 1688-count-of-matches-in-tournament.kt ├── 0455-assign-cookies.kt ├── 0867-transpose-matrix.kt ├── 0997-find-the-town-judge.kt ├── 1523-count-odd-numbers-in-an-interval-range.kt ├── 2390-removing-stars-from-a-string.kt ├── 2405-optimal-partition-of-string.kt ├── 2439-minimize-maximum-of-array.kt └── 2870-minimum-number-of-operations-to-make-array-empty.kt ├── csharp ├── 0136-single-number.cs ├── 0371-sum-of-two-integers.cs ├── 1480-running-sum-of-1d-array.cs ├── 0190-reverse-bits.cs ├── 0268-missing-number.cs ├── 0929-unique-email-addresses.cs ├── 0179-largest-number.cs ├── 0217-contains-duplicate.cs ├── 0191-number-of-1-bits.cs ├── 0198-house-robber.cs ├── 1299-Replace-Elements-With-Greatest-Element-On-Right-Side.cs ├── 1299-replace-elements-with-greatest-element-on-right-side.cs ├── 0070-climbing-stairs.cs ├── 1929-concatenation-of-array.cs ├── 0026-remove-duplicates-from-sorted-array.cs ├── 0066-plus-one.cs ├── 0169-majority-element.cs ├── 0055-jump-game.cs ├── 0303-range-sum-query-immutable.cs ├── 0617-merge-two-binary-trees.cs └── 1603-design-parking-system.cs └── articles └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .metals 3 | .vscode 4 | .idea 5 | node_modules -------------------------------------------------------------------------------- /ruby/0136-single-number.rb: -------------------------------------------------------------------------------- 1 | def single_number(nums) 2 | nums.inject { |accu, num| accu ^ num } 3 | end 4 | -------------------------------------------------------------------------------- /go/0912-sort-an-array.go: -------------------------------------------------------------------------------- 1 | func sortArray(nums []int) []int { 2 | sort.Ints(nums) 3 | return nums 4 | } 5 | -------------------------------------------------------------------------------- /python/2235-add-two-integers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sum(self, num1: int, num2: int) -> int: 3 | return num1 + num2 4 | -------------------------------------------------------------------------------- /go/0215-kth-largest-element-in-an-array.go: -------------------------------------------------------------------------------- 1 | func findKthLargest(nums []int, k int) int { 2 | sort.Ints(nums) 3 | return nums[len(nums)-k] 4 | } -------------------------------------------------------------------------------- /cpp/0231-power-of-two.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | return n > 0 && !(n & (n - 1)); 5 | } 6 | }; -------------------------------------------------------------------------------- /ruby/1929-concatenation-of-array.rb: -------------------------------------------------------------------------------- 1 | # @param {Integer[]} nums 2 | # @return {Integer[]} 3 | def get_concatenation(nums) 4 | nums + nums 5 | end 6 | -------------------------------------------------------------------------------- /go/0136-single-number.go: -------------------------------------------------------------------------------- 1 | func singleNumber(nums []int) int { 2 | res := 0 3 | 4 | for _, num := range nums { 5 | res ^= num 6 | } 7 | 8 | return res 9 | } -------------------------------------------------------------------------------- /python/0459-repeated-substring-pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def repeatedSubstringPattern(self, s: str) -> bool: 3 | return s in (s + s)[1:-1] 4 | 5 | -------------------------------------------------------------------------------- /go/0191-number-of-1-bits.go: -------------------------------------------------------------------------------- 1 | func hammingWeight(num uint32) int { 2 | res := 0 3 | for num > 0 { 4 | num &= num - 1 5 | res += 1 6 | } 7 | return res 8 | } -------------------------------------------------------------------------------- /go/0344-reverse-string.go: -------------------------------------------------------------------------------- 1 | func reverseString(s []byte) { 2 | L, R := 0, len(s)-1 3 | 4 | for L < len(s)/2 { 5 | s[L], s[R] = s[R], s[L] 6 | L++ 7 | R-- 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ruby/0179-largest-number.rb: -------------------------------------------------------------------------------- 1 | # @param {Integer[]} nums 2 | # @return {String} 3 | def largest_number(nums) 4 | nums.sort! {|a, b| b.to_s + a.to_s <=> a.to_s + b.to_s}.join.to_i.to_s 5 | end -------------------------------------------------------------------------------- /scala/0485-max-consecutive-ones.scala: -------------------------------------------------------------------------------- 1 | object Solution { 2 | def findMaxConsecutiveOnes(nums: Array[Int]): Int = 3 | nums.scanLeft(0)((m, x) => if (x == 0) 0 else m + 1).max 4 | } -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /dart/0058-length-of-last-word.dart: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int lengthOfLastWord(String s) { 3 | final words = s.trim().split(" "); 4 | return words[words.length - 1].length; 5 | } 6 | } -------------------------------------------------------------------------------- /go/0283-move-zeroes.go: -------------------------------------------------------------------------------- 1 | func moveZeroes(nums []int) { 2 | for l, r := 0, 0; r < len(nums); r++ { 3 | if nums[r] != 0 { 4 | nums[l], nums[r] = nums[r], nums[l] 5 | l++ 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /go/0371-sum-of-two-integers.go: -------------------------------------------------------------------------------- 1 | func getSum(a int, b int) int { 2 | for b != 0 { 3 | temp := (a & b) << 1 4 | a = (a ^ b) 5 | b = temp 6 | } 7 | return a 8 | } -------------------------------------------------------------------------------- /javascript/0263-ugly-number.js: -------------------------------------------------------------------------------- 1 | var isUgly = function (n) { 2 | if (n <= 0) return false; 3 | 4 | for (const p of [2, 3, 5]) while (n % p == 0) n = n / p; 5 | return n == 1; 6 | }; 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "scripts": { 3 | "format": "prettier --write \"**/**/*.{js,ts,md,json}\"" 4 | }, 5 | "dependencies": { 6 | "prettier": "^3.6.2" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /c/0136-single-number.c: -------------------------------------------------------------------------------- 1 | int singleNumber(int* nums, int numsSize){ 2 | int res = 0; 3 | for (int i = 0; i < numsSize; i++) { 4 | res = nums[i] ^ res; 5 | } 6 | return res; 7 | } -------------------------------------------------------------------------------- /c/0371-sum-of-two-integers.c: -------------------------------------------------------------------------------- 1 | int getSum(int a, int b){ 2 | while (b != 0) { 3 | int temp = a ^ b; 4 | b = (unsigned)(a & b) << 1; 5 | a = temp; 6 | } 7 | return a; 8 | } -------------------------------------------------------------------------------- /cpp/2235-add-two-integers.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int sum(int num1, int num2){ 4 | return num1 + num2; 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /go/0268-missing-number.go: -------------------------------------------------------------------------------- 1 | func missingNumber(nums []int) int { 2 | res := len(nums) 3 | 4 | for i := 0; i < len(nums); i++ { 5 | res += i - nums[i] 6 | } 7 | return res 8 | } -------------------------------------------------------------------------------- /java/0342-power-of-four.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean isPowerOfFour(int n) { 4 | double x = Math.log(n) / Math.log(4); 5 | return x == (int) x; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /go/0070-climbing-stairs.go: -------------------------------------------------------------------------------- 1 | func climbStairs(n int) int { 2 | one, two := 1, 1 3 | 4 | for i := 0; i < n-1; i++ { 5 | sum := one + two 6 | one, two = two, sum 7 | } 8 | 9 | return two 10 | } -------------------------------------------------------------------------------- /python/0136-single-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: List[int]) -> int: 3 | res = 0 4 | for n in nums: 5 | res = n ^ res 6 | return res 7 | -------------------------------------------------------------------------------- /ruby/0217-contains-duplicate.rb: -------------------------------------------------------------------------------- 1 | def contains_duplicate(nums) 2 | hash = {} 3 | nums.each do |num| 4 | return true if hash.key? num 5 | 6 | hash[num] = true 7 | end 8 | false 9 | end 10 | -------------------------------------------------------------------------------- /c/0268-missing-number.c: -------------------------------------------------------------------------------- 1 | int missingNumber(int* nums, int numsSize){ 2 | int res = numsSize; 3 | 4 | for (int i = 0; i < numsSize; i++) { 5 | res += i - nums[i]; 6 | } 7 | return res; 8 | } -------------------------------------------------------------------------------- /python/0191-number-of-1-bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, n: int) -> int: 3 | res = 0 4 | while n: 5 | n &= n - 1 6 | res += 1 7 | return res 8 | -------------------------------------------------------------------------------- /ruby/0190-reverse-bits.rb: -------------------------------------------------------------------------------- 1 | def reverse_bits(n) 2 | reversed_bits = 0 3 | 31.downto(0) do |nbr| 4 | insert = ((n >> (31 - nbr)) & 1) << nbr 5 | reversed_bits |= insert 6 | end 7 | reversed_bits 8 | end 9 | -------------------------------------------------------------------------------- /scala/0179-largest-number.scala: -------------------------------------------------------------------------------- 1 | object Solution { 2 | def largestNumber(nums: Array[Int]): String = { 3 | BigInt(nums.map(_.toString).sortWith((l, r) => l ++ r >= r ++ l).foldLeft("")(_ + _)).toString 4 | } 5 | } -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /python/1461-check-if-a-string-contains-all-binary-codes-of-size-k.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hasAllCodes(self, s: str, k: int) -> bool: 3 | return len(set(s[i : i + k] for i in range(len(s) - k + 1))) == 2**k 4 | -------------------------------------------------------------------------------- /typescript/0066-plus-one.ts: -------------------------------------------------------------------------------- 1 | function plusOne(digits: number[]): number[] { 2 | return (BigInt(digits.join('')) + BigInt(1)) 3 | .toString() 4 | .split('') 5 | .map((item) => Number(item)); 6 | } 7 | -------------------------------------------------------------------------------- /go/0190-reverse-bits.go: -------------------------------------------------------------------------------- 1 | func reverseBits(num uint32) uint32 { 2 | var res uint32 = 0 3 | for i := 0; i < 32; i++ { 4 | bit := (num >> i) & 1 5 | res = res | (bit << (31 - i)) 6 | } 7 | return res 8 | } -------------------------------------------------------------------------------- /java/2220-minimum-bit-flips-to-convert-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minBitFlips(int start, int goal) { 3 | int xorResult = start ^ goal; 4 | return Integer.bitCount(xorResult); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /ruby/0001-two-sum.rb: -------------------------------------------------------------------------------- 1 | def two_sum(nums, target) 2 | hash = {} 3 | nums.each_with_index do |num, idx| 4 | return [hash[num], idx] if hash.key? num 5 | 6 | hash[target - num] = idx 7 | end 8 | nil 9 | end 10 | -------------------------------------------------------------------------------- /dart/0028-find-the-index-of-the-first-occurrence-in-a-string.dart: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int strStr(String haystack, String needle) { 3 | var result = haystack.replaceAll(needle, '0').indexOf('0'); 4 | return result; 5 | } 6 | } -------------------------------------------------------------------------------- /python/0268-missing-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingNumber(self, nums: List[int]) -> int: 3 | res = len(nums) 4 | 5 | for i in range(len(nums)): 6 | res += i - nums[i] 7 | return res 8 | -------------------------------------------------------------------------------- /typescript/2469-convert-the-temperature.ts: -------------------------------------------------------------------------------- 1 | function convertTemperature(celsius: number): number[] { 2 | const kelvin = celsius + 273.15; 3 | const fahrenheit = celsius * 1.8 + 32.0; 4 | return [kelvin, fahrenheit]; 5 | } 6 | -------------------------------------------------------------------------------- /javascript/2235-add-two-integers.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} num1 3 | * @param {number} num2 4 | * @return {number} 5 | */ 6 | var sum = function (num1, num2) { 7 | return num1 + num2; // add num1 and num2 and return it 8 | }; 9 | -------------------------------------------------------------------------------- /python/1523-count-odd-numbers-in-an-interval-range.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countOdds(self, low: int, high: int) -> int: 3 | if low%2!=0 or high%2!=0: 4 | return (high-low)//2 +1 5 | return (high-low)//2 6 | -------------------------------------------------------------------------------- /rust/0136-single-number.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn single_number(nums: Vec) -> i32 { 3 | let mut res = 0; 4 | for n in nums { 5 | res ^= n; 6 | } 7 | res 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /typescript/0136-single-number.ts: -------------------------------------------------------------------------------- 1 | function singleNumber(nums: number[]): number { 2 | let res = 0; 3 | 4 | for (let i = 0; i < nums.length; i++) { 5 | res = nums[i] ^ res; 6 | } 7 | 8 | return res; 9 | } 10 | -------------------------------------------------------------------------------- /c/0190-reverse-bits.c: -------------------------------------------------------------------------------- 1 | uint32_t reverseBits(uint32_t n) { 2 | uint32_t res = 0; 3 | 4 | for (int i = 0; i < 32; i++) { 5 | res <<= 1; 6 | res |= n & 1; 7 | n >>= 1; 8 | } 9 | return res; 10 | } -------------------------------------------------------------------------------- /go/0062-unique-paths.go: -------------------------------------------------------------------------------- 1 | func uniquePaths(m int, n int) int { 2 | dp := make([]int, n) 3 | dp[0] = 1 4 | 5 | for i := 0; i < m; i++ { 6 | for j := 1; j < n; j++ { 7 | dp[j] += dp[j-1] 8 | } 9 | } 10 | 11 | return dp[n-1] 12 | } -------------------------------------------------------------------------------- /go/0263-ugly-number.go: -------------------------------------------------------------------------------- 1 | func isUgly(n int) bool { 2 | if n <= 0 { 3 | return false 4 | } 5 | 6 | primes := []int{2, 3, 5} 7 | for _, p := range primes { 8 | for n%p == 0 { 9 | n /= p 10 | } 11 | } 12 | return n == 1 13 | } -------------------------------------------------------------------------------- /java/0104-maximum-depth-of-binary-tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int maxDepth(TreeNode root) { 4 | if (root == null) return 0; 5 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /java/1464-maximum-product-of-two-elements-in-an-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProduct(int[] nums) { 3 | Arrays.sort(nums); 4 | 5 | return (nums[nums.length-1]-1)*(nums[nums.length-2] -1); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /python/0190-reverse-bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseBits(self, n: int) -> int: 3 | res = 0 4 | for i in range(32): 5 | bit = (n >> i) & 1 6 | res += (bit << (31 - i)) 7 | return res 8 | -------------------------------------------------------------------------------- /go/0009-palindrome-number.go: -------------------------------------------------------------------------------- 1 | func isPalindrome(x int) bool { 2 | s := strconv.Itoa(x) 3 | r := []rune(s) 4 | for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { 5 | if r[i] != r[j] { 6 | return false 7 | } 8 | } 9 | return true 10 | } -------------------------------------------------------------------------------- /c/1822-sign-of-the-product-of-an-array.c: -------------------------------------------------------------------------------- 1 | int arraySign(int *nums, int numsSize) { 2 | char prodSign = 1; 3 | for (int i = 0; i < numsSize; i++) 4 | prodSign *= ((unsigned)-nums[i] >> 31) - ((unsigned)nums[i] >> 31); 5 | return prodSign; 6 | } 7 | -------------------------------------------------------------------------------- /java/0338-counting-bits.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] countBits(int n) { 3 | int res[] = new int[n + 1]; 4 | for (int i = 1; i <= n; i++) 5 | res[i] = 1 + res[i & (i - 1)]; 6 | return res; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /swift/0104-maximum-depth-of-binary-tree.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maxDepth(_ root: TreeNode?) -> Int { 3 | guard root != nil else { return 0 } 4 | return max(maxDepth(root?.left) + 1, maxDepth(root?.right) + 1) 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /go/0055-jump-game.go: -------------------------------------------------------------------------------- 1 | func canJump(nums []int) bool { 2 | goal := len(nums) - 1 3 | 4 | for i := len(nums) - 2; i >= 0; i-- { 5 | if i + nums[i] >= goal { 6 | goal = i 7 | } 8 | } 9 | return goal == 0 10 | } -------------------------------------------------------------------------------- /kotlin/0217-contains-duplicate.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun containsDuplicate(nums: IntArray): Boolean { 3 | val hs = HashSet() 4 | for (e in nums) 5 | if (!hs.add(e)) return true 6 | return false 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /python/1929-concatenation-of-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getConcatenation(self, nums: List[int]) -> List[int]: 3 | ans = [] 4 | for i in range(2): 5 | for n in nums: 6 | ans.append(n) 7 | return ans 8 | -------------------------------------------------------------------------------- /swift/0179-largest-number.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func largestNumber(_ nums: [Int]) -> String { 3 | return nums.reduce(into: Bool(false), { $0 = $0 || $1 > 0 }) ? nums.map { String($0) }.sorted { $0 + $1 > $1 + $0 }.joined() : "0" 4 | } 5 | } -------------------------------------------------------------------------------- /python/0125-valid-palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, s: str) -> bool: 3 | new = '' 4 | for a in s: 5 | if a.isalpha() or a.isdigit(): 6 | new += a.lower() 7 | return (new == new[::-1]) 8 | -------------------------------------------------------------------------------- /rust/0190-reverse-bits.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn reverse_bits(mut x: u32) -> u32 { 3 | (0..32).fold(0, |mut res, _| { 4 | res = (res << 1) | (x & 1); 5 | x >>= 1; 6 | res 7 | }) 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /csharp/0136-single-number.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int SingleNumber(int[] nums) { 3 | var x = 0; 4 | for (int i=0;i < nums.Length; i++) 5 | { 6 | x ^= nums[i]; 7 | } 8 | return x; 9 | } 10 | } -------------------------------------------------------------------------------- /ruby/0100-same-tree.rb: -------------------------------------------------------------------------------- 1 | def is_same_tree(p, q) 2 | if p.nil? && q.nil? 3 | true 4 | elsif p && q 5 | (p.val == q.val) && 6 | is_same_tree(p.left, q.left) && 7 | is_same_tree(p.right, q.right) 8 | else 9 | false 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /ruby/0104-maximum-depth-of-binary-tree.rb: -------------------------------------------------------------------------------- 1 | def max_depth(root) 2 | return 0 if root.nil? 3 | return 1 if root.left.nil? && root.right.nil? 4 | 5 | left = 1 + max_depth(root.left) 6 | right = 1 + max_depth(root.right) 7 | left > right ? left : right 8 | end 9 | -------------------------------------------------------------------------------- /rust/0035-search-insert-position.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn search_insert(nums: Vec, target: i32) -> i32 { 3 | match nums.binary_search(&target) { 4 | Ok(i) => i as i32, 5 | Err(i) => i as i32, 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /typescript/2667-create-hello-world-function.ts: -------------------------------------------------------------------------------- 1 | function createHelloWorld() { 2 | return function (...args): string { 3 | return 'Hello World'; 4 | }; 5 | } 6 | 7 | /** 8 | * const f = createHelloWorld(); 9 | * f(); // "Hello World" 10 | */ 11 | -------------------------------------------------------------------------------- /go/0058-Length-of-Last-Word.go: -------------------------------------------------------------------------------- 1 | func lengthOfLastWord(s string) int { 2 | l := 0 3 | 4 | for i := len(s) - 1; i >= 0; i-- { 5 | if s[i] == ' ' { 6 | if l >= 1 { 7 | return l 8 | } 9 | } else { 10 | l++ 11 | } 12 | } 13 | 14 | return l 15 | }å -------------------------------------------------------------------------------- /go/0058-length-of-last-word.go: -------------------------------------------------------------------------------- 1 | func lengthOfLastWord(s string) int { 2 | l := 0 3 | 4 | for i := len(s) - 1; i >= 0; i-- { 5 | if s[i] == ' ' { 6 | if l >= 1 { 7 | return l 8 | } 9 | } else { 10 | l++ 11 | } 12 | } 13 | 14 | return l 15 | }å -------------------------------------------------------------------------------- /go/0169-majority-element.go: -------------------------------------------------------------------------------- 1 | func majorityElement(nums []int) int { 2 | counter := map[int]int{} 3 | treshold := len(nums) / 2 4 | for _, n := range nums { 5 | counter[n]++ 6 | if counter[n] > treshold { 7 | return n 8 | } 9 | } 10 | return -1 11 | } 12 | -------------------------------------------------------------------------------- /python/0746-min-cost-climbing-stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCostClimbingStairs(self, cost: List[int]) -> int: 3 | for i in range(len(cost) - 3, -1, -1): 4 | cost[i] += min(cost[i + 1], cost[i + 2]) 5 | 6 | return min(cost[0], cost[1]) 7 | -------------------------------------------------------------------------------- /ruby/0049-group-anagrams.rb: -------------------------------------------------------------------------------- 1 | def group_anagrams(strs) 2 | anagrams = Hash.new { |h, k| h[k] = [] } 3 | strs.each do |str| 4 | hash = Hash.new(0) 5 | str.each_char { |c| hash[c] += 1 } 6 | anagrams[hash] << str 7 | end 8 | anagrams.values 9 | end 10 | -------------------------------------------------------------------------------- /c/0055-jump-game.c: -------------------------------------------------------------------------------- 1 | bool canJump(int* nums, int numsSize){ 2 | int goal = numsSize - 1; 3 | 4 | for (int i = numsSize - 2; i >= 0; i--) { 5 | if (i + nums[i] >= goal) { 6 | goal = i; 7 | } 8 | } 9 | return goal == 0; 10 | } -------------------------------------------------------------------------------- /go/0001-two-sum.go: -------------------------------------------------------------------------------- 1 | func twoSum(nums []int, target int) []int { 2 | m := make(map[int]int) 3 | for idx, num := range nums { 4 | 5 | if val, found := m[target-num]; found { 6 | return []int{val, idx} 7 | } 8 | 9 | m[num] = idx 10 | } 11 | return nil 12 | } 13 | -------------------------------------------------------------------------------- /python/0055-jump-game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | goal = len(nums) - 1 4 | 5 | for i in range(len(nums) - 2, -1, -1): 6 | if i + nums[i] >= goal: 7 | goal = i 8 | return goal == 0 9 | -------------------------------------------------------------------------------- /swift/0268-missing-number.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func missingNumber(_ nums: [Int]) -> Int { 3 | var res = nums.count 4 | 5 | for i in 0...nums.count-1 { 6 | res += i - nums[i] 7 | } 8 | return res 9 | } 10 | } -------------------------------------------------------------------------------- /c/0191-number-of-1-bits.c: -------------------------------------------------------------------------------- 1 | int hammingWeight(uint32_t n) { 2 | int res = 0; 3 | int bit = 0; 4 | while (n != 0) { 5 | bit = n & 1; 6 | if (bit == 1) { 7 | res++; 8 | } 9 | n = n >> 1; 10 | } 11 | return res; 12 | } -------------------------------------------------------------------------------- /javascript/1822-sign-of-the-product-of-an-array.js: -------------------------------------------------------------------------------- 1 | const arraySign = function (nums) { 2 | let sign = 1; 3 | 4 | for (const num of nums) { 5 | if (num == 0) return 0; 6 | if (num < 0) sign = -1 * sign; 7 | } 8 | 9 | return sign; 10 | }; 11 | -------------------------------------------------------------------------------- /javascript/2769-find-the-maximum-achievable-number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} num 3 | * @param {number} t 4 | * @return {number} 5 | */ 6 | var theMaximumAchievableX = function (num, t) { 7 | return num + t * 2; // return sum of value of num and twice the value of t 8 | }; 9 | -------------------------------------------------------------------------------- /kotlin/0136-single-number.kt: -------------------------------------------------------------------------------- 1 | package kotlin 2 | 3 | class Solution { 4 | fun singleNumber(nums: IntArray): Int { 5 | var res = 0 6 | 7 | for(n in nums){ 8 | res = res xor n 9 | } 10 | return res 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /python/0263-ugly-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isUgly(self, n: int) -> bool: 3 | if n <= 0: 4 | return False 5 | 6 | for p in [2, 3, 5]: 7 | while n % p == 0: 8 | n = n // p 9 | return n == 1 10 | -------------------------------------------------------------------------------- /ruby/0226-invert-binary-tree.rb: -------------------------------------------------------------------------------- 1 | def invert_tree(root) 2 | return root if root.nil? 3 | return root if root.left.nil? && root.right.nil? 4 | 5 | root.left, root.right = root.right, root.left 6 | invert_tree(root.left) 7 | invert_tree(root.right) 8 | root 9 | end 10 | -------------------------------------------------------------------------------- /rust/0055-jump-game.rs: -------------------------------------------------------------------------------- 1 | pub fn can_jump(nums: Vec) -> bool { 2 | let mut goal = nums.len() - 1; 3 | 4 | for i in (0..goal).rev() { 5 | if i + nums[i] as usize >= goal { 6 | goal = i; 7 | } 8 | } 9 | 10 | goal == 0 11 | } 12 | -------------------------------------------------------------------------------- /rust/0191-number-of-1-bits.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn hammingWeight(mut n: u32) -> i32 { 3 | let mut count = 0; 4 | 5 | while n > 0 { 6 | n = n & (n - 1); 7 | count += 1; 8 | } 9 | 10 | count 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /typescript/1929-concatenation-of-array.ts: -------------------------------------------------------------------------------- 1 | function getConcatenation(nums: number[]): number[] { 2 | let result: number[] = []; 3 | 4 | for (let i = 0; i < 2; i++) { 5 | nums.forEach((num) => result.push(num)); 6 | } 7 | 8 | return result; 9 | } 10 | -------------------------------------------------------------------------------- /dart/0746-min-cost-climbing-stairs.dart: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int minCostClimbingStairs(List cost) { 3 | for (int i = cost.length - 3; i >= 0; i--) { 4 | cost[i] += min(cost[i + 1], cost[i + 2]); 5 | } 6 | 7 | return min(cost[0], cost[1]); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /go/0219-contains-duplicate-ii.go: -------------------------------------------------------------------------------- 1 | func containsNearbyDuplicate(nums []int, k int) bool { 2 | seen := make(map[int]int) 3 | 4 | for i, n := range nums { 5 | if j, ok := seen[n]; ok && i - j <= k { 6 | return true 7 | } 8 | seen[n] = i 9 | } 10 | return false 11 | } 12 | -------------------------------------------------------------------------------- /java/0371-sum-of-two-integers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int getSum(int a, int b) { 4 | while (b != 0) { 5 | int tmp = (a & b) << 1; 6 | a = (a ^ b); 7 | b = tmp; 8 | } 9 | return a; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /kotlin/0746-min-cost-climbing-stairs.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun minCostClimbingStairs(cost: IntArray): Int { 3 | for (i in cost.size - 3 downTo 0) { 4 | cost[i] += minOf(cost[i + 1], cost[i + 2]) 5 | } 6 | return minOf(cost[0], cost[1]) 7 | } 8 | } -------------------------------------------------------------------------------- /python/0198-house-robber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | rob1, rob2 = 0, 0 4 | 5 | for n in nums: 6 | temp = max(n + rob1, rob2) 7 | rob1 = rob2 8 | rob2 = temp 9 | return rob2 10 | -------------------------------------------------------------------------------- /python/0392-is-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSubsequence(self, s: str, t: str) -> bool: 3 | i, j = 0, 0 4 | while i < len(s) and j < len(t): 5 | if s[i] == t[j]: 6 | i += 1 7 | j += 1 8 | return i == len(s) 9 | -------------------------------------------------------------------------------- /ruby/0053-maximum-subarray.rb: -------------------------------------------------------------------------------- 1 | def max_sub_array(nums) 2 | max_sub = nums[0] 3 | current_sum = 0 4 | 5 | nums.each do |num| 6 | current_sum = 0 if current_sum < 0 7 | current_sum += num 8 | max_sub = [max_sub,current_sum].max 9 | end 10 | return max_sub 11 | end -------------------------------------------------------------------------------- /ruby/1299-replace-elements-with-greatest-element-on-right-side.rb: -------------------------------------------------------------------------------- 1 | def replace_elements(arr) 2 | right_max = -1 3 | (arr.length - 1).downto(0) do |i| 4 | cur_max = [right_max, arr[i]].max 5 | arr[i] = right_max 6 | right_max = cur_max 7 | end 8 | arr 9 | end 10 | -------------------------------------------------------------------------------- /rust/0198-house-robber.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn rob(nums: Vec) -> i32 { 3 | nums.into_iter() 4 | .fold((0, 0), |loot, money| (loot.1, loot.1.max(loot.0 + money))) 5 | .1 6 | } 7 | } 8 | 9 | 10 | 11 | - 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /typescript/1822-sign-of-the-product-of-an-array.ts: -------------------------------------------------------------------------------- 1 | function arraySign(nums: number[]): number { 2 | let sign = 1; 3 | 4 | for (const num of nums) { 5 | if (num == 0) return 0; 6 | if (num < 0) sign = -1 * sign; 7 | } 8 | 9 | return sign; 10 | } 11 | -------------------------------------------------------------------------------- /csharp/0371-sum-of-two-integers.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int GetSum(int a, int b) { 3 | while (b != 0) 4 | { 5 | var carry = a & b; 6 | a = a ^ b; 7 | b = carry << 1; 8 | } 9 | return a; 10 | } 11 | } -------------------------------------------------------------------------------- /go/0100-same-tree.go: -------------------------------------------------------------------------------- 1 | func isSameTree(p *TreeNode, q *TreeNode) bool { 2 | if p == nil && q == nil { 3 | return true 4 | } 5 | 6 | if p == nil || q == nil || p.Val != q.Val { 7 | return false 8 | } 9 | 10 | return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) 11 | } -------------------------------------------------------------------------------- /go/0104-maximum-depth-of-binary-tree.go: -------------------------------------------------------------------------------- 1 | func maxDepth(root *TreeNode) int { 2 | if root == nil { 3 | return 0 4 | } 5 | 6 | left := maxDepth(root.Left) 7 | right := maxDepth(root.Right) 8 | 9 | if left > right { 10 | return 1 + left 11 | } 12 | 13 | return right + 1 14 | } -------------------------------------------------------------------------------- /go/0122-best-time-to-buy-and-sell-stock-ii.go: -------------------------------------------------------------------------------- 1 | func maxProfit(prices []int) int { 2 | var maxProfit int 3 | 4 | for i := 0; i < len(prices) - 1; i++ { 5 | if prices[i] < prices[i+1] { 6 | maxProfit += prices[i+1] - prices[i] 7 | } 8 | } 9 | 10 | return maxProfit 11 | } 12 | -------------------------------------------------------------------------------- /ruby/0198-house-robber.rb: -------------------------------------------------------------------------------- 1 | # @param {Integer[]} nums 2 | # @return {Integer} 3 | def rob(nums) 4 | dp = Array.new(nums.size + 3) { 0 } 5 | 6 | nums.each_with_index do |num, i| 7 | dp[i + 3] = num + [dp[i + 1], dp[i]].max 8 | end 9 | 10 | [dp[-1], dp[-2]].max 11 | end 12 | -------------------------------------------------------------------------------- /typescript/0070-climbing-stairs.ts: -------------------------------------------------------------------------------- 1 | function climbStairs(n: number): number { 2 | let one = 1; 3 | let two = 1; 4 | 5 | for (let i = 0; i < n - 1; i++) { 6 | let temp = one; 7 | one = one + two; 8 | two = temp; 9 | } 10 | return one; 11 | } 12 | -------------------------------------------------------------------------------- /typescript/2620-counter.ts: -------------------------------------------------------------------------------- 1 | function createCounter(n: number): () => number { 2 | return function () { 3 | return n++; 4 | }; 5 | } 6 | 7 | /** 8 | * const counter = createCounter(10) 9 | * counter() // 10 10 | * counter() // 11 11 | * counter() // 12 12 | */ 13 | -------------------------------------------------------------------------------- /go/1220-count-vowels-permutation.go: -------------------------------------------------------------------------------- 1 | const mod = 1_000_000_007 2 | 3 | func countVowelPermutation(n int) int { 4 | a, e, i, o, u := 1, 1, 1, 1, 1 5 | for k := 0; k < n-1; k++ { 6 | a, e, i, o, u = e%mod, (a+i)%mod, (a+e+o+u)%mod, (i+u)%mod, a%mod 7 | } 8 | return (a + e + i + o + u) % mod 9 | } -------------------------------------------------------------------------------- /swift/0191-number-of-1-bits.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func hammingWeight(_ n: Int) -> Int { 3 | var x = n 4 | var count = 0 5 | while x != 0 { 6 | x = x & (x - 1) 7 | count += 1 8 | } 9 | return count 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /typescript/0055-jump-game.ts: -------------------------------------------------------------------------------- 1 | function canJump(nums: number[]): boolean { 2 | let goal = nums.length - 1; 3 | 4 | for (let i = nums.length - 2; i >= 0; i--) { 5 | if (i + nums[i] >= goal) { 6 | goal = i; 7 | } 8 | } 9 | return goal == 0; 10 | } 11 | -------------------------------------------------------------------------------- /typescript/0268-missing-number.ts: -------------------------------------------------------------------------------- 1 | function missingNumber(nums: number[]): number { 2 | let sum: number = 0; 3 | let total: number = (nums.length * (nums.length + 1)) / 2; 4 | for (let i = 0; i < nums.length; i++) { 5 | sum += nums[i]; 6 | } 7 | return total - sum; 8 | } 9 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /cpp/0263-ugly-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isUgly(int n) { 4 | if(n <= 0) 5 | return false; 6 | 7 | for(int p: {2, 3, 5}) 8 | while(n % p == 0) 9 | n = n / p; 10 | return n == 1; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /csharp/1480-running-sum-of-1d-array.cs: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public int[] RunningSum(int[] nums) 4 | { 5 | for (int i = 1; i < nums.Length; i++) 6 | { 7 | nums[i] = nums[i - 1] + nums[i]; 8 | } 9 | return nums; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /go/0338-counting-bits.go: -------------------------------------------------------------------------------- 1 | func countBits(n int) []int { 2 | dp := make([]int, n + 1) 3 | offset := 1 4 | 5 | for i := 1; i <= n; i++ { 6 | if offset * 2 == i { 7 | offset = i 8 | } 9 | dp[i] = 1 + dp[i - offset] 10 | } 11 | return dp 12 | } -------------------------------------------------------------------------------- /go/0658-find-k-closest-elements.go: -------------------------------------------------------------------------------- 1 | func findClosestElements(arr []int, k int, x int) []int { 2 | l, r := 0, len(arr)-k 3 | 4 | for l < r { 5 | m := (l + r) / 2 6 | if x-arr[m] > arr[m+k]-x { 7 | l = m + 1 8 | } else { 9 | r = m 10 | } 11 | } 12 | return arr[l : l+k] 13 | } 14 | -------------------------------------------------------------------------------- /java/1822-sign-of-the-product-of-an-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int arraySign(int[] nums) { 3 | int sign = 1; 4 | for (int i : nums) { 5 | if (i == 0) return 0; 6 | if (i < 0) sign *= -1; 7 | } 8 | return sign; 9 | } 10 | } -------------------------------------------------------------------------------- /python/0217-contains-duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | hashset = set() 4 | 5 | for n in nums: 6 | if n in hashset: 7 | return True 8 | hashset.add(n) 9 | return False 10 | -------------------------------------------------------------------------------- /python/0274-H-index.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hIndex(self, citations: List[int]) -> int: 3 | length = len(citations) 4 | citations.sort() 5 | for i in range(length): 6 | if citations[i] >= length - i: 7 | return length - i 8 | return 0 9 | -------------------------------------------------------------------------------- /python/0280-wiggle-sort.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wiggleSort(self, nums: List[int]) -> None: 3 | for i in range(1, len(nums)): 4 | if (i % 2 == 1 and nums[i] < nums[i - 1]) or (i % 2 == 0 and nums[i] > nums[i - 1]): 5 | nums[i], nums[i - 1] = nums[i - 1], nums[i] 6 | -------------------------------------------------------------------------------- /ruby/0121-best-time-to-buy-and-sell-stock.rb: -------------------------------------------------------------------------------- 1 | def max_profit(prices) 2 | max_profit = 0 3 | min = prices.first 4 | prices.each do |price| 5 | min = price if price < min 6 | profit = price - min 7 | max_profit = profit if profit > max_profit 8 | end 9 | max_profit 10 | end 11 | -------------------------------------------------------------------------------- /rust/0070-climbing-stairs.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn climb_stairs(n: i32) -> i32 { 3 | std::iter::successors(Some((0, 1)), |dp| Some((dp.1, dp.0 + dp.1))) 4 | .take((n + 1) as usize) 5 | .last() 6 | .unwrap() 7 | .1 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /swift/0190-reverse-bits.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func reverseBits(_ n: Int) -> Int { 3 | var res = 0 4 | 5 | for i in 0...31 { 6 | let bit = (n >> i) & 1 7 | res = res | (bit << (31 - i)) 8 | } 9 | return res 10 | } 11 | } -------------------------------------------------------------------------------- /typescript/0344-reverse-string.ts: -------------------------------------------------------------------------------- 1 | function reverseString(s: string[]): void { 2 | let l = 0; 3 | let r = s.length - 1; 4 | 5 | while (l < r) { 6 | let temp = s[l]; 7 | s[l] = s[r]; 8 | s[r] = temp; 9 | l += 1; 10 | r -= 1; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /swift/0100-same-tree.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool { 3 | if p == nil && q == nil { return true } 4 | if p?.val != q?.val { return false } 5 | return isSameTree(p?.left, q?.left) && isSameTree(p?.right, q?.right) 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /typescript/0190-reverse-bits.ts: -------------------------------------------------------------------------------- 1 | function reverseBits(n: number): number { 2 | let result = 0b0; 3 | 4 | for (let i = 0; i < 32; i++) { 5 | const bit = n & 0b1; 6 | result <<= 1; 7 | result |= bit; 8 | n >>= 1; 9 | } 10 | return result >>> 0; 11 | } 12 | -------------------------------------------------------------------------------- /typescript/0198-house-robber.ts: -------------------------------------------------------------------------------- 1 | function rob(nums: number[]): number { 2 | let rob1 = 0; 3 | let rob2 = 0; 4 | 5 | for (const n of nums) { 6 | let temp = Math.max(n + rob1, rob2); 7 | rob1 = rob2; 8 | rob2 = temp; 9 | } 10 | 11 | return rob2; 12 | } 13 | -------------------------------------------------------------------------------- /typescript/0263-ugly-number.ts: -------------------------------------------------------------------------------- 1 | function isUgly(n: number): boolean { 2 | if (n < 1) { 3 | return false; 4 | } 5 | 6 | for (let prime of [2, 3, 5]) { 7 | while (n % prime == 0) { 8 | n /= prime; 9 | } 10 | } 11 | 12 | return n == 1; 13 | } 14 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /dart/0070-climbing-stairs.dart: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int climbStairs(int n) { 3 | int first=0; 4 | int second=1; 5 | int res=1; 6 | for(int i=0;i) -> i32 { 3 | let length = nums.len() as i32; 4 | let mut ans = length; 5 | for i in 0..length { 6 | ans ^= i ^ nums[i as usize]; 7 | } 8 | ans 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /typescript/0058-length-of-last-word.ts: -------------------------------------------------------------------------------- 1 | function lengthOfLastWord(s: string): number { 2 | let res = 0; 3 | for (let i = s.length - 1; i > -1; i--) { 4 | if (s[i] === ' ' && res === 0) continue; 5 | if (s[i] === ' ') break; 6 | res += 1; 7 | } 8 | return res; 9 | } 10 | -------------------------------------------------------------------------------- /typescript/0217-contains-duplicate.ts: -------------------------------------------------------------------------------- 1 | function containsDuplicate(nums: number[]): boolean { 2 | const set = new Set(); 3 | 4 | for (let i = 0; i < nums.length; i++) { 5 | if (set.has(nums[i])) return true; 6 | else set.add(nums[i]); 7 | } 8 | 9 | return false; 10 | } 11 | -------------------------------------------------------------------------------- /typescript/0746-min-cost-climbing-stairs.ts: -------------------------------------------------------------------------------- 1 | function minCostClimbingStairs(cost: number[]): number { 2 | cost.push(0); 3 | 4 | for (let i = cost.length - 3; i > -1; i--) { 5 | cost[i] += Math.min(cost[i + 1], cost[i + 2]); 6 | } 7 | 8 | return Math.min(cost[0], cost[1]); 9 | } 10 | -------------------------------------------------------------------------------- /typescript/0876-middle-of-the-linked-list.ts: -------------------------------------------------------------------------------- 1 | function middleNode(head: ListNode | null): ListNode | null { 2 | let slow = head; 3 | let fast = head; 4 | 5 | while (fast && fast.next) { 6 | slow = slow?.next!; 7 | fast = fast.next.next; 8 | } 9 | return slow; 10 | } 11 | -------------------------------------------------------------------------------- /go/0027-remove-element.go: -------------------------------------------------------------------------------- 1 | func removeElement(nums []int, val int) int { 2 | left, right := 0, len(nums)-1 3 | 4 | for left <= right { 5 | if nums[left] == val { 6 | nums[left], nums[right] = nums[right], nums[left] 7 | right-- 8 | } else { 9 | left++ 10 | } 11 | } 12 | 13 | return left 14 | } -------------------------------------------------------------------------------- /javascript/2626-array-reduce-transformation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {Function} fn 4 | * @param {number} init 5 | * @return {number} 6 | */ 7 | var reduce = function (nums, fn, init) { 8 | ans = init; 9 | for (let n of nums) ans = fn(ans, n); 10 | return ans; 11 | }; 12 | -------------------------------------------------------------------------------- /javascript/2634-filter-elements-from-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {Function} fn 4 | * @return {number[]} 5 | */ 6 | var filter = function (arr, fn) { 7 | ans = []; 8 | for (let i = 0; i < arr.length; i++) if (fn(arr[i], i)) ans.push(arr[i]); 9 | return ans; 10 | }; 11 | -------------------------------------------------------------------------------- /python/0014-longest-common-prefix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonPrefix(self, strs: List[str]) -> str: 3 | for i in range(len(strs[0])): 4 | for s in strs: 5 | if i >= len(s) or s[i] != strs[0][i]: 6 | return strs[0][:i] 7 | return strs[0] 8 | -------------------------------------------------------------------------------- /python/2405-optimal-partition-of-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def partitionString(self, s: str) -> int: 3 | c=0 4 | res=set() 5 | for i in s: 6 | if i in res: 7 | c=c+1 8 | res=set() 9 | res.add(i) 10 | return c+1 11 | -------------------------------------------------------------------------------- /rust/0344-reverse-string.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn reverse_string(s: &mut Vec) { 3 | let (mut left, mut right) = (0, s.len() - 1); 4 | 5 | while left < right { 6 | s.swap(left, right); 7 | left += 1; 8 | right -= 1; 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /typescript/0191-number-of-1-bits.ts: -------------------------------------------------------------------------------- 1 | function hammingWeight(n: number): number { 2 | let base2 = n.toString(2).split(''); 3 | let count = 0; 4 | 5 | base2.forEach((item) => { 6 | if (item === '1') { 7 | count += 1; 8 | } 9 | }); 10 | 11 | return count; 12 | } 13 | -------------------------------------------------------------------------------- /c/0026-remove-duplicates-from-sorted-array.c: -------------------------------------------------------------------------------- 1 | int removeDuplicates(int* nums, int numsSize){ 2 | int indx = 1; 3 | 4 | for(int i = 1; i < numsSize; i++){ 5 | if(nums[i] != nums[i-1]){ 6 | nums[indx] = nums[i]; 7 | indx++; 8 | } 9 | } 10 | return indx; 11 | } -------------------------------------------------------------------------------- /c/0070-climbing-stairs.c: -------------------------------------------------------------------------------- 1 | int climbStairs(int n){ 2 | if (n <= 3) { 3 | return n; 4 | } 5 | 6 | int n1 = 2; 7 | int n2 = 3; 8 | 9 | for (int i = 4; i <= n; i++) { 10 | int temp = n1 + n2; 11 | n1 = n2; 12 | n2 = temp; 13 | } 14 | return n2; 15 | } -------------------------------------------------------------------------------- /c/0746-min-cost-climbing-stairs.c: -------------------------------------------------------------------------------- 1 | int min(int a, int b) { return a > b ? b : a; } 2 | 3 | int minCostClimbingStairs(int *cost, int costSize) { 4 | 5 | for (int i = 2; i < costSize; i++) 6 | cost[i] += min(cost[i - 1], cost[i - 2]); 7 | 8 | return min(cost[costSize - 1], cost[costSize - 2]); 9 | } -------------------------------------------------------------------------------- /csharp/0190-reverse-bits.cs: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public uint reverseBits(uint n) 4 | { 5 | uint result = 0; 6 | for (int i = 0; i < 32; i++) 7 | { 8 | uint temp = (n & 1); 9 | result = (result << 1) + temp; 10 | n >>= 1; 11 | } 12 | return result; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /kotlin/0268-missing-number.kt: -------------------------------------------------------------------------------- 1 | package kotlin 2 | 3 | class Solution { 4 | fun missingNumber(nums: IntArray): Int { 5 | var missing = nums.size 6 | for(i in nums.indices){ 7 | missing = missing xor i xor nums[i] 8 | } 9 | 10 | return missing 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /python/0070-climbing-stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | if n <= 3: 4 | return n 5 | n1, n2 = 2, 3 6 | 7 | for i in range(4, n + 1): 8 | temp = n1 + n2 9 | n1 = n2 10 | n2 = temp 11 | return n2 12 | -------------------------------------------------------------------------------- /python/0122-best-time-to-buy-and-sell-stock-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | max_profit = 0 4 | for i in range(1, len(prices)): 5 | if prices[i] > prices[i-1]: 6 | max_profit += prices[i] - prices[i-1] 7 | return max_profit 8 | -------------------------------------------------------------------------------- /python/0169-majority-element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def majorityElement(self, nums: List[int]) -> int: 3 | res, count = 0, 0 4 | 5 | for n in nums: 6 | if count == 0: 7 | res = n 8 | count += (1 if n == res else -1) 9 | 10 | return res -------------------------------------------------------------------------------- /c/0027-remove-element.c: -------------------------------------------------------------------------------- 1 | int removeElement(int* nums, int numsSize, int val){ 2 | int k = 0; 3 | 4 | for(int i = 0; i < numsSize; i++) 5 | { 6 | if(nums[i] != val) 7 | { 8 | nums[k] = nums[i]; 9 | k++; 10 | } 11 | } 12 | 13 | return k; 14 | } 15 | -------------------------------------------------------------------------------- /cpp/1213-maximum-product-difference-between-two-pairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int maxProductDifference(vector& nums){ 4 | sort(nums.begin(), nums.end()); 5 | return nums.rbegin()[1] * nums.back() - nums[0] * nums[1]; 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /go/0026-remove-duplicates-from-sorted-array.go: -------------------------------------------------------------------------------- 1 | func removeDuplicates(nums []int) int { 2 | length := len(nums) 3 | if length < 2 { 4 | return length 5 | } 6 | k, i := 1, 1 7 | for i < length { 8 | if nums[i] != nums[i-1] { 9 | nums[k] = nums[i] 10 | k++ 11 | } 12 | i++ 13 | } 14 | return k 15 | } 16 | -------------------------------------------------------------------------------- /go/0367-valid-perfect-square.go: -------------------------------------------------------------------------------- 1 | func isPerfectSquare(num int) bool { 2 | l, r := 0, num 3 | for l <= r { 4 | m := (l + r) / 2 5 | product := m * m 6 | if product == num { 7 | return true 8 | } else if product > num { 9 | r = m - 1 10 | } else { 11 | l = m + 1 12 | } 13 | } 14 | return false 15 | } -------------------------------------------------------------------------------- /go/0392-is-subsequence.go: -------------------------------------------------------------------------------- 1 | func isSubsequence(s string, t string) bool { 2 | if len(s) == 0 { 3 | return true 4 | } 5 | 6 | p := 0 7 | 8 | 9 | for i := 0; i < len(t); i++ { 10 | if s[p] == t[i] { 11 | p++ 12 | } 13 | 14 | if p == len(s) { 15 | return true 16 | } 17 | } 18 | 19 | return false 20 | } -------------------------------------------------------------------------------- /kotlin/0263-ugly-number.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun isUgly(_n: Int): Boolean { 3 | if (_n <= 0) return false 4 | 5 | var n = _n 6 | for (p in listOf(2, 3, 5)) { 7 | while (n % p == 0) 8 | n /= p 9 | } 10 | 11 | return n == 1 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /python/0278-first-bad-version.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstBadVersion(self, n: int) -> int: 3 | l, r = 1, n 4 | while l < r: 5 | v = (l + r) // 2 6 | if isBadVersion(v): 7 | r = v 8 | else: 9 | l = v + 1 10 | return l 11 | -------------------------------------------------------------------------------- /rust/0283-move-zeroes.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn move_zeroes(nums: &mut Vec) { 3 | let mut left = 0; 4 | 5 | for r in 0..nums.len() { 6 | if nums[r] != 0 { 7 | nums.swap(left, r); 8 | left += 1; 9 | } 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /scala/0070-climbing-stairs.scala: -------------------------------------------------------------------------------- 1 | object Solution { 2 | def climbStairs(n: Int): Int = { 3 | var one = 1 4 | var two = 1 5 | for (i <- 0 until n - 1) { 6 | val temp = one 7 | one = one + two 8 | two = temp 9 | } 10 | one 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /swift/0198-house-robber.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func rob(_ nums: [Int]) -> Int { 3 | var rob1 = 0, rob2 = 0 4 | 5 | for n in nums { 6 | let temp = max(n + rob1, rob2) 7 | rob1 = rob2 8 | rob2 = temp 9 | } 10 | return rob2 11 | } 12 | } -------------------------------------------------------------------------------- /typescript/0027-remove-element.ts: -------------------------------------------------------------------------------- 1 | function removeElement(nums: number[], val: number): number { 2 | let k = 0; 3 | 4 | for (let i = 0; i < nums.length; i++) { 5 | if (nums[i] != val) { 6 | nums[k] = nums[i]; 7 | k += 1; 8 | } 9 | } 10 | 11 | return k; 12 | } 13 | -------------------------------------------------------------------------------- /typescript/0371-sum-of-two-integers.ts: -------------------------------------------------------------------------------- 1 | function getSum(a: number, b: number): number { 2 | let res = a; 3 | let secondInt = b; 4 | 5 | while (secondInt != 0) { 6 | let temp = (res & secondInt) << 1; 7 | res ^= secondInt; 8 | secondInt = temp; 9 | } 10 | return res; 11 | } 12 | -------------------------------------------------------------------------------- /dart/0392-is-subsequence.dart: -------------------------------------------------------------------------------- 1 | class Solution { 2 | bool isSubsequence(String s, String t) { 3 | int i = 0, j = 0; 4 | while (i < t.length && j != s.length) { 5 | if (t[i] == s[j]) { 6 | j += 1; 7 | } 8 | i += 1; 9 | } 10 | return j == s.length; 11 | } 12 | } -------------------------------------------------------------------------------- /go/0121-best-time-to-buy-and-sell-stock.go: -------------------------------------------------------------------------------- 1 | func maxProfit(prices []int) int { 2 | min := math.MaxUint32 3 | res := 0 4 | 5 | for _, price := range prices { 6 | if price > min { 7 | if price-min > res { 8 | res = price - min 9 | } 10 | } else { 11 | min = price 12 | } 13 | } 14 | 15 | return res 16 | } -------------------------------------------------------------------------------- /java/0343-integer-break.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int integerBreak(int n) { 3 | if (n < 4) return n - 1; 4 | 5 | int res = 1; 6 | 7 | while (n > 4) { 8 | n -= 3; 9 | res *= 3; 10 | } 11 | 12 | res *= n; 13 | return res; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /kotlin/0122-best-time-to-buy-and-sell-stock-ii.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun maxProfit(prices: IntArray): Int { 3 | var profit = 0 4 | for(i in 0 until prices.size-1){ 5 | if(prices[i+1] > prices[i]) profit += (prices[i+1] - prices[i]) 6 | } 7 | return profit 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /rust/1480-running-sum-of-1d-array.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn running_sum(nums: Vec) -> Vec { 3 | let mut total = 0; 4 | let mut arr = Vec::new(); 5 | for n in nums { 6 | total += n; 7 | arr.push(total); 8 | } 9 | return arr; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /swift/1929-concatenation-of-array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func getConcatenation(_ nums: [Int]) -> [Int] { 3 | var ans: [Int] = [] 4 | 5 | for i in 0..<2 { 6 | for n in nums { 7 | ans.append(n) 8 | } 9 | } 10 | 11 | return ans 12 | } 13 | } -------------------------------------------------------------------------------- /c/0058-length-of-last-word.c: -------------------------------------------------------------------------------- 1 | int lengthOfLastWord(char * s){ 2 | int len = 0; 3 | 4 | if(s[0] != ' ') len = 1; 5 | 6 | for(int i=1; i= 0; i-- { 3 | if digits[i] < 9 { 4 | digits[i] += 1 5 | return digits 6 | } 7 | digits[i] = 0 8 | } 9 | digits[0] = 1 10 | digits = append(digits, 0) 11 | return digits 12 | } -------------------------------------------------------------------------------- /go/0217-contains-duplicate.go: -------------------------------------------------------------------------------- 1 | func containsDuplicate(nums []int) bool { 2 | if len(nums) <= 1 { 3 | return false 4 | } 5 | 6 | xm := make(map[int]struct{}) 7 | 8 | for _, v := range nums { 9 | if _, ok := xm[v]; ok { 10 | return true 11 | } 12 | 13 | xm[v] = struct{}{} 14 | } 15 | 16 | return false 17 | } 18 | -------------------------------------------------------------------------------- /go/0560-subarray-sum-equals-k.go: -------------------------------------------------------------------------------- 1 | func subarraySum(nums []int, k int) int { 2 | prefix := map[int]int{0: 1} 3 | curSum := 0 4 | count := 0 5 | for _, n := range nums { 6 | curSum += n 7 | if _, ok := prefix[curSum-k]; ok { 8 | count += prefix[curSum-k] 9 | } 10 | prefix[curSum]++ 11 | } 12 | return count 13 | } 14 | -------------------------------------------------------------------------------- /java/1929-concatenation-of-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] getConcatenation(int[] nums) { 3 | int[] ans = new int[nums.length*2]; 4 | for(int i=0;i (b + a).compareTo(a + b) } ) 5 | return if(strs[0][0] == '0') "0" else strs.joinToString("") 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /python/0026-remove-duplicates-from-sorted-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums: List[int]) -> int: 3 | L = 1 4 | 5 | for R in range(1, len(nums)): 6 | if nums[R] != nums[R - 1]: 7 | nums[L] = nums[R] 8 | L += 1 9 | return L 10 | -------------------------------------------------------------------------------- /swift/0027-Remove-Element.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func removeElement(_ nums: inout [Int], _ val: Int) -> Int { 3 | var count: Int = 0 4 | 5 | for i in nums where i != val { 6 | nums[count] = i 7 | count += 1 8 | } 9 | 10 | return count 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /swift/0027-remove-element.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func removeElement(_ nums: inout [Int], _ val: Int) -> Int { 3 | var count: Int = 0 4 | 5 | for i in nums where i != val { 6 | nums[count] = i 7 | count += 1 8 | } 9 | 10 | return count 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /swift/0509-fibonacci-number.swift: -------------------------------------------------------------------------------- 1 | /** 2 | * Question Link: https://leetcode.com/problems/fibonacci-number/ 3 | */ 4 | 5 | class Solution { 6 | func fib(_ n: Int) -> Int { 7 | let goldenRatio = (1 + 5.0.squareRoot()) / 2.0 8 | return Int(round(pow(goldenRatio, Double(n)) / 5.0.squareRoot())) 9 | } 10 | } -------------------------------------------------------------------------------- /typescript/0392-is-subsequence.ts: -------------------------------------------------------------------------------- 1 | function isSubsequence(s: string, t: string): boolean { 2 | let i = 0; 3 | let j = 0; 4 | 5 | while (i < s.length && j < t.length) { 6 | if (s[i] === t[j]) { 7 | i += 1; 8 | } 9 | j += 1; 10 | } 11 | 12 | return i === s.length; 13 | } 14 | -------------------------------------------------------------------------------- /java/0201-bitwise-and-of-numbers-range.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rangeBitwiseAnd(int left, int right) { 3 | int i = 0; 4 | while(left != right){ 5 | left = left >> 1; 6 | right = right >> 1; 7 | i += 1; 8 | } 9 | return left << i; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/0268-missing-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int missingNumber(int[] nums) { 4 | int sum = 0; 5 | int total = nums.length * (nums.length + 1) / 2; 6 | for (int i = 0; i < nums.length; i++) { 7 | sum += nums[i]; 8 | } 9 | return total - sum; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/1846-maximum-element-after-decreasing-and-rearranging.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maximumElementAfterDecrementingAndRearranging(int[] arr) { 3 | Arrays.sort(arr); 4 | int prev = 0; 5 | for(int n: arr) 6 | prev = Math.min(prev + 1, n); 7 | return prev; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /javascript/0179-largest-number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {string} 4 | */ 5 | var largestNumber = function (nums) { 6 | let largest = nums 7 | .map((n) => n.toString()) 8 | .sort((x, y) => y + x - (x + y)) 9 | .join(''); 10 | return largest[0] === '0' ? '0' : largest; 11 | }; 12 | -------------------------------------------------------------------------------- /kotlin/0053-maximum-subarray.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun maxSubArray(nums: IntArray): Int { 3 | var sum = nums[0] 4 | var currsum = 0 5 | for (num in nums) { 6 | currsum = maxOf(currsum + num, num) 7 | sum = maxOf(currsum, sum) 8 | } 9 | return sum 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /python/0053-maximum-subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | res = nums[0] 4 | 5 | total = 0 6 | for n in nums: 7 | total += n 8 | res = max(res, total) 9 | if total < 0: 10 | total = 0 11 | return res 12 | -------------------------------------------------------------------------------- /python/1930-unique-length-3-palindromic-subsequences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPalindromicSubsequence(self, s: str) -> int: 3 | count = 0 4 | chars = set(s) 5 | for char in chars: 6 | first,last = s.find(char),s.rfind(char) 7 | count += len(set(s[first+1:last])) 8 | return count -------------------------------------------------------------------------------- /python/1985-find-the-kth-largest-integer-in-the-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthLargestNumber(self, nums: List[str], k: int) -> str: 3 | maxHeap = [-int(n) for n in nums] 4 | heapq.heapify(maxHeap) 5 | while k>1: 6 | heapq.heappop(maxHeap) 7 | k-=1 8 | return str(-maxHeap[0]) 9 | -------------------------------------------------------------------------------- /cpp/0344-Reverse-String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reverseString(vector& s) { 4 | int left = 0, right = s.size() - 1; 5 | 6 | while (left < right){ 7 | swap(s[left], s[right]); 8 | 9 | left++; 10 | right--; 11 | } 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /cpp/0344-reverse-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reverseString(vector& s) { 4 | int left = 0, right = s.size() - 1; 5 | 6 | while (left < right){ 7 | swap(s[left], s[right]); 8 | 9 | left++; 10 | right--; 11 | } 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /csharp/0929-unique-email-addresses.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int NumUniqueEmails(string[] emails) 3 | => emails.Select(x => x.Split('@')). 4 | Select(split => split[0]. 5 | Split('+')[0]. 6 | Replace(".", "") + "@" + split[1]). 7 | Distinct(). 8 | Count(); 9 | } -------------------------------------------------------------------------------- /go/0187-repeated-dna-sequences.go: -------------------------------------------------------------------------------- 1 | func findRepeatedDnaSequences(s string) []string { 2 | seen, res := map[string]bool{}, map[string]bool{} 3 | 4 | for l := range len(s) - 9 { 5 | cur := s[l : l+10] 6 | if seen[cur] { 7 | res[cur] = true 8 | } 9 | seen[cur] = true 10 | } 11 | return slices.Collect(maps.Keys(res)) 12 | } 13 | -------------------------------------------------------------------------------- /go/1512-number-of-good-pairs.go: -------------------------------------------------------------------------------- 1 | func numIdenticalPairs(nums []int) int { 2 | pairs := 0 3 | 4 | for i := 0; i < len(nums); i++ { 5 | for j := i+1; j < len(nums); j++ { 6 | if nums[i] == nums[j] { 7 | pairs++ 8 | } 9 | } 10 | } 11 | 12 | return pairs 13 | } 14 | 15 | -------------------------------------------------------------------------------- /go/1929-concatenation-of-array.go: -------------------------------------------------------------------------------- 1 | func getConcatenation(nums []int) []int { 2 | n := len(nums) 3 | ans := make([]int, 2*n) //lets make an array of int type and 2*n size 4 | i := 0 5 | for i < n { //implementing for loop for the given condition 6 | ans[i] = nums[i] 7 | ans[i+n] = nums[i] 8 | i++ 9 | } 10 | return ans 11 | } 12 | -------------------------------------------------------------------------------- /go/1963-minimum-number-of-swaps-to-make-the-string-balanced.go: -------------------------------------------------------------------------------- 1 | func minSwaps(s string) int { 2 | close, maxClose := 0, 0 3 | for _, c := range s { 4 | if c == '[' { 5 | close += -1 6 | } else { 7 | close += +1 8 | } 9 | 10 | if close > maxClose { 11 | maxClose = close 12 | } 13 | } 14 | return (maxClose + 1) / 2 15 | } -------------------------------------------------------------------------------- /kotlin/0168-excel-sheet-column-title.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun convertToTitle(_cN: Int) = buildString { 3 | var cN = _cN 4 | while (cN > 0) { 5 | val rem = (cN - 1) % 26 6 | val char = 'A' + rem 7 | insert(0, char) 8 | cN = (cN - 1) / 26 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /python/1822-sign-of-the-product-of-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arraySign(self, nums: List[int]) -> int: 3 | flag = True 4 | for i in nums: 5 | if i == 0: 6 | return 0 7 | if i < 0: 8 | flag = not flag 9 | 10 | return 1 if flag else -1 11 | -------------------------------------------------------------------------------- /ruby/0338-counting-bits.rb: -------------------------------------------------------------------------------- 1 | def count_bits(n) 2 | bits = [] 3 | offset = 2 4 | (n + 1).times do |nbr| 5 | bits << if nbr <= 2 || nbr == (offset * 2) 6 | nbr.zero? ? 0 : 1 7 | else 8 | (bits[offset] + bits[nbr - offset]) 9 | end 10 | 11 | offset *= 2 if nbr == offset * 2 12 | end 13 | bits 14 | end 15 | -------------------------------------------------------------------------------- /typescript/0026-remove-duplicates-from-sorted-array.ts: -------------------------------------------------------------------------------- 1 | function removeDuplicates(nums: number[]): number { 2 | let k = 1; 3 | 4 | for (let i = 1; i < nums.length; i++) { 5 | if (nums[i] !== nums[i - 1]) { 6 | nums[k] = nums[i]; 7 | k += 1; 8 | } 9 | } 10 | 11 | return k; 12 | } 13 | -------------------------------------------------------------------------------- /csharp/0179-largest-number.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public string LargestNumber(int[] nums) 3 | { 4 | if(nums.All(_ => _ == 0)) return "0"; 5 | 6 | var s = nums.Select(_ => _.ToString()).ToList(); 7 | 8 | s.Sort((a, b) => (b+a).CompareTo(a+b)); 9 | 10 | return string.Concat(s); 11 | } 12 | } -------------------------------------------------------------------------------- /csharp/0217-contains-duplicate.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool ContainsDuplicate(int[] nums) { 3 | HashSet set = new HashSet(); 4 | 5 | foreach (int x in nums){ 6 | if (set.Contains(x)) return true; 7 | set.Add(x); 8 | } 9 | return false; 10 | } 11 | } -------------------------------------------------------------------------------- /go/0179-largest-number.go: -------------------------------------------------------------------------------- 1 | func largestNumber(nums []int) string { 2 | ans, s := "", make([]string, len(nums)) 3 | for i, num := range nums { s[i] = strconv.Itoa(num) } 4 | sort.Slice(s, func(a, b int) bool { return s[a] + s[b] > s[b] + s[a] }) 5 | if s[0] == "0" { return "0" } 6 | for _, v := range s { ans += v } 7 | return ans 8 | } -------------------------------------------------------------------------------- /go/0881-boats-to-save-people.go: -------------------------------------------------------------------------------- 1 | func numRescueBoats(people []int, limit int) int { 2 | sort.Ints(people) 3 | 4 | res := 0 // boats 5 | l, r := 0, len(people)-1 6 | for l <= r { 7 | remain := limit - people[r] 8 | r -= 1 9 | res += 1 10 | if l <= r && remain >= people[l] { 11 | l += 1 12 | } 13 | } 14 | return res 15 | } 16 | -------------------------------------------------------------------------------- /java/0055-jump-game.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean canJump(int[] nums) { 4 | int goal = nums.length - 1; 5 | for (int i = nums.length - 2; i >= 0; i--) { 6 | if (nums[i] + i >= goal) { 7 | goal = i; 8 | } 9 | } 10 | return goal == 0; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /java/0226-invert-binary-tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public TreeNode invertTree(TreeNode root) { 4 | if (root == null) return null; 5 | TreeNode node = new TreeNode(root.val); 6 | node.right = invertTree(root.left); 7 | node.left = invertTree(root.right); 8 | return node; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /javascript/2620-counter.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {Function} counter 4 | */ 5 | var createCounter = function(n) { 6 | return function() { 7 | return n++; 8 | }; 9 | }; 10 | 11 | /** 12 | * const counter = createCounter(10) 13 | * counter() // 10 14 | * counter() // 11 15 | * counter() // 12 16 | * 17 | -------------------------------------------------------------------------------- /javascript/2635-apply-transform-over-each-element-in-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {Function} fn 4 | * @return {number[]} 5 | */ 6 | const map = (arr, fn) => { 7 | const result = []; 8 | for (let i = 0; i < arr.length; i++) { 9 | result.push(fn(arr[i], i)); 10 | } 11 | return result; 12 | }; 13 | -------------------------------------------------------------------------------- /kotlin/1845-seat-reservation-manager.kt: -------------------------------------------------------------------------------- 1 | class SeatManager(n: Int) { 2 | val unres = PriorityQueue() 3 | 4 | init { 5 | for (i in 1..n) 6 | unres.add(i) 7 | } 8 | 9 | fun reserve() = unres.poll() 10 | 11 | fun unreserve(seatNumber: Int) { 12 | unres.add(seatNumber) 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /python/0001-two-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | prevMap = {} # val -> index 4 | 5 | for i, n in enumerate(nums): 6 | diff = target - n 7 | if diff in prevMap: 8 | return [prevMap[diff], i] 9 | prevMap[n] = i 10 | -------------------------------------------------------------------------------- /go/0007-reverse-integer.go: -------------------------------------------------------------------------------- 1 | func reverse(x int) int { 2 | negative := x < 0 3 | num := 0 4 | 5 | if negative { 6 | x = -x 7 | } 8 | 9 | for x > 0 { 10 | if math.MaxInt32/10 < num { 11 | return 0 12 | } 13 | 14 | num = 10*num + x%10 15 | x /= 10 16 | } 17 | 18 | if negative { 19 | return -num 20 | } 21 | 22 | return num 23 | } -------------------------------------------------------------------------------- /go/0035-search-insert-position.go: -------------------------------------------------------------------------------- 1 | func searchInsert(nums []int, target int) int { 2 | low, high := 0, len(nums) 3 | for low < high { 4 | mid := low + (high - low)/2 5 | if target > nums[mid] { 6 | low = mid + 1 7 | } else { 8 | high = mid 9 | } 10 | } 11 | return low 12 | } 13 | -------------------------------------------------------------------------------- /go/0198-house-robber.go: -------------------------------------------------------------------------------- 1 | func rob(nums []int) int { 2 | dp := make([] int, len(nums)+2) 3 | 4 | for i := 2; i < len(dp); i++ { 5 | if dp[i-1] > dp[i-2] + nums[i-2] { 6 | dp[i] = dp[i-1] 7 | } else { 8 | dp[i] = dp[i-2] + nums[i-2] 9 | } 10 | } 11 | 12 | return dp[len(dp)-1] 13 | } -------------------------------------------------------------------------------- /java/0700-search-in-a-binary-search-tree.java: -------------------------------------------------------------------------------- 1 | public TreeNode searchBST(TreeNode root, int val) { 2 | if (root == null) { 3 | return root; 4 | } else if (root.val < val) { 5 | return searchBST(root.right, val); 6 | } else if (root.val > val) { 7 | return searchBST(root.left, val); 8 | } 9 | return root; 10 | } -------------------------------------------------------------------------------- /kotlin/0027-remove-element.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun removeElement(nums: IntArray, `val`: Int): Int { 3 | var pointer = 0 4 | for(n in nums){ 5 | if(n != `val`){ 6 | nums[pointer] = n 7 | pointer++ 8 | } 9 | } 10 | return pointer 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /python/0083-remove-duplicates-from-sorted-list.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: 3 | cur = head 4 | while cur: 5 | while cur.next and cur.next.val == cur.val: 6 | cur.next = cur.next.next 7 | cur = cur.next 8 | return head 9 | -------------------------------------------------------------------------------- /scala/0217-contains-duplicate.scala: -------------------------------------------------------------------------------- 1 | import scala.collection.mutable.HashSet 2 | 3 | object Solution { 4 | def containsDuplicate(nums: Array[Int]): Boolean = { 5 | var seen: HashSet[Int] = HashSet() 6 | for (num <- nums) { 7 | if (seen.contains(num)) return true 8 | seen.add(num) 9 | } 10 | return false 11 | } 12 | } -------------------------------------------------------------------------------- /cpp/1470-shuffle-the-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector shuffle(vector& nums, int n) { 4 | int lp = 0; 5 | int rp = n; 6 | int p = 0; 7 | vector shuffled(2*n); 8 | 9 | while (p < 2 * n) { 10 | shuffled[p++] = nums[lp++]; 11 | shuffled[p++] = nums[rp++]; 12 | } 13 | return shuffled; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /go/0605-can-place-flowers.go: -------------------------------------------------------------------------------- 1 | func canPlaceFlowers(flowerbed []int, n int) bool { 2 | f := append(append([]int{0}, flowerbed...), 0) 3 | 4 | for i := 1; i < len(f) - 1; i++ { 5 | if f[i - 1] == 0 && f[i] == 0 && f[i + 1] == 0 { 6 | f[i] = 1 7 | n -= 1 8 | } 9 | } 10 | return n <= 0 11 | } 12 | -------------------------------------------------------------------------------- /go/0852-peak-index-in-a-mountain-array.go: -------------------------------------------------------------------------------- 1 | func peakIndexInMountainArray(arr []int) int { 2 | left, right := 0, len(arr)-1 3 | res := -1 4 | 5 | for left <= right { 6 | mid := left + (right-left+1)/2 7 | 8 | if arr[mid-1] <= arr[mid] { 9 | left, res = mid+1, mid 10 | } else { 11 | right = mid - 1 12 | } 13 | } 14 | 15 | return res 16 | } -------------------------------------------------------------------------------- /java/0169-majority-element.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int majorityElement(int[] nums) { 3 | int res = 0, count = 0; 4 | 5 | for(int n: nums) { 6 | if(count == 0) 7 | res = n; 8 | count += (n == res? 1: -1); 9 | } 10 | 11 | return res; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/1461-check-if-a-string-contains-all-binary-codes-of-size-k.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean hasAllCodes(String s, int k) { 3 | Set set = new HashSet<>(); 4 | for (int i = 0; i <= s.length() - k; i++) { 5 | set.add(s.substring(i, i + k)); 6 | } 7 | return set.size() == Math.pow(2, k); 8 | } 9 | } -------------------------------------------------------------------------------- /java/2348-number-of-zero-filled-subarrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long zeroFilledSubarray(int[] nums) { 3 | long res = 0; 4 | long count = 0; 5 | for (int i : nums) { 6 | if (i != 0) count = 0; 7 | else count++; 8 | res += count; 9 | } 10 | return res; 11 | } 12 | } -------------------------------------------------------------------------------- /java/2433-find-the-original-array-of-prefix-xor.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] findArray(int[] pref) { 3 | int n = pref.length; 4 | int[] arr = new int[n]; 5 | arr[0] = pref[0]; 6 | 7 | for(int i = 1; i < n; i++) 8 | arr[i] = pref[i]^pref[i-1]; 9 | 10 | return arr; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /kotlin/0058-length-of-last-word.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun lengthOfLastWord(s: String): Int { 3 | var p = s.length-1 4 | while(s[p].isWhitespace()) p-- 5 | var count = 0 6 | while(p >= 0 && !s[p].isWhitespace()){ 7 | count++ 8 | p-- 9 | } 10 | return count 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /kotlin/1822-sign-of-the-product-of-an-array.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun arraySign(nums: IntArray): Int { 3 | var res = 1 4 | for (n in nums){ 5 | if (n == 0) 6 | return 0 7 | if (n < 0) 8 | res *= -1 9 | } 10 | return if (res > 0) 1 else -1 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /python/0120-triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumTotal(self, triangle: List[List[int]]) -> int: 3 | dp = triangle[-1] 4 | 5 | for row in range(len(triangle) - 2, -1, -1): 6 | for col in range(0, row + 1): 7 | dp[col] = triangle[row][col] + min(dp[col], dp[col + 1]) 8 | 9 | return dp[0] 10 | -------------------------------------------------------------------------------- /python/0344-reverse-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseString(self, s: List[str]) -> None: 3 | """ 4 | Do not return anything, modify s in-place instead. 5 | """ 6 | l = 0 7 | r = len(s) - 1 8 | while l < r: 9 | s[l],s[r] = s[r],s[l] 10 | l += 1 11 | r -= 1 12 | -------------------------------------------------------------------------------- /python/0349-intersection-of-two-arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 | seen = set(nums1) 4 | 5 | res = [] 6 | for n in nums2: 7 | if n in seen: 8 | res.append(n) 9 | seen.remove(n) 10 | return res 11 | -------------------------------------------------------------------------------- /python/1299-replace-elements-with-greatest-element-on-right-side.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def replaceElements(self, arr: List[int]) -> List[int]: 3 | rightMax = -1 4 | for i in range(len(arr) -1, -1, -1): 5 | newMax = max(rightMax, arr[i]) 6 | arr[i] = rightMax 7 | rightMax = newMax 8 | return arr 9 | -------------------------------------------------------------------------------- /rust/0371-sum-of-two-integers.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn get_sum(a: i32, b: i32) -> i32 { 3 | fn recurse(a: i32, b: i32) -> i32 { 4 | if (a & b) << 1 == 0 { 5 | return a ^ b; 6 | } 7 | 8 | recurse(a ^ b, (a & b) << 1) 9 | } 10 | 11 | recurse(a, b) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /swift/0055-jump-game.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func canJump(_ nums: [Int]) -> Bool { 3 | var goal = nums.count - 1 4 | 5 | for i in stride(from: nums.count-2, through: 0, by: -1){ 6 | if i + nums[i] >= goal { 7 | goal = i 8 | } 9 | } 10 | return goal == 0 11 | } 12 | } -------------------------------------------------------------------------------- /csharp/0191-number-of-1-bits.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int HammingWeight(uint n) { 3 | var binary = Convert.ToString(n, 2); 4 | var hammingWeight = 0; 5 | for (int i = 0; i < binary.Length; i++) 6 | { 7 | hammingWeight += binary[i] - '0'; 8 | } 9 | return hammingWeight; 10 | } 11 | } -------------------------------------------------------------------------------- /csharp/0198-house-robber.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int Rob(int[] nums) { 3 | int rob1 = 0, rob2 = 0; 4 | 5 | foreach(var num in nums) { 6 | var temp = Math.Max(num + rob1, rob2); 7 | rob1 = rob2; 8 | rob2 = temp; 9 | } 10 | 11 | return rob2; 12 | } 13 | } -------------------------------------------------------------------------------- /dart/0344-reverse-string.dart: -------------------------------------------------------------------------------- 1 | // Time Complexity: O(n) 2 | // Space Complexity: O(1) 3 | 4 | class Solution { 5 | void reverseString(List s) { 6 | var l = 0, r = s.length - 1; 7 | while (l <= r) { 8 | var tmp = s[l]; 9 | s[l] = s[r]; 10 | s[r] = tmp; 11 | l += 1; 12 | r -= 1; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /go/0189-rotate-array.go: -------------------------------------------------------------------------------- 1 | func rotate(nums []int, k int) { 2 | k = k % len(nums) 3 | reverse(nums, 0, len(nums) - 1) 4 | reverse(nums, 0, k - 1) 5 | reverse(nums, k, len(nums) - 1) 6 | } 7 | 8 | func reverse(nums []int, start, end int) { 9 | for start <= end { 10 | nums[start], nums[end] = nums[end], nums[start] 11 | start++ 12 | end-- 13 | } 14 | } -------------------------------------------------------------------------------- /kotlin/0242-valid-anagram.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun isAnagram(s: String, t: String): Boolean { 3 | if (s.length != t.length) return false 4 | val arr = Array(26) {0} 5 | for (i in s.indices) { 6 | arr[s[i] - 'a']++ 7 | arr[t[i] - 'a']-- 8 | } 9 | return arr.all{it == 0} 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /python/0121-best-time-to-buy-and-sell-stock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | res = 0 4 | 5 | lowest = prices[0] 6 | for price in prices: 7 | if price < lowest: 8 | lowest = price 9 | res = max(res, price - lowest) 10 | return res 11 | -------------------------------------------------------------------------------- /python/0442-find-all-duplicates-in-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicates(self, nums: List[int]) -> List[int]: 3 | res = [] 4 | 5 | for n in nums: 6 | n = abs(n) 7 | if nums[n - 1] < 0: 8 | res.append(n) 9 | nums[n - 1] = -nums[n - 1] 10 | 11 | return res 12 | -------------------------------------------------------------------------------- /ruby/0134-gas-station.rb: -------------------------------------------------------------------------------- 1 | def can_complete_circuit(gas, cost) 2 | return -1 if gas.sum < cost.sum 3 | 4 | total = start = 0 5 | 6 | (0..gas.size()-1).each do |i| 7 | total += (gas[i] - cost[i]) 8 | if (total < 0) 9 | total = 0 10 | start = i +1 11 | end 12 | end 13 | 14 | return start 15 | end -------------------------------------------------------------------------------- /rust/1929-concatenation-of-array.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn get_concatenation(nums: Vec) -> Vec { 3 | let n = nums.len(); 4 | let mut ans = vec![0; 2 * n]; 5 | 6 | for i in 0..nums.len() { 7 | ans[i] = nums[i]; 8 | ans[i + n] = nums[i]; 9 | } 10 | 11 | ans 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /swift/0263-ugly-number.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func isUgly(_ n: Int) -> Bool { 3 | if n <= 0 { 4 | return false 5 | } 6 | 7 | var num = n 8 | for p in [2, 3, 5] { 9 | while num % p == 0 { 10 | num /= p 11 | } 12 | } 13 | return num == 1 14 | } 15 | } -------------------------------------------------------------------------------- /swift/0283-Move-Zeroes.Swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func moveZeroes(_ nums: inout [Int]) { 3 | var index: Int = 0 4 | 5 | for num in nums where num != 0 { 6 | nums[index] = num 7 | index += 1 8 | } 9 | 10 | for i in index.. a[1] - a[0] - (b[1] - b[0])); 3 | 4 | let totalCost = 0; 5 | let n = costs.length / 2; 6 | for (let i = 0; i < n; i++) { 7 | totalCost += costs[i][1] + costs[i + n][0]; 8 | } 9 | return totalCost; 10 | } 11 | -------------------------------------------------------------------------------- /dart/0226-invert-binary-tree.dart: -------------------------------------------------------------------------------- 1 | class Solution { 2 | TreeNode? invertTree(TreeNode? root) { 3 | if (root == null) { 4 | return null; 5 | } 6 | 7 | var tmp = root.left; 8 | root.left = root.right; 9 | root.right = tmp; 10 | 11 | invertTree(root.left); 12 | invertTree(root.right); 13 | 14 | return root; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /go/0075-sort-colors.go: -------------------------------------------------------------------------------- 1 | func sortColors(nums []int) { 2 | low, mid, hi := 0, 0, len(nums)-1 3 | 4 | for low <= hi { 5 | if nums[low] == 2 { 6 | nums[low], nums[hi] = nums[hi], nums[low] 7 | hi-- 8 | } else if nums[low] == 0 { 9 | nums[low], nums[mid] = nums[mid], nums[low] 10 | mid++ 11 | low++ 12 | } else { 13 | low++ 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /java/0190-reverse-bits.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | // you need treat n as an unsigned value 4 | public int reverseBits(int n) { 5 | int ans = 0; 6 | 7 | for (int i = 0; i < 32; i++) { 8 | ans <<= 1; 9 | ans |= (n & 1); 10 | n >>= 1; 11 | } 12 | return ans; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /javascript/2621-sleep.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} millis 3 | * @return {Promise} 4 | */ 5 | async function sleep(millis) { 6 | return new Promise((resolve) => 7 | setTimeout(() => resolve('Completed!'), millis), 8 | ); 9 | } 10 | 11 | /** 12 | * let t = Date.now() 13 | * sleep(100).then(() => console.log(Date.now() - t)) // 100 14 | */ 15 | -------------------------------------------------------------------------------- /kotlin/1984-minimum-difference-between-highest-and-lowest-of-k-scores.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun minimumDifference(nums: IntArray, k: Int): Int { 3 | nums.sort() 4 | var min = Integer.MAX_VALUE 5 | for(i in 0..nums.size-k) { 6 | min = minOf(min, nums[i+k-1]-nums[i]) 7 | } 8 | return min 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /python/0509-fibonacci-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | Memo = {} 3 | 4 | def fib(self, n: int): 5 | if n in self.Memo: 6 | return self.Memo[n] 7 | if n == 0: 8 | return 0 9 | if n == 1: 10 | return 1 11 | self.Memo[n] = self.fib(n - 1) + self.fib(n - 2) 12 | return self.Memo[n] 13 | -------------------------------------------------------------------------------- /python/0876-middle-of-the-linked-list.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: 3 | if not head or not head.next: 4 | return head 5 | 6 | slow = fast = head 7 | while fast and fast.next: 8 | slow, fast = slow.next, fast.next.next 9 | 10 | return slow 11 | -------------------------------------------------------------------------------- /ruby/0045-jump-game-ii.rb: -------------------------------------------------------------------------------- 1 | def jump(nums) 2 | 3 | result = 0 4 | l = r = 0 5 | 6 | while (r< nums.size()-1) 7 | farthest = 0 8 | (l..r).each do |i| 9 | farthest = [farthest,(i + nums[i])].max 10 | end 11 | l= r+1 12 | r = farthest 13 | result +=1 14 | end 15 | 16 | return result 17 | end -------------------------------------------------------------------------------- /scala/0058-length-of-last-word.scala: -------------------------------------------------------------------------------- 1 | object Solution { 2 | def lengthOfLastWord(s: String): Int = { 3 | var i = s.length - 1 4 | var length = 0 5 | 6 | while (s(i) == ' ') { 7 | i -= 1 8 | } 9 | 10 | while (i >= 0 && s(i) != ' ') { 11 | length += 1 12 | i -= 1 13 | } 14 | 15 | length 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /swift/0746-min-cost-climbing-stairs.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func minCostClimbingStairs(_ cost: [Int]) -> Int { 3 | var stepsCost = cost 4 | for i in stride(from: cost.count - 3, through: 0, by: -1) { 5 | stepsCost[i] += min(stepsCost[i + 1], stepsCost[i + 2]) 6 | } 7 | return min(stepsCost[0], stepsCost[1]) 8 | } 9 | } -------------------------------------------------------------------------------- /dart/1299-replace-elements-with-greatest-element-on-right-side.dart: -------------------------------------------------------------------------------- 1 | class Solution { 2 | List replaceElements(List arr) { 3 | var curMax = -1; 4 | for (int i = arr.length - 1; i > -1; i--) { 5 | int newMax = max(curMax, arr[i]); 6 | arr[i] = curMax; 7 | curMax = newMax; 8 | } 9 | return arr; 10 | } 11 | } -------------------------------------------------------------------------------- /go/0045-jump-game-ii.go: -------------------------------------------------------------------------------- 1 | func jump(nums []int) int { 2 | step, end, max := 0, 0, 0 3 | 4 | for i := 0; i < len(nums)-1; i++ { 5 | if i + nums[i] > max { 6 | max = i+nums[i] 7 | } 8 | 9 | if i == end { 10 | step++; 11 | end = max 12 | } 13 | } 14 | 15 | return step 16 | } -------------------------------------------------------------------------------- /java/0344-reverse-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void reverseString(char[] s) { 3 | //Do not return anything, modify s in-place instead. 4 | int l = 0; 5 | int r = s.length - 1; 6 | while(l <= r) { 7 | char tmp = s[l]; 8 | s[l++] = s[r]; 9 | s[r--] = tmp; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /kotlin/0371-sum-of-two-integers.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun getSum(a: Int, b: Int): Int { 3 | var a1 = a 4 | var b1 = b 5 | var carry = a1.and(b1) 6 | while (carry != 0) { 7 | b1 = a1.xor(b1) 8 | a1 = carry.shl(1) 9 | carry = a1.and(b1) 10 | } 11 | return a1.xor(b1) 12 | } 13 | } -------------------------------------------------------------------------------- /kotlin/0392-is-subsequence.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun isSubsequence(s: String, t: String): Boolean { 3 | var sIndex = 0 4 | var tIndex = 0 5 | while(sIndex < s.length && tIndex < t.length){ 6 | if(s[sIndex] == t[tIndex]) sIndex++ 7 | tIndex++ 8 | } 9 | return sIndex == s.length 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /kotlin/1637-widest-vertical-area-between-two-points-containing-no-points.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun maxWidthOfVerticalArea(points: Array): Int { 3 | points.sortBy { it[0] } 4 | var res = -1 5 | for (i in 1 until points.size) 6 | res = maxOf(res, points[i][0] - points[i - 1][0]) 7 | return res 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /python/1845-seat-reservation-manager.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class SeatManager: 4 | 5 | def __init__(self, n: int): 6 | self.seats = [i for i in range(1, n + 1)] 7 | 8 | def reserve(self) -> int: 9 | return heapq.heappop(self.seats) 10 | 11 | def unreserve(self, seatNumber: int) -> None: 12 | heapq.heappush(self.seats, seatNumber) -------------------------------------------------------------------------------- /typescript/0053-maximum-subarray.ts: -------------------------------------------------------------------------------- 1 | function maxSubArray(nums: number[]): number { 2 | let maxSub = nums[0]; 3 | let curSum = 0; 4 | 5 | for (const n of nums) { 6 | if (curSum < 0) { 7 | curSum = 0; 8 | } 9 | curSum += n; 10 | maxSub = Math.max(maxSub, curSum); 11 | } 12 | 13 | return maxSub; 14 | } 15 | -------------------------------------------------------------------------------- /go/0238-product-of-array-except-self.go: -------------------------------------------------------------------------------- 1 | func productExceptSelf(nums []int) []int { 2 | res := make([]int, len(nums)) 3 | 4 | prefix := 1 5 | for i, num := range nums { 6 | res[i] = prefix 7 | prefix *= num 8 | } 9 | 10 | postfix := 1 11 | for i := len(nums) - 1; i >= 0; i-- { 12 | res[i] *= postfix 13 | postfix *= nums[i] 14 | } 15 | return res 16 | } 17 | -------------------------------------------------------------------------------- /go/0926-flip-string-to-monotone-increasing.go: -------------------------------------------------------------------------------- 1 | func minFlipsMonoIncr(s string) int { 2 | res, countOne := 0, 0 3 | 4 | for _, ch := range s { 5 | if ch == '1' { 6 | countOne++ 7 | } else { 8 | res = min(res+1, countOne) 9 | } 10 | } 11 | 12 | return res 13 | } 14 | 15 | func min(a, b int) int { 16 | if a < b { 17 | return a 18 | } 19 | return b 20 | } -------------------------------------------------------------------------------- /go/1968-array-with-elements-not-equal-to-average-of-neighbors.go: -------------------------------------------------------------------------------- 1 | func rearrangeArray(nums []int) []int { 2 | sort.Ints(nums) 3 | res := []int{} 4 | 5 | l, r := 0, len(nums)-1 6 | for len(res) != len(nums) { 7 | res = append(res, nums[l]) 8 | l += 1 9 | 10 | if l <= r { 11 | res = append(res, nums[r]) 12 | r -= 1 13 | } 14 | } 15 | return res 16 | } 17 | -------------------------------------------------------------------------------- /javascript/2390-removing-stars-from-a-string.js: -------------------------------------------------------------------------------- 1 | var removeStars = function (s) { 2 | if (!s.length) return ''; 3 | 4 | const result = []; 5 | 6 | for (let char of s) { 7 | if (char == '*') result.pop(); 8 | else result.push(char); 9 | } 10 | return result.join(''); 11 | }; 12 | // Time Complexity: O(n) 13 | // Space Complexity: O(n) 14 | -------------------------------------------------------------------------------- /kotlin/0066-plus-one.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun plusOne(digits: IntArray): IntArray { 3 | for (i in digits.size-1 downTo 0) { 4 | digits[i] += 1 5 | 6 | if (digits[i] <= 9) 7 | return digits 8 | 9 | digits[i] = 0 10 | } 11 | 12 | return IntArray(digits.size+1).also{ it[0] = 1 } 13 | } 14 | } -------------------------------------------------------------------------------- /kotlin/0070-climbing-stairs.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun climbStairs(n: Int): Int { 3 | if (n <= 3) { 4 | return n 5 | } 6 | var n1 = 2 7 | var n2 = 3 8 | 9 | for (i in 4..n) { 10 | val temp = n1 + n2 11 | n1 = n2 12 | n2 = temp 13 | } 14 | return n2 15 | } 16 | } -------------------------------------------------------------------------------- /kotlin/0120-triangle.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun minimumTotal(triangle: List>): Int { 3 | val dp = IntArray(triangle.last().size + 1) 4 | 5 | for (row in triangle.reversed()) { 6 | for ((i,n) in row.withIndex()) 7 | dp[i] = minOf(dp[i], dp[i + 1]) + n 8 | } 9 | 10 | return dp[0] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /kotlin/1603-design-parking-system.kt: -------------------------------------------------------------------------------- 1 | class ParkingSystem(big: Int, medium: Int, small: Int) { 2 | 3 | val spaces = intArrayOf(big, medium, small) 4 | 5 | fun addCar(carType: Int): Boolean { 6 | if (spaces[carType - 1] > 0) { 7 | spaces[carType - 1]-- 8 | return true 9 | } 10 | return false 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /python/0069-sqrtx.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mySqrt(self, x: int) -> int: 3 | l, r = 0, x 4 | while l <= r: 5 | mid = (l + r) // 2 6 | if mid * mid == x: 7 | return mid 8 | if mid * mid < x: 9 | l = mid + 1 10 | else: 11 | r = mid - 1 12 | return r 13 | -------------------------------------------------------------------------------- /ruby/0191-number-of-1-bits.rb: -------------------------------------------------------------------------------- 1 | def hamming_weight(n) 2 | total_ones = 0 3 | until n.zero? 4 | total_ones += (n % 2) 5 | n = n >> 1 6 | end 7 | total_ones 8 | end 9 | 10 | # Solution utilizing & (n - 1) 11 | def hamming_weight(n) 12 | total_ones = 0 13 | until n.zero? 14 | n &= (n - 1) 15 | total_ones += 1 16 | end 17 | total_ones 18 | end 19 | -------------------------------------------------------------------------------- /swift/0070-climbing-stairs.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func climbStairs(_ n: Int) -> Int { 3 | if n <= 3 { 4 | return n 5 | } 6 | var n1 = 2 7 | var n2 = 3 8 | 9 | for i in 4...n { 10 | let temp = n1 + n2 11 | n1 = n2 12 | n2 = temp 13 | } 14 | return n2 15 | } 16 | } -------------------------------------------------------------------------------- /swift/0371-sum-of-two-integers.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func getSum(_ a: Int, _ b: Int) -> Int { 3 | var res = a 4 | var secondInt = b 5 | 6 | while secondInt != 0 { 7 | let temp = (res & secondInt) << 1 8 | res ^= secondInt 9 | secondInt = temp 10 | } 11 | return res 12 | } 13 | } -------------------------------------------------------------------------------- /cpp/0280-wiggle-sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Time: O(n) 3 | Space: O(1) 4 | */ 5 | 6 | class Solution { 7 | public: 8 | void wiggleSort(vector &nums) { 9 | for(int i=1; i nums[i-1]))) 11 | swap(nums[i], nums[i-1]); 12 | } 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /go/0287-find-the-duplicate-number.go: -------------------------------------------------------------------------------- 1 | func findDuplicate(nums []int) int { 2 | slow, fast := nums[0], nums[nums[0]] 3 | 4 | for slow != fast { 5 | slow = nums[slow] 6 | fast = nums[nums[fast]] 7 | } 8 | 9 | slow = 0 10 | for slow != fast { 11 | slow = nums[slow] 12 | fast = nums[fast] 13 | } 14 | return slow 15 | } -------------------------------------------------------------------------------- /java/1572-matrix-diagonal-sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int diagonalSum(int[][] mat) { 3 | int res = 0; 4 | int n = mat.length; 5 | 6 | for (int i = 0; i < n; i++) { 7 | res += mat[i][i]; 8 | res += mat[i][n - 1 - i]; 9 | } 10 | 11 | return res - (n % 2 == 1 ? mat[n / 2][n / 2] : 0); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /kotlin/0009-palindrome-number.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun isPalindrome(x: Int): Boolean { 3 | if (x < 0) return false 4 | 5 | var reverse = 0 6 | var x2 = x 7 | while (x2 != 0) { 8 | reverse *= 10 9 | reverse += x2 % 10 10 | x2 /= 10 11 | } 12 | 13 | return reverse == x 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /kotlin/0338-counting-bits.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun countBits(n: Int): IntArray { 3 | var dp = IntArray(n + 1) 4 | var offset = 1 5 | 6 | for (i in 1..n) { 7 | if (offset * 2 == i) { 8 | offset = i 9 | } 10 | dp[i] = 1 + dp[i - offset] 11 | } 12 | return dp 13 | } 14 | } -------------------------------------------------------------------------------- /python/0058-length-of-last-word.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | """ 4 | one shortcut 5 | """ 6 | # return len(s.split()[-1]) 7 | count = 0 8 | for i in range(len(s) - 1, -1, -1): 9 | char = s[i] 10 | if char == " ": 11 | if count >= 1: 12 | return count 13 | else: 14 | count += 1 15 | return count 16 | -------------------------------------------------------------------------------- /ruby/0046-permutations.rb: -------------------------------------------------------------------------------- 1 | def permute(nums) 2 | return [[]] if nums.empty? 3 | 4 | perms = [] 5 | 6 | (0...nums.length).each do |i| 7 | el = nums[i] 8 | rest = nums.take(i) + nums.drop(i + 1) 9 | new_perms = permute(rest).map { |perm| perm.unshift(el) } 10 | perms.concat(new_perms) 11 | end 12 | 13 | perms 14 | end -------------------------------------------------------------------------------- /c/0069-sqrtx.c: -------------------------------------------------------------------------------- 1 | int mySqrt(int x){ 2 | int l = 0; 3 | int r = x; 4 | 5 | while(l <= r){ 6 | long int m = (l + r) / 2; 7 | if(m * m == x){ 8 | return m; 9 | } 10 | else if(m * m > x){ 11 | r = m - 1; 12 | } 13 | else{ 14 | l = m + 1; 15 | } 16 | } 17 | return r; 18 | } 19 | -------------------------------------------------------------------------------- /csharp/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] ReplaceElements(int[] arr) { 3 | int max = -1; 4 | for(int i = arr.Length-1; i >= 0; i--) { 5 | int newMax = Math.Max(arr[i], max); 6 | arr[i] = max; 7 | max = newMax; 8 | } 9 | return arr; 10 | } 11 | } -------------------------------------------------------------------------------- /csharp/1299-replace-elements-with-greatest-element-on-right-side.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] ReplaceElements(int[] arr) { 3 | int max = -1; 4 | for(int i = arr.Length-1; i >= 0; i--) { 5 | int newMax = Math.Max(arr[i], max); 6 | arr[i] = max; 7 | max = newMax; 8 | } 9 | return arr; 10 | } 11 | } -------------------------------------------------------------------------------- /dart/0217-contains-duplicate.dart: -------------------------------------------------------------------------------- 1 | // Time Complexity: O(n) 2 | // Space Complexity: O(n) 3 | 4 | class Solution { 5 | bool containsDuplicate(List nums) { 6 | Set hashSet = Set(); 7 | for (int n in nums) { 8 | if (hashSet.contains(n)) { 9 | return true; 10 | } 11 | hashSet.add(n); 12 | } 13 | return false; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /go/0647-palindromic-substrings.go: -------------------------------------------------------------------------------- 1 | func countSubstrings(s string) int { 2 | n := len(s) 3 | pal := func(l, r int) int { 4 | count := 0 5 | for l >= 0 && r < n && s[l] == s[r] { 6 | count++ 7 | l-- 8 | r++ 9 | } 10 | return count 11 | } 12 | 13 | count := 0 14 | for i := range s { 15 | count += pal(i, i) 16 | count += pal(i, i+1) 17 | } 18 | return count 19 | } -------------------------------------------------------------------------------- /java/0058-length-of-last-word.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLastWord(String s) { 3 | int i = s.length() - 1, length = 0; 4 | while (s.charAt(i) == ' ') { 5 | i -= 1; 6 | } 7 | while (i >= 0 && s.charAt(i) != ' ') { 8 | length += 1; 9 | i -= 1; 10 | } 11 | return length; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /kotlin/0349-intersection-of-two-arrays.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun intersection(nums1: IntArray, nums2: IntArray): IntArray { 3 | val seen = nums1.toSet() 4 | 5 | val res = mutableSetOf () 6 | for (n in nums2) { 7 | if (n in seen) 8 | res.add(n) 9 | } 10 | 11 | return res.toIntArray() 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /kotlin/1572-matrix-diagonal-sum.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun diagonalSum(mat: Array): Int { 3 | val n = mat.lastIndex 4 | 5 | var sum = 0 6 | for (i in 0..n) { 7 | sum += mat[i][i] + mat[n - i][i] 8 | } 9 | 10 | if (n % 2 == 0) 11 | sum -= mat[n/2][n/2] 12 | 13 | return sum 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /python/0300-longest-increasing-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLIS(self, nums: List[int]) -> int: 3 | LIS = [1] * len(nums) 4 | 5 | for i in range(len(nums) - 1, -1, -1): 6 | for j in range(i + 1, len(nums)): 7 | if nums[i] < nums[j]: 8 | LIS[i] = max(LIS[i], 1 + LIS[j]) 9 | return max(LIS) 10 | -------------------------------------------------------------------------------- /python/2017-grid-game.py: -------------------------------------------------------------------------------- 1 | # Time: O(n) Space: O(1) 2 | 3 | class Solution(object): 4 | def gridGame(self, grid): 5 | result = float("inf") 6 | left, right = 0, sum(grid[0]) 7 | 8 | for a, b in zip(grid[0], grid[1]): 9 | right -= a 10 | result = min(result, max(left, right)) 11 | left += b 12 | return result 13 | -------------------------------------------------------------------------------- /ruby/0703-kth-largest-element-in-a-stream.rb: -------------------------------------------------------------------------------- 1 | require "rb_heap" 2 | 3 | class KthLargest 4 | def initialize(k, nums) 5 | @k = k 6 | @heap = Heap.new 7 | nums.each { |num| @heap << num } 8 | @heap.pop until @heap.size <= @k 9 | end 10 | 11 | def add(val) 12 | @heap << val 13 | @heap.pop until @heap.size <= @k 14 | @heap.peak 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /cpp/1920-build-array-from-permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector buildArray(vector& nums){ 4 | vector ans; 5 | for(int & n : nums){ 6 | ans.push_back(nums[n]); 7 | } 8 | return ans; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /java/0026-remove-duplicates-from-sorted-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | int swap = 1; 4 | 5 | for(int i=1; i int: 3 | row = [1] * n 4 | 5 | for i in range(m - 1): 6 | newRow = [1] * n 7 | for j in range(n - 2, -1, -1): 8 | newRow[j] = newRow[j + 1] + row[j] 9 | row = newRow 10 | return row[0] 11 | 12 | # O(n * m) O(n) 13 | -------------------------------------------------------------------------------- /python/0724-find-pivot-index.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def pivotIndex(self, nums: List[int]) -> int: 3 | total = sum(nums) # O(n) 4 | 5 | leftSum = 0 6 | for i in range(len(nums)): 7 | rightSum = total - nums[i] - leftSum 8 | if leftSum == rightSum: 9 | return i 10 | leftSum += nums[i] 11 | return -1 12 | -------------------------------------------------------------------------------- /rust/0206-reverse-linked-list.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn reverse_list(mut head: Option>) -> Option> { 3 | let (mut prev, mut curr) = (None, head); 4 | while let Some(mut node) = curr{ 5 | curr = node.next; 6 | node.next = prev; 7 | prev = Some(node); 8 | } 9 | pre 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /typescript/0001-two-sum.ts: -------------------------------------------------------------------------------- 1 | function twoSum(nums: number[], target: number): number[] { 2 | let hash: { [key: number]: number } = {}; 3 | for (let i = 0; i < nums.length; i++) { 4 | let diff = target - nums[i]; 5 | if (diff in hash) { 6 | return [hash[diff], i]; 7 | } else { 8 | hash[nums[i]] = i; 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /typescript/0926-flip-string-to-monotone-increasing.ts: -------------------------------------------------------------------------------- 1 | function minFlipsMonoIncr(s: string): number { 2 | let res: number = 0; 3 | let countOne: number = 0; 4 | 5 | for (let ch of s) { 6 | if (ch == '1') { 7 | countOne++; 8 | } else { 9 | res = Math.min(res + 1, countOne); 10 | } 11 | } 12 | 13 | return res; 14 | } 15 | -------------------------------------------------------------------------------- /typescript/2390-removing-stars-from-a-string.ts: -------------------------------------------------------------------------------- 1 | function removeStars(s: string): string { 2 | if (!s.length) return ''; 3 | 4 | const result = []; 5 | 6 | for (let char of s) { 7 | if (char == '*') result.pop(); 8 | else result.push(char); 9 | } 10 | return result.join(''); 11 | } 12 | 13 | // Time Complexity: O(n) 14 | // Space Complexity: O(n) 15 | -------------------------------------------------------------------------------- /c/0344-reverse-string.c: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that reverses a string. The input string is given as an array of characters s. 3 | 4 | Space: O(1) 5 | Time: O(n) 6 | */ 7 | 8 | void reverseString(char* s, int sSize){ 9 | int h = sSize/2; 10 | for (int i=0; i= 0; i--){ 5 | if(num.charAt(i) % 2 != 0){ 6 | res = num.substring(0, i+1); 7 | break; 8 | } 9 | } 10 | return res; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /java/2971-find-polygon-with-the-largest-perimeter.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public long largestPerimeter(int[] nums) { 4 | Arrays.sort(nums); 5 | long res = -1, amt = 0; 6 | 7 | for (int i : nums) { 8 | if (amt > i) 9 | res = amt + i; 10 | amt += i; 11 | } 12 | 13 | return res; 14 | } 15 | } -------------------------------------------------------------------------------- /javascript/0374-guess-number-higher-or-lower.js: -------------------------------------------------------------------------------- 1 | var guessNumber = function (n) { 2 | let low = 1; 3 | let high = n; 4 | 5 | while (true) { 6 | let mid = low + Math.floor((high - low) / 2); 7 | let myGuess = guess(mid); 8 | if (myGuess == 1) low = mid + 1; 9 | else if (myGuess == -1) high = mid - 1; 10 | else return mid; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /javascript/1929-concatenation-of-array.js: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/concatenation-of-array/description/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @return {number[]} 6 | */ 7 | var getConcatenation = function (nums) { 8 | let res = []; 9 | for (let i = 0; i < nums.length * 2; i++) { 10 | res.push(nums[i % nums.length]); 11 | } 12 | return res; 13 | }; 14 | -------------------------------------------------------------------------------- /kotlin/0724-find-pivot-index.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun pivotIndex(nums: IntArray): Int { 3 | var leftSum = 0 4 | var rightSum = 0 5 | for(num in nums) rightSum += num 6 | for(i in nums.indices){ 7 | if(leftSum == rightSum - nums[i] - leftSum) return i 8 | leftSum += nums[i] 9 | } 10 | return -1 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /python/0205-isomorphic-strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isIsomorphic(self, s: str, t: str) -> bool: 3 | mapST, mapTS = {}, {} 4 | 5 | for c1, c2 in zip(s, t): 6 | if (c1 in mapST and mapST[c1] != c2) or (c2 in mapTS and mapTS[c2] != c1): 7 | return False 8 | mapST[c1] = c2 9 | mapTS[c2] = c1 10 | 11 | return True -------------------------------------------------------------------------------- /python/0997-find-the-town-judge.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findJudge(self, n: int, trust: List[List[int]]) -> int: 3 | delta = defaultdict(int) 4 | 5 | for src, dst in trust: 6 | delta[src] -= 1 7 | delta[dst] += 1 8 | 9 | for i in range(1, n + 1): 10 | if delta[i] == n - 1: 11 | return i 12 | return -1 13 | -------------------------------------------------------------------------------- /python/2390-removing-stars-from-a-string.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/removing-stars-from-a-string/submissions/1011668695/ 2 | class Solution(object) : 3 | def removeStars(self, s) : 4 | res = [] 5 | for c in s : 6 | if res and c == '*': 7 | res.pop() 8 | else: 9 | res.append(c) 10 | return ''.join(res) 11 | -------------------------------------------------------------------------------- /scala/1929-concatenation-of-array.scala: -------------------------------------------------------------------------------- 1 | object Solution { 2 | def getConcatenation(nums: Array[Int]): Array[Int] = { 3 | val n = nums.length 4 | val ans = new Array[Int](2 * n) 5 | 6 | for (i <- 0 until n) { 7 | ans(i) = nums(i) 8 | ans(i + n) = nums(i) 9 | } 10 | 11 | ans 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /swift/0053-maximum-subarray.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maxSubArray(_ nums: [Int]) -> Int { 3 | var res = nums[0] 4 | var total = 0 5 | 6 | for n in nums { 7 | total += n 8 | res = max(res, total) 9 | if total < 0 { 10 | total = 0 11 | } 12 | } 13 | return res 14 | } 15 | } -------------------------------------------------------------------------------- /typescript/0724-find-pivot-index.ts: -------------------------------------------------------------------------------- 1 | function pivotIndex(nums: number[]): number { 2 | let total = nums.reduce((a, b) => a + b); 3 | let leftSum = 0; 4 | 5 | for (let i = 0; i < nums.length; i++) { 6 | const rightSum = total - nums[i] - leftSum; 7 | 8 | if (leftSum === rightSum) return i; 9 | leftSum += nums[i]; 10 | } 11 | 12 | return -1; 13 | } 14 | -------------------------------------------------------------------------------- /typescript/1137-n-th-tribonacci-number.ts: -------------------------------------------------------------------------------- 1 | function tribonacci(n: number): number { 2 | let t = [0, 1, 1]; 3 | 4 | if (n < 3) return t[n]; 5 | 6 | for (let i = 3; i < n + 1; i++) { 7 | [t[0], t[1], t[2]] = [t[1], t[2], sum(t)]; 8 | } 9 | 10 | return t[2]; 11 | } 12 | 13 | function sum(arr: number[]): number { 14 | return arr.reduce((a, b) => a + b); 15 | } 16 | -------------------------------------------------------------------------------- /typescript/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.ts: -------------------------------------------------------------------------------- 1 | function replaceElements(arr: number[]): number[] { 2 | let currMax = -1; 3 | 4 | for(let i = arr.length -1 ; i >= 0; i--) { 5 | let newMax = Math.max(currMax, arr[i]); 6 | arr[i] = currMax; 7 | 8 | currMax = newMax; 9 | } 10 | 11 | return arr; 12 | }; 13 | -------------------------------------------------------------------------------- /typescript/1299-replace-elements-with-greatest-element-on-right-side.ts: -------------------------------------------------------------------------------- 1 | function replaceElements(arr: number[]): number[] { 2 | let currMax = -1; 3 | 4 | for(let i = arr.length -1 ; i >= 0; i--) { 5 | let newMax = Math.max(currMax, arr[i]); 6 | arr[i] = currMax; 7 | 8 | currMax = newMax; 9 | } 10 | 11 | return arr; 12 | }; 13 | -------------------------------------------------------------------------------- /csharp/0026-remove-duplicates-from-sorted-array.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int RemoveDuplicates(int[] nums) { 3 | int l = 1, r = 1; 4 | while (r < nums.Length) { 5 | if (nums[r] != nums[r - 1]) { 6 | nums[l] = nums[r]; 7 | ++l; 8 | } 9 | ++r; 10 | } 11 | return l; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /csharp/0066-plus-one.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] PlusOne(int[] digits) { 3 | string n = string.Join("", digits); 4 | n = (BigInteger.Parse(n) + 1).ToString(); 5 | int[] result = new int[n.Length]; 6 | for (int i = 0; i < n.Length; i++) 7 | { 8 | result[i] = n[i] - '0'; 9 | } 10 | return result; 11 | } 12 | } -------------------------------------------------------------------------------- /dart/0169-majority-element.dart: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int majorityElement(List nums) { 3 | int res = 0; 4 | int count = 0; 5 | 6 | for (int n in nums) { 7 | if (count == 0) { 8 | res = n; 9 | } 10 | 11 | if (res == n) { 12 | count++; 13 | } else { 14 | count--; 15 | } 16 | } 17 | 18 | return res; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/0876-middle-of-the-linked-list.java: -------------------------------------------------------------------------------- 1 | //fast and slow pointer 2 | class Solution { 3 | 4 | public ListNode middleNode(ListNode head) { 5 | ListNode slow = head; 6 | ListNode fast = head; 7 | while (fast != null && fast.next != null) { 8 | fast = fast.next.next; 9 | slow = slow.next; 10 | } 11 | return slow; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/0901-online-stock-span.java: -------------------------------------------------------------------------------- 1 | class StockSpanner { 2 | Stack s = new Stack<>(); 3 | 4 | public StockSpanner() { 5 | 6 | } 7 | 8 | public int next(int price) { 9 | int span=1; 10 | while(!s.isEmpty() && s.peek()[0]<=price) 11 | span+=s.pop()[1]; 12 | s.push(new int[]{price,span}); 13 | return span; 14 | } 15 | } -------------------------------------------------------------------------------- /kotlin/0191-number-of-1-bits.kt: -------------------------------------------------------------------------------- 1 | package kotlin 2 | 3 | class Solution { 4 | // you need treat n as an unsigned value 5 | fun hammingWeight(n:Int):Int { 6 | 7 | var n = n 8 | var count = 0 9 | for(i in 0..31){ 10 | if( n and 1 == 1) count++ 11 | n = n shr 1 12 | } 13 | 14 | return count 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /kotlin/0442-find-all-duplicates-in-an-array.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun findDuplicates(nums: IntArray): List { 3 | val res = mutableListOf () 4 | 5 | for (n in nums) { 6 | val n = if (n < 0) -n else n 7 | if (nums[n - 1] < 0) res.add(n) 8 | nums[n - 1] *= -1 9 | } 10 | 11 | return res 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /kotlin/1071-greatest-common-divisor-of-strings.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun gcdOfStrings(str1: String, str2: String): String { 3 | if(str1+str2 != str2+str1) return "" 4 | val gcd = findGcd(str1.length, str2.length) 5 | return str1.substring(0, gcd) 6 | } 7 | fun findGcd(p: Int, q: Int): Int { 8 | return if(q == 0) p else findGcd(q, p%q) 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /python/1800-maximum-ascending-subarray-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxAscendingSum(self, nums: List[int]) -> int: 3 | curSum = results = nums[0] 4 | 5 | for i in range(1, len(nums)): 6 | if nums[i] <= nums[i - 1]: 7 | curSum = 0 8 | curSum += nums[i] 9 | results = max(curSum, results) 10 | 11 | return results 12 | -------------------------------------------------------------------------------- /python/1984-minimum-difference-between-highest-and-lowest-of-k-scores.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumDifference(self, nums: List[int], k: int) -> int: 3 | nums.sort() 4 | l, r = 0, k - 1 5 | res = float("inf") 6 | 7 | while r < len(nums): 8 | res = min(res, nums[r] - nums[l]) 9 | l, r = l + 1, r + 1 10 | return res 11 | -------------------------------------------------------------------------------- /ruby/0020-valid-parentheses.rb: -------------------------------------------------------------------------------- 1 | def is_valid(s) 2 | paren = [] 3 | match = { 4 | "{" => "}", 5 | "(" => ")", 6 | "[" => "]", 7 | } 8 | s.each_char do |char| 9 | if match.key?(char) 10 | paren << char 11 | next 12 | elsif paren.empty? || match[paren.pop] != char 13 | return false 14 | end 15 | paren.pop 16 | end 17 | paren.empty? 18 | end 19 | -------------------------------------------------------------------------------- /ruby/0133-clone-graph.rb: -------------------------------------------------------------------------------- 1 | def cloneGraph(node) 2 | dfs(node, {}) 3 | end 4 | 5 | def dfs(node, clones) 6 | return unless node 7 | return clones[node] if clones.key?(node) 8 | 9 | clone = Node.new(node.val) 10 | clones[node] = clone 11 | 12 | node.neighbors.each do |n| 13 | clone.neighbors << dfs(n, clones) 14 | end 15 | 16 | clone 17 | end 18 | -------------------------------------------------------------------------------- /rust/0053-maximum-subarray.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn max_sub_array(nums: Vec) -> i32 { 3 | let mut res = nums[0]; 4 | let mut sum = 0; 5 | 6 | for n in nums { 7 | if sum < 0 { 8 | sum = 0; 9 | } 10 | 11 | sum += n; 12 | res = res.max(sum); 13 | } 14 | 15 | res 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /swift/0058-Length-of-Last-Word.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func lengthOfLastWord(_ s: String) -> Int { 3 | var length: Int = 0 4 | 5 | for c in s.reversed() { 6 | if c != " " { 7 | length += 1 8 | } else if (length > 0){ 9 | break; 10 | } 11 | } 12 | 13 | return length 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /swift/0058-length-of-last-word.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func lengthOfLastWord(_ s: String) -> Int { 3 | var length: Int = 0 4 | 5 | for c in s.reversed() { 6 | if c != " " { 7 | length += 1 8 | } else if (length > 0){ 9 | break; 10 | } 11 | } 12 | 13 | return length 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /c/1470-shuffle-the-array.c: -------------------------------------------------------------------------------- 1 | int* shuffle(int* nums, int numsSize, int n, int* returnSize) { 2 | *returnSize = numsSize; 3 | int* result = (int*)malloc(numsSize * sizeof(int)); 4 | 5 | int i, j, k; 6 | i = j = k = 0; 7 | 8 | while (i < n) { 9 | result[k++] = nums[i]; 10 | result[k++] = nums[i + n]; 11 | i++; 12 | } 13 | 14 | return result; 15 | } 16 | -------------------------------------------------------------------------------- /csharp/0169-majority-element.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MajorityElement(int[] nums) { 3 | int res = 0; 4 | int count = 0; 5 | 6 | for(var i = 0; i < nums.Length; i ++){ 7 | if (count == 0){ 8 | res = nums[i]; 9 | } 10 | count += (nums[i] == res) ? 1 : -1; 11 | } 12 | return res; 13 | } 14 | } -------------------------------------------------------------------------------- /java/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] replaceElements(int[] arr) { 3 | int rightMax = -1; 4 | for (int i = arr.length - 1; i >= 0; i--) { 5 | int newMax = Math.max(rightMax, arr[i]); 6 | arr[i] = rightMax; 7 | rightMax = newMax; 8 | } 9 | return arr; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/1299-replace-elements-with-greatest-element-on-right-side.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] replaceElements(int[] arr) { 3 | int rightMax = -1; 4 | for (int i = arr.length - 1; i >= 0; i--) { 5 | int newMax = Math.max(rightMax, arr[i]); 6 | arr[i] = rightMax; 7 | rightMax = newMax; 8 | } 9 | return arr; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/2486-append-characters-to-string-to-make-subsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int appendCharacters(String s, String t) { 3 | int i = 0, j = 0; 4 | while(i < s.length() && j < t.length()){ 5 | if(s.charAt(i) == t.charAt(j)){ 6 | j++; 7 | } 8 | i++; 9 | } 10 | return t.length() - j; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /javascript/1588-sum-of-all-odd-length-subarrays.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @return {number} 4 | */ 5 | var sumOddLengthSubarrays = function (arr) { 6 | let sum = 0, 7 | len = arr.length; 8 | for (let i = 0; i < arr.length; i++) { 9 | let total = i * (len - i) + (len - i); 10 | sum += Math.ceil(total / 2) * arr[i]; 11 | } 12 | return sum; 13 | }; 14 | -------------------------------------------------------------------------------- /kotlin/0901-online-stock-span.kt: -------------------------------------------------------------------------------- 1 | class StockSpanner() { 2 | val stack = LinkedList>() 3 | 4 | fun next(price: Int): Int { 5 | var span = 1 6 | while (stack.isNotEmpty() && stack.peekLast().first <= price) { 7 | span += stack.removeLast().second 8 | } 9 | stack.addLast(price to span) 10 | return span 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /python/0213-house-robber-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1])) 4 | 5 | def helper(self, nums): 6 | rob1, rob2 = 0, 0 7 | 8 | for n in nums: 9 | newRob = max(rob1 + n, rob2) 10 | rob1 = rob2 11 | rob2 = newRob 12 | return rob2 13 | -------------------------------------------------------------------------------- /python/0448-find-all-numbers-disappeared-in-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 3 | for n in nums: 4 | i = abs(n) - 1 5 | nums[i] = -1 * abs(nums[i]) 6 | 7 | res = [] 8 | for i, n in enumerate(nums): 9 | if n > 0: 10 | res.append(i + 1) 11 | return res 12 | -------------------------------------------------------------------------------- /ruby/0235-lowest-common-ancestor-of-a-binary-search-tree.rb: -------------------------------------------------------------------------------- 1 | def lowest_common_ancestor(root, p, q) 2 | return root if root.val == p.val || root.val == q.val 3 | return root if root.val.between?(p.val, q.val) || root.val.between?(q.val, p.val) 4 | 5 | if root.val > p.val 6 | lowest_common_ancestor(root.left, p, q) 7 | else 8 | lowest_common_ancestor(root.right, p, q) 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /ruby/0268-missing-number.rb: -------------------------------------------------------------------------------- 1 | def missing_number(nums) 2 | missing = 0 3 | (0..nums.length).each do |i| 4 | nbr = (nums[i].nil? ? 0 : nums[i]) 5 | missing += (i - nbr) 6 | end 7 | missing 8 | end 9 | 10 | # Solution using Gauss summation 11 | def missing_number(nums) 12 | gauss = (nums.length / 2.0) * (nums.length + 1) 13 | nums.each { |n| gauss -= n } 14 | gauss.to_i 15 | end 16 | -------------------------------------------------------------------------------- /typescript/0050-powx-n.ts: -------------------------------------------------------------------------------- 1 | function myPow(x: number, n: number): number { 2 | function helper(x: number, n: number): number { 3 | if (x == 0) return 0; 4 | if (n == 0) return 1; 5 | 6 | let res = helper(x * x, Math.floor(n / 2)); 7 | return n % 2 ? x * res : res; 8 | } 9 | 10 | let res = helper(x, Math.abs(n)); 11 | return n >= 0 ? res : 1 / res; 12 | } 13 | -------------------------------------------------------------------------------- /csharp/0055-jump-game.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool CanJump(int[] nums) { 3 | int goal = nums.Length - 1; 4 | for (int i = nums.Length-1; i>=0; i--) 5 | { 6 | if (nums[i] + i >= goal) 7 | { 8 | goal = i; 9 | } 10 | } 11 | 12 | return goal == 0 ; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /dart/0001-two-sum.dart: -------------------------------------------------------------------------------- 1 | // Time Complexity: O(n) 2 | // Space Complexity: O(n) 3 | 4 | class Solution { 5 | List twoSum(List nums, int target) { 6 | var map = Map(); 7 | for (int i = 0; i < nums.length; i++) { 8 | var x = target - nums[i]; 9 | if (map.containsKey(x)) return [map[x]!, i]; 10 | map[nums[i]] = i; 11 | } 12 | throw ""; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /go/0014-longest-common-prefix.go: -------------------------------------------------------------------------------- 1 | func longestCommonPrefix(strs []string) string { 2 | var res strings.Builder 3 | for i := 0; i < len(strs[0]); i++ { 4 | for _, s := range(strs) { 5 | if i == len(s) || s[i] != strs[0][i] { 6 | return res.String() 7 | } 8 | } 9 | res.WriteByte(strs[0][i]) 10 | } 11 | return res.String() 12 | } 13 | -------------------------------------------------------------------------------- /go/0141-linked-list-cycle.go: -------------------------------------------------------------------------------- 1 | func hasCycle(head *ListNode) bool { 2 | if head == nil || head.Next == nil { 3 | return false 4 | } 5 | slow := head 6 | fast := head 7 | for fast != nil && fast.Next != nil { 8 | slow = slow.Next 9 | fast = fast.Next.Next 10 | if slow == fast { 11 | return true 12 | } 13 | } 14 | return false 15 | } 16 | -------------------------------------------------------------------------------- /javascript/2629-function-composition.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {Function[]} functions 3 | * @return {Function} 4 | */ 5 | var compose = function (functions) { 6 | return function (x) { 7 | let ans = x; 8 | for (fn of functions.reverse()) ans = fn(ans); 9 | return ans; 10 | }; 11 | }; 12 | 13 | /** 14 | * const fn = compose([x => x + 1, x => 2 * x]) 15 | * fn(4) // 9 16 | */ 17 | -------------------------------------------------------------------------------- /kotlin/1299-replace-elements-with-greatest-element-on-right-side.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun replaceElements(arr: IntArray): IntArray { 3 | val res = IntArray(arr.size) 4 | var max = -1 5 | 6 | arr.reversed().forEachIndexed { i, value -> 7 | res[i] = max 8 | max = maxOf(max, value) 9 | } 10 | return res.reversed().toIntArray() 11 | } 12 | } -------------------------------------------------------------------------------- /python/0045-jump-game-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, nums: List[int]) -> int: 3 | l, r = 0, 0 4 | res = 0 5 | while r < (len(nums) - 1): 6 | maxJump = 0 7 | for i in range(l, r + 1): 8 | maxJump = max(maxJump, i + nums[i]) 9 | l = r + 1 10 | r = maxJump 11 | res += 1 12 | return res 13 | -------------------------------------------------------------------------------- /python/0901-online-stock-span.py: -------------------------------------------------------------------------------- 1 | class StockSpanner: 2 | def __init__(self): 3 | self.stack = [] # pair: (price, span) 4 | 5 | def next(self, price: int) -> int: 6 | span = 1 7 | while self.stack and self.stack[-1][0] <= price: 8 | span += self.stack[-1][1] 9 | self.stack.pop() 10 | self.stack.append((price, span)) 11 | return span 12 | -------------------------------------------------------------------------------- /python/0946-validate-stack-sequences.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def validateStackSequences(self, pushed, popped): 3 | i = 0 4 | stack = [] 5 | for n in pushed: 6 | stack.append(n) 7 | while i < len(popped) and stack and popped[i] == stack[-1]: 8 | stack.pop() 9 | i += 1 10 | 11 | return not stack 12 | 13 | 14 | -------------------------------------------------------------------------------- /python/1189-maximum-number-of-balloons.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | def maxNumberOfBalloons(self, text: str) -> int: 6 | countText = Counter(text) 7 | balloon = Counter("balloon") 8 | 9 | res = len(text) # or float("inf") 10 | for c in balloon: 11 | res = min(res, countText[c] // balloon[c]) 12 | return res 13 | -------------------------------------------------------------------------------- /python/1464-maximum-product-of-two-elements-in-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, nums: List[int]) -> int: 3 | high = secondHigh = 0 4 | for n in nums: 5 | if n > high: 6 | secondHigh = high 7 | high = n 8 | else: 9 | secondHigh = max(n, secondHigh) 10 | return (high - 1) * (secondHigh - 1) 11 | -------------------------------------------------------------------------------- /ruby/0167-two-sum-ii-input-array-is-sorted.rb: -------------------------------------------------------------------------------- 1 | def two_sum(numbers, target) 2 | idx_start = 0 3 | idx_end = numbers.length - 1 4 | while idx_start < idx_end 5 | case numbers[idx_start] + numbers[idx_end] <=> target 6 | when 1 7 | idx_end -= 1 8 | when 0 9 | return [idx_start + 1, idx_end + 1] 10 | when -1 11 | idx_start += 1 12 | end 13 | end 14 | nil 15 | end 16 | -------------------------------------------------------------------------------- /rust/0202-happy-number.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn is_happy(mut n: i32) -> bool { 3 | loop { 4 | let mut s = 0; 5 | while n > 0 { 6 | s += (n % 10).pow(2); 7 | n /= 10; 8 | } 9 | match s { 10 | 1 | 4 => break s == 1, 11 | _ => n = s, 12 | } 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /rust/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.rs: -------------------------------------------------------------------------------- 1 | use std::cmp::max; 2 | 3 | impl Solution { 4 | pub fn replace_elements(arr: Vec) -> Vec { 5 | let length = arr.len(); 6 | let mut ans: Vec = vec![-1; length]; 7 | for i in (1..=(length - 1)).rev() { 8 | ans[i - 1] = max(arr[i], ans[i]); 9 | } 10 | ans 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /rust/1299-replace-elements-with-greatest-element-on-right-side.rs: -------------------------------------------------------------------------------- 1 | use std::cmp::max; 2 | 3 | impl Solution { 4 | pub fn replace_elements(arr: Vec) -> Vec { 5 | let length = arr.len(); 6 | let mut ans: Vec = vec![-1; length]; 7 | for i in (1..=(length - 1)).rev() { 8 | ans[i - 1] = max(arr[i], ans[i]); 9 | } 10 | ans 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /typescript/0929-unique-email-addresses.ts: -------------------------------------------------------------------------------- 1 | function numUniqueEmails(emails: string[]): number { 2 | const unique = new Set(); 3 | 4 | for (const email of emails) { 5 | let [local, domain] = email.split('@'); 6 | local = local.split('+')[0]; 7 | local = local.split('.').join(''); 8 | unique.add(local + '@' + domain); 9 | } 10 | 11 | return unique.size; 12 | } 13 | -------------------------------------------------------------------------------- /csharp/0303-range-sum-query-immutable.cs: -------------------------------------------------------------------------------- 1 | public class NumArray { 2 | private int[] nums; 3 | public NumArray(int[] nums) { 4 | this.nums = nums; 5 | } 6 | 7 | public int SumRange(int left, int right) { 8 | int sum = 0; 9 | for (int i = left; i <= right; i++) 10 | { 11 | sum += this.nums[i]; 12 | } 13 | return sum; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /go/0203-remove-linked-list-elements.go: -------------------------------------------------------------------------------- 1 | func removeElements(head *ListNode, val int) *ListNode { 2 | if head == nil { 3 | return nil 4 | } 5 | 6 | curr := head 7 | 8 | for curr.Next != nil { 9 | if curr.Next.Val == val { 10 | curr.Next = curr.Next.Next 11 | } else { 12 | curr = curr.Next 13 | } 14 | } 15 | 16 | if head.Val == val { 17 | return head.Next 18 | } 19 | 20 | return head 21 | } -------------------------------------------------------------------------------- /go/0704-binary-search.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func search(nums []int, target int) int { 4 | left := 0 5 | right := len(nums) - 1 6 | 7 | for left <= right { 8 | middle := (left + right) / 2 9 | 10 | if nums[middle] == target { 11 | return middle 12 | } else if nums[middle] < target { 13 | left = middle + 1 14 | } else { 15 | right = middle - 1 16 | } 17 | } 18 | return -1 19 | 20 | } 21 | -------------------------------------------------------------------------------- /go/1822-sign-of-the-product-of-an-array.go: -------------------------------------------------------------------------------- 1 | /* 2 | Time: O(n) 3 | Space: O(1) 4 | */ 5 | 6 | func arraySign(nums []int) int { 7 | neg := 0 8 | for _, n := range nums { 9 | if n == 0 { 10 | return 0 11 | } else if n < 0 { 12 | neg++ 13 | } 14 | } 15 | if neg%2 == 0 { 16 | return 1 17 | } else { 18 | return -1 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/0136-single-number.java: -------------------------------------------------------------------------------- 1 | //We can use xor operation as it cancel out itself (i.e. only when values are different in binary representation then give output). See how xor operation works if confused. 2 | class Solution { 3 | 4 | public int singleNumber(int[] nums) { 5 | int ans = nums[0]; 6 | for (int i = 1; i < nums.length; i++) ans ^= nums[i]; 7 | return ans; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /java/0217-contains-duplicate.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean containsDuplicate(int[] nums) { 4 | Set uniques = new HashSet<>(); 5 | for (int i = 0; i < nums.length; i++) { 6 | if (uniques.contains(nums[i])) { 7 | return true; 8 | } 9 | uniques.add(nums[i]); 10 | } 11 | return false; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /kotlin/0026-remove-duplicates-from-sorted-array.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun removeDuplicates(nums: IntArray): Int { 3 | var last = 0 4 | var i = 0 5 | while(i < nums.size) { 6 | var j = i 7 | while(j < nums.size && nums[i] == nums[j]) j++ 8 | nums[last++] = nums[i] 9 | i = j 10 | } 11 | return last 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /rust/0179-largest-number.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn largest_number(nums: Vec) -> String { 3 | let mut v: Vec = nums.iter().map(|&num| num.to_string()).collect(); 4 | v.sort_by(|a: &String, b: &String| (b.clone() + a).cmp(&(a.clone() + b))); 5 | if v[0] == "0" { 6 | String::from("0") 7 | } else { 8 | v.join("") 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /rust/0746-min-cost-climbing-stairs.rs: -------------------------------------------------------------------------------- 1 | // time compexity : O(n) 2 | // space compexity : O(1) 3 | 4 | impl Solution { 5 | pub fn min_cost_climbing_stairs(mut cost: Vec) -> i32 { 6 | for i in 2..cost.len(){ 7 | cost[i] += cost[i- 1].min(cost[i-2]); 8 | } 9 | 10 | let len = cost.len(); 11 | 12 | cost[len - 1].min(cost[len - 2]) 13 | } 14 | } -------------------------------------------------------------------------------- /rust/2114-maximum-number-of-words-found-in-sentences.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn most_words_found(sentences: Vec) -> i32 { 3 | let mut most = 0; 4 | for sentence in sentences { 5 | let size = sentence.split_whitespace().count(); 6 | if size > most { 7 | most = size; 8 | } 9 | } 10 | return most as i32; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /typescript/0009-palindrome-number.ts: -------------------------------------------------------------------------------- 1 | var isPalindrome = (x: number) => { 2 | // Creates array from int characters 3 | // 121 -> [1,2,1] 4 | let arr = Array.from(String(x), Number); 5 | 6 | // Uses two pointer 7 | for (let i = 0; i < arr.length; i++) { 8 | if (arr[i] !== arr[arr.length - 1 - i]) { 9 | return false; 10 | } 11 | } 12 | return true; 13 | }; 14 | -------------------------------------------------------------------------------- /typescript/0014-longest-common-prefix.ts: -------------------------------------------------------------------------------- 1 | function longestCommonPrefix(strs: string[]): string { 2 | let res = ''; 3 | 4 | for (let i = 0; i < strs[0].length; i++) { 5 | for (const s of strs) { 6 | if (i == s.length || s[i] !== strs[0][i]) { 7 | return res; 8 | } 9 | } 10 | res += strs[0][i]; 11 | } 12 | 13 | return res; 14 | } 15 | -------------------------------------------------------------------------------- /typescript/0518-coin-change-ii.ts: -------------------------------------------------------------------------------- 1 | function change(amount: number, coins: number[]): number { 2 | let table = Array(amount + 1).fill(0); 3 | table[0] = 1; 4 | for (let coin of coins) { 5 | for (let i = 0; i < table.length; i++) { 6 | if (coin <= i) { 7 | table[i] += table[i - coin]; 8 | } 9 | } 10 | } 11 | return table[amount]; 12 | } 13 | -------------------------------------------------------------------------------- /articles/README.md: -------------------------------------------------------------------------------- 1 | # Article Guide 2 | 3 | 1. Each article should be written in markdown. Exanple: [duplicate-integer.md](https://github.com/neetcode-gh/leetcode/blob/main/articles/duplicate-integer.md) 4 | 2. At least one solution should be similar to a solution present in the NeetCode video. Ideally all solutions from the video are present. 5 | 3. Add time & space complexity 6 | 4. Cover all relevant solutions if possible. 7 | -------------------------------------------------------------------------------- /c/0162-find-peak-element.c: -------------------------------------------------------------------------------- 1 | int findPeakElement(int* nums, int numsSize) { 2 | int start = 0; 3 | int end = numsSize - 1; 4 | 5 | while(start < end){ 6 | int mid = start + (end - start)/2; 7 | 8 | if(nums[mid] > nums[mid+1]) 9 | end = mid; 10 | else if(nums[mid] < nums[mid+1]) 11 | start = mid + 1; 12 | } 13 | 14 | return start; 15 | } -------------------------------------------------------------------------------- /c/0287-find-the-duplicate-number.c: -------------------------------------------------------------------------------- 1 | int findDuplicate(int* nums, int numsSize){ 2 | int slow = nums[0]; 3 | int fast = nums[nums[0]]; 4 | 5 | while (slow != fast) { 6 | slow = nums[slow]; 7 | fast = nums[nums[fast]]; 8 | } 9 | 10 | slow = 0; 11 | while (slow != fast) { 12 | slow = nums[slow]; 13 | fast = nums[fast]; 14 | } 15 | return slow; 16 | } -------------------------------------------------------------------------------- /c/1137-n-th-tribonacci-number.c: -------------------------------------------------------------------------------- 1 | int tribonacci(int n) { 2 | if (n == 0) 3 | return 0; 4 | else if (n == 1 || n == 2) 5 | return 1; 6 | 7 | int trib[n + 1]; 8 | trib[0] = 0; 9 | trib[1] = 1; 10 | trib[2] = 1; 11 | 12 | for (int i = 3; i <= n; i++) { 13 | trib[i] = trib[i - 1] + trib[i - 2] + trib[i - 3]; 14 | } 15 | 16 | return trib[n]; 17 | } 18 | -------------------------------------------------------------------------------- /cpp/0283-move-zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void moveZeroes(vector& nums) { 4 | int left = 0; 5 | 6 | for(int i = 0; i < nums.size(); i++){ 7 | if(nums[i] != 0){ 8 | nums[left++] = nums[i]; 9 | } 10 | } 11 | 12 | for(left; left < nums.size(); left ++){ 13 | nums[left] = 0; 14 | } 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /csharp/0617-merge-two-binary-trees.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public TreeNode MergeTrees(TreeNode root1, TreeNode root2) { 3 | if (root1 == null) return root2; 4 | 5 | if (root2 == null) return root1; 6 | 7 | return new TreeNode(root1.val + root2.val, 8 | MergeTrees(root1.left, root2.left), 9 | MergeTrees(root1.right, root2.right) 10 | ); 11 | } 12 | } -------------------------------------------------------------------------------- /csharp/1603-design-parking-system.cs: -------------------------------------------------------------------------------- 1 | public class ParkingSystem 2 | { 3 | private int[] spaces; 4 | 5 | public ParkingSystem(int big, int medium, int small) 6 | { 7 | spaces = [big, medium, small]; 8 | } 9 | 10 | public bool AddCar(int carType) 11 | { 12 | if (spaces[carType - 1] <= 0) return false; 13 | spaces[carType - 1] -= 1; 14 | return true; 15 | } 16 | } -------------------------------------------------------------------------------- /go/0128-longest-consecutive-sequence.go: -------------------------------------------------------------------------------- 1 | func longestConsecutive(nums []int) int { 2 | set := make(map[int]bool) 3 | longest := 0 4 | 5 | for _, n := range nums { 6 | set[n] = true 7 | } 8 | 9 | for _, n := range nums { 10 | if !set[n - 1] { 11 | length := 1 12 | for set[n + length] { 13 | length++ 14 | } 15 | longest = max(length, longest) 16 | } 17 | } 18 | 19 | return longest 20 | } 21 | -------------------------------------------------------------------------------- /go/0724-find-pivot-index.go: -------------------------------------------------------------------------------- 1 | func pivotIndex(nums []int) int { 2 | total := 0 3 | for _, n := range(nums) { 4 | total += n 5 | } 6 | 7 | leftSum := 0 8 | for i := 0; i < len(nums); i++ { 9 | rightSum := total - nums[i] - leftSum 10 | if leftSum == rightSum { 11 | return i 12 | } 13 | leftSum += nums[i] 14 | } 15 | return -1 16 | } 17 | -------------------------------------------------------------------------------- /java/0746-min-cost-climbing-stairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minCostClimbingStairs(int[] cost) { 3 | int one = 0; 4 | int two = 0; 5 | 6 | for (int i = cost.length - 1; i >= 0; i--) { 7 | cost[i] += Math.min(one, two); 8 | two = one; 9 | one = cost[i]; 10 | } 11 | 12 | return Math.min(cost[0], cost[1]); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/0896-monotonic-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isMonotonic(int[] nums) { 3 | boolean inc = true, dec = true; 4 | 5 | for (int i = 0; i < nums.length - 1; i++) { 6 | if (nums[i] > nums[i + 1]) 7 | inc = false; 8 | if (nums[i] < nums[i + 1]) 9 | dec = false; 10 | } 11 | 12 | return inc || dec; 13 | } 14 | } -------------------------------------------------------------------------------- /java/1611-minimum-one-bit-operations-to-make-integers-zero.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumOneBitOperations(int n) { 3 | if(n == 0) 4 | return 0; 5 | 6 | int k = 0; 7 | while((int)Math.pow(2,k) <= n) 8 | k += 1; 9 | k -= 1; 10 | return (int)Math.pow(2,k+1) - 1 - minimumOneBitOperations((int)Math.pow(2,k) ^ n); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /javascript/0926-flip-string-to-monotone-increasing.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var minFlipsMonoIncr = function (s) { 6 | let [res, countOne] = [0, 0]; 7 | 8 | for (ch of s) { 9 | if (ch == '1') { 10 | countOne++; 11 | } else { 12 | res = Math.min(res + 1, countOne); 13 | } 14 | } 15 | 16 | return res; 17 | }; 18 | -------------------------------------------------------------------------------- /javascript/1029-two-city-scheduling.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} costs 3 | * @return {number} 4 | */ 5 | const twoCitySchedCost = (costs) => { 6 | costs.sort((a, b) => a[1] - a[0] - (b[1] - b[0])); 7 | 8 | let totalCost = 0; 9 | let n = costs.length / 2; 10 | for (let i = 0; i < n; i++) { 11 | totalCost += costs[i][1] + costs[i + n][0]; 12 | } 13 | return totalCost; 14 | }; 15 | -------------------------------------------------------------------------------- /python/0322-coin-change.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def coinChange(self, coins: List[int], amount: int) -> int: 3 | dp = [amount + 1] * (amount + 1) 4 | dp[0] = 0 5 | 6 | for a in range(1, amount + 1): 7 | for c in coins: 8 | if a - c >= 0: 9 | dp[a] = min(dp[a], 1 + dp[a - c]) 10 | return dp[amount] if dp[amount] != amount + 1 else -1 11 | -------------------------------------------------------------------------------- /python/0441-arranging-coins.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrangeCoins(self, n: int) -> int: 3 | l, r = 1, n 4 | res = 0 5 | while l <=r: 6 | mid = (l+r)//2 7 | coins = (mid /2) * (mid+1) 8 | if coins > n: 9 | r = mid - 1 10 | else: 11 | l = mid + 1 12 | res = max(mid, res) 13 | return res 14 | -------------------------------------------------------------------------------- /python/0881-boats-to-save-people.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numRescueBoats(self, people: list[int], limit: int) -> int: 3 | people.sort() 4 | right = len(people) - 1 5 | left = res = 0 6 | while left <= right: 7 | if people[left] + people[right] <= limit: 8 | left += 1 9 | right -= 1 10 | res += 1 11 | return res 12 | -------------------------------------------------------------------------------- /python/1750-minimum-length-of-string-after-deleting-similar-ends.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumLength(self, s: str) -> int: 3 | l, r = 0, len(s) - 1 4 | 5 | while l < r and s[l] == s[r]: 6 | tmp = s[l] 7 | while l <= r and s[l] == tmp: 8 | l += 1 9 | while l <= r and s[r] == tmp: 10 | r -= 1 11 | return (r - l + 1) 12 | -------------------------------------------------------------------------------- /ruby/1046-Last-Stone-Weight.rb: -------------------------------------------------------------------------------- 1 | require "rubygems" 2 | require "algorithms" 3 | include Containers 4 | 5 | def last_stone_weight(stones) 6 | heap = MaxHeap.new 7 | stones.each { |stone| heap << stone } 8 | until heap.size <= 1 9 | stone1 = heap.pop 10 | stone2 = heap.pop 11 | heap << (stone1 - stone2).abs if stone1 != stone2 12 | end 13 | last = heap.pop 14 | last.nil? ? 0 : last 15 | end 16 | -------------------------------------------------------------------------------- /ruby/1046-last-stone-weight.rb: -------------------------------------------------------------------------------- 1 | require "rubygems" 2 | require "algorithms" 3 | include Containers 4 | 5 | def last_stone_weight(stones) 6 | heap = MaxHeap.new 7 | stones.each { |stone| heap << stone } 8 | until heap.size <= 1 9 | stone1 = heap.pop 10 | stone2 = heap.pop 11 | heap << (stone1 - stone2).abs if stone1 != stone2 12 | end 13 | last = heap.pop 14 | last.nil? ? 0 : last 15 | end 16 | -------------------------------------------------------------------------------- /rust/0263-ugly-number.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn is_ugly(n: i32) -> bool { 3 | if n < 1 { 4 | return false; 5 | } 6 | let mut n = n; 7 | let ugly_primes = vec![2, 3, 5]; 8 | 9 | for prime in ugly_primes { 10 | while n % prime == 0 { 11 | n /= prime; 12 | } 13 | } 14 | 15 | n == 1 16 | } 17 | } -------------------------------------------------------------------------------- /rust/0926-flip-string-to-monotone-increasing.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn min_flips_mono_incr(s: String) -> i32 { 3 | let (mut res, mut count_one) = (0, 0); 4 | 5 | for ch in s.chars() { 6 | if ch == '1' { 7 | count_one += 1; 8 | } else { 9 | res = i32::min(res + 1, count_one); 10 | } 11 | } 12 | res 13 | } 14 | } -------------------------------------------------------------------------------- /rust/1137-n-th-tribonacci-number.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn tribonacci(n: i32) -> i32 { 3 | let mut t = [0, 1, 1]; 4 | 5 | if n <= 2 { 6 | return t[n as usize]; 7 | } 8 | 9 | for i in 3..(n + 1) as usize { 10 | t.swap(0, 1); 11 | t.swap(1, 2); 12 | t[2] = t.iter().sum(); 13 | } 14 | 15 | t[2] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /scala/0125-valid-palindrome.scala: -------------------------------------------------------------------------------- 1 | object Solution { 2 | def isPalindrome(s: String): Boolean = { 3 | val smallCased = s.toLowerCase 4 | // removing all non-alphanumeric characters 5 | val notAlphaNumericRegex = """[\W_]""".r 6 | val toCompareWith = notAlphaNumericRegex.replaceAllIn(smallCased, "") 7 | 8 | val reversed = toCompareWith.reverse 9 | toCompareWith == reversed 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /typescript/0062-unique-paths.ts: -------------------------------------------------------------------------------- 1 | function uniquePaths(m: number, n: number): number { 2 | let row = new Array(n).fill(1); 3 | 4 | for (let i = 0; i < m - 1; i++) { 5 | let newRow = new Array(n).fill(1); 6 | 7 | for (let j = n - 2; j > -1; j--) { 8 | newRow[j] = newRow[j + 1] + row[j]; 9 | } 10 | 11 | row = newRow; 12 | } 13 | 14 | return row[0]; 15 | } 16 | -------------------------------------------------------------------------------- /go/0226-invert-binary-tree.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * type TreeNode struct { 4 | * Val int 5 | * Left *TreeNode 6 | * Right *TreeNode 7 | * } 8 | */ 9 | func invertTree(root *TreeNode) *TreeNode { 10 | if root == nil { 11 | return root 12 | } 13 | 14 | left := invertTree(root.Left) 15 | root.Left = invertTree(root.Right) 16 | root.Right = left 17 | 18 | return root 19 | } -------------------------------------------------------------------------------- /java/0045-jump-game-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int jump(int[] nums) { 4 | int res = 0, r = 0, l = 0, fur = 0; 5 | 6 | while (r < nums.length - 1) { 7 | fur = 0; 8 | for (int i = l; i <= r; i++) fur = Math.max(fur, i + nums[i]); 9 | l = r + 1; 10 | r = fur; 11 | res++; 12 | } 13 | return res; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/0442-find-all-duplicates-in-an-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List findDuplicates(int[] nums) { 3 | List res = new ArrayList<>(); 4 | 5 | for (int n : nums) { 6 | n = Math.abs(n); 7 | if (nums[n - 1] < 0) 8 | res.add(n); 9 | nums[n - 1] = -nums[n - 1]; 10 | } 11 | 12 | return res; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /python/0050-powx-n.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x: float, n: int) -> float: 3 | def helper(x, n): 4 | if x == 0: 5 | return 0 6 | if n == 0: 7 | return 1 8 | 9 | res = helper(x * x, n // 2) 10 | return x * res if n % 2 else res 11 | 12 | res = helper(x, abs(n)) 13 | return res if n >= 0 else 1 / res 14 | -------------------------------------------------------------------------------- /python/0238-product-of-array-except-self.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def productExceptSelf(self, nums: List[int]) -> List[int]: 3 | res = [1] * (len(nums)) 4 | 5 | for i in range(1, len(nums)): 6 | res[i] = res[i-1] * nums[i-1] 7 | postfix = 1 8 | for i in range(len(nums) - 1, -1, -1): 9 | res[i] *= postfix 10 | postfix *= nums[i] 11 | return res 12 | -------------------------------------------------------------------------------- /python/0896-monotonic-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isMonotonic(self, nums: List[int]) -> bool: 3 | increasing = decreasing = True 4 | 5 | for i in range(len(nums) - 1): 6 | if nums[i] > nums[i + 1]: 7 | increasing = False 8 | if nums[i] < nums[i + 1]: 9 | decreasing = False 10 | 11 | return increasing or decreasing 12 | -------------------------------------------------------------------------------- /python/1423-maximum-points-you-can-obtain-from-cards.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxScore(self, cardPoints: List[int], k: int) -> int: 3 | n = len(cardPoints) 4 | 5 | score = maxScore = sum(cardPoints[:k]) 6 | 7 | for i in range(1, k + 1): 8 | score += cardPoints[-i] - cardPoints[k - i] 9 | maxScore = max(maxScore, score) 10 | 11 | return maxScore 12 | -------------------------------------------------------------------------------- /ruby/0110-balanced-binary-tree.rb: -------------------------------------------------------------------------------- 1 | def is_balanced(root) 2 | $balance = true 3 | balanced?(root) 4 | $balance 5 | end 6 | 7 | def balanced?(root) 8 | return -1 if root.nil? 9 | 10 | left_height = 1 + balanced?(root.left) 11 | right_height = 1 + balanced?(root.right) 12 | $balance = false if (left_height - right_height).abs > 1 13 | 14 | left_height > right_height ? left_height : right_height 15 | end 16 | -------------------------------------------------------------------------------- /scala/0167-two-sum-ii-input-array-is-sorted.scala: -------------------------------------------------------------------------------- 1 | object Solution { 2 | def twoSum(numbers: Array[Int], target: Int): Array[Int] = { 3 | def loop(p1: Int, p2: Int): Array[Int] = { 4 | if(numbers(p1) + numbers(p2) == target) Array(p1 + 1, p2 + 1) 5 | else if(numbers(p1) + numbers(p2) > target) loop(p1, p2 - 1) 6 | else loop(p1 + 1, p2) 7 | } 8 | loop(0, numbers.length - 1) 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /swift/0026-Remove-Duplicates-from-Sorted-Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func removeDuplicates(_ nums: inout [Int]) -> Int { 3 | var left: Int = 0 4 | 5 | for right in 1.. Int { 3 | var left: Int = 0 4 | 5 | for right in 1.. { 2 | if (node === null) return; 3 | 4 | inDepth(node.left, stack); 5 | 6 | stack.push(node.val); 7 | 8 | inDepth(node.right, stack); 9 | }; 10 | 11 | function kthSmallest(root: TreeNode | null, k: number): number { 12 | let stack = []; 13 | 14 | inDepth(root, stack); 15 | 16 | return stack[k - 1]; 17 | } 18 | -------------------------------------------------------------------------------- /go/0013-roman-to-integer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func romanToInt(s string) int { 4 | letters := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 5 | length := len(s) 6 | var ans int 7 | for i := 0; i < length; i++ { 8 | if i+1 < length && letters[s[i]] < letters[s[i+1]] { 9 | ans -= letters[s[i]] 10 | } else { 11 | ans += letters[s[i]] 12 | } 13 | } 14 | return ans 15 | } 16 | -------------------------------------------------------------------------------- /go/1029-two-city-scheduling.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func main() { 6 | 7 | } 8 | 9 | func twoCitySchedCost(costs [][]int) int { 10 | sort.Slice(costs, func(a, b int) bool { return costs[a][1] - costs[a][0] < costs[b][1] - costs[b][0]}); 11 | 12 | n ,totalCost := len(costs) / 2, 0 13 | for i := 0; i < n ; i++ { 14 | totalCost += costs[i][1] + costs[i +n][0] 15 | } 16 | return totalCost 17 | } -------------------------------------------------------------------------------- /javascript/0371-sum-of-two-integers.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/sum-of-two-integers/ 3 | * Time O(1) | Space O(1) 4 | * @param {number} a 5 | * @param {number} b 6 | * @return {number} 7 | */ 8 | var getSum = function (a, b) { 9 | while (b !== 0) { 10 | const [xor, carry] = [a ^ b, (a & b) << 1]; 11 | 12 | a = xor; 13 | b = carry; 14 | } 15 | 16 | return a; 17 | }; 18 | -------------------------------------------------------------------------------- /javascript/1512-number-of-good-pairs.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var numIdenticalPairs = function (nums) { 6 | let result = 0; 7 | for (let i = 0; i < nums.length; i++) { 8 | for (let j = i + 1; j < nums.length; j++) { 9 | if (nums[i] == nums[j]) { 10 | result++; 11 | } 12 | } 13 | } 14 | return result; 15 | }; 16 | -------------------------------------------------------------------------------- /kotlin/0283-move-zeroes.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun moveZeroes(nums: IntArray): Unit { 3 | var l = 0 4 | for(r in 0 until nums.size) { 5 | if(nums[r] != 0){ 6 | nums.swap(l,r) 7 | l++ 8 | } 9 | } 10 | return 11 | } 12 | fun IntArray.swap(i: Int, j: Int) { 13 | this[i] = this[j].also{this[j] = this[i]} 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /kotlin/0342-power-of-four.kt: -------------------------------------------------------------------------------- 1 | // recursion time O(logn) 2 | class Solution { 3 | fun isPowerOfFour(n: Int): Boolean { 4 | if (n == 1) return true 5 | if (n <= 0 || n % 4 != 0) return false 6 | return isPowerOfFour(n / 4) 7 | } 8 | } 9 | 10 | // bit manipulation time O(1) 11 | class Solution { 12 | fun isPowerOfFour(n: Int) = n > 0 && (n and (n - 1) == 0) && (n and 0x55555555) != 0 13 | } 14 | -------------------------------------------------------------------------------- /kotlin/0926-flip-string-to-monotone-increasing.kt: -------------------------------------------------------------------------------- 1 | // optimal solution 2 | class Solution { 3 | fun minFlipsMonoIncr(s: String): Int { 4 | 5 | var noOfOnes = 0 6 | var noOfFlips = 0 7 | 8 | for (bit in s) { 9 | if (bit == '1') noOfOnes++ 10 | else noOfFlips = minOf(noOfOnes, noOfFlips + 1) 11 | } 12 | 13 | return minOf(noOfOnes, noOfFlips) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /kotlin/1688-count-of-matches-in-tournament.kt: -------------------------------------------------------------------------------- 1 | // O(1) using summation of series 2 | class Solution { 3 | fun numberOfMatches(n: Int) = n - 1 4 | } 5 | 6 | // log(n) 7 | class Solution { 8 | fun numberOfMatches(n: Int): Int { 9 | var x = n 10 | var res = 0 11 | while (x > 1) { 12 | res += x / 2 13 | x = (x + 1) / 2 14 | } 15 | return res 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /python/0013-roman-to-integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def romanToInt(self, s: str) -> int: 3 | roman = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} 4 | res = 0 5 | for i in range(len(s)): 6 | if i + 1 < len(s) and roman[s[i]] < roman[s[i + 1]]: 7 | res -= roman[s[i]] 8 | else: 9 | res += roman[s[i]] 10 | return res 11 | -------------------------------------------------------------------------------- /python/0168-excel-sheet-column-title.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def convertToTitle(self, columnNumber: int) -> str: 3 | # Time: O(logn) - Log base 26 of n 4 | res = "" 5 | while columnNumber > 0: 6 | remainder = (columnNumber - 1) % 26 7 | res += chr(ord('A') + remainder) 8 | columnNumber = (columnNumber - 1) // 26 9 | 10 | return res[::-1] # reverse output 11 | -------------------------------------------------------------------------------- /python/0383-ransom-note.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def canConstruct(self, ransomNote: str, magazine: str) -> bool: 5 | r_counter = Counter(ransomNote) 6 | m_counter = Counter(magazine) 7 | # magazine contains (>=) ransomNote 8 | for c in ransomNote: 9 | if m_counter[c] < r_counter[c]: 10 | return False 11 | return True 12 | -------------------------------------------------------------------------------- /ruby/0007-reverse-integer.rb: -------------------------------------------------------------------------------- 1 | def reverse(x) 2 | max = 0xffffffff >> 1 3 | max_last_digit = max % 10 4 | max_minus_digit = max / 10 5 | reverse = 0 6 | until x.zero? 7 | digit = x.remainder(10) 8 | return 0 if reverse.abs > max_minus_digit || (reverse.abs == max_minus_digit && digit > max_last_digit) 9 | 10 | reverse = (reverse * 10) + digit 11 | x = (x / 10.0).to_i 12 | end 13 | reverse 14 | end 15 | -------------------------------------------------------------------------------- /ruby/0202-happy-number.rb: -------------------------------------------------------------------------------- 1 | def is_happy(n) 2 | visit = Set.new([]) 3 | 4 | while !visit.include?(n) 5 | visit.add(n) 6 | n = sum_of_squares(n) 7 | return true if n==1 8 | end 9 | 10 | return false 11 | 12 | end 13 | 14 | def sum_of_squares(n) 15 | output = 0 16 | while n != 0 17 | digit = n%10 18 | output += (digit*digit) 19 | n = n/10 20 | end 21 | return output 22 | end -------------------------------------------------------------------------------- /ruby/0242-valid-anagram.rb: -------------------------------------------------------------------------------- 1 | def is_anagram(s, t) 2 | return false unless s.length == t.length 3 | 4 | hash = Hash.new(0) 5 | s.each_char.with_index do |_, idx| 6 | hash[s[idx]] += 1 7 | hash[t[idx]] -= 1 8 | end 9 | hash.all? { |_k, v| v.zero? } 10 | end 11 | 12 | # For nlogn time and O(1) space, can sort then check if equal 13 | def is_anagram(s, t) 14 | s.chars.sort.join == t.chars.sort.join 15 | end 16 | -------------------------------------------------------------------------------- /ruby/1899-merge-triplets-to-form-target-triplet.rb: -------------------------------------------------------------------------------- 1 | def merge_triplets(triplets, target) 2 | good = Set.new([]) 3 | triplets.each do |triplet| 4 | next if ((triplet[0] > target[0]) || (triplet[1] > target[1]) || (triplet[2] > target[2])) 5 | triplet.each_with_index do |value,index| 6 | good.add(index) if value == target[index] 7 | end 8 | end 9 | return good.length == 3 10 | end -------------------------------------------------------------------------------- /typescript/0118-pascals-triangle.ts: -------------------------------------------------------------------------------- 1 | function generate(numRows: number): number[][] { 2 | let res = [[1]]; 3 | 4 | for (let i = 0; i < numRows - 1; i++) { 5 | let temp = [0, ...res.at(-1), 0]; 6 | let row = []; 7 | for (let j = 0; j < res.at(-1).length + 1; j++) { 8 | row.push(temp[j] + temp[j + 1]); 9 | } 10 | res.push(row); 11 | } 12 | return res; 13 | } 14 | -------------------------------------------------------------------------------- /typescript/0283-move-zeroes.ts: -------------------------------------------------------------------------------- 1 | /** 2 | Do not return anything, modify nums in-place instead. 3 | */ 4 | function moveZeroes(nums: number[]): void { 5 | let left = 0; 6 | 7 | for (let index in nums) { 8 | if (nums[index] != 0) { 9 | const temp = nums[left]; 10 | nums[left] = nums[index]; 11 | nums[index] = temp; 12 | left++; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /dart/0014-longest-common-prefix.dart: -------------------------------------------------------------------------------- 1 | class Solution { 2 | String longestCommonPrefix(List strs) { 3 | String res = ""; 4 | for (int i=0; i= s.length || strs[0][i] != s[i]){ 7 | return res; 8 | } 9 | } 10 | res += strs[0][i]; 11 | } 12 | return res; 13 | } 14 | } -------------------------------------------------------------------------------- /go/0665-non-decreasing-array.go: -------------------------------------------------------------------------------- 1 | func checkPossibility(nums []int) bool { 2 | changed := false 3 | 4 | for i := 0; i < len(nums)-1; i++ { 5 | if nums[i] <= nums[i+1] { 6 | continue 7 | } 8 | if changed { 9 | return false 10 | } 11 | if i == 0 || nums[i+1] >= nums[i-1] { 12 | nums[i] = nums[i+1] 13 | } else { 14 | nums[i+1] = nums[i] 15 | } 16 | 17 | changed = true 18 | } 19 | 20 | return true 21 | } -------------------------------------------------------------------------------- /java/0705-design-hashset.java: -------------------------------------------------------------------------------- 1 | class MyHashSet { 2 | boolean [] setArray; 3 | public MyHashSet() { 4 | setArray=new boolean[(int)1e6+1]; 5 | } 6 | 7 | public void add(int key) { 8 | setArray[key]=true; 9 | } 10 | 11 | public void remove(int key) { 12 | setArray[key]=false; 13 | } 14 | 15 | public boolean contains(int key) { 16 | return setArray[key]; 17 | } 18 | } -------------------------------------------------------------------------------- /java/2544-alternating-digit-sum: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int alternateDigitSum(int n) { 3 | 4 | int result =0; 5 | int flag = 1; 6 | 7 | String num = String.valueOf(n); 8 | for(int i=0; i> 1, i & 1]; 10 | const bits = dp[mid] + bit; 11 | 12 | dp.push(bits); 13 | } 14 | 15 | return dp; 16 | }; 17 | -------------------------------------------------------------------------------- /javascript/1768-merge-strings-alternately.js: -------------------------------------------------------------------------------- 1 | // Time complexity: O(n) 2 | // Space complexity: O(n) 3 | 4 | var mergeAlternately = function (word1, word2) { 5 | const buffer = []; 6 | 7 | for (let i = 0; i < word1.length || i < word2.length; i++) { 8 | if (i < word1.length) buffer.push(word1[i]); 9 | if (i < word2.length) buffer.push(word2[i]); 10 | } 11 | 12 | return buffer.join(''); 13 | }; 14 | -------------------------------------------------------------------------------- /kotlin/0455-assign-cookies.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun findContentChildren(g: IntArray, s: IntArray): Int { 3 | g.sort() 4 | s.sort() 5 | 6 | var i = 0 7 | var j = 0 8 | while (i < g.size) { 9 | while (j < s.size && g[i] > s[j]) j++ 10 | if (j == s.size) break 11 | i++ 12 | j++ 13 | } 14 | 15 | return i 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /python/0187-repeated-dna-sequences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findRepeatedDnaSequences(self, s: str) -> list[str]: 3 | result = set() 4 | previous_sequences = set() 5 | for i in range(len(s) - 9): 6 | current = s[i:i+10] 7 | if current in previous_sequences: 8 | result.add(current) 9 | previous_sequences.add(current) 10 | return list(result) 11 | -------------------------------------------------------------------------------- /ruby/0128-longest-consecutive-sequence.rb: -------------------------------------------------------------------------------- 1 | def longest_consecutive(nums) 2 | set = Set.new(nums) 3 | set.reduce(0) do |longest, num| 4 | if !set.include?(num-1) 5 | length = 0 6 | while set.include?(num + length) do 7 | length += 1 8 | end 9 | next(longest > length ? longest : length) 10 | end 11 | 12 | longest 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /ruby/0543-diameter-of-binary-tree.rb: -------------------------------------------------------------------------------- 1 | def diameter_of_binary_tree(root) 2 | $max = 0 3 | max_height = diameter(root) 4 | $max > max_height ? $max : max_height 5 | end 6 | 7 | def diameter(root) 8 | return -1 if root.nil? 9 | 10 | left = 1 + diameter(root.left) 11 | right = 1 + diameter(root.right) 12 | diameter = left + right 13 | $max = diameter if diameter > $max 14 | 15 | left > right ? left : right 16 | end 17 | -------------------------------------------------------------------------------- /typescript/0187-repeated-dna-sequences.ts: -------------------------------------------------------------------------------- 1 | function findRepeatedDnaSequences(s: string): string[] { 2 | let seen = new Set(); 3 | let res = new Set(); 4 | 5 | for (let i = 0; i < s.length - 9; i++) { 6 | let cur = s.slice(i, i + 10); 7 | if (seen.has(cur)) { 8 | res.add(cur); 9 | } 10 | seen.add(cur); 11 | } 12 | 13 | return Array.from(res); 14 | } 15 | -------------------------------------------------------------------------------- /c/0367-valid-perfect-square.c: -------------------------------------------------------------------------------- 1 | bool isPerfectSquare(int num) { 2 | int low = 0; 3 | int high = num; 4 | 5 | while(low <= high){ 6 | long long int mid = low + (high - low)/2; 7 | 8 | if(mid * mid == num) 9 | return true; 10 | 11 | if(mid * mid < num) 12 | low = mid + 1; 13 | else 14 | high = mid - 1; 15 | } 16 | return false; 17 | } -------------------------------------------------------------------------------- /cpp/0027-remove-element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeElement(vector& nums, int val) { 4 | int n=nums.size(); 5 | int count=0; 6 | for(int i=0;i& nums, int k) { 11 | sort(nums.begin(),nums.end(),st); 12 | return nums[nums.size()-k]; 13 | 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /cpp/1985-find-the-kth-largest-integer-in-the-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | static bool st(string &a,string &b){ 4 | if(a.size()==b.size()) return a& nums, int k) { 11 | sort(nums.begin(),nums.end(),st); 12 | return nums[nums.size()-k]; 13 | 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /go/0374-guess-number-higher-or-lower.go: -------------------------------------------------------------------------------- 1 | func guessNumber(n int) int { 2 | low := 1 3 | high := n 4 | 5 | for true { 6 | mid := low + (high - low)/2 7 | myGuess := guess(mid) 8 | if myGuess == 1 { 9 | low = mid + 1 10 | } else if myGuess == -1 { 11 | high = mid - 1 12 | } else { 13 | return mid 14 | } 15 | } 16 | return -1 17 | } 18 | -------------------------------------------------------------------------------- /java/1029-two-city-scheduling.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int twoCitySchedCost(int[][] costs) { 3 | Arrays.sort(costs, 4 | (a, b) -> (a[1] - a[0]) - (b[1] - b[0]) 5 | ); 6 | 7 | int n = costs.length / 2; 8 | int total = 0; 9 | for (int i = 0; i < n; i++) { 10 | total += costs[i][1] + costs[i + n][0]; 11 | } 12 | 13 | return total; 14 | } 15 | } -------------------------------------------------------------------------------- /java/2405-optimal-partition-of-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int partitionString(String s) { 3 | Set set = new HashSet<>(); 4 | int res = 1; 5 | for (char ch : s.toCharArray()) { 6 | if (set.contains(ch)) { 7 | set = new HashSet<>(); 8 | res++; 9 | } 10 | set.add(ch); 11 | } 12 | return res; 13 | } 14 | } -------------------------------------------------------------------------------- /javascript/0268-missing-number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/missing-number/ 3 | * Time O(N) | Space O(1) 4 | * @param {number[]} nums 5 | * @return {number} 6 | */ 7 | var missingNumber = function (nums, missingNumber = nums.length) { 8 | for (let i = 0; i < nums.length; i++) { 9 | const xor = i ^ nums[i]; 10 | 11 | missingNumber ^= xor; 12 | } 13 | 14 | return missingNumber; 15 | }; 16 | -------------------------------------------------------------------------------- /javascript/1137-n-th-tribonacci-number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {number} 4 | */ 5 | var tribonacci = function (n) { 6 | let t = [0, 1, 1]; 7 | 8 | if (n < 3) return t[n]; 9 | 10 | for (let i = 3; i < n + 1; i++) { 11 | [t[0], t[1], t[2]] = [t[1], t[2], sum(t)]; 12 | } 13 | 14 | return t[2]; 15 | }; 16 | 17 | function sum(arr) { 18 | return arr.reduce((a, b) => a + b); 19 | } 20 | -------------------------------------------------------------------------------- /kotlin/0867-transpose-matrix.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun transpose(matrix: Array): Array { 3 | val m = matrix.size 4 | val n = matrix[0].size 5 | val res = Array (n) { IntArray (m) } 6 | 7 | for (i in 0 until m) { 8 | for (j in 0 until n) { 9 | res[j][i] = matrix[i][j] 10 | } 11 | } 12 | 13 | return res 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /kotlin/0997-find-the-town-judge.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun findJudge(n: Int, trust: Array): Int { 3 | val delta = IntArray (n + 1) 4 | 5 | for ((src, dst) in trust) { 6 | delta[dst]++ 7 | delta[src]-- 8 | } 9 | 10 | for (i in 1..n) { 11 | if (delta[i] == n - 1) 12 | return i 13 | } 14 | 15 | return -1 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /kotlin/1523-count-odd-numbers-in-an-interval-range.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun countOdds(low: Int, high: Int): Int { 3 | 4 | var res = 0 5 | res += (high - low) / 2 6 | if (low % 2 == 1 || high % 2 == 1) res += 1 7 | 8 | return res 9 | } 10 | } 11 | 12 | //shorter 1 line solution 13 | class Solution { 14 | fun countOdds(low: Int, high: Int) = (high + 1) / 2 - low / 2 15 | } 16 | -------------------------------------------------------------------------------- /kotlin/2390-removing-stars-from-a-string.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun removeStars(s: String): String { 3 | val stack = LinkedList() 4 | 5 | for (c in s) { 6 | if (c == '*' && stack.isNotEmpty()) { 7 | stack.removeLast() 8 | } else { 9 | stack.addLast(c) 10 | } 11 | } 12 | 13 | return stack.joinToString("") 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /ruby/0050-powx-n.rb: -------------------------------------------------------------------------------- 1 | 2 | def my_pow(x, n) 3 | solution = multiply(x, n.abs) 4 | 5 | if n>=0 6 | return solution 7 | else 8 | return (1/solution) 9 | 10 | end 11 | end 12 | 13 | 14 | def multiply(x,n) 15 | return 0 if x==0 16 | return 1 if n==0 17 | result = multiply((x*x),n/2) 18 | if (n%2 ==1) 19 | return (x * result) 20 | else 21 | return result 22 | end 23 | end -------------------------------------------------------------------------------- /rust/0026-remove-duplicates-from-sorted-array.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn remove_duplicates(nums: &mut Vec) -> i32 { 3 | let mut dup_count = 0; 4 | 5 | for i in 1..nums.len() { 6 | if nums[i] == nums[i - 1] { 7 | dup_count += 1 8 | } 9 | 10 | nums[i - dup_count] = nums[i]; 11 | } 12 | 13 | (nums.len() - dup_count) as i32 14 | } 15 | } -------------------------------------------------------------------------------- /rust/0048-rotate-image.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn rotate(matrix: &mut [Vec]) { 3 | matrix.reverse(); 4 | let len = matrix.len(); 5 | for i in 0..len { 6 | for j in i..len { 7 | let x = matrix[i][j]; 8 | let y = matrix[j][i]; 9 | matrix[j][i] = x; 10 | matrix[i][j] = y; 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /scala/0198-house-robber.scala: -------------------------------------------------------------------------------- 1 | object Solution { 2 | def rob(nums: Array[Int]): Int = { 3 | var (prevTwoMaxProfit, prevMaxProfit) = (0, 0) 4 | 5 | for (currCash <- nums) { 6 | val currProfit = (currCash + prevTwoMaxProfit).max(prevMaxProfit) 7 | prevTwoMaxProfit = prevMaxProfit 8 | prevMaxProfit = currProfit 9 | } 10 | 11 | return prevMaxProfit 12 | } 13 | } -------------------------------------------------------------------------------- /swift/0094-binary-tree-inorder-traversal.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func inorderTraversal(_ root: TreeNode?) -> [Int] { 3 | var result: [Int] = [] 4 | func rec(_ node: TreeNode?) { 5 | guard let node = node else { return } 6 | rec(node.left) 7 | result.append(node.val) 8 | rec(node.right) 9 | } 10 | 11 | rec(root) 12 | return result 13 | } 14 | } -------------------------------------------------------------------------------- /swift/0344-reverse-string.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func reverseString(_ s: inout [Character]) { 3 | var left: Int = 0 4 | var right: Int = s.count - 1 5 | 6 | while left < right { 7 | let temp: Character = s[left] 8 | 9 | s[left] = s[right] 10 | s[right] = temp 11 | 12 | left += 1 13 | right -= 1 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /c/0080-remove-duplicates-from-sorted-array-ii.c: -------------------------------------------------------------------------------- 1 | int removeDuplicates(int* nums, int numsSize) { 2 | int k = 1; 3 | int sequence = 0; 4 | for (int pos = 1; pos < numsSize; pos++) { 5 | int repNum = nums[pos] == nums[k - 1]; 6 | if (sequence && repNum) 7 | k--; 8 | else if (repNum) 9 | sequence = 1; 10 | else 11 | sequence = 0; 12 | nums[k] = nums[pos]; 13 | k++; 14 | } 15 | return k; 16 | } 17 | -------------------------------------------------------------------------------- /go/0300-longest-increasing-subsequence.go: -------------------------------------------------------------------------------- 1 | func lengthOfLIS(nums []int) int { 2 | cache := make([]int, len(nums)) 3 | LIS := 0 4 | for i := range nums { 5 | curMax := 0 6 | for j := 0; j < i+1; j++ { 7 | if nums[j] < nums[i] { 8 | if curMax < cache[j] { 9 | curMax = cache[j] 10 | } 11 | } 12 | } 13 | cache[i] = curMax + 1 14 | if cache[i] > LIS { 15 | LIS = cache[i] 16 | } 17 | } 18 | return LIS 19 | } 20 | -------------------------------------------------------------------------------- /java/0283-move-zeroes.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void moveZeroes(int[] nums) { 3 | //Do not return anything, modify nums in-place instead. 4 | int l = 0; 5 | for(int r = 0; r < nums.length; r++) 6 | if(nums[r] != 0) { 7 | int tmp = nums[l]; 8 | nums[l] = nums[r]; 9 | nums[r] = tmp; 10 | l += 1; 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/1359-count-all-valid-pickup-and-delivery-options.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countOrders(int n) { 3 | int MOD = (int) 1e9 + 7; 4 | int slots = 2*n; 5 | long res = 1; 6 | 7 | while(slots > 0){ 8 | int valid_choices = slots*(slots - 1)/2; 9 | res = (res * valid_choices) % MOD; 10 | slots -= 2; 11 | } 12 | return (int)res; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/1603-design-parking-system.java: -------------------------------------------------------------------------------- 1 | class ParkingSystem { 2 | 3 | int[] space; 4 | 5 | public ParkingSystem(int big, int medium, int small) { 6 | this.space = new int[] { big, medium, small }; 7 | } 8 | 9 | public boolean addCar(int carType) { 10 | if (this.space[carType - 1] == 0) { 11 | return false; 12 | } 13 | this.space[carType - 1]--; 14 | return true; 15 | } 16 | } -------------------------------------------------------------------------------- /javascript/2439-minimize-maximum-of-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Time O(n) | Space O(1) 3 | * @param {number[]} nums 4 | * @return {number} 5 | */ 6 | var minimizeArrayValue = function (nums) { 7 | let currTotal = nums[0]; 8 | let max = nums[0]; 9 | 10 | for (let i = 1; i < nums.length; i++) { 11 | currTotal += nums[i]; 12 | max = Math.max(max, Math.ceil(currTotal / (i + 1))); 13 | } 14 | return max; 15 | }; 16 | -------------------------------------------------------------------------------- /kotlin/2405-optimal-partition-of-string.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun partitionString(s: String): Int { 3 | val hs = HashSet() 4 | var res = 0 5 | 6 | for (c in s) { 7 | if (hs.contains(c)) { 8 | res++ 9 | hs.clear() 10 | } 11 | hs.add(c) 12 | } 13 | 14 | return if(hs.size != 0) res + 1 else res 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /kotlin/2439-minimize-maximum-of-array.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun minimizeArrayValue(nums: IntArray): Int { 3 | var res = nums[0].toDouble() 4 | var sum = nums[0].toDouble() 5 | 6 | for (i in 1..nums.lastIndex) { 7 | sum += nums[i].toDouble() 8 | var current = Math.ceil(sum / (i + 1)) 9 | res = maxOf(res, current) 10 | } 11 | 12 | return res.toInt() 13 | } 14 | -------------------------------------------------------------------------------- /kotlin/2870-minimum-number-of-operations-to-make-array-empty.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun minOperations(nums: IntArray): Int { 3 | val count = nums.asIterable().groupingBy { it }.eachCount() 4 | 5 | var res = 0 6 | for (c in count.values) { 7 | if (c == 1) return -1 8 | res += (c / 3) + if (c % 3 > 0) 1 else 0 // "Ceil" function 9 | } 10 | 11 | return res 12 | } 13 | } 14 | --------------------------------------------------------------------------------