├── hard ├── 0032-longest-valid-parantheses │ └── sol.cpp ├── 1526-min-increments │ └── sol.py ├── 0440-kth-smallest-lexicographical-number │ └── sol.cpp ├── 0084-largest-rectangle-in-histogram │ └── sol.cpp ├── 0042-trapping-rain-water │ └── sol.cpp ├── 0968-BT-cameras │ └── sol.py └── 0115-distinct-subsequences │ └── sol.py ├── .vscode └── settings.json ├── easy ├── 1523-count-odd-nos-in-range │ └── sol.py ├── 2481-min-cuts-dividing-circle │ └── sol.cpp ├── 2413-smallest-even-multiple │ └── sol.cpp ├── 1470-shuffle-array │ └── sol.py ├── 0461-hamming-dist │ └── sol.py ├── 0009-palindrome-number │ ├── sol.go │ └── sol.py ├── 1342-steps-reduce-number-to-zero │ └── sol.py ├── 3190-min-operations-make-elements-div-by-3 │ └── sol.cpp ├── 0717-1bit-2bit-chars │ └── sol.py ├── 0231-power-of-two │ ├── sol.py │ └── sol.cpp ├── 0268-missing-num │ └── sol.py ├── 0326-power-of-three │ └── sol.cpp ├── 0121-best-time-to-buy-sell-stock │ ├── sol.py │ └── sol.cpp ├── 1716-money-in-leetcode-bank │ └── sol.py ├── 2154-keep-multiplying-found-vals-by-2 │ └── sol.py ├── 1281-subtract-product-sum-of-integer │ └── sol.cpp ├── 0485-max-consecutive-ones-I │ └── sol.py ├── 2600-k-items-max-sum │ └── sol.cpp ├── 0001-2sum │ ├── sol.ts │ ├── sol.py │ └── sol.cpp ├── 1317-two-non-zero-int-sum │ └── sol.py ├── 1323-max-69-num │ └── sol.py ├── 0206-reverse-linked-list │ └── sol.cpp ├── 0342-power-of-four │ └── sol.py ├── 1844-replace-digit-with-char │ └── sol.cpp ├── 1518-water-bottles │ └── sol.cpp ├── 1863-sum-of-all-subset-XOR-total │ └── sol.cpp ├── 2220-min-bit-flips-to-convert-number │ └── sol.cpp ├── 1437-check-all-1s-atleast-k-away │ ├── sol.py │ └── sol.cpp ├── 3392-total-subarrays-with-condition │ └── sol.cpp ├── 1822-sign-of-product-of-array │ └── sol.cpp ├── 3370-min-num-all-set-bits │ └── sol.py ├── 0026-remove-duplicates │ └── sol.cpp ├── 0448-nums-disappeared-in-arr │ └── sol.py ├── 1018-binary-prefix-div-by-5 │ └── sol.cpp ├── 2144-min-cost-to-buy-candy-with-discount │ └── sol.cpp ├── 0217-contains-duplicates │ └── sol.cpp ├── 1710-max-units-on-truck │ └── sol.py ├── 0028-occurence-of-first-string-index │ └── sol.cpp ├── 3289-sneaky-digits-of-digitville │ └── sol.py ├── 3461-string-equal-after-operations-I │ └── sol.py ├── 2169-operatoins-to-obtain-zero │ └── sol.py ├── 2206-divide-array-equal-pairs │ └── sol.cpp ├── 2490-circular-sentence │ └── sol.cpp ├── 0069-sqrtx │ └── sol.py ├── 0657-robot-return-to-origin │ └── sol.cpp ├── 0700-search-in-BST │ └── sol.py ├── 0746-min-cost-climbing-stairs │ └── sol.cpp ├── 3423-max-diff-in-circular-array │ └── sol.cpp ├── 1539-kth-missing-positive-num │ └── sol.py ├── 3194-min-avg-of-min-max-in-array │ └── sol.cpp ├── 1025-divisor-game │ └── sol.py ├── 1550-consecutive-odds │ └── sol.cpp ├── 0119-pascals-triangle-II │ └── sol.py ├── 0434-total-segments-in-string │ └── sol.cpp ├── 3000-max-area-of-longest-diag │ └── sol.py ├── 0796-rotate-string │ └── sol.cpp ├── 3432-partitions-even-odd-sums │ └── sol.py ├── 1588-sum-odd-length-subarrays │ └── sol.py ├── 3304-kth-char-in-string-game-I │ └── sol.cpp ├── 3151-special-array-I │ └── sol.cpp ├── 0202-happy-number │ ├── sol.ts │ ├── sol.py │ └── sol.cpp ├── 0543-diameter-of-binary-tree │ └── sol.cpp ├── 0118-pascal-triangle │ └── sol.py ├── 0557-reverse-word-in-string-III │ └── sol.py ├── 1800-max-ascending-subarray-sum │ └── sol.cpp ├── 3168-min-chairs-in-waiting-room │ └── sol.cpp ├── 3174-clear-digits │ └── sol.cpp ├── 1941-characters-have-equal-occurences │ └── sol.cpp ├── 2022-1d-into-2d-array │ └── sol.cpp ├── 0169-majority-element │ └── sol.py ├── 0367-valid-perfect-square │ └── sol.cpp ├── 0014-longest-common-prefix │ └── sol.cpp ├── 0653-2-sum-IV-input-is-BST │ └── sol.py ├── 1752-check-if-array-is-sorted-and-rotated │ └── sol.cpp ├── 0234-palindrome-LL │ ├── sol.cpp │ └── sol.go ├── 0876-middle-of-LL │ └── sol.cpp ├── 3375-min-operations-make-arr-vals-equals-K │ └── sol.cpp ├── 1957-delete-chars-to-make-fancy-string │ └── sol.cpp ├── 0111-min-depth-of-BT │ └── sol.cpp ├── 2574-left-right-sum-difference │ └── sol.cpp ├── 1854-max-population-year │ └── sol.cpp ├── 0383-ransom-note │ └── sol.cpp ├── 0387-first-unique-char │ └── sol.py ├── 0283-move-zeroes │ └── sol.cpp ├── 0303-range-sum-query-immutable │ └── sol.py ├── 2965-find-missing-and-repeated-values │ └── sol.cpp ├── 0643-max-average-subarray-I │ └── sol.cpp ├── 2379-min-recolors-for-K-black-blocks │ └── sol.cpp ├── 0035-search-insert-position │ └── sol.cpp ├── 2190-most-frequent-num-following-key-in-array │ └── sol.cpp ├── 0409-longest-palindrome │ └── sol.py ├── 3264-final-arr-state-after-K-multiplications-I │ └── sol.cpp ├── 0706-design-hashmap │ └── sol.py ├── 2264-largest-3-same-number │ └── sol.py ├── 1422-max-score-after-splitting-string │ └── sol.cpp ├── 2558-take-largest-from-richest-pile │ └── sol.cpp ├── 0703-kth-largest-element-in-stream │ └── sol.py ├── 1652-defuse-bomb │ └── sol.cpp ├── 1331-rank-transform-of-array │ └── sol.cpp ├── 0104-max-depth-of-binary-tree │ └── sol.cpp ├── 0374-guess-number-higher-or-lower │ └── sol.cpp ├── 1603-design-parking-system │ └── sol.cpp ├── 0404-left-leaf-sum │ └── sol.cpp ├── 1790-check-one-swap-makes-string-equal │ └── sol.cpp ├── 0232-implement-queue-using-stacks │ └── sol.cpp ├── 0933-total-recents-callls │ └── sol.py ├── 0226-invert-binary-tree │ └── sol.cpp ├── 2696-min-string-length-after-removing-substrings │ └── sol.cpp └── 0257-binary-tree-paths │ └── sol.py ├── medium ├── 0912-sort-an-array │ └── sol.cpp ├── 1780-check-number-power-of-three │ └── sol.cpp ├── 0198-house-robber │ ├── sol.py │ └── sol.cpp ├── 2579-total-colored-cells │ ├── 2024-11-01.cpp │ └── 2025-03-05.cpp ├── 3179-nth-value-after-k-seconds │ └── sol.py ├── 0442-duplicates-in-arr │ └── sol.py ├── 3228-max-moves-shift-one-to-right │ └── sol.py ├── 2320-total-ways-to-place-house │ └── sol.py ├── 2914-min-changes-to-make-binary-string-beautiful │ └── sol.cpp ├── 3021-alice-bob-flower-game │ └── sol.py ├── 1980-unqiue-binary-string │ └── sol.cpp ├── 3760-max-substrings-distinct-start │ └── sol.py ├── 0540-single-element-in-sorted-array │ └── sol.cpp ├── 3577-computer-unlocking-permutations │ └── sol.py ├── 0053-max-subarray │ └── sol.py ├── 3147-take-max-energy-from-dungeon │ └── sol.py ├── 0357-count-digits-with-unique-digits │ └── sol.cpp ├── 0007-reverse-integer │ └── sol.cpp ├── 0435-non-overlapping-intervals │ └── sol.py ├── 3137-operations-to-make-K-periodic │ └── sol.py ├── 0077-combinations │ └── sol.py ├── 0973-k-closest-points-to-origin │ └── sol.py ├── 1010-pairs-divisible-by-60 │ └── sol.cpp ├── 3727-max-alternating-square-sum │ └── sol.py ├── 0334-increasing-triplet-subsequence │ └── sol.py ├── 3759-elements-with-atleast-K-greater-elements │ └── sol.py ├── 0848-shifting-letters │ └── sol.cpp ├── 1143-LCS │ └── sol.py ├── 2938-seperate-white-black-balls │ └── sol.cpp ├── 0056-merge-intervals │ ├── sol.py │ └── sol.cpp ├── 2139-min-moves-to-reach-target-score │ └── sol.cpp ├── 0062-unique-paths │ └── sol.cpp ├── 0279-perfect-squares │ └── sol.cpp ├── 0633-sum-of-square-numbers │ └── sol.cpp ├── 0313-super-ugly-number │ └── sol.py ├── 3185-total-pairs-forming-complete-days-II │ └── sol.cpp ├── 0064-min-path-sum │ ├── sol.py │ └── sol.cpp ├── 3653-xor-range-multiplication-after-queries-I │ └── sol.py ├── 1833-max-icecream-bars │ └── sol.cpp ├── 3195-smallest-area-covering-all-ones-I │ └── sol.py ├── 0647-palindromic-substrings │ └── sol.py ├── 0646-max-len-pair-chain │ └── sol.py ├── 2125-total-laser-beams-in-bank │ ├── sol.py │ └── sol.cpp ├── 1513-total-substrings-only-1s │ └── sol.py ├── 0238-product-of-arr-except-self │ └── sol.py ├── 0692-top-K-frequent-words │ └── sol.py ├── 1726-tuple-with-same-product │ └── sol.cpp ├── 0299-bulls-n-cows │ └── sol.py ├── 2109-adding-spaces-to-string │ └── sol.cpp ├── 0189-rotate-array │ └── sol.cpp ├── 0606-string-from-BT │ └── sol.py ├── 0090-subsets-II │ └── sol.ts ├── 0204-total-primes │ └── sol.cpp ├── 0386-lexicographical-numbers │ └── sol.cpp ├── 0078-subsets │ └── sol.cpp ├── 1493-longest-subarray-after-deleting-one-zero │ └── sol.py ├── 1352-last-K-products │ └── sol.cpp ├── 2364-count-bad-pairs │ └── sol.cpp ├── 0153-min-in-rotated-sorted-array │ └── sol.cpp ├── 0525-contiguous-array │ └── sol.cpp ├── 3163-string-compression-III │ └── sol.cpp ├── 0011-container-most-water │ └── sol.py ├── 1545-kth-bit-in-nth-binary-string │ └── sol.cpp ├── 0300-longest-increasing-subsequence │ └── sol.cpp ├── 0516-longest-palindromic-subsequence │ └── sol.py ├── 0050-pow │ └── sol.py ├── 3201-valid-subsequence-I │ └── sol.py ├── 0201-bitwise-AND-of-number-range │ └── sol.cpp ├── 0921-min-add-to-make-paranthesis-valid │ └── sol.cpp ├── 0038-count-and-say │ └── sol.cpp ├── 0523-continuous-subarray-sum │ └── sol.cpp ├── 3767-max-points-after-K-tasks │ └── sol.py ├── 0400-nth-digit │ └── sol.cpp ├── 1695-max-erasure-value │ └── sol.py ├── 0264-ugly-number-II │ └── sol.py ├── 0788-rotated-digits │ └── sol.py ├── 3381-max-subarray-sum-of-length-div-by-K │ └── sol.py ├── 0075-sort-colors │ ├── sol.cpp │ └── sol.py ├── 0799-champagne-tower │ └── sol.py ├── 2348-zero-filled-subarrays │ └── sol.py ├── 2028-find-missing-observations │ └── sol.cpp ├── 0080-remove-duplicates-from-sorted-array-II │ └── sol.cpp ├── 3761-min-abs-diff-bw-mirror-pairs │ └── sol.py ├── 0003-longest-substring-without-repeating-characters │ └── sol.cpp ├── 0048-rotate-image │ └── sol.py ├── 0096-unique-BSTs │ └── sol.py ├── 1283-smallest-divisor-within-budget │ └── sol.py ├── 1261-elements-in-contaminated-binary-tree │ └── sol.cpp ├── 1277-submatrices-with-ones │ └── sol.py ├── 3295-report-spam-message │ └── sol.cpp ├── 0086-partition-list │ └── sol.py ├── 3542-min-ops-all-elements-zero │ └── sol.py ├── 0343-integer-break │ └── sol.cpp ├── 3531-count-covered-buildings │ └── sol.py ├── 0236-lowest-common-ancestor-in-binary-tree │ └── sol.cpp ├── 0039-combination-sum │ └── sol.py ├── 2095-delete-middle-node-of-linked-list │ └── sol.cpp ├── 2304-min-cost-grid-path │ └── sol.py ├── 2044-total-max-OR-subsets │ └── sol.cpp ├── 0151-reverse-word-in-string │ └── sol.cpp ├── 2530-maximal-score-after-k-operations │ └── sol.cpp ├── 0155-min-stack │ └── sol.cpp ├── 0560-subarray-sum-equals-K │ └── sol.cpp ├── 2270-total-ways-to-split-array │ └── sol.cpp ├── 3191-min-switch-to-make-binary-array-equal-to-one │ └── sol.cpp ├── 1208-equal-substring-within-budget │ └── sol.py ├── 0394-decode-string │ └── sol.py ├── 1605-valid-matrix-given-row-col-sums │ └── sol.cpp ├── 2410-max-matching-of-players-trainers │ └── sol.cpp ├── 0322-coin-change │ └── sol.cpp ├── 1004-max-consecutive-ones-III │ └── sol.py ├── 1584-min-cost-connect-all-points │ └── sol.py ├── 0650-2-keys-keyboard │ └── sol.cpp ├── 0983-min-ticket-cost │ └── sol.py ├── 1524-total-subarrays-with-odd-sum │ └── sol.cpp ├── 2090-k-radius-subarray-averages │ └── sol.cpp ├── 0781-rabbits-in-forest │ └── sol.cpp ├── 0852-peak-index-in-mountain-arr │ └── sol.py ├── 0045-jump-game-II │ └── sol.cpp ├── 1318-min-flips-to-make-aORb-equals-c │ └── sol.cpp ├── 0148-sort-list │ └── sol.cpp ├── 0684-redundant-connection │ └── sol.py ├── 0055-jump-game │ └── sol.cpp ├── 0063-unique-paths-II │ └── sol.py ├── 0091-decode-ways │ └── sol.py ├── 1922-good-numbers │ └── sol.py ├── 0739-daily-temperatures │ └── sol.cpp ├── 0814-BT-pruning │ └── sol.cpp ├── 0443-string-compression │ └── sol.cpp ├── 0518-coin-change-II │ └── sol.cpp ├── 0235-lowest-common-ancestor-of-BST │ └── sol.cpp ├── 0413-artihmetic-slices │ └── sol.py ├── 1123-lowest-common-ancestor-of-deepest-nodes │ └── sol.cpp ├── 2598-smallest-missing-nonNegative-after-operations │ └── sol.py ├── 1749-max-abs-sum-of-subarray │ └── sol.cpp ├── 0503-next-greater-element-II │ └── sol.cpp ├── 0071-simplify-path │ └── sol.cpp ├── 2161-partition-by-pivot │ └── sol.py ├── 3217-delete-nodes-in-list │ └── sol.py ├── 1404-total-steps-to-reduce-binary-to-one │ └── sol.cpp ├── 2684-max-no-of-moves-in-matrix │ └── sol.cpp ├── 3075-maximize-happiness-of-selected-children │ └── sol.cpp ├── 3542-min-op-all-arr-elem-to-zero │ └── sol.py ├── 0187-dna-sequences │ └── sol.cpp ├── 1590-make-sum-divisible-by-P │ └── sol.cpp ├── 1899-merge-target-from-target-triplet │ └── sol.py ├── 2761-prime-pairs-with-target-sum │ └── sol.cpp ├── 1578-min-time-rope-colorful │ └── sol.py ├── 2140-solving-questions-with-brainpower │ └── sol.cpp ├── 0986-interval-list-intersections │ └── sol.cpp ├── 1003-check-word-valid-after-substitution │ └── sol.cpp ├── 1371-longest-substring-with-even-count-vowels │ └── sol.cpp ├── 0284-peeking-iterator │ └── sol.cpp ├── 1930-unique-3-len-palindromic-subsequences │ └── sol.py ├── 0092-reverse-LL-II │ └── sol.py ├── 0129-sum-root-to-leaf-nodes │ └── sol.cpp ├── 0508-most-frequent-subtree-sum │ └── sol.cpp ├── 1721-swapping-nodes-in-LL │ └── sol.cpp ├── 1904-full-rounds-played │ └── sol.py ├── 2419-longest-subarray-with-max-bitwise-AND │ └── sol.cpp ├── 0763-partition-labels │ └── sol.py ├── 2559-count-vowel-range-in-string │ └── sol.cpp ├── 2807-insert-gcd-in-LL │ └── sol.cpp ├── 3160-distinct-ball-colors │ └── sol.cpp └── 3583-special-triplets │ └── sol.py └── README.md /hard/0032-longest-valid-parantheses/sol.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "C_Cpp.errorSquiggles": "disabled" 3 | } -------------------------------------------------------------------------------- /easy/1523-count-odd-nos-in-range/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countOdds(self, low: int, high: int) -> int: 3 | n = high - low + 1 4 | if n & 1: return (low&1) + (n-1)//2 5 | else: return n//2 -------------------------------------------------------------------------------- /easy/2481-min-cuts-dividing-circle/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | int numberOfCuts(int n) { 6 | if(n==1) return 0; 7 | if(n%2==0) return n/2; 8 | return n; 9 | } 10 | }; -------------------------------------------------------------------------------- /easy/2413-smallest-even-multiple/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | int smallestEvenMultiple(int n) { 6 | if(n==1) return 2; 7 | if(n%2==0) return n; 8 | return n*2; 9 | } 10 | }; -------------------------------------------------------------------------------- /easy/1470-shuffle-array/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shuffle(self, nums: List[int], n: int) -> List[int]: 3 | arr = [] 4 | 5 | for i in range(n): 6 | arr.append(nums[i]) 7 | arr.append(nums[i+n]) 8 | 9 | return arr -------------------------------------------------------------------------------- /easy/0461-hamming-dist/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingDistance(self, x: int, y: int) -> int: 3 | n = x ^ y 4 | dist = 0 5 | 6 | while n > 0: 7 | if n & 1: dist += 1 8 | n >>= 1 9 | 10 | return dist -------------------------------------------------------------------------------- /easy/0009-palindrome-number/sol.go: -------------------------------------------------------------------------------- 1 | package palindromenumber 2 | 3 | func isPalindrome(x int) bool { 4 | if x < 0 { 5 | return false 6 | } 7 | 8 | rev := 0 9 | 10 | for n := x; n > 0; n = n / 10 { 11 | rev = rev*10 + n%10 12 | } 13 | 14 | return rev == x 15 | } 16 | -------------------------------------------------------------------------------- /easy/1342-steps-reduce-number-to-zero/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfSteps(self, num: int) -> int: 3 | steps = 0 4 | while num > 0: 5 | if num&1: steps += 1 6 | num >>= 1 7 | if num>0: steps += 1 8 | 9 | return steps -------------------------------------------------------------------------------- /medium/0912-sort-an-array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector sortArray(vector& nums) { 8 | sort(nums.begin(),nums.end()); 9 | return nums; 10 | } 11 | }; -------------------------------------------------------------------------------- /medium/1780-check-number-power-of-three/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | bool checkPowersOfThree(int n) { 6 | for(;n>0;n/=3) 7 | if(n%3 == 2) 8 | return false; 9 | 10 | return true; 11 | } 12 | }; -------------------------------------------------------------------------------- /easy/3190-min-operations-make-elements-div-by-3/sol.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumOperations(vector& nums) { 4 | int ans = 0; 5 | for(int i=0;i int: 3 | n = len(nums) 4 | dp = [0] * (n+3) 5 | 6 | for i, num in enumerate(nums): 7 | dp[i+3] = nums[i] + max(dp[i+1], dp[i]) 8 | 9 | return max(dp[n+2], dp[n+1]) -------------------------------------------------------------------------------- /medium/2579-total-colored-cells/2024-11-01.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | long long coloredCells(int n) { 6 | long long s = 0; 7 | for(int i=n-1;i>1;i-=1) 8 | s += i-1; 9 | 10 | return 1 + (s+n-1)*4; 11 | } 12 | }; -------------------------------------------------------------------------------- /easy/0717-1bit-2bit-chars/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isOneBitCharacter(self, bits: List[int]) -> bool: 3 | prev = None 4 | ans = True 5 | 6 | for bit in bits: 7 | ans = False if prev else True 8 | prev = 0 if bit and prev else bit 9 | 10 | return ans -------------------------------------------------------------------------------- /easy/0231-power-of-two/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfTwo(self, n: int) -> bool: 3 | if n <= 0: 4 | return False 5 | 6 | while n > 0: 7 | if n % 2 == 1 and n > 1: 8 | return False 9 | n >>= 1 10 | 11 | return True -------------------------------------------------------------------------------- /easy/0268-missing-num/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingNumber(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | xor1, xor2 = 0, 0 5 | 6 | for i in range(n+1): 7 | xor1 ^= i 8 | for i in range(n): 9 | xor2 ^= nums[i] 10 | 11 | return xor1 ^ xor2 -------------------------------------------------------------------------------- /hard/1526-min-increments/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minNumberOperations(self, target: List[int]) -> int: 3 | ans = target[0] 4 | n = len(target) 5 | 6 | for i in range(1,n): 7 | if target[i]-target[i-1] > 0: 8 | ans += target[i]-target[i-1] 9 | 10 | return ans -------------------------------------------------------------------------------- /medium/3179-nth-value-after-k-seconds/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def valueAfterKSeconds(self, n: int, k: int) -> int: 3 | a = [1]*n 4 | MOD = 10**9+7 5 | 6 | for _ in range(k): 7 | for i in range(1,n): 8 | a[i] = (a[i] + a[i-1]) % MOD 9 | 10 | return a[n-1] -------------------------------------------------------------------------------- /easy/0326-power-of-three/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | bool isPowerOfThree(int n) { 6 | if(n==1) return true; 7 | if(n<2 || n%3!=0) return false; 8 | 9 | while(n%3==0 && n>3) 10 | n /= 3; 11 | 12 | return n==3; 13 | } 14 | }; -------------------------------------------------------------------------------- /medium/0442-duplicates-in-arr/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicates(self, nums: List[int]) -> List[int]: 3 | dups = [] 4 | for x in nums: 5 | num = abs(x) 6 | if nums[num-1] < 0: 7 | dups.append(num) 8 | nums[num-1] *= -1 9 | 10 | return dups -------------------------------------------------------------------------------- /easy/0121-best-time-to-buy-sell-stock/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | profit = 0 4 | min_price = prices[0] 5 | 6 | for price in prices: 7 | min_price = min(min_price, price) 8 | profit = max(profit, price-min_price) 9 | 10 | return profit -------------------------------------------------------------------------------- /easy/1716-money-in-leetcode-bank/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def totalMoney(self, n: int) -> int: 3 | k = n//7 # total weeks 4 | acc = int((7*k*(k+7))/2) 5 | 6 | rem = n%7 # non-complete week days 7 | a = k+1 # first term 8 | 9 | s = int((rem*(2*a+(rem-1)))/2) 10 | 11 | return s+acc -------------------------------------------------------------------------------- /easy/2154-keep-multiplying-found-vals-by-2/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findFinalValue(self, nums: List[int], original: int) -> int: 3 | store = set() 4 | for num in nums: 5 | store.add(num) 6 | 7 | while original in store: 8 | original *= 2 9 | 10 | return original -------------------------------------------------------------------------------- /easy/1281-subtract-product-sum-of-integer/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | int subtractProductAndSum(int n) { 6 | int prod = 1, sum = 0; 7 | for(;n>0;n/=10) { 8 | prod *= n%10; 9 | sum += n%10; 10 | } 11 | 12 | return prod - sum; 13 | } 14 | }; -------------------------------------------------------------------------------- /medium/3228-max-moves-shift-one-to-right/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxOperations(self, s: str) -> int: 3 | ans = 0 4 | ones = 0 5 | 6 | for i in range(len(s)): 7 | if s[i] == '1': 8 | ones += 1 9 | elif i>0 and s[i-1] == '1': 10 | ans += ones 11 | 12 | return ans -------------------------------------------------------------------------------- /medium/2320-total-ways-to-place-house/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countHousePlacements(self, n: int) -> int: 3 | f = [1,2] 4 | MOD = 1_000_000_007 5 | 6 | for i in range(2,n+1): 7 | t = (f[0] + f[1]) % MOD 8 | f[0] = f[1] 9 | f[1] = t 10 | 11 | return (f[1]**2) % MOD 12 | -------------------------------------------------------------------------------- /medium/2914-min-changes-to-make-binary-string-beautiful/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int minChanges(string s) { 7 | int changes = 0; 8 | 9 | for(int i=1;i int: 3 | def evens(x): 4 | return int(x/2) if x%2==0 else int((x-1)/2) 5 | def odds(x): 6 | return int(x/2) if x%2==0 else 1+int((x-1)/2) 7 | 8 | ans = evens(n)*odds(m) + evens(m)*odds(n) 9 | return ans 10 | -------------------------------------------------------------------------------- /easy/0009-palindrome-number/sol.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Solution: 4 | def isPalindrome(self, x: int) -> bool: 5 | if x < 0: 6 | return False 7 | 8 | n = x 9 | rev = 0 10 | 11 | while n > 0: 12 | rev = rev*10 + n%10 13 | n = math.floor(n/10) 14 | 15 | return rev == x 16 | -------------------------------------------------------------------------------- /medium/1980-unqiue-binary-string/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | string findDifferentBinaryString(vector& nums) { 8 | string str = ""; 9 | for(int i=0;i int: 3 | used = [False for _ in range(26)] 4 | ans = 0 5 | 6 | for ch in s: 7 | asci = ord(ch) - 97 8 | if not used[asci]: 9 | ans += 1 10 | used[asci] = True 11 | 12 | return ans -------------------------------------------------------------------------------- /easy/0485-max-consecutive-ones-I/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMaxConsecutiveOnes(self, nums: List[int]) -> int: 3 | l, r = -1, 0 4 | ans, n = 0, len(nums) 5 | 6 | while r <= n: 7 | if r == n or nums[r] == 0: 8 | ans = max(ans, r-l-1) 9 | l = r 10 | 11 | r += 1 12 | 13 | 14 | return ans -------------------------------------------------------------------------------- /easy/2600-k-items-max-sum/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { 7 | int ones = min(numOnes, k); 8 | k -= ones; 9 | k -= min(numZeros, k); 10 | int negs = min(numNegOnes, k); 11 | 12 | return ones - negs; 13 | } 14 | }; -------------------------------------------------------------------------------- /medium/0540-single-element-in-sorted-array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int singleNonDuplicate(vector& nums) { 7 | for(int i=0;i int: 3 | ans = 1 4 | MOD = pow(10,9)+7 5 | root = nums[0] 6 | 7 | for i in range(1,len(nums)): 8 | if nums[i] <= root: 9 | ans = 0 10 | break 11 | ans = (ans * i) % MOD 12 | 13 | 14 | return ans -------------------------------------------------------------------------------- /easy/0001-2sum/sol.ts: -------------------------------------------------------------------------------- 1 | function twoSum(nums: number[], target: number): number[] { 2 | let map: Record = {} 3 | 4 | for (let i = 0; i < nums.length; i++) { 5 | const requiredRemainder = target - nums[i] 6 | if (requiredRemainder in map) 7 | return [map[requiredRemainder], i] 8 | else 9 | map[nums[i]] = i 10 | } 11 | return [] 12 | } -------------------------------------------------------------------------------- /easy/0231-power-of-two/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | bool isPowerOfTwo(int n) { 6 | if(n<=0) return false; 7 | 8 | bool foundOne = false; 9 | while(n>0) { 10 | if(foundOne) return false; 11 | if(n%2==1) foundOne = true; 12 | n >>= 1; 13 | } 14 | 15 | return true; 16 | } 17 | }; -------------------------------------------------------------------------------- /easy/1317-two-non-zero-int-sum/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getNoZeroIntegers(self, n: int) -> List[int]: 3 | def has_zero(x:int): 4 | while x > 0: 5 | if x%10 == 0: return True 6 | x = int(x/10) 7 | return False 8 | 9 | for i in range(1,n): 10 | if not has_zero(i) and not has_zero(n-i): 11 | return [i,n-i] -------------------------------------------------------------------------------- /easy/1323-max-69-num/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximum69Number (self, num: int) -> int: 3 | pos, i = -1, 1 4 | n = num 5 | 6 | while num > 0: 7 | if num%10 == 6: 8 | pos = i 9 | 10 | num = int(num/10) 11 | i *= 10 12 | 13 | 14 | if pos > -1: 15 | n += pos*3 16 | 17 | return n -------------------------------------------------------------------------------- /medium/0053-max-subarray/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | local_sum, global_sum = 0, nums[0] 4 | 5 | for num in nums: 6 | local_sum += num 7 | global_sum = max(global_sum,local_sum) 8 | 9 | if local_sum < 0: 10 | local_sum = 0 11 | 12 | 13 | 14 | return global_sum -------------------------------------------------------------------------------- /easy/0206-reverse-linked-list/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | ListNode* reverseList(ListNode* head) { 6 | ListNode *curr = head, *prev = nullptr; 7 | 8 | while(curr) { 9 | ListNode *temp = curr->next; 10 | curr->next = prev; 11 | prev = curr; 12 | curr = temp; 13 | } 14 | 15 | return prev; 16 | } 17 | }; -------------------------------------------------------------------------------- /easy/0342-power-of-four/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfFour(self, n: int) -> bool: 3 | if n <= 0: 4 | return False 5 | 6 | flag = False 7 | 8 | while n > 0: 9 | if n % 2 == 1 and n > 1: 10 | return False 11 | n >>= 1 12 | # switch state to count stages in 2 13 | flag = not flag 14 | 15 | return flag -------------------------------------------------------------------------------- /easy/1844-replace-digit-with-char/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | private: 6 | char shift(char c, int x) { 7 | return c + x; 8 | } 9 | 10 | public: 11 | string replaceDigits(string s) { 12 | for(int i=1;i(s[i])-48); 14 | 15 | return s; 16 | } 17 | }; -------------------------------------------------------------------------------- /medium/3147-take-max-energy-from-dungeon/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumEnergy(self, energy: List[int], k: int) -> int: 3 | n, max_energy = len(energy), -inf 4 | dp = [0]*n 5 | 6 | for i in range(n-1,-1,-1): 7 | collected_energy = dp[i+k] if i+k= numExchange) { 8 | total += floor(numBottles/numExchange); 9 | numBottles = (numBottles % numExchange) + floor(numBottles/numExchange); 10 | } 11 | 12 | return total; 13 | } 14 | }; -------------------------------------------------------------------------------- /easy/1863-sum-of-all-subset-XOR-total/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | private: 6 | int xorSum(vector& nums, int i, int currXOR) { 7 | if(i==nums.size()) return currXOR; 8 | return xorSum(nums,i+1,currXOR^nums[i]) + xorSum(nums,i+1,currXOR); 9 | } 10 | 11 | public: 12 | int subsetXORSum(vector& nums) { 13 | return xorSum(nums,0,0); 14 | } 15 | }; -------------------------------------------------------------------------------- /easy/2220-min-bit-flips-to-convert-number/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | int minBitFlips(int start, int goal) { 6 | int xor_value = start^goal; 7 | int minFlips = 0; 8 | 9 | while(xor_value > 0) { 10 | if(xor_value%2==1) 11 | minFlips += 1; 12 | xor_value >>= 1; 13 | } 14 | 15 | return minFlips; 16 | } 17 | }; -------------------------------------------------------------------------------- /medium/0357-count-digits-with-unique-digits/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | int countNumbersWithUniqueDigits(int n) { 6 | int uniques = 1; 7 | for(int i=1;i<=n;i+=1) { 8 | int sum = 9; 9 | for(int j=9;j>=9-(i-2);j-=1) 10 | sum *= j; 11 | uniques += sum; 12 | } 13 | 14 | return uniques; 15 | } 16 | }; -------------------------------------------------------------------------------- /easy/1437-check-all-1s-atleast-k-away/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kLengthApart(self, nums: List[int], k: int) -> bool: 3 | prev = -1 4 | ans = True 5 | 6 | for i in range(len(nums)): 7 | num = nums[i] 8 | if num == 1: 9 | if prev >= 0 and i-prev-1 < k: 10 | ans = False 11 | break 12 | prev = i 13 | 14 | return ans -------------------------------------------------------------------------------- /easy/3392-total-subarrays-with-condition/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int countSubarrays(vector& nums) { 7 | int left = 0, right = 2; 8 | int total = 0; 9 | 10 | for(;right 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int arraySign(vector& nums) { 7 | bool negative = false; 8 | int len = nums.size(); 9 | 10 | for(int i=0; i int: 3 | low, high = 1, n 4 | ans = -1 5 | 6 | while low <= high: 7 | mid = low + (high-low)//2 8 | x = 2**mid - 1 9 | 10 | if x < n: 11 | low = mid+1 12 | else: 13 | ans = x 14 | high = mid-1 15 | 16 | 17 | return ans -------------------------------------------------------------------------------- /easy/0026-remove-duplicates/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution 5 | { 6 | public: 7 | int removeDuplicates(vector& nums) { 8 | int low = 0, high = 1; 9 | for(;high List[int]: 3 | for num in nums: 4 | i = abs(num) - 1 5 | if nums[i] > 0: 6 | nums[i] *= -1 7 | 8 | disappeared = [] 9 | for i, num in enumerate(nums): 10 | if num > 0: 11 | disappeared.append(i+1) 12 | 13 | return disappeared -------------------------------------------------------------------------------- /easy/1018-binary-prefix-div-by-5/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Solution { 4 | public: 5 | vector prefixesDivBy5(vector& nums) { 6 | vector ans(nums.size(), false); 7 | int num = 0; 8 | 9 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int minimumCost(vector& cost) { 8 | int totalCost = 0; 9 | 10 | sort(cost.begin(),cost.end()); 11 | 12 | for(int i=cost.size()-1; i>=0; i-=3) 13 | totalCost += cost[i] + (i-1 >= 0 ? cost[i-1] : 0); 14 | 15 | return totalCost; 16 | } 17 | }; -------------------------------------------------------------------------------- /medium/0007-reverse-integer/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | int reverse(int x) { 6 | long rev = 0; 7 | 8 | while(x != 0) { 9 | if(x<0 && INT_MIN > rev*10 + x%10) return 0; 10 | else if(x>=0 && INT_MAX < rev*10 + x%10) return 0; 11 | 12 | rev = rev*10 + x%10; 13 | x /= 10; 14 | } 15 | 16 | return (int)(rev); 17 | } 18 | }; -------------------------------------------------------------------------------- /medium/0435-non-overlapping-intervals/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: 3 | intervals.sort(key=lambda x:(x[0],x[1])) 4 | ans = 0 5 | prev = float('-inf') 6 | 7 | for a,b in intervals: 8 | if a < prev: 9 | ans += 1 10 | if b < prev: prev = b 11 | else: 12 | prev = b 13 | 14 | return ans -------------------------------------------------------------------------------- /medium/3137-operations-to-make-K-periodic/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumOperationsToMakeKPeriodic(self, word: str, k: int) -> int: 3 | curr = 0 4 | n = len(word) 5 | total = n // k 6 | f = {} 7 | 8 | for i in range(0,n,k): 9 | w = word[i:i+k] 10 | if w in f: f[w] += 1 11 | else: f[w] = 1 12 | curr = max(curr,f[w]) 13 | 14 | return total - curr -------------------------------------------------------------------------------- /easy/0001-2sum/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | expected = {} 4 | pair = [] 5 | 6 | for i, num in enumerate(nums): 7 | if num in expected: 8 | j = expected.get(num) 9 | pair = [i,j] 10 | break 11 | 12 | else: 13 | expected[target-num] = i 14 | 15 | return pair -------------------------------------------------------------------------------- /easy/0217-contains-duplicates/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool containsDuplicate(vector& nums) { 7 | unordered_set store; 8 | for(int i=0;i int: 3 | boxTypes.sort(key=lambda x: x[1], reverse=True) 4 | units = 0 5 | 6 | for i in range(len(boxTypes)): 7 | if truckSize == 0: break 8 | units += min(truckSize, boxTypes[i][0])*boxTypes[i][1] 9 | truckSize = max(0, truckSize-boxTypes[i][0]) 10 | 11 | return units -------------------------------------------------------------------------------- /easy/0028-occurence-of-first-string-index/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int strStr(string haystack, string needle) { 7 | if(needle.size() > haystack.size()) 8 | return -1; 9 | 10 | for(int i=0;i<=haystack.size()-needle.size();i+=1) 11 | if(haystack.substr(i,needle.size()) == needle) 12 | return i; 13 | 14 | return -1; 15 | } 16 | }; -------------------------------------------------------------------------------- /medium/0077-combinations/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combine(self, n: int, k: int) -> List[List[int]]: 3 | 4 | def backtrack(prev, rem, comb_arr): 5 | if rem == 0: 6 | ans.append(comb_arr) 7 | return 8 | 9 | for num in range(prev+1, n-rem+2): 10 | backtrack(num, rem-1, comb_arr+[num]) 11 | 12 | 13 | ans = [] 14 | backtrack(0, k, []) 15 | 16 | return ans -------------------------------------------------------------------------------- /easy/3289-sneaky-digits-of-digitville/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getSneakyNumbers(self, nums: List[int]) -> List[int]: 3 | seen = set() 4 | ans = [] 5 | n = 0 6 | 7 | for num in nums: 8 | if num in seen: 9 | ans.append(num) 10 | n += 1 11 | else: 12 | seen.add(num) 13 | if n == 2: 14 | break 15 | 16 | 17 | return ans -------------------------------------------------------------------------------- /easy/3461-string-equal-after-operations-I/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hasSameDigits(self, s: str) -> bool: 3 | n = len(s) 4 | 5 | while n > 2: 6 | temp = "" 7 | 8 | for i in range(n-1): 9 | mod = (int(s[i]) + int(s[i+1])) % 10 10 | temp += str(mod) 11 | 12 | s = temp 13 | n = len(s) 14 | 15 | 16 | return True if s[0] == s[1] else False -------------------------------------------------------------------------------- /medium/0973-k-closest-points-to-origin/sol.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class Solution: 4 | def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: 5 | heap = [] 6 | ans = [] 7 | 8 | for x,y in points: 9 | d = x**2 + y**2 10 | heapq.heappush(heap,(d,x,y)) 11 | 12 | for _ in range(k): 13 | d,x,y = heapq.heappop(heap) 14 | ans.append([x,y]) 15 | 16 | return ans -------------------------------------------------------------------------------- /medium/1010-pairs-divisible-by-60/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int numPairsDivisibleBy60(vector& time) { 7 | int pairs = 0; 8 | vector counts(60,0); 9 | 10 | for(int i=0;i int: 3 | nums = sorted(nums, key=lambda x: abs(x), reverse=True) 4 | n = len(nums) 5 | mid = n//2 if n%2==0 else (n+1)//2 6 | result = 0 7 | 8 | for i in range(mid): 9 | result += nums[i]**2 10 | 11 | for i in range(mid,n): 12 | result -= nums[i]**2 13 | 14 | return result -------------------------------------------------------------------------------- /easy/2169-operatoins-to-obtain-zero/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countOperations(self, num1: int, num2: int) -> int: 3 | steps = 0 4 | while num1 > 0 and num2 > 0: 5 | if num1 >= num2: 6 | t = max(1, (num1-num2) // num2) 7 | num1 -= t*num2 8 | else: 9 | t = max(1, (num2-num1) // num1) 10 | num2 -= t*num1 11 | steps += t 12 | 13 | return steps -------------------------------------------------------------------------------- /easy/2206-divide-array-equal-pairs/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool divideArray(vector& nums) { 8 | unordered_set seen; 9 | 10 | for(int i=0;i bool: 3 | INF = float('inf') 4 | a,b = INF, INF 5 | ans = False 6 | 7 | for num in nums: 8 | if num < a: 9 | a = num 10 | elif num < b and num != a: 11 | b = num 12 | elif num > b: 13 | ans = True 14 | break 15 | 16 | return ans -------------------------------------------------------------------------------- /medium/3759-elements-with-atleast-K-greater-elements/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countElements(self, nums: List[int], k: int) -> int: 3 | nums.sort() 4 | n = len(nums) 5 | ans, dup = 0, 0 6 | 7 | for i, num in enumerate(nums): 8 | if i < n-1 and num == nums[i+1]: 9 | dup += 1 10 | continue 11 | if n-i-1 >= k: 12 | ans += dup+1 13 | dup = 0 14 | 15 | return ans -------------------------------------------------------------------------------- /easy/2490-circular-sentence/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool isCircularSentence(string sentence) { 7 | if(sentence[0] != sentence[sentence.size()-1]) 8 | return false; 9 | 10 | for(int i=0;i int: 3 | if x == 0: 4 | return 0 5 | 6 | low, high = 1, x//2 7 | ans = 1 8 | 9 | while low <= high: 10 | mid = low + (high-low)//2 11 | sq = mid * mid 12 | 13 | if sq > x: 14 | high = mid-1 15 | else: 16 | ans = mid 17 | low = mid+1 18 | 19 | return ans -------------------------------------------------------------------------------- /easy/0657-robot-return-to-origin/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool judgeCircle(string moves) { 7 | int h = 0, v = 0; 8 | for(int i=0;i Optional[TreeNode]: 4 | ptr = root 5 | result = None 6 | 7 | while ptr: 8 | if not ptr: break 9 | 10 | if ptr.val == val: 11 | result = ptr 12 | break 13 | 14 | if val < ptr.val: ptr = ptr.left 15 | else: ptr = ptr.right 16 | 17 | 18 | return result -------------------------------------------------------------------------------- /medium/0848-shifting-letters/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | string shiftingLetters(string s, vector& shifts) { 8 | int totalShift = 0; 9 | for(int i=shifts.size()-1;i>=0;i--) { 10 | totalShift = (totalShift + shifts[i]) % 26; 11 | s[i] = (char)((static_cast(s[i]) - 97 + totalShift) % 26 + 97); 12 | } 13 | 14 | return s; 15 | } 16 | }; -------------------------------------------------------------------------------- /medium/1143-LCS/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 3 | m,n = len(text1), len(text2) 4 | dp = [[0 for _ in range(n+1)] for _ in range(m+1)] 5 | 6 | for i in range(1,m+1): 7 | for j in range(1,n+1): 8 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]) 9 | if text1[i-1] == text2[j-1]: 10 | dp[i][j] = max(dp[i][j], 1+dp[i-1][j-1]) 11 | 12 | return dp[m][n] -------------------------------------------------------------------------------- /medium/2938-seperate-white-black-balls/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | long long minimumSteps(string s) { 7 | if(s.size() == 1) 8 | return 0; 9 | 10 | int swaps = 0; 11 | long long minSteps = 0; 12 | 13 | for (int i = s.size() - 1; i >= 0; i-=1) 14 | if(s[i] == '0') swaps += 1; 15 | else minSteps += swaps; 16 | 17 | return minSteps; 18 | } 19 | }; -------------------------------------------------------------------------------- /easy/0746-min-cost-climbing-stairs/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int minCostClimbingStairs(vector& cost) { 8 | if(cost.size()==1) 9 | return cost[0]; 10 | 11 | vector dp(cost.size()+2, 0); 12 | 13 | for(int i=cost.size()-1;i>=0;i-=1) 14 | dp[i] = cost[i] + min(dp[i+1],dp[i+2]); 15 | 16 | return min(dp[0],dp[1]); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /easy/3423-max-diff-in-circular-array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxAdjacentDistance(vector& nums) { 8 | int maxAdjDiff = 0; 9 | 10 | for(int index = 0; index < nums.size(); index += 1) { 11 | int adjIndex = (index + 1) % nums.size(); 12 | maxAdjDiff = max(maxAdjDiff, abs(nums[index] - nums[adjIndex])); 13 | } 14 | 15 | return maxAdjDiff; 16 | } 17 | }; -------------------------------------------------------------------------------- /medium/0056-merge-intervals/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, arr: List[List[int]]) -> List[List[int]]: 3 | arr.sort(key=lambda x:(x[0],x[1])) 4 | result = [] 5 | currMax = arr[0][1] 6 | left = arr[0][0] 7 | 8 | for a,b in arr: 9 | if a > currMax: 10 | result.append([ left, currMax ]) 11 | left = a 12 | currMax = max(currMax, b) 13 | 14 | result.append([ left, currMax ]) 15 | return result -------------------------------------------------------------------------------- /medium/2139-min-moves-to-reach-target-score/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | int minMoves(int target, int maxDoubles) { 6 | int moves = 0; 7 | while(maxDoubles > 0 && target > 1) { 8 | if(target%2 == 0) { 9 | target /= 2; 10 | maxDoubles -= 1; 11 | } 12 | else target -= 1; 13 | 14 | moves += 1; 15 | } 16 | 17 | return moves + target - 1; 18 | } 19 | }; -------------------------------------------------------------------------------- /easy/1539-kth-missing-positive-num/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findKthPositive(self, arr: List[int], k: int) -> int: 3 | prev = 0 4 | ans = None 5 | 6 | for num in arr: 7 | diff = num - prev - 1 8 | 9 | if diff < k: 10 | k -= diff 11 | else: 12 | ans = prev + k 13 | break 14 | 15 | prev = num 16 | 17 | 18 | if not ans: 19 | ans = prev + k 20 | 21 | return ans -------------------------------------------------------------------------------- /hard/0440-kth-smallest-lexicographical-number/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | int findKthNumber(int n, int k) { 6 | long curr = 1; 7 | 8 | for(int i=1; i=n) 13 | curr = curr/10; 14 | curr += 1; 15 | } 16 | } 17 | 18 | return (int)curr; 19 | } 20 | }; -------------------------------------------------------------------------------- /medium/0062-unique-paths/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int uniquePaths(int m, int n) { 7 | vector> dp(m+1, vector(n+1, 0)); 8 | dp[m-1][n-1] = 1; 9 | 10 | for (int i = m-1; i>=0; i-=1) 11 | for (int j = n-1; j>=0; j-=1) { 12 | if(i==m-1 && j==n-1) continue; 13 | dp[i][j] = dp[i+1][j] + dp[i][j+1]; 14 | } 15 | 16 | return dp[0][0]; 17 | } 18 | }; -------------------------------------------------------------------------------- /medium/0279-perfect-squares/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | int numSquares(int n) { 6 | int maxCoin = floor(sqrt(n)), val; 7 | vector dp(n,n); 8 | 9 | for(int i=0;i i+1) continue; 13 | if(val == i+1) dp[i] = 1; 14 | else dp[i] = min(dp[i],1+dp[i-val]); 15 | } 16 | 17 | return dp[n-1]; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /medium/0633-sum-of-square-numbers/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool judgeSquareSum(int c) { 7 | long low = 0, high = ceil(sqrt(c)); 8 | long sum = 0; 9 | 10 | while(low <= high) { 11 | sum = low*low + high*high; 12 | if(sum == c) 13 | return true; 14 | if(sum < c) left += 1; 15 | else high -= 1; 16 | } 17 | 18 | return false; 19 | } 20 | }; -------------------------------------------------------------------------------- /easy/3194-min-avg-of-min-max-in-array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | double minimumAverage(vector& nums) { 9 | double minAvg = INT_MAX; 10 | sort(nums.begin(),nums.end()); 11 | 12 | for(int low = 0, high = nums.size()-1; low < high; low+=1, high-=1) 13 | minAvg = min(minAvg,(double)(nums[low]+nums[high])); 14 | 15 | return minAvg/2; 16 | } 17 | }; -------------------------------------------------------------------------------- /medium/0313-super-ugly-number/sol.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class Solution: 4 | def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int: 5 | heap = [] 6 | heapq.heappush(heap,1) 7 | seen = set() 8 | 9 | for _ in range(n-1): 10 | num = heapq.heappop(heap) 11 | for p in primes: 12 | if p*num not in seen: 13 | heapq.heappush(heap,p*num) 14 | seen.add(p*num) 15 | 16 | return heapq.heappop(heap) -------------------------------------------------------------------------------- /easy/1025-divisor-game/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def divisorGame(self, n: int) -> bool: 3 | ''' 4 | dp[2] = True 5 | dp[3] = !dp[2] = False 6 | dp[4] = !dp[3] or !dp[2] = True 7 | dp[5] = !dp[4] = False 8 | dp[6] = !dp[5] or !dp[4] or !dp[3] = True 9 | ... 10 | ... 11 | 12 | observation: dp[odd] = not dp[even] always = False 13 | as such, odd -> False always 14 | even -> True always 15 | ''' 16 | return n % 2 == 0 -------------------------------------------------------------------------------- /medium/3185-total-pairs-forming-complete-days-II/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | long long countCompleteDayPairs(vector& hours) { 7 | long long completeDays = 0; 8 | vector buckets(24,0); 9 | 10 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector twoSum(vector& nums, int target) { 8 | unordered_map map; 9 | for(int i=0;i 0) 11 | return {map[nums[i]], i}; 12 | 13 | map[target-nums[i]] = i; 14 | } 15 | 16 | return {}; 17 | } 18 | }; -------------------------------------------------------------------------------- /medium/0064-min-path-sum/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minPathSum(self, grid: List[List[int]]) -> int: 3 | m, n = len(grid), len(grid[0]) 4 | dp = [[ 99_999 for _ in range(n+1)] for _ in range(m+1)] 5 | 6 | # not to hinder with last cell value 7 | dp[m][n-1], dp[m-1][n] = 0, 0 8 | 9 | # bottom up approach 10 | for i in range(m-1,-1,-1): 11 | for j in range(n-1,-1,-1): 12 | dp[i][j] = grid[i][j] + min(dp[i][j+1], dp[i+1][j]) 13 | 14 | return dp[0][0] -------------------------------------------------------------------------------- /medium/3653-xor-range-multiplication-after-queries-I/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def xorAfterQueries(self, nums: List[int], queries: List[List[int]]) -> int: 3 | factors = [1]*len(nums) 4 | MOD = 1_000_000_007 5 | xor = 0 6 | 7 | for q in queries: 8 | for i in range(q[0],q[1]+1,q[2]): 9 | factors[i] = (factors[i]*q[3]) % MOD 10 | 11 | for i, num in enumerate(nums): 12 | xor ^= (factors[i]*num) % MOD 13 | 14 | return xor -------------------------------------------------------------------------------- /easy/1550-consecutive-odds/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool threeConsecutiveOdds(vector& arr) { 7 | int consecutiveOdds = 0; 8 | 9 | for(int i=0;i 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int maxIceCream(vector& costs, int coins) { 7 | sort(costs.begin(), costs.end()); 8 | int maxBars = 0; 9 | 10 | for (int i = 0; i < costs.size();i+=1) 11 | if(costs[i] <= coins) { 12 | coins -= costs[i]; 13 | maxBars += 1; 14 | } 15 | else 16 | break; 17 | 18 | return maxBars; 19 | } 20 | }; -------------------------------------------------------------------------------- /medium/3195-smallest-area-covering-all-ones-I/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumArea(self, grid: List[List[int]]) -> int: 3 | x1, x2, y1, y2 = inf, 0, inf, 0 4 | 5 | for i in range(len(grid)): 6 | for j in range(len(grid[0])): 7 | if grid[i][j] == 1: 8 | x1 = min(x1,j) 9 | x2 = max(x2,j) 10 | y1 = min(y1,i) 11 | y2 = max(y2,i) 12 | 13 | area = (x2-x1+1)*(y2-y1+1) 14 | return area -------------------------------------------------------------------------------- /medium/0647-palindromic-substrings/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subpalindromes(self, s, l, r): 3 | count = 0 4 | while l>=0 and r int: 14 | count = 0 15 | 16 | for i in range(len(s)): 17 | count += self.subpalindromes(s,i,i) 18 | count += self.subpalindromes(s,i,i+1) 19 | 20 | return count -------------------------------------------------------------------------------- /easy/0119-pascals-triangle-II/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getRow(self, rowIndex: int) -> List[int]: 3 | last_row = [1] 4 | 5 | for row in range(2, rowIndex+2): 6 | curr_row = [] 7 | 8 | for j in range(row): 9 | val = 1 10 | if j > 0 and j < row-1: 11 | val = last_row[j-1] + last_row[j] 12 | 13 | curr_row.append(val) 14 | 15 | last_row = curr_row 16 | 17 | 18 | return last_row -------------------------------------------------------------------------------- /easy/0434-total-segments-in-string/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int countSegments(string s) { 7 | s += ' '; 8 | int segments = 0; 9 | bool found = false; 10 | 11 | for(int i=0;i int: 3 | max_area, max_diag = 0, 0 4 | 5 | for dim in dimensions: 6 | diag = dim[0]**2 + dim[1]**2 7 | if max_diag <= diag: 8 | if max_diag == diag: 9 | max_area = max(max_area, dim[0] * dim[1]) 10 | else: 11 | max_area = dim[0] * dim[1] 12 | 13 | max_diag = diag 14 | 15 | 16 | return max_area -------------------------------------------------------------------------------- /medium/0198-house-robber/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int rob(vector& nums) { 8 | if(nums.size()==1) return nums[0]; 9 | else if(nums.size()==2) return max(nums[0], nums[1]); 10 | 11 | vector dp(nums.size(),0); 12 | 13 | for(int i=0;i=0 ? dp[i-2] : 0, i-3>=0 ? dp[i-3] : 0); 15 | 16 | return dp[nums.size()-1]; 17 | } 18 | }; -------------------------------------------------------------------------------- /medium/0646-max-len-pair-chain/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findLongestChain(self, pairs: List[List[int]]) -> int: 3 | n = len(pairs) 4 | pairs = sorted(pairs) 5 | 6 | dp = [0]*(n+1) 7 | dp[n-1] = 1 8 | 9 | for i in range(n-1,-1,-1): 10 | index = n 11 | for j in range(i+1,n): 12 | if pairs[j][0] > pairs[i][1]: 13 | index = j 14 | break 15 | dp[i] = max(1+dp[index], dp[i+1]) 16 | 17 | return dp[0] -------------------------------------------------------------------------------- /medium/2125-total-laser-beams-in-bank/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfBeams(self, bank: List[str]) -> int: 3 | beams = 0 4 | prev_count, curr_count = 0, 0 5 | 6 | for row in bank: 7 | for cell in row: 8 | if cell == '1': 9 | curr_count += 1 10 | if prev_count > 0: 11 | beams += prev_count * curr_count 12 | if curr_count > 0: 13 | prev_count = curr_count 14 | curr_count = 0 15 | 16 | return beams -------------------------------------------------------------------------------- /easy/0796-rotate-string/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool rotateString(string s, string goal) { 7 | if(s.size()!=goal.size()) 8 | return false; 9 | 10 | int count = 1, n = s.size(); 11 | 12 | while(count <= n) { 13 | if(s.substr(count-1,n) == goal) 14 | return true; 15 | 16 | s += s[count-1]; 17 | count += 1; 18 | } 19 | 20 | return false; 21 | } 22 | }; -------------------------------------------------------------------------------- /medium/2579-total-colored-cells/2025-03-05.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | long long coloredCells(int n) { 6 | // halfGridSquares(t) = no of squares in n*n grid in one side of the diagonal = n(n-1)/2 7 | // without_borders = t + n - n - n + 1 = t - n + 1 8 | // ans = 4*without_borders + 1 + (n-1)*4 9 | // ans = 4t + 1 10 | 11 | long long halfGridSquares = n%2 == 0 ? (long long)(n/2)*(n-1) : (long long)n*((n-1)/2); 12 | return 4*halfGridSquares + 1; 13 | } 14 | }; -------------------------------------------------------------------------------- /medium/1513-total-substrings-only-1s/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numSub(self, s: str) -> int: 3 | 4 | MOD = 10**9+7 5 | curr = 0 6 | ans = 0 7 | 8 | for ch in s+"0": 9 | if ch == '1': 10 | curr = (curr + 1) % MOD 11 | elif curr > 0: 12 | if curr & 1: a,b = curr, (curr+1) // 2 13 | else: a,b = curr+1, curr // 2 14 | ans = (ans + (a*b % MOD)) % MOD 15 | curr = 0 16 | 17 | 18 | return ans -------------------------------------------------------------------------------- /easy/3432-partitions-even-odd-sums/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPartitions(self, nums: List[int]) -> int: 3 | # 3 - 1 = 2 and 4 -2 = 2 -> O,O or E,E (0 = E) 4 | n = len(nums) 5 | pre = [0 for _ in range(n)] 6 | ans = 0 7 | 8 | for i, num in enumerate(nums): 9 | pre[i] = nums[i] + (pre[i-1] if i>0 else 0) 10 | 11 | for i in range(n-1): 12 | a,b = pre[i], pre[n-1] - pre[i] 13 | if not (a&1)^(b&1): 14 | ans += 1 15 | 16 | return ans -------------------------------------------------------------------------------- /medium/0238-product-of-arr-except-self/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def productExceptSelf(self, nums: List[int]) -> List[int]: 3 | n = len(nums) 4 | arr = [1] * n 5 | 6 | 7 | # left product prefix 8 | prod = 1 9 | for i in range(0,n-1): 10 | prod *= nums[i] 11 | arr[i+1] *= prod 12 | 13 | 14 | # right product suffix 15 | prod = 1 16 | for i in range(n-1,0,-1): 17 | prod *= nums[i] 18 | arr[i-1] *= prod 19 | 20 | 21 | return arr -------------------------------------------------------------------------------- /easy/1588-sum-odd-length-subarrays/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumOddLengthSubarrays(self, arr: List[int]) -> int: 3 | n = len(arr) 4 | pre = [0]*n 5 | pre[0] = arr[0] 6 | 7 | for i in range(1,n): 8 | pre[i] = pre[i-1] + arr[i] 9 | 10 | ans = pre[-1] 11 | k = 3 12 | 13 | for k in range(3,n+1,2): 14 | for i in range(n-k+1): 15 | j = i+k-1 16 | prev = 0 if i==0 else pre[i-1] 17 | ans += pre[j] - prev 18 | 19 | 20 | return ans -------------------------------------------------------------------------------- /medium/0692-top-K-frequent-words/sol.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | from collections import defaultdict 3 | 4 | class Solution: 5 | def topKFrequent(self, words: List[str], k: int) -> List[str]: 6 | heap = [] 7 | ans = [] 8 | freqs = defaultdict(int) 9 | for w in words: 10 | freqs[w] += 1 11 | 12 | for w,f in freqs.items(): 13 | heapq.heappush(heap,(-f,w)) 14 | 15 | for _ in range(k): 16 | _, w = heapq.heappop(heap) 17 | ans.append(w) 18 | 19 | return ans -------------------------------------------------------------------------------- /medium/1726-tuple-with-same-product/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int tupleSameProduct(vector& nums) { 8 | unordered_map hash; 9 | int count = 0; 10 | 11 | for(int i=1;i=0;j-=1) { 13 | int currProd = nums[i] * nums[j]; 14 | count += hash[currProd]; 15 | hash[currProd] += 1; 16 | } 17 | } 18 | 19 | return count * 8; 20 | } 21 | }; -------------------------------------------------------------------------------- /easy/3304-kth-char-in-string-game-I/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | private: 7 | string generate(string s) { 8 | for(int i=0;i(s[i]) - 97 + 1) % 26 + 97); 10 | return s; 11 | } 12 | 13 | public: 14 | char kthCharacter(int k) { 15 | string s = "a"; 16 | for(int i=0;i str: 3 | n = len(secret) 4 | bulls, cows = 0, 0 5 | c = [0 for _ in range(10)] 6 | 7 | for i in range(n): 8 | if secret[i] == guess[i]: 9 | bulls += 1 10 | else: 11 | a,b = int(secret[i]), int(guess[i]) 12 | if c[a]>0: cows += 1 13 | if c[b]<0: cows += 1 14 | c[a] -= 1 15 | c[b] += 1 16 | 17 | return f"{bulls}A{cows}B" -------------------------------------------------------------------------------- /medium/2109-adding-spaces-to-string/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | string addSpaces(string s, vector& spaces) { 8 | string spacedString = ""; 9 | int curr = 0; 10 | 11 | for(int i=0;i 2 | using namespace std; 3 | 4 | class Solution { 5 | private: 6 | bool parity(int x) { return x%2 == 0; } 7 | 8 | public: 9 | bool isArraySpecial(vector& nums) { 10 | bool lastParity = parity(nums[0]), currParity; 11 | 12 | for(int i=1;i 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | void rotate(vector& nums, int k) { 7 | k %= nums.size(); 8 | if(k==0) 9 | return; 10 | 11 | int offset = nums.size()-k; 12 | int index = 0; 13 | vector rotated(nums.size(),0); 14 | 15 | for(int i=offset;i str: 21 | return self.preorder(root) -------------------------------------------------------------------------------- /medium/0090-subsets-II/sol.ts: -------------------------------------------------------------------------------- 1 | function subsetsWithDup(nums: number[]): number[][] { 2 | let items: Set = new Set() 3 | items.add('[]') 4 | 5 | let subsets: number[][] = [] 6 | 7 | for(let num of nums) { 8 | for(let item of items) 9 | subsets.push([...JSON.parse(item), num].sort()) 10 | 11 | for(let subset of subsets) 12 | items.add(JSON.stringify(subset)) 13 | 14 | subsets = [] 15 | } 16 | 17 | for(let item of items) 18 | subsets.push(JSON.parse(item)) 19 | 20 | return subsets 21 | } -------------------------------------------------------------------------------- /easy/0202-happy-number/sol.ts: -------------------------------------------------------------------------------- 1 | function isHappy(n: number): boolean { 2 | if (n <= 3 && n !== 1) 3 | return false 4 | 5 | const sumOfSquares = (n: number): number => 6 | n === 0 7 | ? 0 8 | : Math.pow(n % 10, 2) + sumOfSquares(parseInt(String(n / 10))) 9 | 10 | let set = new Set() 11 | let sq: number = sumOfSquares(n) 12 | 13 | while (n !== 1 && !set.has(sq)) { 14 | set.add(sq) 15 | sq = sumOfSquares(sq) 16 | } 17 | 18 | if (sq === 1) 19 | return true 20 | 21 | return false 22 | 23 | }; -------------------------------------------------------------------------------- /medium/0204-total-primes/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // sieve of erastho...something 5 | class Solution { 6 | public: 7 | int countPrimes(int n) { 8 | if(n==0) 9 | return 0; 10 | 11 | int primes = 0; 12 | vector isPrime(n,true); 13 | isPrime[0] = false; 14 | 15 | for(int i=2;i 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | vector lexicalOrder(int n) { 7 | vector lexicals(n,0); 8 | int curr = 1; 9 | 10 | for(int i=0; i=n) 16 | curr /= 10; 17 | curr += 1; 18 | } 19 | } 20 | 21 | return lexicals; 22 | } 23 | }; -------------------------------------------------------------------------------- /easy/0543-diameter-of-binary-tree/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | private: 6 | int diameter = 0; 7 | 8 | int maxHeight(TreeNode *ptr) { 9 | if(!ptr) return 0; 10 | 11 | int leftSize = maxHeight(ptr->left); 12 | int rightSize = maxHeight(ptr->right); 13 | 14 | diameter = max(diameter, leftSize + rightSize); 15 | 16 | return 1 + max(leftSize,rightSize); 17 | } 18 | 19 | public: 20 | int diameterOfBinaryTree(TreeNode* root) { 21 | maxHeight(root); 22 | return diameter; 23 | } 24 | }; -------------------------------------------------------------------------------- /medium/0078-subsets/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | vector> subsets(vector& nums) { 7 | vector> ans = {{}}; 8 | vector temp; 9 | int currLen; 10 | 11 | for(int i=0;i List[List[int]]: 3 | pascal_triangle = [] 4 | 5 | for i in range(1,numRows+1): 6 | new_row = [] 7 | size = i 8 | 9 | for j in range(size): 10 | val = 1 11 | if j > 0 and j < size-1: 12 | val = pascal_triangle[i-2][j-1] + pascal_triangle[i-2][j] 13 | 14 | new_row.append(val) 15 | 16 | 17 | pascal_triangle.append(new_row) 18 | 19 | 20 | 21 | return pascal_triangle -------------------------------------------------------------------------------- /easy/0557-reverse-word-in-string-III/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | word = "" 4 | rev = "" 5 | SPACE = " " 6 | n = len(s) 7 | 8 | for i in range(n+1): 9 | ch = s[i] if i != n else SPACE 10 | 11 | if ch == SPACE: 12 | if word != "": 13 | rev += word 14 | word = "" 15 | if i != n: 16 | rev += SPACE 17 | 18 | else: 19 | word = ch + word 20 | 21 | 22 | return rev -------------------------------------------------------------------------------- /easy/1800-max-ascending-subarray-sum/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxAscendingSum(vector& nums) { 8 | int currSum = nums[0], maxSum = 0; 9 | for(int i=1;i nums[i-1]) 11 | currSum += nums[i]; 12 | else { 13 | maxSum = max(maxSum, currSum); 14 | currSum = nums[i]; 15 | } 16 | } 17 | 18 | maxSum = max(maxSum, currSum); 19 | return maxSum; 20 | } 21 | }; -------------------------------------------------------------------------------- /easy/3168-min-chairs-in-waiting-room/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int minimumChairs(string s) { 9 | int minChairs = INT_MIN, 10 | local_min = 0; 11 | 12 | for(int i=0;i int: 3 | has_zero = False 4 | n = len(nums) 5 | l, r = -1, 0 6 | ans, prev_len = 0, 0 7 | 8 | while r <= n: 9 | if r == n or nums[r] == 0: 10 | ans = max(ans, r-l+prev_len-2) # 2 substrings both end with 0s 11 | prev_len = r-l 12 | l = r 13 | if r < n: 14 | has_zero = True 15 | 16 | r += 1 17 | 18 | 19 | return ans if has_zero else n-1 -------------------------------------------------------------------------------- /easy/0202-happy-number/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | @staticmethod 3 | def sum_of_squares(n: int) -> int: 4 | if n==0 : 5 | return 0 6 | return (n%10)**2 + Solution.sum_of_squares(n//10) 7 | 8 | def isHappy(self, n: int) -> bool: 9 | if n <= 3: 10 | return False 11 | 12 | visited_nums = set() 13 | sq = self.sum_of_squares(n) 14 | 15 | while sq != 1 and sq not in visited_nums: 16 | visited_nums.add(sq) 17 | sq = self.sum_of_squares(sq) 18 | 19 | return True if sq == 1 else False 20 | -------------------------------------------------------------------------------- /easy/3174-clear-digits/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | string clearDigits(string s) { 7 | int pendingDigits = 0; 8 | string cleared = ""; 9 | 10 | for(int i=s.size()-1;i>=0;i-=1) { 11 | if(s[i]>='0' && s[i]<='9') 12 | pendingDigits += 1; 13 | else { 14 | if(pendingDigits > 0) 15 | pendingDigits -= 1; 16 | else 17 | cleared = s[i] + cleared; 18 | } 19 | } 20 | 21 | return cleared; 22 | } 23 | }; -------------------------------------------------------------------------------- /medium/1352-last-K-products/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class ProductOfNumbers { 5 | private: 6 | vector prods; 7 | 8 | public: 9 | ProductOfNumbers() {} 10 | 11 | void add(int num) { 12 | for(int i=prods.size()-1;i>=0;i-=1) { 13 | if(prods[i]==0) 14 | break; 15 | prods[i] *= num; 16 | } 17 | 18 | prods.push_back(num); 19 | } 20 | 21 | int getProduct(int k) { 22 | return prods[prods.size() - k]; 23 | } 24 | }; -------------------------------------------------------------------------------- /medium/2364-count-bad-pairs/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | long long countBadPairs(vector& nums) { 8 | unordered_map store; 9 | long long badPairs = 0; 10 | 11 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool areOccurrencesEqual(string s) { 8 | vector freqs(26,0); 9 | int latch; 10 | 11 | for(int i=0;i(s[i]) - 97; 13 | freqs[index] += 1; 14 | latch = freqs[index]; 15 | } 16 | 17 | for(int i=0;i<26;i+=1) 18 | if(freqs[i] && freqs[i]!=latch) 19 | return false; 20 | 21 | return true; 22 | } 23 | }; -------------------------------------------------------------------------------- /easy/2022-1d-into-2d-array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | vector> construct2DArray(vector& original, int m, int n) { 7 | int size = original.size(); 8 | 9 | if(m*n != size) 10 | return {}; 11 | 12 | int curr = 0; 13 | vector> dda(m, vector(n, 0)); 14 | 15 | for(int i = 0; i < m; i++) 16 | for(int j = 0; j < n; j++) { 17 | dda[i][j] = original[curr]; 18 | curr++; 19 | } 20 | 21 | return dda; 22 | } 23 | }; -------------------------------------------------------------------------------- /medium/0153-min-in-rotated-sorted-array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int findMin(vector& nums) { 7 | int low = 0, high = nums.size()-1; 8 | int mid; 9 | 10 | while(low<=high) { 11 | mid = low + (high-low)/2; 12 | 13 | if(nums[mid] > nums[high]) 14 | low = mid+1; 15 | else { 16 | if(mid == 0 || nums[mid] < nums[mid-1]) 17 | break; 18 | high = mid; 19 | } 20 | } 21 | 22 | return nums[mid]; 23 | } 24 | }; -------------------------------------------------------------------------------- /medium/0525-contiguous-array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int findMaxLength(vector& nums) { 8 | unordered_map cache; 9 | int count = 0, maxLen = 0; 10 | cache[0] = -1; 11 | 12 | for(int i=0; i int: 3 | # ans and freq 4 | ans, freq = nums[0], 0 5 | 6 | for num in nums: 7 | # if freq = 0: ans = num and freq = 1 8 | if freq == 0: 9 | ans = num 10 | freq = 1 11 | 12 | else: 13 | # if num == ans: freq+1 14 | if num == ans: 15 | freq += 1 16 | 17 | # else: freq-1 18 | else: 19 | freq -= 1 20 | 21 | 22 | return ans -------------------------------------------------------------------------------- /easy/0367-valid-perfect-square/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | public: 5 | bool isPerfectSquare(int num) { 6 | if(num == 1) 7 | return true; 8 | 9 | int low = 1, high = num/2; 10 | int mid; 11 | 12 | while(low<=high) { 13 | mid = low + (high-low)/2; 14 | 15 | if(mid == num/mid && num%mid==0) 16 | return true; 17 | 18 | if(mid > num/mid) 19 | high = mid-1; 20 | else 21 | low = mid+1; 22 | } 23 | 24 | return false; 25 | } 26 | }; -------------------------------------------------------------------------------- /medium/3163-string-compression-III/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | string compressedString(string word) { 7 | string comp = ""; 8 | int count = 1; 9 | char curr = word[0]; 10 | 11 | for(int i=1;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | string longestCommonPrefix(vector& strs) { 9 | sort(strs.begin(), strs.end()); 10 | int lcpIndex = -1; 11 | 12 | for(int i=0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int maxProfit(vector& prices) { 9 | if(prices.size()==1) 10 | return 0; 11 | 12 | int currHigh = INT_MIN, profit = 0; 13 | for(int i = prices.size()-2; i >= 0; i -= 1) { 14 | currHigh = max(currHigh, prices[i+1]); 15 | profit = max(profit, currHigh - prices[i]); 16 | } 17 | 18 | if(profit <= 0) 19 | return 0; 20 | 21 | return profit; 22 | } 23 | }; -------------------------------------------------------------------------------- /medium/0011-container-most-water/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, heights: List[int]) -> int: 3 | start, end = 0, len(heights)-1 4 | max_water = 0 5 | 6 | while start < end: 7 | water = (end - start) * min(heights[start], heights[end]) 8 | max_water = max(max_water, water) 9 | 10 | if heights[start] > heights[end]: 11 | end -= 1 12 | elif heights[start] < heights[end]: 13 | start += 1 14 | else: 15 | start += 1 16 | end -= 1 17 | 18 | 19 | return max_water -------------------------------------------------------------------------------- /medium/1545-kth-bit-in-nth-binary-string/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | private: 6 | string invertAndReverse(string s) { 7 | string edited = ""; 8 | for(int i=s.size()-1;i>=0;i-=1) 9 | edited += s[i] == '0' ? '1' : '0'; 10 | return edited; 11 | } 12 | 13 | public: 14 | char findKthBit(int n, int k) { 15 | // len after n moves: 2^n - 1 16 | string s = "0"; 17 | 18 | while(s.size() < k) 19 | s += "1" + invertAndReverse(s); 20 | 21 | return s[k-1]; 22 | } 23 | }; -------------------------------------------------------------------------------- /easy/0653-2-sum-IV-input-is-BST/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTarget(self, root: Optional[TreeNode], k: int) -> bool: 3 | 4 | def inorder(ptr): 5 | nonlocal isFound, wanted 6 | if not ptr or isFound: return 7 | if ptr.val in wanted: 8 | isFound = True 9 | return 10 | 11 | wanted.add(k-ptr.val) 12 | 13 | if not isFound: inorder(ptr.left) 14 | if not isFound: inorder(ptr.right) 15 | 16 | 17 | wanted = set() 18 | isFound = False 19 | inorder(root) 20 | 21 | return isFound -------------------------------------------------------------------------------- /medium/0300-longest-increasing-subsequence/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int lengthOfLIS(vector& nums) { 8 | vector lis; 9 | 10 | for(int i=0;i 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool check(vector& nums) { 7 | int curr = nums[0]; 8 | bool dipped = false, check = false; 9 | 10 | for(int i=1;i nums[0]) 19 | return false; 20 | } 21 | 22 | return true; 23 | } 24 | } -------------------------------------------------------------------------------- /medium/0516-longest-palindromic-subsequence/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestPalindromeSubseq(self, s: str) -> int: 3 | n = len(s) 4 | dp = [[0 for _ in range(n)] for _ in range(n)] 5 | 6 | # fill diagonals with 1 7 | for i in range(n): 8 | dp[i][i] = 1 9 | 10 | # from bottom to top build-up 11 | for i in range(n-2,-1,-1): 12 | for j in range(i+1,n): 13 | if s[j] == s[i]: 14 | dp[i][j] = 2 + dp[i+1][j-1] 15 | else: 16 | dp[i][j] = max(dp[i][j-1],dp[i+1][j]) 17 | 18 | return dp[0][n-1] -------------------------------------------------------------------------------- /easy/1437-check-all-1s-atleast-k-away/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool kLengthApart(vector& nums, int k) { 7 | int left = -1, right = 0; 8 | bool allCorrectlyAway = true; 9 | 10 | for(; right= k ? true : false; 15 | left = right; 16 | } 17 | } 18 | 19 | return allCorrectlyAway; 20 | } 21 | }; -------------------------------------------------------------------------------- /medium/0050-pow/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x: float, n: int) -> float: 3 | if x==0: 4 | return 0 5 | if n==0 or x==1: 6 | return 1 7 | if x==-1: 8 | return 1 if n % 2 == 0 else -1 9 | 10 | ans = 1.0 11 | reciprocal = True if n < 0 else False 12 | n = n if n > 0 else -1*n 13 | 14 | for i in range(n): 15 | if ans >= 0 and ans <= 0.00001: 16 | return ans 17 | 18 | if reciprocal: 19 | ans *= 1/x 20 | else: 21 | ans *= x 22 | 23 | return ans -------------------------------------------------------------------------------- /medium/3201-valid-subsequence-I/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumLength(self, nums: List[int]) -> int: 3 | evens, odds, alternates = 0, 0, 0 4 | last_even = False if nums[0] % 2 == 0 else True 5 | 6 | for num in nums: 7 | if num % 2 == 0: 8 | evens += 1 9 | if not last_even: 10 | alternates += 1 11 | last_even = True 12 | else: 13 | odds += 1 14 | if last_even: 15 | alternates += 1 16 | last_even = False 17 | 18 | return max(evens, max(odds, alternates)) -------------------------------------------------------------------------------- /easy/0234-palindrome-LL/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool isPalindrome(ListNode* head) { 7 | ListNode *slow = head, *fast = head; 8 | stack st; 9 | 10 | while(fast && fast->next) { 11 | fast = fast->next; 12 | st.push(slow->val); 13 | if(fast->next) { 14 | slow = slow->next; 15 | fast = fast->next; 16 | } 17 | } 18 | 19 | slow = slow->next; 20 | 21 | while(slow) { 22 | if(slow->val != st.top()) 23 | return false; 24 | st.pop(); 25 | slow = slow->next; 26 | } 27 | 28 | return true; 29 | } 30 | }; -------------------------------------------------------------------------------- /easy/0876-middle-of-LL/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | ListNode() : val(0), next(nullptr) {} 7 | ListNode(int x) : val(x), next(nullptr) {} 8 | ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | ListNode* middleNode(ListNode* head) { 14 | ListNode* tortoise = head; 15 | ListNode* hare = head; 16 | while(hare && hare->next) { 17 | hare = hare->next->next; 18 | tortoise = tortoise->next; 19 | } 20 | 21 | return tortoise; 22 | } 23 | }; -------------------------------------------------------------------------------- /easy/3375-min-operations-make-arr-vals-equals-K/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int minOperations(vector& nums, int k) { 8 | vector exists(101,false); 9 | int least = 101, unique = 0; 10 | 11 | for(int i=0;i least) return -1; 20 | 21 | return unique - 1 + (k==least ? 0 : 1); 22 | } 23 | }; -------------------------------------------------------------------------------- /medium/0201-bitwise-AND-of-number-range/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | private: 5 | int checkAND(int low, int high) { 6 | for(;low<=high;low+=1) 7 | if(low%2==0) return 0; 8 | return 1; 9 | } 10 | 11 | public: 12 | int rangeBitwiseAnd(int left, int right) { 13 | if(left==right) 14 | return left; 15 | 16 | int i = 0, andSum = 0; 17 | while(right>0) { 18 | andSum += (1<>= 1; 20 | right >>= 1; 21 | i += 1; 22 | } 23 | 24 | return andSum; 25 | } 26 | }; -------------------------------------------------------------------------------- /medium/0921-min-add-to-make-paranthesis-valid/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int minAddToMakeValid(string s) { 7 | int count = 0, found = 0; 8 | 9 | for(int i=0;i 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | string countAndSay(int n) { 7 | string rle = "1", temp; 8 | int low, high; 9 | 10 | for(;n>1;n-=1) { 11 | temp = ""; 12 | low = 0, high = 0; 13 | while(high < rle.size()) { 14 | while(high < rle.size() && rle[high]==rle[low]) 15 | high += 1; 16 | temp += to_string(high-low) + rle[low]; 17 | low = high; 18 | } 19 | rle = temp; 20 | } 21 | 22 | return rle; 23 | } 24 | }; -------------------------------------------------------------------------------- /medium/0523-continuous-subarray-sum/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool checkSubarraySum(vector& nums, int k) { 8 | unordered_map finds; 9 | int sum = 0; 10 | for(int i=0;i= 1) || (finds.find(sum) != finds.end() && i-finds[sum] >= 2)) 13 | return true; 14 | if(finds.find(sum) == finds.end()) 15 | finds[sum] = i; 16 | } 17 | 18 | return false; 19 | } 20 | }; -------------------------------------------------------------------------------- /medium/3767-max-points-after-K-tasks/sol.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class Solution: 4 | def maxPoints(self, t1: List[int], t2: List[int], k: int) -> int: 5 | heap = [] 6 | ans = 0 7 | used = set() 8 | 9 | for i in range(len(t1)): 10 | diff = t1[i] - t2[i] 11 | heapq.heappush(heap,(-diff,i)) 12 | 13 | for _ in range(k): 14 | _, i = heapq.heappop(heap) 15 | ans += t1[i] 16 | used.add(i) 17 | 18 | for i in range(len(t1)): 19 | if i not in used: 20 | ans += max(t1[i],t2[i]) 21 | 22 | return ans 23 | -------------------------------------------------------------------------------- /easy/1957-delete-chars-to-make-fancy-string/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | string makeFancyString(string s) { 7 | string fancy = ""; 8 | char curr = s[0]; 9 | bool allowMore = true; 10 | 11 | fancy += s[0]; 12 | for(int i=1;i 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int findNthDigit(int n) { 8 | int num = 1, digits = 1; 9 | int offset = 0; 10 | 11 | while((long)(offset + 9 * digits * pow(10,digits-1)) < (long)n) { 12 | offset += 9 * digits * pow(10,digits-1); 13 | digits += 1; 14 | num *= 10; 15 | } 16 | 17 | n -= offset; 18 | num += (n-1)/digits; 19 | while(n > digits) 20 | n -= digits; 21 | 22 | return static_cast(to_string(num)[n-1]) - 48; 23 | } 24 | }; -------------------------------------------------------------------------------- /medium/1695-max-erasure-value/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumUniqueSubarray(self, nums: List[int]) -> int: 3 | map = {} 4 | curr_sum, max_sum, n = 0, 0, len(nums) 5 | l, r = 0, 0 6 | 7 | 8 | while r < n: 9 | curr_sum += nums[r] 10 | 11 | if nums[r] in map: 12 | index = map[nums[r]] + 1 13 | while l < index: 14 | curr_sum -= nums[l] 15 | l += 1 16 | 17 | 18 | max_sum = max(max_sum, curr_sum) 19 | 20 | map[nums[r]] = r 21 | r += 1 22 | 23 | 24 | return max_sum -------------------------------------------------------------------------------- /easy/0111-min-depth-of-BT/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | private: 7 | int minDep; 8 | 9 | void findDepth(TreeNode *ptr, int curr) { 10 | if(!ptr->left && !ptr->right) { 11 | minDep = min(minDep,curr); 12 | return; 13 | } 14 | 15 | if(ptr->left) findDepth(ptr->left,curr+1); 16 | if(ptr->right) findDepth(ptr->right,curr+1); 17 | } 18 | 19 | public: 20 | int minDepth(TreeNode* root) { 21 | if(!root) return 0; 22 | minDep = INT_MAX; 23 | findDepth(root, 1); 24 | return minDep; 25 | } 26 | }; -------------------------------------------------------------------------------- /easy/2574-left-right-sum-difference/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector leftRightDifference(vector& nums) { 8 | vector leftSum(nums.size(),0), rightSum(nums.size(),0); 9 | 10 | for(int i=1;i int: 5 | heap = [] 6 | heapq.heappush(heap,1) 7 | seen = set() 8 | 9 | for _ in range(n-1): 10 | x = heapq.heappop(heap) 11 | if x*2 not in seen: 12 | heapq.heappush(heap,x*2) 13 | seen.add(x*2) 14 | if x*3 not in seen: 15 | heapq.heappush(heap,x*3) 16 | seen.add(x*3) 17 | if x*5 not in seen: 18 | heapq.heappush(heap,x*5) 19 | seen.add(x*5) 20 | 21 | return heapq.heappop(heap) -------------------------------------------------------------------------------- /medium/0788-rotated-digits/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotatedDigits(self, n: int) -> int: 3 | 4 | def isGood(num): 5 | flag = False 6 | while num > 0: 7 | dig = num % 10 8 | if dig in [3,4,7]: 9 | return False 10 | if dig in [2,5,6,9] and not flag: 11 | flag = True 12 | 13 | num //= 10 14 | 15 | return flag 16 | 17 | 18 | dp = 0 # n=1 -> 0 good 19 | for num in range(2,n+1): 20 | dp += int(isGood(num)) 21 | 22 | return dp -------------------------------------------------------------------------------- /medium/3381-max-subarray-sum-of-length-div-by-K/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubarraySum(self, nums: List[int], k: int) -> int: 3 | globalSum = float('-inf') 4 | currSum = 0 5 | sums = [0 for _ in range(k)] 6 | 7 | for i in range(k): 8 | currSum += nums[i] 9 | 10 | globalSum = max(globalSum,currSum) 11 | sums[0] = max(0,currSum) 12 | 13 | for i in range(k,len(nums)): 14 | x = (i-k+1)%k 15 | currSum += nums[i] - nums[i-k] 16 | globalSum = max(globalSum,currSum+sums[x]) 17 | sums[x] = max(0,currSum+sums[x]) 18 | 19 | return globalSum -------------------------------------------------------------------------------- /easy/1854-max-population-year/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int maximumPopulation(vector>& logs) { 7 | vector alive(101, 0); 8 | int maxPIndex = 0; 9 | 10 | for(int i=0;i alive[maxPIndex]) 18 | maxPIndex = i; 19 | } 20 | 21 | return maxPIndex + 1950; 22 | } 23 | }; -------------------------------------------------------------------------------- /medium/0075-sort-colors/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | void sortColors(vector& nums) { 7 | if(nums.size() == 1) return; 8 | 9 | int low = 0, high = nums.size()-1, mid = 0; 10 | while(mid <= high) { 11 | if(nums[mid] < 1) { 12 | swap(nums[mid],nums[low]); 13 | low += 1; 14 | mid += 1; 15 | } 16 | else if(nums[mid] > 1) { 17 | swap(nums[mid],nums[high]); 18 | high -= 1; 19 | } 20 | else 21 | mid += 1; 22 | } 23 | } 24 | }; -------------------------------------------------------------------------------- /medium/0799-champagne-tower/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: 3 | dp = [[0 for _ in range(query_row+2)] for _ in range(query_row+2)] 4 | dp[0][0] = poured 5 | 6 | for i in range(query_row+1): 7 | for j in range(i+1): 8 | # check for overflow 9 | if dp[i][j] > 1: 10 | rem = dp[i][j] - 1 11 | dp[i][j] = 1 12 | 13 | # pour to bottom level 14 | dp[i+1][j] += rem/2 15 | dp[i+1][j+1] += rem/2 16 | 17 | 18 | return dp[query_row][query_glass] -------------------------------------------------------------------------------- /medium/2348-zero-filled-subarrays/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def zeroFilledSubarray(self, nums: List[int]) -> int: 3 | l, size = -1, len(nums) 4 | ans = 0 5 | flag = False 6 | 7 | for i in range(1+size): 8 | # count subarrays when non zero 9 | if i == size or nums[i] != 0: 10 | if flag: 11 | n = i-l 12 | ans += int((n*(n+1))/2) 13 | flag = False 14 | 15 | # increase size when zeroes 16 | else: 17 | if not flag: 18 | l = i 19 | flag = True 20 | 21 | return ans -------------------------------------------------------------------------------- /medium/2028-find-missing-observations/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector missingRolls(vector& rolls, int mean, int n) { 8 | int sumN, sumM = 0; 9 | for(int i=0;i 6 || (floor(sumN/n)==6 && sumN%n>0) || sumN < n) 15 | return {}; 16 | 17 | vector otherHalf(n,floor(sumN/n)); 18 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool canConstruct(string ransomNote, string magazine) { 8 | if(ransomNote.size() > magazine.size()) 9 | return false; 10 | 11 | vector freqs(26,0); 12 | 13 | for(int i=0;i int: 3 | freq = [-1]*26 4 | 5 | for i in range(len(s)): 6 | j = ord(s[i]) - 97 7 | 8 | # found earlier 9 | if freq[j] >= 0: 10 | freq[j] = -2 11 | 12 | # update first occurence 13 | elif freq[j] == -1: 14 | freq[j] = i 15 | 16 | 17 | # find least index 18 | INF = float('inf') 19 | ans = INF 20 | 21 | for f in freq: 22 | if f >= 0: 23 | ans = min(ans, f) 24 | 25 | return ans if ans != INF else -1 -------------------------------------------------------------------------------- /medium/0080-remove-duplicates-from-sorted-array-II/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int removeDuplicates(vector& nums) { 7 | int left = -1, count = 0; 8 | for(int i=0;i int: 5 | 6 | def rev(x): 7 | rev = 0 8 | while x > 0: 9 | rev = rev*10 + x%10 10 | x //= 10 11 | return rev 12 | 13 | 14 | cache = defaultdict(int) 15 | INF = float('inf') 16 | ans = INF 17 | 18 | for i, num in enumerate(nums): 19 | if num in cache: 20 | ans = min(ans,abs(i-cache[num])) 21 | cache[rev(num)] = i 22 | 23 | return ans if ans != INF else -1 -------------------------------------------------------------------------------- /hard/0084-largest-rectangle-in-histogram/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int largestRectangleArea(vector& heights) { 8 | int maxArea = INT_MIN; 9 | int local_min = INT_MAX; 10 | int len = heights.size(); 11 | 12 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int lengthOfLongestSubstring(string s) { 8 | int currLen = 0, maxLen = 0; 9 | unordered_map lastFound; 10 | 11 | for(int i=0;i 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | void moveZeroes(vector& nums) { 7 | int left = 0; 8 | for(int right = 0;right= nums.size()-1) 13 | return; 14 | 15 | while(right <= left) 16 | right += 1; 17 | 18 | if(nums[right] != 0) { 19 | nums[left] = nums[right]; 20 | nums[right] = 0; 21 | } 22 | } 23 | } 24 | }; -------------------------------------------------------------------------------- /medium/0048-rotate-image/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, matrix: List[List[int]]) -> None: 3 | n = len(matrix) 4 | mid = math.floor(n/2) 5 | 6 | for i in range(mid): 7 | for j in range(i,n-i-1): 8 | # switch values of the 4 cells 9 | x, y = i, j 10 | temp = matrix[y][n-1-x] 11 | matrix[y][n-1-x] = matrix[x][y] 12 | 13 | for step in range(3): 14 | x, y = y, n-1-x 15 | matrix[y][n-1-x], temp = temp, matrix[y][n-1-x] 16 | if step == 2: 17 | temp = matrix[y][n-1-x] 18 | 19 | matrix[i][j] = temp -------------------------------------------------------------------------------- /medium/0096-unique-BSTs/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numTrees(self, n: int) -> int: 3 | def subTreeWays(x): 4 | nonlocal ways 5 | # return cache 6 | if ways[x]: 7 | return ways[x] 8 | # compute for this nodes subtree 9 | ans = 0 10 | for i in range(x): 11 | left = subTreeWays(i) 12 | right = subTreeWays(x-1-i) 13 | ans += left * right 14 | # save to cache and return 15 | ways[x] = ans 16 | return ans 17 | 18 | 19 | ways = [0 for _ in range(n+1)] 20 | ways[0] = ways[1] = 1 21 | 22 | return subTreeWays(n) 23 | -------------------------------------------------------------------------------- /medium/1283-smallest-divisor-within-budget/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def smallestDivisor(self, nums: List[int], threshold: int) -> int: 3 | low, high = 1, pow(10,6) 4 | s = 0 5 | ans = 1 6 | 7 | while low <= high: 8 | mid = low + (high-low)//2 9 | s = 0 10 | flag = False 11 | 12 | for num in nums: 13 | s += (num+mid-1) // mid 14 | if s > threshold: 15 | low = mid+1 16 | flag = True 17 | break 18 | 19 | if flag: continue 20 | ans = mid 21 | high = mid-1 22 | 23 | 24 | return ans -------------------------------------------------------------------------------- /easy/0303-range-sum-query-immutable/sol.py: -------------------------------------------------------------------------------- 1 | class NumArray: 2 | 3 | def __init__(self, nums: List[int]): 4 | self.n = len(nums) 5 | self.leftSum = [0]*self.n 6 | self.rightSum = [0]*self.n 7 | 8 | for i in range(self.n): 9 | j = self.n-1-i 10 | self.leftSum[i] = nums[i] + (self.leftSum[i-1] if i>0 else 0) 11 | self.rightSum[j] = nums[j] + (self.rightSum[j+1] if j int: 16 | lsum = self.leftSum[left-1] if left > 0 else 0 17 | rsum = self.rightSum[right+1] if right < self.n-1 else 0 18 | return self.leftSum[self.n-1] - (lsum + rsum) 19 | -------------------------------------------------------------------------------- /medium/0064-min-path-sum/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int minPathSum(vector>& grid) { 8 | vector> dp(grid.size(),vector(grid[0].size(),0)); 9 | 10 | for(int i=grid.size()-1;i>=0;i-=1) 11 | for(int j=grid[0].size()-1;j>=0;j-=1) 12 | if(i==grid.size()-1 && j==grid[0].size()-1) 13 | dp[i][j] = grid[i][j]; 14 | else 15 | dp[i][j] = grid[i][j] + min(i+1 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | vector findMissingAndRepeatedValues(vector>& grid) { 7 | int n = grid.size(); 8 | int sum = (n*n)*(n*n+1)/2; 9 | int dup = 0; 10 | vector exists(n*n,false); 11 | 12 | for(int i=0;i 2 | using namespace std; 3 | 4 | class FindElements { 5 | private: 6 | unordered_set store; 7 | 8 | void recoverTree(TreeNode *ptr, int val) { 9 | if(!ptr) return; 10 | 11 | ptr->val = val; 12 | store.insert(val); 13 | 14 | if(ptr->left) 15 | recoverTree(ptr->left, 2*ptr->val + 1); 16 | if(ptr->right) 17 | recoverTree(ptr->right, 2*ptr->val + 2); 18 | } 19 | 20 | public: 21 | FindElements(TreeNode* root) { 22 | recoverTree(root, 0); 23 | } 24 | 25 | bool find(int target) { 26 | return store.count(target); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /medium/1277-submatrices-with-ones/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSquares(self, matrix: List[List[int]]) -> int: 3 | rows, cols = len(matrix), len(matrix[0]) 4 | squares = 0 5 | 6 | for i in range(rows-1,-1,-1): 7 | for j in range(cols-1,-1,-1): 8 | if matrix[i][j] > 0: 9 | right = matrix[i][j+1] if j < cols-1 else 0 10 | bottom = matrix[i+1][j] if i < rows-1 else 0 11 | bott_right = matrix[i+1][j+1] if i < rows-1 and j < cols-1 else 0 12 | 13 | matrix[i][j] = 1 + min(right, bottom, bott_right) 14 | squares += matrix[i][j] 15 | 16 | 17 | return squares -------------------------------------------------------------------------------- /medium/3295-report-spam-message/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | bool reportSpam(vector& message, vector& bannedWords) { 9 | unordered_set store; 10 | bool foundDouble = true; 11 | 12 | for(int i=0;i Optional[ListNode]: 3 | if not head: 4 | return None 5 | 6 | lower, higher = [], [] 7 | ptr = head 8 | 9 | while ptr: 10 | if ptr.val < x: lower.append(ptr.val) 11 | else: higher.append(ptr.val) 12 | ptr = ptr.next 13 | 14 | ptr = head 15 | m,n = len(lower), len(higher) 16 | 17 | for i in range(m): 18 | ptr.val = lower[i] 19 | ptr = ptr.next 20 | for i in range(n): 21 | ptr.val = higher[i] 22 | ptr = ptr.next 23 | 24 | return head -------------------------------------------------------------------------------- /medium/2125-total-laser-beams-in-bank/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int numberOfBeams(vector& bank) { 8 | int beams = 0; 9 | int prevFloor = 0, floorBeams = 0; 10 | 11 | for(int i=0;i(bank[i][j]) - 48; 15 | 16 | if(floorBeams > 0) { 17 | beams += prevFloor*floorBeams; 18 | prevFloor = floorBeams; 19 | } 20 | } 21 | 22 | return beams; 23 | } 24 | }; -------------------------------------------------------------------------------- /medium/3542-min-ops-all-elements-zero/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, nums: List[int]) -> int: 3 | st = [] 4 | ans = 0 5 | 6 | for num in nums: 7 | if num == 0: 8 | st = [] 9 | else: 10 | if not st or num > st[-1]: 11 | ans += 1 12 | st.append(num) 13 | 14 | elif num < st[-1]: 15 | while st and st[-1] > num: 16 | st.pop() 17 | if not st or st[-1] < num: 18 | ans += 1 19 | st.append(num) 20 | 21 | 22 | return ans -------------------------------------------------------------------------------- /medium/0343-integer-break/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | /* 4 | for a number n being divided into x parts, then product is x^(n/x) 5 | derivative of it = (n/x) * x^(n/x - 1) + n*logx 6 | log x to be max => 2 < e < 3 7 | so max 2 or 3 should be selected 8 | 9 | */ 10 | 11 | class Solution { 12 | public: 13 | int integerBreak(int n) { 14 | if(n==2) return 1; 15 | if(n==3) return 2; 16 | 17 | int prod = 1; 18 | while(n>0) { 19 | if(n==2 || n==3 || n==4) { 20 | prod *= n; 21 | break; 22 | } 23 | 24 | prod *= 3; 25 | n -= 3; 26 | } 27 | 28 | return prod; 29 | } 30 | }; -------------------------------------------------------------------------------- /easy/0643-max-average-subarray-I/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | double findMaxAverage(vector& nums, int k) { 9 | double sum = 0.0, maxSum = INT_MIN; 10 | int left = 0, right = k-1; 11 | for(int i=0;i<=right;i+=1) 12 | sum += nums[i]; 13 | 14 | maxSum = max(maxSum, sum); 15 | right += 1; 16 | left += 1; 17 | 18 | for(; right int: 5 | hor,ver = defaultdict(tuple), defaultdict(tuple) 6 | covered = 0 7 | 8 | for a,b in buildings: 9 | if a in ver: ver[a] = ( min(ver[a][0],b), max(ver[a][1],b) ) 10 | else: ver[a] = ( b, b ) 11 | if b in hor: hor[b] = ( min(hor[b][0],a), max(hor[b][1],a) ) 12 | else: hor[b] = ( a, a ) 13 | 14 | for a,b in buildings: 15 | if (hor[b][0] < a < hor[b][1]) and (ver[a][0] < b < ver[a][1]): 16 | covered += 1 17 | 18 | return covered -------------------------------------------------------------------------------- /easy/0202-happy-number/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | private: 6 | int sum_of_squares(int n) { 7 | int sum = 0; 8 | while(n > 0) { 9 | int digit = n % 10; 10 | sum += digit * digit; 11 | n /= 10; 12 | } 13 | 14 | return sum; 15 | } 16 | 17 | public: 18 | bool isHappy(int n) { 19 | unordered_set visited_nums; 20 | int sq = sum_of_squares(n); 21 | 22 | while(sq!=1 && visited_nums.find(sq)==visited_nums.end()) { 23 | visited_nums.insert(sq); 24 | sq = sum_of_squares(sq); 25 | } 26 | 27 | return sq == 1; 28 | } 29 | }; -------------------------------------------------------------------------------- /medium/0236-lowest-common-ancestor-in-binary-tree/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | private: 5 | TreeNode *lca, *a, *b; 6 | int findLCA(TreeNode *ptr) { 7 | if(!ptr || lca) 8 | return 0; 9 | 10 | int desc = findLCA(ptr->left) + findLCA(ptr->right); 11 | 12 | if(desc == 2 || ((ptr == a || ptr == b) && desc == 1)) { 13 | lca = ptr; 14 | return 0; 15 | } 16 | 17 | return (ptr == a || ptr == b ? 1 : 0) + desc; 18 | } 19 | 20 | public: 21 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 22 | a = p; 23 | b = q; 24 | findLCA(root); 25 | return lca; 26 | } 27 | }; -------------------------------------------------------------------------------- /easy/2379-min-recolors-for-K-black-blocks/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int minimumRecolors(string blocks, int k) { 7 | int minRecolors = 0; 8 | int whites = 0; 9 | int left = 0, right = k-1; 10 | 11 | for(;left<=right;left+=1) 12 | if(blocks[left] == 'W') 13 | whites += 1; 14 | 15 | minRecolors = whites; 16 | 17 | for(left=1,right+=1;right List[List[int]]: 4 | 5 | def backtrack(rem, prev_used, used): 6 | if rem == 0: 7 | ans.append(used) 8 | return 9 | 10 | for num in candidates: 11 | if num > rem: 12 | break 13 | if num < prev_used: 14 | continue 15 | updated = used[:] 16 | updated.append(num) 17 | backtrack(rem-num, num, updated) 18 | 19 | 20 | ans = [] 21 | candidates = sorted(candidates) 22 | backtrack(target, -1, []) 23 | 24 | return ans -------------------------------------------------------------------------------- /easy/0234-palindrome-LL/sol.go: -------------------------------------------------------------------------------- 1 | package palindromell 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func isPalindrome(head *ListNode) bool { 9 | recorded := []int{} 10 | slow, fast := head, head 11 | count, ptr := 0, 0 12 | 13 | // track first half values 14 | for fast != nil { 15 | recorded = append(recorded, slow.Val) 16 | slow = slow.Next 17 | fast = fast.Next 18 | count += 1 19 | 20 | if fast != nil { 21 | fast = fast.Next 22 | count += 1 23 | } 24 | } 25 | 26 | ptr = count/2 - 1 27 | 28 | // check palindrome for half the list 29 | for slow != nil { 30 | if slow.Val != recorded[ptr] { 31 | return false 32 | } 33 | slow = slow.Next 34 | ptr -= 1 35 | } 36 | 37 | return true 38 | } 39 | -------------------------------------------------------------------------------- /medium/2095-delete-middle-node-of-linked-list/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | }; 7 | 8 | class Solution { 9 | public: 10 | ListNode* deleteMiddle(ListNode* head) { 11 | ListNode *slow = head, *fast = head; 12 | ListNode *prev = nullptr; 13 | 14 | while(fast && fast->next) { 15 | fast = fast->next; 16 | prev = slow; 17 | slow = slow->next; 18 | 19 | if(fast && fast->next) 20 | fast = fast->next; 21 | } 22 | 23 | if(!prev) 24 | return nullptr; 25 | 26 | prev->next = slow->next; 27 | slow->next = nullptr; 28 | 29 | return head; 30 | } 31 | }; -------------------------------------------------------------------------------- /easy/0035-search-insert-position/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int searchInsert(vector& nums, int target) { 7 | int low = 0, high = nums.size()-1; 8 | int mid; 9 | 10 | while(low<=high) { 11 | mid = low + (high-low)/2; 12 | 13 | if(nums[mid]==target) return mid; 14 | else if(mid-1 >=0 && nums[mid-1]target) return mid; 15 | else if(mid+1 target && nums[mid] int: 3 | m, n = len(grid), len(grid[0]) 4 | cost = [0]*n 5 | min_cost, ans = inf, inf 6 | 7 | for i in range(m-2,-1,-1): 8 | for j in range(n): 9 | cell = grid[i][j] 10 | 11 | for k in range(n): 12 | cost = moveCost[cell][k] + grid[i+1][k] 13 | min_cost = min(min_cost, cost) 14 | 15 | grid[i][j] += min_cost 16 | min_cost = inf 17 | 18 | if i == 0: 19 | ans = min(ans, grid[i][j]) 20 | 21 | 22 | return ans -------------------------------------------------------------------------------- /easy/2190-most-frequent-num-following-key-in-array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int mostFrequent(vector& nums, int key) { 8 | unordered_map counts; 9 | int maxTarget = 0; 10 | 11 | for(int i=0;i int: 3 | # A-Z 0-25 and a-z 26-51 4 | f = [0 for _ in range(52)] 5 | 6 | for ch in s: 7 | i = ord(ch) - 65 8 | if i > 26: i -= 6 # for a-z 9 | f[i] += 1 10 | 11 | odd_taken = False 12 | ans = 0 13 | 14 | for val in f: 15 | # odd count 16 | if val&1: 17 | if not odd_taken: 18 | ans += val 19 | odd_taken = True 20 | else: 21 | ans += val-1 22 | 23 | # even count 24 | else: 25 | ans += val 26 | 27 | 28 | return ans -------------------------------------------------------------------------------- /easy/3264-final-arr-state-after-K-multiplications-I/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector getFinalState(vector& nums, int k, int multiplier) { 9 | priority_queue, vector>, greater>> heap; 10 | 11 | for (int i = 0; i < nums.size(); i += 1) 12 | heap.push({ nums[i], i }); 13 | 14 | for (; k > 0; k -= 1) { 15 | pair x = heap.top(); 16 | heap.pop(); 17 | nums[x.second] = x.first * multiplier; 18 | heap.push({ x.first * multiplier, x.second }); 19 | } 20 | 21 | return nums; 22 | } 23 | }; -------------------------------------------------------------------------------- /medium/2044-total-max-OR-subsets/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int countMaxOrSubsets(vector& nums) { 8 | unordered_map freq; 9 | vector ORs = {0}; 10 | int maxOR = 0, n, OR; 11 | 12 | for(int i=0;i None: 14 | row, col = self.getRowCol(key) 15 | self.spaces[row][col] = value 16 | 17 | 18 | def get(self, key: int) -> int: 19 | row, col = self.getRowCol(key) 20 | val = self.spaces[row][col] 21 | return val if val != None else -1 22 | 23 | 24 | def remove(self, key: int) -> None: 25 | row, col = self.getRowCol(key) 26 | self.spaces[row][col] = None 27 | 28 | -------------------------------------------------------------------------------- /medium/0151-reverse-word-in-string/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | string reverseWords(string s) { 7 | s = ' ' + s; 8 | bool addSpace = false; 9 | string temp = "", reversed = ""; 10 | 11 | for(int i=s.size()-1;i>=0;i-=1) 12 | if(s[i] == ' ') { 13 | if(temp.size() > 0) { 14 | if(addSpace) reversed += ' '; 15 | else addSpace = true; 16 | reversed.append(temp); 17 | temp = ""; 18 | } 19 | } 20 | else 21 | temp = s[i] + temp; 22 | 23 | return reversed; 24 | } 25 | }; -------------------------------------------------------------------------------- /medium/2530-maximal-score-after-k-operations/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public : 7 | long long maxKelements(vector& nums, int k) { 8 | long long score = 0; 9 | priority_queue heap; 10 | for (int i = 0; i < nums.size(); i += 1) 11 | heap.push(nums[i]); 12 | 13 | int curr = 0; 14 | 15 | for (int i = 0; i < k; i += 1) { 16 | if (!heap.empty() && curr <= heap.top()) { 17 | heap.push(curr); 18 | curr = heap.top(); 19 | heap.pop(); 20 | } 21 | score += curr; 22 | curr = ceil((double)curr/3.0); 23 | } 24 | 25 | return score; 26 | } 27 | }; -------------------------------------------------------------------------------- /easy/2264-largest-3-same-number/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def is_good(self, num: str): 3 | return num[0] == num[1] and num[1] == num[2] 4 | 5 | def largestGoodInteger(self, num: str) -> str: 6 | curr_score = num[0:3] 7 | 8 | max_score = -1 9 | if self.is_good(curr_score): 10 | max_score = int(curr_score) 11 | 12 | 13 | for left in range(1, len(num)-2): 14 | right = left + 2 15 | curr_score = curr_score[1:] + num[right] 16 | 17 | if self.is_good(curr_score): 18 | max_score = max(max_score, int(curr_score)) 19 | 20 | 21 | if max_score == -1: 22 | return "" 23 | if max_score == 0: 24 | return "000" 25 | return str(max_score) -------------------------------------------------------------------------------- /hard/0042-trapping-rain-water/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int trap(vector& height) { 8 | int len = height.size(); 9 | vector left(len), 10 | right(len); 11 | int waterTrapped = 0; 12 | 13 | for(int i=0, j=len-1; i < len, j >= 0; i++, j--) { 14 | int l = i==0 ? INT_MIN : left[i-1]; 15 | left[i] = max(l ,height[i]); 16 | 17 | int r = j==len-1 ? INT_MIN : right[j+1]; 18 | right[j] = max(r, height[j]); 19 | } 20 | 21 | for(int i=0; i 2 | #include 3 | using namespace std; 4 | 5 | class MinStack { 6 | public: 7 | int topIndex; 8 | stack> st; 9 | 10 | MinStack() { 11 | topIndex = -1; 12 | } 13 | 14 | void push(int val) { 15 | int curr_min = val; 16 | if(topIndex > -1) 17 | curr_min = min(val,st.top().second); 18 | 19 | st.push(make_pair(val,curr_min)); 20 | topIndex += 1; 21 | } 22 | 23 | void pop() { 24 | if(topIndex==-1) return; 25 | st.pop(); 26 | topIndex -= 1; 27 | } 28 | 29 | int top() { 30 | return st.top().first; 31 | } 32 | 33 | int getMin() { 34 | return st.top().second; 35 | } 36 | }; -------------------------------------------------------------------------------- /medium/0560-subarray-sum-equals-K/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int subarraySum(vector& nums, int k) { 8 | unordered_map lookback; 9 | vector pre(nums.size(),0); 10 | int total = 0; 11 | 12 | lookback[0] = 1; 13 | 14 | for(int i=0;i0 ? pre[i-1] : 0) + nums[i]; 16 | 17 | if(lookback.count(pre[i]-k)) 18 | total += lookback[pre[i]-k]; 19 | 20 | if(lookback.count(pre[i])) lookback[pre[i]] += 1; 21 | else lookback[pre[i]] = 1; 22 | } 23 | 24 | return total; 25 | } 26 | }; -------------------------------------------------------------------------------- /medium/2270-total-ways-to-split-array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int waysToSplitArray(vector& nums) { 7 | vector> prefixSum(2, vector(nums.size(),0)); 8 | int ways = 0; 9 | 10 | for(int i=0;i0?prefixSum[0][i-1]:0)+nums[i]; 13 | prefixSum[1][backIndex] = (backIndex= prefixSum[1][i+1]) 18 | ways += 1; 19 | 20 | return ways; 21 | } 22 | }; -------------------------------------------------------------------------------- /medium/3191-min-switch-to-make-binary-array-equal-to-one/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int minOperations(vector& nums) { 7 | int left = 0; 8 | int steps = 0; 9 | 10 | for(;left+2 int: 3 | n = len(s) 4 | pre = [0 for _ in range(n)] 5 | curr = 0 6 | 7 | # build prefix sum 8 | for i in range(n): 9 | num = abs(ord(s[i]) - ord(t[i])) 10 | curr += num 11 | pre[i] = curr 12 | 13 | # 2 pointers find longest subarr with sum <= maxCost 14 | l,r = -1,0 15 | maxLen = 0 16 | 17 | while r < n: 18 | s = pre[r] - (pre[l] if l>=0 else 0) 19 | if s <= maxCost: 20 | maxLen = max(maxLen,r-l) 21 | r += 1 22 | else: 23 | l += 1 24 | 25 | 26 | return maxLen -------------------------------------------------------------------------------- /medium/0394-decode-string/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def decodeString(self, s: str) -> str: 3 | word = "" 4 | count = 0 5 | st = [] 6 | 7 | for ch in s: 8 | if ch == '[': 9 | st.append(word) 10 | st.append(max(1,count)) 11 | word = "" 12 | count = 0 13 | 14 | elif ch == ']': 15 | times = st.pop() 16 | temp = st.pop() + word*times 17 | word = temp 18 | 19 | else: 20 | asci = ord(ch) 21 | if 48 <= asci <= 57: 22 | count = count*10 + int(ch) 23 | else: 24 | word += ch 25 | 26 | 27 | return word -------------------------------------------------------------------------------- /medium/1605-valid-matrix-given-row-col-sums/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector> restoreMatrix(vector& rowSum, vector& colSum) { 8 | vector> matrix(rowSum.size(), vector(colSum.size(), 0)); 9 | int tempMin; 10 | 11 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int matchPlayersAndTrainers(vector& players, vector& trainers) { 8 | sort(trainers.begin(), trainers.end()); 9 | sort(players.begin(), players.end()); 10 | 11 | int pairs = 0, trainer = 0; 12 | 13 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int coinChange(vector& coins, int amount) { 8 | if(amount == 0) 9 | return 0; 10 | 11 | vector dp(amount, -1); 12 | sort(coins.begin(), coins.end()); 13 | 14 | for(int a=1;a<=amount;a+=1) 15 | for(int i=0;i a) 17 | continue; 18 | else if(coins[i] == a) 19 | dp[a-1] = 1; 20 | else if(dp[a-1-coins[i]] != -1) 21 | dp[a-1] = min(dp[a-1] == -1 ? INT_MAX : dp[a-1], 1 + dp[a-1-coins[i]]); 22 | } 23 | 24 | return dp[amount-1]; 25 | } 26 | }; -------------------------------------------------------------------------------- /medium/1004-max-consecutive-ones-III/sol.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class Solution: 4 | def longestOnes(self, nums: List[int], k: int) -> int: 5 | l, r = -1, 0 6 | ans, prev_sum = 0, 0 7 | n, count = len(nums), 0 8 | q = deque() 9 | 10 | while r <= n: 11 | if r == n or nums[r] == 0: 12 | ans = max(ans, r-l-1+prev_sum) 13 | 14 | if k > 0: 15 | prev_sum = prev_sum + r-l 16 | if count >= k: 17 | prev_sum -= q.popleft() 18 | 19 | q.append(r-l) 20 | count += 1 21 | 22 | l = r 23 | 24 | r += 1 25 | 26 | 27 | return ans -------------------------------------------------------------------------------- /medium/1584-min-cost-connect-all-points/sol.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class Solution: 4 | def minCostConnectPoints(self, points: List[List[int]]) -> int: 5 | visited = set() 6 | n = len(points) 7 | rem = n 8 | heap = [] 9 | cost = 0 10 | 11 | heapq.heappush(heap,[0,0]) 12 | 13 | while rem > 0: 14 | d,i = heapq.heappop(heap) 15 | if i in visited: 16 | continue 17 | cost += d 18 | visited.add(i) 19 | rem -= 1 20 | 21 | for j in range(n): 22 | if j not in visited: 23 | dist = abs(points[j][0]-points[i][0]) + abs(points[j][1]-points[i][1]) 24 | heapq.heappush(heap,[dist,j]) 25 | 26 | return cost -------------------------------------------------------------------------------- /easy/1422-max-score-after-splitting-string/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int maxScore(string s) { 9 | vector> pre(2, vector(s.size(),0)); 10 | int maxStringScore = 0; 11 | 12 | for(int i=0;i0 ? pre[0][i-1] : 0) + (s[i] == '0' ? 1 : 0); 15 | pre[1][backIndex] = (backIndex 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | long long pickGifts(vector& gifts, int k) { 10 | long long sum = 0, deducted = 0; 11 | int largest, remainder; 12 | priority_queue heap; 13 | 14 | for(int i=0;i int: 26 | x = self.postorder(root) 27 | if x==UNMONITORED: 28 | self.cams += 1 29 | 30 | return self.cams -------------------------------------------------------------------------------- /medium/0650-2-keys-keyboard/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int minSteps(int n) { 9 | int copy, paste; 10 | vector> dp(n+1, vector(n+1, 0)); 11 | 12 | for(int i=n-1;i>=1;i-=1) 13 | for(int c=n;c>=0;c-=1) { 14 | // copy option 15 | if(c==i) copy = INT_MAX; 16 | else copy = 1 + dp[i][i]; 17 | 18 | // paste option 19 | if(c==0 || i+c>n) paste = INT_MAX; 20 | else paste = 1 + dp[i+c][c]; 21 | 22 | dp[i][c] = min(min(copy,paste), INT_MAX-1); 23 | } 24 | 25 | return dp[1][0]; 26 | } 27 | }; -------------------------------------------------------------------------------- /medium/0983-min-ticket-cost/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mincostTickets(self, days: List[int], costs: List[int]) -> int: 3 | n = len(days) 4 | lastDay = days[n-1] 5 | j = n-1 6 | dp = [0 for _ in range(lastDay+1)] 7 | 8 | for i in range(lastDay,0,-1): 9 | # not a trip day 10 | if j < 0 or i != days[j]: 11 | dp[i] = dp[i+1] 12 | 13 | # is a trip day 14 | else: 15 | j -= 1 16 | dp[i] = min(costs[0] + (dp[i+1] if i+1 <= lastDay else 0), 17 | costs[1] + (dp[i+7] if i+7 <= lastDay else 0), 18 | costs[2] + (dp[i+30] if i+30 <= lastDay else 0) 19 | ) 20 | 21 | 22 | return dp[1] -------------------------------------------------------------------------------- /medium/1524-total-subarrays-with-odd-sum/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define MOD 1000'000'007 5 | 6 | class Solution { 7 | public: 8 | int numOfSubarrays(vector& arr) { 9 | int total = 0, s = 0, n = arr.size(); 10 | vector> pre(2,vector(n,0)); 11 | bool isOne; 12 | 13 | for(int i=0;i=0;i-=1) { 17 | isOne = pre[0][i] == 1; 18 | pre[0][i] = (i==n-1 ? 0 : pre[0][i+1]) + (isOne ? 1 : 0); 19 | pre[1][i] = (i==n-1 ? 0 : pre[1][i+1]) + (!isOne ? 1 : 0); 20 | } 21 | 22 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector getAverages(vector& nums, int k) { 8 | vector avgs(nums.size(),-1); 9 | 10 | if(k*2 > nums.size()-1) 11 | return avgs; 12 | 13 | int left = 0, right = k*2; 14 | long sum = 0; 15 | 16 | for(int i=0;i<=right;i+=1) 17 | sum += nums[i]; 18 | 19 | for(;right 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int numRabbits(vector& answers) { 8 | unordered_map counts; 9 | int rabbits = 0; 10 | 11 | for(int i=0;i 0) { 16 | counts[ans] -= 1; 17 | } 18 | 19 | // if not accounted, increase rabbits by 1 + num[i] 20 | else { 21 | counts[ans] = ans; 22 | rabbits += 1 + ans; 23 | } 24 | } 25 | 26 | return rabbits; 27 | } 28 | }; -------------------------------------------------------------------------------- /medium/0852-peak-index-in-mountain-arr/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def peakIndexInMountainArray(self, arr: List[int]) -> int: 3 | n = len(arr) 4 | low, high = 0, n-1 5 | peak = -1 6 | 7 | while low <= high: 8 | mid = low + (high-low)//2 9 | mid = max(1, min(n-2, mid)) 10 | 11 | # mid is peak 12 | if arr[mid-1] < arr[mid] and arr[mid] > arr[mid+1]: 13 | peak = mid 14 | break 15 | 16 | # mid is at increasing slope 17 | if arr[mid-1] < arr[mid] < arr[mid+1]: 18 | low = mid+1 19 | 20 | # mid is at decreasing slope 21 | if arr[mid-1] > arr[mid] > arr[mid+1]: 22 | high = mid-1 23 | 24 | 25 | return peak -------------------------------------------------------------------------------- /medium/0045-jump-game-II/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int jump(vector& nums) { 8 | vector dp(nums.size(),0); 9 | int local_min, limit; 10 | 11 | for(int i=nums.size()-2;i>=0;i-=1) { 12 | if(nums[i]==0) { 13 | dp[i] = INT_MAX; 14 | continue; 15 | } 16 | 17 | local_min = INT_MAX; 18 | limit = nums.size() < i+1+nums[i] ? nums.size() : i+1+nums[i]; 19 | for(int j=i+1;j0) { 22 | flips += compareBits(a,b,c); 23 | a >>= 1; 24 | b >>= 1; 25 | c >>= 1; 26 | maxNum >>= 1; 27 | } 28 | 29 | return flips; 30 | } 31 | }; -------------------------------------------------------------------------------- /easy/0703-kth-largest-element-in-stream/sol.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class KthLargest: 4 | 5 | def __init__(self, k: int, nums: List[int]): 6 | self.heap = nums 7 | self.extra = False if len(nums) >= k else True 8 | heapq.heapify(self.heap) 9 | if not self.extra: 10 | for _ in range(len(nums)-k): 11 | heapq.heappop(self.heap) 12 | 13 | 14 | def add(self, val: int) -> int: 15 | top = self.heap[0] if self.heap else None 16 | if (top != None and val > top) or not top: 17 | heapq.heappush(self.heap, val) 18 | if not self.extra: 19 | heapq.heappop(self.heap) 20 | else: 21 | self.extra = False 22 | top = self.heap[0] if self.heap else None 23 | 24 | return top 25 | 26 | -------------------------------------------------------------------------------- /medium/0148-sort-list/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | ListNode() : val(0), next(nullptr) {} 7 | ListNode(int x) : val(x), next(nullptr) {} 8 | ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | ListNode* sortList(ListNode* head) { 14 | if(!head) return NULL; 15 | 16 | priority_queue,greater> pq; 17 | ListNode* ptr = head; 18 | 19 | while(ptr) { 20 | pq.push(ptr->val); 21 | ptr = ptr->next; 22 | } 23 | 24 | ptr = head; 25 | while(ptr) { 26 | ptr->val = pq.top(); 27 | pq.pop(); 28 | ptr = ptr->next; 29 | } 30 | 31 | return head; 32 | } 33 | }; -------------------------------------------------------------------------------- /medium/0684-redundant-connection/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: 3 | 4 | def find(n): 5 | while dsu[n] != n: 6 | n = dsu[n] 7 | return n 8 | 9 | def update_dsu(x,y): 10 | a, b = find(x), find(y) 11 | if a < b: dsu[b] = a 12 | else: dsu[a] = b 13 | 14 | 15 | 16 | n = len(edges) 17 | dsu = [x for x in range(n+1)] 18 | ans = None 19 | 20 | for a,b in edges: 21 | orig1 = find(a) 22 | orig2 = find(b) 23 | if orig1 == orig2: 24 | ans = [a,b] 25 | break 26 | else: 27 | update_dsu(a,b) 28 | 29 | 30 | return ans 31 | -------------------------------------------------------------------------------- /medium/0055-jump-game/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool canJump(vector& nums) { 8 | vector dp(nums.size(),0); 9 | int localMin, limit; 10 | 11 | for(int i=nums.size()-2;i>=0;i-=1) { 12 | if(nums[i]==0) { 13 | dp[i] = INT_MAX; 14 | continue; 15 | } 16 | 17 | localMin = INT_MAX; 18 | limit = nums.size() < i+1+nums[i] ? nums.size() : i+1+nums[i]; 19 | 20 | for(int j=i+1;j int: 3 | rows = len(obstacleGrid) 4 | cols = len(obstacleGrid[0]) 5 | 6 | if obstacleGrid[rows-1][cols-1] == 1 or obstacleGrid[0][0] == 1: 7 | return 0 8 | 9 | obstacleGrid[rows-1][cols-1] = 1 10 | 11 | for i in range(rows-1,-1,-1): 12 | for j in range(cols-1,-1,-1): 13 | if i==rows-1 and j==cols-1: 14 | continue 15 | if obstacleGrid[i][j] == 1: 16 | obstacleGrid[i][j] = 0 17 | else: 18 | obstacleGrid[i][j] = (obstacleGrid[i+1][j] if i+1 int: 3 | ans = 0 4 | dp = [0,1] 5 | 6 | for i in range(len(s)): 7 | ans = 0 8 | digit = int(s[i]) 9 | 10 | # check validity 11 | if digit == 0 and (i == 0 or s[i-1] == '0'): 12 | break 13 | 14 | # consider digit as single decode 15 | if digit != 0: 16 | ans += dp[1] 17 | 18 | # consider digit as double decode 19 | if i > 0: 20 | if s[i-1] == '1' or (s[i-1] == '2' and 0 <= digit <= 6): 21 | ans += dp[0] 22 | 23 | # update memory / dp 24 | dp[0], dp[1] = dp[1], ans 25 | 26 | 27 | 28 | return ans -------------------------------------------------------------------------------- /medium/1922-good-numbers/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countGoodNumbers(self, n: int) -> int: 3 | 4 | # BINARY EXPONENTIATION WITH MODULO 5 | # NOT NEEDED IN PYTHON BUT GOOD TO PRACTICE 6 | def binpow(a,n,mod): 7 | res = 1 8 | while n > 0: 9 | if n&1: res = (res*a) % mod 10 | a = (a*a) % mod 11 | n >>= 1 12 | return res 13 | 14 | 15 | a,b = 0,0 16 | MOD = 10**9+7 17 | 18 | if n&1: a,b = (n+1)//2, (n-1)//2 19 | else: a,b = n//2, n//2 20 | 21 | x = binpow(5,a,MOD) 22 | y = binpow(4,b,MOD) 23 | 24 | ans = 0 25 | if x&1: ans = ((2*((x-1)//2*y)%MOD)%MOD+y)%MOD 26 | else: ans = 2*(((x//2)*y)%MOD)%MOD 27 | 28 | return ans -------------------------------------------------------------------------------- /easy/1652-defuse-bomb/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | vector decrypt(vector& code, int k) { 7 | vector ans(code.size(),0); 8 | 9 | if(k==0) 10 | return ans; 11 | 12 | int curr = 0, n = code.size(); 13 | int left = k > 0 ? 1%n : (n+k)%n; 14 | int right = k < 0 ? (n-1)%n : k%n; 15 | 16 | for(int i=left;i<=right;i+=1) 17 | curr += code[i%n]; 18 | 19 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector dailyTemperatures(vector& temperatures) { 8 | vector nextWarmDays = vector(temperatures.size(), 0); 9 | stack st; 10 | for(int i=0;ileft); 9 | bool rv = prune(ptr->right); 10 | 11 | if(!ptr->val) { 12 | if(!lv && rv) ptr->left = nullptr; 13 | else if(lv && !rv) ptr->right = nullptr; 14 | 15 | return lv | rv | false; 16 | } 17 | else { 18 | if(!lv) ptr->left = nullptr; 19 | if(!rv) ptr->right = nullptr; 20 | return true; 21 | } 22 | 23 | return false; 24 | } 25 | 26 | 27 | public: 28 | TreeNode* pruneTree(TreeNode* root) { 29 | bool hasOnes = prune(root); 30 | return !hasOnes ? nullptr : root; 31 | } 32 | }; -------------------------------------------------------------------------------- /easy/1331-rank-transform-of-array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector arrayRankTransform(vector& arr) { 9 | if(arr.size()==0) return {}; 10 | 11 | unordered_map scores; 12 | vector ranks = arr; 13 | 14 | sort(arr.begin(),arr.end()); 15 | int rank = 2; 16 | 17 | scores[arr[0]] = 1; 18 | 19 | for(int i=1;i 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int compress(vector& chars) { 7 | int left = 0, right = 0; 8 | int count = 0; 9 | 10 | for(;right<=chars.size();right+=1) { 11 | if(right==chars.size() || chars[right]!=chars[left]) { 12 | if(count > 1) { 13 | string str = to_string(count); 14 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int change(int amount, vector& coins) { 8 | int n = coins.size(); 9 | vector> dp(amount+1, vector(n+1,0)); 10 | 11 | for(int i=0;i<=amount;i+=1) { 12 | for(int j=n-1;j>=0;j-=1) { 13 | unsigned int combinations = 0; 14 | for(int k=0;k<=i/coins[j];k+=1) { 15 | int rem = i - k*coins[j]; 16 | if(rem == 0) combinations += 1; 17 | else combinations += max((unsigned int)0, dp[rem][j+1]); 18 | } 19 | dp[i][j] = combinations; 20 | } 21 | } 22 | 23 | return dp[amount][0]; 24 | } 25 | }; -------------------------------------------------------------------------------- /medium/0235-lowest-common-ancestor-of-BST/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class Solution { 4 | private: 5 | TreeNode *a, *b, *result; 6 | 7 | int traverse(TreeNode *ptr) { 8 | if(result || !ptr) return 0; 9 | 10 | int lc = traverse(ptr->left); 11 | int rc = traverse(ptr->right); 12 | int anc = 0; 13 | 14 | if(ptr==a || ptr==b) anc += 1; 15 | if(lc==1) anc += 1; 16 | if(rc==1) anc += 1; 17 | 18 | if(anc==2) { 19 | result = ptr; 20 | return 0; 21 | } 22 | 23 | return anc; 24 | } 25 | 26 | public: 27 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 28 | a = p; 29 | b = q; 30 | traverse(root); 31 | return result; 32 | } 33 | }; -------------------------------------------------------------------------------- /medium/0413-artihmetic-slices/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def total_subslices(self, n): 3 | return int(((n-1)*(n-2))/2) 4 | 5 | 6 | def numberOfArithmeticSlices(self, nums: List[int]) -> int: 7 | curr_diff, curr_len = inf, 1 8 | slices = 0 9 | 10 | for i in range(1, len(nums)): 11 | num = nums[i] 12 | diff = num - nums[i-1] 13 | 14 | if diff == curr_diff: 15 | curr_len += 1 16 | else: 17 | if curr_len >= 3: 18 | slices += self.total_subslices(curr_len) 19 | 20 | curr_diff = diff 21 | curr_len = 2 22 | 23 | 24 | # final check after loop ends 25 | if curr_len >= 3: 26 | slices += self.total_subslices(curr_len) 27 | 28 | return slices -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode Problems 2 | 3 |   4 |   5 |   6 | 7 |
8 | 9 | ## ⚖️ License 10 | 11 | This project is licensed under the MIT License - see the LICENSE file for details, 12 | 13 |
14 | 15 |

 Kushal Kumar

16 | -------------------------------------------------------------------------------- /medium/1123-lowest-common-ancestor-of-deepest-nodes/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | private: 6 | TreeNode *LCA; 7 | int maxDepth; 8 | 9 | int solveByDepth(TreeNode *ptr, int depth) { 10 | if(!ptr) return depth; 11 | int leftMaxDepth = solveByDepth(ptr->left, depth+1); 12 | int rightMaxDepth = solveByDepth(ptr->right, depth+1); 13 | if(leftMaxDepth == rightMaxDepth && leftMaxDepth >= maxDepth) { 14 | maxDepth = leftMaxDepth; 15 | LCA = ptr; 16 | } 17 | return max(leftMaxDepth, rightMaxDepth); 18 | } 19 | 20 | public: 21 | TreeNode* lcaDeepestLeaves(TreeNode* root) { 22 | LCA = nullptr; 23 | maxDepth = 0; 24 | 25 | solveByDepth(root, 0); 26 | return LCA; 27 | } 28 | }; -------------------------------------------------------------------------------- /medium/2598-smallest-missing-nonNegative-after-operations/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findSmallestInteger(self, nums: List[int], value: int) -> int: 3 | buff = [0]*value 4 | mex = None 5 | looped, i = 0, 0 6 | 7 | # slot into buffer 8 | for num in nums: 9 | i = (num+value*1000_000_000) % value 10 | buff[i] += 1 11 | 12 | i = 0 13 | 14 | while True: 15 | # find MEX 16 | if buff[i] == 0: 17 | mex = i + looped*value 18 | break 19 | 20 | else: 21 | buff[i] -= 1 22 | 23 | # increase index 24 | if i == value-1: 25 | i = 0 26 | looped += 1 27 | else: 28 | i += 1 29 | 30 | return mex -------------------------------------------------------------------------------- /easy/0104-max-depth-of-binary-tree/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | struct TreeNode { 4 | int val; 5 | TreeNode *left; 6 | TreeNode *right; 7 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | }; 11 | 12 | class Solution { 13 | private: 14 | int nodeDepth(TreeNode *ptr) { 15 | if(!ptr) return 0; 16 | if(!ptr->left && !ptr->right) return 1; 17 | if(!ptr->left) return 1 + nodeDepth(ptr->right); 18 | if(!ptr->right) return 1 + nodeDepth(ptr->left); 19 | return 1 + max(nodeDepth(ptr->left), nodeDepth(ptr->right)); 20 | } 21 | 22 | public: 23 | int maxDepth(TreeNode* root) { 24 | return nodeDepth(root); 25 | } 26 | }; -------------------------------------------------------------------------------- /medium/1749-max-abs-sum-of-subarray/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int maxAbsoluteSum(vector& nums) { 9 | int globalMax = INT_MIN, globalMin = INT_MAX; 10 | int currMax = 0, currMin = 0; 11 | 12 | for(int i=0;i 0) 23 | currMin = 0; 24 | } 25 | 26 | return max(abs(globalMax), abs(globalMin)); 27 | } 28 | }; -------------------------------------------------------------------------------- /easy/0374-guess-number-higher-or-lower/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | /** 4 | * Forward declaration of guess API. 5 | * @param num your guess 6 | * @return -1 if num is higher than the picked number 7 | * 1 if num is lower than the picked number 8 | * otherwise return 0 9 | * int guess(int num); 10 | */ 11 | 12 | class Solution { 13 | public: 14 | int guessNumber(int n) { 15 | int low = 1, high = n; 16 | int mid = low + (high-low)/2; 17 | int isCorrect = guess(mid); 18 | 19 | while(isCorrect != 0) { 20 | if(isCorrect == 1) low = mid + 1; 21 | else high = mid - 1; 22 | 23 | mid = low + (high-low)/2; 24 | isCorrect = guess(mid); 25 | } 26 | 27 | return mid; 28 | } 29 | }; -------------------------------------------------------------------------------- /medium/0503-next-greater-element-II/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector nextGreaterElements(vector& nums) { 8 | int i,j; 9 | stack st; 10 | vector ans(nums.size(),-1); 11 | 12 | for(int j=0;j<2*nums.size();j+=1) { 13 | i = j % nums.size(); 14 | if(st.empty() && j < nums.size()) 15 | st.push(i); 16 | else { 17 | while(!st.empty() && nums[st.top()] < nums[i] && ans[st.top()]==-1) { 18 | ans[st.top()] = nums[i]; 19 | st.pop(); 20 | } 21 | if(j < nums.size()) 22 | st.push(i); 23 | } 24 | } 25 | 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /easy/1603-design-parking-system/sol.cpp: -------------------------------------------------------------------------------- 1 | #define BIG 1 2 | #define MEDIUM 2 3 | #define SMALL 3 4 | using namespace std; 5 | 6 | class ParkingSystem { 7 | private: 8 | int big, medium, small; 9 | 10 | public: 11 | ParkingSystem(int big, int medium, int small) { 12 | this->big = big; 13 | this->medium = medium; 14 | this->small = small; 15 | } 16 | 17 | bool addCar(int carType) { 18 | if(carType == BIG) { 19 | if(!this->big) return false; 20 | this->big -= 1; 21 | } 22 | else if(carType == MEDIUM) { 23 | if(!this->medium) return false; 24 | this->medium -= 1; 25 | } 26 | else if(carType == SMALL) { 27 | if(!this->small) return false; 28 | this->small -= 1; 29 | } 30 | return true; 31 | } 32 | }; -------------------------------------------------------------------------------- /hard/0115-distinct-subsequences/sol.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class Solution: 4 | def numDistinct(self, s: str, t: str) -> int: 5 | m,n = len(t),len(s) 6 | if m > n: return 0 7 | 8 | dp = [[0 for _ in range(n+1)] for _ in range(m+1)] 9 | seen = defaultdict(int) 10 | 11 | for j in range(n+1): 12 | dp[0][j] = 1 13 | 14 | for i in range(1,m+1): 15 | asci = ord(t[i-1])-97 16 | freq = seen[asci] 17 | 18 | for j in range(1,n+1): 19 | dp[i][j] = dp[i][j-1] 20 | if t[i-1] == s[j-1]: 21 | if freq > 0: 22 | freq -= 1 23 | continue 24 | dp[i][j] += dp[i-1][j-1] 25 | 26 | seen[asci] += 1 27 | 28 | 29 | return dp[m][n] -------------------------------------------------------------------------------- /medium/0071-simplify-path/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | string simplifyPath(string path) { 8 | path += '/'; 9 | stack st; 10 | string curr = "", simplified = ""; 11 | 12 | for(int i=0;i List[int]: 3 | lesser, equal, higher = 0, 0, 0 4 | n = len(nums) 5 | 6 | for num in nums: 7 | if num < pivot: lesser += 1 8 | elif num == pivot: equal += 1 9 | 10 | lessStart = 0 11 | equalStart = lesser 12 | higherStart = lesser + equal 13 | 14 | ans = [0 for _ in range(n)] 15 | 16 | for num in nums: 17 | if num < pivot: 18 | ans[lessStart] = num 19 | lessStart += 1 20 | elif num == pivot: 21 | ans[equalStart] = num 22 | equalStart += 1 23 | else: 24 | ans[higherStart] = num 25 | higherStart += 1 26 | 27 | 28 | return ans -------------------------------------------------------------------------------- /medium/3217-delete-nodes-in-list/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def modifiedList(self, nums: List[int], head: Optional[ListNode]) -> Optional[ListNode]: 3 | numbers = set() 4 | for num in nums: 5 | numbers.add(num) 6 | 7 | left, right = None, head 8 | while right: 9 | # go to node not in numbers 10 | while right and right.val in numbers: 11 | right = right.next 12 | 13 | # if node = None 14 | if not right: 15 | if left: left.next = None 16 | break 17 | # if node exists 18 | else: 19 | if left: left.next = right 20 | else: head = right 21 | left = right 22 | 23 | right = right.next 24 | 25 | 26 | return head -------------------------------------------------------------------------------- /easy/0404-left-leaf-sum/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | struct TreeNode { 4 | int val; 5 | TreeNode *left; 6 | TreeNode *right; 7 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | }; 11 | 12 | class Solution { 13 | private: 14 | int leftLeafSum(TreeNode* ptr) { 15 | if(!ptr) return 0; 16 | int rightSum = leftLeafSum(ptr->right); 17 | if(ptr->left && !ptr->left->left && !ptr->left->right) 18 | return ptr->left->val + rightSum; 19 | int leftSum = leftLeafSum(ptr->left); 20 | return leftSum + rightSum; 21 | } 22 | 23 | public: 24 | int sumOfLeftLeaves(TreeNode* root) { 25 | return leftLeafSum(root); 26 | } 27 | }; -------------------------------------------------------------------------------- /medium/1404-total-steps-to-reduce-binary-to-one/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | private: 6 | char binarySum(char a, char &carry) { 7 | if(a=='1' && carry=='1') 8 | carry = '1'; 9 | if((a=='0' && carry=='0') || (a=='1' && carry=='1')) 10 | return '0'; 11 | return '1'; 12 | } 13 | 14 | public: 15 | int numSteps(string s) { 16 | int steps = s.size() - 1; 17 | char carry = '0'; 18 | for(int i=s.size()-1;i>=0;i-=1) { 19 | if(s[i]=='0' && carry=='0') 20 | continue; 21 | s[i] = binarySum(s[i],carry); 22 | if((s[i]=='1' && i!=0) || (i==0 && carry=='1')) { 23 | steps += 1; 24 | carry = '1'; 25 | } 26 | } 27 | 28 | return steps; 29 | } 30 | }; -------------------------------------------------------------------------------- /medium/2684-max-no-of-moves-in-matrix/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxMoves(vector>& grid) { 8 | int maxMove = 0; 9 | vector> dp(grid.size(),vector(2,0)); 10 | int k = 0; 11 | 12 | for(int j=grid[0].size()-2;j>=0;j-=1) { 13 | for(int i=0;i 0 && grid[i][j] < grid[i-1][j+1]) ? 1 + dp[i-1][k^1] : 0, max((grid[i][j] < grid[i][j+1]) ? 1 + dp[i][k^1] : 0, (i < grid.size()-1 && grid[i][j] < grid[i+1][j+1]) ? 1 + dp[i+1][k^1] : 0)); 15 | 16 | if(j==0) 17 | maxMove = max(maxMove, dp[i][k]); 18 | } 19 | 20 | k ^= 1; 21 | } 22 | 23 | return maxMove; 24 | } 25 | }; -------------------------------------------------------------------------------- /medium/3075-maximize-happiness-of-selected-children/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | private: 7 | struct Compare { 8 | bool operator()(const int a, const int b) const { 9 | return a > b; 10 | } 11 | }; 12 | 13 | public: 14 | long long maximumHappinessSum(vector& happiness, int k) { 15 | Compare compare; 16 | sort(happiness.begin(), happiness.end(), compare); 17 | 18 | long long maxHappiness = 0; 19 | int temp; 20 | 21 | for(int i=0; i happiness[i]) temp = 0; 23 | else temp = happiness[i] - i; 24 | 25 | maxHappiness += temp; 26 | } 27 | 28 | return maxHappiness; 29 | } 30 | }; -------------------------------------------------------------------------------- /medium/3542-min-op-all-arr-elem-to-zero/sol.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def minOperations(self, nums: List[int]) -> int: 5 | st = [] 6 | ans = 0 7 | 8 | for num in nums: 9 | # fresh start 10 | if num == 0: 11 | st = [] 12 | else: 13 | # new number so ans + 1 14 | if not st or num > st[-1]: 15 | ans += 1 16 | st.append(num) 17 | 18 | # pop and check stack 19 | elif num < st[-1]: 20 | while st and st[-1] > num: 21 | st.pop() 22 | if not st or st[-1] < num: 23 | ans += 1 24 | st.append(num) 25 | 26 | 27 | return ans -------------------------------------------------------------------------------- /easy/1790-check-one-swap-makes-string-equal/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool areAlmostEqual(string s1, string s2) { 7 | bool hasPaired = false, swtch = false; 8 | char a, b; 9 | 10 | for(int i=0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector findRepeatedDnaSequences(string s) { 9 | if(s.size() <= 10) 10 | return {}; 11 | 12 | vector ans; 13 | unordered_map seq; 14 | string curr = s.substr(0,10); 15 | 16 | seq[curr] = 1; 17 | 18 | for(int i=10;i 2 | using namespace std; 3 | 4 | class MyQueue { 5 | private: 6 | stack s1,s2; 7 | 8 | public: 9 | MyQueue() { 10 | } 11 | 12 | void push(int x) { 13 | while(!s1.empty()) { 14 | s2.push(s1.top()); 15 | s1.pop(); 16 | } 17 | 18 | s1.push(x); 19 | 20 | while(!s2.empty()) { 21 | s1.push(s2.top()); 22 | s2.pop(); 23 | } 24 | } 25 | 26 | int pop() { 27 | if(!s1.empty()) { 28 | int val = s1.top(); 29 | s1.pop(); 30 | return val; 31 | } 32 | return -1; 33 | } 34 | 35 | int peek() { 36 | if(!s1.empty()) 37 | return s1.top(); 38 | return -1; 39 | } 40 | 41 | bool empty() { 42 | return s1.empty(); 43 | } 44 | }; -------------------------------------------------------------------------------- /medium/1590-make-sum-divisible-by-P/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int minSubarray(vector& nums, int p) { 9 | int k = 0; 10 | for(int i=0;i mod; 17 | mod[0] = -1; 18 | 19 | for(int i=0;i int: 14 | node = self.Node(t) 15 | if not self.rear: 16 | self.front = self.rear = node 17 | else: 18 | self.rear.next = node 19 | self.rear = node 20 | 21 | self.pings += 1 22 | 23 | # trim from left if needed 24 | lower_limit = t - 3000 25 | ptr = self.front 26 | while ptr.val < lower_limit: 27 | temp = ptr 28 | ptr = ptr.next 29 | self.pings -= 1 30 | del temp 31 | 32 | self.front = ptr 33 | return self.pings 34 | -------------------------------------------------------------------------------- /medium/0075-sort-colors/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortColors(self, nums: List[int]) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | LOWEST, MIDVAL, HIGHEST = 0, 1, 2 7 | low, mid, high = 0, 0, len(nums)-1 8 | 9 | # iterate till mid > high: 10 | while mid <= high: 11 | 12 | # if mid = 0 then swap with low and increment low 13 | if nums[mid] == LOWEST: 14 | nums[low], nums[mid] = nums[mid], nums[low] 15 | low += 1 16 | mid += 1 17 | 18 | # if mid = 1 then increment 19 | elif nums[mid] == MIDVAL: 20 | mid += 1 21 | 22 | # if mid = 2 then swap with high and decrement high 23 | else: 24 | nums[mid], nums[high] = nums[high], nums[mid] 25 | high -= 1 -------------------------------------------------------------------------------- /medium/1899-merge-target-from-target-triplet/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: 3 | 4 | x,y,z = target 5 | target_num_found = [False for _ in range(3)] 6 | xorAll = 7 # 111 in binary 7 | 8 | for a,b,c in triplets: 9 | if a>x or b>y or c>z: 10 | continue 11 | if a==x and not target_num_found[0]: 12 | target_num_found[0] = True 13 | xorAll ^= 4 14 | if b==y and not target_num_found[1]: 15 | target_num_found[1] = True 16 | xorAll ^= 2 17 | if c==z and not target_num_found[2]: 18 | target_num_found[2] = True 19 | xorAll ^= 1 20 | if xorAll == 0: 21 | break 22 | 23 | 24 | return True if xorAll == 0 else False -------------------------------------------------------------------------------- /medium/2761-prime-pairs-with-target-sum/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | vector> findPrimePairs(int n) { 7 | if(n<=1) 8 | return {}; 9 | 10 | // use sieve of erasto-- to pre-compute [1,n] 11 | vector isPrime(n, true); 12 | isPrime[0] = isPrime[1] = false; // for readability of index i == actual number 13 | 14 | for(int i=2;i> primePairs; 23 | for(int i=2;i<=n/2;i+=1) 24 | if(isPrime[i] && isPrime[n-i]) 25 | primePairs.push_back({ i, n-i }); 26 | 27 | return primePairs; 28 | } 29 | }; -------------------------------------------------------------------------------- /easy/0226-invert-binary-tree/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | struct TreeNode { 4 | int val; 5 | TreeNode *left; 6 | TreeNode *right; 7 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | }; 11 | 12 | class Solution { 13 | private: 14 | TreeNode *traverse(TreeNode *ptr) { 15 | if (!ptr) 16 | return nullptr; 17 | traverse(ptr->left); 18 | traverse(ptr->right); 19 | 20 | if (ptr->left || ptr->right) { 21 | TreeNode *temp = ptr->right; 22 | ptr->right = ptr->left; 23 | ptr->left = temp; 24 | } 25 | 26 | return ptr; 27 | } 28 | 29 | public: 30 | TreeNode *invertTree(TreeNode *root) { 31 | return traverse(root); 32 | } 33 | }; -------------------------------------------------------------------------------- /medium/1578-min-time-rope-colorful/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCost(self, colors: str, neededTime: List[int]) -> int: 3 | l, r, n = 0, 1, len(colors) 4 | cost = 0 5 | 6 | while r < n: 7 | # keep traversing till consecutive colors are same 8 | localSum = neededTime[l] 9 | localMax = neededTime[l] 10 | while r < n and colors[r] == colors[l]: 11 | localSum += neededTime[r] 12 | localMax = max(neededTime[r], localMax) 13 | r += 1 14 | 15 | # only one balloon of same color in consecutive group 16 | if l == r or (r == n and l == n-1): 17 | continue 18 | 19 | # update cost and omit max time one 20 | cost += localSum - localMax 21 | l = r 22 | r += 1 23 | 24 | 25 | return cost 26 | -------------------------------------------------------------------------------- /medium/2140-solving-questions-with-brainpower/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | long long mostPoints(vector>& questions) { 8 | int n = questions.size(); 9 | long long maxPoints = 0; 10 | vector dp(n,0); 11 | 12 | // solve using dp from back to front 13 | for(int i=n-1;i>=0;i-=1) { 14 | int jumpedIndex = min(n,questions[i][1]+i+1); // find next jump index 15 | long long maxPossiblePointsAtJump = jumpedIndex == n ? 0 : dp[jumpedIndex]; // compute points max points earned 16 | dp[i] = max(maxPoints, (long long)(questions[i][0] + maxPossiblePointsAtJump)); // update to cost 17 | 18 | // update max count 19 | maxPoints = max(maxPoints, dp[i]); 20 | } 21 | 22 | return maxPoints; 23 | } 24 | }; -------------------------------------------------------------------------------- /medium/0986-interval-list-intersections/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | vector> intervalIntersection(vector>& a, vector>& b) { 7 | vector> intersections = {}; 8 | int i = 0, j = 0; 9 | 10 | while(i < a.size() && j < b.size()) { 11 | if(a[i][1] < b[j][0]) i += 1; 12 | else if(a[i][0] > b[j][1]) j += 1; 13 | else { 14 | intersections.push_back({ max(a[i][0], b[j][0]), min(a[i][1], b[j][1]) }); 15 | 16 | if(b[j][1] > a[i][1]) i += 1; 17 | else if(b[j][1] < a[i][1]) j += 1; 18 | else { 19 | i += 1; 20 | j += 1; 21 | } 22 | } 23 | } 24 | 25 | return intersections; 26 | } 27 | }; -------------------------------------------------------------------------------- /medium/1003-check-word-valid-after-substitution/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | #define A false 6 | #define AB true 7 | 8 | class Solution { 9 | public: 10 | bool isValid(string s) { 11 | stack st; 12 | 13 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int findTheLongestSubstring(string s) { 8 | vector cases(32,-2); 9 | cases[0] = -1; 10 | int longest = 0, 11 | prevSimilar = 0, 12 | mask = 0; 13 | 14 | for(int i=0;i 2 | using namespace std; 3 | 4 | class PeekingIterator : public Iterator { 5 | private: 6 | vector arr; 7 | int curr, n; 8 | 9 | public: 10 | PeekingIterator(const vector& nums) : Iterator(nums) { 11 | // Initialize any member here. 12 | // **DO NOT** save a copy of nums and manipulate it directly. 13 | // You should only use the Iterator interface methods. 14 | arr = nums; 15 | curr = 0; 16 | n = nums.size(); 17 | } 18 | 19 | // Returns the next element in the iteration without advancing the iterator. 20 | int peek() { 21 | return arr[curr]; 22 | } 23 | 24 | // hasNext() and next() should behave the same as in the Iterator interface. 25 | // Override them if needed. 26 | int next() { 27 | curr += 1; 28 | return arr[curr-1]; 29 | } 30 | 31 | bool hasNext() const { 32 | return curr < n; 33 | } 34 | }; -------------------------------------------------------------------------------- /medium/1930-unique-3-len-palindromic-subsequences/sol.py: -------------------------------------------------------------------------------- 1 | from linecache import cache 2 | 3 | class Solution: 4 | def countPalindromicSubsequence(self, s: str) -> int: 5 | @cache 6 | def asci(ch): return ord(ch)-97 7 | 8 | INF = float('inf') 9 | ranges = [[INF,INF] for _ in range(26)] 10 | dp = [[0 for _ in range(26)] for _ in range(26)] 11 | ans = 0 12 | 13 | for i in range(len(s)): 14 | j = asci(s[i]) 15 | if ranges[j][0] == INF: ranges[j][0] = i 16 | else: ranges[j][1] = i 17 | 18 | for i in range(len(s)): 19 | c = asci(s[i]) 20 | for j in range(26): 21 | if ranges[j][0] == INF: continue 22 | if ranges[j][1] != INF and dp[j][c] == 0 and ranges[j][0] < i < ranges[j][1]: 23 | dp[j][c] = 1 24 | ans += 1 25 | 26 | return ans -------------------------------------------------------------------------------- /medium/0092-reverse-LL-II/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: 3 | if left == right: 4 | return head 5 | 6 | k = right - left + 1 7 | ptr = head 8 | 9 | for _ in range(left-2): 10 | ptr = ptr.next 11 | 12 | leftTail = None 13 | if left > 1: 14 | leftTail = ptr 15 | ptr = ptr.next 16 | 17 | prev = None 18 | rev = ptr 19 | for i in range(k): 20 | temp = ptr.next 21 | ptr.next = prev 22 | prev = ptr 23 | ptr = temp 24 | if left == 1 and i == k-1: 25 | head = prev 26 | 27 | rightTail = ptr 28 | if leftTail: 29 | leftTail.next = prev 30 | if rightTail: 31 | rev.next = rightTail 32 | 33 | return head -------------------------------------------------------------------------------- /easy/2696-min-string-length-after-removing-substrings/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int minLength(string s) { 8 | stack> st; 9 | string reduced = ""; 10 | 11 | for (int i = 0; i < s.size();i+=1) { 12 | if(s[i]=='B' || s[i]=='D') { 13 | if(!st.empty() && ((st.top().first=='A' && s[i]=='B') || (st.top().first=='C' && s[i]=='D'))) { 14 | s[st.top().second] = '#'; 15 | s[i] = '#'; 16 | st.pop(); 17 | } 18 | else 19 | st.push({s[i], i}); 20 | } 21 | else 22 | st.push({s[i], i}); 23 | } 24 | 25 | for (int i = 0; i < s.size();i+=1) 26 | if(s[i]!='#') 27 | reduced += s[i]; 28 | 29 | return reduced.size(); 30 | } 31 | }; -------------------------------------------------------------------------------- /medium/0129-sum-root-to-leaf-nodes/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | struct TreeNode { 4 | int val; 5 | TreeNode *left; 6 | TreeNode *right; 7 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | }; 11 | 12 | 13 | class Solution { 14 | private: 15 | int total = 0; 16 | void recursiveSum(TreeNode* ptr, int sum) { 17 | if(!ptr) 18 | return; 19 | 20 | sum = sum*10 + ptr->val; 21 | 22 | if(!ptr->left && !ptr->right) { 23 | total += sum; 24 | return; 25 | } 26 | 27 | recursiveSum(ptr->left, sum); 28 | recursiveSum(ptr->right, sum); 29 | } 30 | 31 | public: 32 | int sumNumbers(TreeNode* root) { 33 | recursiveSum(root,0); 34 | return total; 35 | } 36 | }; -------------------------------------------------------------------------------- /medium/0056-merge-intervals/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector> merge(vector>& intervals) { 8 | if(intervals.size() < 2) 9 | return intervals; 10 | 11 | sort(intervals.begin(),intervals.end()); 12 | 13 | vector> merged; 14 | int low = 0, high = 0; 15 | 16 | for(int ptr=1;ptr intervals[high][1]) 18 | high = ptr; 19 | else if(intervals[ptr][0] > intervals[high][1]) { 20 | merged.push_back({ intervals[low][0], intervals[high][1] }); 21 | low = ptr; 22 | high = ptr; 23 | } 24 | } 25 | 26 | merged.push_back({ intervals[low][0], intervals[high][1] }); 27 | return merged; 28 | } 29 | }; -------------------------------------------------------------------------------- /medium/0508-most-frequent-subtree-sum/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | private: 8 | unordered_map counts; 9 | vector nums; 10 | int maxSum; 11 | 12 | int nodeSum(TreeNode *ptr) { 13 | if(!ptr) return 0; 14 | int sum = ptr->val + nodeSum(ptr->left) + nodeSum(ptr->right); 15 | 16 | if(counts.count(sum)) counts[sum] += 1; 17 | else counts[sum] = 1; 18 | 19 | if(counts[sum] == maxSum) 20 | nums.push_back(sum); 21 | else if(counts[sum] > maxSum) { 22 | nums = { sum }; 23 | maxSum = counts[sum]; 24 | } 25 | 26 | return sum; 27 | } 28 | 29 | public: 30 | vector findFrequentTreeSum(TreeNode* root) { 31 | maxSum = INT_MIN; 32 | nodeSum(root); 33 | return nums; 34 | } 35 | }; -------------------------------------------------------------------------------- /medium/1721-swapping-nodes-in-LL/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | ListNode() : val(0), next(nullptr) {} 7 | ListNode(int x) : val(x), next(nullptr) {} 8 | ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | }; 10 | 11 | 12 | class Solution { 13 | public: 14 | ListNode* swapNodes(ListNode* head, int k) { 15 | ListNode *left = head, *right = head; 16 | ListNode *record; 17 | 18 | for( ; k>1; k-=1) 19 | right = right->next; 20 | 21 | record = right; 22 | 23 | while(right->next) { 24 | right = right->next; 25 | left = left->next; 26 | } 27 | 28 | if(left->val != record->val) { 29 | left->val ^= record->val; 30 | record->val ^= left->val; 31 | left->val ^= record->val; 32 | } 33 | 34 | return head; 35 | } 36 | }; -------------------------------------------------------------------------------- /medium/1904-full-rounds-played/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def timeRound(self, t:int, ceil:bool) -> int: 3 | rem = t % 15 4 | if rem == 0: return t 5 | if ceil: return t+(15-rem) if t+(15-rem) < 24*60 else 0 6 | return t-rem 7 | 8 | 9 | def numberOfRounds(self, loginTime: str, logoutTime: str) -> int: 10 | inArr = loginTime.split(":") 11 | outArr = logoutTime.split(":") 12 | 13 | hIn, mIn = int(inArr[0]), int(inArr[1]) 14 | hOut, mOut = int(outArr[0]), int(outArr[1]) 15 | 16 | inTime = self.timeRound(hIn*60 + mIn, True) 17 | outTime = self.timeRound(hOut*60 + mOut, False) 18 | 19 | rounds = 0 20 | 21 | if not 0 < (hOut*60 + mOut - hIn*60 - mIn) < 15: 22 | if inTime <= outTime: 23 | rounds = (outTime - inTime) // 15 24 | else: 25 | rounds = (24*60 - (inTime - outTime)) // 15 26 | 27 | 28 | return rounds -------------------------------------------------------------------------------- /medium/2419-longest-subarray-with-max-bitwise-AND/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int longestSubarray(vector& nums) { 7 | int maxNum = nums[0]; 8 | int local_count = 1, 9 | global_count = 1; 10 | 11 | for(int i=1; i maxNum) { 13 | maxNum = nums[i]; 14 | local_count = 1; 15 | global_count = 1; 16 | continue; 17 | } 18 | else if(nums[i] == maxNum) { 19 | if(nums[i-1] == maxNum) { 20 | local_count += 1; 21 | global_count = max(global_count, local_count); 22 | } 23 | else { 24 | local_count = 1; 25 | } 26 | } 27 | } 28 | 29 | return global_count; 30 | } 31 | }; -------------------------------------------------------------------------------- /easy/0257-binary-tree-paths/sol.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class Solution: 4 | 5 | def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: 6 | stack = [] 7 | queue = deque() 8 | queue.append((root, "")) 9 | DELIMITER = '->' 10 | 11 | result = [] 12 | 13 | # DFS method to traverse paths ------- 14 | while queue or stack: 15 | if not queue: 16 | queue.append(stack.pop()) 17 | 18 | ptr, curr = queue.popleft() 19 | curr += str(ptr.val) 20 | 21 | if ptr.left or ptr.right: 22 | if ptr.left and ptr.right: 23 | stack.append((ptr.right, curr+DELIMITER)) 24 | 25 | node = ptr.left if ptr.left else ptr.right 26 | queue.append((node, curr+DELIMITER)) 27 | 28 | else: 29 | result.append(curr) 30 | 31 | 32 | return result -------------------------------------------------------------------------------- /medium/0763-partition-labels/sol.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class Solution: 4 | def partitionLabels(self, s: str) -> List[int]: 5 | index = [-1 for _ in range(26)] 6 | n = len(s) 7 | maxSize = defaultdict(int) 8 | ans = [] 9 | 10 | for i in range(n): 11 | ch = s[i] 12 | asci = ord(ch)-97 13 | if index[asci] == -1: 14 | index[asci] = i 15 | maxSize[i] = i 16 | else: 17 | for j in range(26): 18 | if index[j] != index[asci] and index[asci] < index[j] < i: 19 | index[j] = index[asci] 20 | maxSize[index[asci]] = i 21 | 22 | 23 | for ch in s: 24 | asci = ord(ch)-97 25 | i = index[asci] 26 | if maxSize[i] == -1: continue 27 | ans.append(maxSize[i] - i + 1) 28 | maxSize[i] = -1 29 | 30 | 31 | return ans -------------------------------------------------------------------------------- /medium/2559-count-vowel-range-in-string/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | private: 7 | int hasEdgeVowels(string str) { 8 | char vowels[5] = {'a','e','i','o','u'}; 9 | bool l = false, r = false; 10 | for(int i=0;i<5;i+=1) { 11 | l |= str[0]==vowels[i]; 12 | r |= str[str.size()-1]==vowels[i]; 13 | } 14 | return l&r ? 1 : 0; 15 | } 16 | 17 | public: 18 | vector vowelStrings(vector& words, vector>& queries) { 19 | vector pre(words.size(),0), ans(queries.size(),0); 20 | 21 | for(int i=0;i0?pre[i-1]:0)+hasEdgeVowels(words[i]); 23 | 24 | for(int i=0;i= 0 ? pre[queries[i][0]-1] : 0); 26 | 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /medium/2807-insert-gcd-in-LL/sol.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | 7 | ListNode() : val(0), next(nullptr) {} 8 | ListNode(int x) : val(x), next(nullptr) {} 9 | ListNode(int x, ListNode *next) : val(x), next(next) {} 10 | }; 11 | 12 | class Solution { 13 | private: 14 | int gcd(int a, int b) { 15 | if(a==0) return b; 16 | if(b==0) return a; 17 | if(a > b) return gcd(a%b,b); 18 | return gcd(a,b%a); 19 | } 20 | 21 | public: 22 | ListNode* insertGreatestCommonDivisors(ListNode* head) { 23 | ListNode *front = head, *back = head; 24 | while(front->next) { 25 | front = front->next; 26 | int gcd_val = gcd(front->val,back->val); 27 | ListNode* temp = new ListNode(gcd_val, front); 28 | back->next = temp; 29 | back = back->next->next; 30 | } 31 | 32 | return head; 33 | } 34 | }; -------------------------------------------------------------------------------- /medium/3160-distinct-ball-colors/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector queryResults(int limit, vector>& queries) { 8 | int distinct = 0; 9 | unordered_map colors, balls; 10 | vector ans(queries.size(), 0); 11 | 12 | for(int i=0;i int: 5 | count = defaultdict(list) 6 | ans = 0 7 | z = 0 8 | MOD = pow(10,9) + 7 9 | 10 | for num in nums: 11 | if num == 0: 12 | z += 1 13 | else: 14 | # count 'j' after 'i' seen 15 | if num in count: 16 | count[num][-1] = (count[num][-1] + 1) % MOD 17 | 18 | # mark 'i' and 'k' 19 | if not num&1: 20 | count[num//2].append(0) 21 | 22 | 23 | for v in count.values(): 24 | n = len(v) 25 | if n > 1: 26 | for i in range(n-1): 27 | ans = (ans + v[i]*(n-i-1)*(i+1)) % MOD 28 | 29 | if z > 2: 30 | ans = (ans + (z*(z-1)*(z-2) // 6) % MOD) % MOD 31 | 32 | return ans --------------------------------------------------------------------------------