├── Array ├── CheckIfAll1sAreAtLeastLengthKPlacesAway.cpp ├── CountSquareSubmatricesWithAllOnes.cpp ├── DesignHashMap.cpp ├── DesignHashSet.cpp ├── FinalPricesWithSpecialDiscountInAShop.cpp ├── FindAllDuplicatesInAnArray.cpp ├── FindTheDuplicateNumber.cpp ├── LeastNumberOfUniqueIntegersAfterKRemovals.cpp ├── MaxConsecutiveOnes.cpp ├── MaximumSumCircularSubarray.cpp ├── MedianOfTwoSortedArrays.cpp ├── NextGreaterElementI.cpp ├── NextGreaterElementII.cpp ├── NextGreaterElementIII.cpp ├── ProductOfArrayExceptSelf.cpp ├── ReduceArraySizeToTheHalf.cpp ├── SortArrayByParityI.cpp ├── SortArrayByParityII.cpp ├── SubarrayProductLessThank.cpp ├── SubrectangleQueries.cpp ├── TheKStrongestValuesInAnArray.cpp └── ValidMountainArray.cpp ├── BinarySearch ├── FindFirstAndLastPositionOfElementInSortedArray.cpp ├── FindMinimumInRotatedSortedArray.cpp ├── FindPeakElement.cpp ├── FindSmallestLetterGreaterThanTarget.cpp ├── H-IndexII.cpp ├── MinimumNumberOfDaysToMakeMBouquets.cpp ├── PeakIndexInAMountainArray.cpp └── SumOfMutatedArrayClosestToTarget.cpp ├── DFS ├── NumberOfEnclaves.cpp ├── NumberOfIslands.cpp └── SurroundedRegions.cpp ├── DP ├── CoinChange.cpp ├── CoinChange2.cpp ├── CountingBits.cpp ├── DeleteAndEarn.cpp ├── DungeonGame-Memoization.cpp ├── DungeonGame-Tabulation.cpp ├── HouseRobber.cpp ├── LargestDivisibleSubset.cpp ├── LongestIncreasingSubsequence.cpp ├── LongestStringChain.cpp ├── LongestTurbulentSubarray.cpp ├── MaximumProductSubarray.cpp ├── UncrossedLines.cpp ├── UniquePaths.cpp └── edit_distance.cpp ├── LICENSE.md ├── LinkedList ├── AddTwoNumbers.cpp ├── AddTwoNumbersII.cpp ├── DesignLinkedList.cpp ├── LinkedListCycleI.cpp ├── LinkedListCycleII.cpp ├── MergeTwoSortedLists.cpp ├── MiddleOfTheLinkedList.cpp ├── NextGreaterNodeInLinkedList.cpp ├── OddEvenLinkedList.cpp ├── RemoveDuplicatesFromSortedListII.cpp ├── RemoveNthNodeFromEndOfList.cpp ├── ReverseLinkedList.cpp ├── ReverseLinkedListII.cpp ├── RotateList.cpp └── SwapNodeInPairs.cpp ├── README.md ├── SlidingWindow ├── FruitIntoBaskets.cpp ├── GrumpyBookstoreOwner.cpp ├── LongestContinuousSubarrayWithAbsoluteDiffLessThanOrEqualToLimit.cpp ├── MaxConsecutiveOnesIII.cpp ├── NumberOfSubstringsContainingAllThreeCharacters.cpp └── ReplaceTheSubstringForBalancedString.cpp ├── Stack ├── DesignAStackWithIncrementOperation.cpp ├── ImplementQueueUsingStacks.cpp ├── LRUCache.cpp └── MinStack.cpp ├── Strings ├── CheckIfAStringCanBreakAnotherString.cpp ├── ImplementstrStr-KMP.cpp ├── ImplementstrStr-Rabin-Karp.cpp ├── MakingFileNamesUnique.cpp ├── RepeatedStringMatch.cpp └── RepeatedSubstringPattern.cpp ├── Tree ├── BalancedBinaryTree.cpp ├── BinaryTreeZigzagLevelOrderTraversal.cpp ├── ConstructBinarySearchTreeFromPreorderTraversal.cpp ├── ConstructBinaryTreeFromPreorderAndPostorderTraversal.cpp ├── CountCompleteTreeNodes.cpp ├── CountGoodNodesInBinaryTree.cpp ├── CousinsInBinaryTree.cpp ├── DiameterOfBinaryTree.cpp ├── IncreasingOrderSearchTree.cpp ├── InvertBinaryTree.cpp ├── KthSmallestElementInABST.cpp ├── MaximumDepthOfBinaryTree.cpp ├── MaximumDepthOfN-AryTree.cpp ├── MergeTwoBinaryTree.cpp ├── MinimumAbsoluteDifferenceInBST.cpp ├── MinimumDistanceBetweenBSTNodes.cpp ├── N-AryTreeLevelOrderTraversal.cpp ├── RangeSumOfBST.cpp ├── SearchInABinarySearchTree.cpp ├── SumRootToLeafNumbers.cpp └── UniqueBinarySearchTrees.cpp ├── Trie ├── AddAndSearchWord-DataStructureDesign.cpp ├── ImplementTrie-PrefixTree.cpp ├── ReplaceWords.cpp └── WordSearchII.cpp ├── UnionFind ├── FriendCircles.cpp ├── NumberOfOperationsToMakeNetworkConnected.cpp ├── RedundantConnection.cpp └── SatisfiabilityOfEqualityEquations.cpp └── _config.yml /Array/CheckIfAll1sAreAtLeastLengthKPlacesAway.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool kLengthApart(vector& nums, int k) { 4 | vector ones; 5 | int pre = -10101; 6 | for(int i = 0; i < nums.size(); i++) { 7 | if(nums[i]) { 8 | if(i - pre <= k) 9 | return 0; 10 | pre = i; 11 | } 12 | } 13 | return 1; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Array/CountSquareSubmatricesWithAllOnes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countSquares(vector>& matrix) { 4 | int res = 0; 5 | for(int i = 0; i < matrix.size(); i++) { 6 | for(int j = 0; j < matrix[0].size(); j++) { 7 | if(matrix[i][j] && i && j) { 8 | matrix[i][j] += min({matrix[i-1][j], matrix[i-1][j-1], matrix[i][j-1]}); 9 | } 10 | res += matrix[i][j]; 11 | } 12 | } 13 | return res; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Array/DesignHashMap.cpp: -------------------------------------------------------------------------------- 1 | class MyHashMap { 2 | vector>> data; 3 | int size = 10000; 4 | public: 5 | /** Initialize your data structure here. */ 6 | MyHashMap() { 7 | data.resize(size); 8 | } 9 | 10 | /** value will always be non-negative. */ 11 | void put(int key, int value) { 12 | auto & list = data[key % size]; 13 | for(auto &val: list) { 14 | if(val.first == key) { 15 | val.second = value; 16 | return; 17 | } 18 | } 19 | list.push_back({key, value}); 20 | } 21 | 22 | /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ 23 | int get(int key) { 24 | auto &list = data[key % size]; 25 | if(list.empty()) 26 | return -1; 27 | for(auto &val: list) { 28 | if(val.first == key) 29 | return val.second; 30 | } 31 | return -1; 32 | } 33 | 34 | /** Removes the mapping of the specified value key if this map contains a mapping for the key */ 35 | void remove(int key) { 36 | auto &list = data[key % size]; 37 | for(auto val: list) { 38 | if(val.first == key) { 39 | list.remove(val); 40 | return; 41 | } 42 | } 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Array/DesignHashSet.cpp: -------------------------------------------------------------------------------- 1 | class MyHashSet { 2 | public: 3 | /** Initialize your data structure here. */ 4 | vector v; 5 | MyHashSet() { 6 | } 7 | 8 | void add(int key) { 9 | if(v.empty()) 10 | v.push_back(key); 11 | for(int i = 0; i < v.size(); i++) { 12 | if(v[i] == key) { 13 | v[i] = key; 14 | return; 15 | } 16 | } 17 | v.push_back(key); 18 | } 19 | 20 | void remove(int key) { 21 | if(v.empty()) 22 | return; 23 | for(int i = 0; i < v.size(); i++) { 24 | if(v[i] == key) { 25 | v.erase(v.begin() + i); 26 | return; 27 | } 28 | } 29 | } 30 | 31 | /** Returns true if this set contains the specified element */ 32 | bool contains(int key) { 33 | if(v.empty()) 34 | return false; 35 | for(int i = 0; i < v.size(); i++) 36 | if(v[i] == key) 37 | return true; 38 | return false; 39 | } 40 | }; 41 | 42 | -------------------------------------------------------------------------------- /Array/FinalPricesWithSpecialDiscountInAShop.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector finalPrices(vector& prices) { 4 | vector res(prices); 5 | stack s; 6 | for(int i = 0; i < prices.size(); i++) { 7 | while(s.size() && prices[s.top()] >= prices[i]) { 8 | res[s.top()] -= prices[i]; 9 | s.pop(); 10 | } 11 | s.push(i); 12 | } 13 | return res; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Array/FindAllDuplicatesInAnArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findDuplicates(vector& nums) { 4 | vector res; 5 | for(int i = 0; i < nums.size(); i++) { 6 | nums[abs(nums[i]) - 1] = -nums[abs(nums[i]) - 1]; 7 | if(nums[abs(nums[i])-1] > 0) res.push_back(abs(nums[i])); 8 | } 9 | return res; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Array/FindTheDuplicateNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | int tortoise = nums[0]; 5 | int hare = nums[0]; 6 | do { 7 | tortoise = nums[tortoise]; 8 | hare = nums[nums[hare]]; 9 | }while(tortoise != hare); 10 | tortoise = nums[0]; 11 | while(tortoise != hare) { 12 | tortoise = nums[tortoise]; 13 | hare = nums[hare]; 14 | } 15 | return hare; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Array/LeastNumberOfUniqueIntegersAfterKRemovals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int findLeastNumOfUniqueInts(vector& arr, int k) { 5 | unordered_map mp; 6 | for(int i = 0; i < arr.size(); i++) { 7 | mp[arr[i]]++; 8 | } 9 | vector> values(mp.begin(),mp.end()); 10 | auto cmp = [](const pair& l, pair& r) { return l.second < r.second;}; 11 | sort(values.begin(),values.end(),cmp); 12 | int count = 0; 13 | for(auto it = values.begin(); it != values.end(); it++) { 14 | while(k > 0 && it->second > 0) { 15 | it->second--; 16 | k--; 17 | } 18 | 19 | if(it->second <= 0) 20 | count++; 21 | 22 | if(k <= 0) 23 | break; 24 | } 25 | return mp.size() - count; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Array/MaxConsecutiveOnes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxConsecutiveOnes(vector& arr) { 4 | int count = 0, res = 0; 5 | for(int i = 0; i < arr.size(); i++) { 6 | if(arr[i] == 1) 7 | count++; 8 | else { 9 | res = max(count, res); 10 | count = 0; 11 | } 12 | } 13 | res = max(res, count); 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Array/MaximumSumCircularSubarray.cpp: -------------------------------------------------------------------------------- 1 | int kadane(vector A, int i, int j, int sign) { 2 | int currsum = INT_MIN, best = INT_MIN; 3 | for(int k = i; k <= j; ++k) { 4 | currsum = sign * A[k] + max(currsum , 0); 5 | best = max(best, currsum); 6 | } 7 | return best; 8 | } 9 | 10 | class Solution { 11 | public: 12 | int maxSubarraySumCircular(vector& A) { 13 | if(A.size() == 1) 14 | return A[0]; 15 | int sum = 0; 16 | for(int x: A) 17 | sum += x; 18 | int ans = kadane(A, 0, A.size()-1, 1); 19 | int ans1 = sum + kadane(A, 1, A.size()-1, -1); 20 | int ans2 = sum + kadane(A, 0, A.size()-2, -1); 21 | return max({ans, ans1, ans2}); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Array/MedianOfTwoSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 4 | int i = 0, j = 0, n = nums1.size(), m = nums2.size(); 5 | vector arr; 6 | while(i < n && j < m) { 7 | if(nums1[i] > nums2[j]) 8 | arr.push_back(nums2[j++]); 9 | else 10 | arr.push_back(nums1[i++]); 11 | } 12 | while(i < n) 13 | arr.push_back(nums1[i++]); 14 | while(j < m) 15 | arr.push_back(nums2[j++]); 16 | int len = n + m; 17 | if(len % 2 == 0) { 18 | int mid = len / 2; 19 | return (double)(arr[mid] + arr[mid - 1]) / 2; 20 | } 21 | int mid = len / 2; 22 | return arr[mid]; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Array/NextGreaterElementI.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextGreaterElement(vector& nums1, vector& nums2) { 4 | unordered_map mp; 5 | stack s; 6 | for(int n: nums2) { 7 | while(s.size() && s.top() < n) { 8 | mp[s.top()] = n; 9 | s.pop(); 10 | } 11 | s.push(n); 12 | } 13 | vector res(nums1.size(), - 1); 14 | for(int i = 0; i < nums1.size(); i++) { 15 | auto itr = mp.find(nums1[i]); 16 | if(itr != mp.end()) 17 | res[i] = mp[nums1[i]]; 18 | } 19 | return res; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Array/NextGreaterElementII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextGreaterElements(vector& nums) { 4 | stack s; 5 | int n = nums.size(); 6 | vector res(n, -1); 7 | for(int i = 0; i < n * 2; i++) { 8 | while(s.size() && nums[s.top()] < nums[i % n]) { 9 | res[s.top()] = nums[i % n]; 10 | s.pop(); 11 | } 12 | s.push(i % n); 13 | } 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Array/NextGreaterElementIII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nextGreaterElement(int n) { 4 | string s = to_string(n); 5 | next_permutation(begin(s), end(s)); 6 | auto res = stoll(s); 7 | return (res > INT_MAX || res <= n) ? -1 : res; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Array/ProductOfArrayExceptSelf.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector productExceptSelf(vector& nums) { 4 | int pref_mul = 1, n = nums.size(), suf_mul = 1; 5 | vector pref; 6 | for(int i = 0; i < n; i++) { 7 | pref.push_back(pref_mul); 8 | pref_mul *= nums[i]; 9 | } 10 | for(int i = n-1; i >= 0; i--) { 11 | pref[i] *= suf_mul; 12 | suf_mul *= nums[i]; 13 | } 14 | return pref; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Array/ReduceArraySizeToTheHalf.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSetSize(vector& arr) { 4 | //int freq[100000] = {0}; 5 | unordered_map mp; 6 | int n = arr.size(); 7 | int mid = n / 2; 8 | for(int i = 0; i < n; i++) { 9 | //freq[arr[i]]++; 10 | mp[arr[i]]++; 11 | } 12 | vector v; 13 | for(auto x: mp) { 14 | v.push_back(x.second); 15 | } 16 | sort(v.begin(), v.end()); 17 | int currSize = 0, idx = 0, count = 0; 18 | if(v.size() == 1) 19 | return 1; 20 | for(int i = v.size() - 1; i >= 0; i--) { 21 | currSize += v[i]; 22 | if(currSize >= mid) { 23 | count = v.size() - i; 24 | break; 25 | } 26 | } 27 | return count; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Array/SortArrayByParityI.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortArrayByParity(vector& A) { 4 | vector even, odd; 5 | for(int i = 0; i < A.size(); i++) { 6 | if(A[i]%2 == 0) 7 | even.push_back(A[i]); 8 | else 9 | odd.push_back(A[i]); 10 | } 11 | vector res = even; 12 | for(int i = 0; i < odd.size(); i++) 13 | res.push_back(odd[i]); 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Array/SortArrayByParityII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortArrayByParityII(vector& A) { 4 | vector res(A.size()); 5 | int even=0, odd=1; 6 | for(int i=0; i& nums, int k) { 4 | if(k <= 1) return 0; 5 | int prod = 1; 6 | int ans = 0, left = 0, right = 0; 7 | for(int i = 0; i < nums.size(); i++) { 8 | prod *= nums[i]; 9 | while(prod >= k) { 10 | prod /= nums[left]; 11 | left += 1; 12 | } 13 | ans += right - left + 1; 14 | right++; 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Array/SubrectangleQueries.cpp: -------------------------------------------------------------------------------- 1 | class SubrectangleQueries { 2 | public: 3 | vector> rect; 4 | SubrectangleQueries(vector>& rectangle) { 5 | rect = rectangle; 6 | } 7 | 8 | void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) { 9 | for(int i = row1; i <= row2; i++) { 10 | for(int j = col1; j <= col2; j++) { 11 | rect[i][j] = newValue; 12 | } 13 | } 14 | } 15 | 16 | int getValue(int row, int col) { 17 | return rect[row][col]; 18 | } 19 | }; 20 | 21 | -------------------------------------------------------------------------------- /Array/TheKStrongestValuesInAnArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getStrongest(vector& arr, int k) { 4 | if(arr.size() == 1) 5 | return arr; 6 | sort(arr.begin(), arr.end()); 7 | vector res; 8 | int n = arr.size(); 9 | int median = arr[(n - 1) / 2]; 10 | int i = 0, j = n - 1; 11 | while(i <= j && res.size() < k) { 12 | if(abs(arr[i] - median) > abs(arr[j] - median)) { 13 | res.push_back(arr[i]); 14 | i++; 15 | } 16 | else if(abs(arr[i] - median) == abs(arr[j] - median)) { 17 | if(arr[i] > arr[j]) { 18 | res.push_back(arr[i]); 19 | i++; 20 | } 21 | else { 22 | res.push_back(arr[j]); 23 | j--; 24 | } 25 | } 26 | else { 27 | res.push_back(arr[j]); 28 | j--; 29 | } 30 | } 31 | return res; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Array/ValidMountainArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validMountainArray(vector& A) { 4 | if(A.size() <= 2) 5 | return false; 6 | int i = 0; 7 | int n = A.size(); 8 | while(i + 1 < n && A[i] < A[i + 1]) 9 | i++; 10 | int j = n - 1; 11 | while(j > 0 && A[j - 1] > A[j]) 12 | j--; 13 | return i > 0 && i == j && j < n - 1; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /BinarySearch/FindFirstAndLastPositionOfElementInSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | int low = 0, high = nums.size() - 1; 5 | vector res(2, -1); 6 | if(nums.size() == 0) 7 | return res; 8 | while(low < high) { 9 | int mid = (low + high) / 2; 10 | if(nums[mid] < target) 11 | low = mid + 1; 12 | else 13 | high = mid; 14 | } 15 | if(nums[low] != target) return res; 16 | else res[0] = low; 17 | high = nums.size() - 1; 18 | while(low < high) { 19 | int mid = (low + high) / 2 + 1; 20 | if(nums[mid] > target) 21 | high = mid - 1; 22 | else 23 | low = mid; 24 | } 25 | res[1] = high; 26 | return res; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /BinarySearch/FindMinimumInRotatedSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int low = 0, high = nums.size() - 1; 5 | while(low < high) { 6 | if(nums[low] < nums[high]) 7 | return nums[low]; 8 | int mid = (low + high) / 2; 9 | if(nums[mid] >= nums[low]) 10 | low = mid + 1; 11 | else 12 | high = mid; 13 | } 14 | return nums[low]; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /BinarySearch/FindPeakElement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findPeakElement(vector& nums) { 4 | int low = 0, high = nums.size() - 1; 5 | while(low < high) { 6 | int mid = (low + high) >> 1; 7 | if(nums[mid] > nums[mid + 1]) 8 | high = mid; 9 | else 10 | low = mid + 1; 11 | } 12 | return low; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /BinarySearch/FindSmallestLetterGreaterThanTarget.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char nextGreatestLetter(vector& letters, char target) { 4 | int low = 0, high = letters.size() - 1; 5 | if(letters[low] > target || letters[high] <= target) 6 | return letters[low]; 7 | while(low <= high) { 8 | int mid = low + (high - low) / 2; 9 | if(letters[mid] == target) { 10 | if(letters[mid + 1] > target) 11 | return letters[mid + 1]; 12 | else 13 | low = mid + 1; 14 | } 15 | else if(letters[mid] < target) 16 | low = mid + 1; 17 | else 18 | high = mid - 1; 19 | } 20 | return letters[low]; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /BinarySearch/H-IndexII.cpp: -------------------------------------------------------------------------------- 1 | //Binary Search 2 | class Solution { 3 | public: 4 | int hIndex(vector& citations) { 5 | int n = citations.size(); 6 | int low = 0, high = n - 1; 7 | while(low <= high) { 8 | int mid = (low + high) >> 1; 9 | if(citations[mid] == n - mid) 10 | return citations[mid]; 11 | else if(citations[mid] > (n - mid)) 12 | high = mid - 1; 13 | else 14 | low = mid + 1; 15 | } 16 | return n - low; 17 | } 18 | }; 19 | 20 | //Counting Sort 21 | class Solution { 22 | public: 23 | int hIndex(vector& citations) { 24 | int n = citations.size(); 25 | vector count(n + 1, 0); 26 | for(int i = 0; i < n; i++) { 27 | if(citations[i] >= n) 28 | count[n]++; 29 | else 30 | count[citations[i]]++; 31 | } 32 | int h_index = 0; 33 | for(int i = n; i >= 0; i--) { 34 | h_index += count[i]; 35 | if(h_index >= i) 36 | return i; 37 | } 38 | return 0; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /BinarySearch/MinimumNumberOfDaysToMakeMBouquets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool check(vector& v, int m, int k, int mid) { 4 | int c = 0, tot = 0; 5 | for(int i = 0; i < v.size(); i++) { 6 | if(v[i] <= mid) { 7 | c++; 8 | if(c == k) { 9 | tot++; 10 | c = 0; 11 | } 12 | } 13 | else 14 | c = 0; 15 | } 16 | if(tot >= m) return true; 17 | return false; 18 | } 19 | 20 | int minDays(vector& bloomDay, int m, int k) { 21 | int ans = -1; 22 | int low = 0, high = INT_MAX - 1; 23 | while(low <= high) { 24 | int mid = low + (high - low) / 2; 25 | if(check(bloomDay, m, k, mid)) { 26 | ans = mid; 27 | high = mid - 1; 28 | } 29 | else 30 | low = mid + 1; 31 | } 32 | return ans; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /BinarySearch/PeakIndexInAMountainArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int peakIndexInMountainArray(vector& A) { 4 | int low = 0, high = A.size() - 1; 5 | while(low <= high) { 6 | int mid = low + (high - low) / 2; 7 | if((A[mid] > A[mid - 1] && A[mid] > A[mid + 1])) 8 | return mid; 9 | else if(A[mid] < A[mid + 1]) 10 | low = mid + 1; 11 | else 12 | high = mid - 1; 13 | } 14 | return low; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /BinarySearch/SumOfMutatedArrayClosestToTarget.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int check(int mid, vector arr, int target) { 4 | int sum = 0; 5 | for(int i = 0; i < arr.size(); i++) 6 | sum += min(arr[i], mid); 7 | return abs(sum - target); 8 | } 9 | 10 | int findBestValue(vector& arr, int target) { 11 | int low = 0, high = arr.size() - 1; 12 | while(low < high) { 13 | int mid = (low + high) >> 1; 14 | if(check(mid, arr, target) <= check(mid + 1, arr, target)) 15 | high = mid; 16 | else 17 | low = mid + 1; 18 | } 19 | return arr[low]; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /DFS/NumberOfEnclaves.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Flood Fill from boundary and then sum up remaining ones 4 | void dfs(vector>& A, int i, int j) { 5 | if(i < 0 || j < 0 || i == A.size() || j == A[i].size() || A[i][j] == 0) 6 | return; 7 | A[i][j] = 0; 8 | dfs(A, i + 1, j); 9 | dfs(A, i - 1, j); 10 | dfs(A, i, j + 1); 11 | dfs(A, i, j - 1); 12 | } 13 | 14 | int numEnclaves(vector>& A) { 15 | for(int i = 0; i < A.size(); i++) 16 | for(int j = 0; j < A[0].size(); j++) 17 | if(i * j == 0 || i == A.size() - 1 || j == A[i].size() - 1) 18 | dfs(A, i, j); 19 | 20 | return accumulate(begin(A), end(A), 0, [](int s, vector &r){ 21 | return s + accumulate(begin(r), end(r), 0); 22 | }); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /DFS/NumberOfIslands.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numIslands(vector>& grid) { 4 | int n = grid.size(); 5 | int m = n ? grid[0].size() : 0; 6 | int islands = 0; 7 | for(int i = 0; i < n; i++) { 8 | for(int j = 0; j < m; j++) { 9 | if(grid[i][j] == '1') { 10 | islands++; 11 | dfs(grid, i, j, n, m); 12 | } 13 | } 14 | } 15 | return islands; 16 | } 17 | 18 | void dfs(vector>& grid, int i, int j, int n, int m) { 19 | if(i < 0 || i == n || j < 0 || j == m || grid[i][j] == '0') 20 | return; 21 | grid[i][j] = '0'; 22 | dfs(grid, i-1, j, n, m); 23 | dfs(grid, i+1, j, n, m); 24 | dfs(grid, i, j-1, n, m); 25 | dfs(grid, i, j+1, n, m); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /DFS/SurroundedRegions.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void solve(vector>& board) { 4 | if (board.empty()) return; 5 | int row = board.size(), col = board[0].size(); 6 | for (int i = 0; i < row; ++i) { 7 | check(board, i, 0); // first column 8 | check(board, i, col - 1); // last column 9 | } 10 | for (int j = 1; j < col - 1; ++j) { 11 | check(board, 0, j); // first row 12 | check(board, row - 1, j); // last row 13 | } 14 | for (int i = 0; i < row; ++i) 15 | for (int j = 0; j < col; ++j) 16 | if (board[i][j] == 'O') board[i][j] = 'X'; 17 | else if (board[i][j] == '1') board[i][j] = 'O'; 18 | } 19 | 20 | void check(vector>& board, int i, int j) { 21 | if (board[i][j] == 'O') { 22 | board[i][j] = '1'; 23 | if (i > 1) check(board, i - 1, j); 24 | if (j > 1) check(board, i, j - 1); 25 | if (i + 1 < board.size()) check(board, i + 1, j); 26 | if (j + 1 < board[0].size()) check(board, i, j + 1); 27 | } 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /DP/CoinChange.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int coinChange(vector& coins, int amount) { 4 | int max_size = amount + 1; 5 | vector dp(max_size + 1, max_size); 6 | dp[0] = 0; 7 | int n = coins.size(); 8 | for (int n = 1; n <= amount; n++) { 9 | for (int i = 0; i < coins.size(); i++) { 10 | if (n - coins[i] >= 0) { 11 | int subprob = dp[n - coins[i]]; 12 | dp[n] = min(dp[n], subprob + 1); 13 | } 14 | } 15 | } 16 | return dp[amount] > amount ? - 1 : dp[amount]; 17 | } 18 | }; -------------------------------------------------------------------------------- /DP/CoinChange2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int change(int amount, vector& coins) { 4 | ios::sync_with_stdio(false); 5 | cin.tie(0); 6 | cout.tie(0); 7 | int dp[coins.size() + 1][amount + 1]; 8 | memset(dp, 0, sizeof(dp)); 9 | dp[0][0] = 1; 10 | for(int j = 1; j <= coins.size(); j++) { 11 | dp[j][0] = 1; 12 | for(int i = 1; i <= amount; i++) { 13 | dp[j][i] = dp[j - 1][i]; 14 | if(i - coins[j - 1] >= 0) 15 | dp[j][i] += dp[j][i - coins[j - 1]]; 16 | } 17 | } 18 | return dp[coins.size()][amount]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /DP/CountingBits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector countBits(int num) { 4 | vector dp(num+1); 5 | dp[0] = 0; 6 | for(int i = 1; i <= num; i++ ) { 7 | if(i % 2 == 0) 8 | dp[i] = dp[i/2]; 9 | else 10 | dp[i] = dp[i-1]+1; 11 | } 12 | return dp; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /DP/DeleteAndEarn.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int deleteAndEarn(vector& nums) { 4 | int buckets[10001] = {0}; 5 | for (int num : nums) 6 | buckets[num] += num; 7 | int dp[10001] = {0}; 8 | dp[0] = buckets[0]; 9 | dp[1] = buckets[1]; 10 | for (int i = 2; i < 10001; i++) 11 | dp[i] = max(buckets[i] + dp[i - 2], dp[i - 1]); 12 | return dp[10000]; 13 | } 14 | }; -------------------------------------------------------------------------------- /DP/DungeonGame-Memoization.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int solve(vector>& arr, vector>& dp, int i, int j, int n, int m) { 4 | if(i == n - 1 && j == m - 1) 5 | return arr[i][j] > 0 ? 1 : abs(arr[i][j]) + 1; 6 | 7 | if(dp[i][j] != - 1) 8 | return dp[i][j]; 9 | 10 | if(i == n - 1 || j == m - 1) { 11 | return i == n - 1 ? max(1, solve(arr, dp, i, j + 1, n, m) - arr[i][j]) : 12 | max(1, solve(arr, dp, i + 1, j, n, m) - arr[i][j]); 13 | } 14 | 15 | return dp[i][j] = max(1, min(solve(arr, dp, i + 1, j, n, m) - arr[i][j], solve(arr, dp, i, j + 1, n, m) - arr[i][j])); 16 | } 17 | 18 | int calculateMinimumHP(vector>& arr) { 19 | int n = arr.size(); 20 | int m = arr[0].size(); 21 | vector> dp(n, vector(m, -1)); 22 | return solve(arr, dp, 0, 0, n, m); 23 | } 24 | 25 | }; 26 | 27 | 28 | -------------------------------------------------------------------------------- /DP/DungeonGame-Tabulation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int calculateMinimumHP(vector>& arr) { 4 | int n = arr.size(); 5 | int m = arr[0].size(); 6 | vector> dp(n+1, vector(m+1, INT_MAX)); 7 | dp[n - 1][m] = 1; 8 | dp[n][m - 1] = 1; 9 | for(int i = n - 1; i >= 0; i--) 10 | for(int j = m - 1; j >= 0; j--) 11 | dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - arr[i][j]); 12 | return dp[0][0]; 13 | } 14 | 15 | }; 16 | -------------------------------------------------------------------------------- /DP/HouseRobber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | int n = nums.size(); 5 | if (n == 0) 6 | return 0; 7 | if (n == 1) 8 | return nums[0]; 9 | int dp[401] = {0}; 10 | dp[0] = nums[0]; 11 | dp[1] = max(nums[1], dp[0]); 12 | for (int i = 2; i < n; i++) { 13 | dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]); 14 | } 15 | return dp[n - 1]; 16 | } 17 | }; -------------------------------------------------------------------------------- /DP/LargestDivisibleSubset.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector largestDivisibleSubset(vector& nums) { 4 | if(nums.size() == 0) 5 | return vector(); 6 | 7 | if(nums.size() == 1) { 8 | vectorres; 9 | res.push_back(nums[0]); 10 | return res; 11 | } 12 | 13 | sort(nums.begin(), nums.end()); 14 | vector dp(nums.size()), parent(nums.size(), -1); 15 | int largest = 0, largestIndex = 0; 16 | dp[0] = 1; 17 | for(int i = 1; i < dp.size(); i++) { 18 | dp[i] = 1; 19 | for(int j = i - 1; j >= 0; j--) { 20 | if(nums[i] % nums[j] == 0 && dp[i] < dp[j] + 1) { 21 | dp[i] = dp[j] + 1; 22 | parent[i] = j; 23 | } 24 | } 25 | if(dp[i] > largest) { 26 | largest = dp[i]; 27 | largestIndex = i; 28 | } 29 | } 30 | vector res; 31 | for(int i = 0; i < largest; i++) { 32 | res.insert(res.begin(), nums[largestIndex]); 33 | largestIndex = parent[largestIndex]; 34 | } 35 | return res; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /DP/LongestIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLIS(vector& nums) { 4 | int n = nums.size(); 5 | vector dp(n, 1); 6 | for (int i = 0; i < n; i++) { 7 | for (int j = 0; j < i; j++) { 8 | if (nums[i] > nums[j]) 9 | dp[i] = max(dp[i], dp[j] + 1); 10 | } 11 | } 12 | int max_count = 0; 13 | for (int i = 0; i < n; i++) 14 | max_count = max(dp[i], max_count); 15 | return max_count; 16 | } 17 | }; -------------------------------------------------------------------------------- /DP/LongestStringChain.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static bool compare(const string &s1, const string &s2) { 4 | return s1.length() < s2.length(); 5 | } 6 | int longestStrChain(vector& words) { 7 | int n = words.size(); 8 | sort(words.begin(), words.end(), compare); 9 | unordered_map dp; 10 | int res = 0; 11 | for (string s : words) { 12 | for (int i = 0; i < s.length(); i++) 13 | dp[s] = max(dp[s], dp[s.substr(0, i) + s.substr(i + 1)] + 1); 14 | res = max(dp[s], res); 15 | } 16 | return res; 17 | } 18 | }; -------------------------------------------------------------------------------- /DP/LongestTurbulentSubarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxTurbulenceSize(vector& A) { 4 | vector> dp(A.size(), vector(2, 1)); 5 | int res = 1; 6 | for(int i = 1; i < A.size(); i++) { 7 | if(A[i] > A[i - 1]) 8 | dp[i][0] = dp[i - 1][1] + 1; 9 | else if(A[i] < A[i - 1]) 10 | dp[i][1] = dp[i - 1][0] + 1; 11 | res = max({res, dp[i][0], dp[i][1]}); 12 | } 13 | return res; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /DP/MaximumProductSubarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& nums) { 4 | int frontProduct = 1, backProduct = 1; 5 | int ans = INT_MIN, n = nums.size(); 6 | for (int i = 0; i < n; i++) { 7 | frontProduct *= nums[i]; 8 | backProduct *= nums[n - i - 1]; 9 | ans = max(max(frontProduct, backProduct), ans); 10 | frontProduct = frontProduct == 0 ? 1 : frontProduct; 11 | backProduct = backProduct == 0 ? 1 : backProduct; 12 | } 13 | return ans; 14 | } 15 | }; -------------------------------------------------------------------------------- /DP/UncrossedLines.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxUncrossedLines(vector& A, vector& B) { 4 | int n = A.size(), m = B.size(), dp[n+1][m+1]; 5 | memset(dp, 0, sizeof(dp)); 6 | for(int i = 1; i <= n; i++) 7 | for(int j = 1; j <= m; j++) 8 | dp[i][j] = A[i - 1] == B[j - 1] ? dp[i - 1][j - 1] + 1: max(dp[i][j - 1], dp[i - 1][j]); 9 | return dp[n][m]; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /DP/UniquePaths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | vector> dp(m, vector(n, 1)); 5 | for(int i = 1; i < m; i++) { 6 | for(int j = 1; j < n; j++) { 7 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 8 | } 9 | } 10 | return dp[m - 1][n - 1]; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /DP/edit_distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int t[1000][1000]; 5 | 6 | int get(string s1,string s2,int x,int y){ 7 | if(x==0 && y==0)return 0; 8 | if(t[x][y]!=-1)return t[x][y]; 9 | if(x==0 && y>0)return t[x][y]=y; 10 | if(x>0 && y==0)return t[x][y]=x; 11 | if(s1[x]==s2[y]){ 12 | return t[x][y]=get(s1,s2,x-1,y-1); 13 | }else{ 14 | return t[x][y]=1+min(get(s1,s2,x-1,y-1),min(get(s1,s2,x-1,y),get(s1,s2,x,y-1))); 15 | } 16 | } 17 | 18 | int minDistance(string s1, string s2) { 19 | s1='!'+s1; 20 | s2='!'+s2; 21 | int n=s1.size(); 22 | int m=s2.size(); 23 | for(int i=0;ival : 0) + (l2 ? l2->val : 0); 9 | t->next = new ListNode(c % 10); 10 | t = t->next; 11 | c /= 10; 12 | if(l1) l1 = l1->next; 13 | if(l2) l2 = l2->next; 14 | } 15 | t->next = NULL; 16 | return head.next; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /LinkedList/AddTwoNumbersII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 4 | vector nums1, nums2; 5 | while(l1) { 6 | nums1.push_back(l1->val); 7 | l1 = l1->next; 8 | } 9 | 10 | while(l2) { 11 | nums2.push_back(l2->val); 12 | l2 = l2->next; 13 | } 14 | 15 | int i = nums1.size() - 1, j = nums2.size() - 1, carry = 0, sum = 0; 16 | ListNode *head = NULL, *ptr = NULL; 17 | while(i >= 0 || j >= 0 || carry > 0) { 18 | sum = carry; 19 | if(i >= 0) 20 | sum += nums1[i]; 21 | 22 | if(j >= 0) 23 | sum += nums2[j]; 24 | 25 | carry = sum / 10; 26 | ptr = new ListNode(sum % 10); 27 | ptr->next = head; 28 | head = ptr; 29 | i--, j--; 30 | } 31 | return head; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /LinkedList/DesignLinkedList.cpp: -------------------------------------------------------------------------------- 1 | class MyLinkedList { 2 | private: 3 | struct node{ 4 | int val; 5 | node *next; 6 | }; 7 | node *head; 8 | node *tail; 9 | int size; 10 | public: 11 | MyLinkedList() { 12 | head = NULL; 13 | tail = NULL; 14 | size = 0; 15 | } 16 | int get(int index) { 17 | if(index >= size|| index < 0) 18 | return -1; 19 | node *cur = new node; 20 | cur = head; 21 | for(int i = 0;inext; 23 | } 24 | 25 | return cur->val; 26 | 27 | } 28 | void addAtHead(int val) { 29 | node *temp = new node(); 30 | temp->val = val; 31 | temp->next = head; 32 | head = temp; 33 | if(size==0) tail = temp; 34 | ++size; 35 | } 36 | void addAtTail(int val) { 37 | node *temp = new node(); 38 | temp->val = val; 39 | if(size==0) { 40 | tail = temp; 41 | head = temp; 42 | } 43 | tail->next = temp; 44 | tail = temp; 45 | ++size; 46 | } 47 | void addAtIndex(int index, int val) { 48 | if(index>size || index < 0) return; 49 | else if(index == 0) { 50 | addAtHead(val); 51 | return; 52 | } 53 | else if(index == size) { 54 | addAtTail(val); 55 | return; 56 | } 57 | node *cur = new node(); 58 | cur = head; 59 | for(int i = 0;inext; 61 | } 62 | node *temp = new node(); 63 | temp->val = val; 64 | temp->next = cur->next; 65 | cur->next = temp; 66 | ++size; 67 | } 68 | void deleteAtIndex(int index) { 69 | if(index>=size || index < 0) return; 70 | else if(index == 0){ 71 | head = head->next; 72 | --size; 73 | return; 74 | } 75 | node *cur = new node(); 76 | cur = head; 77 | for(int i = 0;inext; 79 | } 80 | cur->next= cur->next->next; 81 | if(index == size-1) tail = cur; 82 | --size; 83 | } 84 | }; 85 | 86 | -------------------------------------------------------------------------------- /LinkedList/LinkedListCycleI.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasCycle(ListNode *head) { 4 | ListNode *tortoise = head, *hare = head; 5 | if(head == NULL || head->next == NULL) 6 | return false; 7 | int flag = 0; 8 | while(tortoise && hare) { 9 | tortoise = tortoise->next; 10 | if(hare->next == NULL) return NULL; 11 | hare = hare->next->next; 12 | if(tortoise == hare) { 13 | flag = 1; 14 | break; 15 | } 16 | } 17 | if(flag == 0) 18 | return false; 19 | tortoise = head; 20 | while(tortoise != hare) { 21 | tortoise = tortoise->next; 22 | hare = hare->next; 23 | } 24 | return hare; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LinkedList/LinkedListCycleII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode *detectCycle(ListNode *head) { 4 | ListNode *tortoise = head; 5 | ListNode *hare = head; 6 | if(head == NULL || head->next == NULL) 7 | return NULL; 8 | int flag = 0; 9 | while(tortoise && hare) { 10 | tortoise = tortoise->next; 11 | if(hare->next == NULL) return NULL; 12 | hare = hare->next->next; 13 | if(tortoise == hare) { 14 | flag = 1; 15 | break; 16 | } 17 | } 18 | if(flag == 0) 19 | return NULL; 20 | tortoise = head; 21 | while(tortoise != hare) { 22 | tortoise = tortoise->next; 23 | hare = hare->next; 24 | } 25 | return hare; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /LinkedList/MergeTwoSortedLists.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 4 | if(l1 == NULL) 5 | return l2; 6 | if(l2 == NULL) 7 | return l1; 8 | ListNode *head = NULL, *tail = NULL; 9 | while(l1 != NULL && l2 != NULL) { 10 | ListNode *ptr; 11 | if(l1->val <= l2->val) { 12 | ptr = new ListNode(l1->val); 13 | if(head == NULL) { 14 | head = ptr; 15 | tail = ptr; 16 | } else { 17 | tail->next = ptr; 18 | tail = ptr; 19 | } 20 | l1 = l1->next; 21 | } 22 | else { 23 | ptr = new ListNode(l2->val); 24 | if(head == NULL) { 25 | head = ptr; 26 | tail = ptr; 27 | } else { 28 | tail->next = ptr; 29 | tail = ptr; 30 | } 31 | l2 = l2->next; 32 | } 33 | } 34 | ListNode *rem; 35 | while(l1) { 36 | rem = new ListNode(l1->val); 37 | tail->next = rem; 38 | tail = rem; 39 | l1 = l1->next; 40 | } 41 | while(l2) { 42 | rem = new ListNode(l2->val); 43 | tail->next = rem; 44 | tail = rem; 45 | l2 = l2->next; 46 | } 47 | return head; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /LinkedList/MiddleOfTheLinkedList.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* middleNode(ListNode* head) { 4 | ListNode *slow = head, *fast = head; 5 | while(fast!=NULL && fast->next!=NULL) { 6 | fast = fast->next->next; 7 | slow = slow->next; 8 | } 9 | return slow; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /LinkedList/NextGreaterNodeInLinkedList.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextLargerNodes(ListNode* head) { 4 | vector nums; 5 | ListNode *ptr = head; 6 | while(ptr) { 7 | nums.push_back(ptr->val); 8 | ptr = ptr->next; 9 | } 10 | vector res(nums.size(), 0); 11 | stack s; 12 | for(int i = 0; i < nums.size(); i++) { 13 | while(s.size() && nums[s.top()] < nums[i]) { 14 | res[s.top()] = nums[i]; 15 | s.pop(); 16 | } 17 | s.push(i); 18 | } 19 | return res; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LinkedList/OddEvenLinkedList.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* oddEvenList(ListNode* head) { 4 | if(head == NULL) 5 | return NULL; 6 | ios::sync_with_stdio(false); 7 | cin.tie(0), cout.tie(0); 8 | ListNode *one = head; 9 | ListNode *two = head->next; 10 | ListNode *dummy = head->next; 11 | while(one && two && one->next && two->next){ 12 | one->next = one->next->next; 13 | one = one->next; 14 | two->next = two->next->next; 15 | two = two->next; 16 | } 17 | one->next = dummy; 18 | return head; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LinkedList/RemoveDuplicatesFromSortedListII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* deleteDuplicates(ListNode* head) { 4 | ListNode *dummy = new ListNode(0); 5 | ListNode *tail = dummy; 6 | int flag = 0; 7 | while(head) { 8 | while(head && head->next && head->val == head->next->val) { 9 | flag = 1; 10 | head = head->next; 11 | } 12 | if(flag == 0) { 13 | tail->next = head; 14 | tail = head; 15 | } 16 | head = head->next; 17 | flag = 0; 18 | } 19 | tail->next = NULL; 20 | return dummy->next; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /LinkedList/RemoveNthNodeFromEndOfList.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* removeNthFromEnd(ListNode* head, int n) { 4 | ListNode *slow = head, *fast = head; 5 | 6 | while(n-- > 0) 7 | fast = fast->next; 8 | 9 | if(fast == NULL) return head->next; 10 | 11 | while(fast->next != NULL) { 12 | slow = slow->next; 13 | fast = fast->next; 14 | } 15 | slow->next = slow->next->next; 16 | return head; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /LinkedList/ReverseLinkedList.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* reverseList(ListNode* head) { 4 | if(head == NULL || head->next == NULL) return head; 5 | ListNode *p = reverseList(head->next); 6 | head->next->next = head; 7 | head->next = NULL; 8 | return p; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /LinkedList/ReverseLinkedListII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* reverseBetween(ListNode* head, int m, int n) { 4 | ListNode dummy = ListNode(0), *pre = &dummy, *curr; 5 | dummy.next = head; 6 | for(int i = 0; i < m - 1; i++) 7 | pre = pre->next; 8 | curr = pre->next; 9 | for(int i = 0; i < n - m; i++) { 10 | ListNode *temp = pre->next; 11 | pre->next = curr->next; 12 | curr->next = curr->next->next; 13 | pre->next->next = temp; 14 | } 15 | return dummy.next; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /LinkedList/RotateList.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* rotateRight(ListNode* head, int k) { 4 | if(!head) 5 | return head; 6 | int len = 1; 7 | ListNode *ptr = head; 8 | while(ptr->next) { 9 | len++; 10 | ptr = ptr->next; 11 | } 12 | ptr->next = head; 13 | int index = len - k % len; 14 | for(int i = 0; i < index; i++) 15 | ptr = ptr->next; 16 | head = ptr->next; 17 | ptr->next = NULL; 18 | return head; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LinkedList/SwapNodeInPairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* swapPairs(ListNode* head) { 4 | if(head == NULL || head->next == NULL) 5 | return head; 6 | ListNode *temp = head->next; 7 | head->next = swapPairs(head->next->next); 8 | temp->next = head; 9 | return temp; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [LeetCode Solutions](https://leetcode.com/problemset/all/) 2 | 3 | 4 | ![Language](https://img.shields.io/badge/Language-C%2B%2B-important)  5 | ![Programs](https://img.shields.io/badge/Programs-106-blueviolet)  6 | ![Update](https://img.shields.io/badge/Update-Daily-brightgreen)  7 | [![License](https://img.shields.io/badge/License-MIT-informational)](./LICENSE.md) 

8 | ![Easy](https://img.shields.io/badge/Easy-33-success)  9 | ![Medium](https://img.shields.io/badge/Medium-69-orange)  10 | ![Hard](https://img.shields.io/badge/Hard-4-red) 11 | 12 | ## Array 13 | | # | Title | Solution | Difficulty | 14 | |-----|---------------- | --------------- |------------- | 15 | 0442 | [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [View](./Array/FindAllDuplicatesInAnArray.cpp) | Medium ||| 16 | 1437 | [Check If All 1's Are at Least Length K Places Away](https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/) | [View](./Array/CheckIfAll1sAreAtLeastLengthKPlacesAway.cpp) | Medium ||| 17 | 0706 | [Design Hash Map](https://leetcode.com/problems/design-hashmap/) | [View](./Array/DesignHashMap.cpp) | Easy ||| 18 | 0705 | [Design Hash Set](https://leetcode.com/problems/design-hashset/) | [View](./Array/DesignHashSet.cpp) | Easy ||| 19 | 1475 | [Final Prices With a Special Discount in a Shop](https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/) | [View](./Array/FinalPricesWithSpecialDiscountInAShop.cpp) | Easy ||| 20 | 1277 | [Count Square Submatrices with All Ones](https://leetcode.com/problems/count-square-submatrices-with-all-ones/) | [View](./Array/CountSquareSubmatricesWithAllOnes.cpp) | Medium ||| 21 | 1475 | [Final Prices With a Special Discount in a Shop](https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/) | [View](./Array/FinalPricesWithSpecialDiscountInAShop.cpp) | Easy ||| 22 | 0287 | [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) | [View](./Array/FindTheDuplicateNumber.cpp) | Medium ||| 23 | 1481 | [Least Number of Unique Integers after K Removals](https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/) | [View](./Array/LeastNumberOfUniqueIntegersAfterKRemovals.cpp) | Medium 24 | ||| 25 | 0485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) | [View](./Array/MaxConsecutiveOnes.cpp) | Easy ||| 26 | 0004 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [View](./Array/MedianOfTwoSortedArrays.cpp) | Hard ||| 27 | 0918 | [Maximum Sum Circular Subarray](https://leetcode.com/problems/maximum-sum-circular-subarray/) | [View](./Array/MaximumSumCircularSubarray.cpp) | Medium ||| 28 | 0496 | [Next Greater Element I](https://leetcode.com/problems/next-greater-element-i/) | [View](./Array/NextGreaterElementI.cpp) | Easy ||| 29 | 0503 | [Next Greater Element II](https://leetcode.com/problems/next-greater-element-ii/) | [View](./Array/NextGreaterElementII.cpp) | Medium ||| 30 | 0556 | [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) | [View](./Array/NextGreaterElementIII.cpp) | Medium ||| 31 | 0238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [View](./Array/ProductOfArrayExceptSelf.cpp) | Medium ||| 32 | 1338 | [Reduce Array Size to The Half](https://leetcode.com/problems/reduce-array-size-to-the-half/) | [View](./Array/ReduceArraySizeToTheHalf.cpp) | Medium ||| 33 | 0905 | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [View](./Array/SortArrayByParityI.cpp) | Easy ||| 34 | 0922 | [Sort Array By Parity II](https://leetcode.com/problems/sort-array-by-parity-ii/) | [View](./Array/SortArrayByParityII.cpp) | Easy ||| 35 | 0713 | [Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k/) | [View](./Array/SubarrayProductLessThank.cpp) | Medium ||| 36 | 1476 | [Subrectangle Queries](https://leetcode.com/problems/subrectangle-queries/) | [View](./Array/SubrectangleQueries.cpp) | Medium ||| 37 | 1471 | [The k Strongest Values in an Array](https://leetcode.com/problems/the-k-strongest-values-in-an-array/) | [View](./Array/TheKStrongestValuesInAnArray.cpp) | Medium ||| 38 | 0941 | [Valid Mountain Array](https://leetcode.com/problems/valid-mountain-array/) | [View](./Array/ValidMountainArray.cpp) | Medium ||| 39 | 40 | ## Binary Search 41 | | # | Title | Solution | Difficulty | 42 | |-----|---------------- | --------------- |------------- | 43 | 0034 | [Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) | [View](./BinarySearch/FindFirstAndLastPositionOfElementInSortedArray.cpp) | Medium ||| 44 | 0153 | [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [View](./BinarySearch/FindMinimumInRotatedSortedArray.cpp) | Medium ||| 45 | 0162 | [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [View](./BinarySearch/FindPeakElement.cpp) | Medium ||| 46 | 0744 | [Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target/) | [View](./BinarySearch/FindSmallestLetterGreaterThanTarget.cpp) | Easy ||| 47 | 0275 | [H-Index II](https://leetcode.com/problems/h-index-ii/) | [View](./BinarySearch/H-IndexII.cpp) | Medium ||| 48 | 1482 | [Minimum Number of Days to Make m Bouquets](https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/) | [View](./BinarySearch/MinimumNumberOfDaysToMakeMBouquets.cpp) | Medium ||| 49 | 0852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [View](./BinarySearch/PeakIndexInAMountainArray.cpp) | Easy ||| 50 | 1300 | [Sum of Mutated Array Closest to Target](https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/) | [View](./BinarySearch/SumOfMutatedArrayClosestToTarget.cpp) | Medium ||| 51 | 52 | ## DFS (Depth First Search) 53 | | # | Title | Solution | Difficulty | 54 | |-----|---------------- | --------------- |------------- | 55 | 0200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [View](./DFS/NumberOfIslands.cpp) | Medium ||| 56 | 1020 | [Number of Enclaves](https://leetcode.com/problems/number-of-enclaves/) | [View](./DFS/NumberOfEnclaves.cpp) | Medium ||| 57 | 0130 | [Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) | [View](./DFS/SurroundedRegions.cpp) | Medium ||| 58 | 59 | ## DP (Dynamic Programming) 60 | | # | Title | Solution | Difficulty | 61 | |-----|---------------- | --------------- |------------- | 62 | 0322 | [Coin Change](https://leetcode.com/problems/coin-change/) | [View](./DP/CoinChange.cpp) | Medium ||| 63 | 0518 | [Coin Change 2](https://leetcode.com/problems/coin-change-2/) | [View](./DP/CoinChange2.cpp) | Medium ||| 64 | 0338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) | [View](./DP/CountingBits.cpp) | Medium ||| 65 | 0740 | [Delete and Earn](https://leetcode.com/problems/delete-and-earn/) | [View](./DP/DeleteAndEarn.cpp) | Medium ||| 66 | 0174 | [Dungeon Game - Memoization](https://leetcode.com/problems/dungeon-game/) | [View](./DP/DungeonGame-Memoization.cpp) | Hard ||| 67 | 0174 | [Dungeon Game - Tabulation](https://leetcode.com/problems/dungeon-game/) | [View](./DP/DungeonGame-Tabulation.cpp) | Hard ||| 68 | 0198 | [House Robber](https://leetcode.com/problems/house-robber/) | [View](./DP/HouseRobber.cpp) | Easy ||| 69 | 0368 | [Largest Divisble Subset](https://leetcode.com/problems/largest-divisble-subset/) | [View](./DP/LargestDivisbleSubset.cpp) | Medium ||| 70 | 0300 | [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) | [View](./DP/LongestIncreasingSubsequence.cpp) | Medium ||| 71 | 1048 | [Longest String Chain](https://leetcode.com/problems/longest-string-chain/) | [View](./DP/LongestStringChain.cpp) | Medium ||| 72 | 0978 | [Longest Turbulent Subarray](https://leetcode.com/problems/longest-turbulent-subarray/) | [View](./DP/LongestTurbulentSubarray.cpp) | Medium ||| 73 | 1035 | [Uncrossed Lines](https://leetcode.com/problems/uncrossed-lines/) | [View](./DP/UncrossedLines.cpp) | Medium ||| 74 | 0062 | [Unique Paths](https://leetcode.com/problems/unique-paths/) | [View](./DP/UniquePaths.cpp) | Medium ||| 75 | 76 | ## Linked List 77 | | # | Title | Solution | Difficulty | 78 | |-----|---------------- | --------------- |------------- | 79 | 0002 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [View](./LinkedList/AddTwoNumbers.cpp) | Medium ||| 80 | 0445 | [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/) | [View](./LinkedList/AddTwoNumbersII.cpp) | Medium ||| 81 | 0707 | [Design Linked List](https://leetcode.com/problems/design-linked-list/) | [View](./LinkedList/DesignLinkedList.cpp) | Medium ||| 82 | 0141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) | [View](./LinkedList/LinkedListCycleI.cpp) | Easy ||| 83 | 0142 | [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/) | [View](./LinkedList/LinkedListCycleII.cpp) | Medium ||| 84 | 0876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [View](./LinkedList/MiddleOfTheLinkedList.cpp) | Easy ||| 85 | 0021 | [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | [View](./LinkedList/MergeTwoSortedLists.cpp) | Easy ||| 86 | 1019 | [Next Greater Node In Linked List](https://leetcode.com/problems/next-greater-node-in-linked-list/) | [View](./LinkedList/NextGreaterNodeInLinkedList.cpp) | Medium ||| 87 | 0328 | [Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) | [View](./LinkedList/OddEvenLinkedList.cpp) | Medium ||| 88 | 0082 | [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/) | [View](./LinkedList/RemoveDuplicatesFromSortedListII.cpp) | Medium ||| 89 | 0061 | [Rotate List](https://leetcode.com/problems/rotate-list/) | [View](./LinkedList/RotateList.cpp) | Medium ||| 90 | 0206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [View](./LinkedList/ReverseLinkedList.cpp) | Easy ||| 91 | 0092 | [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/) | [View](./LinkedList/ReverseLinkedListII.cpp) | Medium ||| 92 | 0019 | [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) | [View](./LinkedList/RemoveNthNodeFromEndOfList.cpp) | Medium ||| 93 | 0024 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) | [View](./LinkedList/SwapNodeInPairs.cpp) | Medium ||| 94 | 95 | ## Strings 96 | | # | Title | Solution | Difficulty | 97 | |-----|---------------- | --------------- |------------- | 98 | 1433 | [Check If a String Can Break Another String](https://leetcode.com/problems/check-if-a-string-can-break-another-string/) | [View](./Strings/CheckIfAStringCanBreakAnotherString.cpp) | Medium ||| 99 | 0028 | [Implement strStr() - KMP Algorithm](https://leetcode.com/problems/implement-strstr/) | [View](./Strings/ImplementstrStr-KMP.cpp) | Easy ||| 100 | 0028 | [Implement strStr() - Rabin Karp Algorithm](https://leetcode.com/problems/implement-strstr/) | [View](./Strings/ImplementstrStr-Rabin-Karp.cpp) | Easy ||| 101 | 0459 | [Repeated Substring Pattern - KMP Algorithm](https://leetcode.com/problems/repeated-substring-pattern/) | [View](./Strings/RepeatedSubstringPattern.cpp) | Easy ||| 102 | 0686 | [Repeated String Match - KMP Algorithm](https://leetcode.com/problems/repeated-string-match/) | [View](./Strings/RepeatedStringMatch.cpp) | Easy ||| 103 | 1487 | [Making File Names Unique](https://leetcode.com/problems/making-file-names-unique/) | [View](./Strings/MakingFileNamesUnique.cpp) | Medium ||| 104 | 105 | ## Stack 106 | | # | Title | Solution | Difficulty | 107 | |-----|---------------- | --------------- |------------- | 108 | 1381 | [Design a Stack With Increment Operation](https://leetcode.com/problems/design-a-stack-with-increment-operation/) | [View](./Stack/DesignAStackWithIncrementOperation.cpp) | Medium ||| 109 | 0146 | [LRU Cache](https://leetcode.com/problems/lru-cache/) | [View](./Stack/LRUCache.cpp) | Medium ||| 110 | 0232 | [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | [View](./Stack/ImplementQueueUsingStacks.cpp) | Easy ||| 111 | 0155 | [Min Stack](https://leetcode.com/problems/min-stack/) | [View](./Stack/MinStack.cpp) | Easy ||| 112 | 113 | ## Sliding Window 114 | | # | Title | Solution | Difficulty | 115 | |-----|---------------- | --------------- |------------- | 116 | 0904 | [Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/) | [View](./SlidingWindow/FruitsIntoBaskets.cpp) | Medium ||| 117 | 1052 | [Grumpy Bookstore Owner](https://leetcode.com/problems/grumpy-bookstore-owner/) | [View](./SlidingWindow/GrumpyBookstoreOwner.cpp) | Medium ||| 118 | 1438 | [ Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit](https://leetcode.com/problems/replace-the-substring-for-balanced-string/) | [View](./SlidingWindow/LongestContinuousSubarrayWithAbsoluteDiffLessThanOrEqualToLimit.cpp) | Medium ||| 119 | 1004 | [Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii/) | [View](./SlidingWindow/MaxConsecutiveOnesIII.cpp) | Medium ||| 120 | 1358 | [Number of Substrings Containing All Three Characters](https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/) | [View](./SlidingWindow/NumberOfSubstringsContainingAllThreeCharacters.cpp) | Medium ||| 121 | 1234 | [Replace the Substring for Balanced String](https://leetcode.com/problems/replace-the-substring-for-balanced-string/) | [View](./SlidingWindow/ReplaceTheSubstringForBalancedString.cpp) | Medium ||| 122 | 123 | ## Tree 124 | | # | Title | Solution | Difficulty | 125 | |-----|---------------- | --------------- |------------- | 126 | 0938 | [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/) | [View](./Tree/RangeSumOfBST.cpp) | Easy ||| 127 | 0617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/) | [View](./Tree/MergeTwoBinaryTree.cpp) | Easy ||| 128 | 0700 | [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/) | [View](./Tree/SearchInABinarySearchTree.cpp) | Easy ||| 129 | 0129 | [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | [View](./Tree/SumRootToLeafNumbers.cpp) | Medium ||| 130 | 0897 | [Increasing Order Search Tree](https://leetcode.com/problems/increasing-order-search-tree/) | [View](./Tree/IncreasingOrderSearchTree.cpp) | Easy ||| 131 | 0559 | [Maximum Depth of N-ary Tree](https://leetcode.com/problems/maximum-depth-of-n-ary-tree/) | [View](./Tree/MaximumDepthOfN-AryTree.cpp) | Easy ||| 132 | 0104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) | [View](./Tree/MaximumDepthOfBinaryTree.cpp) | Easy ||| 133 | 0226 | [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [View](./Tree/InvertBinaryTree.cpp) | Easy ||| 134 | 0530 | [Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst/) | [View](./Tree/MinimumAbsoluteDifferenceInBST.cpp) | Easy ||| 135 | 0993 | [Cousins in Binary Tree](https://leetcode.com/problems/cousins-in-binary-tree/) | [View](./Tree/CousinsInBinaryTree.cpp) | Easy ||| 136 | 0783 | [Minimum Distance Between BST Nodes](https://leetcode.com/problems/minimum-distance-between-bst-nodes/) | [View](./Tree/MinimumDistanceBetweenBSTNodes.cpp) | Easy ||| 137 | 0543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [View](./Tree/DiameterOfBinaryTree.cpp) | Easy ||| 138 | 0110 | [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | [View](./Tree/BalancedBinaryTree.cpp) | Easy ||| 139 | 0222 | [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | [View](./Tree/CountCompleteTreeNodes.cpp) | Medium ||| 140 | 1008 | [Construct Binary Search Tree from Preorder Traversal](https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/) | [View](./Tree/ConstructBinarySearchTreeFromPreorderTraversal.cpp) | Medium ||| 141 | 1448 | [Count Good Nodes in Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree/) | [View](./Tree/ConstructBinarySearchTreeFromPreorderTraversal.cpp) | Medium ||| 142 | 0889 | [Construct Binary Tree from Preorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/) | [View](./Tree/ConstructBinaryTreeFromPreorderAndPostorderTraversal.cpp) | Medium ||| 143 | 0429 | [N-ary Tree Level Order Traversal](https://leetcode.com/problems/n-ary-tree-level-order-traversal/) | [View](./Tree/N-AryTreeLevelOrderTraversal.cpp) | Medium ||| 144 | 0230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [View](./Tree/KthSmallestElementInABST.cpp) | Medium ||| 145 | 0096 | [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) | [View](./Tree/UniqueBinarySearchTrees.cpp) | Medium ||| 146 | 103 | [Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/) | [View](./Tree/BinaryTreeZigzagLevelOrderTraversal.cpp) | Medium ||| 147 | 148 | ## Trie 149 | | # | Title | Solution | Difficulty | 150 | |-----|---------------- | --------------- |------------- | 151 | 0208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [View](./Trie/ImplementTrie-PrefixTree.cpp) | Medium ||| 152 | 0211 | [Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [View](./Trie/AddAndSearchWord-DataStructureDesign.cpp) | Medium ||| 153 | 0648 | [Replace Words](https://leetcode.com/problems/replace-words/) | [View](./Trie/ReplaceWords.cpp) | Medium ||| 154 | 0212 | [Word Search II](https://leetcode.com/problems/word-replace-ii/) | [View](./Trie/WordSearchII.cpp) | Hard ||| 155 | 156 | ## Union Find 157 | | # | Title | Solution | Difficulty | 158 | |-----|---------------- | --------------- |------------- | 159 | 0547 | [Friend Circles](https://leetcode.com/problems/friend-circles/) | [View](./UnionFind/FriendCircles.cpp) | Medium ||| 160 | 1319 | [Number of Operations to Make Network Connected](https://leetcode.com/problems/number-of-operations-to-make-network-connected/) | [View](./UnionFind/NumberOfOperationsToMakeNetworkConnected.cpp) | Medium ||| 161 | 0684 | [Redundant Connection](https://leetcode.com/problems/redundant-connection/) | [View](./UnionFind/RedundantConnection.cpp) | Medium ||| 162 | 0990 | [Satisfiability of Equality Equations](https://leetcode.com/problems/satisfiability-of-equality-equations/) | [View](./UnionFind/SatisfiabilityOfEqualityEquations.cpp) | Medium ||| 163 | -------------------------------------------------------------------------------- /SlidingWindow/FruitIntoBaskets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int totalFruit(vector& tree) { 4 | int i = 0, j = 0, n = tree.size(), res=INT_MIN; 5 | unordered_map mp; 6 | for(; i < tree.size(); i++) { 7 | mp[tree[i]]++; 8 | while(j < n && mp.size() > 2) { 9 | res = max(res, i - j); 10 | mp[tree[j]]--; 11 | if(mp[tree[j]] == 0) 12 | mp.erase(tree[j]); 13 | j++; 14 | } 15 | } 16 | res = max(res, i - j); 17 | return res == INT_MIN ? (mp.size() > 0 ? n : 0) : res; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /SlidingWindow/GrumpyBookstoreOwner.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSatisfied(vector& customers, vector& grumpy, int X) { 4 | int notgrumpy = 0; 5 | for(int i = 0; i < customers.size(); i++) 6 | if(grumpy[i] == 0) 7 | notgrumpy += customers[i]; 8 | 9 | int winStart = 0, winSum = 0, satisfied = 0; 10 | for(int winEnd = 0; winEnd < customers.size(); winEnd++) { 11 | if(grumpy[winEnd]) 12 | winSum += customers[winEnd]; 13 | if(winEnd >= X - 1) { 14 | satisfied = max(satisfied, winSum); 15 | if(grumpy[winStart]) 16 | winSum -= customers[winStart]; 17 | winStart++; 18 | } 19 | } 20 | return notgrumpy + satisfied; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /SlidingWindow/LongestContinuousSubarrayWithAbsoluteDiffLessThanOrEqualToLimit.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestSubarray(vector& nums, int limit) { 4 | int s = 0, e = 0, res = 0; 5 | deque maxq, minq; 6 | while(e < nums.size()) { 7 | int x = nums[e]; 8 | while(!minq.empty() && nums[minq.back()] >= x) 9 | minq.pop_back(); 10 | minq.push_back(e); 11 | while(!maxq.empty() && nums[maxq.back()] <= x) 12 | maxq.pop_back(); 13 | maxq.push_back(e); 14 | int mini = nums[minq.front()]; 15 | int maxi = nums[maxq.front()]; 16 | if(maxi - mini > limit) { 17 | s++; 18 | if(s > minq.front()) 19 | minq.pop_front(); 20 | if(s > maxq.front()) 21 | maxq.pop_front(); 22 | } 23 | else { 24 | res = max(res, e - s + 1); 25 | e++; 26 | } 27 | } 28 | return res; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /SlidingWindow/MaxConsecutiveOnesIII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestOnes(vector& A, int K) { 4 | int i = 0, j = 0, res = INT_MIN, count = 0; 5 | for(; j < A.size(); j++) { 6 | if(A[j] == 0) count++; 7 | 8 | while(count > K && i < A.size()) { 9 | res = max(res, j - i); 10 | if(A[i] == 0) 11 | count--; 12 | i++; 13 | } 14 | } 15 | res = max(res, j - i); 16 | return res == INT_MIN ? ((count <= K ? A.size() : 0)) : res; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /SlidingWindow/NumberOfSubstringsContainingAllThreeCharacters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfSubstrings(string s) { 4 | int freq[3] = {0}; 5 | int j = 0, res = 0; 6 | for(int i = 0; i < s.length(); i++) { 7 | ++freq[s[i] - 'a']; 8 | while(freq[0] && freq[1] && freq[2]) { 9 | cout << "I:" << i << endl; 10 | --freq[s[j++] - 'a']; 11 | } 12 | cout << "J: " << j << endl; 13 | res += j; 14 | } 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /SlidingWindow/ReplaceTheSubstringForBalancedString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int balancedString(string s) { 4 | int n = s.length(); 5 | int bal = n / 4; 6 | unordered_map mp; 7 | for(int i = 0; i < n; i++) { 8 | mp[s[i]]++; 9 | } 10 | int j = 0, res = n; 11 | for(int i = 0; i < n; i++) { 12 | mp[s[i]]--; 13 | while(j < n && mp['Q'] <= bal && mp['W'] <= bal && mp['E'] <= bal && mp['R'] <= bal) { 14 | res = min(res, i - j + 1); 15 | mp[s[j++]]++; 16 | } 17 | } 18 | return res; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Stack/DesignAStackWithIncrementOperation.cpp: -------------------------------------------------------------------------------- 1 | class CustomStack { 2 | public: 3 | int size = -1; 4 | vector s; 5 | CustomStack(int maxSize) { 6 | s.resize(maxSize); 7 | } 8 | 9 | void push(int x) { 10 | if(size + 1 < s.size()) 11 | s[++size] = x; 12 | } 13 | 14 | int pop() { 15 | return size < 0 ? -1 : s[size--]; 16 | } 17 | 18 | void increment(int k, int val) { 19 | for(int i = 0; i < min(k, size + 1); i++) 20 | s[i] += val; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Stack/ImplementQueueUsingStacks.cpp: -------------------------------------------------------------------------------- 1 | class MyQueue { 2 | public: 3 | stack input, output; 4 | /** Initialize your data structure here. */ 5 | MyQueue() { 6 | 7 | } 8 | 9 | /** Push element x to the back of queue. */ 10 | void push(int x) { 11 | input.push(x); 12 | } 13 | 14 | /** Removes the element from in front of queue and returns that element. */ 15 | int pop() { 16 | peek(); 17 | int ele = output.top(); 18 | output.pop(); 19 | return ele; 20 | } 21 | 22 | /** Get the front element. */ 23 | int peek() { 24 | if(output.empty()) { 25 | while(input.size()) { 26 | output.push(input.top()); 27 | input.pop(); 28 | } 29 | } 30 | return output.top(); 31 | } 32 | 33 | /** Returns whether the queue is empty. */ 34 | bool empty() { 35 | return input.empty() && output.empty(); 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Stack/LRUCache.cpp: -------------------------------------------------------------------------------- 1 | class LRUCache { 2 | public: 3 | int cap; 4 | listkey_list; 5 | unordered_mapmp; 6 | 7 | 8 | LRUCache(int capacity) { 9 | cap = capacity; 10 | } 11 | 12 | int get(int key) { 13 | if(mp.find(key) == mp.end() ) 14 | return -1; 15 | 16 | else{ 17 | key_list.remove(key); 18 | key_list.push_back(key); 19 | return mp[key]; 20 | } 21 | } 22 | 23 | void put(int key, int value) { 24 | if(mp.find(key) != mp.end() ){ 25 | mp.erase(key); 26 | key_list.remove(key); 27 | } 28 | if(key_list.size() == cap){ 29 | int temp = key_list.front(); 30 | key_list.pop_front(); 31 | mp.erase(temp); 32 | } 33 | mp[key] = value; 34 | key_list.push_back(key); 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Stack/MinStack.cpp: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | public: 3 | /** initialize your data structure here. */ 4 | vector v; 5 | int t; 6 | MinStack() { 7 | t = -1; 8 | } 9 | 10 | void push(int x) { 11 | v.push_back(x); 12 | t++; 13 | } 14 | 15 | void pop() { 16 | v.pop_back(); 17 | t--; 18 | } 19 | 20 | int top() { 21 | return v[t]; 22 | } 23 | 24 | int getMin() { 25 | return *min_element(v.begin(), v.end()); 26 | } 27 | }; 28 | 29 | -------------------------------------------------------------------------------- /Strings/CheckIfAStringCanBreakAnotherString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkIfCanBreak(string s1, string s2) { 4 | sort(s1.begin(), s1.end()); 5 | sort(s2.begin(), s2.end()); 6 | int f = 1, s = 1; 7 | for(int i = 0; i < s1.length(); i++) { 8 | if(s1[i] > s2[i]) 9 | f = 0; 10 | else if(s2[i] > s1[i]) 11 | s = 0; 12 | } 13 | if(f || s) 14 | return true; 15 | return false; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Strings/ImplementstrStr-KMP.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void computeLPSArray(string pat, int m, int* lps) { 4 | int len = 0; 5 | lps[0] = 0; 6 | 7 | int i = 1; 8 | while(i < m) { 9 | if(pat[i] == pat[len]) { 10 | //If Equal we store len at curr index 11 | lps[i++] = ++len; 12 | } 13 | else { 14 | //If not equal 15 | if(len != 0) 16 | len = lps[len - 1]; 17 | else { 18 | //If len == 0 19 | lps[i] = 0; 20 | i++; 21 | } 22 | } 23 | 24 | } 25 | 26 | } 27 | 28 | int strStr(string txt, string pat) { 29 | // KMP algorithm 30 | int n = txt.length(); 31 | int m = pat.length(); 32 | 33 | if(!m) 34 | return 0; 35 | 36 | int lps[m]; 37 | computeLPSArray(pat, m, lps); 38 | 39 | int i = 0; 40 | int j = 0; 41 | while(i < n) { 42 | if(pat[j] == txt[i]) 43 | i++, j++; 44 | 45 | if(j == m) 46 | return i - j; 47 | 48 | else if(i < n && pat[j] != txt[i]) { 49 | //move j 50 | if(j != 0) 51 | j = lps[j - 1]; 52 | // inc i to find match with j if j == 0 53 | else 54 | i++; 55 | } 56 | } 57 | return -1; 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /Strings/ImplementstrStr-Rabin-Karp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int strStr(string source, string target) { 4 | // Rabin Karp algorithm 5 | int m = source.length(); 6 | int n = target.length(); 7 | if(m < n) 8 | return -1; 9 | long preCompute = 1; 10 | long hCode = 0; 11 | long tCode = 0; 12 | long d = 256; 13 | long q = 101; 14 | 15 | for(int i = 0; i < n - 1; i++) 16 | preCompute = (preCompute * d) % q; 17 | 18 | for(int j = 0; j < n; j++) { 19 | hCode = (hCode * d + source[j]) % q; 20 | tCode = (tCode * d + target[j]) % q; 21 | } 22 | 23 | for(int i = 0; i <= m - n; i++) { 24 | if(hCode == tCode) { 25 | int j = 0; 26 | for(; j < n; j++) { 27 | if(source[i+j] != target[j]) 28 | break; 29 | } 30 | if(j == n) 31 | return i; 32 | } 33 | if(i < m - n) { 34 | hCode = (d * (hCode - source[i] * preCompute) + source[i + n]) % q; 35 | if(hCode < 0) 36 | hCode += q; 37 | } 38 | } 39 | return -1; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Strings/MakingFileNamesUnique.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getFolderNames(vector& names) { 4 | unordered_map mp; 5 | vector res(names.size()); 6 | for(int i = 0; i < names.size(); i++) { 7 | if(mp.find(names[i]) != mp.end()) { 8 | int val = mp[names[i]]; 9 | string str = names[i] + '(' + to_string(val) + ')'; 10 | while(mp.find(str) != mp.end()) { 11 | val++; 12 | str = names[i] + '(' + to_string(val) + ')'; 13 | } 14 | res[i] = str; 15 | mp[str] = 1; 16 | mp[names[i]] = val + 1; 17 | } else { 18 | res[i] = names[i]; 19 | mp[names[i]] = 1; 20 | } 21 | } 22 | return res; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Strings/RepeatedStringMatch.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void computeLPSArray(string pat, int m, int* lps) { 4 | int len = 0; 5 | lps[0] = 0; 6 | int i = 1; 7 | while(i < m) { 8 | if(pat[i] == pat[len]) 9 | lps[i++] = ++len; 10 | else { 11 | if(len == 0) { 12 | lps[i] = 0; 13 | i++; 14 | } else 15 | len = lps[len - 1]; 16 | } 17 | } 18 | } 19 | 20 | int repeatedStringMatch(string A, string B) { 21 | int n = A.size(); 22 | int m = B.size(); 23 | 24 | int lps[m]; 25 | computeLPSArray(B, m, lps); 26 | 27 | int i = 0, j = 0; 28 | while(i < n) { 29 | while(j < m && A[(i + j) % n] == B[j]) { 30 | j++; 31 | } 32 | 33 | if(j == m) 34 | return ceil((float)(i + j) / n); 35 | 36 | i++; 37 | 38 | if(j > 0) 39 | j = lps[j - 1]; 40 | } 41 | return -1; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Strings/RepeatedSubstringPattern.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void computeLPSArray(string pat, int m, int* lps) { 4 | int len = 0; 5 | int i = 1; 6 | lps[0] = 0; 7 | while(i < m) { 8 | if(pat[i] == pat[len]) 9 | lps[i++] = ++len; 10 | else { 11 | if(len == 0) { 12 | lps[i] = 0; 13 | i++; 14 | } else 15 | len = lps[len - 1]; 16 | } 17 | } 18 | } 19 | 20 | bool repeatedSubstringPattern(string s) { 21 | int n = s.length(); 22 | int lps[n]; 23 | computeLPSArray(s, n, lps); 24 | return lps[n - 1] && n % (n - lps[n - 1]) == 0; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Tree/BalancedBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int Depth(TreeNode *root) { 4 | if(!root) return 0; 5 | int L = Depth(root->left); 6 | int R = Depth(root->right); 7 | return 1 + max(L, R); 8 | } 9 | bool isBalanced(TreeNode* root) { 10 | if(root == NULL) 11 | return true; 12 | int left = Depth(root->left); 13 | int right = Depth(root->right); 14 | 15 | if(abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right)) 16 | return true; 17 | return false; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Tree/BinaryTreeZigzagLevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector> zigzagLevelOrder(TreeNode* root) { 15 | vector> ans; 16 | if(root == NULL) 17 | return ans; 18 | queue q1; 19 | q1.push(root); 20 | while(!q1.empty()) 21 | { 22 | int n = q1.size(); 23 | vector sub; 24 | for(int i = 0; ival); 28 | q1.pop(); 29 | if(temp->left) 30 | q1.push(temp->left); 31 | if(temp->right) 32 | q1.push(temp->right); 33 | } 34 | ans.push_back(sub); 35 | } 36 | for(int i = 0; ival) 10 | root->left = constructTree(val, root->left); 11 | else 12 | root->right = constructTree(val, root->right); 13 | return root; 14 | } 15 | 16 | 17 | class Solution { 18 | public: 19 | TreeNode* bstFromPreorder(vector& preorder) { 20 | TreeNode *root = new TreeNode(preorder[0]); 21 | for(int i = 1; i < preorder.size(); i++) { 22 | root = constructTree(preorder[i], root); 23 | } 24 | return root; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Tree/ConstructBinaryTreeFromPreorderAndPostorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int preIndex = 0, posIndex = 0; 4 | TreeNode* constructFromPrePost(vector& pre, vector& post) { 5 | TreeNode *root = new TreeNode(pre[preIndex++]); 6 | if(root->val != post[posIndex]) 7 | root->left = constructFromPrePost(pre, post); 8 | if(root->val != post[posIndex]) 9 | root->right = constructFromPrePost(pre, post); 10 | posIndex++; 11 | return root; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Tree/CountCompleteTreeNodes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void preorder(TreeNode *root, int& count) { 4 | if(!root) 5 | return; 6 | count++; 7 | preorder(root->left, count); 8 | preorder(root->right, count); 9 | } 10 | 11 | 12 | int countNodes(TreeNode* root) { 13 | int count = 0; 14 | preorder(root, count); 15 | return count; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Tree/CountGoodNodesInBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int count; 4 | void dfs(TreeNode *curr, int maxv) { 5 | if(!curr) 6 | return; 7 | if(curr->val >= maxv) { 8 | maxv = curr->val; 9 | count++; 10 | } 11 | dfs(curr->left, maxv); 12 | dfs(curr->right, maxv); 13 | } 14 | 15 | int goodNodes(TreeNode* root) { 16 | count = 0; 17 | dfs(root, INT_MIN); 18 | return count; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Tree/CousinsInBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | vector dfs(TreeNode *root, int target, int depth, int parent) { 5 | if(root == NULL) 6 | return {}; 7 | if(root->val == target) 8 | return {depth, parent}; 9 | else { 10 | parent = root->val; 11 | vector left = dfs(root->left, target, depth+1, parent); 12 | vector right = dfs(root->right, target, depth+1, parent); 13 | 14 | if(left.empty()) 15 | return right; 16 | else 17 | return left; 18 | } 19 | } 20 | 21 | bool isCousins(TreeNode* root, int x, int y) { 22 | vector d1 = dfs(root, x, 0, -1); 23 | vector d2 = dfs(root, y, 0, -1); 24 | if(d1[0] == d2[0] && d1[1] != d2[1]) 25 | return true; 26 | return false; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Tree/DiameterOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | int height(TreeNode *root, int& ans) { 2 | if(root == NULL) 3 | return 0; 4 | int left = height(root->left, ans); 5 | int right = height(root->right, ans); 6 | ans = max(ans, 1+left+right); 7 | return 1 + max(left, right); 8 | } 9 | class Solution { 10 | public: 11 | int diameterOfBinaryTree(TreeNode* root) { 12 | if(root == NULL) 13 | return 0; 14 | int ans = INT8_MIN; 15 | int height_tree = height(root, ans); 16 | return ans-1; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Tree/IncreasingOrderSearchTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode *incOrder(TreeNode *root, TreeNode *tail) { 4 | if(!root) return tail; 5 | TreeNode *res = incOrder(root->left, root); 6 | root->left = NULL; 7 | root->right = incOrder(root->right, tail); 8 | return res; 9 | } 10 | TreeNode* increasingBST(TreeNode* root){ 11 | return incOrder(root, NULL); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Tree/InvertBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* invert(TreeNode* root) { 4 | if(!root) 5 | return NULL; 6 | TreeNode* temp = invert(root->left); 7 | root->left = invert(root->right); 8 | root->right = temp; 9 | return root; 10 | } 11 | TreeNode* invertTree(TreeNode* root) { 12 | return invert(root); 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Tree/KthSmallestElementInABST.cpp: -------------------------------------------------------------------------------- 1 | void preorder(TreeNode *root, vector &pre) { 2 | if(root == NULL) 3 | return; 4 | pre.push_back(root->val); 5 | preorder(root->left, pre); 6 | preorder(root->right, pre); 7 | } 8 | 9 | class Solution { 10 | public: 11 | int kthSmallest(TreeNode* root, int k) { 12 | vector pre; 13 | preorder(root, pre); 14 | sort(pre.begin(), pre.end()); 15 | return pre[k-1]; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Tree/MaximumDepthOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDepth(TreeNode* root) { 4 | if(!root) return 0; 5 | int left = maxDepth(root->left); 6 | int right = maxDepth(root->right); 7 | return 1 + max(left, right); 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Tree/MaximumDepthOfN-AryTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int maxDepth(Node* root) { 5 | if(root == NULL) return 0; 6 | int depth = 0; 7 | for(auto child: root->children) depth = max(depth, maxDepth(child)); 8 | return 1 + depth; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Tree/MergeTwoBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | TreeNode* newNode(TreeNode *node, TreeNode *tree1, TreeNode *tree2) { 2 | if(tree1 && tree2) 3 | node = new TreeNode(tree1->val + tree2->val); 4 | else if(tree1 == NULL && tree2 != NULL) 5 | node = new TreeNode(tree2->val); 6 | else if(tree1 != NULL && tree2 == NULL) 7 | node = new TreeNode(tree1->val); 8 | return node; 9 | } 10 | 11 | TreeNode* merge(TreeNode *tree1, TreeNode *tree2, TreeNode *newroot) { 12 | if(tree1 == NULL) 13 | return tree2; 14 | if(tree2 == NULL) 15 | return tree1; 16 | newroot->left = merge(tree1->left, tree2->left, newNode(newroot->left, tree1->left, tree2->left)); 17 | newroot->right = merge(tree1->right, tree2->right, newNode(newroot->right, tree1->right, tree2->right)); 18 | return newroot; 19 | } 20 | 21 | class Solution { 22 | public: 23 | TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { 24 | TreeNode *newroot = NULL; 25 | if(t1 == NULL && t2 == NULL) 26 | return NULL; 27 | if(t1 == NULL) 28 | newroot = new TreeNode(t2->val); 29 | else if(t2 == NULL) 30 | newroot = new TreeNode(t1->val); 31 | else 32 | newroot = new TreeNode(t1->val + t2->val); 33 | newroot = merge(t1, t2, newroot); 34 | return newroot; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Tree/MinimumAbsoluteDifferenceInBST.cpp: -------------------------------------------------------------------------------- 1 | void traverse(TreeNode *root, vector &preorder) { 2 | if(root == NULL) 3 | return; 4 | preorder.push_back(root->val); 5 | if(root->left) 6 | traverse(root->left, preorder); 7 | if(root->right) 8 | traverse(root->right, preorder); 9 | return; 10 | } 11 | 12 | class Solution { 13 | public: 14 | int getMinimumDifference(TreeNode* root) { 15 | vector preorder; 16 | traverse(root, preorder); 17 | sort(preorder.begin(), preorder.end()); 18 | int minDist = INT_MAX; 19 | for(int i = 0; i < preorder.size() - 1; i++) { 20 | minDist = min(minDist, (preorder[i+1] - preorder[i])); 21 | } 22 | return minDist; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Tree/MinimumDistanceBetweenBSTNodes.cpp: -------------------------------------------------------------------------------- 1 | void inorder(TreeNode *root, vector &trav) { 2 | if(root == NULL) 3 | return; 4 | inorder(root->left, trav); 5 | trav.push_back(root->val); 6 | inorder(root->right, trav); 7 | } 8 | class Solution { 9 | public: 10 | int minDiffInBST(TreeNode* root) { 11 | vector trav; 12 | inorder(root, trav); 13 | int minDiff = INT_MAX; 14 | for(int i = 1; i < trav.size(); i++) 15 | minDiff = min(minDiff, (abs(trav[i-1] - trav[i]))); 16 | return minDiff; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Tree/N-AryTreeLevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> levelOrder(Node* root) { 4 | if(root == NULL) 5 | return vector>(); 6 | queue q; 7 | q.push(root); 8 | q.push(NULL); 9 | vector> ans; 10 | vector v; 11 | while(!q.empty()) { 12 | Node *node = q.front(); 13 | q.pop(); 14 | if(node) { 15 | v.push_back(node->val); 16 | for(int i = 0; i < node->children.size(); i++) 17 | q.push(node->children[i]); 18 | } 19 | else { 20 | ans.push_back(v); 21 | v.clear(); 22 | if(q.empty()) break; 23 | q.push(NULL); 24 | 25 | } 26 | } 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Tree/RangeSumOfBST.cpp: -------------------------------------------------------------------------------- 1 | void preorder(TreeNode *root, int L, int R, int &sum) { 2 | if(root == NULL) 3 | return; 4 | if(root->val >= L && root->val <= R) { 5 | sum += root->val; 6 | } 7 | preorder(root->left, L, R, sum); 8 | preorder(root->right, L, R, sum); 9 | } 10 | 11 | class Solution { 12 | public: 13 | int rangeSumBST(TreeNode* root, int L, int R) { 14 | int sum = 0; 15 | preorder(root, L, R, sum); 16 | return sum; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Tree/SearchInABinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* searchBST(TreeNode* root, int val) { 4 | if(root == NULL) 5 | return NULL; 6 | if(root->val == val) 7 | return root; 8 | TreeNode* left = root->left ? searchBST(root->left, val) : NULL; 9 | TreeNode *right = root->right ? searchBST(root->right, val) : NULL; 10 | if(left == NULL) 11 | return right; 12 | if(right == NULL) 13 | return left; 14 | return root; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Tree/SumRootToLeafNumbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sumNumbers(TreeNode *root, int currSum, int& sum) { 4 | currSum = currSum * 10 + root->val; 5 | if(!root->left && !root->right) 6 | sum += currSum; 7 | if(root->left) 8 | sumNumbers(root->left, currSum, sum); 9 | if(root->right) 10 | sumNumbers(root->right, currSum, sum); 11 | } 12 | 13 | int sumNumbers(TreeNode* root) { 14 | if(!root) 15 | return 0; 16 | int sum = 0; 17 | sumNumbers(root, 0, sum); 18 | return sum; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Tree/UniqueBinarySearchTrees.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numTrees(int n) { 4 | vectordp(n + 1); 5 | dp[0] = 1; 6 | dp[1] = 1; 7 | for(int i = 2; i <= n; i++) 8 | for(int j = 1; j <= i; j++) 9 | dp[i] += dp[j - 1] * dp[i - j]; 10 | return dp[n]; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Trie/AddAndSearchWord-DataStructureDesign.cpp: -------------------------------------------------------------------------------- 1 | struct TrieNode { 2 | bool end; 3 | TrieNode* children[26]; 4 | TrieNode() { 5 | end = false; 6 | memset(children, NULL, sizeof(children)); 7 | } 8 | }; 9 | class WordDictionary { 10 | TrieNode *root; 11 | bool search(const char* word, TrieNode *node) { 12 | for(int i = 0; word[i] && node; i++) { 13 | if(word[i] != '.') 14 | node = node->children[word[i] - 'a']; 15 | else { 16 | TrieNode *tmp = node; 17 | for(int j = 0; j < 26; j++) { 18 | node = tmp->children[j]; 19 | if(search(word + i + 1, node)) 20 | return true; 21 | } 22 | } 23 | } 24 | return node && node->end; 25 | } 26 | public: 27 | /** Initialize your data structure here. */ 28 | WordDictionary() { 29 | root = new TrieNode(); 30 | } 31 | 32 | /** Adds a word into the data structure. */ 33 | void addWord(string word) { 34 | TrieNode *dummy = root; 35 | for(char c: word) { 36 | if(!dummy->children[c - 'a']) 37 | dummy->children[c - 'a'] = new TrieNode(); 38 | dummy = dummy->children[c - 'a']; 39 | } 40 | dummy->end = true; 41 | } 42 | 43 | /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ 44 | bool search(string word) { 45 | return search(word.c_str(), root); 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Trie/ImplementTrie-PrefixTree.cpp: -------------------------------------------------------------------------------- 1 | struct TrieNode { 2 | bool end; 3 | TrieNode *children[26]; 4 | TrieNode() { 5 | end = false; 6 | memset(children, NULL, sizeof(children)); 7 | } 8 | }; 9 | class Trie { 10 | TrieNode *root; 11 | public: 12 | /** Initialize your data structure here. */ 13 | Trie() { 14 | root = new TrieNode(); 15 | } 16 | 17 | // Destructor 18 | ~Trie() { 19 | clear(root); 20 | } 21 | 22 | // Clear memory 23 | void clear(TrieNode *root) { 24 | for(int i = 0; i < 26; i++) { 25 | if(root->children[i]) clear(root->children[i]); 26 | } 27 | delete root; 28 | } 29 | 30 | /** Inserts a word into the trie. */ 31 | void insert(string word) { 32 | TrieNode *dummy = root; 33 | for(char c: word) { 34 | if(!dummy->children[c - 'a']) 35 | dummy->children[c - 'a'] = new TrieNode(); 36 | dummy = dummy->children[c - 'a']; 37 | } 38 | dummy->end = true; 39 | } 40 | 41 | /** Returns if the word is in the trie. */ 42 | bool search(string word) { 43 | TrieNode *dummy = root; 44 | for(char c: word) { 45 | if(!dummy->children[c - 'a']) 46 | return false; 47 | dummy = dummy->children[c - 'a']; 48 | } 49 | return dummy && dummy->end; 50 | } 51 | 52 | /** Returns if there is any word in the trie that starts with the given prefix. */ 53 | bool startsWith(string prefix) { 54 | TrieNode *dummy = root; 55 | for(char c: prefix) { 56 | if(!dummy->children[c - 'a']) 57 | return false; 58 | dummy = dummy->children[c - 'a']; 59 | } 60 | return dummy; 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /Trie/ReplaceWords.cpp: -------------------------------------------------------------------------------- 1 | struct TrieNode { 2 | bool end; 3 | TrieNode *children[26]; 4 | TrieNode() { 5 | end = false; 6 | memset(children, NULL, sizeof(children)); 7 | } 8 | }; 9 | 10 | class Trie { 11 | public: 12 | TrieNode *root; 13 | Trie(vector& dict) { 14 | root = new TrieNode(); 15 | for(int i = 0; i < dict.size(); i++) 16 | addWord(dict[i]); 17 | } 18 | void addWord(const string& s) { 19 | TrieNode *dummy = root; 20 | for(int i = 0; i < s.length(); i++) { 21 | if(!dummy->children[s[i] - 'a']) 22 | dummy->children[s[i] - 'a'] = new TrieNode; 23 | dummy = dummy->children[s[i] - 'a']; 24 | } 25 | dummy->end = true; 26 | } 27 | }; 28 | 29 | class Solution { 30 | public: 31 | string replaceWords(vector& dict, string sentence) { 32 | Trie *trie = new Trie(dict); 33 | TrieNode *root = trie->root; 34 | stringstream ss(sentence); 35 | string res, word; 36 | while(ss >> word) { 37 | res += search(root, word) + " "; 38 | } 39 | if(res != "") 40 | res.pop_back(); 41 | return res; 42 | } 43 | 44 | string search(TrieNode *root, string& word){ 45 | TrieNode* t = root; 46 | for(int i=0;iend) 48 | return word.substr(0,i); 49 | if(t->children[word[i]-'a']) 50 | t=t->children[word[i]-'a']; 51 | else 52 | return word; 53 | } 54 | return word; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /Trie/WordSearchII.cpp: -------------------------------------------------------------------------------- 1 | struct TrieNode { 2 | bool end; 3 | TrieNode *children[26]; 4 | TrieNode() { 5 | end = false; 6 | memset(children, NULL, sizeof(children)); 7 | } 8 | }; 9 | 10 | class Trie { 11 | public: 12 | TrieNode* root; 13 | Trie(vector& words) { 14 | root = new TrieNode(); 15 | for(int i = 0; i < words.size(); i++) 16 | addWord(words[i]); 17 | } 18 | void addWord(const string& s) { 19 | TrieNode *dummy = root; 20 | for(char c: s) { 21 | if(!dummy->children[c - 'a']) 22 | dummy->children[c - 'a'] = new TrieNode(); 23 | dummy = dummy->children[c - 'a']; 24 | } 25 | dummy->end = true; 26 | } 27 | }; 28 | 29 | 30 | class Solution { 31 | public: 32 | vector findWords(vector>& board, vector& words) { 33 | Trie* trie = new Trie(words); 34 | set s; 35 | TrieNode *root = trie->root; 36 | for(int x = 0; x < board.size(); x++) { 37 | for(int y = 0; y < board[0].size(); y++) { 38 | findWords(board, x, y, root, "", s); 39 | } 40 | } 41 | vector res; 42 | for(auto it: s) res.push_back(it); 43 | return res; 44 | } 45 | 46 | void findWords(vector>& board, int x, int y, TrieNode *root, string word, set& s) { 47 | if(x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || board[x][y] == ' ') return; 48 | if(root->children[board[x][y] - 'a']) { 49 | word += board[x][y]; 50 | root = root->children[board[x][y] - 'a']; 51 | if(root->end) s.insert(word); 52 | char c = board[x][y]; 53 | board[x][y] = ' '; 54 | findWords(board, x+1, y, root, word, s); 55 | findWords(board, x-1, y, root, word, s); 56 | findWords(board, x, y+1, root, word, s); 57 | findWords(board, x, y-1, root, word, s); 58 | board[x][y] = c; 59 | } 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /UnionFind/FriendCircles.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int find(vector &parent, int x) { 4 | return parent[x] == x ? parent[x] : parent[x] = find(parent, parent[x]); 5 | } 6 | 7 | void unite(vector& children, vector& parent, int x, int y) { 8 | if(find(parent, x) == find(parent, y)) return; 9 | 10 | if(children[find(parent, x)] > children[find(parent, y)]) { 11 | children[find(parent, x)] += children[find(parent, y)]; 12 | parent[find(parent, y)] = find(parent, x); 13 | } else { 14 | children[find(parent, y)] += children[find(parent, x)]; 15 | parent[find(parent, x)] = find(parent, y); 16 | } 17 | } 18 | 19 | int findCircleNum(vector>& M) { 20 | int n = M.size(); 21 | vector parent(n); 22 | vector children(n); 23 | for(int i = 0; i < n; i++) { 24 | parent[i] = i; 25 | children[i] = 1; 26 | } 27 | for(int i = 0; i < n; i++) 28 | for(int j = i + 1; j < n; j++) 29 | if(M[i][j]) unite(children, parent, i, j); 30 | 31 | int count = 0; 32 | for(int i = 0; i < n; i++) 33 | if(find(parent, i) == i) 34 | ++count; 35 | return count; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /UnionFind/NumberOfOperationsToMakeNetworkConnected.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int find(vector& parent, int x) { 4 | return parent[x] < 0 ? x : parent[x] = find(parent, parent[x]); 5 | } 6 | 7 | int makeConnected(int n, vector>& connections) { 8 | if(connections.size() < n-1) return -1; 9 | vector parent(n, -1); 10 | for(auto &c: connections) { 11 | int i = find(parent, c[0]); 12 | int j = find(parent, c[1]); 13 | if(i != j) { 14 | parent[j] = i; 15 | --n; 16 | } 17 | } 18 | return n-1; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /UnionFind/RedundantConnection.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector parent; 4 | int find(int x) { 5 | return parent[x] == x ? x : find(parent[x]); 6 | } 7 | vector findRedundantConnection(vector>& edges) { 8 | ios::sync_with_stdio(false); 9 | cin.tie(0), cout.tie(0); 10 | int n = edges.size(); 11 | parent.resize(n+1, 0); 12 | for(int i = 0; i <= n; i++) 13 | parent[i] = i; 14 | 15 | vector res(2, 0); 16 | for(int i = 0; i < n; i++) { 17 | int x = find(edges[i][0]); 18 | int y = find(edges[i][1]); 19 | if(x != y) { 20 | parent[y] = x; 21 | } 22 | else { 23 | res[0] = edges[i][0]; 24 | res[1] = edges[i][1]; 25 | } 26 | } 27 | return res; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /UnionFind/SatisfiabilityOfEqualityEquations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int parent[26]; 4 | int find(int x) { 5 | if(parent[x] != x) parent[x] = find(parent[x]); 6 | return parent[x]; 7 | } 8 | 9 | bool equationsPossible(vector& equations) { 10 | for(int i = 0; i < 26; ++i) 11 | parent[i] = i; 12 | for(string eq: equations) { 13 | if(eq[1] == '=') { 14 | int x = find(eq[0] - 'a'); 15 | int y = find(eq[3] - 'a'); 16 | parent[x] = y; 17 | } 18 | } 19 | for(string eq: equations) { 20 | if(eq[1] == '!') { 21 | int x = find(eq[0] - 'a'); 22 | int y = find(eq[3] - 'a'); 23 | if(x == y) return false; 24 | } 25 | } 26 | return true; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-midnight --------------------------------------------------------------------------------